text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* $RCSfile: filehelper.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2004-08-20 12:54:41 $
*
* 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 _CONFIGMGR_FILEHELPER_HXX_
#define _CONFIGMGR_FILEHELPER_HXX_
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif
namespace io = com::sun::star::io;
namespace configmgr
{
//==========================================================================
//= FileHelper
//==========================================================================
/** Within the FileHelper namespace there is a list of methods declared, which ease
specific file operations.
*/
namespace FileHelper
{
/// delimiter used in URLs and ConfPath
static const ::sal_Unicode delimiter = sal_Unicode('/');
/// string representation of the delimiter
const rtl::OUString& delimiterAsString();
/// Tests if the file exists.
bool fileExists(rtl::OUString const& _sFileURL);
/// Tests if the directory exists.
bool dirExists(rtl::OUString const& _sDirURL);
/** Returns the parent part of the pathname of this File URL,
or an empty string if the name has no parent part.
The parent part is generally everything leading up to the last occurrence
of the separator character.
*/
rtl::OUString getParentDir(rtl::OUString const& _aFileURL);
/**
Returns the file name part of a file URL.
@param aFileUrl file URL
@return everything in the URL from the last delimiter on
*/
rtl::OUString getFileName(const rtl::OUString& aFileUrl) ;
/**
Splits a file URL between its parent directory/file name
parts.
@param aFileUrl file URL
@param aParentDirectory parent directory filled on return
@param aFileName file name filled on return
*/
void splitFileUrl(const rtl::OUString& aFileUrl,
rtl::OUString& aParentDirectory,
rtl::OUString& aFileName) ;
/** creates a directory whose pathname is specified by a FileURL.
@return true if directory could be created or does exist, otherwise false.
*/
osl::FileBase::RC mkdir(rtl::OUString const& _sDirURL);
/** creates a directory whose pathname is specified by a FileURL,
including any necessary parent directories.
@return true if directory (or directories) could be created or do(es) exist, otherwise false.
*/
osl::FileBase::RC mkdirs(rtl::OUString const& _aDirectory);
/** replaces a file specified by _aToURL with a file specified by _aFromURL.
*/
void replaceFile(const rtl::OUString& _aToURL, const rtl::OUString &_aFromURL) CFG_THROW1(io::IOException);
/** removes a file specified by _aURL. Ignores the case of a non-existing file.
*/
void removeFile(const rtl::OUString& _aURL) CFG_THROW1(io::IOException);
/** removes a file specified by _aURL. Ignores the case of a non-existing file.
*/
bool tryToRemoveFile(const rtl::OUString& _aURL, bool tryBackupFirst);
/** creates an error msg string for a given file error return code.
*/
rtl::OUString createOSLErrorString(osl::FileBase::RC eError);
/** determines the modification time of a directory entry specified by a URL.
@return the TimeValue of the last modification, if the file exists, otherwise a TimeValue(0,0).
*/
TimeValue getModifyTime(rtl::OUString const& _aNormalizedFilename);
/** determines the status of a directory entry specified by a URL.
@return the Size of the file in bytes and the TimeValue of the last modification, if the file exists,
otherwise 0 and a TimeValue(0,0).
*/
sal_uInt64 getModifyStatus(rtl::OUString const& _aNormalizedFilename, TimeValue & rModifyTime);
}
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.60); FILE MERGED 2005/09/05 17:04:26 rt 1.11.60.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filehelper.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:47:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONFIGMGR_FILEHELPER_HXX_
#define _CONFIGMGR_FILEHELPER_HXX_
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif
namespace io = com::sun::star::io;
namespace configmgr
{
//==========================================================================
//= FileHelper
//==========================================================================
/** Within the FileHelper namespace there is a list of methods declared, which ease
specific file operations.
*/
namespace FileHelper
{
/// delimiter used in URLs and ConfPath
static const ::sal_Unicode delimiter = sal_Unicode('/');
/// string representation of the delimiter
const rtl::OUString& delimiterAsString();
/// Tests if the file exists.
bool fileExists(rtl::OUString const& _sFileURL);
/// Tests if the directory exists.
bool dirExists(rtl::OUString const& _sDirURL);
/** Returns the parent part of the pathname of this File URL,
or an empty string if the name has no parent part.
The parent part is generally everything leading up to the last occurrence
of the separator character.
*/
rtl::OUString getParentDir(rtl::OUString const& _aFileURL);
/**
Returns the file name part of a file URL.
@param aFileUrl file URL
@return everything in the URL from the last delimiter on
*/
rtl::OUString getFileName(const rtl::OUString& aFileUrl) ;
/**
Splits a file URL between its parent directory/file name
parts.
@param aFileUrl file URL
@param aParentDirectory parent directory filled on return
@param aFileName file name filled on return
*/
void splitFileUrl(const rtl::OUString& aFileUrl,
rtl::OUString& aParentDirectory,
rtl::OUString& aFileName) ;
/** creates a directory whose pathname is specified by a FileURL.
@return true if directory could be created or does exist, otherwise false.
*/
osl::FileBase::RC mkdir(rtl::OUString const& _sDirURL);
/** creates a directory whose pathname is specified by a FileURL,
including any necessary parent directories.
@return true if directory (or directories) could be created or do(es) exist, otherwise false.
*/
osl::FileBase::RC mkdirs(rtl::OUString const& _aDirectory);
/** replaces a file specified by _aToURL with a file specified by _aFromURL.
*/
void replaceFile(const rtl::OUString& _aToURL, const rtl::OUString &_aFromURL) CFG_THROW1(io::IOException);
/** removes a file specified by _aURL. Ignores the case of a non-existing file.
*/
void removeFile(const rtl::OUString& _aURL) CFG_THROW1(io::IOException);
/** removes a file specified by _aURL. Ignores the case of a non-existing file.
*/
bool tryToRemoveFile(const rtl::OUString& _aURL, bool tryBackupFirst);
/** creates an error msg string for a given file error return code.
*/
rtl::OUString createOSLErrorString(osl::FileBase::RC eError);
/** determines the modification time of a directory entry specified by a URL.
@return the TimeValue of the last modification, if the file exists, otherwise a TimeValue(0,0).
*/
TimeValue getModifyTime(rtl::OUString const& _aNormalizedFilename);
/** determines the status of a directory entry specified by a URL.
@return the Size of the file in bytes and the TimeValue of the last modification, if the file exists,
otherwise 0 and a TimeValue(0,0).
*/
sal_uInt64 getModifyStatus(rtl::OUString const& _aNormalizedFilename, TimeValue & rModifyTime);
}
} // namespace configmgr
#endif
<|endoftext|>
|
<commit_before>//#include <iostream>
//#include <fstream>
//
//#include <TAlienCollection.h>
//#include <TFile.h>
//#include <TGrid.h>
//#include <TGridResult.h>
//#include <TMath.h>
//#include <TROOT.h>
//#include <TString.h>
//#include <TSystem.h>
//
//#include "AliCDBManager.h"
//#include "AliDAQ.h"
//#include "AliLog.h"
//#include "AliQA.h"
//#include "AliQADataMakerSteer.h"
//#include "AliRawReader.h"
//#include "AliRawReaderRoot.h"
//#include "AliTRDrawStreamBase.h"
//#include "AliGeomManager.h"
TString ClassName() { return "rawqa" ; }
//________________________________qa______________________________________
void rawqa(const char * filename)
{
// retrieve evironment variables
const char * year = gSystem->Getenv("YEAR") ;
const TString baseDir(gSystem->Getenv("BASEDIR")) ;
const Int_t runNumber = atoi(gSystem->Getenv("RUNNUM")) ;
// build the default storage of OCDB
TString sfilename(filename) ;
sfilename = sfilename.Strip() ;
sfilename = sfilename.Strip(TString::kLeading) ;
sfilename.Prepend("alien://") ;
baseDir.Append("/") ;
TString temp(filename) ;
temp = temp.ReplaceAll(baseDir, "") ;
temp = temp.Strip(TString::kLeading, '/') ;
baseDir.Append(temp(0, temp.Index("/"))) ;
char * kDefaultOCDBStorage = Form("alien://folder=%s/OCDB/", baseDir.Data()) ;
// set the location of reference data
//AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
AliQA::SetQARefStorage("local://$ALICE_ROOT") ;
AliLog::SetGlobalDebugLevel(0) ;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS",
"PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG",
"EMCAL", "DAQ_TEST", "HLT"} ;
AliQADataMakerSteer qas("rec") ;
TString detectors = "";
TString detectorsW = "";
UShort_t eventsProcessed = 0 ;
UShort_t filesProcessed = 1 ;
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(kDefaultOCDBStorage) ;
man->SetRun(runNumber) ;
AliGeomManager::LoadGeometry();
printf("INFO: Proccessing file %s\n", filename) ;
// check which detectors are present
AliRawReader * rawReader = new AliRawReaderRoot(sfilename);
AliTRDrawStreamBase::SetRawStreamVersion("TB");
while ( rawReader->NextEvent() ) {
man->SetRun(rawReader->GetRunNumber());
AliLog::Flush();
UChar_t * data ;
while (rawReader->ReadNextData(data)) {
Int_t detID = rawReader->GetDetectorID();
if (detID < 0 || detID >= AliDAQ::kNDetectors) {
printf("INFO: Wrong detector ID! Skipping payload...\n");
continue;
}
detIn[detID] = kTRUE ;
}
for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
if (detIn[detID]) {
if ( ! detectors.Contains(detNameOff[detID]) ) {
detectors.Append(detNameOff[detID]) ;
detectors.Append(" ") ;
}
}
}
if ( !detectors.IsNull() )
break ;
}
if ( !detectors.IsNull() ) {
//qas->SetMaxEvents(1) ;
detectorsW = qas.Run(detectors, rawReader) ;
qas.Reset() ;
} else {
printf("ERROR: No valid detectors found") ;
}
delete rawReader ;
eventsProcessed += qas.GetCurrentEvent() ;
//qas.Merge(runNumber) ;
// The summary
printf("\n\n********** Summary for run %d **********", runNumber) ;
printf(" data file : %s\n", filename);
printf(" detectors present in the run : %s\n", detectors.Data()) ;
printf(" detectors present in the run with QA: %s\n", detectorsW.Data()) ;
printf(" number of files/events processed : %d/%d\n", filesProcessed, eventsProcessed) ;
TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
if ( qaResult ) {
AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
if ( qa) {
for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
if (detectorsW.Contains(AliQA::GetDetName(index)))
qa->Show((AliQA::GetDetIndex(AliQA::GetDetName(index)))) ;
} else {
printf("ERROR: %s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName()) ;
}
} else {
printf("ERROR: %s has not been produced !", AliQA::GetQAResultFileName()) ;
}
}
<commit_msg>added mandatory task setting<commit_after>//#include <iostream>
//#include <fstream>
//
//#include <TAlienCollection.h>
//#include <TFile.h>
//#include <TGrid.h>
//#include <TGridResult.h>
//#include <TMath.h>
//#include <TROOT.h>
//#include <TString.h>
//#include <TSystem.h>
//
//#include "AliCDBManager.h"
//#include "AliDAQ.h"
//#include "AliLog.h"
//#include "AliQA.h"
//#include "AliQADataMakerSteer.h"
//#include "AliRawReader.h"
//#include "AliRawReaderRoot.h"
//#include "AliTRDrawStreamBase.h"
//#include "AliGeomManager.h"
TString ClassName() { return "rawqa" ; }
//________________________________qa______________________________________
void rawqa(const char * filename)
{
// retrieve evironment variables
const char * year = gSystem->Getenv("YEAR") ;
const TString baseDir(gSystem->Getenv("BASEDIR")) ;
const Int_t runNumber = atoi(gSystem->Getenv("RUNNUM")) ;
// build the default storage of OCDB
TString sfilename(filename) ;
sfilename = sfilename.Strip() ;
sfilename = sfilename.Strip(TString::kLeading) ;
sfilename.Prepend("alien://") ;
baseDir.Append("/") ;
TString temp(filename) ;
temp = temp.ReplaceAll(baseDir, "") ;
temp = temp.Strip(TString::kLeading, '/') ;
baseDir.Append(temp(0, temp.Index("/"))) ;
char * kDefaultOCDBStorage = Form("alien://folder=%s/OCDB/", baseDir.Data()) ;
// set the location of reference data
//AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
AliQA::SetQARefStorage("local://$ALICE_ROOT") ;
AliLog::SetGlobalDebugLevel(0) ;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS",
"PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG",
"EMCAL", "DAQ_TEST", "HLT"} ;
AliQADataMakerSteer qas("rec") ;
TString detectors = "";
TString detectorsW = "";
UShort_t eventsProcessed = 0 ;
UShort_t filesProcessed = 1 ;
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(kDefaultOCDBStorage) ;
man->SetRun(runNumber) ;
AliGeomManager::LoadGeometry();
printf("INFO: Proccessing file %s\n", filename) ;
// check which detectors are present
AliRawReader * rawReader = new AliRawReaderRoot(sfilename);
AliTRDrawStreamBase::SetRawStreamVersion("TB");
while ( rawReader->NextEvent() ) {
man->SetRun(rawReader->GetRunNumber());
AliLog::Flush();
UChar_t * data ;
while (rawReader->ReadNextData(data)) {
Int_t detID = rawReader->GetDetectorID();
if (detID < 0 || detID >= AliDAQ::kNDetectors) {
printf("INFO: Wrong detector ID! Skipping payload...\n");
continue;
}
detIn[detID] = kTRUE ;
}
for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
if (detIn[detID]) {
if ( ! detectors.Contains(detNameOff[detID]) ) {
detectors.Append(detNameOff[detID]) ;
detectors.Append(" ") ;
}
}
}
if ( !detectors.IsNull() )
break ;
}
if ( !detectors.IsNull() ) {
//qas->SetMaxEvents(1) ;
qas.SetTasks(Form("%d", AliQA::kRAWS));
detectorsW = qas.Run(detectors, rawReader) ;
qas.Reset() ;
} else {
printf("ERROR: No valid detectors found") ;
}
delete rawReader ;
eventsProcessed += qas.GetCurrentEvent() ;
//qas.Merge(runNumber) ;
// The summary
printf("\n\n********** Summary for run %d **********", runNumber) ;
printf(" data file : %s\n", filename);
printf(" detectors present in the run : %s\n", detectors.Data()) ;
printf(" detectors present in the run with QA: %s\n", detectorsW.Data()) ;
printf(" number of files/events processed : %d/%d\n", filesProcessed, eventsProcessed) ;
TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
if ( qaResult ) {
AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
if ( qa) {
for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
if (detectorsW.Contains(AliQA::GetDetName(index)))
qa->Show((AliQA::GetDetIndex(AliQA::GetDetName(index)))) ;
} else {
printf("ERROR: %s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName()) ;
}
} else {
printf("ERROR: %s has not been produced !", AliQA::GetQAResultFileName()) ;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2020 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.
// testing default transition sequence.
// This test requires that the transitions are set
// as depicted in design.ros2.org
#include <gtest/gtest.h>
extern "C"
{
#include "rclc_lifecycle/rclc_lifecycle.h"
}
TEST(TestRclcLifecycle, lifecycle_node) {
rcl_context_t context = rcl_get_zero_initialized_context();
rcl_init_options_t init_options = rcl_get_zero_initialized_init_options();
rcl_allocator_t allocator = rcl_get_default_allocator();
rcl_init_options_init(&init_options, allocator);
rcl_init(0, nullptr, &init_options, &context);
rcl_node_t my_node = rcl_get_zero_initialized_node();
rcl_node_options_t node_ops = rcl_node_get_default_options();
rcl_node_init(&my_node, "lifecycle_node", "rclc", &context, &node_ops);
rclc_lifecycle_node_t lifecycle_node;
rcl_lifecycle_state_machine_t state_machine_ = rcl_lifecycle_get_zero_initialized_state_machine();
rcl_ret_t res = rclc_make_node_a_lifecycle_node(
&lifecycle_node,
&my_node,
&state_machine_,
&node_ops);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
RCL_RET_OK,
rcl_lifecycle_state_machine_is_initialized(lifecycle_node.state_machine));
}
<commit_msg>Further tests: lifeycycle node transitions<commit_after>// Copyright 2020 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.
// testing default transition sequence.
// This test requires that the transitions are set
// as depicted in design.ros2.org
#include <gtest/gtest.h>
extern "C"
{
#include "rclc_lifecycle/rclc_lifecycle.h"
#include <lifecycle_msgs/msg/state.h>
#include <lifecycle_msgs/msg/transition.h>
}
TEST(TestRclcLifecycle, lifecycle_node) {
rcl_context_t context = rcl_get_zero_initialized_context();
rcl_init_options_t init_options = rcl_get_zero_initialized_init_options();
rcl_allocator_t allocator = rcl_get_default_allocator();
rcl_init_options_init(&init_options, allocator);
rcl_init(0, nullptr, &init_options, &context);
rcl_node_t my_node = rcl_get_zero_initialized_node();
rcl_node_options_t node_ops = rcl_node_get_default_options();
rcl_node_init(&my_node, "lifecycle_node", "rclc", &context, &node_ops);
rclc_lifecycle_node_t lifecycle_node;
rcl_lifecycle_state_machine_t state_machine_ = rcl_lifecycle_get_zero_initialized_state_machine();
rcl_ret_t res = rclc_make_node_a_lifecycle_node(
&lifecycle_node,
&my_node,
&state_machine_,
&node_ops);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
RCL_RET_OK,
rcl_lifecycle_state_machine_is_initialized(lifecycle_node.state_machine));
}
TEST(TestRclcLifecycle, lifecycle_node_transitions) {
rcl_context_t context = rcl_get_zero_initialized_context();
rcl_init_options_t init_options = rcl_get_zero_initialized_init_options();
rcl_allocator_t allocator = rcl_get_default_allocator();
rcl_init_options_init(&init_options, allocator);
rcl_init(0, nullptr, &init_options, &context);
rcl_node_t my_node = rcl_get_zero_initialized_node();
rcl_node_options_t node_ops = rcl_node_get_default_options();
rcl_node_init(&my_node, "lifecycle_node", "rclc", &context, &node_ops);
rclc_lifecycle_node_t lifecycle_node;
rcl_lifecycle_state_machine_t state_machine_ = rcl_lifecycle_get_zero_initialized_state_machine();
rcl_ret_t res = rclc_make_node_a_lifecycle_node(
&lifecycle_node,
&my_node,
&state_machine_,
&node_ops);
// configure
res = rclc_lifecycle_change_state(
&lifecycle_node,
lifecycle_msgs__msg__Transition__TRANSITION_CONFIGURE,
true);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
lifecycle_msgs__msg__State__PRIMARY_STATE_INACTIVE,
lifecycle_node.state_machine->current_state->id);
// activate
res = rclc_lifecycle_change_state(
&lifecycle_node,
lifecycle_msgs__msg__Transition__TRANSITION_ACTIVATE,
true);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
lifecycle_msgs__msg__State__PRIMARY_STATE_ACTIVE,
lifecycle_node.state_machine->current_state->id);
// deactivate
res = rclc_lifecycle_change_state(
&lifecycle_node,
lifecycle_msgs__msg__Transition__TRANSITION_DEACTIVATE,
true);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
lifecycle_msgs__msg__State__PRIMARY_STATE_INACTIVE,
lifecycle_node.state_machine->current_state->id);
// cleanup
res = rclc_lifecycle_change_state(
&lifecycle_node,
lifecycle_msgs__msg__Transition__TRANSITION_CLEANUP,
true);
EXPECT_EQ(RCL_RET_OK, res);
EXPECT_EQ(
lifecycle_msgs__msg__State__PRIMARY_STATE_UNCONFIGURED,
lifecycle_node.state_machine->current_state->id);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>
/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
BString *output = new BString;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
output->Append(buf);
(void) pclose(ptr);
return output;
}
/*
enum {
DELETE_EVERYTHING;
CREATE_FOLDER;
CREATE_FILE;
DELETE_THIS;
}
*/
int
parse_command(const char* command)
{
if(command[0] == 'R'
&& command[1] == 'E'
&& command[2] == 'S'
&& command[3] == 'E'
&& command[4] == 'T')
{
printf("Burn Everything. 8D\n");
}
else
{
printf("Something more specific.\n");
}
return 0;
}
int32
get_next_line(BString *src, BString *dest)
{
int32 eol = src->FindFirst('\n');
if(eol == B_ERROR)
return B_ERROR;
src->MoveInto(*dest,0,eol+1);
return B_OK;
}
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//ask Dropbox for deltas!
BString *delta_commands = run_script("python db_delta.py");
BString line;
while(get_next_line(delta_commands,&line) == B_OK)
{
(void) parse_command(line.String());
}
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
BPath *path;
BFile *file;
while(err == B_OK) //loop over files
{
file = new BFile(entry, B_READ_ONLY);
this->tracked_files.AddItem((void*)(file)); //add file to my list
path = new BPath;
entry->GetPath(path);
printf("tracking: %s\n",path->Path());
this->tracked_filepaths.AddItem((void*)path);
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp.String());
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
printf("Putting %s to Dropbox.\n", filepath);
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
// unpack the message
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
// add the new file to Dropbox
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
// add the new file to global tracking lists
BFile *file = new BFile(&new_file, B_READ_ONLY);
this->tracked_files.AddItem((void*)file);
BPath *path2 = new BPath;
new_file.GetPath(path2);
this->tracked_filepaths.AddItem((void*)path2);
// listen for EDIT alerts on the new file
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
if(err != B_OK)
printf("Watch new file %s: Not Ok.\n", path2->Path());
}
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BFile *filePtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop %d times\n", limit);
while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
{
printf("In loop.\n");
filePtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
printf("%s\n",path->Path());
delete_file_on_dropbox(path->Path());
this->tracked_files.RemoveItem(ktr);
this->tracked_filepaths.RemoveItem(ktr);
break; //break out of loop
}
ktr++;
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BFile * filePtr;
int32 ktr = 0;
while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
{
filePtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath *path;
path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
update_file_in_dropbox(path->Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<commit_msg>actually use that BString compare function rather than looking one char at a time.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>
/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
BString *output = new BString;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
output->Append(buf);
(void) pclose(ptr);
return output;
}
/*
enum {
DELETE_EVERYTHING;
CREATE_FOLDER;
CREATE_FILE;
DELETE_THIS;
}
*/
int
parse_command(BString command)
{
if(command.Compare("RESET\n") == 0)
{
printf("Burn Everything. 8D\n");
}
else
{
printf("Something more specific.\n");
}
return 0;
}
int32
get_next_line(BString *src, BString *dest)
{
int32 eol = src->FindFirst('\n');
if(eol == B_ERROR)
return B_ERROR;
src->MoveInto(*dest,0,eol+1);
return B_OK;
}
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//ask Dropbox for deltas!
BString *delta_commands = run_script("python db_delta.py");
BString line;
while(get_next_line(delta_commands,&line) == B_OK)
{
(void) parse_command(line);
}
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
BPath *path;
BFile *file;
while(err == B_OK) //loop over files
{
file = new BFile(entry, B_READ_ONLY);
this->tracked_files.AddItem((void*)(file)); //add file to my list
path = new BPath;
entry->GetPath(path);
printf("tracking: %s\n",path->Path());
this->tracked_filepaths.AddItem((void*)path);
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp.String());
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
printf("Putting %s to Dropbox.\n", filepath);
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
// unpack the message
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
// add the new file to Dropbox
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
// add the new file to global tracking lists
BFile *file = new BFile(&new_file, B_READ_ONLY);
this->tracked_files.AddItem((void*)file);
BPath *path2 = new BPath;
new_file.GetPath(path2);
this->tracked_filepaths.AddItem((void*)path2);
// listen for EDIT alerts on the new file
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
if(err != B_OK)
printf("Watch new file %s: Not Ok.\n", path2->Path());
}
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BFile *filePtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop %d times\n", limit);
while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
{
printf("In loop.\n");
filePtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
printf("%s\n",path->Path());
delete_file_on_dropbox(path->Path());
this->tracked_files.RemoveItem(ktr);
this->tracked_filepaths.RemoveItem(ktr);
break; //break out of loop
}
ktr++;
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BFile * filePtr;
int32 ktr = 0;
while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
{
filePtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath *path;
path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
update_file_in_dropbox(path->Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Window.h>
#include <Button.h>
#include <View.h>
#include <String.h>
#include <Directory.h>
#include <NodeMonitor.h>
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//start watching ~/Dropbox folder
BDirectory dir("/boot/home/Dropbox");
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
}
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
run_script(char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
(void) printf("RAWR%s", buf);
(void) pclose(ptr);
return 0;
}
int
main(void)
{
//Haiku make window code
App *app = new App();
//run some Dropbox code
run_script("python db_ls.py");
app->Run();
delete app;
return 0;
}
<commit_msg>actually understand the opcode :D<commit_after>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Window.h>
#include <Button.h>
#include <View.h>
#include <String.h>
#include <Directory.h>
#include <NodeMonitor.h>
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//start watching ~/Dropbox folder
BDirectory dir("/boot/home/Dropbox");
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
}
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
run_script(char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
(void) printf("RAWR%s", buf);
(void) pclose(ptr);
return 0;
}
int
main(void)
{
//Haiku make window code
App *app = new App();
//run some Dropbox code
run_script("python db_ls.py");
app->Run();
delete app;
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iterator>
#include <vector>
#ifdef DEBUG
#include <bitset>
#include <iostream>
#endif
// Algorithm to be tested
unsigned corresponding_pow(unsigned num)
{
for ( ; (num & (num -1)) != 0 ; num &= num -1) {}
return num;
}
std::vector<unsigned> build_grays(unsigned num)
{
#ifdef _MSC_VER
// It seems that there is a bug VS 14.0 2015
// Following code crashes when usin this compiler
// std::vector<int> make_it_crash(1);
// make_it_crash.reserve(2);
// std::copy(std::rbegin(make_it_crash), std::rend(make_it_crash), std::back_inserter(make_it_crash));
// It seems that push_back invalidate reverse_iterator even if the capacity is right
std::vector<unsigned> codes(2 * corresponding_pow(num));
#else
std::vector<unsigned> codes(1); //initial vector contains one entry
code.reserve(2 * corresponding_pow(num));
// Need to preallocate necessary memory in order to prevent from:
// If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
#endif
unsigned more = 1;
while (more < num)
{
std::transform(
#ifdef _MSC_VER
std::next(codes.rbegin(), codes.size() - more), codes.rend()
, std::next(codes.begin(), more)
#else
codes.rbegin(), codes.rend()
, std::back_inserter(codes)
#endif
, [more](auto prev) {
#ifdef DEBUG
std::cout << std::bitset<8>(prev) << " + " << std::bitset<8>(more) << std::endl;
#endif
return prev + more;
});
more <<= 1;
#ifdef DEBUG
for (auto e : codes)
{
std::cout << std::bitset<8>(e) << std::endl;
}
std::cout << "Next sugar : " << more << std::endl;
std::cout << "Number of entries: " << codes.size() << std::endl;
std::cout << " --- " << std::endl;
#endif
}
codes.erase(std::next(codes.begin(), num), codes.end());
return codes;
}
#include "tests.hpp"
<commit_msg>Fix typos in gray-code/implem<commit_after>#include <algorithm>
#include <iterator>
#include <vector>
#ifdef DEBUG
#include <bitset>
#include <iostream>
#endif
// Algorithm to be tested
unsigned corresponding_pow(unsigned num)
{
for ( ; (num & (num -1)) != 0 ; num &= num -1) {}
return num;
}
std::vector<unsigned> build_grays(unsigned num)
{
#ifdef _MSC_VER
// It seems that there is a bug VS 14.0 2015
// Following code crashes when usin this compiler
// std::vector<int> make_it_crash(1);
// make_it_crash.reserve(2);
// std::copy(std::rbegin(make_it_crash), std::rend(make_it_crash), std::back_inserter(make_it_crash));
// It seems that push_back invalidate reverse_iterator even if the capacity is right
std::vector<unsigned> codes(2 * corresponding_pow(num));
#else
std::vector<unsigned> codes(1); //initial vector contains one entry
codes.reserve(2 * corresponding_pow(num));
// Need to preallocate necessary memory in order to prevent from:
// If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
#endif
unsigned more = 1;
while (more < num)
{
std::transform(
#ifdef _MSC_VER
std::next(codes.rbegin(), codes.size() - more), codes.rend()
, std::next(codes.begin(), more)
#else
codes.rbegin(), codes.rend()
, std::back_inserter(codes)
#endif
, [more](auto prev) {
#ifdef DEBUG
std::cout << std::bitset<8>(prev) << " + " << std::bitset<8>(more) << std::endl;
#endif
return prev + more;
});
more <<= 1;
#ifdef DEBUG
for (auto e : codes)
{
std::cout << std::bitset<8>(e) << std::endl;
}
std::cout << "Next sugar : " << more << std::endl;
std::cout << "Number of entries: " << codes.size() << std::endl;
std::cout << " --- " << std::endl;
#endif
}
codes.erase(std::next(codes.begin(), num), codes.end());
return codes;
}
#include "tests.hpp"
<|endoftext|>
|
<commit_before>
#include "discord.hpp"
#include "topics.hpp"
using namespace rtu::topics;
using namespace discord;
namespace ezecs::network {
static constexpr auto appId = 667545903715975168;
static std::string toString(discord::Status statusNum) {
switch(statusNum) {
case discord::Status::Online: return "ACTIVE";
case discord::Status::Idle: return "IDLE";
case discord::Status::DoNotDisturb: return "NO DISTURB";
case discord::Status::Offline: return "OFFLINE";
default: return "UNKNOWN";
}
}
static std::string toString(discord::LogLevel levelNum) {
switch(levelNum) {
case discord::LogLevel::Info: return "INFO";
case discord::LogLevel::Debug: return "DEBUG";
case discord::LogLevel::Warn: return "WARNING";
case discord::LogLevel::Error: return "ERROR";
default: return "UNKNOWN";
}
}
bool isBad(char c) {
bool visibleAscii = (c >= 33 && c <= 126);
return !visibleAscii;
}
static std::string asciiNoSpaces(std::string str) {
std::replace_if(str.begin(), str.end(), isBad, ':');
return str;
}
std::map<std::string, std::vector<std::string>> DiscordContext::Friend::statusList;
bool DiscordContext::connect() {
Core* core{};
auto result = Core::Create(appId, DiscordCreateFlags_Default, &core);
state.core.reset(core);
if ( ! state.core) {
publishf("err", "Failed to instantiate discord core! (err %i)", result);
return false;
}
state.core->SetLogHook(discord::LogLevel::Info, [](discord::LogLevel level, const char *message) {
publishf("err", "DISCORD %s: %s", toString(level).c_str(), message);
});
state.core->UserManager().OnCurrentUserUpdate.Connect([&]() {
state.core->UserManager().GetCurrentUser(&state.currentUser);
});
updateFriends();
return true;
}
void DiscordContext::tick() {
if (state.core) {
state.core->NetworkManager().Flush();
state.core->RunCallbacks();
}
}
bool DiscordContext::host() {
discord::LobbyTransaction lobby{};
state.core->LobbyManager().GetLobbyCreateTransaction(&lobby);
lobby.SetCapacity(6);
lobby.SetMetadata("name", "Precession Server");
lobby.SetType(discord::LobbyType::Public);
state.core->LobbyManager().CreateLobby(lobby, [&](discord::Result result, discord::Lobby const &lby) {
if (result == discord::Result::Ok) {
publishf("log", "Created lobby, secret is \"%s\"", lby.GetSecret());
std::array<uint8_t, 234> data{};
state.core->LobbyManager().SendLobbyMessage(lby.GetId(), data.data(), data.size(), [](discord::Result result) {
publishf("log", "Sent lobby message. Result was %i.", result);
});
} else {
publishf("err", "Failed to create lobby with error %i.", result);
}
});
return true;
}
bool DiscordContext::join() {
return false;
}
void DiscordContext::list() {
discord::LobbySearchQuery query{};
state.core->LobbyManager().GetSearchQuery(&query);
query.Limit(1);
state.core->LobbyManager().Search(query, [&](discord::Result result) {
if (result == discord::Result::Ok) {
std::int32_t lobbyCount{};
state.core->LobbyManager().LobbyCount(&lobbyCount);
publishf("log", "Lobby search found %i lobbies:", lobbyCount);
for (auto i = 0; i < lobbyCount; ++i) {
discord::LobbyId lobbyId{};
state.core->LobbyManager().GetLobbyId(i, &lobbyId);
char name[4096];
state.core->LobbyManager().GetLobbyMetadataValue(lobbyId, "name", name);
publishf("log", "%20li %s", lobbyId, name);
}
} else {
publishf("err", "Lobby search failed with error %i.", result);
}
});
}
void DiscordContext::frnd(const char *name, const char *dscrm) {
if (name) { lastFrndName = std::string(name); } else { lastFrndName = std::string(); }
if (dscrm) { lastFrndDscrm = std::string(dscrm); } else { lastFrndDscrm = std::string(); }
updateFriends();
if ( ! lastFrndName.empty()) {
UserId idToGet = 0;
uint32_t numMatches = friends.count(lastFrndName);
if (numMatches > 1) {
if ( ! lastFrndDscrm.empty() && friends[lastFrndName].count(lastFrndDscrm)) {
idToGet = friends[lastFrndName][lastFrndDscrm].id;
} else {
publishf("log", "Multiple %s. Try again with name and number (separated by a space).", lastFrndName.c_str());
return;
}
} else if (numMatches) {
idToGet = friends[lastFrndName].begin()->second.id;
} else {
publishf("err", "Could not find user %s.", lastFrndName.c_str());
return;
}
discord::Relationship relat{};
if (discord::Result::Ok == state.core->RelationshipManager().Get(idToGet, &relat)) {
publishf("log", "%s is %s", asciiNoSpaces(relat.GetUser().GetUsername()).c_str(),
toString(relat.GetPresence().GetStatus()).c_str());
} else {
publishf("err", "Could not find %s.", lastFrndName.c_str());
}
} else {
publish("friend_info", friends);
}
}
bool DiscordContext::ovrl() {
return false;
}
void DiscordContext::updateFriends() {
state.core->RelationshipManager().Filter([](discord::Relationship const &relationship) -> bool {
return relationship.GetType() == discord::RelationshipType::Friend;
});
std::int32_t friendCount{0};
state.core->RelationshipManager().Count(&friendCount);
discord::Relationship relat{};
Friend::statusList.clear();
for (auto i = 0; i < friendCount; ++i) {
state.core->RelationshipManager().GetAt(i, &relat);
std::string status = "UNKNOWN";
if (relat.GetPresence().GetActivity().GetApplicationId() == appId) { status = " PRECESSING"; }
else { status = toString(relat.GetPresence().GetStatus()); }
friends[asciiNoSpaces(relat.GetUser().GetUsername())][relat.GetUser().GetDiscriminator()] = {
relat.GetUser().GetId(), relat.GetPresence().GetStatus(),
};
Friend::statusList[status].emplace_back(
(asciiNoSpaces(relat.GetUser().GetUsername()) + " " + std::string(relat.GetUser().GetDiscriminator()))
.c_str());
}
}
}
<commit_msg>tweaked discord message handling<commit_after>
#include "discord.hpp"
#include "topics.hpp"
using namespace rtu::topics;
using namespace discord;
namespace ezecs::network {
static constexpr auto appId = 667545903715975168;
static std::string toString(discord::Status statusNum) {
switch(statusNum) {
case discord::Status::Online: return "ACTIVE";
case discord::Status::Idle: return "IDLE";
case discord::Status::DoNotDisturb: return "NO DISTURB";
case discord::Status::Offline: return "OFFLINE";
default: return "UNKNOWN";
}
}
static std::string toString(discord::LogLevel levelNum) {
switch(levelNum) {
case discord::LogLevel::Info: return "INFO";
case discord::LogLevel::Debug: return "DEBUG";
case discord::LogLevel::Warn: return "WARNING";
case discord::LogLevel::Error: return "ERROR";
default: return "UNKNOWN";
}
}
bool isBad(char c) {
bool visibleAscii = (c >= 33 && c <= 126);
return !visibleAscii;
}
static std::string asciiNoSpaces(std::string str) {
std::replace_if(str.begin(), str.end(), isBad, ':');
return str;
}
std::map<std::string, std::vector<std::string>> DiscordContext::Friend::statusList;
bool DiscordContext::connect() {
Core* core{};
auto result = Core::Create(appId, DiscordCreateFlags_Default, &core);
state.core.reset(core);
if ( ! state.core) {
publishf("err", "Failed to instantiate discord core! (err %i)", result);
return false;
}
state.core->SetLogHook(discord::LogLevel::Info, [](discord::LogLevel level, const char *message) {
publishf("err", "DISCORD %s: %s", toString(level).c_str(), message);
if (level == discord::LogLevel::Error) {
publish("err", "\nPlease make sure you're logged into discord.");
}
});
state.core->UserManager().OnCurrentUserUpdate.Connect([&]() {
state.core->UserManager().GetCurrentUser(&state.currentUser);
});
updateFriends();
return true;
}
void DiscordContext::tick() {
if (state.core) {
state.core->NetworkManager().Flush();
state.core->RunCallbacks();
}
}
bool DiscordContext::host() {
discord::LobbyTransaction lobby{};
state.core->LobbyManager().GetLobbyCreateTransaction(&lobby);
lobby.SetCapacity(6);
lobby.SetMetadata("name", "Precession Server");
lobby.SetType(discord::LobbyType::Public);
state.core->LobbyManager().CreateLobby(lobby, [&](discord::Result result, discord::Lobby const &lby) {
if (result == discord::Result::Ok) {
publishf("log", "Created lobby, secret is \"%s\"", lby.GetSecret());
std::array<uint8_t, 234> data{};
state.core->LobbyManager().SendLobbyMessage(lby.GetId(), data.data(), data.size(), [](discord::Result result) {
publishf("log", "Sent lobby message. Result was %i.", result);
});
} else {
publishf("err", "Failed to create lobby with error %i.", result);
}
});
return true;
}
bool DiscordContext::join() {
return false;
}
void DiscordContext::list() {
discord::LobbySearchQuery query{};
state.core->LobbyManager().GetSearchQuery(&query);
query.Limit(1);
state.core->LobbyManager().Search(query, [&](discord::Result result) {
if (result == discord::Result::Ok) {
std::int32_t lobbyCount{};
state.core->LobbyManager().LobbyCount(&lobbyCount);
publishf("log", "Lobby search found %i lobbies:", lobbyCount);
for (auto i = 0; i < lobbyCount; ++i) {
discord::LobbyId lobbyId{};
state.core->LobbyManager().GetLobbyId(i, &lobbyId);
char name[4096];
state.core->LobbyManager().GetLobbyMetadataValue(lobbyId, "name", name);
publishf("log", "%20li %s", lobbyId, name);
}
} else {
publishf("err", "Lobby search failed with error %i.", result);
}
});
}
void DiscordContext::frnd(const char *name, const char *dscrm) {
if (name) { lastFrndName = std::string(name); } else { lastFrndName = std::string(); }
if (dscrm) { lastFrndDscrm = std::string(dscrm); } else { lastFrndDscrm = std::string(); }
updateFriends();
if ( ! lastFrndName.empty()) {
UserId idToGet = 0;
uint32_t numMatches = friends.count(lastFrndName);
if (numMatches > 1) {
if ( ! lastFrndDscrm.empty() && friends[lastFrndName].count(lastFrndDscrm)) {
idToGet = friends[lastFrndName][lastFrndDscrm].id;
} else {
publishf("log", "Multiple %s. Try again with name and number (separated by a space).", lastFrndName.c_str());
return;
}
} else if (numMatches) {
idToGet = friends[lastFrndName].begin()->second.id;
} else {
publishf("err", "Could not find user %s.", lastFrndName.c_str());
return;
}
discord::Relationship relat{};
if (discord::Result::Ok == state.core->RelationshipManager().Get(idToGet, &relat)) {
publishf("log", "%s is %s", asciiNoSpaces(relat.GetUser().GetUsername()).c_str(),
toString(relat.GetPresence().GetStatus()).c_str());
} else {
publishf("err", "Could not find %s.", lastFrndName.c_str());
}
} else {
publish("friend_info", friends);
}
}
bool DiscordContext::ovrl() {
return false;
}
void DiscordContext::updateFriends() {
state.core->RelationshipManager().Filter([](discord::Relationship const &relationship) -> bool {
return relationship.GetType() == discord::RelationshipType::Friend;
});
std::int32_t friendCount{0};
state.core->RelationshipManager().Count(&friendCount);
discord::Relationship relat{};
Friend::statusList.clear();
for (auto i = 0; i < friendCount; ++i) {
state.core->RelationshipManager().GetAt(i, &relat);
std::string status = "UNKNOWN";
if (relat.GetPresence().GetActivity().GetApplicationId() == appId) { status = " PRECESSING"; }
else { status = toString(relat.GetPresence().GetStatus()); }
friends[asciiNoSpaces(relat.GetUser().GetUsername())][relat.GetUser().GetDiscriminator()] = {
relat.GetUser().GetId(), relat.GetPresence().GetStatus(),
};
Friend::statusList[status].emplace_back(
(asciiNoSpaces(relat.GetUser().GetUsername()) + " " + std::string(relat.GetUser().GetDiscriminator()))
.c_str());
}
}
}
<|endoftext|>
|
<commit_before>#include "test.h"
#include "mjolnir/osmnode.h"
#include <fstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "mjolnir/pbfgraphparser.h"
#include <valhalla/baldr/graphconstants.h>
using namespace std;
using namespace valhalla::mjolnir;
using namespace valhalla::baldr;
namespace {
void write_config(const std::string& filename) {
std::ofstream file;
try {
file.open(filename, std::ios_base::trunc);
file << "{ \
\"mjolnir\": { \
\"input\": { \
\"type\": \"protocolbuffer\" \
}, \
\"hierarchy\": { \
\"tile_dir\": \"test/tiles\", \
\"levels\": [ \
{\"name\": \"local\", \"level\": 2, \"size\": 0.25}, \
{\"name\": \"arterial\", \"level\": 1, \"size\": 1, \"importance_cutoff\": \"TertiaryUnclassified\"}, \
{\"name\": \"highway\", \"level\": 0, \"size\": 4, \"importance_cutoff\": \"Trunk\"} \
] \
}, \
\"tagtransform\": { \
\"node_script\": \"test/lua/vertices.lua\", \
\"node_function\": \"nodes_proc\", \
\"way_script\": \"test/lua/edges.lua\", \
\"way_function\": \"ways_proc\" , \
\"relation_script\": \"test/lua/edges.lua\", \
\"relation_function\": \"rels_proc\" \
} \
} \
}";
}
catch(...) {
}
file.close();
}
void BollardsGates(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/liechtenstein-latest.osm.pbf"});
//We split set the uses at bollards and gates.
auto node = osmdata.GetNode(392700757);
if (!node->intersection())
throw std::runtime_error("Bollard not marked as intersection.");
//We split set the uses at bollards and gates.
node = osmdata.GetNode(376947468);
if (!node->intersection())
throw std::runtime_error("Gate not marked as intersection.");
//Is a gate with foot and bike flags set; however, access is private.
node = osmdata.GetNode(2949666866);
if (!node->intersection() ||
node->type() != NodeType::kGate || node->access_mask() != 6)
throw std::runtime_error("Gate at end of way test failed.");
//Is a bollard with foot and bike flags set.
node = osmdata.GetNode(569645326);
if (!node->intersection() ||
node->type() != NodeType::kBollard || node->access_mask() != 6)
throw std::runtime_error("Bollard(with flags) not marked as intersection.");
//Is a bollard=block with foot flag set.
node = osmdata.GetNode(1819036441);
if (!node->intersection() ||
node->type() != NodeType::kBollard || node->access_mask() != 2)
throw std::runtime_error("Bollard=block not marked as intersection.");
}
void RemovableBollards(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/rome.osm.pbf"});
//Is a bollard=rising is saved as a gate...with foot flag and bike set.
auto node = osmdata.GetNode(2425784125);
if (!node->intersection() ||
node->type() != NodeType::kGate || node->access_mask() != 7)
throw std::runtime_error("Rising Bollard not marked as intersection.");
}
void Exits(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/harrisburg.osm.pbf"});
auto node = osmdata.GetNode(33698177);
if (!node->intersection() ||
!node->ref() || osmdata.node_ref[33698177] != "51A-B")
throw std::runtime_error("Ref not set correctly .");
node = osmdata.GetNode(1901353894);
if (!node->intersection() ||
!node->ref() || osmdata.node_name[1901353894] != "Harrisburg East")
throw std::runtime_error("Ref not set correctly .");
node = osmdata.GetNode(462240654);
if (!node->intersection() || osmdata.node_exit_to[462240654] != "PA441")
throw std::runtime_error("Ref not set correctly .");
}
void Ways(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/baltimore.osm.pbf"});
for (uint32_t wayindex = 0; wayindex < osmdata.ways.size(); wayindex++) {
const auto& way = osmdata.ways[wayindex];
// bike_forward and reverse is set to false by default. Meaning defaults for
// highway = pedestrian. Bike overrides bicycle=designated and/or cycleway=shared_lane
// make it bike_forward and reverse = true
if (way.way_id() == 216240466) {
if (way.auto_forward() != false || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != true) {
throw std::runtime_error("Access is not set correctly for way 216240466.");
}
} // access for all
else if (way.way_id() == 138388359) {
if (way.auto_forward() != true || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != true || way.bike_backward() != true) {
throw std::runtime_error("Access is not set correctly for way 138388359.");
}
} // footway...pedestrian only
else if (way.way_id() == 133689121) {
if (way.auto_forward() != false || way.bike_forward() != false || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != false) {
throw std::runtime_error("Access is not set correctly for way 133689121.");
}
} // oneway
else if (way.way_id() == 49641455) {
if (way.auto_forward() != true || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != false) {
throw std::runtime_error("Access is not set correctly for way 49641455.");
}
}
}
}
void BicycleTrafficSignals(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/nyc.osm.pbf"});
//When we support finding bike rentals, this test will need updated.
auto node = osmdata.GetNode(3146484929);
// if (node != osmdata.nodes.end())
// throw std::runtime_error("Bike rental test failed.");
/*else {
if (node->intersection())
throw std::runtime_error("Bike rental not marked as intersection.");
}*/
//When we support finding shops that rent bikes, this test will need updated.
node = osmdata.GetNode(2592264881);
// if (node != osmdata.nodes.end())
// throw std::runtime_error("Bike rental at a shop test failed.");
/*else {
if (node->second.intersection())
throw std::runtime_error("Bike rental at a shop not marked as intersection.");
}*/
node = osmdata.GetNode(42439096);
if (!node->intersection() || !node->traffic_signal())
throw std::runtime_error("Traffic Signal test failed.");
}
void DoConfig() {
//make a config file
write_config("test/test_config");
}
void TestBollardsGates() {
//write the tiles with it
BollardsGates("test/test_config");
}
void TestRemovableBollards() {
//write the tiles with it
RemovableBollards("test/test_config");
}
void TestBicycleTrafficSignals() {
//write the tiles with it
BicycleTrafficSignals("test/test_config");
}
void TestExits() {
//write the tiles with it
Exits("test/test_config");
}
void TestWays() {
//write the tiles with it
Ways("test/test_config");
}
}
int main() {
test::suite suite("parser");
suite.test(TEST_CASE(DoConfig));
suite.test(TEST_CASE(TestBollardsGates));
suite.test(TEST_CASE(TestRemovableBollards));
suite.test(TEST_CASE(TestBicycleTrafficSignals));
suite.test(TEST_CASE(TestExits));
suite.test(TEST_CASE(TestWays));
return suite.tear_down();
}
<commit_msg>updated test conf to Tertiary for cut off.<commit_after>#include "test.h"
#include "mjolnir/osmnode.h"
#include <fstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "mjolnir/pbfgraphparser.h"
#include <valhalla/baldr/graphconstants.h>
using namespace std;
using namespace valhalla::mjolnir;
using namespace valhalla::baldr;
namespace {
void write_config(const std::string& filename) {
std::ofstream file;
try {
file.open(filename, std::ios_base::trunc);
file << "{ \
\"mjolnir\": { \
\"input\": { \
\"type\": \"protocolbuffer\" \
}, \
\"hierarchy\": { \
\"tile_dir\": \"test/tiles\", \
\"levels\": [ \
{\"name\": \"local\", \"level\": 2, \"size\": 0.25}, \
{\"name\": \"arterial\", \"level\": 1, \"size\": 1, \"importance_cutoff\": \"Unclassified\"}, \
{\"name\": \"highway\", \"level\": 0, \"size\": 4, \"importance_cutoff\": \"Trunk\"} \
] \
}, \
\"tagtransform\": { \
\"node_script\": \"test/lua/vertices.lua\", \
\"node_function\": \"nodes_proc\", \
\"way_script\": \"test/lua/edges.lua\", \
\"way_function\": \"ways_proc\" , \
\"relation_script\": \"test/lua/edges.lua\", \
\"relation_function\": \"rels_proc\" \
} \
} \
}";
}
catch(...) {
}
file.close();
}
void BollardsGates(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/liechtenstein-latest.osm.pbf"});
//We split set the uses at bollards and gates.
auto node = osmdata.GetNode(392700757);
if (!node->intersection())
throw std::runtime_error("Bollard not marked as intersection.");
//We split set the uses at bollards and gates.
node = osmdata.GetNode(376947468);
if (!node->intersection())
throw std::runtime_error("Gate not marked as intersection.");
//Is a gate with foot and bike flags set; however, access is private.
node = osmdata.GetNode(2949666866);
if (!node->intersection() ||
node->type() != NodeType::kGate || node->access_mask() != 6)
throw std::runtime_error("Gate at end of way test failed.");
//Is a bollard with foot and bike flags set.
node = osmdata.GetNode(569645326);
if (!node->intersection() ||
node->type() != NodeType::kBollard || node->access_mask() != 6)
throw std::runtime_error("Bollard(with flags) not marked as intersection.");
//Is a bollard=block with foot flag set.
node = osmdata.GetNode(1819036441);
if (!node->intersection() ||
node->type() != NodeType::kBollard || node->access_mask() != 2)
throw std::runtime_error("Bollard=block not marked as intersection.");
}
void RemovableBollards(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/rome.osm.pbf"});
//Is a bollard=rising is saved as a gate...with foot flag and bike set.
auto node = osmdata.GetNode(2425784125);
if (!node->intersection() ||
node->type() != NodeType::kGate || node->access_mask() != 7)
throw std::runtime_error("Rising Bollard not marked as intersection.");
}
void Exits(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/harrisburg.osm.pbf"});
auto node = osmdata.GetNode(33698177);
if (!node->intersection() ||
!node->ref() || osmdata.node_ref[33698177] != "51A-B")
throw std::runtime_error("Ref not set correctly .");
node = osmdata.GetNode(1901353894);
if (!node->intersection() ||
!node->ref() || osmdata.node_name[1901353894] != "Harrisburg East")
throw std::runtime_error("Ref not set correctly .");
node = osmdata.GetNode(462240654);
if (!node->intersection() || osmdata.node_exit_to[462240654] != "PA441")
throw std::runtime_error("Ref not set correctly .");
}
void Ways(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/baltimore.osm.pbf"});
for (uint32_t wayindex = 0; wayindex < osmdata.ways.size(); wayindex++) {
const auto& way = osmdata.ways[wayindex];
// bike_forward and reverse is set to false by default. Meaning defaults for
// highway = pedestrian. Bike overrides bicycle=designated and/or cycleway=shared_lane
// make it bike_forward and reverse = true
if (way.way_id() == 216240466) {
if (way.auto_forward() != false || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != true) {
throw std::runtime_error("Access is not set correctly for way 216240466.");
}
} // access for all
else if (way.way_id() == 138388359) {
if (way.auto_forward() != true || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != true || way.bike_backward() != true) {
throw std::runtime_error("Access is not set correctly for way 138388359.");
}
} // footway...pedestrian only
else if (way.way_id() == 133689121) {
if (way.auto_forward() != false || way.bike_forward() != false || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != false) {
throw std::runtime_error("Access is not set correctly for way 133689121.");
}
} // oneway
else if (way.way_id() == 49641455) {
if (way.auto_forward() != true || way.bike_forward() != true || way.pedestrian() != true ||
way.auto_backward() != false || way.bike_backward() != false) {
throw std::runtime_error("Access is not set correctly for way 49641455.");
}
}
}
}
void BicycleTrafficSignals(const std::string& config_file) {
boost::property_tree::ptree conf;
boost::property_tree::json_parser::read_json(config_file, conf);
auto osmdata = PBFGraphParser::Parse(conf.get_child("mjolnir"), {"test/data/nyc.osm.pbf"});
//When we support finding bike rentals, this test will need updated.
auto node = osmdata.GetNode(3146484929);
// if (node != osmdata.nodes.end())
// throw std::runtime_error("Bike rental test failed.");
/*else {
if (node->intersection())
throw std::runtime_error("Bike rental not marked as intersection.");
}*/
//When we support finding shops that rent bikes, this test will need updated.
node = osmdata.GetNode(2592264881);
// if (node != osmdata.nodes.end())
// throw std::runtime_error("Bike rental at a shop test failed.");
/*else {
if (node->second.intersection())
throw std::runtime_error("Bike rental at a shop not marked as intersection.");
}*/
node = osmdata.GetNode(42439096);
if (!node->intersection() || !node->traffic_signal())
throw std::runtime_error("Traffic Signal test failed.");
}
void DoConfig() {
//make a config file
write_config("test/test_config");
}
void TestBollardsGates() {
//write the tiles with it
BollardsGates("test/test_config");
}
void TestRemovableBollards() {
//write the tiles with it
RemovableBollards("test/test_config");
}
void TestBicycleTrafficSignals() {
//write the tiles with it
BicycleTrafficSignals("test/test_config");
}
void TestExits() {
//write the tiles with it
Exits("test/test_config");
}
void TestWays() {
//write the tiles with it
Ways("test/test_config");
}
}
int main() {
test::suite suite("parser");
suite.test(TEST_CASE(DoConfig));
suite.test(TEST_CASE(TestBollardsGates));
suite.test(TEST_CASE(TestRemovableBollards));
suite.test(TEST_CASE(TestBicycleTrafficSignals));
suite.test(TEST_CASE(TestExits));
suite.test(TEST_CASE(TestWays));
return suite.tear_down();
}
<|endoftext|>
|
<commit_before>#include "virtualview.hpp"
#include <QGLBuilder>
#include <QGLSceneNode>
#include <QGLAbstractScene>
#include <QMessageBox>
#include <QGraphicsPixmapItem>
#include <QtGui\QMouseEvent>
#include <GoBoard.h>
VirtualView::VirtualView(QWidget *parent){
this->setParent(parent);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->resize(parent->size());
this->setMouseTracking(true);
this->setting_stone_valid = false;
// directories of the images
QString texture_path = "res/textures/";
QString board_directory_size9 = QString(texture_path + "go_board_" + QString::number(9)+".png");
QString board_directory_size13 = QString(texture_path + "go_board_" + QString::number(13)+".png");
QString board_directory_size19 = QString(texture_path + "go_board_" + QString::number(19)+".png");
QString black_stone_directory = QString(texture_path + "black_stone.png");
QString white_stone_directory = QString(texture_path + "white_stone.png");
// loads the images and checks if the image could loaded
board_image_size9 = QImage(board_directory_size9);
board_image_size13 = QImage(board_directory_size13);
board_image_size19 = QImage(board_directory_size19);
black_stone_image = QImage(black_stone_directory);
white_stone_image = QImage(white_stone_directory);
// initialize with nullptr to be able to test against that
ghost_stone = nullptr;
}
VirtualView::~VirtualView(){
}
void VirtualView::createAndSetScene(QSize size, const GoBoard * game_board)
{
if (game_board == nullptr)
return;
this->resize(size);
scene.clear();
scene.setSceneRect(0,0, size.width(), size.height());
fitInView(this->sceneRect());
// loads the board size and checks if its a valid size
board_size = game_board->Size();
QImage board_image;
switch(board_size){
case 9:
board_image = board_image_size9;
break;
case 13:
board_image = board_image_size13;
break;
case 19:
board_image = board_image_size19;
break;
default:
QMessageBox::warning(this, "board size error", "invalid size of the board!");
}
if (board_image.isNull())
QMessageBox::warning(this, "file loading error", "could not load board image!");
if (black_stone_image.isNull())
QMessageBox::warning(this, "file loading error", "could not load black stone image!");
if (white_stone_image.isNull())
QMessageBox::warning(this, "file loading error", "could not laod white stone image!");
// scale_x and scale_y are the scaling factors of the virtual board
float scale_x = size.width() / float(board_image.width());
float scale_y = size.height() / float(board_image.height());
cell_width = static_cast<qreal>(board_image.width()) / (board_size+1);
cell_height = static_cast<qreal>(board_image.height()) / (board_size+1);
// scale the images to the right size
QPixmap board_image_scaled = QPixmap::fromImage(board_image);
board_image_scaled = board_image_scaled.scaled(size.width(),size.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QPixmap black_stone_image_scaled = QPixmap::fromImage(black_stone_image);
black_stone_image_scaled = black_stone_image_scaled.scaled(black_stone_image.width()*scale_x, black_stone_image.height()*scale_y, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QPixmap white_stone_image_scaled = QPixmap::fromImage(white_stone_image);
white_stone_image_scaled = white_stone_image_scaled.scaled(white_stone_image.width()*scale_x, white_stone_image.height()*scale_y, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
if (board_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale board!");
if (black_stone_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale black stone!");
if (white_stone_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale white stone!");
// add the board image to the scene
scene.addItem(new QGraphicsPixmapItem(board_image_scaled));
// get all stone positions for each color and add them on the right position to the scene
auto black_stones = game_board->All(SG_BLACK);
for (auto iter = SgSetIterator(black_stones); iter; ++iter) {
auto point = *iter;
// Reducing by -1 because board starts at 1,1
auto col = SgPointUtil::Col(point) - 1;
auto row = SgPointUtil::Row(point) - 1;
//Vertically mirroring stones
row = board_size - row - 1;
QGraphicsPixmapItem* black_stone_item = new QGraphicsPixmapItem(black_stone_image_scaled);
black_stone_item->setPos(cell_width * scale_x * col, cell_height * scale_y * row);
black_stone_item->setOffset(cell_width * scale_x - black_stone_image_scaled.width()/2, cell_height * scale_y - black_stone_image_scaled.height()/2);
scene.addItem(black_stone_item);
}
auto white_stones = game_board->All(SG_WHITE);
for (auto iter = SgSetIterator(white_stones); iter; ++iter) {
auto point = *iter;
// Reducing by -1 because board starts at 1,1
auto col = SgPointUtil::Col(point) - 1;
auto row = SgPointUtil::Row(point) - 1;
//Vertically mirroring stones
row = board_size - row - 1;
QGraphicsPixmapItem* black_stone_item = new QGraphicsPixmapItem(white_stone_image_scaled);
black_stone_item->setPos(cell_width * scale_x * col, cell_height * scale_y * row);
black_stone_item->setOffset(cell_width * scale_x - white_stone_image_scaled.width()/2, cell_height * scale_y - black_stone_image_scaled.height()/2);
scene.addItem(black_stone_item);
}
// Stone that could be placed on board when user chooses to
if (this->virtual_game_mode){
if (ghost_stone == nullptr)
this->ghost_stone = new QGraphicsEllipseItem(QRectF());
ghost_stone->setRect(selection_ellipse);
QBrush ghost_brush = game_board->ToPlay() == SG_BLACK ?
QBrush(Qt::GlobalColor::black):
QBrush(Qt::GlobalColor::white);
this->ghost_stone->setOpacity(0.5);
this->ghost_stone->setBrush(ghost_brush);
this->scene.addItem(this->ghost_stone);
}
this->setScene(&scene);
setting_stone_valid = true;
}
void VirtualView::resizeVirtualView(){
this->resize(this->parentWidget()->size());
this->fitInView(scene.sceneRect());
}
//SLOTS
void VirtualView::slot_setVirtualGameMode(bool checked){
this->virtual_game_mode = checked;
if (!checked && scene.isActive())
scene.removeItem(ghost_stone);
}
void VirtualView::mousePressEvent(QMouseEvent* event){
if (!virtual_game_mode)
return;
if (event->button() == Qt::LeftButton && setting_stone_valid){
// the mouse_hover_coord is calculated starting from upper left corner
// game board starts at left bottom corner -> mirror vertically
int ycoord = board_size - mouse_hover_coord.y() + 1;
emit signal_virtualViewplayMove(mouse_hover_coord.x(), ycoord);
setting_stone_valid = false;
}
}
void VirtualView::mouseMoveEvent(QMouseEvent* event){
if (!virtual_game_mode)
return;
int pic_boarder_x = 60, pic_boarder_y = 55, board_pix;
switch(this->board_size){
case 9:
board_pix = this->board_image_size9.size().width();
break;
case 13:
board_pix = this->board_image_size13.size().width();
break;
case 19:
board_pix = this->board_image_size19.size().width();
break;
default:
return;
break;
}
// calculate the scale of picture in viewport
qreal scale_x = scene.sceneRect().size().width() * qreal(1.0)/board_pix;
qreal scale_y = scene.sceneRect().size().height() * qreal(1.0)/board_pix;
// getting transformation of scene (fitInView() scales the scene!)
qreal transform_x = qreal(1.0) / this->transform().m11();
qreal transform_y = qreal(1.0) / this->transform().m22();
// mapping mousecoordinates to gameboard coordinates (example: x=0,2515, y=2,7622)
qreal xCoordAccurate = (event->pos().x() * transform_x - pic_boarder_x * scale_x) / (this->cell_width * scale_x);
qreal yCoordAccurate = (event->pos().y() * transform_y - pic_boarder_y * scale_y) / (this->cell_height * scale_y);
// Rounding half up (example: x=0, y=3)
int board_x_coord = static_cast<int>(xCoordAccurate);
int board_y_coord = static_cast<int>(yCoordAccurate);
board_x_coord = xCoordAccurate - board_x_coord < 0.5f ? board_x_coord : board_x_coord + 1;
board_y_coord = yCoordAccurate - board_y_coord < 0.5f ? board_y_coord : board_y_coord + 1;
// Until now we calculated from 0,0. Game starts counting at 1,1
QPoint new_mouse_hover_coord = QPoint(board_x_coord + 1,board_y_coord + 1);
// If mouse hover coordinates differ -> move ellipse to new coordinates
if (new_mouse_hover_coord != mouse_hover_coord
&& board_x_coord < board_size && board_y_coord < board_size){
// calculate exact position of where to draw new ellipse
qreal ellipse_xPos = (pic_boarder_x * scale_x) + (board_x_coord * this->cell_width * scale_x) - (this->cell_width * scale_x)/2.0f;
qreal ellipse_yPos = (pic_boarder_y * scale_y) + (board_y_coord * this->cell_height * scale_y) - (this->cell_height * scale_y)/2.0f;
QRectF new_selection_ellipse = QRectF(ellipse_xPos, ellipse_yPos, this->cell_width * scale_x, this->cell_height * scale_y);
if (ghost_stone == nullptr)
this->ghost_stone = new QGraphicsEllipseItem(QRectF());
ghost_stone->setRect(new_selection_ellipse);
selection_ellipse = new_selection_ellipse;
// save new mouse hover coordinates
mouse_hover_coord = new_mouse_hover_coord;
}
}<commit_msg>fixes #140 Now correct creating and deleting of ghost_stone in dependence of "scene.clear()"<commit_after>#include "virtualview.hpp"
#include <QGLBuilder>
#include <QGLSceneNode>
#include <QGLAbstractScene>
#include <QMessageBox>
#include <QGraphicsPixmapItem>
#include <QtGui\QMouseEvent>
#include <GoBoard.h>
VirtualView::VirtualView(QWidget *parent){
this->setParent(parent);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->resize(parent->size());
this->setMouseTracking(true);
this->setting_stone_valid = false;
// directories of the images
QString texture_path = "res/textures/";
QString board_directory_size9 = QString(texture_path + "go_board_" + QString::number(9)+".png");
QString board_directory_size13 = QString(texture_path + "go_board_" + QString::number(13)+".png");
QString board_directory_size19 = QString(texture_path + "go_board_" + QString::number(19)+".png");
QString black_stone_directory = QString(texture_path + "black_stone.png");
QString white_stone_directory = QString(texture_path + "white_stone.png");
// loads the images and checks if the image could loaded
board_image_size9 = QImage(board_directory_size9);
board_image_size13 = QImage(board_directory_size13);
board_image_size19 = QImage(board_directory_size19);
black_stone_image = QImage(black_stone_directory);
white_stone_image = QImage(white_stone_directory);
// initialize ghost_stone
this->ghost_stone = new QGraphicsEllipseItem(QRectF());
}
VirtualView::~VirtualView(){
}
void VirtualView::createAndSetScene(QSize size, const GoBoard * game_board)
{
if (game_board == nullptr)
return;
this->resize(size);
scene.clear();
scene.setSceneRect(0,0, size.width(), size.height());
fitInView(this->sceneRect());
// loads the board size and checks if its a valid size
board_size = game_board->Size();
QImage board_image;
switch(board_size){
case 9:
board_image = board_image_size9;
break;
case 13:
board_image = board_image_size13;
break;
case 19:
board_image = board_image_size19;
break;
default:
QMessageBox::warning(this, "board size error", "invalid size of the board!");
}
if (board_image.isNull())
QMessageBox::warning(this, "file loading error", "could not load board image!");
if (black_stone_image.isNull())
QMessageBox::warning(this, "file loading error", "could not load black stone image!");
if (white_stone_image.isNull())
QMessageBox::warning(this, "file loading error", "could not laod white stone image!");
// scale_x and scale_y are the scaling factors of the virtual board
float scale_x = size.width() / float(board_image.width());
float scale_y = size.height() / float(board_image.height());
cell_width = static_cast<qreal>(board_image.width()) / (board_size+1);
cell_height = static_cast<qreal>(board_image.height()) / (board_size+1);
// scale the images to the right size
QPixmap board_image_scaled = QPixmap::fromImage(board_image);
board_image_scaled = board_image_scaled.scaled(size.width(),size.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QPixmap black_stone_image_scaled = QPixmap::fromImage(black_stone_image);
black_stone_image_scaled = black_stone_image_scaled.scaled(black_stone_image.width()*scale_x, black_stone_image.height()*scale_y, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QPixmap white_stone_image_scaled = QPixmap::fromImage(white_stone_image);
white_stone_image_scaled = white_stone_image_scaled.scaled(white_stone_image.width()*scale_x, white_stone_image.height()*scale_y, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
if (board_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale board!");
if (black_stone_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale black stone!");
if (white_stone_image_scaled.isNull())
QMessageBox::warning(this, "image scale error", "could not scale white stone!");
// add the board image to the scene
scene.addItem(new QGraphicsPixmapItem(board_image_scaled));
// get all stone positions for each color and add them on the right position to the scene
auto black_stones = game_board->All(SG_BLACK);
for (auto iter = SgSetIterator(black_stones); iter; ++iter) {
auto point = *iter;
// Reducing by -1 because board starts at 1,1
auto col = SgPointUtil::Col(point) - 1;
auto row = SgPointUtil::Row(point) - 1;
//Vertically mirroring stones
row = board_size - row - 1;
QGraphicsPixmapItem* black_stone_item = new QGraphicsPixmapItem(black_stone_image_scaled);
black_stone_item->setPos(cell_width * scale_x * col, cell_height * scale_y * row);
black_stone_item->setOffset(cell_width * scale_x - black_stone_image_scaled.width()/2, cell_height * scale_y - black_stone_image_scaled.height()/2);
scene.addItem(black_stone_item);
}
auto white_stones = game_board->All(SG_WHITE);
for (auto iter = SgSetIterator(white_stones); iter; ++iter) {
auto point = *iter;
// Reducing by -1 because board starts at 1,1
auto col = SgPointUtil::Col(point) - 1;
auto row = SgPointUtil::Row(point) - 1;
//Vertically mirroring stones
row = board_size - row - 1;
QGraphicsPixmapItem* black_stone_item = new QGraphicsPixmapItem(white_stone_image_scaled);
black_stone_item->setPos(cell_width * scale_x * col, cell_height * scale_y * row);
black_stone_item->setOffset(cell_width * scale_x - white_stone_image_scaled.width()/2, cell_height * scale_y - black_stone_image_scaled.height()/2);
scene.addItem(black_stone_item);
}
// Stone that could be placed on board when user chooses to
if (this->virtual_game_mode){
// scene is cleared and deleted ghost_stone. Here we have to create a new one!
ghost_stone = new QGraphicsEllipseItem(QRectF());
ghost_stone->setVisible(true);
ghost_stone->setRect(selection_ellipse);
QBrush ghost_brush = game_board->ToPlay() == SG_BLACK ?
QBrush(Qt::GlobalColor::black):
QBrush(Qt::GlobalColor::white);
this->ghost_stone->setOpacity(0.5);
this->ghost_stone->setBrush(ghost_brush);
this->scene.addItem(this->ghost_stone);
}
this->setScene(&scene);
setting_stone_valid = true;
}
void VirtualView::resizeVirtualView(){
this->resize(this->parentWidget()->size());
this->fitInView(scene.sceneRect());
}
//SLOTS
void VirtualView::slot_setVirtualGameMode(bool checked){
this->virtual_game_mode = checked;
if (!checked && scene.isActive())
scene.removeItem(ghost_stone);
if (checked && scene.isActive())
scene.addItem(ghost_stone);
}
void VirtualView::mousePressEvent(QMouseEvent* event){
if (!virtual_game_mode)
return;
if (event->button() == Qt::LeftButton && setting_stone_valid){
// the mouse_hover_coord is calculated starting from upper left corner
// game board starts at left bottom corner -> mirror vertically
int ycoord = board_size - mouse_hover_coord.y() + 1;
emit signal_virtualViewplayMove(mouse_hover_coord.x(), ycoord);
setting_stone_valid = false;
}
}
void VirtualView::mouseMoveEvent(QMouseEvent* event){
if (!virtual_game_mode)
return;
int pic_boarder_x = 60, pic_boarder_y = 55, board_pix;
switch(this->board_size){
case 9:
board_pix = this->board_image_size9.size().width();
break;
case 13:
board_pix = this->board_image_size13.size().width();
break;
case 19:
board_pix = this->board_image_size19.size().width();
break;
default:
return;
break;
}
// calculate the scale of picture in viewport
qreal scale_x = scene.sceneRect().size().width() * qreal(1.0)/board_pix;
qreal scale_y = scene.sceneRect().size().height() * qreal(1.0)/board_pix;
// getting transformation of scene (fitInView() scales the scene!)
qreal transform_x = qreal(1.0) / this->transform().m11();
qreal transform_y = qreal(1.0) / this->transform().m22();
// mapping mousecoordinates to gameboard coordinates (example: x=0,2515, y=2,7622)
qreal xCoordAccurate = (event->pos().x() * transform_x - pic_boarder_x * scale_x) / (this->cell_width * scale_x);
qreal yCoordAccurate = (event->pos().y() * transform_y - pic_boarder_y * scale_y) / (this->cell_height * scale_y);
// Rounding half up (example: x=0, y=3)
int board_x_coord = static_cast<int>(xCoordAccurate);
int board_y_coord = static_cast<int>(yCoordAccurate);
board_x_coord = xCoordAccurate - board_x_coord < 0.5f ? board_x_coord : board_x_coord + 1;
board_y_coord = yCoordAccurate - board_y_coord < 0.5f ? board_y_coord : board_y_coord + 1;
// Until now we calculated from 0,0. Game starts counting at 1,1
QPoint new_mouse_hover_coord = QPoint(board_x_coord + 1,board_y_coord + 1);
// If mouse hover coordinates differ -> move ellipse to new coordinates
if (new_mouse_hover_coord != mouse_hover_coord
&& board_x_coord < board_size && board_y_coord < board_size){
// calculate exact position of where to draw new ellipse
qreal ellipse_xPos = (pic_boarder_x * scale_x) + (board_x_coord * this->cell_width * scale_x) - (this->cell_width * scale_x)/2.0f;
qreal ellipse_yPos = (pic_boarder_y * scale_y) + (board_y_coord * this->cell_height * scale_y) - (this->cell_height * scale_y)/2.0f;
QRectF new_selection_ellipse = QRectF(ellipse_xPos, ellipse_yPos, this->cell_width * scale_x, this->cell_height * scale_y);
ghost_stone->setVisible(true);
ghost_stone->setRect(new_selection_ellipse);
selection_ellipse = new_selection_ellipse;
// save new mouse hover coordinates
mouse_hover_coord = new_mouse_hover_coord;
}
}<|endoftext|>
|
<commit_before>#include "ImwWindow.h"
#include "ImwWindowManager.h"
namespace ImWindow
{
//SFF_BEGIN
int ImwWindow::s_iNextId = 0;
#ifdef IMW_CUSTOM_IMPLEMENT_IMWWINDOW
IMW_CUSTOM_IMPLEMENT_IMWWINDOW
#endif //IMW_CUSTOM_IMPLEMENT_IMWWINDOW
ImwWindow::ImwWindow()
{
m_pTitle = NULL;
m_bClosable = true;
m_bAlone = false;
m_bFillingSpace = false;
m_iId = s_iNextId++;
//Write Id to string
int iIndex = 0;
int iNumber = m_iId;
do
{
m_pId[iIndex++] = iNumber % 10 + '0';
}
while ((iNumber /= 10) > 0 && iIndex <= 10);
m_pId[iIndex] = '\0';
ImwWindowManager::GetInstance()->AddWindow(this);
}
ImwWindow::~ImwWindow()
{
ImwWindowManager::GetInstance()->RemoveWindow(this);
ImwSafeFree(m_pTitle);
}
void ImwWindow::OnContextMenu()
{
}
bool ImwWindow::IsFillingSpace() const
{
return m_bFillingSpace;
}
void ImwWindow::SetFillingSpace(bool bFilling)
{
m_bFillingSpace = bFilling;
}
void ImwWindow::GetParameters(JsonValue& /*oOutParameters*/)
{
}
void ImwWindow::SetParameters(const JsonValue& /*oParameters*/)
{
}
ImU32 ImwWindow::GetId() const
{
return m_iId;
}
const ImwChar* ImwWindow::GetIdStr() const
{
return m_pId;
}
void ImwWindow::Destroy()
{
ImwWindowManager::GetInstance()->DestroyWindow(this);
}
void ImwWindow::SetTitle(const ImwChar* pTitle)
{
ImwSafeFree(m_pTitle);
if (NULL != pTitle)
{
size_t iLen = strlen(pTitle) + 1;
m_pTitle = (ImwChar*)ImwMalloc(sizeof(ImwChar) * iLen);
strcpy(m_pTitle, pTitle);
}
}
const ImwChar* ImwWindow::GetTitle() const
{
return m_pTitle;
}
void ImwWindow::SetClosable( bool bClosable )
{
m_bClosable = bClosable;
}
bool ImwWindow::IsClosable() const
{
return m_bClosable;
}
void ImwWindow::SetAlone(bool bAlone)
{
m_bAlone = bAlone;
}
bool ImwWindow::IsAlone() const
{
return m_bAlone;
}
const ImVec2& ImwWindow::GetLastPosition() const
{
return m_oLastPosition;
}
const ImVec2& ImwWindow::GetLastSize() const
{
return m_oLastSize;
}
//SFF_END
}<commit_msg>Better member init for ImWindow contstructor<commit_after>#include "ImwWindow.h"
#include "ImwWindowManager.h"
namespace ImWindow
{
//SFF_BEGIN
int ImwWindow::s_iNextId = 0;
#ifdef IMW_CUSTOM_IMPLEMENT_IMWWINDOW
IMW_CUSTOM_IMPLEMENT_IMWWINDOW
#endif //IMW_CUSTOM_IMPLEMENT_IMWWINDOW
ImwWindow::ImwWindow()
: m_pTitle(NULL)
, m_bClosable(true)
, m_bAlone(false)
, m_bFillingSpace(false)
, m_oLastPosition(0.f, 0.f)
, m_oLastSize(0.f, 0.f)
{
m_iId = s_iNextId++;
//Write Id to string
int iIndex = 0;
int iNumber = m_iId;
do
{
m_pId[iIndex++] = iNumber % 10 + '0';
}
while ((iNumber /= 10) > 0 && iIndex <= 10);
m_pId[iIndex] = '\0';
ImwWindowManager::GetInstance()->AddWindow(this);
}
ImwWindow::~ImwWindow()
{
ImwWindowManager::GetInstance()->RemoveWindow(this);
ImwSafeFree(m_pTitle);
}
void ImwWindow::OnContextMenu()
{
}
bool ImwWindow::IsFillingSpace() const
{
return m_bFillingSpace;
}
void ImwWindow::SetFillingSpace(bool bFilling)
{
m_bFillingSpace = bFilling;
}
void ImwWindow::GetParameters(JsonValue& /*oOutParameters*/)
{
}
void ImwWindow::SetParameters(const JsonValue& /*oParameters*/)
{
}
ImU32 ImwWindow::GetId() const
{
return m_iId;
}
const ImwChar* ImwWindow::GetIdStr() const
{
return m_pId;
}
void ImwWindow::Destroy()
{
ImwWindowManager::GetInstance()->DestroyWindow(this);
}
void ImwWindow::SetTitle(const ImwChar* pTitle)
{
ImwSafeFree(m_pTitle);
if (NULL != pTitle)
{
size_t iLen = strlen(pTitle) + 1;
m_pTitle = (ImwChar*)ImwMalloc(sizeof(ImwChar) * iLen);
strcpy(m_pTitle, pTitle);
}
}
const ImwChar* ImwWindow::GetTitle() const
{
return m_pTitle;
}
void ImwWindow::SetClosable( bool bClosable )
{
m_bClosable = bClosable;
}
bool ImwWindow::IsClosable() const
{
return m_bClosable;
}
void ImwWindow::SetAlone(bool bAlone)
{
m_bAlone = bAlone;
}
bool ImwWindow::IsAlone() const
{
return m_bAlone;
}
const ImVec2& ImwWindow::GetLastPosition() const
{
return m_oLastPosition;
}
const ImVec2& ImwWindow::GetLastSize() const
{
return m_oLastSize;
}
//SFF_END
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "itkCastImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
#include "itkCastImageFilter.h"
#include "otbUnaryImageFunctorWithVectorImageFilter.h"
#include "otbStreamingShrinkImageFilter.h"
#include "itkListSample.h"
#include "otbListSampleToHistogramListGenerator.h"
#include "itkImageRegionConstIterator.h"
namespace otb
{
namespace Wrapper
{
namespace Functor
{
template< class TScalar >
class ITK_EXPORT LogFunctor
{
public:
LogFunctor(){};
~LogFunctor(){};
TScalar operator() (const TScalar& v) const
{
return vcl_log(v);
}
};
} // end namespace Functor
class Convert : public Application
{
public:
/** Standard class typedefs. */
typedef Convert Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Convert, otb::Application);
/** Filters typedef */
typedef itk::Statistics::ListSample<FloatVectorImageType::PixelType> ListSampleType;
typedef itk::Statistics::DenseFrequencyContainer2 DFContainerType;
typedef ListSampleToHistogramListGenerator<ListSampleType,
FloatVectorImageType::InternalPixelType,
DFContainerType> HistogramsGeneratorType;
typedef StreamingShrinkImageFilter<FloatVectorImageType,
FloatVectorImageType> ShrinkFilterType;
typedef Functor::LogFunctor<FloatVectorImageType::InternalPixelType> TransferLogFunctor;
typedef UnaryImageFunctorWithVectorImageFilter<FloatVectorImageType,
FloatVectorImageType,
TransferLogFunctor> TransferLogType;
private:
void DoInit() ITK_OVERRIDE
{
SetName("Convert");
SetDescription("Convert an image to a different format, optionally rescaling the data"
" and/or changing the pixel type.");
// Documentation
SetDocName("Image Conversion");
SetDocLongDescription("This application performs an image pixel type conversion "
" (short, ushort, uchar, int, uint, float and double types are handled). "
"The output image is written in the specified format (ie. that corresponds "
"to the given extension).\n The conversion can include a rescale using "
"the image 2 percent minimum and maximum values. The rescale can be linear or log2.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Rescale");
AddDocTag(Tags::Manip);
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_Choice, "type", "Rescale type");
SetParameterDescription("type", "Transfer function for the rescaling");
AddChoice("type.none", "None");
AddChoice("type.linear", "Linear");
AddChoice("type.log2", "Log2");
SetParameterString("type", "none", false);
AddParameter(ParameterType_Float,"type.linear.gamma","Gamma correction factor");
SetParameterDescription("type.linear.gamma","Gamma correction factor");
SetDefaultParameterFloat("type.linear.gamma",1.0);
MandatoryOff("type.linear.gamma");
AddParameter(ParameterType_InputImage, "mask", "Input mask");
SetParameterDescription("mask", "The masked pixels won't be used to adapt the dynamic "
"(the mask must have the same dimensions as the input image)");
MandatoryOff("mask");
DisableParameter("mask");
AddParameter(ParameterType_Group,"hcp","Histogram Cutting Parameters");
SetParameterDescription("hcp","Parameters to cut the histogram edges before rescaling");
AddParameter(ParameterType_Float, "hcp.high", "High Cut Quantile");
SetParameterDescription("hcp.high", "Quantiles to cut from histogram high values "
"before computing min/max rescaling (in percent, 2 by default)");
MandatoryOff("hcp.high");
SetDefaultParameterFloat("hcp.high", 2.0);
DisableParameter("hcp.high");
AddParameter(ParameterType_Float, "hcp.low", "Low Cut Quantile");
SetParameterDescription("hcp.low", "Quantiles to cut from histogram low values "
"before computing min/max rescaling (in percent, 2 by default)");
MandatoryOff("hcp.low");
SetDefaultParameterFloat("hcp.low", 2.0);
DisableParameter("hcp.low");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "otbConvertWithScalingOutput.png uint8");
SetDocExampleParameterValue("type", "linear");
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
// Nothing to do here for the parameters : all are independent
}
template<class TImageType>
void GenericDoExecute()
{
typename TImageType::Pointer castIm;
std::string rescaleType = this->GetParameterString("type");
if( (rescaleType != "none") && (rescaleType != "linear") && (rescaleType != "log2") )
{
itkExceptionMacro("Unknown rescale type "<<rescaleType<<".");
}
if( rescaleType == "none" )
{
castIm = this->GetParameterImage<TImageType>("in");
}
else
{
FloatVectorImageType::Pointer input = this->GetParameterImage("in");
FloatVectorImageType::Pointer mask;
bool useMask = false;
if (IsParameterEnabled("mask"))
{
mask = this->GetParameterImage("mask");
useMask = true;
}
const unsigned int nbComp(input->GetNumberOfComponentsPerPixel());
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType, TImageType> RescalerType;
typename TImageType::PixelType minimum;
typename TImageType::PixelType maximum;
minimum.SetSize(nbComp);
maximum.SetSize(nbComp);
minimum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::min() );
maximum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::max() );
typename RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetOutputMinimum(minimum);
rescaler->SetOutputMaximum(maximum);
// We need to subsample the input image in order to estimate its
// histogram
typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
// Shrink factor is computed so as to load a quicklook of 1000
// pixels square at most
typename FloatVectorImageType::SizeType imageSize = input->GetLargestPossibleRegion().GetSize();
unsigned int shrinkFactor =
std::max(imageSize[0], imageSize[1]) < 1000 ? 1 : std::max(imageSize[0], imageSize[1])/1000;
otbAppLogDEBUG( << "Shrink factor used to compute Min/Max: "<<shrinkFactor );
otbAppLogDEBUG( << "Shrink starts..." );
shrinkFilter->SetShrinkFactor(shrinkFactor);
shrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(shrinkFilter->GetStreamer(), "Computing shrink Image for min/max estimation...");
if ( rescaleType == "log2")
{
//define the transfer log
m_TransferLog = TransferLogType::New();
m_TransferLog->SetInput(input);
m_TransferLog->UpdateOutputInformation();
shrinkFilter->SetInput(m_TransferLog->GetOutput());
rescaler->SetInput(m_TransferLog->GetOutput());
shrinkFilter->Update();
}
else
{
shrinkFilter->SetInput(input);
rescaler->SetInput(input);
shrinkFilter->Update();
}
ShrinkFilterType::Pointer maskShrinkFilter = ShrinkFilterType::New();
if (useMask)
{
maskShrinkFilter->SetShrinkFactor(shrinkFactor);
maskShrinkFilter->SetInput(mask);
maskShrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
maskShrinkFilter->Update();
}
otbAppLogDEBUG( << "Shrink done" );
otbAppLogDEBUG( << "Evaluating input Min/Max..." );
itk::ImageRegionConstIterator<FloatVectorImageType>
it(shrinkFilter->GetOutput(), shrinkFilter->GetOutput()->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<FloatVectorImageType> itMask;
if (useMask)
{
itMask = itk::ImageRegionConstIterator<FloatVectorImageType>(
maskShrinkFilter->GetOutput(),maskShrinkFilter->GetOutput()->GetLargestPossibleRegion());
}
typename ListSampleType::Pointer listSample = ListSampleType::New();
listSample->SetMeasurementVectorSize(input->GetNumberOfComponentsPerPixel());
// Now we generate the list of samples
if (useMask)
{
// Remove masked pixels
it.GoToBegin();
itMask.GoToBegin();
while (!it.IsAtEnd())
{
// float values, so the threshold is set to 0.5
if (itMask.Get()[0] < 0.5)
{
listSample->PushBack(it.Get());
}
++it;
++itMask;
}
}
else
{
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
listSample->PushBack(it.Get());
}
}
// if all pixels were masked, we assume a wrong mask and then include all image
if (listSample->Size() == 0)
{
otbAppLogINFO( << "All pixels were masked, the application assume a wrong mask "
"and include all the image");
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
listSample->PushBack(it.Get());
}
}
// And then the histogram
typename HistogramsGeneratorType::Pointer histogramsGenerator = HistogramsGeneratorType::New();
histogramsGenerator->SetListSample(listSample);
histogramsGenerator->SetNumberOfBins(255);
histogramsGenerator->NoDataFlagOn();
histogramsGenerator->Update();
// And extract the lower and upper quantile
typename FloatVectorImageType::PixelType inputMin(nbComp), inputMax(nbComp);
for(unsigned int i = 0; i < nbComp; ++i)
{
inputMin[i] =
histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0,
0.01 * GetParameterFloat("hcp.low"));
inputMax[i] =
histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0,
1.0 - 0.01 * GetParameterFloat("hcp.high"));
}
otbAppLogDEBUG( << std::setprecision(5) << "Min/Max computation done : min=" << inputMin
<< " max=" << inputMax );
rescaler->AutomaticInputMinMaxComputationOff();
rescaler->SetInputMinimum(inputMin);
rescaler->SetInputMaximum(inputMax);
if ( rescaleType == "linear")
{
rescaler->SetGamma(GetParameterFloat("type.linear.gamma"));
}
m_TmpFilter = rescaler;
castIm = rescaler->GetOutput();
}
SetParameterOutputImage<TImageType>("out", castIm);
}
void DoExecute() ITK_OVERRIDE
{
switch ( this->GetParameterOutputImagePixelType("out") )
{
case ImagePixelType_uint8:
GenericDoExecute<UInt8VectorImageType>();
break;
case ImagePixelType_int16:
GenericDoExecute<Int16VectorImageType>();
break;
case ImagePixelType_uint16:
GenericDoExecute<UInt16VectorImageType>();
break;
case ImagePixelType_int32:
GenericDoExecute<Int32VectorImageType>();
break;
case ImagePixelType_uint32:
GenericDoExecute<UInt32VectorImageType>();
break;
case ImagePixelType_float:
GenericDoExecute<FloatVectorImageType>();
break;
case ImagePixelType_double:
GenericDoExecute<DoubleVectorImageType>();
break;
default:
itkExceptionMacro("Unknown pixel type "<<this->GetParameterOutputImagePixelType("out")<<".");
break;
}
}
itk::ProcessObject::Pointer m_TmpFilter;
TransferLogType::Pointer m_TransferLog;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Convert)
<commit_msg>REFAC: add new channels parameters<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "itkCastImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
#include "itkCastImageFilter.h"
#include "otbUnaryImageFunctorWithVectorImageFilter.h"
#include "otbStreamingShrinkImageFilter.h"
#include "itkListSample.h"
#include "otbListSampleToHistogramListGenerator.h"
#include "itkImageRegionConstIterator.h"
#include "otbImageListToVectorImageFilter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbImageList.h"
namespace otb
{
namespace Wrapper
{
namespace Functor
{
template< class TScalar >
class ITK_EXPORT LogFunctor
{
public:
LogFunctor(){};
~LogFunctor(){};
TScalar operator() (const TScalar& v) const
{
return vcl_log(v);
}
};
} // end namespace Functor
class Convert : public Application
{
public:
/** Standard class typedefs. */
typedef Convert Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Convert, otb::Application);
/** Filters typedef */
typedef itk::Statistics::ListSample<FloatVectorImageType::PixelType> ListSampleType;
typedef itk::Statistics::DenseFrequencyContainer2 DFContainerType;
typedef ListSampleToHistogramListGenerator<ListSampleType,
FloatVectorImageType::InternalPixelType,
DFContainerType> HistogramsGeneratorType;
typedef StreamingShrinkImageFilter<FloatVectorImageType,
FloatVectorImageType> ShrinkFilterType;
typedef Functor::LogFunctor<FloatVectorImageType::InternalPixelType> TransferLogFunctor;
typedef UnaryImageFunctorWithVectorImageFilter<FloatVectorImageType,
FloatVectorImageType,
TransferLogFunctor> TransferLogType;
typedef otb::ImageList<FloatImageType> ImageListType;
typedef ImageListToVectorImageFilter<ImageListType,
FloatVectorImageType > ListConcatenerFilterType;
typedef MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType,
FloatImageType::PixelType> ExtractROIFilterType;
typedef ObjectList<ExtractROIFilterType> ExtractROIFilterListType;
private:
std::string m_channelMode;
Convert() : m_channelMode("default") {}
void DoInit() ITK_OVERRIDE
{
SetName("Convert");
SetDescription("Convert an image to a different format, optionally rescaling the data"
" and/or changing the pixel type.");
// Documentation
SetDocName("Image Conversion");
SetDocLongDescription("This application performs an image pixel type conversion "
" (short, ushort, uchar, int, uint, float and double types are handled). "
"The output image is written in the specified format (ie. that corresponds "
"to the given extension).\n The conversion can include a rescale using "
"the image 2 percent minimum and maximum values. The rescale can be linear or log2.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Rescale");
AddDocTag(Tags::Manip);
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_Choice, "type", "Rescale type");
SetParameterDescription("type", "Transfer function for the rescaling");
AddChoice("type.none", "None");
AddChoice("type.linear", "Linear");
AddChoice("type.log2", "Log2");
SetParameterString("type", "none", false);
AddParameter(ParameterType_Float,"type.linear.gamma","Gamma correction factor");
SetParameterDescription("type.linear.gamma","Gamma correction factor");
SetDefaultParameterFloat("type.linear.gamma",1.0);
MandatoryOff("type.linear.gamma");
AddParameter(ParameterType_InputImage, "mask", "Input mask");
SetParameterDescription("mask", "The masked pixels won't be used to adapt the dynamic "
"(the mask must have the same dimensions as the input image)");
MandatoryOff("mask");
DisableParameter("mask");
AddParameter(ParameterType_Group,"hcp","Histogram Cutting Parameters");
SetParameterDescription("hcp","Parameters to cut the histogram edges before rescaling");
AddParameter(ParameterType_Float, "hcp.high", "High Cut Quantile");
SetParameterDescription("hcp.high", "Quantiles to cut from histogram high values "
"before computing min/max rescaling (in percent, 2 by default)");
MandatoryOff("hcp.high");
SetDefaultParameterFloat("hcp.high", 2.0);
DisableParameter("hcp.high");
AddParameter(ParameterType_Float, "hcp.low", "Low Cut Quantile");
SetParameterDescription("hcp.low", "Quantiles to cut from histogram low values "
"before computing min/max rescaling (in percent, 2 by default)");
MandatoryOff("hcp.low");
SetDefaultParameterFloat("hcp.low", 2.0);
DisableParameter("hcp.low");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
SetDefaultOutputPixelType("out",ImagePixelType_uint8);
// TODO add parameter descriptions
AddParameter(ParameterType_Choice, "channels", "Channels selection");
SetParameterDescription("channels", "Channels selection");
AddChoice("channels.default", "Default mode");
SetParameterDescription("channels.default", "Select all bands in the input image.");
AddChoice("channels.mono", "Channels selection ...");
AddChoice("channels.rgb", "Channels selection RGB");
AddParameter(ParameterType_Int, "channels.rgb.red", "Red Channel");
SetParameterDescription("channels.rgb.red", "TODO");
SetDefaultParameterInt("channels.rgb.red", 1);
AddParameter(ParameterType_Int, "channels.rgb.green", "Green Channel");
SetParameterDescription("channels.rgb.green", "TODO");
SetDefaultParameterInt("channels.rgb.green", 2);
AddParameter(ParameterType_Int, "channels.rgb.blue", "Blue Channel");
SetParameterDescription("channels.rgb.blue", "TODO");
SetDefaultParameterInt("channels.rgb.blue", 3);
m_ExtractorList = ExtractROIFilterListType::New();
m_ImageList = ImageListType::New();
m_Concatener = ListConcatenerFilterType::New();
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "otbConvertWithScalingOutput.png");
SetDocExampleParameterValue("type", "linear");
SetDocExampleParameterValue("channels", "rgb");
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
m_ImageList = ImageListType::New();
m_Concatener = ListConcatenerFilterType::New();
m_ExtractorList = ExtractROIFilterListType::New();
}
template<class TImageType>
void GenericDoExecute()
{
m_channelMode = GetParameterString("channels");
std::string rescaleType = this->GetParameterString("type");
typename TImageType::Pointer castIm;
if( (rescaleType != "none") && (rescaleType != "linear") && (rescaleType != "log2") )
{
itkExceptionMacro("Unknown rescale type "<<rescaleType<<".");
}
if( rescaleType == "none" )
{
castIm = this->GetParameterImage<TImageType>("in");
}
else // linear or log2
{
FloatVectorImageType::Pointer input = this->GetParameterImage("in");
FloatVectorImageType::Pointer interInput;
FloatVectorImageType::Pointer mask;
bool useMask = false;
if (IsParameterEnabled("mask"))
{
mask = this->GetParameterImage("mask");
useMask = true;
}
// channel mode
const bool monoChannel = IsParameterEnabled("channels.mono");
if (IsParameterEnabled("channels.rgb") || monoChannel)
{
otbAppLogINFO( << "Select channels ...");
GetChannels();
input->UpdateOutputInformation();
for (std::vector<int>::iterator j=m_Channels.begin(); j!=m_Channels.end(); ++j)
{
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetInput(input);
if (!monoChannel) extractROIFilter->SetChannel((*j)+1);
extractROIFilter->UpdateOutputInformation();
m_ExtractorList->PushBack(extractROIFilter);
m_ImageList->PushBack(extractROIFilter->GetOutput());
}
m_Concatener->SetInput(m_ImageList);
m_Concatener->UpdateOutputInformation();
interInput = m_Concatener->GetOutput();
}
else
{
interInput = input;
}
const unsigned int nbComp(interInput->GetNumberOfComponentsPerPixel());
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType, TImageType> RescalerType;
typename TImageType::PixelType minimum;
typename TImageType::PixelType maximum;
minimum.SetSize(nbComp);
maximum.SetSize(nbComp);
minimum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::min() );
maximum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::max() );
typename RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetOutputMinimum(minimum);
rescaler->SetOutputMaximum(maximum);
// We need to subsample the input image in order to estimate its
// histogram
typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
// Shrink factor is computed so as to load a quicklook of 1000
// pixels square at most
typename FloatVectorImageType::SizeType imageSize = interInput->GetLargestPossibleRegion().GetSize();
unsigned int shrinkFactor =
std::max(imageSize[0], imageSize[1]) < 1000 ? 1 : std::max(imageSize[0], imageSize[1])/1000;
otbAppLogDEBUG( << "Shrink factor used to compute Min/Max: "<<shrinkFactor );
otbAppLogDEBUG( << "Shrink starts..." );
shrinkFilter->SetShrinkFactor(shrinkFactor);
shrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(shrinkFilter->GetStreamer(), "Computing shrink Image for min/max estimation...");
if ( rescaleType == "log2")
{
//define the transfer log
m_TransferLog = TransferLogType::New();
m_TransferLog->SetInput(interInput);
m_TransferLog->UpdateOutputInformation();
shrinkFilter->SetInput(m_TransferLog->GetOutput());
rescaler->SetInput(m_TransferLog->GetOutput());
shrinkFilter->Update();
}
else
{
shrinkFilter->SetInput(interInput);
rescaler->SetInput(interInput);
shrinkFilter->Update();
}
ShrinkFilterType::Pointer maskShrinkFilter = ShrinkFilterType::New();
if (useMask)
{
maskShrinkFilter->SetShrinkFactor(shrinkFactor);
maskShrinkFilter->SetInput(mask);
maskShrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
maskShrinkFilter->Update();
}
otbAppLogDEBUG( << "Shrink done" );
otbAppLogDEBUG( << "Evaluating input Min/Max..." );
itk::ImageRegionConstIterator<FloatVectorImageType>
it(shrinkFilter->GetOutput(), shrinkFilter->GetOutput()->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<FloatVectorImageType> itMask;
if (useMask)
{
itMask = itk::ImageRegionConstIterator<FloatVectorImageType>(
maskShrinkFilter->GetOutput(),maskShrinkFilter->GetOutput()->GetLargestPossibleRegion());
}
typename ListSampleType::Pointer listSample = ListSampleType::New();
listSample->SetMeasurementVectorSize(interInput->GetNumberOfComponentsPerPixel());
// Now we generate the list of samples
if (useMask)
{
// Remove masked pixels
it.GoToBegin();
itMask.GoToBegin();
while (!it.IsAtEnd())
{
// float values, so the threshold is set to 0.5
if (itMask.Get()[0] < 0.5)
{
listSample->PushBack(it.Get());
}
++it;
++itMask;
}
}
else
{
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
listSample->PushBack(it.Get());
}
}
// if all pixels were masked, we assume a wrong mask and then include all image
if (listSample->Size() == 0)
{
otbAppLogINFO( << "All pixels were masked, the application assume a wrong mask "
"and include all the image");
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
listSample->PushBack(it.Get());
}
}
// And then the histogram
typename HistogramsGeneratorType::Pointer histogramsGenerator = HistogramsGeneratorType::New();
histogramsGenerator->SetListSample(listSample);
histogramsGenerator->SetNumberOfBins(255);
histogramsGenerator->NoDataFlagOn();
histogramsGenerator->Update();
// And extract the lower and upper quantile
typename FloatVectorImageType::PixelType inputMin(nbComp), inputMax(nbComp);
for(unsigned int i = 0; i < nbComp; ++i)
{
inputMin[i] =
histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0,
0.01 * GetParameterFloat("hcp.low"));
inputMax[i] =
histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0,
1.0 - 0.01 * GetParameterFloat("hcp.high"));
}
otbAppLogDEBUG( << std::setprecision(5) << "Min/Max computation done : min=" << inputMin
<< " max=" << inputMax );
rescaler->AutomaticInputMinMaxComputationOff();
rescaler->SetInputMinimum(inputMin);
rescaler->SetInputMaximum(inputMax);
if ( rescaleType == "linear")
{
rescaler->SetGamma(GetParameterFloat("type.linear.gamma"));
}
m_TmpFilter = rescaler;
castIm = rescaler->GetOutput();
}
SetParameterOutputImage<TImageType>("out", castIm);
}
// TODO comment function
void GetChannels()
{
m_Channels.clear();
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
int nbChan = GetParameterImage("in")->GetNumberOfComponentsPerPixel();
if(m_channelMode == "mono")
{
m_Channels = {1,1,1};
}
else if (m_channelMode == "rgb")
{
if ((GetParameterInt("channels.rgb.red") <= nbChan)
&& ( GetParameterInt("channels.rgb.green") <= nbChan)
&& ( GetParameterInt("channels.rgb.blue") <= nbChan))
{
m_Channels = {GetParameterInt("channels.rgb.red"),
GetParameterInt("channels.rgb.green"),
GetParameterInt("channels.rgb.blue")};
}
else
{
itkExceptionMacro(<< "At least one needed channel has an invalid index");
}
}
else if (m_channelMode == "default")
{
// take all bands
}
}
void DoExecute() ITK_OVERRIDE
{
switch ( this->GetParameterOutputImagePixelType("out") )
{
case ImagePixelType_uint8:
GenericDoExecute<UInt8VectorImageType>();
break;
case ImagePixelType_int16:
GenericDoExecute<Int16VectorImageType>();
break;
case ImagePixelType_uint16:
GenericDoExecute<UInt16VectorImageType>();
break;
case ImagePixelType_int32:
GenericDoExecute<Int32VectorImageType>();
break;
case ImagePixelType_uint32:
GenericDoExecute<UInt32VectorImageType>();
break;
case ImagePixelType_float:
GenericDoExecute<FloatVectorImageType>();
break;
case ImagePixelType_double:
GenericDoExecute<DoubleVectorImageType>();
break;
default:
itkExceptionMacro("Unknown pixel type "<<this->GetParameterOutputImagePixelType("out")<<".");
break;
}
}
itk::ProcessObject::Pointer m_TmpFilter;
TransferLogType::Pointer m_TransferLog;
std::vector<int> m_Channels;
ImageListType::Pointer m_ImageList;
ListConcatenerFilterType::Pointer m_Concatener;
ExtractROIFilterListType::Pointer m_ExtractorList;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Convert)
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkCESTImageNormalizationFilter.h"
#include <mitkCustomTagParser.h>
#include <mitkImage.h>
#include <mitkImageAccessByItk.h>
#include <mitkImageCast.h>
#include <mitkLocaleSwitch.h>
#include <boost/algorithm/string.hpp>
mitk::CESTImageNormalizationFilter::CESTImageNormalizationFilter()
{
}
mitk::CESTImageNormalizationFilter::~CESTImageNormalizationFilter()
{
}
void mitk::CESTImageNormalizationFilter::GenerateData()
{
mitk::Image::ConstPointer inputImage = this->GetInput(0);
if ((inputImage->GetDimension() != 4))
{
mitkThrow() << "mitk::CESTImageNormalizationFilter:GenerateData works only with 4D images, sorry.";
return;
}
auto resultMitkImage = this->GetOutput();
AccessFixedDimensionByItk(inputImage, NormalizeTimeSteps, 4);
auto originalTimeGeometry = this->GetInput()->GetTimeGeometry();
auto resultTimeGeometry = mitk::ProportionalTimeGeometry::New();
unsigned int numberOfNonM0s = m_NonM0Indices.size();
resultTimeGeometry->Expand(numberOfNonM0s);
for (unsigned int index = 0; index < numberOfNonM0s; ++index)
{
resultTimeGeometry->SetTimeStepGeometry(originalTimeGeometry->GetGeometryCloneForTimeStep(m_NonM0Indices.at(index)), index);
}
resultMitkImage->SetTimeGeometry(resultTimeGeometry);
resultMitkImage->SetPropertyList(this->GetInput()->GetPropertyList()->Clone());
resultMitkImage->GetPropertyList()->SetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), m_RealOffsets.c_str());
// remove uids
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0008.0018");
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000D");
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000E");
}
template <typename TPixel, unsigned int VImageDimension>
void mitk::CESTImageNormalizationFilter::NormalizeTimeSteps(const itk::Image<TPixel, VImageDimension>* image)
{
mitk::LocaleSwitch localeSwitch("C");
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::Image<double, VImageDimension> OutputImageType;
std::string offsets = "";
this->GetInput()->GetPropertyList()->GetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), offsets);
std::vector<std::string> parts;
boost::split(parts, offsets, boost::is_any_of(" "));
// determine normalization images
std::vector<unsigned int> mZeroIndices;
std::stringstream offsetsWithoutM0;
m_NonM0Indices.clear();
for (unsigned int index = 0; index < parts.size(); ++index)
{
if ((std::stod(parts.at(index)) < -299) || (std::stod(parts.at(index)) > 299))
{
mZeroIndices.push_back(index);
}
else
{
offsetsWithoutM0 << parts.at(index) << " ";
m_NonM0Indices.push_back(index);
}
}
auto resultImage = OutputImageType::New();
typename ImageType::RegionType targetEntireRegion = image->GetLargestPossibleRegion();
targetEntireRegion.SetSize(3, m_NonM0Indices.size());
resultImage->SetRegions(targetEntireRegion);
resultImage->Allocate();
resultImage->FillBuffer(0);
unsigned int numberOfTimesteps = image->GetLargestPossibleRegion().GetSize(3);
typename ImageType::RegionType lowerMZeroRegion = image->GetLargestPossibleRegion();
lowerMZeroRegion.SetSize(3, 1);
typename ImageType::RegionType upperMZeroRegion = image->GetLargestPossibleRegion();
upperMZeroRegion.SetSize(3, 1);
typename ImageType::RegionType sourceRegion = image->GetLargestPossibleRegion();
sourceRegion.SetSize(3, 1);
typename OutputImageType::RegionType targetRegion = resultImage->GetLargestPossibleRegion();
targetRegion.SetSize(3, 1);
unsigned int targetTimestep = 0;
for (unsigned int sourceTimestep = 0; sourceTimestep < numberOfTimesteps; ++sourceTimestep)
{
unsigned int lowerMZeroIndex = mZeroIndices[0];
unsigned int upperMZeroIndex = mZeroIndices[0];
for (unsigned int loop = 0; loop < mZeroIndices.size(); ++loop)
{
if (mZeroIndices[loop] <= sourceTimestep)
{
lowerMZeroIndex = mZeroIndices[loop];
}
if (mZeroIndices[loop] > sourceTimestep)
{
upperMZeroIndex = mZeroIndices[loop];
break;
}
}
bool isMZero = (lowerMZeroIndex == sourceTimestep);
double weight = 0.0;
if (lowerMZeroIndex == upperMZeroIndex)
{
weight = 1.0;
}
else
{
weight = 1.0 - double(sourceTimestep - lowerMZeroIndex) / double(upperMZeroIndex - lowerMZeroIndex);
}
if (isMZero)
{
//do nothing
}
else
{
lowerMZeroRegion.SetIndex(3, lowerMZeroIndex);
upperMZeroRegion.SetIndex(3, upperMZeroIndex);
sourceRegion.SetIndex(3, sourceTimestep);
targetRegion.SetIndex(3, targetTimestep);
itk::ImageRegionConstIterator<ImageType> lowerMZeroIterator(image, lowerMZeroRegion);
itk::ImageRegionConstIterator<ImageType> upperMZeroIterator(image, upperMZeroRegion);
itk::ImageRegionConstIterator<ImageType> sourceIterator(image, sourceRegion);
itk::ImageRegionIterator<OutputImageType> targetIterator(resultImage.GetPointer(), targetRegion);
while (!sourceIterator.IsAtEnd())
{
double normalizationFactor = weight * lowerMZeroIterator.Get() + (1.0 - weight) * upperMZeroIterator.Get();
if (mitk::Equal(normalizationFactor, 0))
{
targetIterator.Set(0);
}
else
{
targetIterator.Set(double(sourceIterator.Get()) / normalizationFactor);
}
++lowerMZeroIterator;
++upperMZeroIterator;
++sourceIterator;
++targetIterator;
}
++targetTimestep;
}
}
// get Pointer to output image
mitk::Image::Pointer resultMitkImage = this->GetOutput();
// write into output image
mitk::CastToMitkImage<OutputImageType>(resultImage, resultMitkImage);
m_RealOffsets = offsetsWithoutM0.str();
}
void mitk::CESTImageNormalizationFilter::GenerateOutputInformation()
{
mitk::Image::ConstPointer input = this->GetInput();
mitk::Image::Pointer output = this->GetOutput();
itkDebugMacro(<< "GenerateOutputInformation()");
}
<commit_msg>Fixed T24700<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkCESTImageNormalizationFilter.h"
#include <mitkCustomTagParser.h>
#include <mitkImage.h>
#include <mitkImageAccessByItk.h>
#include <mitkImageCast.h>
#include <mitkLocaleSwitch.h>
#include <boost/algorithm/string.hpp>
mitk::CESTImageNormalizationFilter::CESTImageNormalizationFilter()
{
}
mitk::CESTImageNormalizationFilter::~CESTImageNormalizationFilter()
{
}
void mitk::CESTImageNormalizationFilter::GenerateData()
{
mitk::Image::ConstPointer inputImage = this->GetInput(0);
if ((inputImage->GetDimension() != 4))
{
mitkThrow() << "mitk::CESTImageNormalizationFilter:GenerateData works only with 4D images, sorry.";
return;
}
auto resultMitkImage = this->GetOutput();
AccessFixedDimensionByItk(inputImage, NormalizeTimeSteps, 4);
auto originalTimeGeometry = this->GetInput()->GetTimeGeometry();
auto resultTimeGeometry = mitk::ProportionalTimeGeometry::New();
unsigned int numberOfNonM0s = m_NonM0Indices.size();
resultTimeGeometry->Expand(numberOfNonM0s);
for (unsigned int index = 0; index < numberOfNonM0s; ++index)
{
resultTimeGeometry->SetTimeStepGeometry(originalTimeGeometry->GetGeometryCloneForTimeStep(m_NonM0Indices.at(index)), index);
}
resultMitkImage->SetTimeGeometry(resultTimeGeometry);
resultMitkImage->SetPropertyList(this->GetInput()->GetPropertyList()->Clone());
resultMitkImage->GetPropertyList()->SetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), m_RealOffsets.c_str());
// remove uids
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0008.0018");
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000D");
resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000E");
}
template <typename TPixel, unsigned int VImageDimension>
void mitk::CESTImageNormalizationFilter::NormalizeTimeSteps(const itk::Image<TPixel, VImageDimension>* image)
{
mitk::LocaleSwitch localeSwitch("C");
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::Image<double, VImageDimension> OutputImageType;
std::string offsets = "";
this->GetInput()->GetPropertyList()->GetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), offsets);
boost::algorithm::trim(offsets);
std::vector<std::string> parts;
boost::split(parts, offsets, boost::is_any_of(" "));
// determine normalization images
std::vector<unsigned int> mZeroIndices;
std::stringstream offsetsWithoutM0;
m_NonM0Indices.clear();
for (unsigned int index = 0; index < parts.size(); ++index)
{
if ((std::stod(parts.at(index)) < -299) || (std::stod(parts.at(index)) > 299))
{
mZeroIndices.push_back(index);
}
else
{
offsetsWithoutM0 << parts.at(index) << " ";
m_NonM0Indices.push_back(index);
}
}
auto resultImage = OutputImageType::New();
typename ImageType::RegionType targetEntireRegion = image->GetLargestPossibleRegion();
targetEntireRegion.SetSize(3, m_NonM0Indices.size());
resultImage->SetRegions(targetEntireRegion);
resultImage->Allocate();
resultImage->FillBuffer(0);
unsigned int numberOfTimesteps = image->GetLargestPossibleRegion().GetSize(3);
typename ImageType::RegionType lowerMZeroRegion = image->GetLargestPossibleRegion();
lowerMZeroRegion.SetSize(3, 1);
typename ImageType::RegionType upperMZeroRegion = image->GetLargestPossibleRegion();
upperMZeroRegion.SetSize(3, 1);
typename ImageType::RegionType sourceRegion = image->GetLargestPossibleRegion();
sourceRegion.SetSize(3, 1);
typename OutputImageType::RegionType targetRegion = resultImage->GetLargestPossibleRegion();
targetRegion.SetSize(3, 1);
unsigned int targetTimestep = 0;
for (unsigned int sourceTimestep = 0; sourceTimestep < numberOfTimesteps; ++sourceTimestep)
{
unsigned int lowerMZeroIndex = mZeroIndices[0];
unsigned int upperMZeroIndex = mZeroIndices[0];
for (unsigned int loop = 0; loop < mZeroIndices.size(); ++loop)
{
if (mZeroIndices[loop] <= sourceTimestep)
{
lowerMZeroIndex = mZeroIndices[loop];
}
if (mZeroIndices[loop] > sourceTimestep)
{
upperMZeroIndex = mZeroIndices[loop];
break;
}
}
bool isMZero = (lowerMZeroIndex == sourceTimestep);
double weight = 0.0;
if (lowerMZeroIndex == upperMZeroIndex)
{
weight = 1.0;
}
else
{
weight = 1.0 - double(sourceTimestep - lowerMZeroIndex) / double(upperMZeroIndex - lowerMZeroIndex);
}
if (isMZero)
{
//do nothing
}
else
{
lowerMZeroRegion.SetIndex(3, lowerMZeroIndex);
upperMZeroRegion.SetIndex(3, upperMZeroIndex);
sourceRegion.SetIndex(3, sourceTimestep);
targetRegion.SetIndex(3, targetTimestep);
itk::ImageRegionConstIterator<ImageType> lowerMZeroIterator(image, lowerMZeroRegion);
itk::ImageRegionConstIterator<ImageType> upperMZeroIterator(image, upperMZeroRegion);
itk::ImageRegionConstIterator<ImageType> sourceIterator(image, sourceRegion);
itk::ImageRegionIterator<OutputImageType> targetIterator(resultImage.GetPointer(), targetRegion);
while (!sourceIterator.IsAtEnd())
{
double normalizationFactor = weight * lowerMZeroIterator.Get() + (1.0 - weight) * upperMZeroIterator.Get();
if (mitk::Equal(normalizationFactor, 0))
{
targetIterator.Set(0);
}
else
{
targetIterator.Set(double(sourceIterator.Get()) / normalizationFactor);
}
++lowerMZeroIterator;
++upperMZeroIterator;
++sourceIterator;
++targetIterator;
}
++targetTimestep;
}
}
// get Pointer to output image
mitk::Image::Pointer resultMitkImage = this->GetOutput();
// write into output image
mitk::CastToMitkImage<OutputImageType>(resultImage, resultMitkImage);
m_RealOffsets = offsetsWithoutM0.str();
}
void mitk::CESTImageNormalizationFilter::GenerateOutputInformation()
{
mitk::Image::ConstPointer input = this->GetInput();
mitk::Image::Pointer output = this->GetOutput();
itkDebugMacro(<< "GenerateOutputInformation()");
}
<|endoftext|>
|
<commit_before>AliAnalysisTaskLegendreCoef* AddTaskLegendreCoef(TString name = "name")
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":LongFluctuations"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskLegendreCoef* task = new AliAnalysisTaskLegendreCoef(name.Data());
if(!task) return 0x0;
task->SelectCollisionCandidates(AliVEvent::kINT7);
task->SetMCRead(kFALSE);
task->SetPileUpRead(kFALSE);
task->SetChi2DoF(4);
task->SetPtLimits(0.2, 2.0);
task->SetEtaLimit(0.8);
task->SetBuildBackground(kFALSE);
task->SetBuildLegendre(kFALSE);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer("EtaBG", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<commit_msg>Update AddTaskLegendreCoef.C<commit_after>AliAnalysisTaskLegendreCoef* AddTaskLegendreCoef(const char *suffix = "")
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
TString name;
name.Form("LegCoef%s", suffix);
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":LongFluctuations"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskLegendreCoef* task = new AliAnalysisTaskLegendreCoef(name.Data());
if(!task) return 0x0;
task->SelectCollisionCandidates(AliVEvent::kINT7);
task->SetMCRead(kFALSE);
task->SetPileUpRead(kFALSE);
task->SetChi2DoF(4);
task->SetPtLimits(0.2, 2.0);
task->SetEtaLimit(0.8);
task->SetBuildBackground(kFALSE);
task->SetBuildLegendre(kFALSE);
printf("Container name is %s\n",name.Data());
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer(name.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<|endoftext|>
|
<commit_before>/*
* AliFemtoDreamAnalysis.cxx
*
* Created on: 24 Nov 2017
* Author: bernhardhohlweger
*/
#include <vector>
#include "AliLog.h"
#include "AliFemtoDreamAnalysis.h"
#include "TClonesArray.h"
#include <iostream>
ClassImp(AliFemtoDreamAnalysis)
AliFemtoDreamAnalysis::AliFemtoDreamAnalysis()
:fMVPileUp(false)
,fEvtCutQA(false)
,fQA()
,fFemtoTrack()
,fFemtov0()
,fFemtoCasc()
,fEvent()
,fEvtCuts()
,fTrackCuts()
,fAntiTrackCuts()
,fv0Cuts()
,fAntiv0Cuts()
,fCascCuts()
,fAntiCascCuts()
,fPairCleaner()
,fControlSample()
,fTrackBufferSize(0)
,fGTI(0)
,fConfig(0)
,fPartColl(0)
{
}
AliFemtoDreamAnalysis::~AliFemtoDreamAnalysis() {
if (fFemtoTrack) {
delete fFemtoTrack;
}
if (fFemtov0) {
delete fFemtov0;
}
if (fFemtoCasc) {
delete fFemtoCasc;
}
}
void AliFemtoDreamAnalysis::Init(bool isMonteCarlo,UInt_t trigger) {
fFemtoTrack=new AliFemtoDreamTrack();
fFemtoTrack->SetUseMCInfo(isMonteCarlo);
fFemtov0=new AliFemtoDreamv0();
fFemtov0->SetPDGCode(fv0Cuts->GetPDGv0());
fFemtov0->SetUseMCInfo(isMonteCarlo);
fFemtov0->SetPDGDaughterPos(fv0Cuts->GetPDGPosDaug());//order +sign doesnt play a role
fFemtov0->GetPosDaughter()->SetUseMCInfo(isMonteCarlo);
fFemtov0->SetPDGDaughterNeg(fv0Cuts->GetPDGNegDaug());//only used for MC Matching
fFemtov0->GetNegDaughter()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc=new AliFemtoDreamCascade();
fFemtoCasc->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGCode(fCascCuts->GetPDGCodeCasc());
fFemtoCasc->SetPDGDaugPos(fCascCuts->GetPDGCodePosDaug());
fFemtoCasc->GetPosDaug()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGDaugNeg(fCascCuts->GetPDGCodeNegDaug());
fFemtoCasc->GetNegDaug()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGDaugBach(fCascCuts->GetPDGCodeBach());
fFemtoCasc->GetBach()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->Setv0PDGCode(fCascCuts->GetPDGv0());
fEvtCuts->InitQA();
fTrackCuts->Init();
fAntiTrackCuts->Init();
fv0Cuts->Init();
fAntiv0Cuts->Init();
fCascCuts->Init();
fAntiCascCuts->Init();
fGTI=new AliAODTrack*[fTrackBufferSize];
fEvent=new AliFemtoDreamEvent(fMVPileUp,fEvtCutQA,trigger);
fEvent->SetMultiplicityEstimator(fConfig->GetMultiplicityEstimator());
bool MinBooking=
!((!fConfig->GetMinimalBookingME())||(!fConfig->GetMinimalBookingSample()));
fPairCleaner=new AliFemtoDreamPairCleaner(4,4,MinBooking);
if (!MinBooking) {
fQA=new TList();
fQA->SetOwner();
fQA->SetName("QA");
fQA->Add(fPairCleaner->GetHistList());
if (fEvtCutQA) fQA->Add(fEvent->GetEvtCutList());
}
fPartColl=
new AliFemtoDreamPartCollection(fConfig,fConfig->GetMinimalBookingME());
fControlSample=
new AliFemtoDreamControlSample(fConfig,fConfig->GetMinimalBookingSample());
return;
}
void AliFemtoDreamAnalysis::ResetGlobalTrackReference(){
//This method was inherited form H. Beck analysis
// Sets all the pointers to zero. To be called at
// the beginning or end of an event
for(UShort_t i=0;i<fTrackBufferSize;i++)
{
fGTI[i]=0;
}
}
void AliFemtoDreamAnalysis::StoreGlobalTrackReference(AliAODTrack *track){
//This method was inherited form H. Beck analysis
//bhohlweg@cern.ch: We ask for the Unique Track ID that points back to the
//ESD. Seems like global tracks have a positive ID, Tracks with Filterbit
//128 only have negative ID, this is used to match the Tracks later to their
//global counterparts
// Stores the pointer to the global track
// This was AOD073
// // Don't use the filter bits 2 (ITS standalone) and 128 TPC only
// // Remove this return statement and you'll see they don't have
// // any TPC signal
// if(track->TestFilterBit(128) || track->TestFilterBit(2))
// return;
// This is AOD086
// Another set of tracks was introduced: Global constrained.
// We only want filter bit 1 <-- NO! we also want no
// filter bit at all, which are the v0 tracks
// if(!track->TestFilterBit(1))
// return;
// There are also tracks without any filter bit, i.e. filter map 0,
// at the beginning of the event: they have ~id 1 to 5, 1 to 12
// This are tracks that didn't survive the primary track filter but
// got written cause they are V0 daughters
// Check whether the track has some info
// I don't know: there are tracks with filter bit 0
// and no TPC signal. ITS standalone V0 daughters?
// if(!track->GetTPCsignal()){
// printf("Warning: track has no TPC signal, "
// // "not adding it's info! "
// "ID: %d FilterMap: %d\n"
// ,track->GetID(),track->GetFilterMap());
// // return;
// }
// Check that the id is positive
const int trackID = track->GetID();
if(trackID<0){
return;
}
// Check id is not too big for buffer
if(trackID>=fTrackBufferSize){
printf("Warning: track ID too big for buffer: ID: %d, buffer %d\n"
,trackID,fTrackBufferSize);
return;
}
// Warn if we overwrite a track
if(fGTI[trackID])
{
// Seems like there are FilterMap 0 tracks
// that have zero TPCNcls, don't store these!
if( (!track->GetFilterMap()) && (!track->GetTPCNcls()) ){
return;
}
// Imagine the other way around, the zero map zero clusters track
// is stored and the good one wants to be added. We ommit the warning
// and just overwrite the 'bad' track
if( fGTI[trackID]->GetFilterMap() || fGTI[trackID]->GetTPCNcls() ){
// If we come here, there's a problem
printf("Warning! global track info already there!");
printf(" TPCNcls track1 %u track2 %u",
(fGTI[trackID])->GetTPCNcls(),track->GetTPCNcls());
printf(" FilterMap track1 %u track2 %u\n",
(fGTI[trackID])->GetFilterMap(),track->GetFilterMap());
}
} // Two tracks same id
// // There are tracks with filter bit 0,
// // do they have TPCNcls stored?
// if(!track->GetFilterMap()){
// printf("Filter map is zero, TPCNcls: %u\n"
// ,track->GetTPCNcls());
// }
// Assign the pointer
(fGTI[trackID]) = track;
}
void AliFemtoDreamAnalysis::Make(AliAODEvent *evt) {
if (!evt) {
AliFatal("No Input Event");
}
fEvent->SetEvent(evt);
if (!fEvtCuts->isSelected(fEvent)) {
return;
}
ResetGlobalTrackReference();
for(int iTrack = 0;iTrack<evt->GetNumberOfTracks();++iTrack){
AliAODTrack *track=static_cast<AliAODTrack*>(evt->GetTrack(iTrack));
if (!track) {
AliFatal("No Standard AOD");
return;
}
StoreGlobalTrackReference(track);
}
std::vector<AliFemtoDreamBasePart> Particles;
std::vector<AliFemtoDreamBasePart> AntiParticles;
fFemtoTrack->SetGlobalTrackInfo(fGTI,fTrackBufferSize);
for (int iTrack = 0;iTrack<evt->GetNumberOfTracks();++iTrack) {
AliAODTrack *track=static_cast<AliAODTrack*>(evt->GetTrack(iTrack));
if (!track) {
AliFatal("No Standard AOD");
return;
}
fFemtoTrack->SetTrack(track);
if (fTrackCuts->isSelected(fFemtoTrack)) {
Particles.push_back(*fFemtoTrack);
}
if (fAntiTrackCuts->isSelected(fFemtoTrack)) {
AntiParticles.push_back(*fFemtoTrack);
}
}
std::vector<AliFemtoDreamBasePart> Decays;
std::vector<AliFemtoDreamBasePart> AntiDecays;
// Look for the lambda, store it in an event
// Get a V0 from the event:
TClonesArray *v01 = static_cast<TClonesArray*>(evt->GetV0s());
//number of V0s:
fFemtov0->SetGlobalTrackInfo(fGTI,fTrackBufferSize);
int entriesV0= v01->GetEntriesFast();
for (int iv0=0; iv0<entriesV0; iv0++) {
AliAODv0 *v0 = evt->GetV0(iv0);
fFemtov0->Setv0(evt, v0);
if (fv0Cuts->isSelected(fFemtov0)) {
Decays.push_back(*fFemtov0);
}
if (fAntiv0Cuts->isSelected(fFemtov0)) {
AntiDecays.push_back(*fFemtov0);
}
}
std::vector<AliFemtoDreamBasePart> XiDecays;
std::vector<AliFemtoDreamBasePart> AntiXiDecays;
int numcascades = evt->GetNumberOfCascades();
for (int iXi=0;iXi<numcascades;++iXi) {
AliAODcascade *xi = evt->GetCascade(iXi);
if (!xi) continue;
fFemtoCasc->SetCascade(evt,xi);
if (fCascCuts->isSelected(fFemtoCasc)) {
XiDecays.push_back(*fFemtoCasc);
}
if (fAntiCascCuts->isSelected(fFemtoCasc)) {
AntiXiDecays.push_back(*fFemtoCasc);
}
}
fPairCleaner->ResetArray();
fPairCleaner->CleanTrackAndDecay(&Particles,&Decays,0);
fPairCleaner->CleanTrackAndDecay(&Particles,&XiDecays,2);
fPairCleaner->CleanTrackAndDecay(&AntiParticles,&AntiDecays,1);
fPairCleaner->CleanTrackAndDecay(&AntiParticles,&AntiXiDecays,3);
fPairCleaner->CleanDecay(&Decays,0);
fPairCleaner->CleanDecay(&AntiDecays,1);
fPairCleaner->CleanDecay(&XiDecays,2);
fPairCleaner->CleanDecay(&AntiXiDecays,3);
fPairCleaner->StoreParticle(Particles);
fPairCleaner->StoreParticle(AntiParticles);
fPairCleaner->StoreParticle(Decays);
fPairCleaner->StoreParticle(AntiDecays);
fPairCleaner->StoreParticle(XiDecays);
fPairCleaner->StoreParticle(AntiXiDecays);
if (fConfig->GetUseEventMixing()) {
fPartColl->SetEvent(
fPairCleaner->GetCleanParticles(),fEvent->GetZVertex(),
fEvent->GetMultiplicity(),fEvent->GetV0MCentrality());
}
if (fConfig->GetUsePhiSpinning()) {
fControlSample->SetEvent(
fPairCleaner->GetCleanParticles(), fEvent->GetMultiplicity());
}
}
<commit_msg>Fixes to the initialization and the posting of data<commit_after>/*
* AliFemtoDreamAnalysis.cxx
*
* Created on: 24 Nov 2017
* Author: bernhardhohlweger
*/
#include <vector>
#include "AliLog.h"
#include "AliFemtoDreamAnalysis.h"
#include "TClonesArray.h"
#include <iostream>
ClassImp(AliFemtoDreamAnalysis)
AliFemtoDreamAnalysis::AliFemtoDreamAnalysis()
:fMVPileUp(false)
,fEvtCutQA(false)
,fQA()
,fFemtoTrack()
,fFemtov0()
,fFemtoCasc()
,fEvent()
,fEvtCuts()
,fTrackCuts()
,fAntiTrackCuts()
,fv0Cuts()
,fAntiv0Cuts()
,fCascCuts()
,fAntiCascCuts()
,fPairCleaner()
,fControlSample()
,fTrackBufferSize(0)
,fGTI(0)
,fConfig(0)
,fPartColl(0)
{
}
AliFemtoDreamAnalysis::~AliFemtoDreamAnalysis() {
if (fFemtoTrack) {
delete fFemtoTrack;
}
if (fFemtov0) {
delete fFemtov0;
}
if (fFemtoCasc) {
delete fFemtoCasc;
}
}
void AliFemtoDreamAnalysis::Init(bool isMonteCarlo,UInt_t trigger) {
fFemtoTrack=new AliFemtoDreamTrack();
fFemtoTrack->SetUseMCInfo(isMonteCarlo);
fFemtov0=new AliFemtoDreamv0();
fFemtov0->SetPDGCode(fv0Cuts->GetPDGv0());
fFemtov0->SetUseMCInfo(isMonteCarlo);
fFemtov0->SetPDGDaughterPos(fv0Cuts->GetPDGPosDaug());//order +sign doesnt play a role
fFemtov0->GetPosDaughter()->SetUseMCInfo(isMonteCarlo);
fFemtov0->SetPDGDaughterNeg(fv0Cuts->GetPDGNegDaug());//only used for MC Matching
fFemtov0->GetNegDaughter()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc=new AliFemtoDreamCascade();
fFemtoCasc->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGCode(fCascCuts->GetPDGCodeCasc());
fFemtoCasc->SetPDGDaugPos(fCascCuts->GetPDGCodePosDaug());
fFemtoCasc->GetPosDaug()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGDaugNeg(fCascCuts->GetPDGCodeNegDaug());
fFemtoCasc->GetNegDaug()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->SetPDGDaugBach(fCascCuts->GetPDGCodeBach());
fFemtoCasc->GetBach()->SetUseMCInfo(isMonteCarlo);
fFemtoCasc->Setv0PDGCode(fCascCuts->GetPDGv0());
fEvtCuts->InitQA();
fTrackCuts->Init();
fAntiTrackCuts->Init();
fv0Cuts->Init();
fAntiv0Cuts->Init();
fCascCuts->Init();
fAntiCascCuts->Init();
fGTI=new AliAODTrack*[fTrackBufferSize];
fEvent=new AliFemtoDreamEvent(fMVPileUp,fEvtCutQA,trigger);
fEvent->SetMultiplicityEstimator(fConfig->GetMultiplicityEstimator());
bool MinBooking=
!((!fConfig->GetMinimalBookingME())||(!fConfig->GetMinimalBookingSample()));
fPairCleaner=new AliFemtoDreamPairCleaner(4,4,MinBooking);
if (MinBooking) {
fQA=new TList();
fQA->SetOwner();
fQA->SetName("QA");
fQA->Add(fPairCleaner->GetHistList());
if (fEvtCutQA) fQA->Add(fEvent->GetEvtCutList());
}
fPartColl=
new AliFemtoDreamPartCollection(fConfig,fConfig->GetMinimalBookingME());
fControlSample=
new AliFemtoDreamControlSample(fConfig,fConfig->GetMinimalBookingSample());
return;
}
void AliFemtoDreamAnalysis::ResetGlobalTrackReference(){
//This method was inherited form H. Beck analysis
// Sets all the pointers to zero. To be called at
// the beginning or end of an event
for(UShort_t i=0;i<fTrackBufferSize;i++)
{
fGTI[i]=0;
}
}
void AliFemtoDreamAnalysis::StoreGlobalTrackReference(AliAODTrack *track){
//This method was inherited form H. Beck analysis
//bhohlweg@cern.ch: We ask for the Unique Track ID that points back to the
//ESD. Seems like global tracks have a positive ID, Tracks with Filterbit
//128 only have negative ID, this is used to match the Tracks later to their
//global counterparts
// Stores the pointer to the global track
// This was AOD073
// // Don't use the filter bits 2 (ITS standalone) and 128 TPC only
// // Remove this return statement and you'll see they don't have
// // any TPC signal
// if(track->TestFilterBit(128) || track->TestFilterBit(2))
// return;
// This is AOD086
// Another set of tracks was introduced: Global constrained.
// We only want filter bit 1 <-- NO! we also want no
// filter bit at all, which are the v0 tracks
// if(!track->TestFilterBit(1))
// return;
// There are also tracks without any filter bit, i.e. filter map 0,
// at the beginning of the event: they have ~id 1 to 5, 1 to 12
// This are tracks that didn't survive the primary track filter but
// got written cause they are V0 daughters
// Check whether the track has some info
// I don't know: there are tracks with filter bit 0
// and no TPC signal. ITS standalone V0 daughters?
// if(!track->GetTPCsignal()){
// printf("Warning: track has no TPC signal, "
// // "not adding it's info! "
// "ID: %d FilterMap: %d\n"
// ,track->GetID(),track->GetFilterMap());
// // return;
// }
// Check that the id is positive
const int trackID = track->GetID();
if(trackID<0){
return;
}
// Check id is not too big for buffer
if(trackID>=fTrackBufferSize){
printf("Warning: track ID too big for buffer: ID: %d, buffer %d\n"
,trackID,fTrackBufferSize);
return;
}
// Warn if we overwrite a track
if(fGTI[trackID])
{
// Seems like there are FilterMap 0 tracks
// that have zero TPCNcls, don't store these!
if( (!track->GetFilterMap()) && (!track->GetTPCNcls()) ){
return;
}
// Imagine the other way around, the zero map zero clusters track
// is stored and the good one wants to be added. We ommit the warning
// and just overwrite the 'bad' track
if( fGTI[trackID]->GetFilterMap() || fGTI[trackID]->GetTPCNcls() ){
// If we come here, there's a problem
printf("Warning! global track info already there!");
printf(" TPCNcls track1 %u track2 %u",
(fGTI[trackID])->GetTPCNcls(),track->GetTPCNcls());
printf(" FilterMap track1 %u track2 %u\n",
(fGTI[trackID])->GetFilterMap(),track->GetFilterMap());
}
} // Two tracks same id
// // There are tracks with filter bit 0,
// // do they have TPCNcls stored?
// if(!track->GetFilterMap()){
// printf("Filter map is zero, TPCNcls: %u\n"
// ,track->GetTPCNcls());
// }
// Assign the pointer
(fGTI[trackID]) = track;
}
void AliFemtoDreamAnalysis::Make(AliAODEvent *evt) {
if (!evt) {
AliFatal("No Input Event");
}
fEvent->SetEvent(evt);
if (!fEvtCuts->isSelected(fEvent)) {
return;
}
ResetGlobalTrackReference();
for(int iTrack = 0;iTrack<evt->GetNumberOfTracks();++iTrack){
AliAODTrack *track=static_cast<AliAODTrack*>(evt->GetTrack(iTrack));
if (!track) {
AliFatal("No Standard AOD");
return;
}
StoreGlobalTrackReference(track);
}
std::vector<AliFemtoDreamBasePart> Particles;
std::vector<AliFemtoDreamBasePart> AntiParticles;
fFemtoTrack->SetGlobalTrackInfo(fGTI,fTrackBufferSize);
for (int iTrack = 0;iTrack<evt->GetNumberOfTracks();++iTrack) {
AliAODTrack *track=static_cast<AliAODTrack*>(evt->GetTrack(iTrack));
if (!track) {
AliFatal("No Standard AOD");
return;
}
fFemtoTrack->SetTrack(track);
if (fTrackCuts->isSelected(fFemtoTrack)) {
Particles.push_back(*fFemtoTrack);
}
if (fAntiTrackCuts->isSelected(fFemtoTrack)) {
AntiParticles.push_back(*fFemtoTrack);
}
}
std::vector<AliFemtoDreamBasePart> Decays;
std::vector<AliFemtoDreamBasePart> AntiDecays;
// Look for the lambda, store it in an event
// Get a V0 from the event:
TClonesArray *v01 = static_cast<TClonesArray*>(evt->GetV0s());
//number of V0s:
fFemtov0->SetGlobalTrackInfo(fGTI,fTrackBufferSize);
int entriesV0= v01->GetEntriesFast();
for (int iv0=0; iv0<entriesV0; iv0++) {
AliAODv0 *v0 = evt->GetV0(iv0);
fFemtov0->Setv0(evt, v0);
if (fv0Cuts->isSelected(fFemtov0)) {
Decays.push_back(*fFemtov0);
}
if (fAntiv0Cuts->isSelected(fFemtov0)) {
AntiDecays.push_back(*fFemtov0);
}
}
std::vector<AliFemtoDreamBasePart> XiDecays;
std::vector<AliFemtoDreamBasePart> AntiXiDecays;
int numcascades = evt->GetNumberOfCascades();
for (int iXi=0;iXi<numcascades;++iXi) {
AliAODcascade *xi = evt->GetCascade(iXi);
if (!xi) continue;
fFemtoCasc->SetCascade(evt,xi);
if (fCascCuts->isSelected(fFemtoCasc)) {
XiDecays.push_back(*fFemtoCasc);
}
if (fAntiCascCuts->isSelected(fFemtoCasc)) {
AntiXiDecays.push_back(*fFemtoCasc);
}
}
fPairCleaner->ResetArray();
fPairCleaner->CleanTrackAndDecay(&Particles,&Decays,0);
fPairCleaner->CleanTrackAndDecay(&Particles,&XiDecays,2);
fPairCleaner->CleanTrackAndDecay(&AntiParticles,&AntiDecays,1);
fPairCleaner->CleanTrackAndDecay(&AntiParticles,&AntiXiDecays,3);
fPairCleaner->CleanDecay(&Decays,0);
fPairCleaner->CleanDecay(&AntiDecays,1);
fPairCleaner->CleanDecay(&XiDecays,2);
fPairCleaner->CleanDecay(&AntiXiDecays,3);
fPairCleaner->StoreParticle(Particles);
fPairCleaner->StoreParticle(AntiParticles);
fPairCleaner->StoreParticle(Decays);
fPairCleaner->StoreParticle(AntiDecays);
fPairCleaner->StoreParticle(XiDecays);
fPairCleaner->StoreParticle(AntiXiDecays);
if (fConfig->GetUseEventMixing()) {
fPartColl->SetEvent(
fPairCleaner->GetCleanParticles(),fEvent->GetZVertex(),
fEvent->GetMultiplicity(),fEvent->GetV0MCentrality());
}
if (fConfig->GetUsePhiSpinning()) {
fControlSample->SetEvent(
fPairCleaner->GetCleanParticles(), fEvent->GetMultiplicity());
}
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"
#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"
#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX)
void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
Display* XOpenDisplay(int num){return NULL;};
void XCloseDisplay(Display* nativeDisplayType){};
Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
const char * XDisplayName(char * name){return 0;};
Visual * DefaultVisual(Display* nativeDisplayType, int screen){return 0;};
int XVisualIDFromVisual(Visual *v){return 0;};
void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
XVisualInfo * XGetVisualInfo(Display* nativeDisplayType, int mask, XVisualInfo * info, int * n){return 0;};
typedef int (*XErrorHandler)(Display *, XErrorEvent*);
XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
void XFree(void *data){};
XWMHints * XAllocWMHints(){return 0;};
XSizeHints * XAllocSizeHints(){return 0;};
void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
void XFlush(Display* nativeDisplayType){};
void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif
namespace Ogre {
X11EGLSupport::X11EGLSupport()
{
mNativeDisplay = getNativeDisplay();
mGLDisplay = getGLDisplay();
int dummy;
// TODO: Probe video modes
mCurrentMode.first.first = 1280;
mCurrentMode.first.second = 1024;
// mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
// mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
mCurrentMode.second = 0;
mOriginalMode = mCurrentMode;
mVideoModes.push_back(mCurrentMode);
EGLConfig *glConfigs;
int config, nConfigs = 0;
glConfigs = chooseGLConfig(NULL, &nConfigs);
for (config = 0; config < nConfigs; config++)
{
int caveat, samples;
getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);
if (caveat != EGL_SLOW_CONFIG)
{
getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
mSampleLevels.push_back(StringConverter::toString(samples));
}
}
free(glConfigs);
removeDuplicates(mSampleLevels);
}
X11EGLSupport::~X11EGLSupport()
{
if (mNativeDisplay)
{
XCloseDisplay((Display*)mNativeDisplay);
}
if (mGLDisplay)
{
eglTerminate(mGLDisplay);
}
}
NativeDisplayType X11EGLSupport::getNativeDisplay()
{
if (!mNativeDisplay)
{
mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);
if (!mNativeDisplay)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Couldn`t open X display",
"X11EGLSupport::getXDisplay");
}
mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
}
return mNativeDisplay;
}
String X11EGLSupport::getDisplayName(void)
{
return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
}
void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
{
// if (!mRandr)
// return;
int size = 0;
int newSize = -1;
VideoModes::iterator mode;
VideoModes::iterator end = mVideoModes.end();
VideoMode *newMode = 0;
for(mode = mVideoModes.begin(); mode != end; size++)
{
if (mode->first.first >= static_cast<int>(width) &&
mode->first.second >= static_cast<int>(height))
{
if (!newMode ||
mode->first.first < newMode->first.first ||
mode->first.second < newMode->first.second)
{
newSize = size;
newMode = &(*mode);
}
}
VideoMode* lastMode = &(*mode);
while (++mode != end && mode->first == lastMode->first)
{
if (lastMode == newMode && mode->second == frequency)
{
newMode = &(*mode);
}
}
}
if (newMode && *newMode != mCurrentMode)
{
XWindowAttributes winAtt;
newMode->first.first = DisplayWidth(mNativeDisplay, 0);
newMode->first.second = DisplayHeight(mNativeDisplay, 0);
newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
mCurrentMode = *newMode;
}
}
XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
{
XVisualInfo *vi, tmp;
int vid, n;
::EGLDisplay glDisplay;
glDisplay = getGLDisplay();
mNativeDisplay = getNativeDisplay();
if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Fail to get VISUAL_ID from glConfig",
__FUNCTION__);
return 0;
}
EGL_CHECK_ERROR
if (vid == 0)
{
const int screen_number = DefaultScreen(mNativeDisplay);
Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
vid = XVisualIDFromVisual(v);
}
tmp.visualid = vid;
vi = 0;
vi = XGetVisualInfo((Display*)mNativeDisplay,
VisualIDMask,
&tmp, &n);
if (vi == 0)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Fail to get X11 VISUAL",
__FUNCTION__);
return 0;
}
return vi;
}
RenderWindow* X11EGLSupport::newWindow(const String &name,
unsigned int width, unsigned int height,
bool fullScreen,
const NameValuePairList *miscParams)
{
EGLWindow* window = new X11EGLWindow(this);
window->create(name, width, height, fullScreen, miscParams);
return window;
}
//X11EGLSupport::getGLDisplay sets up the native variable
//then calls EGLSupport::getGLDisplay
EGLDisplay X11EGLSupport::getGLDisplay()
{
if (!mGLDisplay)
{
if(!mNativeDisplay)
mNativeDisplay = getNativeDisplay();
return EGLSupport::getGLDisplay();
}
return mGLDisplay;
}
}
<commit_msg>GLES2: Forgot this file in last commit<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"
#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"
#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX) && (OGRE_PLATFORM != OGRE_PLATFORM_TEGRA2)
void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
Display* XOpenDisplay(int num){return NULL;};
void XCloseDisplay(Display* nativeDisplayType){};
Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
const char * XDisplayName(char * name){return 0;};
Visual * DefaultVisual(Display* nativeDisplayType, int screen){return 0;};
int XVisualIDFromVisual(Visual *v){return 0;};
void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
XVisualInfo * XGetVisualInfo(Display* nativeDisplayType, int mask, XVisualInfo * info, int * n){return 0;};
typedef int (*XErrorHandler)(Display *, XErrorEvent*);
XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
void XFree(void *data){};
XWMHints * XAllocWMHints(){return 0;};
XSizeHints * XAllocSizeHints(){return 0;};
void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
void XFlush(Display* nativeDisplayType){};
void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif
namespace Ogre {
X11EGLSupport::X11EGLSupport()
{
// A connection that might be shared with the application for GL rendering:
mGLDisplay = getGLDisplay();
// A connection that is NOT shared to enable independent event processing:
mNativeDisplay = getNativeDisplay();
int dummy = 0;
// TODO: Probe video modes
mCurrentMode.first.first = 1280;
mCurrentMode.first.second = 1024;
// mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
// mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
mCurrentMode.second = 0;
mOriginalMode = mCurrentMode;
mVideoModes.push_back(mCurrentMode);
EGLConfig *glConfigs;
int config, nConfigs = 0;
glConfigs = chooseGLConfig(NULL, &nConfigs);
for (config = 0; config < nConfigs; config++)
{
int caveat, samples;
getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);
if (caveat != EGL_SLOW_CONFIG)
{
getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
mSampleLevels.push_back(StringConverter::toString(samples));
}
}
free(glConfigs);
removeDuplicates(mSampleLevels);
}
X11EGLSupport::~X11EGLSupport()
{
if (mNativeDisplay)
{
XCloseDisplay((Display*)mNativeDisplay);
}
if (mGLDisplay)
{
eglTerminate(mGLDisplay);
}
}
NativeDisplayType X11EGLSupport::getNativeDisplay()
{
if (!mNativeDisplay)
{
mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);
if (!mNativeDisplay)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Couldn`t open X display",
"X11EGLSupport::getXDisplay");
}
mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
}
return mNativeDisplay;
}
String X11EGLSupport::getDisplayName(void)
{
return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
}
void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
{
// if (!mRandr)
// return;
int size = 0;
int newSize = -1;
VideoModes::iterator mode;
VideoModes::iterator end = mVideoModes.end();
VideoMode *newMode = 0;
for(mode = mVideoModes.begin(); mode != end; size++)
{
if (mode->first.first >= static_cast<int>(width) &&
mode->first.second >= static_cast<int>(height))
{
if (!newMode ||
mode->first.first < newMode->first.first ||
mode->first.second < newMode->first.second)
{
newSize = size;
newMode = &(*mode);
}
}
VideoMode* lastMode = &(*mode);
while (++mode != end && mode->first == lastMode->first)
{
if (lastMode == newMode && mode->second == frequency)
{
newMode = &(*mode);
}
}
}
if (newMode && *newMode != mCurrentMode)
{
XWindowAttributes winAtt;
newMode->first.first = DisplayWidth(mNativeDisplay, 0);
newMode->first.second = DisplayHeight(mNativeDisplay, 0);
newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
mCurrentMode = *newMode;
}
}
XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
{
XVisualInfo *vi, tmp;
int vid, n;
::EGLDisplay glDisplay;
glDisplay = getGLDisplay();
mNativeDisplay = getNativeDisplay();
if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Fail to get VISUAL_ID from glConfig",
__FUNCTION__);
return 0;
}
EGL_CHECK_ERROR
if (vid == 0)
{
const int screen_number = DefaultScreen(mNativeDisplay);
Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
vid = XVisualIDFromVisual(v);
}
tmp.visualid = vid;
vi = 0;
vi = XGetVisualInfo((Display*)mNativeDisplay,
VisualIDMask,
&tmp, &n);
if (vi == 0)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Fail to get X11 VISUAL",
__FUNCTION__);
return 0;
}
return vi;
}
RenderWindow* X11EGLSupport::newWindow(const String &name,
unsigned int width, unsigned int height,
bool fullScreen,
const NameValuePairList *miscParams)
{
EGLWindow* window = new X11EGLWindow(this);
window->create(name, width, height, fullScreen, miscParams);
return window;
}
//X11EGLSupport::getGLDisplay sets up the native variable
//then calls EGLSupport::getGLDisplay
EGLDisplay X11EGLSupport::getGLDisplay()
{
if (!mGLDisplay)
{
if(!mNativeDisplay)
mNativeDisplay = getNativeDisplay();
return EGLSupport::getGLDisplay();
}
return mGLDisplay;
}
}
<|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"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}
<commit_msg>Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout<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"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}
// Disabled, flakily exceeds timeout, http://crbug.com/72165.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}
<|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/geolocation/access_token_store.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// The token store factory implementation expects to be used from any well-known
// chrome thread other than UI. We could use any arbitrary thread; IO is
// a good choice as this is the expected usage.
const ChromeThread::ID kExpectedClientThreadId = ChromeThread::IO;
const char* kRefServerUrl1 = "https://test.domain.example/foo?id=bar.bar";
const char* kRefServerUrl2 = "http://another.domain.example/foo?id=bar.bar#2";
} // namespace
class GeolocationAccessTokenStoreTest
: public InProcessBrowserTest,
public AccessTokenStoreFactory::Delegate,
public base::SupportsWeakPtr<GeolocationAccessTokenStoreTest> {
protected:
GeolocationAccessTokenStoreTest()
: token_to_expect_(NULL), token_to_set_(NULL) {}
void StartThreadAndWaitForResults(
const char* ref_url, const string16* token_to_expect,
const string16* token_to_set);
// AccessTokenStoreFactory::Delegate
virtual void OnAccessTokenStoresCreated(
const AccessTokenStoreFactory::TokenStoreSet& access_token_store);
GURL ref_url_;
const string16* token_to_expect_;
const string16* token_to_set_;
};
namespace {
// A WeakPtr may only be used on the thread in which it is created, hence we
// defer the call to delegate->AsWeakPtr() into this function rather than pass
// WeakPtr& in.
void StartTestFromClientThread(
GeolocationAccessTokenStoreTest* delegate,
const GURL& ref_url) {
ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId));
scoped_refptr<AccessTokenStoreFactory> store =
NewChromePrefsAccessTokenStoreFactory();
store->CreateAccessTokenStores(delegate->AsWeakPtr(), ref_url);
}
} // namespace
void GeolocationAccessTokenStoreTest::StartThreadAndWaitForResults(
const char* ref_url, const string16* token_to_expect,
const string16* token_to_set) {
ref_url_ = GURL(ref_url);
token_to_expect_ = token_to_expect;
token_to_set_ = token_to_set;
ChromeThread::PostTask(
kExpectedClientThreadId, FROM_HERE, NewRunnableFunction(
&StartTestFromClientThread, this, ref_url_));
ui_test_utils::RunMessageLoop();
}
void GeolocationAccessTokenStoreTest::OnAccessTokenStoresCreated(
const AccessTokenStoreFactory::TokenStoreSet& access_token_store) {
ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId))
<< "Callback from token factory should be from the same thread as the "
"CreateAccessTokenStores request was made on";
EXPECT_TRUE(token_to_set_ || token_to_expect_) << "No work to do?";
DCHECK_GE(access_token_store.size(), size_t(1));
AccessTokenStoreFactory::TokenStoreSet::const_iterator item =
access_token_store.find(ref_url_);
ASSERT_TRUE(item != access_token_store.end());
scoped_refptr<AccessTokenStore> store = item->second;
ASSERT_TRUE(NULL != store);
string16 token;
bool read_ok = store->GetAccessToken(&token);
if (!token_to_expect_) {
EXPECT_FALSE(read_ok);
EXPECT_TRUE(token.empty());
} else {
ASSERT_TRUE(read_ok);
EXPECT_EQ(*token_to_expect_, token);
}
if (token_to_set_) {
store->SetAccessToken(*token_to_set_);
}
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new MessageLoop::QuitTask);
}
#if defined(OS_LINUX)
// TODO(joth): http://crbug.com/36068 crashes on Linux.
#define MAYBE_SetAcrossInstances DISABLED_SetAcrossInstances
#else
#define MAYBE_SetAcrossInstances SetAcrossInstances
#endif
IN_PROC_BROWSER_TEST_F(GeolocationAccessTokenStoreTest, MAYBE_SetAcrossInstances) {
const string16 ref_token1 = ASCIIToUTF16("jksdfo90,'s#\"#1*(");
const string16 ref_token2 = ASCIIToUTF16("\1\2\3\4\5\6\7\10\11\12=023");
ASSERT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
StartThreadAndWaitForResults(kRefServerUrl1, NULL, &ref_token1);
// Check it was set, and change to new value.
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, &ref_token2);
// And change back.
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token2, &ref_token1);
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
// Set a second server URL
StartThreadAndWaitForResults(kRefServerUrl2, NULL, &ref_token2);
StartThreadAndWaitForResults(kRefServerUrl2, &ref_token2, NULL);
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
}
<commit_msg>Test SetAcrossInstances crashed on Mac also. Disabling.<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/geolocation/access_token_store.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// The token store factory implementation expects to be used from any well-known
// chrome thread other than UI. We could use any arbitrary thread; IO is
// a good choice as this is the expected usage.
const ChromeThread::ID kExpectedClientThreadId = ChromeThread::IO;
const char* kRefServerUrl1 = "https://test.domain.example/foo?id=bar.bar";
const char* kRefServerUrl2 = "http://another.domain.example/foo?id=bar.bar#2";
} // namespace
class GeolocationAccessTokenStoreTest
: public InProcessBrowserTest,
public AccessTokenStoreFactory::Delegate,
public base::SupportsWeakPtr<GeolocationAccessTokenStoreTest> {
protected:
GeolocationAccessTokenStoreTest()
: token_to_expect_(NULL), token_to_set_(NULL) {}
void StartThreadAndWaitForResults(
const char* ref_url, const string16* token_to_expect,
const string16* token_to_set);
// AccessTokenStoreFactory::Delegate
virtual void OnAccessTokenStoresCreated(
const AccessTokenStoreFactory::TokenStoreSet& access_token_store);
GURL ref_url_;
const string16* token_to_expect_;
const string16* token_to_set_;
};
namespace {
// A WeakPtr may only be used on the thread in which it is created, hence we
// defer the call to delegate->AsWeakPtr() into this function rather than pass
// WeakPtr& in.
void StartTestFromClientThread(
GeolocationAccessTokenStoreTest* delegate,
const GURL& ref_url) {
ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId));
scoped_refptr<AccessTokenStoreFactory> store =
NewChromePrefsAccessTokenStoreFactory();
store->CreateAccessTokenStores(delegate->AsWeakPtr(), ref_url);
}
} // namespace
void GeolocationAccessTokenStoreTest::StartThreadAndWaitForResults(
const char* ref_url, const string16* token_to_expect,
const string16* token_to_set) {
ref_url_ = GURL(ref_url);
token_to_expect_ = token_to_expect;
token_to_set_ = token_to_set;
ChromeThread::PostTask(
kExpectedClientThreadId, FROM_HERE, NewRunnableFunction(
&StartTestFromClientThread, this, ref_url_));
ui_test_utils::RunMessageLoop();
}
void GeolocationAccessTokenStoreTest::OnAccessTokenStoresCreated(
const AccessTokenStoreFactory::TokenStoreSet& access_token_store) {
ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId))
<< "Callback from token factory should be from the same thread as the "
"CreateAccessTokenStores request was made on";
EXPECT_TRUE(token_to_set_ || token_to_expect_) << "No work to do?";
DCHECK_GE(access_token_store.size(), size_t(1));
AccessTokenStoreFactory::TokenStoreSet::const_iterator item =
access_token_store.find(ref_url_);
ASSERT_TRUE(item != access_token_store.end());
scoped_refptr<AccessTokenStore> store = item->second;
ASSERT_TRUE(NULL != store);
string16 token;
bool read_ok = store->GetAccessToken(&token);
if (!token_to_expect_) {
EXPECT_FALSE(read_ok);
EXPECT_TRUE(token.empty());
} else {
ASSERT_TRUE(read_ok);
EXPECT_EQ(*token_to_expect_, token);
}
if (token_to_set_) {
store->SetAccessToken(*token_to_set_);
}
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new MessageLoop::QuitTask);
}
#if !defined(OS_WIN)
// TODO(joth): Crashes on Linux and Mac. See http://crbug.com/36068.
#define MAYBE_SetAcrossInstances DISABLED_SetAcrossInstances
#else
#define MAYBE_SetAcrossInstances SetAcrossInstances
#endif
IN_PROC_BROWSER_TEST_F(GeolocationAccessTokenStoreTest, MAYBE_SetAcrossInstances) {
const string16 ref_token1 = ASCIIToUTF16("jksdfo90,'s#\"#1*(");
const string16 ref_token2 = ASCIIToUTF16("\1\2\3\4\5\6\7\10\11\12=023");
ASSERT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
StartThreadAndWaitForResults(kRefServerUrl1, NULL, &ref_token1);
// Check it was set, and change to new value.
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, &ref_token2);
// And change back.
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token2, &ref_token1);
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
// Set a second server URL
StartThreadAndWaitForResults(kRefServerUrl2, NULL, &ref_token2);
StartThreadAndWaitForResults(kRefServerUrl2, &ref_token2, NULL);
StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/drag_util.h"
#include "ui/aura/window.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/file_info.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/public/drag_drop_client.h"
namespace atom {
void DragFileItems(const std::vector<base::FilePath>& files,
const gfx::Image& icon,
gfx::NativeView view) {
// Set up our OLE machinery
ui::OSExchangeData data;
drag_utils::CreateDragImageForFile(files[0], icon.AsImageSkia(), &data);
std::vector<ui::FileInfo> file_infos;
for (const base::FilePath& file : files) {
file_infos.push_back(ui::FileInfo(file, base::FilePath()));
}
data.SetFilenames(file_infos);
aura::Window* root_window = view->GetRootWindow();
if (!root_window || !aura::client::GetDragDropClient(root_window))
return;
gfx::Point location = display::Screen::GetScreen()->GetCursorScreenPoint();
// TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
aura::client::GetDragDropClient(root_window)->StartDragAndDrop(
data,
root_window,
view,
location,
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK,
ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
}
} // namespace atom
<commit_msg>Apply changes to "Wires up drag/drop for aura-mus" https://chromium.googlesource.com/chromium/src.git/+/d509d739efec6c000cea40aae5e24f8b432cf3d5<commit_after>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/drag_util.h"
#include "ui/aura/window.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/file_info.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/widget/widget.h"
#include "ui/aura/client/drag_drop_client.h"
namespace atom {
void DragFileItems(const std::vector<base::FilePath>& files,
const gfx::Image& icon,
gfx::NativeView view) {
// Set up our OLE machinery
ui::OSExchangeData data;
drag_utils::CreateDragImageForFile(files[0], icon.AsImageSkia(), &data);
std::vector<ui::FileInfo> file_infos;
for (const base::FilePath& file : files) {
file_infos.push_back(ui::FileInfo(file, base::FilePath()));
}
data.SetFilenames(file_infos);
aura::Window* root_window = view->GetRootWindow();
if (!root_window || !aura::client::GetDragDropClient(root_window))
return;
gfx::Point location = display::Screen::GetScreen()->GetCursorScreenPoint();
// TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
aura::client::GetDragDropClient(root_window)->StartDragAndDrop(
data,
root_window,
view,
location,
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK,
ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
}
} // namespace atom
<|endoftext|>
|
<commit_before>#include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#include "evpp/sockets.h"
namespace evpp {
std::string strerror(int e) {
#ifdef H_OS_WINDOWS
LPVOID buf = NULL;
::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
if (buf) {
std::string s = (char*)buf;
LocalFree(buf);
return s;
}
return std::string();
#else
char buf[1024] = {};
return std::string(strerror_r(e, buf, sizeof buf));
#endif
}
namespace sock {
int CreateNonblockingSocket() {
int serrno = 0;
//int on = 1;
/* Create listen socket */
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
serrno = errno;
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
SetKeepAlive(fd);
SetReuseAddr(fd);
return fd;
out:
EVUTIL_CLOSESOCKET(fd);
return INVALID_SOCKET;
}
int CreateUDPServer(int port) {
int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
int serrno = errno;
LOG_ERROR << "socket error " << strerror(serrno);
return INVALID_SOCKET;
}
SetReuseAddr(fd);
std::string addr = std::string("0.0.0.0:") + std::to_string(port);
struct sockaddr_in local = ParseFromIPPort(addr.c_str());
if (::bind(fd, (struct sockaddr*)&local, sizeof(local))) {
int serrno = errno;
LOG_ERROR << "socket bind error " << strerror(serrno);
return INVALID_SOCKET;
}
return fd;
}
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_WARN << "ParseFromIPPort inet_pton(AF_INET, '" << a.data() << "', ...) failed : " << 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()) {
saddr.append(":", 1).append(std::to_string(port));
}
return saddr;
}
std::string ToIPPort(const struct sockaddr* ss) {
return ToIPPort(sockaddr_storage_cast(ss));
}
std::string ToIPPort(const struct sockaddr_in* ss) {
return ToIPPort(sockaddr_storage_cast(ss));
}
EVPP_EXPORT std::string ToIP(const struct sockaddr* s) {
auto ss = sockaddr_storage_cast(s);
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) {
return std::string(addr);
}
} 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) {
return std::string(addr);
}
} else {
LOG_ERROR << "unknown socket family connected";
}
return std::string();
}
void SetTimeout(int fd, uint32_t timeout_ms) {
#ifdef H_OS_WINDOWS
DWORD tv = timeout_ms;
#else
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
#endif
int ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
assert(ret == 0);
if (ret != 0) {
int err = errno;
LOG_ERROR << "setsockopt SO_RCVTIMEO ERROR " << err << strerror(err);
}
}
void SetKeepAlive(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
assert(rc == 0);
(void)rc; // avoid compile warning
}
void SetReuseAddr(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
assert(rc == 0);
(void)rc; // avoid compile warning
}
}
}
#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>Fix conflicts<commit_after>#include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#include "evpp/sockets.h"
namespace evpp {
std::string strerror(int e) {
#ifdef H_OS_WINDOWS
LPVOID buf = NULL;
::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
if (buf) {
std::string s = (char*)buf;
LocalFree(buf);
return s;
}
return std::string();
#else
char buf[1024] = {};
return std::string(strerror_r(e, buf, sizeof buf));
#endif
}
namespace sock {
int CreateNonblockingSocket() {
int serrno = 0;
//int on = 1;
/* Create listen socket */
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
serrno = errno;
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
SetKeepAlive(fd);
SetReuseAddr(fd);
return fd;
out:
EVUTIL_CLOSESOCKET(fd);
return INVALID_SOCKET;
}
int CreateUDPServer(int port) {
int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
int serrno = errno;
LOG_ERROR << "socket error " << strerror(serrno);
return INVALID_SOCKET;
}
SetReuseAddr(fd);
std::string addr = std::string("0.0.0.0:") + std::to_string(port);
struct sockaddr_in local = ParseFromIPPort(addr.c_str());
if (::bind(fd, (struct sockaddr*)&local, sizeof(local))) {
int serrno = errno;
LOG_ERROR << "socket bind error " << strerror(serrno);
return INVALID_SOCKET;
}
return fd;
}
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';
int rc = ::inet_pton(AF_INET, a.data(), &addr.sin_addr);
if (rc == 0) {
LOG_INFO << "ParseFromIPPort inet_pton(AF_INET '" << a.data() << "', ...) rc=0. " << a.data() << " is not a valid IP address. Maybe it is a hostname.";
} else if (rc < 0) {
int serrno = errno;
if (serrno == 0) {
LOG_INFO << "[" << a.data() << "] is not a IP address. Maybe it is a hostname.";
} else {
LOG_WARN << "ParseFromIPPort inet_pton(AF_INET, '" << a.data() << "', ...) failed : " << 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()) {
saddr.append(":", 1).append(std::to_string(port));
}
return saddr;
}
std::string ToIPPort(const struct sockaddr* ss) {
return ToIPPort(sockaddr_storage_cast(ss));
}
std::string ToIPPort(const struct sockaddr_in* ss) {
return ToIPPort(sockaddr_storage_cast(ss));
}
EVPP_EXPORT std::string ToIP(const struct sockaddr* s) {
auto ss = sockaddr_storage_cast(s);
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) {
return std::string(addr);
}
} 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) {
return std::string(addr);
}
} else {
LOG_ERROR << "unknown socket family connected";
}
return std::string();
}
void SetTimeout(int fd, uint32_t timeout_ms) {
#ifdef H_OS_WINDOWS
DWORD tv = timeout_ms;
#else
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
#endif
int ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
assert(ret == 0);
if (ret != 0) {
int err = errno;
LOG_ERROR << "setsockopt SO_RCVTIMEO ERROR " << err << strerror(err);
}
}
void SetKeepAlive(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
assert(rc == 0);
(void)rc; // avoid compile warning
}
void SetReuseAddr(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
assert(rc == 0);
(void)rc; // avoid compile warning
}
}
}
#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>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: c_slots.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:33:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ARY_CPP_C_SLOTS_HXX
#define ARY_CPP_C_SLOTS_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/ceslot.hxx>
// COMPONENTS
#include <ary/cpp/c_idlist.hxx>
// PARAMETERS
namespace ary
{
namespace cpp
{
class Slot_SubNamespaces : public ary::Slot
{
public:
Slot_SubNamespaces(
const Map_NamespacePtr &
i_rData );
virtual ~Slot_SubNamespaces();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const Map_NamespacePtr *
pData;
};
class Slot_BaseClass : public ary::Slot
{
public:
Slot_BaseClass(
const List_Bases & i_rData );
virtual ~Slot_BaseClass();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const List_Bases * pData;
};
} // namespace cpp
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS adc18 (1.2.56); FILE MERGED 2007/10/18 13:27:01 np 1.2.56.1: #i81775#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: c_slots.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-11-02 15:27:28 $
*
* 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 ARY_CPP_C_SLOTS_HXX
#define ARY_CPP_C_SLOTS_HXX
// BASE CLASSES
#include <ary/ceslot.hxx>
// USED SERVICES
#include <ary/cpp/c_slntry.hxx>
namespace ary
{
namespace cpp
{
class Slot_SubNamespaces : public ary::Slot
{
public:
Slot_SubNamespaces(
const Map_NamespacePtr &
i_rData );
virtual ~Slot_SubNamespaces();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const Map_NamespacePtr *
pData;
};
class Slot_BaseClass : public ary::Slot
{
public:
Slot_BaseClass(
const List_Bases & i_rData );
virtual ~Slot_BaseClass();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const List_Bases * pData;
};
} // namespace cpp
} // namespace ary
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ca_type.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:34:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include <ary/cpp/ca_type.hxx>
// NOT FULLY DEFINED SERVICES
namespace ary
{
namespace cpp
{
//********************** Type **************************//
Rid
Type::inq_RelatedCe() const
{
return 0;
}
//********************** BuiltInType **************************//
BuiltInType::BuiltInType( Tid i_nId,
const udmstri & i_sName,
E_TypeSpecialisation i_eSpecialisation )
: nId( i_nId ),
sName( i_sName ),
eSpecialisation( i_eSpecialisation )
{
}
Tid
BuiltInType::inq_Id_Type() const
{
return nId;
}
bool
BuiltInType::inq_IsConst() const
{
return false;
}
void
BuiltInType::inq_Get_Text( StreamStr & o_rPreName,
StreamStr & o_rName,
StreamStr & o_rPostName,
const DisplayGate & i_rGate ) const
{
switch (eSpecialisation)
{
case TYSP_unsigned: o_rName << "unsigned "; break;
case TYSP_signed: o_rName << "signed "; break;
default: // Does nothing.
;
}
o_rName << sName;
}
//********************** NullType **************************//
Tid
NullType::inq_Id_Type() const
{
return 0;
}
bool
NullType::inq_IsConst() const
{
return false;
}
void
NullType::inq_Get_Text( StreamStr & o_rPreName,
StreamStr & o_rName,
StreamStr & o_rPostName,
const DisplayGate & i_rGate ) const
{
}
#if 0
void
NamedType::GetText( StreamStr & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_QualifiedName(o_rOut, Name(), "::");
}
BuiltInType::BuiltInType( const S_InitData & i_rData )
: nId(i_rData.nId),
aName(i_rData.aName)
{
}
Tid
BuiltInType::IdAsType() const
{
return nId;
}
const QName &
BuiltInType::Name() const
{
return aName;
}
#if 0
PredeclaredType::PredeclaredType( Tid i_nId,
const char * i_sName,
Cid i_nOwner )
: nId(i_nId),
aName(i_sName,i_nOwner)
{
}
Tid
PredeclaredType::IdAsType() const
{
return nId;
}
const QName &
PredeclaredType::Name() const
{
return aName;
}
#endif // 0
Tid
ReferingType::IdAsType() const
{
return nId;
}
Tid
ReferingType::ReferedType() const
{
return nReferedType;
}
ReferingType::ReferingType( Tid i_nId,
Tid i_nReferedType )
: nId(i_nId),
nReferedType(i_nReferedType)
{
}
ConstType::ConstType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
ConstType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " const";
}
VolatileType::VolatileType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
VolatileType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " volatile";
}
PtrType::PtrType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
PtrType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " *";
}
RefType::RefType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
RefType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " &";
}
TemplateInstance::TemplateInstance( Tid i_nId,
Cid i_nReferedClass,
const char * i_sInstantiation )
: nId(i_nId),
nReferedClass(i_nReferedClass),
sInstantiation(i_sInstantiation)
{
}
bool
TemplateInstance::operator<( const TemplateInstance & i_r ) const
{
if ( nReferedClass < i_r.nReferedClass )
return true;
if ( nReferedClass == i_r.nReferedClass
AND sInstantiation < i_r.sInstantiation )
return true;
return false;
}
Tid
TemplateInstance::IdAsType() const
{
return nId;
}
void
TemplateInstance::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,nReferedClass);
o_rOut << "< " << sInstantiation << " >";
}
#endif // 0
} // namespace cpp
} // namespace ary
<commit_msg>INTEGRATION: CWS warnings01 (1.3.4); FILE MERGED 2005/10/18 08:35:41 np 1.3.4.1: #i53898#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ca_type.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:49:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include <ary/cpp/ca_type.hxx>
// NOT FULLY DEFINED SERVICES
namespace ary
{
namespace cpp
{
//********************** Type **************************//
Rid
Type::inq_RelatedCe() const
{
return 0;
}
//********************** BuiltInType **************************//
BuiltInType::BuiltInType( Tid i_nId,
const udmstri & i_sName,
E_TypeSpecialisation i_eSpecialisation )
: nId( i_nId ),
sName( i_sName ),
eSpecialisation( i_eSpecialisation )
{
}
Tid
BuiltInType::inq_Id_Type() const
{
return nId;
}
bool
BuiltInType::inq_IsConst() const
{
return false;
}
void
BuiltInType::inq_Get_Text( StreamStr & ,
StreamStr & o_rName,
StreamStr & ,
const DisplayGate & ) const
{
switch (eSpecialisation)
{
case TYSP_unsigned: o_rName << "unsigned "; break;
case TYSP_signed: o_rName << "signed "; break;
default: // Does nothing.
;
}
o_rName << sName;
}
//********************** NullType **************************//
Tid
NullType::inq_Id_Type() const
{
return 0;
}
bool
NullType::inq_IsConst() const
{
return false;
}
void
NullType::inq_Get_Text( StreamStr & ,
StreamStr & ,
StreamStr & ,
const DisplayGate & ) const
{
}
#if 0
void
NamedType::GetText( StreamStr & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_QualifiedName(o_rOut, Name(), "::");
}
BuiltInType::BuiltInType( const S_InitData & i_rData )
: nId(i_rData.nId),
aName(i_rData.aName)
{
}
Tid
BuiltInType::IdAsType() const
{
return nId;
}
const QName &
BuiltInType::Name() const
{
return aName;
}
#if 0
PredeclaredType::PredeclaredType( Tid i_nId,
const char * i_sName,
Cid i_nOwner )
: nId(i_nId),
aName(i_sName,i_nOwner)
{
}
Tid
PredeclaredType::IdAsType() const
{
return nId;
}
const QName &
PredeclaredType::Name() const
{
return aName;
}
#endif // 0
Tid
ReferingType::IdAsType() const
{
return nId;
}
Tid
ReferingType::ReferedType() const
{
return nReferedType;
}
ReferingType::ReferingType( Tid i_nId,
Tid i_nReferedType )
: nId(i_nId),
nReferedType(i_nReferedType)
{
}
ConstType::ConstType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
ConstType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " const";
}
VolatileType::VolatileType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
VolatileType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " volatile";
}
PtrType::PtrType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
PtrType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " *";
}
RefType::RefType( Tid nId,
Tid nReferedType )
: ReferingType(nId, nReferedType)
{
}
void
RefType::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,ReferedType());
o_rOut << " &";
}
TemplateInstance::TemplateInstance( Tid i_nId,
Cid i_nReferedClass,
const char * i_sInstantiation )
: nId(i_nId),
nReferedClass(i_nReferedClass),
sInstantiation(i_sInstantiation)
{
}
bool
TemplateInstance::operator<( const TemplateInstance & i_r ) const
{
if ( nReferedClass < i_r.nReferedClass )
return true;
if ( nReferedClass == i_r.nReferedClass
AND sInstantiation < i_r.sInstantiation )
return true;
return false;
}
Tid
TemplateInstance::IdAsType() const
{
return nId;
}
void
TemplateInstance::GetText( ostream & o_rOut,
const Gate & i_rGate ) const
{
i_rGate.Get_TypeText(o_rOut,nReferedClass);
o_rOut << "< " << sInstantiation << " >";
}
#endif // 0
} // namespace cpp
} // namespace ary
<|endoftext|>
|
<commit_before>#include "BaseScene.h"
#include "../Context.h"
#include "../Input/InputManager.h"
#include "../Objects/Object.h"
#include "../StarComponents.h"
#include "../Objects/BaseCamera.h"
#include "../Graphics/GraphicsManager.h"
#include "../Graphics/ScaleSystem.h"
#include "../Helpers/Debug/DebugDraw.h"
#include "../Physics/Collision/CollisionManager.h"
#include "../Input/Gestures/GestureManager.h"
namespace star
{
BaseScene::BaseScene(const tstring & name)
: m_GestureManagerPtr(nullptr)
, m_CollisionManagerPtr(nullptr)
, m_Objects()
, m_pDefaultCamera(nullptr)
, m_CullingOffsetX(0)
, m_CullingOffsetY(0)
, m_Initialized(false)
, m_Name(name)
{
m_pStopwatch = std::make_shared<Stopwatch>();
m_GestureManagerPtr = std::make_shared<GestureManager>();
m_CollisionManagerPtr = std::make_shared<CollisionManager>();
}
BaseScene::~BaseScene()
{
for(auto object : m_Objects)
{
delete object;
}
m_Objects.clear();
m_GestureManagerPtr = nullptr;
m_CollisionManagerPtr = nullptr;
}
void BaseScene::BaseInitialize()
{
if(!m_Initialized)
{
CreateObjects();
if(m_pDefaultCamera == nullptr)
{
m_pDefaultCamera = new BaseCamera();
AddObject(m_pDefaultCamera);
}
m_Initialized = true;
for(auto object : m_Objects)
{
object->BaseInitialize();
}
BaseAfterInitializedObjects();
}
}
void BaseScene::BaseAfterInitializedObjects()
{
SetActiveCamera(m_pDefaultCamera);
AfterInitializedObjects();
}
void BaseScene::BaseOnActivate()
{
InputManager::GetInstance()->SetGestureManager(m_GestureManagerPtr);
return OnActivate();
}
void BaseScene::BaseOnDeactivate()
{
OnDeactivate();
}
void BaseScene::BaseUpdate(const Context& context)
{
m_pStopwatch->Update(context);
for(auto object : m_Objects)
{
//if(CheckCulling(object))
//{
object->BaseUpdate(context);
//}
}
Update(context);
//[COMMENT] Updating the collisionManager before the objects or here?
// If i do it before the objects, there is the problem that
// the objects won't be translated correctly...
// So i think here is best, unless somebody proves me wrong
m_CollisionManagerPtr->Update(context);
}
void BaseScene::BaseDraw()
{
for(auto object : m_Objects)
{
if(object->IsVisible() && CheckCulling(object))
{
object->BaseDraw();
}
for(auto child : object->GetChildren())
{
if(CheckCulling(child))
{
child->BaseDraw();
}
}
}
Draw();
}
void BaseScene::OnSaveState(void** pData, size_t* pSize)
{
}
void BaseScene::OnConfigurationChanged()
{
}
void BaseScene::OnLowMemory()
{
}
const tstring & BaseScene::GetName() const
{
return m_Name;
}
bool BaseScene::IsInitialized() const
{
return m_Initialized;
}
void BaseScene::AddObject(Object * object)
{
auto it = std::find(m_Objects.begin(), m_Objects.end(), object);
if(it == m_Objects.end())
{
m_Objects.push_back(object);
object->SetScene(this);
}
}
void BaseScene::RemoveObject(Object * object)
{
auto it = std::find(m_Objects.begin(), m_Objects.end(), object);
if(it != m_Objects.end())
{
m_Objects.erase(it);
object->UnsetScene();
}
}
void BaseScene::SetActiveCamera(BaseCamera* pCamera)
{
if(m_pDefaultCamera == pCamera)
{
return;
}
if(m_pDefaultCamera != nullptr)
{
delete m_pDefaultCamera;
m_pDefaultCamera = nullptr;
}
m_pDefaultCamera = pCamera;
m_pDefaultCamera->GetComponent<CameraComponent>()->Activate();
}
BaseCamera* BaseScene::GetActiveCamera() const
{
return m_pDefaultCamera;
}
std::shared_ptr<Stopwatch> BaseScene::GetStopwatch() const
{
return m_pStopwatch;
}
std::shared_ptr<GestureManager> BaseScene::GetGestureManager() const
{
return m_GestureManagerPtr;
}
std::shared_ptr<CollisionManager> BaseScene::GetCollisionManager() const
{
return m_CollisionManagerPtr;
}
bool BaseScene::CheckCulling(Object* object)
{
pos camPos = m_pDefaultCamera->GetTransform()->GetWorldPosition();
float32 xPos = camPos.pos2D().x *
((star::ScaleSystem::GetInstance()->GetWorkingResolution().x) / 2.0f);
float32 yPos = camPos.pos2D().y *
((star::ScaleSystem::GetInstance()->GetWorkingResolution().y) / 2.0f);
int32 screenWidth = GraphicsManager::GetInstance()->GetScreenWidth();
int32 screenHeight = GraphicsManager::GetInstance()->GetScreenHeight();
if(sprite == nullptr && spritesheet == nullptr && text == nullptr)
const auto & objComponents = object->GetComponents();
for ( auto component : objComponents)
{
if(component->CheckCulling(
xPos - m_CullingOffsetX,
xPos + screenWidth + m_CullingOffsetX,
yPos + screenHeight + m_CullingOffsetY,
yPos - m_CullingOffsetY
))
{
return true;
}
}
else if(text != nullptr)
{
spriteWidth = int32(float32(text->GetMaxTextWidth()) * object->GetTransform()->GetWorldScale().x);
spriteHeight = int32(float32(text->GetTotalTextHeight()) * object->GetTransform()->GetWorldScale().y);
}
return false;
}
void BaseScene::SetCullingOffset(int32 offset)
{
m_CullingOffsetX = offset;
m_CullingOffsetY = offset;
}
void BaseScene::SetCullingOffset(int32 offsetX, int32 offsetY)
{
m_CullingOffsetX = offsetX;
m_CullingOffsetY = offsetY;
}
}
<commit_msg>Cleaned up basescene.<commit_after>#include "BaseScene.h"
#include "../Context.h"
#include "../Input/InputManager.h"
#include "../Objects/Object.h"
#include "../StarComponents.h"
#include "../Objects/BaseCamera.h"
#include "../Graphics/GraphicsManager.h"
#include "../Graphics/ScaleSystem.h"
#include "../Helpers/Debug/DebugDraw.h"
#include "../Physics/Collision/CollisionManager.h"
#include "../Input/Gestures/GestureManager.h"
namespace star
{
BaseScene::BaseScene(const tstring & name)
: m_GestureManagerPtr(nullptr)
, m_CollisionManagerPtr(nullptr)
, m_Objects()
, m_pDefaultCamera(nullptr)
, m_CullingOffsetX(0)
, m_CullingOffsetY(0)
, m_Initialized(false)
, m_Name(name)
{
m_pStopwatch = std::make_shared<Stopwatch>();
m_GestureManagerPtr = std::make_shared<GestureManager>();
m_CollisionManagerPtr = std::make_shared<CollisionManager>();
}
BaseScene::~BaseScene()
{
for(auto object : m_Objects)
{
delete object;
}
m_Objects.clear();
m_GestureManagerPtr = nullptr;
m_CollisionManagerPtr = nullptr;
}
void BaseScene::BaseInitialize()
{
if(!m_Initialized)
{
CreateObjects();
if(m_pDefaultCamera == nullptr)
{
m_pDefaultCamera = new BaseCamera();
AddObject(m_pDefaultCamera);
}
m_Initialized = true;
for(auto object : m_Objects)
{
object->BaseInitialize();
}
BaseAfterInitializedObjects();
}
}
void BaseScene::BaseAfterInitializedObjects()
{
SetActiveCamera(m_pDefaultCamera);
AfterInitializedObjects();
}
void BaseScene::BaseOnActivate()
{
InputManager::GetInstance()->SetGestureManager(m_GestureManagerPtr);
return OnActivate();
}
void BaseScene::BaseOnDeactivate()
{
OnDeactivate();
}
void BaseScene::BaseUpdate(const Context& context)
{
m_pStopwatch->Update(context);
for(auto object : m_Objects)
{
object->BaseUpdate(context);
}
Update(context);
//[COMMENT] Updating the collisionManager before the objects or here?
// If i do it before the objects, there is the problem that
// the objects won't be translated correctly...
// So i think here is best, unless somebody proves me wrong
m_CollisionManagerPtr->Update(context);
}
void BaseScene::BaseDraw()
{
for(auto object : m_Objects)
{
if(object->IsVisible() && CheckCulling(object))
{
object->BaseDraw();
}
for(auto child : object->GetChildren())
{
if(CheckCulling(child))
{
child->BaseDraw();
}
}
}
Draw();
}
void BaseScene::OnSaveState(void** pData, size_t* pSize)
{
}
void BaseScene::OnConfigurationChanged()
{
}
void BaseScene::OnLowMemory()
{
}
const tstring & BaseScene::GetName() const
{
return m_Name;
}
bool BaseScene::IsInitialized() const
{
return m_Initialized;
}
void BaseScene::AddObject(Object * object)
{
auto it = std::find(m_Objects.begin(), m_Objects.end(), object);
if(it == m_Objects.end())
{
m_Objects.push_back(object);
object->SetScene(this);
}
}
void BaseScene::RemoveObject(Object * object)
{
auto it = std::find(m_Objects.begin(), m_Objects.end(), object);
if(it != m_Objects.end())
{
m_Objects.erase(it);
object->UnsetScene();
}
}
void BaseScene::SetActiveCamera(BaseCamera* pCamera)
{
if(m_pDefaultCamera == pCamera)
{
return;
}
if(m_pDefaultCamera != nullptr)
{
delete m_pDefaultCamera;
m_pDefaultCamera = nullptr;
}
m_pDefaultCamera = pCamera;
m_pDefaultCamera->GetComponent<CameraComponent>()->Activate();
}
BaseCamera* BaseScene::GetActiveCamera() const
{
return m_pDefaultCamera;
}
std::shared_ptr<Stopwatch> BaseScene::GetStopwatch() const
{
return m_pStopwatch;
}
std::shared_ptr<GestureManager> BaseScene::GetGestureManager() const
{
return m_GestureManagerPtr;
}
std::shared_ptr<CollisionManager> BaseScene::GetCollisionManager() const
{
return m_CollisionManagerPtr;
}
bool BaseScene::CheckCulling(Object* object)
{
pos camPos = m_pDefaultCamera->GetTransform()->GetWorldPosition();
float32 xPos = camPos.pos2D().x *
((star::ScaleSystem::GetInstance()->GetWorkingResolution().x) / 2.0f);
float32 yPos = camPos.pos2D().y *
((star::ScaleSystem::GetInstance()->GetWorkingResolution().y) / 2.0f);
int32 screenWidth = GraphicsManager::GetInstance()->GetScreenWidth();
int32 screenHeight = GraphicsManager::GetInstance()->GetScreenHeight();
const auto & objComponents = object->GetComponents();
for ( auto component : objComponents)
{
if(component->CheckCulling(
xPos - m_CullingOffsetX,
xPos + screenWidth + m_CullingOffsetX,
yPos + screenHeight + m_CullingOffsetY,
yPos - m_CullingOffsetY
))
{
return true;
}
}
return false;
}
void BaseScene::SetCullingOffset(int32 offset)
{
m_CullingOffsetX = offset;
m_CullingOffsetY = offset;
}
void BaseScene::SetCullingOffset(int32 offsetX, int32 offsetY)
{
m_CullingOffsetX = offsetX;
m_CullingOffsetY = offsetY;
}
}
<|endoftext|>
|
<commit_before>/*
* Android File Transfer for Linux: MTP client for android devices
* Copyright (C) 2015 Vladimir Menshakov
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "progressdialog.h"
#include "ui_progressdialog.h"
#include <QCloseEvent>
#include <QPropertyAnimation>
#include <QDebug>
ProgressDialog::ProgressDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ProgressDialog), _progress(0), _duration(0)
{
ui->setupUi(this);
ui->progressBar->setMaximum(10000);
ui->buttonBox->setEnabled(false);
_animation = new QPropertyAnimation(this, "progress", this);
_animation->setDuration(30000);
_animation->setStartValue(0);
_animation->setEndValue(1);
_animation->start();
}
ProgressDialog::~ProgressDialog()
{
delete ui;
}
void ProgressDialog::reject()
{ }
void ProgressDialog::setProgress(float current)
{
ui->progressBar->setValue(current * 10000);
}
void ProgressDialog::setValue(float current)
{
//qDebug() << "setValue " << current;
_duration += _animation->currentTime();
float currentAnimated = _animation->currentValue().toFloat();
if (_duration <= 0)
return;
float currentSpeed = current * 1000 / _duration;
int estimate = 1000 / currentSpeed;
int duration = estimate - _duration;
if (duration < 100)
duration = 100;
//qDebug() << current << currentSpeed << estimate;
_animation->stop();
_animation->setStartValue(currentAnimated);
_animation->setDuration(duration);
_animation->start();
}
void ProgressDialog::setFilename(const QString &filename)
{
ui->label->setText(filename);
}
void ProgressDialog::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<commit_msg>cut current progress value if out of range 0-1<commit_after>/*
* Android File Transfer for Linux: MTP client for android devices
* Copyright (C) 2015 Vladimir Menshakov
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "progressdialog.h"
#include "ui_progressdialog.h"
#include <QCloseEvent>
#include <QPropertyAnimation>
#include <QDebug>
ProgressDialog::ProgressDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ProgressDialog), _progress(0), _duration(0)
{
ui->setupUi(this);
ui->progressBar->setMaximum(10000);
ui->buttonBox->setEnabled(false);
_animation = new QPropertyAnimation(this, "progress", this);
_animation->setDuration(30000);
_animation->setStartValue(0);
_animation->setEndValue(1);
_animation->start();
}
ProgressDialog::~ProgressDialog()
{
delete ui;
}
void ProgressDialog::reject()
{ }
void ProgressDialog::setProgress(float current)
{
if (current < 0)
current = 0;
if (current > 1)
current = 1;
ui->progressBar->setValue(current * 10000);
}
void ProgressDialog::setValue(float current)
{
//qDebug() << "setValue " << current;
_duration += _animation->currentTime();
float currentAnimated = _animation->currentValue().toFloat();
if (_duration <= 0)
return;
float currentSpeed = current * 1000 / _duration;
int estimate = 1000 / currentSpeed;
int duration = estimate - _duration;
if (duration < 100)
duration = 100;
//qDebug() << current << currentSpeed << estimate;
_animation->stop();
_animation->setStartValue(currentAnimated);
_animation->setDuration(duration);
_animation->start();
}
void ProgressDialog::setFilename(const QString &filename)
{
ui->label->setText(filename);
}
void ProgressDialog::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<|endoftext|>
|
<commit_before>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* DecodedBitStreamParser.cpp
* zxing
*
* Created by Christian Brunschen on 20/05/2008.
* Copyright 2008 ZXing 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 <zxing/qrcode/decoder/DecodedBitStreamParser.h>
#include <zxing/common/CharacterSetECI.h>
#include <zxing/FormatException.h>
#include <zxing/common/StringUtils.h>
#include <iostream>
#ifndef NO_ICONV
#include <iconv.h>
#endif
// Required for compatibility. TODO: test on Symbian
#ifdef ZXING_ICONV_CONST
#undef ICONV_CONST
#define ICONV_CONST const
#endif
#ifndef ICONV_CONST
#define ICONV_CONST /**/
#endif
using namespace std;
using namespace zxing;
using namespace zxing::qrcode;
using namespace zxing::common;
const char DecodedBitStreamParser::ALPHANUMERIC_CHARS[] =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'
};
namespace {int GB2312_SUBSET = 1;}
void DecodedBitStreamParser::append(std::string &result,
string const& in,
const char *src) {
append(result, (unsigned char const*)in.c_str(), in.length(), src);
}
void DecodedBitStreamParser::append(std::string &result,
const unsigned char *bufIn,
size_t nIn,
const char *src) {
#ifndef NO_ICONV
if (nIn == 0) {
return;
}
iconv_t cd = iconv_open(StringUtils::UTF8, src);
if (cd == (iconv_t)-1) {
result.append((const char *)bufIn, nIn);
return;
}
const int maxOut = 4 * nIn + 1;
unsigned char* bufOut = new unsigned char[maxOut];
ICONV_CONST char *fromPtr = (ICONV_CONST char *)bufIn;
size_t nFrom = nIn;
char *toPtr = (char *)bufOut;
size_t nTo = maxOut;
while (nFrom > 0) {
size_t oneway = iconv(cd, &fromPtr, &nFrom, &toPtr, &nTo);
if (oneway == (size_t)(-1)) {
iconv_close(cd);
delete[] bufOut;
throw ReaderException("error converting characters");
}
}
iconv_close(cd);
int nResult = maxOut - nTo;
bufOut[nResult] = '\0';
result.append((const char *)bufOut);
delete[] bufOut;
#else
result.append((const char *)bufIn, nIn);
#endif
}
void DecodedBitStreamParser::decodeHanziSegment(Ref<BitSource> bits_,
string& result,
int count) {
BitSource& bits (*bits_);
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available()) {
throw FormatException();
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
size_t nBytes = 2 * count;
unsigned char* buffer = new unsigned char[nBytes];
int offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF) {
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
} else {
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (unsigned char) ((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (unsigned char) (assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try {
append(result, buffer, nBytes, StringUtils::GB2312);
} catch (ReaderException const& re) {
delete [] buffer;
throw FormatException();
}
delete [] buffer;
}
void DecodedBitStreamParser::decodeKanjiSegment(Ref<BitSource> bits, std::string &result, int count) {
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
size_t nBytes = 2 * count;
unsigned char* buffer = new unsigned char[nBytes];
int offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
int twoBytes = bits->readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00) {
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
} else {
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (unsigned char)(assembledTwoBytes >> 8);
buffer[offset + 1] = (unsigned char)assembledTwoBytes;
offset += 2;
count--;
}
append(result, buffer, nBytes, StringUtils::SHIFT_JIS);
delete[] buffer;
}
void DecodedBitStreamParser::decodeByteSegment(Ref<BitSource> bits_,
string& result,
int count,
CharacterSetECI* currentCharacterSetECI,
ArrayRef< ArrayRef<unsigned char> >& byteSegments,
Hashtable const& hints) {
int nBytes = count;
BitSource& bits (*bits_);
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available()) {
throw FormatException();
}
ArrayRef<unsigned char> bytes_ (count);
unsigned char* readBytes = &(*bytes_)[0];
for (int i = 0; i < count; i++) {
readBytes[i] = (unsigned char) bits.readBits(8);
}
string encoding;
if (currentCharacterSetECI == 0) {
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils::guessEncoding(readBytes, count, hints);
} else {
encoding = currentCharacterSetECI->name();
}
try {
append(result, readBytes, nBytes, encoding.c_str());
} catch (ReaderException const& re) {
throw FormatException();
}
byteSegments->values().push_back(bytes_);
}
void DecodedBitStreamParser::decodeNumericSegment(Ref<BitSource> bits, std::string &result, int count) {
int nBytes = count;
unsigned char* bytes = new unsigned char[nBytes];
int i = 0;
// Read three digits at a time
while (count >= 3) {
// Each 10 bits encodes three digits
if (bits->available() < 10) {
throw ReaderException("format exception");
}
int threeDigitsBits = bits->readBits(10);
if (threeDigitsBits >= 1000) {
ostringstream s;
s << "Illegal value for 3-digit unit: " << threeDigitsBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits / 100];
bytes[i++] = ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10];
bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits % 10];
count -= 3;
}
if (count == 2) {
if (bits->available() < 7) {
throw ReaderException("format exception");
}
// Two digits left over to read, encoded in 7 bits
int twoDigitsBits = bits->readBits(7);
if (twoDigitsBits >= 100) {
ostringstream s;
s << "Illegal value for 2-digit unit: " << twoDigitsBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits / 10];
bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits % 10];
} else if (count == 1) {
if (bits->available() < 4) {
throw ReaderException("format exception");
}
// One digit left over to read
int digitBits = bits->readBits(4);
if (digitBits >= 10) {
ostringstream s;
s << "Illegal value for digit unit: " << digitBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[digitBits];
}
append(result, bytes, nBytes, StringUtils::ASCII);
delete[] bytes;
}
char DecodedBitStreamParser::toAlphaNumericChar(size_t value) {
if (value >= sizeof(DecodedBitStreamParser::ALPHANUMERIC_CHARS)) {
throw FormatException();
}
return ALPHANUMERIC_CHARS[value];
}
void DecodedBitStreamParser::decodeAlphanumericSegment(Ref<BitSource> bits_,
string& result,
int count,
bool fc1InEffect) {
BitSource& bits (*bits_);
ostringstream bytes;
// Read two characters at a time
while (count > 1) {
if (bits.available() < 11) {
throw FormatException();
}
int nextTwoCharsBits = bits.readBits(11);
bytes << toAlphaNumericChar(nextTwoCharsBits / 45);
bytes << toAlphaNumericChar(nextTwoCharsBits % 45);
count -= 2;
}
if (count == 1) {
// special case: one character left
if (bits.available() < 6) {
throw FormatException();
}
bytes << toAlphaNumericChar(bits.readBits(6));
}
// See section 6.4.8.1, 6.4.8.2
string s = bytes.str();
if (fc1InEffect) {
// We need to massage the result a bit if in an FNC1 mode:
ostringstream r;
for (size_t i = 0; i < s.length(); i++) {
if (s[i] != '%') {
r << s[i];
} else {
if (i < s.length() - 1 && s[i + 1] == '%') {
// %% is rendered as %
r << s[i++];
} else {
// In alpha mode, % should be converted to FNC1 separator 0x1D
r << (char)0x1D;
}
}
}
s = r.str();
}
append(result, s, StringUtils::ASCII);
}
namespace {
int parseECIValue(BitSource bits) {
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0) {
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80) {
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0) {
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw FormatException();
}
}
Ref<DecoderResult>
DecodedBitStreamParser::decode(ArrayRef<unsigned char> bytes,
Version* version,
ErrorCorrectionLevel const& ecLevel,
Hashtable const& hints) {
Ref<BitSource> bits_ (new BitSource(bytes));
BitSource& bits (*bits_);
string result;
CharacterSetECI* currentCharacterSetECI = 0;
bool fc1InEffect = false;
ArrayRef< ArrayRef<unsigned char> > byteSegments (size_t(0));
Mode* mode = 0;
do {
// While still another segment to read...
if (bits.available() < 4) {
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = &Mode::TERMINATOR;
} else {
try {
mode = &Mode::forBits(bits.readBits(4)); // mode is encoded by 4 bits
} catch (IllegalArgumentException const& iae) {
throw iae;
// throw FormatException.getFormatInstance();
}
}
if (mode != &Mode::TERMINATOR) {
if ((mode == &Mode::FNC1_FIRST_POSITION) || (mode == &Mode::FNC1_SECOND_POSITION)) {
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
} else if (mode == &Mode::STRUCTURED_APPEND) {
// not really supported; all we do is ignore it
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
bits.readBits(16);
} else if (mode == &Mode::ECI) {
// Count doesn't apply to ECI
int value = parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value);
if (currentCharacterSetECI == 0) {
throw FormatException();
}
} else {
// First handle Hanzi mode which does not start with character count
if (mode == &Mode::HANZI) {
//chinese mode contains a sub set indicator right after mode indicator
int subset = bits.readBits(4);
int countHanzi = bits.readBits(mode->getCharacterCountBits(version));
if (subset == GB2312_SUBSET) {
decodeHanziSegment(bits_, result, countHanzi);
}
} else {
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode->getCharacterCountBits(version));
if (mode == &Mode::NUMERIC) {
decodeNumericSegment(bits_, result, count);
} else if (mode == &Mode::ALPHANUMERIC) {
decodeAlphanumericSegment(bits_, result, count, fc1InEffect);
} else if (mode == &Mode::BYTE) {
decodeByteSegment(bits_, result, count, currentCharacterSetECI, byteSegments, hints);
} else if (mode == &Mode::KANJI) {
decodeKanjiSegment(bits_, result, count);
} else {
throw FormatException();
}
}
}
}
} while (mode != &Mode::TERMINATOR);
return Ref<DecoderResult>(new DecoderResult(bytes, Ref<String>(new String(result)), byteSegments, (string)ecLevel));
}
<commit_msg>Generate proper FormatException on QR code with bad structured append segment<commit_after>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* DecodedBitStreamParser.cpp
* zxing
*
* Created by Christian Brunschen on 20/05/2008.
* Copyright 2008 ZXing 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 <zxing/qrcode/decoder/DecodedBitStreamParser.h>
#include <zxing/common/CharacterSetECI.h>
#include <zxing/FormatException.h>
#include <zxing/common/StringUtils.h>
#include <iostream>
#ifndef NO_ICONV
#include <iconv.h>
#endif
// Required for compatibility. TODO: test on Symbian
#ifdef ZXING_ICONV_CONST
#undef ICONV_CONST
#define ICONV_CONST const
#endif
#ifndef ICONV_CONST
#define ICONV_CONST /**/
#endif
using namespace std;
using namespace zxing;
using namespace zxing::qrcode;
using namespace zxing::common;
const char DecodedBitStreamParser::ALPHANUMERIC_CHARS[] =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'
};
namespace {int GB2312_SUBSET = 1;}
void DecodedBitStreamParser::append(std::string &result,
string const& in,
const char *src) {
append(result, (unsigned char const*)in.c_str(), in.length(), src);
}
void DecodedBitStreamParser::append(std::string &result,
const unsigned char *bufIn,
size_t nIn,
const char *src) {
#ifndef NO_ICONV
if (nIn == 0) {
return;
}
iconv_t cd = iconv_open(StringUtils::UTF8, src);
if (cd == (iconv_t)-1) {
result.append((const char *)bufIn, nIn);
return;
}
const int maxOut = 4 * nIn + 1;
unsigned char* bufOut = new unsigned char[maxOut];
ICONV_CONST char *fromPtr = (ICONV_CONST char *)bufIn;
size_t nFrom = nIn;
char *toPtr = (char *)bufOut;
size_t nTo = maxOut;
while (nFrom > 0) {
size_t oneway = iconv(cd, &fromPtr, &nFrom, &toPtr, &nTo);
if (oneway == (size_t)(-1)) {
iconv_close(cd);
delete[] bufOut;
throw ReaderException("error converting characters");
}
}
iconv_close(cd);
int nResult = maxOut - nTo;
bufOut[nResult] = '\0';
result.append((const char *)bufOut);
delete[] bufOut;
#else
result.append((const char *)bufIn, nIn);
#endif
}
void DecodedBitStreamParser::decodeHanziSegment(Ref<BitSource> bits_,
string& result,
int count) {
BitSource& bits (*bits_);
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available()) {
throw FormatException();
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
size_t nBytes = 2 * count;
unsigned char* buffer = new unsigned char[nBytes];
int offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF) {
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
} else {
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (unsigned char) ((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (unsigned char) (assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try {
append(result, buffer, nBytes, StringUtils::GB2312);
} catch (ReaderException const& re) {
delete [] buffer;
throw FormatException();
}
delete [] buffer;
}
void DecodedBitStreamParser::decodeKanjiSegment(Ref<BitSource> bits, std::string &result, int count) {
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
size_t nBytes = 2 * count;
unsigned char* buffer = new unsigned char[nBytes];
int offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
int twoBytes = bits->readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00) {
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
} else {
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (unsigned char)(assembledTwoBytes >> 8);
buffer[offset + 1] = (unsigned char)assembledTwoBytes;
offset += 2;
count--;
}
append(result, buffer, nBytes, StringUtils::SHIFT_JIS);
delete[] buffer;
}
void DecodedBitStreamParser::decodeByteSegment(Ref<BitSource> bits_,
string& result,
int count,
CharacterSetECI* currentCharacterSetECI,
ArrayRef< ArrayRef<unsigned char> >& byteSegments,
Hashtable const& hints) {
int nBytes = count;
BitSource& bits (*bits_);
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available()) {
throw FormatException();
}
ArrayRef<unsigned char> bytes_ (count);
unsigned char* readBytes = &(*bytes_)[0];
for (int i = 0; i < count; i++) {
readBytes[i] = (unsigned char) bits.readBits(8);
}
string encoding;
if (currentCharacterSetECI == 0) {
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils::guessEncoding(readBytes, count, hints);
} else {
encoding = currentCharacterSetECI->name();
}
try {
append(result, readBytes, nBytes, encoding.c_str());
} catch (ReaderException const& re) {
throw FormatException();
}
byteSegments->values().push_back(bytes_);
}
void DecodedBitStreamParser::decodeNumericSegment(Ref<BitSource> bits, std::string &result, int count) {
int nBytes = count;
unsigned char* bytes = new unsigned char[nBytes];
int i = 0;
// Read three digits at a time
while (count >= 3) {
// Each 10 bits encodes three digits
if (bits->available() < 10) {
throw ReaderException("format exception");
}
int threeDigitsBits = bits->readBits(10);
if (threeDigitsBits >= 1000) {
ostringstream s;
s << "Illegal value for 3-digit unit: " << threeDigitsBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits / 100];
bytes[i++] = ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10];
bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits % 10];
count -= 3;
}
if (count == 2) {
if (bits->available() < 7) {
throw ReaderException("format exception");
}
// Two digits left over to read, encoded in 7 bits
int twoDigitsBits = bits->readBits(7);
if (twoDigitsBits >= 100) {
ostringstream s;
s << "Illegal value for 2-digit unit: " << twoDigitsBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits / 10];
bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits % 10];
} else if (count == 1) {
if (bits->available() < 4) {
throw ReaderException("format exception");
}
// One digit left over to read
int digitBits = bits->readBits(4);
if (digitBits >= 10) {
ostringstream s;
s << "Illegal value for digit unit: " << digitBits;
delete[] bytes;
throw ReaderException(s.str().c_str());
}
bytes[i++] = ALPHANUMERIC_CHARS[digitBits];
}
append(result, bytes, nBytes, StringUtils::ASCII);
delete[] bytes;
}
char DecodedBitStreamParser::toAlphaNumericChar(size_t value) {
if (value >= sizeof(DecodedBitStreamParser::ALPHANUMERIC_CHARS)) {
throw FormatException();
}
return ALPHANUMERIC_CHARS[value];
}
void DecodedBitStreamParser::decodeAlphanumericSegment(Ref<BitSource> bits_,
string& result,
int count,
bool fc1InEffect) {
BitSource& bits (*bits_);
ostringstream bytes;
// Read two characters at a time
while (count > 1) {
if (bits.available() < 11) {
throw FormatException();
}
int nextTwoCharsBits = bits.readBits(11);
bytes << toAlphaNumericChar(nextTwoCharsBits / 45);
bytes << toAlphaNumericChar(nextTwoCharsBits % 45);
count -= 2;
}
if (count == 1) {
// special case: one character left
if (bits.available() < 6) {
throw FormatException();
}
bytes << toAlphaNumericChar(bits.readBits(6));
}
// See section 6.4.8.1, 6.4.8.2
string s = bytes.str();
if (fc1InEffect) {
// We need to massage the result a bit if in an FNC1 mode:
ostringstream r;
for (size_t i = 0; i < s.length(); i++) {
if (s[i] != '%') {
r << s[i];
} else {
if (i < s.length() - 1 && s[i + 1] == '%') {
// %% is rendered as %
r << s[i++];
} else {
// In alpha mode, % should be converted to FNC1 separator 0x1D
r << (char)0x1D;
}
}
}
s = r.str();
}
append(result, s, StringUtils::ASCII);
}
namespace {
int parseECIValue(BitSource bits) {
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0) {
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80) {
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0) {
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw FormatException();
}
}
Ref<DecoderResult>
DecodedBitStreamParser::decode(ArrayRef<unsigned char> bytes,
Version* version,
ErrorCorrectionLevel const& ecLevel,
Hashtable const& hints) {
Ref<BitSource> bits_ (new BitSource(bytes));
BitSource& bits (*bits_);
string result;
CharacterSetECI* currentCharacterSetECI = 0;
bool fc1InEffect = false;
ArrayRef< ArrayRef<unsigned char> > byteSegments (size_t(0));
Mode* mode = 0;
do {
// While still another segment to read...
if (bits.available() < 4) {
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = &Mode::TERMINATOR;
} else {
try {
mode = &Mode::forBits(bits.readBits(4)); // mode is encoded by 4 bits
} catch (IllegalArgumentException const& iae) {
throw iae;
// throw FormatException.getFormatInstance();
}
}
if (mode != &Mode::TERMINATOR) {
if ((mode == &Mode::FNC1_FIRST_POSITION) || (mode == &Mode::FNC1_SECOND_POSITION)) {
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
} else if (mode == &Mode::STRUCTURED_APPEND) {
if (bits.available() < 16) {
throw new FormatException();
}
// not really supported; all we do is ignore it
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
bits.readBits(16);
} else if (mode == &Mode::ECI) {
// Count doesn't apply to ECI
int value = parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value);
if (currentCharacterSetECI == 0) {
throw FormatException();
}
} else {
// First handle Hanzi mode which does not start with character count
if (mode == &Mode::HANZI) {
//chinese mode contains a sub set indicator right after mode indicator
int subset = bits.readBits(4);
int countHanzi = bits.readBits(mode->getCharacterCountBits(version));
if (subset == GB2312_SUBSET) {
decodeHanziSegment(bits_, result, countHanzi);
}
} else {
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode->getCharacterCountBits(version));
if (mode == &Mode::NUMERIC) {
decodeNumericSegment(bits_, result, count);
} else if (mode == &Mode::ALPHANUMERIC) {
decodeAlphanumericSegment(bits_, result, count, fc1InEffect);
} else if (mode == &Mode::BYTE) {
decodeByteSegment(bits_, result, count, currentCharacterSetECI, byteSegments, hints);
} else if (mode == &Mode::KANJI) {
decodeKanjiSegment(bits_, result, count);
} else {
throw FormatException();
}
}
}
}
} while (mode != &Mode::TERMINATOR);
return Ref<DecoderResult>(new DecoderResult(bytes, Ref<String>(new String(result)), byteSegments, (string)ecLevel));
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "libjoynrclustercontroller/mqtt/MqttMessagingSkeleton.h"
#include <smrf/exceptions.h>
#include "joynr/DispatcherUtils.h"
#include "joynr/IMessageRouter.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/Message.h"
#include "joynr/Util.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/serializer/Serializer.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "libjoynrclustercontroller/mqtt/MqttReceiver.h"
namespace joynr
{
INIT_LOGGER(MqttMessagingSkeleton);
const std::string MqttMessagingSkeleton::MQTT_MULTI_LEVEL_WILDCARD("#");
std::string MqttMessagingSkeleton::translateMulticastWildcard(std::string topic)
{
if (topic.length() > 0 && topic.back() == util::MULTI_LEVEL_WILDCARD[0]) {
topic.back() = MQTT_MULTI_LEVEL_WILDCARD[0];
}
return topic;
}
MqttMessagingSkeleton::MqttMessagingSkeleton(IMessageRouter& messageRouter,
std::shared_ptr<MqttReceiver> mqttReceiver,
const std::string& multicastTopicPrefix,
uint64_t ttlUplift)
: messageRouter(messageRouter),
mqttReceiver(mqttReceiver),
ttlUplift(ttlUplift),
multicastSubscriptionCount(),
multicastSubscriptionCountMutex(),
multicastTopicPrefix(multicastTopicPrefix)
{
}
void MqttMessagingSkeleton::registerMulticastSubscription(const std::string& multicastId)
{
std::string mqttTopic = translateMulticastWildcard(multicastId);
std::lock_guard<std::mutex> lock(multicastSubscriptionCountMutex);
if (multicastSubscriptionCount.find(mqttTopic) == multicastSubscriptionCount.cend()) {
mqttReceiver->subscribeToTopic(multicastTopicPrefix + mqttTopic);
multicastSubscriptionCount[mqttTopic] = 1;
} else {
multicastSubscriptionCount[mqttTopic]++;
}
}
void MqttMessagingSkeleton::unregisterMulticastSubscription(const std::string& multicastId)
{
std::string mqttTopic = translateMulticastWildcard(multicastId);
std::lock_guard<std::mutex> lock(multicastSubscriptionCountMutex);
auto countIterator = multicastSubscriptionCount.find(mqttTopic);
if (countIterator == multicastSubscriptionCount.cend()) {
JOYNR_LOG_ERROR(
logger, "unregister multicast subscription called for non existing subscription");
} else if (countIterator->second == 1) {
multicastSubscriptionCount.erase(mqttTopic);
mqttReceiver->unsubscribeFromTopic(multicastTopicPrefix + mqttTopic);
} else {
countIterator->second--;
}
}
void MqttMessagingSkeleton::transmit(
std::shared_ptr<ImmutableMessage> message,
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure)
{
const std::string& messageType = message->getType();
if (messageType == Message::VALUE_MESSAGE_TYPE_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST()) {
boost::optional<std::string> optionalReplyTo = message->getReplyTo();
if (!optionalReplyTo.is_initialized()) {
JOYNR_LOG_ERROR(logger,
"message {} did not contain replyTo header, discarding",
message->getId());
return;
}
const std::string& replyTo = *optionalReplyTo;
try {
using system::RoutingTypes::MqttAddress;
MqttAddress address;
joynr::serializer::deserializeFromJson(address, replyTo);
messageRouter.addNextHop(
message->getSender(), std::make_shared<const MqttAddress>(address));
} catch (const std::invalid_argument& e) {
JOYNR_LOG_FATAL(logger,
"could not deserialize MqttAddress from {} - error: {}",
replyTo,
e.what());
// do not try to route the message if address is not valid
return;
}
} else if (messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST()) {
message->setReceivedFromGlobal(true);
}
try {
messageRouter.route(std::move(message));
} catch (const exceptions::JoynrRuntimeException& e) {
onFailure(e);
}
}
void MqttMessagingSkeleton::onMessageReceived(smrf::ByteVector&& rawMessage)
{
std::shared_ptr<ImmutableMessage> immutableMessage;
try {
immutableMessage = std::make_shared<ImmutableMessage>(std::move(rawMessage));
} catch (const smrf::EncodingException& e) {
JOYNR_LOG_ERROR(logger, "Unable to deserialize message - error: {}", e.what());
return;
} catch (const std::invalid_argument& e) {
JOYNR_LOG_ERROR(logger, "deserialized message is not valid - error: {}", e.what());
return;
}
JOYNR_LOG_DEBUG(logger, "<<< INCOMING <<< {}", immutableMessage->toLogMessage());
/*
// TODO remove uplift ???? cannot modify msg here!
const JoynrTimePoint maxAbsoluteTime = DispatcherUtils::getMaxAbsoluteTime();
JoynrTimePoint msgExpiryDate = msg.getHeaderExpiryDate();
std::int64_t maxDiff = std::chrono::duration_cast<std::chrono::milliseconds>(
maxAbsoluteTime - msgExpiryDate).count();
if (static_cast<std::int64_t>(ttlUplift) > maxDiff) {
msg.setHeaderExpiryDate(maxAbsoluteTime);
} else {
JoynrTimePoint newExpiryDate = msgExpiryDate + std::chrono::milliseconds(ttlUplift);
msg.setHeaderExpiryDate(newExpiryDate);
}
*/
auto onFailure = [messageId = immutableMessage->getId()](
const exceptions::JoynrRuntimeException& e)
{
JOYNR_LOG_ERROR(logger,
"Incoming Message with ID {} could not be sent! reason: {}",
messageId,
e.getMessage());
};
transmit(std::move(immutableMessage), onFailure);
}
} // namespace joynr
<commit_msg>[C++] Use "bool operator()" instead of boost::optional::is_initialized()<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "libjoynrclustercontroller/mqtt/MqttMessagingSkeleton.h"
#include <smrf/exceptions.h>
#include "joynr/DispatcherUtils.h"
#include "joynr/IMessageRouter.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/Message.h"
#include "joynr/Util.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/serializer/Serializer.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "libjoynrclustercontroller/mqtt/MqttReceiver.h"
namespace joynr
{
INIT_LOGGER(MqttMessagingSkeleton);
const std::string MqttMessagingSkeleton::MQTT_MULTI_LEVEL_WILDCARD("#");
std::string MqttMessagingSkeleton::translateMulticastWildcard(std::string topic)
{
if (topic.length() > 0 && topic.back() == util::MULTI_LEVEL_WILDCARD[0]) {
topic.back() = MQTT_MULTI_LEVEL_WILDCARD[0];
}
return topic;
}
MqttMessagingSkeleton::MqttMessagingSkeleton(IMessageRouter& messageRouter,
std::shared_ptr<MqttReceiver> mqttReceiver,
const std::string& multicastTopicPrefix,
uint64_t ttlUplift)
: messageRouter(messageRouter),
mqttReceiver(mqttReceiver),
ttlUplift(ttlUplift),
multicastSubscriptionCount(),
multicastSubscriptionCountMutex(),
multicastTopicPrefix(multicastTopicPrefix)
{
}
void MqttMessagingSkeleton::registerMulticastSubscription(const std::string& multicastId)
{
std::string mqttTopic = translateMulticastWildcard(multicastId);
std::lock_guard<std::mutex> lock(multicastSubscriptionCountMutex);
if (multicastSubscriptionCount.find(mqttTopic) == multicastSubscriptionCount.cend()) {
mqttReceiver->subscribeToTopic(multicastTopicPrefix + mqttTopic);
multicastSubscriptionCount[mqttTopic] = 1;
} else {
multicastSubscriptionCount[mqttTopic]++;
}
}
void MqttMessagingSkeleton::unregisterMulticastSubscription(const std::string& multicastId)
{
std::string mqttTopic = translateMulticastWildcard(multicastId);
std::lock_guard<std::mutex> lock(multicastSubscriptionCountMutex);
auto countIterator = multicastSubscriptionCount.find(mqttTopic);
if (countIterator == multicastSubscriptionCount.cend()) {
JOYNR_LOG_ERROR(
logger, "unregister multicast subscription called for non existing subscription");
} else if (countIterator->second == 1) {
multicastSubscriptionCount.erase(mqttTopic);
mqttReceiver->unsubscribeFromTopic(multicastTopicPrefix + mqttTopic);
} else {
countIterator->second--;
}
}
void MqttMessagingSkeleton::transmit(
std::shared_ptr<ImmutableMessage> message,
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure)
{
const std::string& messageType = message->getType();
if (messageType == Message::VALUE_MESSAGE_TYPE_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST() ||
messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST()) {
boost::optional<std::string> optionalReplyTo = message->getReplyTo();
if (!optionalReplyTo) {
JOYNR_LOG_ERROR(logger,
"message {} did not contain replyTo header, discarding",
message->getId());
return;
}
const std::string& replyTo = *optionalReplyTo;
try {
using system::RoutingTypes::MqttAddress;
MqttAddress address;
joynr::serializer::deserializeFromJson(address, replyTo);
messageRouter.addNextHop(
message->getSender(), std::make_shared<const MqttAddress>(address));
} catch (const std::invalid_argument& e) {
JOYNR_LOG_FATAL(logger,
"could not deserialize MqttAddress from {} - error: {}",
replyTo,
e.what());
// do not try to route the message if address is not valid
return;
}
} else if (messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST()) {
message->setReceivedFromGlobal(true);
}
try {
messageRouter.route(std::move(message));
} catch (const exceptions::JoynrRuntimeException& e) {
onFailure(e);
}
}
void MqttMessagingSkeleton::onMessageReceived(smrf::ByteVector&& rawMessage)
{
std::shared_ptr<ImmutableMessage> immutableMessage;
try {
immutableMessage = std::make_shared<ImmutableMessage>(std::move(rawMessage));
} catch (const smrf::EncodingException& e) {
JOYNR_LOG_ERROR(logger, "Unable to deserialize message - error: {}", e.what());
return;
} catch (const std::invalid_argument& e) {
JOYNR_LOG_ERROR(logger, "deserialized message is not valid - error: {}", e.what());
return;
}
JOYNR_LOG_DEBUG(logger, "<<< INCOMING <<< {}", immutableMessage->toLogMessage());
/*
// TODO remove uplift ???? cannot modify msg here!
const JoynrTimePoint maxAbsoluteTime = DispatcherUtils::getMaxAbsoluteTime();
JoynrTimePoint msgExpiryDate = msg.getHeaderExpiryDate();
std::int64_t maxDiff = std::chrono::duration_cast<std::chrono::milliseconds>(
maxAbsoluteTime - msgExpiryDate).count();
if (static_cast<std::int64_t>(ttlUplift) > maxDiff) {
msg.setHeaderExpiryDate(maxAbsoluteTime);
} else {
JoynrTimePoint newExpiryDate = msgExpiryDate + std::chrono::milliseconds(ttlUplift);
msg.setHeaderExpiryDate(newExpiryDate);
}
*/
auto onFailure = [messageId = immutableMessage->getId()](
const exceptions::JoynrRuntimeException& e)
{
JOYNR_LOG_ERROR(logger,
"Incoming Message with ID {} could not be sent! reason: {}",
messageId,
e.getMessage());
};
transmit(std::move(immutableMessage), onFailure);
}
} // namespace joynr
<|endoftext|>
|
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* 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 <TelepathyQt4/DBusProxyFactory>
#include "TelepathyQt4/dbus-proxy-factory-internal.h"
#include "TelepathyQt4/_gen/dbus-proxy-factory-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/DBusProxy>
#include <TelepathyQt4/ReadyObject>
#include <TelepathyQt4/PendingReady>
#include <QDBusConnection>
namespace Tp
{
struct DBusProxyFactory::Private
{
Private(const QDBusConnection &bus)
: bus(bus), cache(new Cache) {}
~Private()
{
delete cache;
}
QDBusConnection bus;
Cache *cache;
};
DBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus)
: mPriv(new Private(bus))
{
}
DBusProxyFactory::~DBusProxyFactory()
{
delete mPriv;
}
const QDBusConnection &DBusProxyFactory::dbusConnection() const
{
return mPriv->bus;
}
SharedPtr<RefCounted> DBusProxyFactory::cachedProxy(const QString &busName,
const QString &objectPath) const
{
QString finalName = finalBusNameFrom(busName);
return mPriv->cache->get(Cache::Key(finalName, objectPath));
}
PendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr<RefCounted> &proxy, bool created) const
{
Q_ASSERT(!proxy.isNull());
// I really hate the casts needed in this function - we must really do something about the
// DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a
// RefCounted, in the API/ABI break - then most of these proxyMisc-> things become just proxy->
DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(proxy.data());
ReadyObject *proxyReady = dynamic_cast<ReadyObject *>(proxy.data());
Q_ASSERT(proxyProxy != NULL);
Q_ASSERT(proxyReady != NULL);
Features specificFeatures = featuresFor(proxy);
// TODO: lookup existing prepareOp, if any, from a private mapping
PendingOperation *prepareOp = NULL;
if (created) {
mPriv->cache->put(Cache::Key(proxyProxy->busName(), proxyProxy->objectPath()), proxy);
prepareOp = prepare(proxy);
// TODO: insert to private prepare op mapping and make sure it's removed when it finishes/is
// destroyed
}
if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) {
return new PendingReady(prepareOp, specificFeatures, proxy, 0);
}
// No features requested or they are all ready - optimize a bit by not calling ReadinessHelper
PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0);
readyOp->setFinished();
return readyOp;
}
PendingOperation *DBusProxyFactory::prepare(const SharedPtr<RefCounted> &object) const
{
// Nothing we could think about needs doing
return NULL;
}
DBusProxyFactory::Cache::Cache()
{
}
DBusProxyFactory::Cache::~Cache()
{
}
SharedPtr<RefCounted> DBusProxyFactory::Cache::get(const Key &key) const
{
SharedPtr<RefCounted> counted(proxies.value(key));
// We already assert for it being a DBusProxy in put()
if (!counted || !dynamic_cast<DBusProxy *>(counted.data())->isValid()) {
// Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still
// haven't got the invalidated() signal for it
return SharedPtr<RefCounted>();
}
return counted;
}
void DBusProxyFactory::Cache::put(const Key &key, const SharedPtr<RefCounted> &obj)
{
Q_ASSERT(!proxies.contains(key));
DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(obj.data());
Q_ASSERT(proxyProxy != NULL);
// This sucks because DBusProxy is not RefCounted...
connect(proxyProxy,
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onProxyInvalidated(Tp::DBusProxy*)));
debug() << "Inserting to factory cache proxy for" << key;
proxies.insert(key, obj);
}
void DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy)
{
Key key(proxy->busName(), proxy->objectPath());
// Not having it would indicate invalidated() signaled twice for the same proxy, or us having
// connected to two proxies with the same key, neither of which should happen
Q_ASSERT(proxies.contains(key));
debug() << "Removing from factory cache invalidated proxy for" << key;
proxies.remove(key);
}
}
<commit_msg>Allow DBusProxyFactory::Cache::put() to override an existing cache item<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* 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 <TelepathyQt4/DBusProxyFactory>
#include "TelepathyQt4/dbus-proxy-factory-internal.h"
#include "TelepathyQt4/_gen/dbus-proxy-factory-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/DBusProxy>
#include <TelepathyQt4/ReadyObject>
#include <TelepathyQt4/PendingReady>
#include <QDBusConnection>
namespace Tp
{
struct DBusProxyFactory::Private
{
Private(const QDBusConnection &bus)
: bus(bus), cache(new Cache) {}
~Private()
{
delete cache;
}
QDBusConnection bus;
Cache *cache;
};
DBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus)
: mPriv(new Private(bus))
{
}
DBusProxyFactory::~DBusProxyFactory()
{
delete mPriv;
}
const QDBusConnection &DBusProxyFactory::dbusConnection() const
{
return mPriv->bus;
}
SharedPtr<RefCounted> DBusProxyFactory::cachedProxy(const QString &busName,
const QString &objectPath) const
{
QString finalName = finalBusNameFrom(busName);
return mPriv->cache->get(Cache::Key(finalName, objectPath));
}
PendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr<RefCounted> &proxy, bool created) const
{
Q_ASSERT(!proxy.isNull());
// I really hate the casts needed in this function - we must really do something about the
// DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a
// RefCounted, in the API/ABI break - then most of these proxyMisc-> things become just proxy->
DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(proxy.data());
ReadyObject *proxyReady = dynamic_cast<ReadyObject *>(proxy.data());
Q_ASSERT(proxyProxy != NULL);
Q_ASSERT(proxyReady != NULL);
Features specificFeatures = featuresFor(proxy);
// TODO: lookup existing prepareOp, if any, from a private mapping
PendingOperation *prepareOp = NULL;
if (created) {
mPriv->cache->put(Cache::Key(proxyProxy->busName(), proxyProxy->objectPath()), proxy);
prepareOp = prepare(proxy);
// TODO: insert to private prepare op mapping and make sure it's removed when it finishes/is
// destroyed
}
if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) {
return new PendingReady(prepareOp, specificFeatures, proxy, 0);
}
// No features requested or they are all ready - optimize a bit by not calling ReadinessHelper
PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0);
readyOp->setFinished();
return readyOp;
}
PendingOperation *DBusProxyFactory::prepare(const SharedPtr<RefCounted> &object) const
{
// Nothing we could think about needs doing
return NULL;
}
DBusProxyFactory::Cache::Cache()
{
}
DBusProxyFactory::Cache::~Cache()
{
}
SharedPtr<RefCounted> DBusProxyFactory::Cache::get(const Key &key) const
{
SharedPtr<RefCounted> counted(proxies.value(key));
// We already assert for it being a DBusProxy in put()
if (!counted || !dynamic_cast<DBusProxy *>(counted.data())->isValid()) {
// Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still
// haven't got the invalidated() signal for it
return SharedPtr<RefCounted>();
}
return counted;
}
void DBusProxyFactory::Cache::put(const Key &key, const SharedPtr<RefCounted> &obj)
{
DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(obj.data());
Q_ASSERT(proxyProxy != NULL);
// This sucks because DBusProxy is not RefCounted...
connect(proxyProxy,
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onProxyInvalidated(Tp::DBusProxy*)));
debug() << "Inserting to factory cache proxy for" << key;
proxies.insert(key, obj);
}
void DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy)
{
Key key(proxy->busName(), proxy->objectPath());
// Not having it would indicate invalidated() signaled twice for the same proxy, or us having
// connected to two proxies with the same key, neither of which should happen
Q_ASSERT(proxies.contains(key));
debug() << "Removing from factory cache invalidated proxy for" << key;
proxies.remove(key);
}
}
<|endoftext|>
|
<commit_before>//
// CoreScene.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
/**
\mainpage vtlib library documentation
\section overview Overview
The <b>vtlib</b> library is built on top of the <b>vtdata</b> library which
handles many kinds of geospatial data. It extends <b>vtdata</b> with the
ability to create 3D geometry of the data for interactive visualization.
It is part of the <a href="http://vterrain.org/">Virtual Terrain Project</a>
and distributed under a completely free <a href="../../license.txt">open
source license</a>.
<b>vtlib</b> contains an abstraction of a Scene Graph API, built on top of
OpenGL and other lower-level APIs such as OSG and SGL.
Because it is higher-level, <b>vtlib</b> lets you construct 3D geometry
and simulations much faster and easier than using the lower-level libraries
directly.
Some documentation for vtlib, and important discussion of how to use the
library, is <a href="http://vterrain.org/Implementation/Libs/vtlib.html">
online</a>.
This folder contains documentation of the classes and methods - see the
<a href="hierarchy.html">Class Hierarchy</a> or <a href="inherits.html">
graphical class hierarchy</a>.
*/
#include "vtlib/vtlib.h"
#include "vtlib/core/Engine.h"
vtWindow::vtWindow()
{
m_BgColor.Set(0.2f, 0.2f, 0.4f);
m_Size.Set(0, 0);
}
vtSceneBase::vtSceneBase()
{
m_pCamera = NULL;
m_pRoot = NULL;
m_pRootEngine = NULL;
m_piKeyState = NULL;
}
vtSceneBase::~vtSceneBase()
{
// cleanup engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
delete list[i];
m_pRootEngine = NULL;
}
void vtSceneBase::OnMouse(vtMouseEvent &event, vtWindow *pWindow)
{
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnMouse(event);
}
}
void vtSceneBase::OnKey(int key, int flags, vtWindow *pWindow)
{
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnKey(key, flags);
}
}
bool vtSceneBase::GetKeyState(int key)
{
if (m_piKeyState)
return m_piKeyState[key];
else
return false;
}
void vtSceneBase::SetWindowSize(int w, int h, vtWindow *pWindow)
{
if (!pWindow)
pWindow = GetWindow(0);
pWindow->SetSize(w, h);
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnWindowSize(w, h);
}
}
IPoint2 vtSceneBase::GetWindowSize(vtWindow *pWindow)
{
if (!pWindow)
pWindow = GetWindow(0);
return pWindow->GetSize();
}
void vtSceneBase::DoEngines()
{
// Evaluate Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled())
pEng->Eval();
}
}
// (for backward compatibility only)
void vtSceneBase::AddEngine(vtEngine *ptr)
{
if (m_pRootEngine)
m_pRootEngine->AddChild(ptr);
else
m_pRootEngine = ptr;
}
<commit_msg>be sure to traverse all engines when freeing them<commit_after>//
// CoreScene.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
/**
\mainpage vtlib library documentation
\section overview Overview
The <b>vtlib</b> library is built on top of the <b>vtdata</b> library which
handles many kinds of geospatial data. It extends <b>vtdata</b> with the
ability to create 3D geometry of the data for interactive visualization.
It is part of the <a href="http://vterrain.org/">Virtual Terrain Project</a>
and distributed under a completely free <a href="../../license.txt">open
source license</a>.
<b>vtlib</b> contains an abstraction of a Scene Graph API, built on top of
OpenGL and other lower-level APIs such as OSG and SGL.
Because it is higher-level, <b>vtlib</b> lets you construct 3D geometry
and simulations much faster and easier than using the lower-level libraries
directly.
Some documentation for vtlib, and important discussion of how to use the
library, is <a href="http://vterrain.org/Implementation/Libs/vtlib.html">
online</a>.
This folder contains documentation of the classes and methods - see the
<a href="hierarchy.html">Class Hierarchy</a> or <a href="inherits.html">
graphical class hierarchy</a>.
*/
#include "vtlib/vtlib.h"
#include "vtlib/core/Engine.h"
vtWindow::vtWindow()
{
m_BgColor.Set(0.2f, 0.2f, 0.4f);
m_Size.Set(0, 0);
}
vtSceneBase::vtSceneBase()
{
m_pCamera = NULL;
m_pRoot = NULL;
m_pRootEngine = NULL;
m_piKeyState = NULL;
}
vtSceneBase::~vtSceneBase()
{
// cleanup engines
vtEngineArray list(m_pRootEngine, false); // ALL engines
for (unsigned int i = 0; i < list.GetSize(); i++)
delete list[i];
m_pRootEngine = NULL;
}
void vtSceneBase::OnMouse(vtMouseEvent &event, vtWindow *pWindow)
{
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnMouse(event);
}
}
void vtSceneBase::OnKey(int key, int flags, vtWindow *pWindow)
{
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnKey(key, flags);
}
}
bool vtSceneBase::GetKeyState(int key)
{
if (m_piKeyState)
return m_piKeyState[key];
else
return false;
}
void vtSceneBase::SetWindowSize(int w, int h, vtWindow *pWindow)
{
if (!pWindow)
pWindow = GetWindow(0);
pWindow->SetSize(w, h);
// Pass event to Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled() &&
(pEng->GetWindow() == NULL || pEng->GetWindow() == pWindow))
pEng->OnWindowSize(w, h);
}
}
IPoint2 vtSceneBase::GetWindowSize(vtWindow *pWindow)
{
if (!pWindow)
pWindow = GetWindow(0);
return pWindow->GetSize();
}
void vtSceneBase::DoEngines()
{
// Evaluate Engines
vtEngineArray list(m_pRootEngine);
for (unsigned int i = 0; i < list.GetSize(); i++)
{
vtEngine *pEng = list[i];
if (pEng->GetEnabled())
pEng->Eval();
}
}
// (for backward compatibility only)
void vtSceneBase::AddEngine(vtEngine *ptr)
{
if (m_pRootEngine)
m_pRootEngine->AddChild(ptr);
else
m_pRootEngine = ptr;
}
<|endoftext|>
|
<commit_before>#include <stm32f0xx_rcc.h>
#include <core_cm0.h>
uint32_t guTickFactor;
uint32_t gmTickFactor;
struct AutoInitSysTick
{
AutoInitSysTick()
{
//update SystemCoreClock to the right frequency
SystemCoreClockUpdate();
//set ms and us factor
guTickFactor = SystemCoreClock / 1000000;
gmTickFactor = SystemCoreClock / 1000;
//enable systick
SysTick->LOAD = 0xffffffff;
SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_CLKSOURCE_Msk; //processor clock
}
};
AutoInitSysTick gAutoInitSysTick;
namespace clock
{
uint32_t getTickCount()
{
return SysTick->VAL;
}
void decrease_ticks(uint32_t nbTicks)
{
uint16_t PreviousTickCounter = getTickCount();
uint16_t CurrentTickCounter;
//ticks count in one iteration
uint16_t elapseTicks = 0;
while( nbTicks > elapseTicks)
{
//decrease total ticks counter
nbTicks -= elapseTicks;
//calculate ticks count between now and previous iteration
CurrentTickCounter = getTickCount();
elapseTicks = PreviousTickCounter - CurrentTickCounter;
PreviousTickCounter = CurrentTickCounter;
}
}
void usleep(unsigned int nTime)
{
//ticks count for the requested time
decrease_ticks(nTime * guTickFactor);
}
void msleep(unsigned int nTime)
{
//ticks count for the requested time
decrease_ticks(nTime * gmTickFactor);
}
unsigned int getTickPerMs()
{
return gmTickFactor;
}
unsigned int getTickPerUs()
{
return guTickFactor;
}
}
<commit_msg>(HAL ST) Add elapsedMicros method.<commit_after>#include <stm32f0xx_rcc.h>
#include <core_cm0.h>
uint32_t guTickFactor;
uint32_t gmTickFactor;
struct AutoInitSysTick
{
AutoInitSysTick()
{
//update SystemCoreClock to the right frequency
SystemCoreClockUpdate();
//set ms and us factor
guTickFactor = SystemCoreClock / 1000000;
gmTickFactor = SystemCoreClock / 1000;
//enable systick
SysTick->LOAD = 0xffffffff;
SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_CLKSOURCE_Msk; //processor clock
}
};
AutoInitSysTick gAutoInitSysTick;
namespace clock
{
uint32_t getTickCount()
{
return SysTick->VAL;
}
void decrease_ticks(uint32_t nbTicks)
{
uint16_t PreviousTickCounter = getTickCount();
uint16_t CurrentTickCounter;
//ticks count in one iteration
uint16_t elapseTicks = 0;
while( nbTicks > elapseTicks)
{
//decrease total ticks counter
nbTicks -= elapseTicks;
//calculate ticks count between now and previous iteration
CurrentTickCounter = getTickCount();
elapseTicks = PreviousTickCounter - CurrentTickCounter;
PreviousTickCounter = CurrentTickCounter;
}
}
uint32_t elapsedMicros(unsigned int PreviousTickCounter)
{
uint32_t CurrentTickCounter = getTickCount();
uint32_t elapseTicks;
if (CurrentTickCounter > PreviousTickCounter)
{
elapseTicks = 0xFFFFFF - (CurrentTickCounter - PreviousTickCounter);
}
else
{
elapseTicks = PreviousTickCounter - CurrentTickCounter;
}
return (elapseTicks/guTickFactor);
}
void usleep(unsigned int nTime)
{
//ticks count for the requested time
decrease_ticks(nTime * guTickFactor);
}
void msleep(unsigned int nTime)
{
//ticks count for the requested time
decrease_ticks(nTime * gmTickFactor);
}
unsigned int getTickPerMs()
{
return gmTickFactor;
}
unsigned int getTickPerUs()
{
return guTickFactor;
}
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX600 グループ・IWDT 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2021 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 独立ウォッチドッグタイマクラス
@param[in] base ベース・アドレス
@param[in] per ペリフェラル型
@param[in] ivec 割り込み要因
@param[in] pclk マスタークロック
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
struct iwdt_t {
static constexpr auto PERIPHERAL = per; ///< ペリフェラル型
static constexpr auto IVEC = ivec; ///< 割り込みベクター
static constexpr auto PCLK = pclk; ///< マスタークロック周波数
//-----------------------------------------------------------------//
/*!
@brief IWDT リフレッシュレジスタ(IWDTRR)
*/
//-----------------------------------------------------------------//
typedef rw8_t<base + 0x00> IWDTRR_;
static IWDTRR_ IWDTRR;
//-----------------------------------------------------------------//
/*!
@brief IWDT コントロールレジスタ(IWDTCR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtcr_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> TOPS;
bits_rw_t<io_, bitpos::B4, 4> CKS;
bits_rw_t<io_, bitpos::B8, 2> RPES;
bits_rw_t<io_, bitpos::B12, 2> RPSS;
};
typedef iwdtcr_t<base + 0x02> IWDTCR_;
static IWDTCR_ IWDTCR;
//-----------------------------------------------------------------//
/*!
@brief IWDT ステータスレジスタ(IWDTSR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtsr_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_ro_t<io_, bitpos::B0, 14> CNTVAL;
bit_rw_t <io_, bitpos::B14> UNDFF;
bit_rw_t <io_, bitpos::B15> REFEF;
};
typedef iwdtsr_t<base + 0x04> IWDTSR_;
static IWDTSR_ IWDTSR;
//-----------------------------------------------------------------//
/*!
@brief IWDT リセットコントロールレジスタ(IWDTRCR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtrcr_t : public rw8_t<ofs> {
typedef rw8_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B7> RSTIRQS;
};
typedef iwdtrcr_t<base + 0x06> IWDTRCR_;
static IWDTRCR_ IWDTRCR;
//-----------------------------------------------------------------//
/*!
@brief IWDT カウント停止コントロールレジスタ(IWDTCSTPR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtcstpr_t : public rw8_t<ofs> {
typedef rw8_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B7> SLCSTP;
};
typedef iwdtcstpr_t<base + 0x08> IWDTCSTPR_;
static IWDTCSTPR_ IWDTCSTPR;
};
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTRR_ iwdt_t<base, per, ivec, pclk>::IWDTRR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTCR_ iwdt_t<base, per, ivec, pclk>::IWDTCR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTSR_ iwdt_t<base, per, ivec, pclk>::IWDTSR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTRCR_ iwdt_t<base, per, ivec, pclk>::IWDTRCR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTCSTPR_ iwdt_t<base, per, ivec, pclk>::IWDTCSTPR;
#if defined(SIG_RX24T)
// interrupt vector: for NMI vector
typedef iwdt_t<0x00088030, peripheral::IWDT, ICU::VECTOR::NONE, 15'000> IWDT;
#else
typedef iwdt_t<0x00088030, peripheral::IWDT, ICU::VECTOR::IWUNI, 120'000> IWDT;
#endif
}
<commit_msg>Update: Add/Support RX621/RX62N<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX600 グループ・IWDT 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2022 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 独立ウォッチドッグタイマクラス
@param[in] base ベース・アドレス
@param[in] per ペリフェラル型
@param[in] ivec 割り込み要因
@param[in] pclk マスタークロック
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
struct iwdt_t {
static constexpr auto PERIPHERAL = per; ///< ペリフェラル型
static constexpr auto IVEC = ivec; ///< 割り込みベクター
static constexpr auto PCLK = pclk; ///< マスタークロック周波数
//-----------------------------------------------------------------//
/*!
@brief IWDT リフレッシュレジスタ(IWDTRR)
*/
//-----------------------------------------------------------------//
typedef rw8_t<base + 0x00> IWDTRR_;
static IWDTRR_ IWDTRR;
//-----------------------------------------------------------------//
/*!
@brief IWDT コントロールレジスタ(IWDTCR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtcr_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> TOPS;
bits_rw_t<io_, bitpos::B4, 4> CKS;
bits_rw_t<io_, bitpos::B8, 2> RPES;
bits_rw_t<io_, bitpos::B12, 2> RPSS;
};
typedef iwdtcr_t<base + 0x02> IWDTCR_;
static IWDTCR_ IWDTCR;
//-----------------------------------------------------------------//
/*!
@brief IWDT ステータスレジスタ(IWDTSR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtsr_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_ro_t<io_, bitpos::B0, 14> CNTVAL;
bit_rw_t <io_, bitpos::B14> UNDFF;
bit_rw_t <io_, bitpos::B15> REFEF;
};
typedef iwdtsr_t<base + 0x04> IWDTSR_;
static IWDTSR_ IWDTSR;
//-----------------------------------------------------------------//
/*!
@brief IWDT リセットコントロールレジスタ(IWDTRCR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtrcr_t : public rw8_t<ofs> {
typedef rw8_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B7> RSTIRQS;
};
typedef iwdtrcr_t<base + 0x06> IWDTRCR_;
static IWDTRCR_ IWDTRCR;
//-----------------------------------------------------------------//
/*!
@brief IWDT カウント停止コントロールレジスタ(IWDTCSTPR)
@param[in] ofs レジスタ・オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct iwdtcstpr_t : public rw8_t<ofs> {
typedef rw8_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B7> SLCSTP;
};
typedef iwdtcstpr_t<base + 0x08> IWDTCSTPR_;
static IWDTCSTPR_ IWDTCSTPR;
};
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTRR_ iwdt_t<base, per, ivec, pclk>::IWDTRR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTCR_ iwdt_t<base, per, ivec, pclk>::IWDTCR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTSR_ iwdt_t<base, per, ivec, pclk>::IWDTSR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTRCR_ iwdt_t<base, per, ivec, pclk>::IWDTRCR;
template <uint32_t base, peripheral per, ICU::VECTOR ivec, uint32_t pclk>
typename iwdt_t<base, per, ivec, pclk>::IWDTCSTPR_ iwdt_t<base, per, ivec, pclk>::IWDTCSTPR;
#if defined(SIG_RX621) || defined(SIG_RX62N)
typedef iwdt_t<0x00088030, peripheral::IWDT, ICU::VECTOR::NONE, 125'000> IWDT;
#elif defined(SIG_RX24T)
// interrupt vector: for NMI vector
typedef iwdt_t<0x00088030, peripheral::IWDT, ICU::VECTOR::NONE, 15'000> IWDT;
#else
typedef iwdt_t<0x00088030, peripheral::IWDT, ICU::VECTOR::IWUNI, 120'000> IWDT;
#endif
}
<|endoftext|>
|
<commit_before>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005
// Bindings
#include "PyROOT.h"
#include "PyRootType.h"
#include "RootWrapper.h"
#include "Adapters.h"
// Standard
#include <string.h>
#include <string>
namespace PyROOT {
namespace {
//= PyROOT type proxy construction/destruction ===============================
PyObject* meta_alloc( PyTypeObject* metatype, Py_ssize_t nitems )
{
// specialized allocator, fitting in a few extra bytes for a TClassRef
int basicsize = metatype->tp_basicsize;
metatype->tp_basicsize = sizeof(PyRootClass);
PyObject* pyclass = PyType_Type.tp_alloc( metatype, nitems );
metatype->tp_basicsize = basicsize;
return pyclass;
}
//____________________________________________________________________________
void meta_dealloc( PyRootClass* pytype )
{
pytype->fClass.~TClassRef();
return PyType_Type.tp_dealloc( (PyObject*)pytype );
}
//____________________________________________________________________________
PyObject* pt_new( PyTypeObject* subtype, PyObject* args, PyObject* kwds )
{
// Called when PyRootType acts as a metaclass; since type_new always resets
// tp_alloc, and since it does not call tp_init on types, the metaclass is
// being fixed up here, and the class is initialized here as well.
// fixup of metaclass (left permanent, and in principle only called once b/c
// PyROOT caches python classes)
subtype->tp_alloc = (allocfunc)meta_alloc;
subtype->tp_dealloc = (destructor)meta_dealloc;
// creation of the python-side class
PyRootClass* result = (PyRootClass*)PyType_Type.tp_new( subtype, args, kwds );
// initialization of class (based on name only, initially, which is lazy)
// there's a snag here: if a python class is derived from the bound class,
// the name will not be known by TClassRef, hence we'll use the meta class
// name from the subtype, rather than given class name
const char* mp = strstr( subtype->tp_name, "_meta" );
if ( ! mp ) {
// there has been a user meta class override in a derived class, so do
// the consistent thing, thus allowing user control over naming
new (&result->fClass) TClassRef( PyString_AS_STRING( PyTuple_GET_ITEM( args, 0 ) ) );
} else {
// coming here from PyROOT, use meta class name instead of given name,
// so that it is safe to inherit python classes from the bound class
new (&result->fClass) TClassRef( std::string( subtype->tp_name ).substr( 0, mp-subtype->tp_name ).c_str() );
}
return (PyObject*)result;
}
//= PyROOT type metaclass behavior ===========================================
PyObject* pt_getattro( PyObject* pyclass, PyObject* pyname )
{
// normal type lookup
PyObject* attr = PyType_Type.tp_getattro( pyclass, pyname );
// extra ROOT lookup in case of failure (e.g. for inner classes on demand)
if ( ! attr && PyString_CheckExact( pyname ) ) {
PyObject *etype, *value, *trace;
PyErr_Fetch( &etype, &value, &trace ); // clears current exception
// filter for python specials and lookup qualified class or function
std::string name = PyString_AS_STRING( pyname );
if ( name.size() <= 2 || name.substr( 0, 2 ) != "__" ) {
attr = MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( name, pyclass );
if ( ! attr ) {
PyErr_Clear();
// get class name to look up CINT tag info ...
attr = GetRootGlobalFromString( name /*, tag */ );
}
}
// if failed, then the original error is likely to be more instructive
if ( ! attr )
PyErr_Restore( etype, value, trace );
// attribute is cached, if found
}
return attr;
}
} // unnamed namespace
//= PyROOT object proxy type type ============================================
PyTypeObject PyRootType_Type = {
PyObject_HEAD_INIT( &PyType_Type )
0, // ob_size
(char*)"ROOT.PyRootType", // tp_name
0, // tp_basicsize
0, // tp_itemsize
0, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
(getattrofunc)pt_getattro, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
(char*)"PyROOT metatype (internal)", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
&PyType_Type, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
(newfunc)pt_new, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0 // tp_weaklist
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3
, 0 // tp_del
#endif
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6
, 0 // tp_version_tag
#endif
};
} // namespace PyROOT
<commit_msg>cache free functions in their namespace<commit_after>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005
// Bindings
#include "PyROOT.h"
#include "PyRootType.h"
#include "RootWrapper.h"
#include "Adapters.h"
// Standard
#include <string.h>
#include <string>
namespace PyROOT {
namespace {
//= PyROOT type proxy construction/destruction ===============================
PyObject* meta_alloc( PyTypeObject* metatype, Py_ssize_t nitems )
{
// specialized allocator, fitting in a few extra bytes for a TClassRef
int basicsize = metatype->tp_basicsize;
metatype->tp_basicsize = sizeof(PyRootClass);
PyObject* pyclass = PyType_Type.tp_alloc( metatype, nitems );
metatype->tp_basicsize = basicsize;
return pyclass;
}
//____________________________________________________________________________
void meta_dealloc( PyRootClass* pytype )
{
pytype->fClass.~TClassRef();
return PyType_Type.tp_dealloc( (PyObject*)pytype );
}
//____________________________________________________________________________
PyObject* pt_new( PyTypeObject* subtype, PyObject* args, PyObject* kwds )
{
// Called when PyRootType acts as a metaclass; since type_new always resets
// tp_alloc, and since it does not call tp_init on types, the metaclass is
// being fixed up here, and the class is initialized here as well.
// fixup of metaclass (left permanent, and in principle only called once b/c
// PyROOT caches python classes)
subtype->tp_alloc = (allocfunc)meta_alloc;
subtype->tp_dealloc = (destructor)meta_dealloc;
// creation of the python-side class
PyRootClass* result = (PyRootClass*)PyType_Type.tp_new( subtype, args, kwds );
// initialization of class (based on name only, initially, which is lazy)
// there's a snag here: if a python class is derived from the bound class,
// the name will not be known by TClassRef, hence we'll use the meta class
// name from the subtype, rather than given class name
const char* mp = strstr( subtype->tp_name, "_meta" );
if ( ! mp ) {
// there has been a user meta class override in a derived class, so do
// the consistent thing, thus allowing user control over naming
new (&result->fClass) TClassRef( PyString_AS_STRING( PyTuple_GET_ITEM( args, 0 ) ) );
} else {
// coming here from PyROOT, use meta class name instead of given name,
// so that it is safe to inherit python classes from the bound class
new (&result->fClass) TClassRef( std::string( subtype->tp_name ).substr( 0, mp-subtype->tp_name ).c_str() );
}
return (PyObject*)result;
}
//= PyROOT type metaclass behavior ===========================================
PyObject* pt_getattro( PyObject* pyclass, PyObject* pyname )
{
// normal type lookup
PyObject* attr = PyType_Type.tp_getattro( pyclass, pyname );
// extra ROOT lookup in case of failure (e.g. for inner classes on demand)
if ( ! attr && PyString_CheckExact( pyname ) ) {
PyObject *etype, *value, *trace;
PyErr_Fetch( &etype, &value, &trace ); // clears current exception
// filter for python specials and lookup qualified class or function
std::string name = PyString_AS_STRING( pyname );
if ( name.size() <= 2 || name.substr( 0, 2 ) != "__" ) {
attr = MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( name, pyclass );
if ( ! attr ) {
PyErr_Clear();
// get class name to look up CINT tag info ...
attr = GetRootGlobalFromString( name /*, tag */ );
if ( attr )
PyObject_SetAttr( pyclass, pyname, attr );
}
}
// if failed, then the original error is likely to be more instructive
if ( ! attr )
PyErr_Restore( etype, value, trace );
// attribute is cached, if found
}
return attr;
}
} // unnamed namespace
//= PyROOT object proxy type type ============================================
PyTypeObject PyRootType_Type = {
PyObject_HEAD_INIT( &PyType_Type )
0, // ob_size
(char*)"ROOT.PyRootType", // tp_name
0, // tp_basicsize
0, // tp_itemsize
0, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
(getattrofunc)pt_getattro, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
(char*)"PyROOT metatype (internal)", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
&PyType_Type, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
(newfunc)pt_new, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0 // tp_weaklist
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3
, 0 // tp_del
#endif
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6
, 0 // tp_version_tag
#endif
};
} // namespace PyROOT
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Rasterizer.h"
using namespace std;
using namespace glm;
using namespace softlit;
Rasterizer::Rasterizer(const RasterizerSetup& setup)
: m_setup(setup)
{
m_frameBuffer.resize(m_setup.viewport.width * m_setup.viewport.height);
m_depthBuffer.resize(m_setup.viewport.width * m_setup.viewport.height);
}
Rasterizer::~Rasterizer()
{
m_frameBuffer.clear();
m_depthBuffer.clear();
}
/*
- v1
- - - -
vo - - - v2
*/
inline float Rasterizer::PixelCoverage(const vec2& a, const vec2& b, const vec2& c) const
{
const int winding = (m_setup.vertexWinding == VertexWinding::COUNTER_CLOCKWISE) ? 1 : -1;
const float x = (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);
return winding * x;
}
void Rasterizer::SetupTriangle(Primitive* prim, const uint64_t idx, glm::vec3& v0, glm::vec3& v1, glm::vec3& v2) const
{
const VertexBuffer& vbo = prim->getVertexBuffer();
const IndexBuffer& ibo = prim->getIndexBuffer();
v0 = vbo[ibo[idx * 3]];
v1 = vbo[ibo[idx * 3 + 1]];
v2 = vbo[ibo[idx * 3 + 2]];
}
bool softlit::Rasterizer::Clip2D(const glm::vec2 & v0, const glm::vec2 & v1, const glm::vec2 & v2, Viewport& vp) const
{
float xmin = fminf(v0.x, fminf(v1.x, v2.x));
float xmax = fmaxf(v0.x, fmaxf(v1.x, v2.x));
float ymin = fminf(v0.y, fminf(v1.y, v2.y));
float ymax = fmaxf(v0.y, fmaxf(v1.y, v2.y));
// Early-out when viewport bounds exceeded
if (xmin + 1 > m_setup.viewport.width || xmax < 0 || ymin + 1 > m_setup.viewport.height || ymax < 0) return false;
vp.x = max<int>(0, (int32_t)xmin);
vp.width = min<int>(m_setup.viewport.width - 1, (int32_t)xmax);
vp.y = max<int>(0, (int32_t)ymin);
vp.height = min<int>(m_setup.viewport.height - 1, (int32_t)ymax);
return true;
}
void Rasterizer::InterpolateAttributes(const float u, const float v, const float w, const Vertex_OUT& out0, const Vertex_OUT& out1, const Vertex_OUT& out2, Vertex_OUT& attribs) const
{
if (!out0.attrib_vec4.empty())
{
DBG_ASSERT(!out1.attrib_vec4.empty());
DBG_ASSERT(!out2.attrib_vec4.empty());
DBG_ASSERT(out0.attrib_vec4.size() == out2.attrib_vec4.size());
DBG_ASSERT(out1.attrib_vec4.size() == out2.attrib_vec4.size());
for (int i = 0; i < out0.attrib_vec4.size(); i++)
{
const vec4& attr0 = out0.attrib_vec4[i];
const vec4& attr1 = out1.attrib_vec4[i];
const vec4& attr2 = out2.attrib_vec4[i];
vec4 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
if (!out0.attrib_vec3.empty())
{
DBG_ASSERT(!out1.attrib_vec3.empty());
DBG_ASSERT(!out2.attrib_vec3.empty());
DBG_ASSERT(out0.attrib_vec3.size() == out2.attrib_vec3.size());
DBG_ASSERT(out1.attrib_vec3.size() == out2.attrib_vec3.size());
for (int i = 0; i < out0.attrib_vec3.size(); i++)
{
const vec3& attr0 = out0.attrib_vec3[i];
const vec3& attr1 = out1.attrib_vec3[i];
const vec3& attr2 = out2.attrib_vec3[i];
vec3 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
if (!out0.attrib_vec2.empty())
{
DBG_ASSERT(!out1.attrib_vec2.empty());
DBG_ASSERT(!out2.attrib_vec2.empty());
DBG_ASSERT(out0.attrib_vec2.size() == out2.attrib_vec2.size());
DBG_ASSERT(out1.attrib_vec2.size() == out2.attrib_vec2.size());
for (int i = 0; i < out0.attrib_vec2.size(); i++)
{
const vec2& attr0 = out0.attrib_vec2[i];
const vec2& attr1 = out1.attrib_vec2[i];
const vec2& attr2 = out2.attrib_vec2[i];
vec2 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
}
void Rasterizer::FetchVertexAttributes(const VertexAttributes& attribs, const uint64_t idx, Vertex_IN& in0, Vertex_IN& in1, Vertex_IN& in2) const
{
// Fetch attributes of type vec4
if (!attribs.attrib_vec4.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec4.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3 + 2]);
}
}
// Fetch attributes of type vec3
if (!attribs.attrib_vec3.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec3.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3 + 2]);
}
}
// Fetch attributes of type vec2
if (!attribs.attrib_vec2.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec2.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3 + 2]);
}
}
}
void Rasterizer::Draw(Primitive* prim)
{
// Only raster primitive is triangle
const uint64_t numTris = prim->getIndexBuffer().size() / 3;
DBG_ASSERT((prim->getIndexBuffer().size() % 3) == 0);
// Re-use VS attributes per primitive
Vertex_IN in0, in1, in2;
Vertex_OUT out0, out1, out2;
// Re-use FS attributes per primitive
Vertex_OUT FS_attribs;
for (uint64_t i = 0; i < numTris; i++)
{
vec3 v0, v1, v2;
SetupTriangle(prim, i, v0, v1, v2);
const vertex_shader VS = prim->getVS();
DBG_ASSERT(VS && "invalid vertex_shader!");
UniformBuffer ubo = prim->UBO();
in0.ResetData(); in1.ResetData(); in2.ResetData();
out0.ResetData(); out1.ResetData(); out2.ResetData();
FetchVertexAttributes(prim->getVertexAttributes(), i, in0, in1, in2);
// Execute VS for each vertex
const vec4 v0Clip = VS(v0, ubo, &in0, &out0);
const vec4 v1Clip = VS(v1, ubo, &in1, &out1);
const vec4 v2Clip = VS(v2, ubo, &in2, &out2);
const float oneOverW0 = 1.f / v0Clip.w;
const float oneOverW1 = 1.f / v1Clip.w;
const float oneOverW2 = 1.f / v2Clip.w;
// Perspective-divide and convert to NDC
const vec3 v0NDC = v0Clip * oneOverW0;
const vec3 v1NDC = v1Clip * oneOverW1;
const vec3 v2NDC = v2Clip * oneOverW2;
// Now to frame buffer-coordinates
vec2 v0Raster = { (v0NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v0NDC.y) / 2 * m_setup.viewport.height };
vec2 v1Raster = { (v1NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v1NDC.y) / 2 * m_setup.viewport.height };
vec2 v2Raster = { (v2NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v2NDC.y) / 2 * m_setup.viewport.height };
const float triCoverage = PixelCoverage(v0Raster, v1Raster, v2Raster);
if (prim->getPrimitiveSetup().cullMode == CullMode::CULL_BACK &&
(triCoverage > 0 && m_setup.vertexWinding == VertexWinding::CLOCKWISE) ||
(triCoverage < 0 && m_setup.vertexWinding == VertexWinding::COUNTER_CLOCKWISE)) continue;
Viewport vp;
if (!Clip2D(v0Raster, v1Raster, v2Raster, vp)) continue;
// Triangle traversal
for (uint32_t y = vp.y; y <= vp.height; y++)
{
for (uint32_t x = vp.x; x <= vp.width; x++)
{
vec2 sample = { x + 0.5f, y + 0.5f };
float w0 = PixelCoverage(v1Raster, v2Raster, sample);
float w1 = PixelCoverage(v2Raster, v0Raster, sample);
float w2 = PixelCoverage(v0Raster, v1Raster, sample);
if (w0 >= 0 && w1 >= 0 && w2 >= 0)
{
w0 /= triCoverage;
w1 /= triCoverage;
w2 = 1.f - w0 - w1;
// Interpolate depth
float z = ((w0 * v0NDC.z) + (w1 * v1NDC.z) + (w2 * v2NDC.z));
if (z < m_depthBuffer[y * m_setup.viewport.width + x]) // Depth test; execute FS if passed & update z-buffer
{
m_depthBuffer[y * m_setup.viewport.width + x] = z;
FS_attribs.ResetData(); // Reset attribs pre-FS for each fragment
const float f0 = w0 * oneOverW0;
const float f1 = w1 * oneOverW1;
const float f2 = w2 * oneOverW2;
// Calc barycentric coordinates for perspectively-correct interpolation
const float u = f0 / (f0 + f1 + f2);
const float v = f1 / (f0 + f1 + f2);
const float w = 1.f - u - v;
InterpolateAttributes(u, v, w, out0, out1, out2, FS_attribs);
const fragment_shader FS = prim->getFS();
const vec4 final_fragment = FS(ubo, &FS_attribs);
m_frameBuffer[y * m_setup.viewport.width + x] = final_fragment;
}
}
}
}
}
}<commit_msg>Resolved shared edges using tiebreaker rule<commit_after>#include "stdafx.h"
#include "Rasterizer.h"
using namespace std;
using namespace glm;
using namespace softlit;
Rasterizer::Rasterizer(const RasterizerSetup& setup)
: m_setup(setup)
{
m_frameBuffer.resize(m_setup.viewport.width * m_setup.viewport.height);
m_depthBuffer.resize(m_setup.viewport.width * m_setup.viewport.height);
}
Rasterizer::~Rasterizer()
{
m_frameBuffer.clear();
m_depthBuffer.clear();
}
/*
- v1
- - - -
vo - - - v2
*/
inline float Rasterizer::PixelCoverage(const vec2& a, const vec2& b, const vec2& c) const
{
const int winding = (m_setup.vertexWinding == VertexWinding::COUNTER_CLOCKWISE) ? 1 : -1;
const float x = (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);
return winding * x;
}
void Rasterizer::SetupTriangle(Primitive* prim, const uint64_t idx, glm::vec3& v0, glm::vec3& v1, glm::vec3& v2) const
{
const VertexBuffer& vbo = prim->getVertexBuffer();
const IndexBuffer& ibo = prim->getIndexBuffer();
v0 = vbo[ibo[idx * 3]];
v1 = vbo[ibo[idx * 3 + 1]];
v2 = vbo[ibo[idx * 3 + 2]];
}
bool softlit::Rasterizer::Clip2D(const glm::vec2 & v0, const glm::vec2 & v1, const glm::vec2 & v2, Viewport& vp) const
{
float xmin = fminf(v0.x, fminf(v1.x, v2.x));
float xmax = fmaxf(v0.x, fmaxf(v1.x, v2.x));
float ymin = fminf(v0.y, fminf(v1.y, v2.y));
float ymax = fmaxf(v0.y, fmaxf(v1.y, v2.y));
// Early-out when viewport bounds exceeded
if (xmin + 1 > m_setup.viewport.width || xmax < 0 || ymin + 1 > m_setup.viewport.height || ymax < 0) return false;
vp.x = max<int>(0, (int32_t)xmin);
vp.width = min<int>(m_setup.viewport.width - 1, (int32_t)xmax);
vp.y = max<int>(0, (int32_t)ymin);
vp.height = min<int>(m_setup.viewport.height - 1, (int32_t)ymax);
return true;
}
void Rasterizer::InterpolateAttributes(const float u, const float v, const float w, const Vertex_OUT& out0, const Vertex_OUT& out1, const Vertex_OUT& out2, Vertex_OUT& attribs) const
{
if (!out0.attrib_vec4.empty())
{
DBG_ASSERT(!out1.attrib_vec4.empty());
DBG_ASSERT(!out2.attrib_vec4.empty());
DBG_ASSERT(out0.attrib_vec4.size() == out2.attrib_vec4.size());
DBG_ASSERT(out1.attrib_vec4.size() == out2.attrib_vec4.size());
for (int i = 0; i < out0.attrib_vec4.size(); i++)
{
const vec4& attr0 = out0.attrib_vec4[i];
const vec4& attr1 = out1.attrib_vec4[i];
const vec4& attr2 = out2.attrib_vec4[i];
vec4 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
if (!out0.attrib_vec3.empty())
{
DBG_ASSERT(!out1.attrib_vec3.empty());
DBG_ASSERT(!out2.attrib_vec3.empty());
DBG_ASSERT(out0.attrib_vec3.size() == out2.attrib_vec3.size());
DBG_ASSERT(out1.attrib_vec3.size() == out2.attrib_vec3.size());
for (int i = 0; i < out0.attrib_vec3.size(); i++)
{
const vec3& attr0 = out0.attrib_vec3[i];
const vec3& attr1 = out1.attrib_vec3[i];
const vec3& attr2 = out2.attrib_vec3[i];
vec3 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
if (!out0.attrib_vec2.empty())
{
DBG_ASSERT(!out1.attrib_vec2.empty());
DBG_ASSERT(!out2.attrib_vec2.empty());
DBG_ASSERT(out0.attrib_vec2.size() == out2.attrib_vec2.size());
DBG_ASSERT(out1.attrib_vec2.size() == out2.attrib_vec2.size());
for (int i = 0; i < out0.attrib_vec2.size(); i++)
{
const vec2& attr0 = out0.attrib_vec2[i];
const vec2& attr1 = out1.attrib_vec2[i];
const vec2& attr2 = out2.attrib_vec2[i];
vec2 attrib = u * attr0 + v * attr1 + w * attr2;
attribs.PushVertexAttribute(attrib);
}
}
}
void Rasterizer::FetchVertexAttributes(const VertexAttributes& attribs, const uint64_t idx, Vertex_IN& in0, Vertex_IN& in1, Vertex_IN& in2) const
{
// Fetch attributes of type vec4
if (!attribs.attrib_vec4.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec4.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec4[i][idx * 3 + 2]);
}
}
// Fetch attributes of type vec3
if (!attribs.attrib_vec3.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec3.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec3[i][idx * 3 + 2]);
}
}
// Fetch attributes of type vec2
if (!attribs.attrib_vec2.empty()) // At least one vec4 attribute buffer created
{
for (int i = 0; i < attribs.attrib_vec2.size(); i++)
{
in0.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3]);
in1.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3 + 1]);
in2.PushVertexAttribute(attribs.attrib_vec2[i][idx * 3 + 2]);
}
}
}
void Rasterizer::Draw(Primitive* prim)
{
// Only raster primitive is triangle
const uint64_t numTris = prim->getIndexBuffer().size() / 3;
DBG_ASSERT((prim->getIndexBuffer().size() % 3) == 0);
// Re-use VS attributes per primitive
Vertex_IN in0, in1, in2;
Vertex_OUT out0, out1, out2;
// Re-use FS attributes per primitive
Vertex_OUT FS_attribs;
for (uint64_t i = 0; i < numTris; i++)
{
vec3 v0, v1, v2;
SetupTriangle(prim, i, v0, v1, v2);
const vertex_shader VS = prim->getVS();
DBG_ASSERT(VS && "invalid vertex_shader!");
UniformBuffer ubo = prim->UBO();
in0.ResetData(); in1.ResetData(); in2.ResetData();
out0.ResetData(); out1.ResetData(); out2.ResetData();
FetchVertexAttributes(prim->getVertexAttributes(), i, in0, in1, in2);
// Execute VS for each vertex
const vec4 v0Clip = VS(v0, ubo, &in0, &out0);
const vec4 v1Clip = VS(v1, ubo, &in1, &out1);
const vec4 v2Clip = VS(v2, ubo, &in2, &out2);
const float oneOverW0 = 1.f / v0Clip.w;
const float oneOverW1 = 1.f / v1Clip.w;
const float oneOverW2 = 1.f / v2Clip.w;
// Perspective-divide and convert to NDC
const vec3 v0NDC = v0Clip * oneOverW0;
const vec3 v1NDC = v1Clip * oneOverW1;
const vec3 v2NDC = v2Clip * oneOverW2;
// Now to frame buffer-coordinates
vec2 v0Raster = { (v0NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v0NDC.y) / 2 * m_setup.viewport.height };
vec2 v1Raster = { (v1NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v1NDC.y) / 2 * m_setup.viewport.height };
vec2 v2Raster = { (v2NDC.x + 1) / 2 * m_setup.viewport.width, (1 - v2NDC.y) / 2 * m_setup.viewport.height };
const float triCoverage = PixelCoverage(v0Raster, v1Raster, v2Raster);
if (prim->getPrimitiveSetup().cullMode == CullMode::CULL_BACK &&
(triCoverage > 0 && m_setup.vertexWinding == VertexWinding::CLOCKWISE) ||
(triCoverage < 0 && m_setup.vertexWinding == VertexWinding::COUNTER_CLOCKWISE)) continue;
Viewport vp;
if (!Clip2D(v0Raster, v1Raster, v2Raster, vp)) continue;
// Store edges
const vec2 edge0 = v2 - v1;
const vec2 edge1 = v0 - v2;
const vec2 edge2 = v1 - v0;
// Pre-compute a flag for each edge to check for shared vertices and only include bottom/left edges
const bool t0 = (edge0.x != 0) ? (edge0.x > 0) : (edge0.y > 0);
const bool t1 = (edge1.x != 0) ? (edge1.x > 0) : (edge1.y > 0);
const bool t2 = (edge2.x != 0) ? (edge2.x > 0) : (edge2.y > 0);
// Triangle traversal
for (uint32_t y = vp.y; y <= vp.height; y++)
{
for (uint32_t x = vp.x; x <= vp.width; x++)
{
vec2 sample = { x + 0.5f, y + 0.5f };
// Evaluate edge functions on sample
float e0 = PixelCoverage(v1Raster, v2Raster, sample);
float e1 = PixelCoverage(v2Raster, v0Raster, sample);
float e2 = PixelCoverage(v0Raster, v1Raster, sample);
bool included = true;
included &= (e0 == 0) ? t0 : (e0 > 0);
included &= (e1 == 0) ? t1 : (e1 > 0);
included &= (e2 == 0) ? t2 : (e2 > 0);
if (included)
{
e0 /= triCoverage;
e1 /= triCoverage;
e2 = 1.f - e0 - e1;
// Interpolate depth
float z = (e0 * v0NDC.z) + (e1 * v1NDC.z) + (e2 * v2NDC.z);
if (z < m_depthBuffer[y * m_setup.viewport.width + x]) // Depth test; execute FS if passed & update z-buffer
{
m_depthBuffer[y * m_setup.viewport.width + x] = z;
FS_attribs.ResetData(); // Reset attribs pre-FS for each fragment
const float f0 = e0 * oneOverW0;
const float f1 = e1 * oneOverW1;
const float f2 = e2 * oneOverW2;
// Calc barycentric coordinates for perspectively-correct interpolation
const float u = f0 / (f0 + f1 + f2);
const float v = f1 / (f0 + f1 + f2);
const float w = 1.f - u - v;
InterpolateAttributes(u, v, w, out0, out1, out2, FS_attribs);
const fragment_shader FS = prim->getFS();
const vec4 final_fragment = FS(ubo, &FS_attribs);
m_frameBuffer[y * m_setup.viewport.width + x] = final_fragment;
}
}
}
}
}
}<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace boost { namespace python {
struct value_converter : public boost::static_visitor<PyObject*>
{
PyObject * operator() (int val) const
{
return ::PyInt_FromLong(val);
}
PyObject * operator() (double val) const
{
return ::PyFloat_FromDouble(val);
}
PyObject * operator() (UnicodeString const& s) const
{
int32_t len = s.length();
boost::scoped_array<wchar_t> buf(new wchar_t(len));
UErrorCode err = U_ZERO_ERROR;
u_strToWCS(buf.get(),len,0,s.getBuffer(),len,&err);
PyObject *obj = Py_None;
if (U_SUCCESS(err))
{
obj = ::PyUnicode_FromWideChar(buf.get(),implicit_cast<ssize_t>(len));
}
return obj;
}
PyObject * operator() (mapnik::value_null const& s) const
{
return NULL;
}
};
struct mapnik_value_to_python
{
static PyObject* convert(mapnik::value const& v)
{
return boost::apply_visitor(value_converter(),v.base());
}
};
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& cl)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}
}
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
std_pair_to_python_converter<std::string const,mapnik::value>();
to_python_converter<mapnik::value,mapnik_value_to_python>();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",no_init)
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
.add_property("properties",
make_function(&Feature::props,return_value_policy<reference_existing_object>()))
// .def("add_geometry", // TODO define more mapnik::Feature methods
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
;
class_<std::map<std::string, mapnik::value> >("Properties")
.def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >())
.def("iteritems",iterator<std::map<std::string,mapnik::value> > ())
;
}
<commit_msg>+ oops, fixed<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace boost { namespace python {
struct value_converter : public boost::static_visitor<PyObject*>
{
PyObject * operator() (int val) const
{
return ::PyInt_FromLong(val);
}
PyObject * operator() (double val) const
{
return ::PyFloat_FromDouble(val);
}
PyObject * operator() (UnicodeString const& s) const
{
int32_t len = s.length();
boost::scoped_array<wchar_t> buf(new wchar_t[len]);
UErrorCode err = U_ZERO_ERROR;
u_strToWCS(buf.get(),len,0,s.getBuffer(),len,&err);
PyObject *obj = Py_None;
if (U_SUCCESS(err))
{
obj = ::PyUnicode_FromWideChar(buf.get(),implicit_cast<ssize_t>(len));
}
return obj;
}
PyObject * operator() (mapnik::value_null const& s) const
{
return NULL;
}
};
struct mapnik_value_to_python
{
static PyObject* convert(mapnik::value const& v)
{
return boost::apply_visitor(value_converter(),v.base());
}
};
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& cl)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}
}
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
std_pair_to_python_converter<std::string const,mapnik::value>();
to_python_converter<mapnik::value,mapnik_value_to_python>();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",no_init)
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
.add_property("properties",
make_function(&Feature::props,return_value_policy<reference_existing_object>()))
// .def("add_geometry", // TODO define more mapnik::Feature methods
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
;
class_<std::map<std::string, mapnik::value> >("Properties")
.def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >())
.def("iteritems",iterator<std::map<std::string,mapnik::value> > ())
;
}
<|endoftext|>
|
<commit_before>#include "SCTPSocket.h"
#include "SocketUtils.h"
#include <netinet/in.h>
#include <poll.h>
using namespace NET;
SCTPSocket::SCTPSocket( unsigned numOutStreams /* = 10 */,
unsigned maxInStreams /* = 65535 */,
unsigned maxAttempts /* = 4 */,
unsigned maxInitTimeout /* = 0 */)
: InternetSocket( STREAM, IPPROTO_SCTP)
{
setInitValues( numOutStreams, maxInStreams, maxAttempts, maxInitTimeout);
}
SCTPSocket::SCTPSocket( Handle handle)
: InternetSocket( handle.m_sockfd)
{
if( handle.m_sockfd == 0)
throw SocketException("Tried to initialize SCTPSocket with invalid Handle");
}
int SCTPSocket::bind( const std::vector<std::string>& localAddresses, unsigned short localPort /* = 0 */)
{
sockaddr_in *dest = new sockaddr_in[localAddresses.size()];
int i = 0;
for( std::vector<std::string>::const_iterator it = localAddresses.begin(); it != localAddresses.end(); ++it) {
fillAddr( (*it), localPort, dest[i++]);
}
int ret = sctp_bindx( m_socket, reinterpret_cast<sockaddr*>(dest), localAddresses.size(), SCTP_BINDX_ADD_ADDR);
delete[] dest;
if(ret < 0)
throw SocketException("SCTPSocket::bind bindx failed");
return ret;
}
int SCTPSocket::connect( const std::vector<std::string>& foreignAddresses, unsigned short foreignPort /* = 0 */)
{
sockaddr_in *dest = new sockaddr_in[foreignAddresses.size()];
int i = 0;
for( std::vector<std::string>::const_iterator it = foreignAddresses.begin(); it != foreignAddresses.end(); ++it)
{
fillAddr( (*it), foreignPort, dest[i++]);
}
int ret = sctp_connectx( m_socket, reinterpret_cast<sockaddr*>(dest), foreignAddresses.size());
delete[] dest;
if(ret < 0)
throw SocketException("SCTPSocket::SCTPSocket connect failed");
}
int SCTPSocket::state() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::state failed");
return status.sstat_state;
}
int SCTPSocket::notAckedData() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::notAckedData failed");
return status.sstat_unackdata;
}
int SCTPSocket::pendingData() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::pendingData failed");
return status.sstat_penddata;
}
unsigned SCTPSocket::inStreams() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::inStreams failed");
return status.sstat_instrms;
}
unsigned SCTPSocket::outStreams() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::outStreams failed");
return status.sstat_outstrms;
}
unsigned SCTPSocket::fragmentationPoint() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if(getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::fragmentationPoint failed");
return status.sstat_fragmentation_point;
}
std::string SCTPSocket::primaryAddress() const
{
}
int SCTPSocket::send( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */,
unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */)
{
int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr, stream, ttl, context);
if( ret < 0)
throw SocketException("SCTPSocket::send failed");
else if (ret < length)
throw SocketException("Interpreted SCTP false, sent a packet fragement");
return ret;
}
int SCTPSocket::sendUnordered( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */,
unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */,
switchAddressFlag switchAddr /* = KEEP_PRIMARY */)
{
int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr + SCTP_UNORDERED, stream, ttl, context);
if( ret < 0)
throw SocketException("SCTPSocket::send failed");
else if (ret < length)
throw SocketException("Interpreted SCTP false, sent a packet fragement");
return ret;
}
int SCTPSocket::receive( void* data, int maxLen, unsigned& stream)
{
struct sctp_sndrcvinfo info;
int ret;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed");
stream = info.sinfo_stream;
return ret;
}
int SCTPSocket::receive( void* data, int maxLen, unsigned& stream, receiveFlag& flag)
{
struct sctp_sndrcvinfo info;
int ret;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed");
stream = info.sinfo_stream;
// flag = info.sinfo_flags;
return ret;
}
int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, unsigned timeout)
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0) return 0;
if( ret < 0)
throw SocketException("SCTPSocket::receive failed (poll)");
if( poll.revents & POLLIN || poll.revents & POLLRDHUP)
{
struct sctp_sndrcvinfo info;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed (receive)");
stream = info.sinfo_stream;
return ret;
}
if( poll.revents & POLLRDHUP)
{
m_peerDisconnected = true;
}
return 0;
}
int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, receiveFlag& flag, unsigned timeout)
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0) return 0;
if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)");
if( poll.revents & POLLIN || poll.revents & POLLRDHUP)
{
struct sctp_sndrcvinfo info;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed (receive)");
stream = info.sinfo_stream;
// flag = info.sinfo_flags;
return ret;
}
if( poll.revents & POLLRDHUP)
{
m_peerDisconnected = true;
}
return 0;
}
void SCTPSocket::listen( int backlog /* = 0 */)
{
::listen( m_socket, backlog);
}
SCTPSocket::Handle SCTPSocket::accept() const
{
int ret;
if( (ret = ::accept( m_socket, 0, 0)) <= 0)
throw SocketException("SCTPSocket::accept failed");
return Handle(ret);
}
SCTPSocket::Handle SCTPSocket::timedAccept( unsigned timeout) const
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0)
return Handle(0);
if( ret < 0)
throw SocketException("SCTPSocket::timedAccept failed(poll)");
if( (ret = ::accept( m_socket, 0, 0)) <= 0)
throw SocketException("SCTPSocket::timedAccept failed (accept)");
return Handle(ret);
}
void SCTPSocket::setInitValues( unsigned numOutStreams, unsigned maxInStreams, unsigned maxAttempts, unsigned maxInitTimeout)
{
struct sctp_initmsg init;
init.sinit_num_ostreams = numOutStreams;
init.sinit_max_instreams = maxInStreams;
init.sinit_max_attempts = maxAttempts;
init.sinit_max_init_timeo = maxInitTimeout;
::setsockopt( m_socket, IPPROTO_SCTP, SCTP_INITMSG, &init, sizeof(init));
}
<commit_msg>code cleanup in SCTP, fix minor error handling problem<commit_after>#include "SCTPSocket.h"
#include "SocketUtils.h"
#include <netinet/in.h>
#include <poll.h>
using namespace NET;
SCTPSocket::SCTPSocket( unsigned numOutStreams /* = 10 */,
unsigned maxInStreams /* = 65535 */,
unsigned maxAttempts /* = 4 */,
unsigned maxInitTimeout /* = 0 */)
: InternetSocket( STREAM, IPPROTO_SCTP)
{
setInitValues( numOutStreams, maxInStreams, maxAttempts, maxInitTimeout);
}
SCTPSocket::SCTPSocket( Handle handle)
: InternetSocket( handle.m_sockfd)
{
if(!handle) throw SocketException("Tried to initialize SCTPSocket with invalid Handle", false);
}
int SCTPSocket::bind( const std::vector<std::string>& localAddresses, unsigned short localPort /* = 0 */)
{
sockaddr_in *dest = new sockaddr_in[localAddresses.size()];
std::vector<std::string>::const_iterator it;
std::vector<std::string>::const_iterator end;
int i = 0;
for( it = localAddresses.begin(), end = localAddresses.end(); it != end; ++it)
{
fillAddr( *it, localPort, dest[i++]);
}
int ret = sctp_bindx( m_socket, reinterpret_cast<sockaddr*>(dest), localAddresses.size(), SCTP_BINDX_ADD_ADDR);
delete[] dest;
if(ret < 0)
throw SocketException("SCTPSocket::bind bindx failed");
return ret;
}
int SCTPSocket::connect( const std::vector<std::string>& foreignAddresses, unsigned short foreignPort /* = 0 */)
{
sockaddr_in *dest = new sockaddr_in[foreignAddresses.size()];
std::vector<std::string>::const_iterator it;
std::vector<std::string>::const_iterator end;
int i = 0;
for( it = foreignAddresses.begin(), end = foreignAddresses.end(); it != end; ++it)
{
fillAddr( *it, foreignPort, dest[i++]);
}
int ret = sctp_connectx( m_socket, reinterpret_cast<sockaddr*>(dest), foreignAddresses.size());
delete[] dest;
if(ret < 0)
throw SocketException("SCTPSocket::SCTPSocket connect failed");
}
int SCTPSocket::state() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::state failed");
return status.sstat_state;
}
int SCTPSocket::notAckedData() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::notAckedData failed");
return status.sstat_unackdata;
}
int SCTPSocket::pendingData() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::pendingData failed");
return status.sstat_penddata;
}
unsigned SCTPSocket::inStreams() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::inStreams failed");
return status.sstat_instrms;
}
unsigned SCTPSocket::outStreams() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::outStreams failed");
return status.sstat_outstrms;
}
unsigned SCTPSocket::fragmentationPoint() const
{
struct sctp_status status;
socklen_t size = sizeof(status);
if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0)
throw SocketException("SCTPSocket::fragmentationPoint failed");
return status.sstat_fragmentation_point;
}
std::string SCTPSocket::primaryAddress() const
{
}
int SCTPSocket::send( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */,
unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */)
{
int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr, stream, ttl, context);
if( ret < 0)
throw SocketException("SCTPSocket::send failed");
else if (ret < length)
throw SocketException("Interpreted SCTP false, sent a packet fragement");
return ret;
}
int SCTPSocket::sendUnordered( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */,
unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */,
switchAddressFlag switchAddr /* = KEEP_PRIMARY */)
{
int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr + SCTP_UNORDERED, stream, ttl, context);
if( ret < 0)
throw SocketException("SCTPSocket::send failed");
else if (ret < length)
throw SocketException("Interpreted SCTP false, sent a packet fragement");
return ret;
}
int SCTPSocket::receive( void* data, int maxLen, unsigned& stream)
{
struct sctp_sndrcvinfo info;
int ret;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed");
stream = info.sinfo_stream;
return ret;
}
int SCTPSocket::receive( void* data, int maxLen, unsigned& stream, receiveFlag& flag)
{
struct sctp_sndrcvinfo info;
int ret;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed");
stream = info.sinfo_stream;
// flag = info.sinfo_flags;
return ret;
}
int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, unsigned timeout)
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0) return 0;
if( ret < 0)
throw SocketException("SCTPSocket::receive failed (poll)");
if( poll.revents & POLLIN || poll.revents & POLLRDHUP)
{
struct sctp_sndrcvinfo info;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed (receive)");
stream = info.sinfo_stream;
return ret;
}
if( poll.revents & POLLRDHUP)
{
m_peerDisconnected = true;
}
return 0;
}
int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, receiveFlag& flag, unsigned timeout)
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0) return 0;
if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)");
if( poll.revents & POLLIN || poll.revents & POLLRDHUP)
{
struct sctp_sndrcvinfo info;
if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0)
throw SocketException("SCTPSocket::receive failed (receive)");
stream = info.sinfo_stream;
// flag = info.sinfo_flags;
return ret;
}
if( poll.revents & POLLRDHUP)
{
m_peerDisconnected = true;
}
return 0;
}
void SCTPSocket::listen( int backlog /* = 0 */)
{
int ret = ::listen( m_socket, backlog);
if( ret < 0)
throw SocketException("listen failed, most likely another socket is already listening on the same port");
}
SCTPSocket::Handle SCTPSocket::accept() const
{
int ret;
if( (ret = ::accept( m_socket, 0, 0)) <= 0)
throw SocketException("SCTPSocket::accept failed");
return Handle(ret);
}
SCTPSocket::Handle SCTPSocket::timedAccept( unsigned timeout) const
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN | POLLPRI | POLLRDHUP;
int ret = ::poll( &poll, 1, timeout);
if( ret == 0)
return Handle(0);
if( ret < 0)
throw SocketException("SCTPSocket::timedAccept failed(poll)");
if( (ret = ::accept( m_socket, 0, 0)) <= 0)
throw SocketException("SCTPSocket::timedAccept failed (accept)");
return Handle(ret);
}
void SCTPSocket::setInitValues( unsigned numOutStreams, unsigned maxInStreams, unsigned maxAttempts, unsigned maxInitTimeout)
{
struct sctp_initmsg init;
init.sinit_num_ostreams = numOutStreams;
init.sinit_max_instreams = maxInStreams;
init.sinit_max_attempts = maxAttempts;
init.sinit_max_init_timeo = maxInitTimeout;
setsockopt( m_socket, IPPROTO_SCTP, SCTP_INITMSG, &init, sizeof(init));
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace boost { namespace python {
struct value_converter : public boost::static_visitor<PyObject*>
{
PyObject * operator() (int val) const
{
return ::PyInt_FromLong(val);
}
PyObject * operator() (double val) const
{
return ::PyFloat_FromDouble(val);
}
PyObject * operator() (UnicodeString const& s) const
{
int32_t len = s.length();
boost::scoped_array<wchar_t> buf(new wchar_t(len));
UErrorCode err = U_ZERO_ERROR;
u_strToWCS(buf.get(),len,0,s.getBuffer(),len,&err);
PyObject *obj = Py_None;
if (U_SUCCESS(err))
{
obj = ::PyUnicode_FromWideChar(buf.get(),implicit_cast<ssize_t>(len));
}
return obj;
}
PyObject * operator() (mapnik::value_null const& s) const
{
return NULL;
}
};
struct mapnik_value_to_python
{
static PyObject* convert(mapnik::value const& v)
{
return boost::apply_visitor(value_converter(),v.base());
}
};
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& cl)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}
}
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
std_pair_to_python_converter<std::string const,mapnik::value>();
to_python_converter<mapnik::value,mapnik_value_to_python>();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",no_init)
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
.add_property("properties",
make_function(&Feature::props,return_value_policy<reference_existing_object>()))
// .def("add_geometry", // TODO define more mapnik::Feature methods
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
;
class_<std::map<std::string, mapnik::value> >("Properties")
.def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >())
.def("iteritems",iterator<std::map<std::string,mapnik::value> > ())
;
}
<commit_msg>+ oops, fixed<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace boost { namespace python {
struct value_converter : public boost::static_visitor<PyObject*>
{
PyObject * operator() (int val) const
{
return ::PyInt_FromLong(val);
}
PyObject * operator() (double val) const
{
return ::PyFloat_FromDouble(val);
}
PyObject * operator() (UnicodeString const& s) const
{
int32_t len = s.length();
boost::scoped_array<wchar_t> buf(new wchar_t[len]);
UErrorCode err = U_ZERO_ERROR;
u_strToWCS(buf.get(),len,0,s.getBuffer(),len,&err);
PyObject *obj = Py_None;
if (U_SUCCESS(err))
{
obj = ::PyUnicode_FromWideChar(buf.get(),implicit_cast<ssize_t>(len));
}
return obj;
}
PyObject * operator() (mapnik::value_null const& s) const
{
return NULL;
}
};
struct mapnik_value_to_python
{
static PyObject* convert(mapnik::value const& v)
{
return boost::apply_visitor(value_converter(),v.base());
}
};
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& cl)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}
}
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
std_pair_to_python_converter<std::string const,mapnik::value>();
to_python_converter<mapnik::value,mapnik_value_to_python>();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",no_init)
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
.add_property("properties",
make_function(&Feature::props,return_value_policy<reference_existing_object>()))
// .def("add_geometry", // TODO define more mapnik::Feature methods
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
;
class_<std::map<std::string, mapnik::value> >("Properties")
.def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >())
.def("iteritems",iterator<std::map<std::string,mapnik::value> > ())
;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "serializablearray.h"
#include <vespa/document/util/serializableexceptions.h>
#include <vespa/document/util/bytebuffer.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/data/databuffer.h>
#include <vespa/document/util/compressor.h>
#include <vespa/log/log.h>
LOG_SETUP(".document.serializable-array");
using std::vector;
namespace document {
namespace serializablearray {
using BufferMapT = vespalib::hash_map<int, ByteBuffer::UP>;
class BufferMap : public BufferMapT {
public:
using BufferMapT::BufferMapT;
};
}
SerializableArray::Statistics SerializableArray::_stats;
SerializableArray::SerializableArray()
: _serializedCompression(CompressionConfig::NONE),
_uncompressedLength(0)
{
}
serializablearray::BufferMap & ensure(std::unique_ptr<serializablearray::BufferMap> & owned) {
if (!owned) {
owned = std::make_unique<serializablearray::BufferMap>();
}
return *owned;
}
SerializableArray::SerializableArray(const SerializableArray& other)
: Cloneable(),
_entries(other._entries),
_owned(),
_uncompSerData(other._uncompSerData.get() ? new ByteBuffer(*other._uncompSerData) : NULL),
_compSerData(other._compSerData.get() ? new ByteBuffer(*other._compSerData) : NULL),
_serializedCompression(other._serializedCompression),
_uncompressedLength(other._uncompressedLength)
{
for (size_t i(0); i < _entries.size(); i++) {
Entry & e(_entries[i]);
if (e.hasBuffer()) {
// Pointing to a buffer in the _owned structure.
ByteBuffer::UP buf(ByteBuffer::copyBuffer(e.getBuffer(_uncompSerData.get()), e.size()));
e.setBuffer(buf->getBuffer());
ensure(_owned)[e.id()] = std::move(buf);
} else {
// If not it is relative to the buffer _uncompSerData, and hence it is valid as is.
}
}
if (_uncompSerData.get()) {
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
}
}
void
SerializableArray::swap(SerializableArray& other)
{
_entries.swap(other._entries);
_owned.swap(other._owned);
std::swap(_uncompSerData, other._uncompSerData);
std::swap(_compSerData, other._compSerData);
std::swap(_serializedCompression, other._serializedCompression);
std::swap(_uncompressedLength, other._uncompressedLength);
}
void SerializableArray::clear()
{
_entries.clear();
_uncompSerData.reset();
_compSerData.reset();
_serializedCompression = CompressionConfig::NONE;
_uncompressedLength = 0;
}
SerializableArray::~SerializableArray()
{
}
void
SerializableArray::invalidate()
{
_compSerData.reset();
}
void
SerializableArray::set(int id, ByteBuffer::UP buffer)
{
maybeDecompress();
Entry e(id, buffer->getRemaining(), buffer->getBuffer());
ensure(_owned)[id] = std::move(buffer);
EntryMap::iterator it = find(id);
if (it == _entries.end()) {
_entries.push_back(e);
} else {
*it = e;
}
invalidate();
}
void SerializableArray::set(int id, const char* value, int len)
{
set(id, std::unique_ptr<ByteBuffer>(ByteBuffer::copyBuffer(value,len)));
}
SerializableArray::EntryMap::const_iterator
SerializableArray::find(int id) const
{
return std::find_if(_entries.begin(), _entries.end(), [id](const auto& e){ return e.id() == id; });
}
SerializableArray::EntryMap::iterator
SerializableArray::find(int id)
{
return std::find_if(_entries.begin(), _entries.end(), [id](const auto& e){ return e.id() == id; });
}
bool
SerializableArray::has(int id) const
{
return (find(id) != _entries.end());
}
vespalib::ConstBufferRef
SerializableArray::get(int id) const
{
vespalib::ConstBufferRef buf;
if ( !maybeDecompressAndCatch() ) {
EntryMap::const_iterator found = find(id);
if (found != _entries.end()) {
const Entry& entry = *found;
buf = vespalib::ConstBufferRef(entry.getBuffer(_uncompSerData.get()), entry.size());
}
} else {
// should we clear all or what?
}
return buf;
}
bool
SerializableArray::deCompressAndCatch() const
{
try {
const_cast<SerializableArray *>(this)->deCompress();
return false;
} catch (const std::exception & e) {
LOG(warning, "Deserializing compressed content failed: %s", e.what());
return true;
}
}
void
SerializableArray::clear(int id)
{
maybeDecompress();
EntryMap::iterator it = find(id);
if (it != _entries.end()) {
_entries.erase(it);
_owned->erase(id);
invalidate();
}
}
void
SerializableArray::deCompress() // throw (DeserializeException)
{
// will only do this once
LOG_ASSERT(_compSerData);
LOG_ASSERT(!_uncompSerData);
if (_serializedCompression == CompressionConfig::NONE ||
_serializedCompression == CompressionConfig::UNCOMPRESSABLE)
{
_uncompSerData = std::move(_compSerData);
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
} else {
ByteBuffer::UP newSerialization(new ByteBuffer(_uncompressedLength));
vespalib::DataBuffer unCompressed(newSerialization->getBuffer(), newSerialization->getLength());
unCompressed.clear();
try {
decompress(_serializedCompression,
_uncompressedLength,
vespalib::ConstBufferRef(_compSerData->getBufferAtPos(), _compSerData->getRemaining()),
unCompressed,
false);
} catch (const std::runtime_error & e) {
throw DeserializeException(
vespalib::make_string( "Document was compressed with code unknown code %d", _serializedCompression),
VESPA_STRLOC);
}
if (unCompressed.getDataLen() != (size_t)_uncompressedLength) {
throw DeserializeException(
vespalib::make_string(
"Did not decompress to the expected length: had %" PRIu64 ", wanted %d, got %" PRIu64,
_compSerData->getRemaining(), _uncompressedLength, unCompressed.getDataLen()),
VESPA_STRLOC);
}
assert(newSerialization->getBuffer() == unCompressed.getData());
newSerialization->setLimit(_uncompressedLength);
_uncompSerData = std::move(newSerialization);
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
}
}
void SerializableArray::assign(EntryMap & entries,
ByteBuffer::UP buffer,
CompressionConfig::Type comp_type,
uint32_t uncompressed_length)
{
_serializedCompression = comp_type;
_entries.clear();
_entries.swap(entries);
if (CompressionConfig::isCompressed(_serializedCompression)) {
_compSerData.reset(buffer.release());
_uncompressedLength = uncompressed_length;
} else {
_uncompressedLength = buffer->getRemaining();
_uncompSerData.reset(buffer.release());
}
}
CompressionInfo
SerializableArray::getCompressionInfo() const {
return CompressionInfo(_uncompressedLength, _compSerData->getRemaining());
}
const char *
SerializableArray::Entry::getBuffer(const ByteBuffer * readOnlyBuffer) const {
return hasBuffer() ? _data._buffer : readOnlyBuffer->getBuffer() + getOffset();
}
} // document
<commit_msg>Only remove if it can potentially exist.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "serializablearray.h"
#include <vespa/document/util/serializableexceptions.h>
#include <vespa/document/util/bytebuffer.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/data/databuffer.h>
#include <vespa/document/util/compressor.h>
#include <vespa/log/log.h>
LOG_SETUP(".document.serializable-array");
using std::vector;
namespace document {
namespace serializablearray {
using BufferMapT = vespalib::hash_map<int, ByteBuffer::UP>;
class BufferMap : public BufferMapT {
public:
using BufferMapT::BufferMapT;
};
}
SerializableArray::Statistics SerializableArray::_stats;
SerializableArray::SerializableArray()
: _serializedCompression(CompressionConfig::NONE),
_uncompressedLength(0)
{
}
serializablearray::BufferMap & ensure(std::unique_ptr<serializablearray::BufferMap> & owned) {
if (!owned) {
owned = std::make_unique<serializablearray::BufferMap>();
}
return *owned;
}
SerializableArray::SerializableArray(const SerializableArray& other)
: Cloneable(),
_entries(other._entries),
_owned(),
_uncompSerData(other._uncompSerData.get() ? new ByteBuffer(*other._uncompSerData) : NULL),
_compSerData(other._compSerData.get() ? new ByteBuffer(*other._compSerData) : NULL),
_serializedCompression(other._serializedCompression),
_uncompressedLength(other._uncompressedLength)
{
for (size_t i(0); i < _entries.size(); i++) {
Entry & e(_entries[i]);
if (e.hasBuffer()) {
// Pointing to a buffer in the _owned structure.
ByteBuffer::UP buf(ByteBuffer::copyBuffer(e.getBuffer(_uncompSerData.get()), e.size()));
e.setBuffer(buf->getBuffer());
ensure(_owned)[e.id()] = std::move(buf);
} else {
// If not it is relative to the buffer _uncompSerData, and hence it is valid as is.
}
}
if (_uncompSerData.get()) {
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
}
}
void
SerializableArray::swap(SerializableArray& other)
{
_entries.swap(other._entries);
_owned.swap(other._owned);
std::swap(_uncompSerData, other._uncompSerData);
std::swap(_compSerData, other._compSerData);
std::swap(_serializedCompression, other._serializedCompression);
std::swap(_uncompressedLength, other._uncompressedLength);
}
void SerializableArray::clear()
{
_entries.clear();
_uncompSerData.reset();
_compSerData.reset();
_serializedCompression = CompressionConfig::NONE;
_uncompressedLength = 0;
}
SerializableArray::~SerializableArray()
{
}
void
SerializableArray::invalidate()
{
_compSerData.reset();
}
void
SerializableArray::set(int id, ByteBuffer::UP buffer)
{
maybeDecompress();
Entry e(id, buffer->getRemaining(), buffer->getBuffer());
ensure(_owned)[id] = std::move(buffer);
EntryMap::iterator it = find(id);
if (it == _entries.end()) {
_entries.push_back(e);
} else {
*it = e;
}
invalidate();
}
void SerializableArray::set(int id, const char* value, int len)
{
set(id, std::unique_ptr<ByteBuffer>(ByteBuffer::copyBuffer(value,len)));
}
SerializableArray::EntryMap::const_iterator
SerializableArray::find(int id) const
{
return std::find_if(_entries.begin(), _entries.end(), [id](const auto& e){ return e.id() == id; });
}
SerializableArray::EntryMap::iterator
SerializableArray::find(int id)
{
return std::find_if(_entries.begin(), _entries.end(), [id](const auto& e){ return e.id() == id; });
}
bool
SerializableArray::has(int id) const
{
return (find(id) != _entries.end());
}
vespalib::ConstBufferRef
SerializableArray::get(int id) const
{
vespalib::ConstBufferRef buf;
if ( !maybeDecompressAndCatch() ) {
EntryMap::const_iterator found = find(id);
if (found != _entries.end()) {
const Entry& entry = *found;
buf = vespalib::ConstBufferRef(entry.getBuffer(_uncompSerData.get()), entry.size());
}
} else {
// should we clear all or what?
}
return buf;
}
bool
SerializableArray::deCompressAndCatch() const
{
try {
const_cast<SerializableArray *>(this)->deCompress();
return false;
} catch (const std::exception & e) {
LOG(warning, "Deserializing compressed content failed: %s", e.what());
return true;
}
}
void
SerializableArray::clear(int id)
{
maybeDecompress();
EntryMap::iterator it = find(id);
if (it != _entries.end()) {
_entries.erase(it);
if (_owned) {
_owned->erase(id);
}
invalidate();
}
}
void
SerializableArray::deCompress() // throw (DeserializeException)
{
// will only do this once
LOG_ASSERT(_compSerData);
LOG_ASSERT(!_uncompSerData);
if (_serializedCompression == CompressionConfig::NONE ||
_serializedCompression == CompressionConfig::UNCOMPRESSABLE)
{
_uncompSerData = std::move(_compSerData);
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
} else {
ByteBuffer::UP newSerialization(new ByteBuffer(_uncompressedLength));
vespalib::DataBuffer unCompressed(newSerialization->getBuffer(), newSerialization->getLength());
unCompressed.clear();
try {
decompress(_serializedCompression,
_uncompressedLength,
vespalib::ConstBufferRef(_compSerData->getBufferAtPos(), _compSerData->getRemaining()),
unCompressed,
false);
} catch (const std::runtime_error & e) {
throw DeserializeException(
vespalib::make_string( "Document was compressed with code unknown code %d", _serializedCompression),
VESPA_STRLOC);
}
if (unCompressed.getDataLen() != (size_t)_uncompressedLength) {
throw DeserializeException(
vespalib::make_string(
"Did not decompress to the expected length: had %" PRIu64 ", wanted %d, got %" PRIu64,
_compSerData->getRemaining(), _uncompressedLength, unCompressed.getDataLen()),
VESPA_STRLOC);
}
assert(newSerialization->getBuffer() == unCompressed.getData());
newSerialization->setLimit(_uncompressedLength);
_uncompSerData = std::move(newSerialization);
LOG_ASSERT(_uncompressedLength == _uncompSerData->getRemaining());
}
}
void SerializableArray::assign(EntryMap & entries,
ByteBuffer::UP buffer,
CompressionConfig::Type comp_type,
uint32_t uncompressed_length)
{
_serializedCompression = comp_type;
_entries.clear();
_entries.swap(entries);
if (CompressionConfig::isCompressed(_serializedCompression)) {
_compSerData.reset(buffer.release());
_uncompressedLength = uncompressed_length;
} else {
_uncompressedLength = buffer->getRemaining();
_uncompSerData.reset(buffer.release());
}
}
CompressionInfo
SerializableArray::getCompressionInfo() const {
return CompressionInfo(_uncompressedLength, _compSerData->getRemaining());
}
const char *
SerializableArray::Entry::getBuffer(const ByteBuffer * readOnlyBuffer) const {
return hasBuffer() ? _data._buffer : readOnlyBuffer->getBuffer() + getOffset();
}
} // document
<|endoftext|>
|
<commit_before>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// 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 <array>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <exception>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <syslog.h>
#include <unistd.h>
#include <bsd/libutil.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#include <bcm_host.h>
#pragma GCC diagnostic pop
#include "cpuTrace.h"
#include "dynamicInfo.h"
#include "framebuffer565.h"
#include "memoryTrace.h"
//-------------------------------------------------------------------------
namespace
{
volatile static std::sig_atomic_t run = 1;
volatile static std::sig_atomic_t display = 1;
const char* defaultDevice = "/dev/fb1";
}
//-------------------------------------------------------------------------
void
messageLog(
bool isDaemon,
const std::string& name,
int priority,
const std::string& message)
{
if (isDaemon)
{
::syslog(LOG_MAKEPRI(LOG_USER, priority), message.c_str());
}
else
{
std::cerr << name << "[" << getpid() << "]:";
switch (priority)
{
case LOG_DEBUG:
std::cerr << "debug";
break;
case LOG_INFO:
std::cerr << "info";
break;
case LOG_NOTICE:
std::cerr << "notice";
break;
case LOG_WARNING:
std::cerr << "warning";
break;
case LOG_ERR:
std::cerr << "error";
break;
default:
std::cerr << "unknown(" << priority << ")";
break;
}
std::cerr << ":" << message << "\n";
}
}
//-------------------------------------------------------------------------
void
perrorLog(
bool isDaemon,
const std::string& name,
const std::string& s)
{
messageLog(isDaemon, name, LOG_ERR, s + " - " + ::strerror(errno));
}
//-------------------------------------------------------------------------
void
printUsage(
std::ostream& os,
const std::string& name)
{
os << "\n";
os << "Usage: " << name << " <options>\n";
os << "\n";
os << " --daemon,-D - start in the background as a daemon\n";
os << " --device,-d - framebuffer device to use";
os << " (default is " << defaultDevice << ")\n";
os << " --help,-h - print usage and exit\n";
os << " --pidfile,-p <pidfile> - create and lock PID file";
os << " (if being run as a daemon)\n";
os << "\n";
}
//-------------------------------------------------------------------------
static void
signalHandler(
int signalNumber)
{
switch (signalNumber)
{
case SIGINT:
case SIGTERM:
run = 0;
break;
case SIGUSR1:
display = 0;
break;
case SIGUSR2:
display = 1;
break;
};
}
//-------------------------------------------------------------------------
int
main(
int argc,
char *argv[])
{
const char* device = defaultDevice;
char* program = basename(argv[0]);
char* pidfile = nullptr;
bool isDaemon = false;
//---------------------------------------------------------------------
static const char* sopts = "d:hp:D";
static struct option lopts[] =
{
{ "device", required_argument, nullptr, 'd' },
{ "help", no_argument, nullptr, 'h' },
{ "pidfile", required_argument, nullptr, 'p' },
{ "daemon", no_argument, nullptr, 'D' },
{ nullptr, no_argument, nullptr, 0 }
};
int opt = 0;
while ((opt = ::getopt_long(argc, argv, sopts, lopts, nullptr)) != -1)
{
switch (opt)
{
case 'd':
device = optarg;
break;
case 'h':
printUsage(std::cout, program);
::exit(EXIT_SUCCESS);
break;
case 'p':
pidfile = optarg;
break;
case 'D':
isDaemon = true;
break;
default:
printUsage(std::cerr, program);
::exit(EXIT_FAILURE);
break;
}
}
//---------------------------------------------------------------------
struct pidfh* pfh = nullptr;
if (isDaemon)
{
if (pidfile != nullptr)
{
pid_t otherpid;
pfh = ::pidfile_open(pidfile, 0600, &otherpid);
if (pfh == nullptr)
{
std::cerr
<< program
<< " is already running "
<< otherpid
<< "\n";
::exit(EXIT_FAILURE);
}
}
if (::daemon(0, 0) == -1)
{
std::cerr << "Cannot daemonize\n";
if (pfh)
{
::pidfile_remove(pfh);
}
::exit(EXIT_FAILURE);
}
if (pfh)
{
::pidfile_write(pfh);
}
::openlog(program, LOG_PID, LOG_USER);
}
//---------------------------------------------------------------------
::bcm_host_init();
//---------------------------------------------------------------------
std::array<int, 4> signals = { SIGINT, SIGTERM, SIGUSR1, SIGUSR2 };
for (auto signal : signals)
{
if (std::signal(signal, signalHandler) == SIG_ERR)
{
if (pfh)
{
::pidfile_remove(pfh);
}
std::string message {"installing "};
message += strsignal(signal);
message += " signal handler";
perrorLog(isDaemon,
program,
"installing SIGINT signal handler");
::exit(EXIT_FAILURE);
}
}
//---------------------------------------------------------------------
try
{
raspifb16::FrameBuffer565 fb(device);
fb.clear(raspifb16::RGB565{0, 0, 0});
//-----------------------------------------------------------------
int16_t traceHeight = 100;
// FIXME - need a better way to work out height of trace windows.
if (fb.getHeight() == 240)
{
traceHeight = 80;
}
int16_t gridHeight = traceHeight / 5;
using Panels = std::vector<std::unique_ptr<Panel>>;
Panels panels;
auto panelTop = [](const Panels& panels) -> int16_t
{
if (panels.empty())
{
return 0;
}
else
{
return panels.back()->getBottom() + 1;
}
};
panels.push_back(
std::make_unique<DynamicInfo>(fb.getWidth(),
panelTop(panels)));
panels.push_back(
std::make_unique<CpuTrace>(fb.getWidth(),
traceHeight,
panelTop(panels),
gridHeight));
panels.push_back(
std::make_unique<MemoryTrace>(fb.getWidth(),
traceHeight,
panelTop(panels),
gridHeight));
//-----------------------------------------------------------------
constexpr auto oneSecond(std::chrono::seconds(1));
std::this_thread::sleep_for(oneSecond);
while (run)
{
auto now = std::chrono::system_clock::now();
auto now_t = std::chrono::system_clock::to_time_t(now);
for (auto& panel : panels)
{
panel->update(now_t);
if (display)
{
panel->show(fb);
}
}
std::this_thread::sleep_for(oneSecond);
}
fb.clear();
}
catch (std::exception& error)
{
std::cerr << "Error: " << error.what() << "\n";
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
messageLog(isDaemon, program, LOG_INFO, "exiting");
if (isDaemon)
{
::closelog();
}
if (pfh)
{
::pidfile_remove(pfh);
}
//---------------------------------------------------------------------
return 0 ;
}
<commit_msg>error message is setting signal fails.<commit_after>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// 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 <array>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <exception>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <syslog.h>
#include <unistd.h>
#include <bsd/libutil.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#include <bcm_host.h>
#pragma GCC diagnostic pop
#include "cpuTrace.h"
#include "dynamicInfo.h"
#include "framebuffer565.h"
#include "memoryTrace.h"
//-------------------------------------------------------------------------
namespace
{
volatile static std::sig_atomic_t run = 1;
volatile static std::sig_atomic_t display = 1;
const char* defaultDevice = "/dev/fb1";
}
//-------------------------------------------------------------------------
void
messageLog(
bool isDaemon,
const std::string& name,
int priority,
const std::string& message)
{
if (isDaemon)
{
::syslog(LOG_MAKEPRI(LOG_USER, priority), message.c_str());
}
else
{
std::cerr << name << "[" << getpid() << "]:";
switch (priority)
{
case LOG_DEBUG:
std::cerr << "debug";
break;
case LOG_INFO:
std::cerr << "info";
break;
case LOG_NOTICE:
std::cerr << "notice";
break;
case LOG_WARNING:
std::cerr << "warning";
break;
case LOG_ERR:
std::cerr << "error";
break;
default:
std::cerr << "unknown(" << priority << ")";
break;
}
std::cerr << ":" << message << "\n";
}
}
//-------------------------------------------------------------------------
void
perrorLog(
bool isDaemon,
const std::string& name,
const std::string& s)
{
messageLog(isDaemon, name, LOG_ERR, s + " - " + ::strerror(errno));
}
//-------------------------------------------------------------------------
void
printUsage(
std::ostream& os,
const std::string& name)
{
os << "\n";
os << "Usage: " << name << " <options>\n";
os << "\n";
os << " --daemon,-D - start in the background as a daemon\n";
os << " --device,-d - framebuffer device to use";
os << " (default is " << defaultDevice << ")\n";
os << " --help,-h - print usage and exit\n";
os << " --pidfile,-p <pidfile> - create and lock PID file";
os << " (if being run as a daemon)\n";
os << "\n";
}
//-------------------------------------------------------------------------
static void
signalHandler(
int signalNumber)
{
switch (signalNumber)
{
case SIGINT:
case SIGTERM:
run = 0;
break;
case SIGUSR1:
display = 0;
break;
case SIGUSR2:
display = 1;
break;
};
}
//-------------------------------------------------------------------------
int
main(
int argc,
char *argv[])
{
const char* device = defaultDevice;
char* program = basename(argv[0]);
char* pidfile = nullptr;
bool isDaemon = false;
//---------------------------------------------------------------------
static const char* sopts = "d:hp:D";
static struct option lopts[] =
{
{ "device", required_argument, nullptr, 'd' },
{ "help", no_argument, nullptr, 'h' },
{ "pidfile", required_argument, nullptr, 'p' },
{ "daemon", no_argument, nullptr, 'D' },
{ nullptr, no_argument, nullptr, 0 }
};
int opt = 0;
while ((opt = ::getopt_long(argc, argv, sopts, lopts, nullptr)) != -1)
{
switch (opt)
{
case 'd':
device = optarg;
break;
case 'h':
printUsage(std::cout, program);
::exit(EXIT_SUCCESS);
break;
case 'p':
pidfile = optarg;
break;
case 'D':
isDaemon = true;
break;
default:
printUsage(std::cerr, program);
::exit(EXIT_FAILURE);
break;
}
}
//---------------------------------------------------------------------
struct pidfh* pfh = nullptr;
if (isDaemon)
{
if (pidfile != nullptr)
{
pid_t otherpid;
pfh = ::pidfile_open(pidfile, 0600, &otherpid);
if (pfh == nullptr)
{
std::cerr
<< program
<< " is already running "
<< otherpid
<< "\n";
::exit(EXIT_FAILURE);
}
}
if (::daemon(0, 0) == -1)
{
std::cerr << "Cannot daemonize\n";
if (pfh)
{
::pidfile_remove(pfh);
}
::exit(EXIT_FAILURE);
}
if (pfh)
{
::pidfile_write(pfh);
}
::openlog(program, LOG_PID, LOG_USER);
}
//---------------------------------------------------------------------
::bcm_host_init();
//---------------------------------------------------------------------
std::array<int, 4> signals = { SIGINT, SIGTERM, SIGUSR1, SIGUSR2 };
for (auto signal : signals)
{
if (std::signal(signal, signalHandler) == SIG_ERR)
{
if (pfh)
{
::pidfile_remove(pfh);
}
std::string message {"installing "};
message += strsignal(signal);
message += " signal handler";
perrorLog(isDaemon, program, message);
::exit(EXIT_FAILURE);
}
}
//---------------------------------------------------------------------
try
{
raspifb16::FrameBuffer565 fb(device);
fb.clear(raspifb16::RGB565{0, 0, 0});
//-----------------------------------------------------------------
int16_t traceHeight = 100;
// FIXME - need a better way to work out height of trace windows.
if (fb.getHeight() == 240)
{
traceHeight = 80;
}
int16_t gridHeight = traceHeight / 5;
using Panels = std::vector<std::unique_ptr<Panel>>;
Panels panels;
auto panelTop = [](const Panels& panels) -> int16_t
{
if (panels.empty())
{
return 0;
}
else
{
return panels.back()->getBottom() + 1;
}
};
panels.push_back(
std::make_unique<DynamicInfo>(fb.getWidth(),
panelTop(panels)));
panels.push_back(
std::make_unique<CpuTrace>(fb.getWidth(),
traceHeight,
panelTop(panels),
gridHeight));
panels.push_back(
std::make_unique<MemoryTrace>(fb.getWidth(),
traceHeight,
panelTop(panels),
gridHeight));
//-----------------------------------------------------------------
constexpr auto oneSecond(std::chrono::seconds(1));
std::this_thread::sleep_for(oneSecond);
while (run)
{
auto now = std::chrono::system_clock::now();
auto now_t = std::chrono::system_clock::to_time_t(now);
for (auto& panel : panels)
{
panel->update(now_t);
if (display)
{
panel->show(fb);
}
}
std::this_thread::sleep_for(oneSecond);
}
fb.clear();
}
catch (std::exception& error)
{
std::cerr << "Error: " << error.what() << "\n";
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
messageLog(isDaemon, program, LOG_INFO, "exiting");
if (isDaemon)
{
::closelog();
}
if (pfh)
{
::pidfile_remove(pfh);
}
//---------------------------------------------------------------------
return 0 ;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2017, STEREOLABS.
//
// All rights reserved.
//
// 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.
//
///////////////////////////////////////////////////////////////////////////
// Standard includes
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
// ZED includes
#include <sl/Camera.hpp>
int main(int argc, char **argv)
{
// Create a ZED camera object
sl::Camera zed;
// Set configuration parameters
sl::InitParameters init_params;
init_params.camera_resolution = sl::RESOLUTION_VGA;
init_params.coordinate_system = sl::COORDINATE_SYSTEM_IMAGE;
init_params.coordinate_units = sl::UNIT_METER;
init_params.depth_mode = sl::DEPTH_MODE_PERFORMANCE;
init_params.sdk_verbose = true;
// Open the camera
sl::ERROR_CODE err = zed.open(init_params);
if (err != sl::SUCCESS) {
exit(-1);
}
// Enable positional tracking with default parameters
sl::TrackingParameters tracking_parameters;
tracking_parameters.initial_world_transform = sl::Transform::identity();
tracking_parameters.enable_spatial_memory = true;
// Enable motion tracking
zed.enableTracking(tracking_parameters);
// Track the camera position during 1000 frames
int i = 0;
sl::Pose zed_pose;
float tx, ty, tz = 0;
float ox, oy, oz, ow = 0;
float rx, ry, rz = 0;
while (i < 1000) {
if (!zed.grab()) {
// Get camera position in World frame
sl::TRACKING_STATE tracking_state = zed.getPosition(zed_pose, sl::REFERENCE_FRAME_WORLD);
// Get motion tracking confidence
int tracking_confidence = zed_pose.pose_confidence;
if (tracking_state == sl::TRACKING_STATE_OK) {
// Extract 3x1 rotation from pose
//sl::Vector3<float> rotation = zed_pose.getRotationVector();
//rx = rotation.x;
//ry = rotation.y;
//rz = rotation.z;
// Extract 4x1 orientation from pose
ox = zed_pose.getOrientation().ox;
oy = zed_pose.getOrientation().oy;
oz = zed_pose.getOrientation().oz;
ow = zed_pose.getOrientation().ow;
// Extract translation from pose
sl::Vector3<float> translation = zed_pose.getTranslation();
tx = translation.tx;
ty = translation.ty;
tz = translation.tz;
// Display the translation & orientation & timestamp
printf("Translation: Tx: %.3f, Ty: %.3f, Tz: %.3f, Timestamp: %llu\n", tx, ty, tz, zed_pose.timestamp);
printf("Orientation: Ox: %.3f, Oy: %.3f, Oz: %.3f, Ow: %.3f\n\n", ox, oy, oz, ow);
i++;
}
}
}
// Disable positional tracking and close the camera
zed.disableTracking();
zed.close();
return 0;
}
<commit_msg>minor changes.<commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2017, STEREOLABS.
//
// All rights reserved.
//
// 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.
//
///////////////////////////////////////////////////////////////////////////
// Standard includes
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
// ZED includes
#include <sl/Camera.hpp>
int main(int argc, char **argv)
{
// Create a ZED camera object
sl::Camera zed;
// Set configuration parameters
sl::InitParameters init_params;
init_params.camera_resolution = sl::RESOLUTION_VGA;
init_params.coordinate_system = sl::COORDINATE_SYSTEM_IMAGE;
init_params.coordinate_units = sl::UNIT_METER;
init_params.depth_mode = sl::DEPTH_MODE_PERFORMANCE;
init_params.sdk_verbose = true;
// Open the camera
sl::ERROR_CODE err = zed.open(init_params);
if (err != sl::SUCCESS) {
exit(-1);
}
// Enable positional tracking with default parameters
sl::TrackingParameters tracking_parameters;
tracking_parameters.initial_world_transform = sl::Transform::identity();
tracking_parameters.enable_spatial_memory = true;
// Enable motion tracking
zed.enableTracking(tracking_parameters);
// Track the camera position during 1000 frames
int i = 0;
sl::Pose zed_pose;
unsigned long long previous_timestamp, current_timestamp = 0;
float tx, ty, tz = 0;
float ox, oy, oz, ow = 0;
float rx, ry, rz = 0;
while (i >= 0) {
if (!zed.grab()) {
// Get camera position in World frame
sl::TRACKING_STATE tracking_state = zed.getPosition(zed_pose, sl::REFERENCE_FRAME_WORLD);
// Get motion tracking confidence
int tracking_confidence = zed_pose.pose_confidence;
if (tracking_state == sl::TRACKING_STATE_OK) {
// Extract 3x1 rotation from pose
//sl::Vector3<float> rotation = zed_pose.getRotationVector();
//rx = rotation.x;
//ry = rotation.y;
//rz = rotation.z;
// Extract 4x1 orientation from pose
ox = zed_pose.getOrientation().ox;
oy = zed_pose.getOrientation().oy;
oz = zed_pose.getOrientation().oz;
ow = zed_pose.getOrientation().ow;
// Extract translation from pose (p_gc)
sl::Vector3<float> translation = zed_pose.getTranslation();
tx = translation.tx;
ty = translation.ty;
tz = translation.tz;
// Extract previous and current timestamp
previous_timestamp = current_timestamp;
current_timestamp = zed_pose.timestamp;
double dt = (double) (current_timestamp - previous_timestamp) * 0.000000001;
// Display the translation & orientation & timestamp
printf("Translation: Tx: %.3f, Ty: %.3f, Tz: %.3f, dt: %.3lf\n", tx, ty, tz, dt);
printf("Orientation: Ox: %.3f, Oy: %.3f, Oz: %.3f, Ow: %.3f\n\n", ox, oy, oz, ow);
i++;
}
}
}
// Disable positional tracking and close the camera
zed.disableTracking();
zed.close();
return 0;
}
<|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-CHROMIUM file.
#include "common/content_client.h"
#include "common/application_info.h"
#include "base/stringprintf.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"
namespace brightray {
ContentClient::ContentClient() {
}
ContentClient::~ContentClient() {
}
std::string ContentClient::GetProduct() const {
return base::StringPrintf("%s/%s", GetApplicationName().c_str(), GetApplicationVersion().c_str());
}
std::string ContentClient::GetUserAgent() const {
return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}
base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}
}<commit_msg>Strip whitespace from the application name in the user agent<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-CHROMIUM file.
#include "common/content_client.h"
#include "common/application_info.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"
namespace brightray {
ContentClient::ContentClient() {
}
ContentClient::~ContentClient() {
}
std::string ContentClient::GetProduct() const {
auto name = GetApplicationName();
RemoveChars(name, kWhitespaceASCII, &name);
return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}
std::string ContentClient::GetUserAgent() const {
return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}
base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}
}<|endoftext|>
|
<commit_before>#include "mettle.hpp"
using namespace mettle;
suite<suites_list> test_suite("test suite", [](auto &_) {
_.test("create a test suite", [](suites_list &suites) {
suite<> inner("inner test suite", [](auto &_){
_.test("inner test", []() {});
}, suites);
expect(suites, array(&inner));
});
_.test("create a test suite with fixture", [](suites_list &suites) {
suite<int> inner("inner test suite", [](auto &_){
_.test("inner test", [](int &) {});
}, suites);
expect(suites, array(&inner));
});
});
<commit_msg>Test that test suites with broken initializers don't get added to the list of suites<commit_after>#include "mettle.hpp"
using namespace mettle;
suite<suites_list> test_suite("test suite", [](auto &_) {
_.test("create a test suite", [](suites_list &suites) {
suite<> inner("inner test suite", [](auto &_){
_.test("inner test", []() {});
}, suites);
expect(suites, array(&inner));
});
_.test("create a test suite with fixture", [](suites_list &suites) {
suite<int> inner("inner test suite", [](auto &_){
_.test("inner test", [](int &) {});
}, suites);
expect(suites, array(&inner));
});
_.test("create a test suite that throws", [](suites_list &suites) {
try {
suite<int> inner("broken test suite", [](auto &){
throw "bad";
}, suites);
} catch(...) {}
expect(suites, array());
});
});
<|endoftext|>
|
<commit_before>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using boost::filesystem::remove_all;
using boost::filesystem::exists;
void test_swarm()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000));
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000));
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000));
ses1.set_severity_level(alert::debug);
ses2.set_severity_level(alert::debug);
ses3.set_severity_level(alert::debug);
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
float rate_limit = 100000;
ses1.set_upload_rate_limit(int(rate_limit));
ses2.set_download_rate_limit(int(rate_limit));
ses3.set_download_rate_limit(int(rate_limit));
ses2.set_upload_rate_limit(int(rate_limit / 2));
ses3.set_upload_rate_limit(int(rate_limit / 2));
session_settings settings;
settings.allow_multiple_connections_per_ip = true;
settings.ignore_limits_on_local_network = false;
ses1.set_settings(settings);
ses2.set_settings(settings);
ses3.set_settings(settings);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm");
float sum_dl_rate2 = 0.f;
float sum_dl_rate3 = 0.f;
int count_dl_rates2 = 0;
int count_dl_rates3 = 0;
for (int i = 0; i < 26; ++i)
{
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
print_alerts(ses3, "ses3");
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
torrent_status st3 = tor3.status();
if (st2.progress < 1.f && st2.progress > 0.5f)
{
sum_dl_rate2 += st2.download_payload_rate;
++count_dl_rates2;
}
if (st3.progress < 1.f && st3.progress > 0.5f)
{
sum_dl_rate3 += st3.download_rate;
++count_dl_rates3;
}
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
if (tor2.is_seed() && tor3.is_seed()) break;
test_sleep(1000);
}
TEST_CHECK(tor2.is_seed());
TEST_CHECK(tor3.is_seed());
float average2 = sum_dl_rate2 / float(count_dl_rates2);
float average3 = sum_dl_rate3 / float(count_dl_rates3);
std::cerr << average2 << std::endl;
std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - "
<< (average3 / 1000.f) << "kB/s" << std::endl;
TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f);
TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f);
if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n";
// make sure the files are deleted
ses1.remove_torrent(tor1, session::delete_files);
ses2.remove_torrent(tor2, session::delete_files);
ses3.remove_torrent(tor3, session::delete_files);
std::auto_ptr<alert> a = ses1.pop_alert();
ptime end = time_now() + seconds(20);
while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0)
{
if (ses1.wait_for_alert(end - time_now()) == 0)
{
std::cerr << "wait_for_alert() expired" << std::endl;
break;
}
a = ses1.pop_alert();
assert(a.get());
std::cerr << a->msg() << std::endl;
}
TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0);
// there shouldn't be any alerts generated from now on
// make sure that the timer in wait_for_alert() works
// this should time out (ret == 0) and it should take
// about 2 seconds
ptime start = time_now();
alert const* ret = ses1.wait_for_alert(seconds(2));
TEST_CHECK(ret == 0);
if (ret != 0) std::cerr << ret->msg() << std::endl;
TEST_CHECK(time_now() - start < seconds(3));
TEST_CHECK(time_now() - start > seconds(2));
}
int test_main()
{
using namespace libtorrent;
using namespace boost::filesystem;
// in case the previous run was terminated
try { remove_all("./tmp1_swarm"); } catch (std::exception&) {}
try { remove_all("./tmp2_swarm"); } catch (std::exception&) {}
try { remove_all("./tmp3_swarm"); } catch (std::exception&) {}
test_swarm();
test_sleep(2000);
TEST_CHECK(!exists("./tmp1_swarm/temporary"));
TEST_CHECK(!exists("./tmp2_swarm/temporary"));
TEST_CHECK(!exists("./tmp3_swarm/temporary"));
remove_all("./tmp1_swarm");
remove_all("./tmp2_swarm");
remove_all("./tmp3_swarm");
return 0;
}
<commit_msg>made test swarm more likely to pass<commit_after>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using boost::filesystem::remove_all;
using boost::filesystem::exists;
void test_swarm()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000));
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000));
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000));
ses1.set_severity_level(alert::debug);
ses2.set_severity_level(alert::debug);
ses3.set_severity_level(alert::debug);
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
float rate_limit = 100000;
ses1.set_upload_rate_limit(int(rate_limit));
ses2.set_download_rate_limit(int(rate_limit));
ses3.set_download_rate_limit(int(rate_limit));
ses2.set_upload_rate_limit(int(rate_limit / 2));
ses3.set_upload_rate_limit(int(rate_limit / 2));
session_settings settings;
settings.allow_multiple_connections_per_ip = true;
settings.ignore_limits_on_local_network = false;
ses1.set_settings(settings);
ses2.set_settings(settings);
ses3.set_settings(settings);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm");
float sum_dl_rate2 = 0.f;
float sum_dl_rate3 = 0.f;
int count_dl_rates2 = 0;
int count_dl_rates3 = 0;
for (int i = 0; i < 27; ++i)
{
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
print_alerts(ses3, "ses3");
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
torrent_status st3 = tor3.status();
if (st2.progress < 1.f && st2.progress > 0.5f)
{
sum_dl_rate2 += st2.download_payload_rate;
++count_dl_rates2;
}
if (st3.progress < 1.f && st3.progress > 0.5f)
{
sum_dl_rate3 += st3.download_rate;
++count_dl_rates3;
}
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
if (tor2.is_seed() && tor3.is_seed()) break;
test_sleep(1000);
}
TEST_CHECK(tor2.is_seed());
TEST_CHECK(tor3.is_seed());
float average2 = sum_dl_rate2 / float(count_dl_rates2);
float average3 = sum_dl_rate3 / float(count_dl_rates3);
std::cerr << average2 << std::endl;
std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - "
<< (average3 / 1000.f) << "kB/s" << std::endl;
TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f);
TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f);
if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n";
// make sure the files are deleted
ses1.remove_torrent(tor1, session::delete_files);
ses2.remove_torrent(tor2, session::delete_files);
ses3.remove_torrent(tor3, session::delete_files);
std::auto_ptr<alert> a = ses1.pop_alert();
ptime end = time_now() + seconds(20);
while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0)
{
if (ses1.wait_for_alert(end - time_now()) == 0)
{
std::cerr << "wait_for_alert() expired" << std::endl;
break;
}
a = ses1.pop_alert();
assert(a.get());
std::cerr << a->msg() << std::endl;
}
TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0);
// there shouldn't be any alerts generated from now on
// make sure that the timer in wait_for_alert() works
// this should time out (ret == 0) and it should take
// about 2 seconds
ptime start = time_now();
alert const* ret = ses1.wait_for_alert(seconds(2));
TEST_CHECK(ret == 0);
if (ret != 0) std::cerr << ret->msg() << std::endl;
TEST_CHECK(time_now() - start < seconds(3));
TEST_CHECK(time_now() - start > seconds(2));
}
int test_main()
{
using namespace libtorrent;
using namespace boost::filesystem;
// in case the previous run was terminated
try { remove_all("./tmp1_swarm"); } catch (std::exception&) {}
try { remove_all("./tmp2_swarm"); } catch (std::exception&) {}
try { remove_all("./tmp3_swarm"); } catch (std::exception&) {}
test_swarm();
test_sleep(2000);
TEST_CHECK(!exists("./tmp1_swarm/temporary"));
TEST_CHECK(!exists("./tmp2_swarm/temporary"));
TEST_CHECK(!exists("./tmp3_swarm/temporary"));
remove_all("./tmp1_swarm");
remove_all("./tmp2_swarm");
remove_all("./tmp3_swarm");
return 0;
}
<|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/value.hpp"
#include "flusspferd/object.hpp"
#include <boost/test/unit_test.hpp>
boost::unit_test::test_suite *init_unit_test_suite(int, char **) {
return 0;
}
BOOST_AUTO_TEST_CASE( void_value ) {
flusspferd::value void_value;
BOOST_CHECK(void_value.is_void());
BOOST_CHECK(!void_value.is_null());
}
BOOST_AUTO_TEST_CASE( null_value ) {
flusspferd::object null_object;
BOOST_REQUIRE(!null_object.is_valid());
flusspferd::value null_value(null_object);
BOOST_CHECK(!null_value.is_void());
BOOST_CHECK(null_value.is_null());
}
<commit_msg>add boolean test<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/value.hpp"
#include "flusspferd/object.hpp"
#include <boost/test/unit_test.hpp>
boost::unit_test::test_suite *init_unit_test_suite(int, char **) {
return 0;
}
BOOST_AUTO_TEST_CASE( void_value ) {
flusspferd::value void_value;
BOOST_CHECK(void_value.is_void());
BOOST_CHECK(!void_value.is_null());
}
BOOST_AUTO_TEST_CASE( null_value ) {
flusspferd::object null_object;
BOOST_REQUIRE(!null_object.is_valid());
flusspferd::value null_value(null_object);
BOOST_CHECK(!null_value.is_void());
BOOST_CHECK(null_value.is_null());
}
BOOST_AUTO_TEST_CASE( boolean_value ) {
flusspferd::value boolean_value(false);
BOOST_CHECK(boolean_value.is_boolean());
BOOST_CHECK(!boolean_value.get_boolean());
boolean_value = true;
BOOST_CHECK(boolean_value.is_boolean());
BOOST_CHECK(boolean_value.get_boolean());
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "input.hpp"
extern "C" {
char sci_getch(void)
{
return 0;
}
};
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
using namespace utils;
#if 0
int a = 0;
uint32_t b = 0;
auto n = (input("%d[, ]%x", "-99 100") % a % b).num();
std::cout << "Num: " << n << std::endl;
std::cout << "1ST: " << a << ", 2ND: " << b << std::endl;
#endif
float a;
int b;
uint32_t c;
auto n = (input("%f,%d,%x", "101.945,-76,7ff") % a % b % c).num();
std::cout << "Num: " << n << std::endl;
std::cout << "1ST: " << a << std::endl;
std::cout << "2ND: " << b << std::endl;
std::cout << "3RD: " << c << std::endl;
}
<commit_msg>update test<commit_after>#include <iostream>
#include "input.hpp"
extern "C" {
char sci_getch(void)
{
return 0;
}
};
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
using namespace utils;
#if 0
int a = 0;
uint32_t b = 0;
auto n = (input("%d[, ]%x", "-99 100") % a % b).num();
std::cout << "Num: " << n << std::endl;
std::cout << "1ST: " << a << ", 2ND: " << b << std::endl;
#endif
float a;
int b;
uint32_t c;
double d;
auto n = (input("%f,%d,%x,%f", "101.945,-76,7ff,1.567") % a % b % c % d).num();
std::cout << "Num: " << n << std::endl;
std::cout << "1ST: " << a << std::endl;
std::cout << "2ND: " << b << std::endl;
std::cout << "3RD: " << c << std::endl;
std::cout << "4TH: " << d << std::endl;
}
<|endoftext|>
|
<commit_before>#include <config.h>
#include <davix.hpp>
#include <gtest/gtest.h>
// instanciate and play with gates
TEST(ContextTest, CreateDelete){
Davix::Context c1;
Davix::Context* c2 = c1.clone();
ASSERT_TRUE(c2 != NULL);
Davix::Context* c3 = c1.clone();
delete c2;
delete c3;
}
TEST(RequestParametersTest, CreateDelete){
Davix::RequestParams params;
ASSERT_EQ(params.getSSLCACheck(), true);
ASSERT_EQ(params.getOperationTimeout()->tv_sec, DAVIX_DEFAULT_OPS_TIMEOUT);
ASSERT_EQ(params.getConnectionTimeout()->tv_sec, DAVIX_DEFAULT_CONN_TIMEOUT);
ASSERT_EQ(params.getClientCertCallbackX509().second, (void*) NULL);
ASSERT_EQ(params.getClientCertCallbackX509().first, (int (*)(void*, const Davix::SessionInfo&, Davix::X509Credential*, Davix::DavixError**)) NULL);
ASSERT_TRUE( params.getTransparentRedirectionSupport());
params.setSSLCAcheck(false);
struct timespec timeout_co, timeout_ops;
timeout_co.tv_sec =10;
timeout_co.tv_nsec=99;
timeout_ops.tv_sec=20;
timeout_ops.tv_nsec=0xFF;
ASSERT_EQ(params.getSSLCACheck(), false);
params.setOperationTimeout(&timeout_co);
ASSERT_EQ(params.getOperationTimeout()->tv_sec, 10);
params.setConnectionTimeout(&timeout_ops);
ASSERT_EQ(params.getConnectionTimeout()->tv_sec, 20);
params.setTransparentRedirectionSupport(false);
ASSERT_FALSE( params.getTransparentRedirectionSupport());
Davix::RequestParams p2(¶ms);
Davix::RequestParams p3(p2);
ASSERT_EQ(p2.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p2.getConnectionTimeout()->tv_sec, 20);
ASSERT_EQ(p3.getConnectionTimeout()->tv_sec, 20);
ASSERT_FALSE( p2.getTransparentRedirectionSupport());
Davix::RequestParams p4 = p3; // test deep copy
ASSERT_EQ(p2.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p4.getConnectionTimeout()->tv_sec, 20);
}
TEST(RequestParametersTest, CreateDeleteDyn){
Davix::RequestParams* params = new Davix::RequestParams();
ASSERT_EQ(params->getSSLCACheck(), true);
ASSERT_EQ(params->getOperationTimeout()->tv_sec, DAVIX_DEFAULT_OPS_TIMEOUT);
ASSERT_EQ(params->getConnectionTimeout()->tv_sec, DAVIX_DEFAULT_CONN_TIMEOUT);
ASSERT_EQ(params->getClientCertCallbackX509().second, (void*) NULL);
ASSERT_EQ(params->getClientCertCallbackX509().first, (int (*)(void*, const Davix::SessionInfo&, Davix::X509Credential*, Davix::DavixError**)) NULL);
params->setSSLCAcheck(false);
struct timespec timeout_co, timeout_ops;
timeout_co.tv_sec =10;
timeout_co.tv_nsec=99;
timeout_ops.tv_sec=20;
timeout_ops.tv_nsec=0xFF;
ASSERT_EQ(params->getSSLCACheck(), false);
params->setOperationTimeout(&timeout_co);
ASSERT_EQ(params->getOperationTimeout()->tv_sec, 10);
params->setConnectionTimeout(&timeout_ops);
ASSERT_EQ(params->getConnectionTimeout()->tv_sec, 20);
Davix::RequestParams *p2 = new Davix::RequestParams(params);
Davix::RequestParams *p3 = new Davix::RequestParams(*p2);
Davix::RequestParams p4(params);
Davix::RequestParams p5(*p3);
ASSERT_EQ(p2->getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3->getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p2->getConnectionTimeout()->tv_sec, 20);
ASSERT_EQ(p3->getConnectionTimeout()->tv_sec, 20);
delete params;
delete p2;
delete p3;
}
TEST(DavixErrorTest, CreateDelete){
Davix::DavixError err("test_dav_scope", Davix::StatusCode::IsNotADirectory, " problem");
ASSERT_EQ(err.getErrMsg(), " problem");
ASSERT_EQ(err.getStatus(), Davix::StatusCode::IsNotADirectory);
ASSERT_EQ(err.getStatus(), DAVIX_STATUS_IS_NOT_A_DIRECTORY);
Davix::DavixError * err2=NULL;
Davix::DavixError::setupError(&err2,"test_dav_scope2", Davix::StatusCode::ConnectionProblem, "connexion problem");
ASSERT_EQ(err2->getErrMsg(), "connexion problem");
ASSERT_EQ(err2->getStatus(), Davix::StatusCode::ConnectionProblem);
Davix::DavixError::clearError(&err2);
Davix::DavixError::clearError(&err2);
}
<commit_msg>- fix problem related to external gtest build on EL5<commit_after>#include <config.h>
#include <davix.hpp>
#include <gtest/gtest.h>
// instanciate and play with gates
TEST(ContextTest, CreateDelete){
Davix::Context c1;
Davix::Context* c2 = c1.clone();
ASSERT_TRUE(c2 != NULL);
Davix::Context* c3 = c1.clone();
delete c2;
delete c3;
}
TEST(RequestParametersTest, CreateDelete){
Davix::RequestParams params;
ASSERT_EQ(params.getSSLCACheck(), true);
ASSERT_EQ(params.getOperationTimeout()->tv_sec, DAVIX_DEFAULT_OPS_TIMEOUT);
ASSERT_EQ(params.getConnectionTimeout()->tv_sec, DAVIX_DEFAULT_CONN_TIMEOUT);
ASSERT_TRUE((params.getClientCertCallbackX509().second == NULL));
ASSERT_TRUE((params.getClientCertCallbackX509().first == NULL));
ASSERT_TRUE( params.getTransparentRedirectionSupport());
params.setSSLCAcheck(false);
struct timespec timeout_co, timeout_ops;
timeout_co.tv_sec =10;
timeout_co.tv_nsec=99;
timeout_ops.tv_sec=20;
timeout_ops.tv_nsec=0xFF;
ASSERT_EQ(params.getSSLCACheck(), false);
params.setOperationTimeout(&timeout_co);
ASSERT_EQ(params.getOperationTimeout()->tv_sec, 10);
params.setConnectionTimeout(&timeout_ops);
ASSERT_EQ(params.getConnectionTimeout()->tv_sec, 20);
params.setTransparentRedirectionSupport(false);
ASSERT_FALSE( params.getTransparentRedirectionSupport());
Davix::RequestParams p2(¶ms);
Davix::RequestParams p3(p2);
ASSERT_EQ(p2.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p2.getConnectionTimeout()->tv_sec, 20);
ASSERT_EQ(p3.getConnectionTimeout()->tv_sec, 20);
ASSERT_FALSE( p2.getTransparentRedirectionSupport());
Davix::RequestParams p4 = p3; // test deep copy
ASSERT_EQ(p2.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3.getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p4.getConnectionTimeout()->tv_sec, 20);
}
TEST(RequestParametersTest, CreateDeleteDyn){
Davix::RequestParams* params = new Davix::RequestParams();
ASSERT_EQ(params->getSSLCACheck(), true);
ASSERT_EQ(params->getOperationTimeout()->tv_sec, DAVIX_DEFAULT_OPS_TIMEOUT);
ASSERT_EQ(params->getConnectionTimeout()->tv_sec, DAVIX_DEFAULT_CONN_TIMEOUT);
ASSERT_TRUE(params->getClientCertCallbackX509().second == NULL);
ASSERT_TRUE(params->getClientCertCallbackX509().first == NULL);
params->setSSLCAcheck(false);
struct timespec timeout_co, timeout_ops;
timeout_co.tv_sec =10;
timeout_co.tv_nsec=99;
timeout_ops.tv_sec=20;
timeout_ops.tv_nsec=0xFF;
ASSERT_EQ(params->getSSLCACheck(), false);
params->setOperationTimeout(&timeout_co);
ASSERT_EQ(params->getOperationTimeout()->tv_sec, 10);
params->setConnectionTimeout(&timeout_ops);
ASSERT_EQ(params->getConnectionTimeout()->tv_sec, 20);
Davix::RequestParams *p2 = new Davix::RequestParams(params);
Davix::RequestParams *p3 = new Davix::RequestParams(*p2);
Davix::RequestParams p4(params);
Davix::RequestParams p5(*p3);
ASSERT_EQ(p2->getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p3->getOperationTimeout()->tv_sec, 10);
ASSERT_EQ(p2->getConnectionTimeout()->tv_sec, 20);
ASSERT_EQ(p3->getConnectionTimeout()->tv_sec, 20);
delete params;
delete p2;
delete p3;
}
TEST(DavixErrorTest, CreateDelete){
Davix::DavixError err("test_dav_scope", Davix::StatusCode::IsNotADirectory, " problem");
ASSERT_EQ(err.getErrMsg(), " problem");
ASSERT_EQ(err.getStatus(), Davix::StatusCode::IsNotADirectory);
ASSERT_EQ(err.getStatus(), DAVIX_STATUS_IS_NOT_A_DIRECTORY);
Davix::DavixError * err2=NULL;
Davix::DavixError::setupError(&err2,"test_dav_scope2", Davix::StatusCode::ConnectionProblem, "connexion problem");
ASSERT_EQ(err2->getErrMsg(), "connexion problem");
ASSERT_EQ(err2->getStatus(), Davix::StatusCode::ConnectionProblem);
Davix::DavixError::clearError(&err2);
Davix::DavixError::clearError(&err2);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#if !defined(_HP_NAMESPACE_STD)
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_OLD_STREAMS
#define XALAN_NO_NAMESPACES
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_SGI_BASED_STL
#define XALAN_NO_STD_NUMERIC_LIMITS
#endif
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_RTTI_AVAILABLE
#define XALAN_POSIX2_AVAILABLE
#define XALAN_INLINE_INITIALIZATION
#define XALAN_UNALIGNED
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Use modern STL when possible.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#if defined(_HP_NAMESPACE_STD)
#define XALAN_MODERN_STL
#else
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_OLD_STREAMS
#define XALAN_NO_NAMESPACES
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_SGI_BASED_STL
#define XALAN_NO_STD_NUMERIC_LIMITS
#endif
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_RTTI_AVAILABLE
#define XALAN_POSIX2_AVAILABLE
#define XALAN_INLINE_INITIALIZATION
#define XALAN_UNALIGNED
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>// Copyright 2016 AUV-IITK
#include <ros.h>
#include <Arduino.h>
#include <std_msgs/Int32.h>
#include <math.h>
#define pwmPinWest 3
#define pwmPinEast 2
#define directionPinEast1 30
#define directionPinEast2 31
#define directionPinWest1 32
#define directionPinWest2 33
#define pwmPinNorthSway 5
#define pwmPinSouthSway 4
#define directionPinSouthSway1 27
#define directionPinSouthSway2 26
#define directionPinNorthSway1 29
#define directionPinNorthSway2 28
#define pwmPinNorthUp 6
#define pwmPinSouthUp 7
#define directionPinNorthUp1 24
#define directionPinNorthUp2 25
#define directionPinSouthUp1 22
#define directionPinSouthUp2 23
#define analogPinPressureSensor A0
const float c092 = 506.22;
const float s092 = -2.65;
const float c093 = 448.62;
const float s093 = -2.92;
const float c099 = 397.65; // reference as their graph is at lowest
const float s099 = -2.71; // reference as their graph is at lowest
const float c113 = 539.85;
const float s113 = -3.38;
const float c117 = 441.32;
const float s117 = -3.03;
const float c122 = 547.39;
const float s122 = -2.93;
int Delay = 1500;
bool isMovingForward = true;
ros::NodeHandle nh;
int btd092(int pwm)
{
pwm = (c099 + s099 * pwm - c092) / (s092);
return pwm;
}
int btd093(int pwm)
{
pwm = (c099 + s099 * pwm - c093) / (s093);
return pwm;
}
int btd099(int pwm)
{
return pwm;
}
int btd113(int pwm)
{
pwm = (c099 + s099 * pwm - c113) / (s113);
return pwm;
}
int btd117(int pwm)
{
pwm = (c099 + s099 * pwm - c117) / (s117);
return pwm;
}
int btd122(int pwm)
{
pwm = (c099 + s099 * pwm - c122) / (s122);
return pwm;
}
void thrusterNorthUp(int pwm, int isUpward)
{
pwm = abs(pwm);
pwm = btd117(pwm);
analogWrite(pwmPinNorthUp, 255 - pwm);
if (isUpward)
{
digitalWrite(directionPinNorthUp1, HIGH);
digitalWrite(directionPinNorthUp2, LOW);
}
else
{
digitalWrite(directionPinNorthUp1, LOW);
digitalWrite(directionPinNorthUp2, HIGH);
}
}
void thrusterSouthUp(int pwm, int isUpward)
{
pwm = abs(pwm);
pwm = btd093(pwm);
analogWrite(pwmPinSouthUp, 255 - pwm);
if (isUpward)
{
digitalWrite(directionPinSouthUp1, HIGH);
digitalWrite(directionPinSouthUp2, LOW);
}
else
{
digitalWrite(directionPinSouthUp1, LOW);
digitalWrite(directionPinSouthUp2, HIGH);
}
}
void thrusterNorthSway(int pwm, int isRight)
{
pwm = abs(pwm);
pwm = btd113(pwm);
analogWrite(pwmPinNorthSway, 255 - pwm);
if (isRight)
{
digitalWrite(directionPinNorthSway1, HIGH);
digitalWrite(directionPinNorthSway2, LOW);
}
else
{
digitalWrite(directionPinNorthSway1, LOW);
digitalWrite(directionPinNorthSway2, HIGH);
}
}
void thrusterSouthSway(int pwm, int isRight)
{
pwm = abs(pwm);
pwm = btd122(pwm);
analogWrite(pwmPinSouthSway, 255 - pwm);
if (isRight)
{
digitalWrite(directionPinSouthSway1, HIGH);
digitalWrite(directionPinSouthSway2, LOW);
}
else
{
digitalWrite(directionPinSouthSway1, LOW);
digitalWrite(directionPinSouthSway2, HIGH);
}
}
void thrusterEast(int pwm, int isForward)
{
pwm = abs(pwm);
pwm = btd092(pwm);
analogWrite(pwmPinEast, 255 - pwm);
if (isForward)
{
digitalWrite(directionPinEast1, HIGH);
digitalWrite(directionPinEast2, LOW);
}
else
{
digitalWrite(directionPinEast1, LOW);
digitalWrite(directionPinEast2, HIGH);
}
}
void thrusterWest(int pwm, int isForward)
{
pwm = abs(pwm);
pwm = btd099(pwm);
analogWrite(pwmPinWest, 255 - pwm);
if (isForward)
{
digitalWrite(directionPinWest1, HIGH);
digitalWrite(directionPinWest2, LOW);
}
else
{
digitalWrite(directionPinWest1, LOW);
digitalWrite(directionPinWest2, HIGH);
}
}
void PWMCbForward(const std_msgs::Int32 &msg)
{
if (msg.data > 0)
{
thrusterEast(msg.data, true);
thrusterWest(msg.data, true);
}
else
{
thrusterEast(msg.data, false);
thrusterWest(msg.data, false);
}
isMovingForward = true;
}
void PWMCbSideward(const std_msgs::Int32 &msg)
{
if (msg.data > 0)
{
thrusterNorthSway(msg.data, true);
thrusterSouthSway(msg.data, true);
}
else
{
thrusterNorthSway(msg.data, false);
thrusterSouthSway(msg.data, false);
}
isMovingForward = false;
}
void PWMCbUpward(const std_msgs::Int32 &msg)
{
if (msg.data > 0)
{
thrusterNorthUp(msg.data, true);
thrusterSouthUp(msg.data, true);
}
else
{
thrusterNorthUp(msg.data, false);
thrusterSouthUp(msg.data, false);
}
}
void PWMCbTurnSway(const std_msgs::Int32 &msg)
{
if (msg.data > 0)
{
thrusterEast(msg.data, true);
thrusterWest(msg.data, false);
}
else
{
thrusterEast(msg.data, false);
thrusterWest(msg.data, true);
}
}
void PWMCbTurn(const std_msgs::Int32 &msg)
{
if (msg.data > 0)
{
thrusterNorthSway(msg.data, false);
thrusterSouthSway(msg.data, true);
}
else
{
thrusterNorthSway(msg.data, true);
thrusterSouthSway(msg.data, false);
}
}
ros::Subscriber<std_msgs::Int32> subPwmForward("/pwm/forward", &PWMCbForward);
ros::Subscriber<std_msgs::Int32> subPwmSideward("/pwm/sideward", &PWMCbSideward);
ros::Subscriber<std_msgs::Int32> subPwmUpward("/pwm/upward", &PWMCbUpward);
ros::Subscriber<std_msgs::Int32> subPwmTurnSway("/pwm/turnsway", &PWMCbTurnSway);
ros::Subscriber<std_msgs::Int32> subPwmTurn("/pwm/turn", &PWMCbTurn);
void setup()
{
nh.initNode();
pinMode(directionPinEast1, OUTPUT);
pinMode(directionPinEast2, OUTPUT);
pinMode(pwmPinWest, OUTPUT);
pinMode(directionPinWest2, OUTPUT);
pinMode(pwmPinEast, OUTPUT);
pinMode(directionPinWest1, OUTPUT);
pinMode(directionPinSouthSway1, OUTPUT);
pinMode(directionPinSouthSway2, OUTPUT);
pinMode(pwmPinNorthSway, OUTPUT);
pinMode(directionPinNorthSway2, OUTPUT);
pinMode(pwmPinSouthSway, OUTPUT);
pinMode(directionPinNorthSway1, OUTPUT);
pinMode(directionPinSouthUp1, OUTPUT);
pinMode(directionPinSouthUp2, OUTPUT);
pinMode(pwmPinNorthUp, OUTPUT);
pinMode(directionPinNorthUp2, OUTPUT);
pinMode(pwmPinSouthUp, OUTPUT);
pinMode(directionPinNorthUp1, OUTPUT);
nh.subscribe(subPwmForward);
nh.subscribe(subPwmSideward);
nh.subscribe(subPwmUpward);
nh.subscribe(subPwmTurn);
nh.subscribe(subPwmTurnSway);
Serial.begin(57600);
}
void loop()
{
nh.spinOnce();
delay(1);
}
<commit_msg>new testing arduino node<commit_after>// Copyright 2016 AUV-IITK
#include <ros.h>
#include <Arduino.h>
#include <std_msgs/Int32.h>
#include <std_msgs/Float64.h>
#include <math.h>
#include <Wire.h>
#include "MS5837.h"
#define pwmPinWest 3
#define pwmPinEast 2
#define directionPinEast1 30
#define directionPinEast2 31
#define directionPinWest1 32
#define directionPinWest2 33
#define pwmPinNorthSway 5
#define pwmPinSouthSway 4
#define directionPinSouthSway1 27
#define directionPinSouthSway2 26
#define directionPinNorthSway1 29
#define directionPinNorthSway2 28
#define pwmPinNorthUp 6
#define pwmPinSouthUp 7
#define directionPinNorthUp1 24
#define directionPinNorthUp2 25
#define directionPinSouthUp1 22
#define directionPinSouthUp2 23
#define analogPinPressureSensor A0
const float c092 = 506.22;
const float s092 = -2.65;
const float c093 = 448.62;
const float s093 = -2.92;
const float c099 = 397.65; // reference as their graph is at lowest
const float s099 = -2.71; // reference as their graph is at lowest
const float c113 = 539.85;
const float s113 = -3.38;
const float c117 = 441.32;
const float s117 = -3.03;
const float c122 = 547.39;
const float s122 = -2.93;
const int neutral_buoyancy_offset = 0;
MS5837 sensor;
bool isMovingForward = true;
float minUpwardPWM = 120;
float biasSouthUp = 0;
float last_pressure_sensor_value, pressure_sensor_value;
std_msgs::Float64 voltage;
ros::NodeHandle nh;
int NormalizePWM(int pwm)
{
return pwm * 53 / 255 + 147;
}
int NormalizeUpwardPWM(int pwm)
{
return pwm * 73 / 255 + minUpwardPWM;
}
int btd092(int pwm)
{
pwm = NormalizePWM(pwm);
if (pwm <= 147)
{
return 0;
}
pwm = (c099 + s099 * pwm - c092) / (s092);
return pwm;
}
int btd093(int pwm)
{
pwm = NormalizeUpwardPWM(pwm);
if (pwm <= minUpwardPWM)
{
return 0;
}
pwm = (c099 + s099 * pwm - c093) / (s093);
return pwm;
}
int btd099(int pwm)
{
pwm = NormalizePWM(pwm);
if (pwm <= 147)
{
return 0;
}
return pwm;
}
int btd113(int pwm)
{
pwm = NormalizePWM(pwm);
if (pwm <= 147)
{
return 0;
}
pwm = (c099 + s099 * pwm - c113) / (s113);
return pwm;
}
int btd117(int pwm)
{
pwm = NormalizeUpwardPWM(pwm);
if (pwm <= minUpwardPWM)
{
return 0;
}
pwm = (c099 + s099 * pwm - c117) / (s117);
return pwm;
}
int btd122(int pwm)
{
pwm = NormalizePWM(pwm);
if (pwm <= 147)
{
return 0;
}
pwm = (c099 + s099 * pwm - c122) / (s122);
return pwm;
}
void thrusterNorthUp(int pwm, int isUpward)
{
pwm = abs(pwm);
pwm = btd117(pwm);
analogWrite(pwmPinNorthUp, 255 - pwm);
if (isUpward)
{
digitalWrite(directionPinNorthUp1, HIGH);
digitalWrite(directionPinNorthUp2, LOW);
}
else
{
digitalWrite(directionPinNorthUp1, LOW);
digitalWrite(directionPinNorthUp2, HIGH);
}
}
void thrusterSouthUp(int pwm, int isUpward)
{
pwm = abs(pwm) + biasSouthUp;
pwm = btd093(pwm);
analogWrite(pwmPinSouthUp, 255 - pwm);
if (isUpward)
{
digitalWrite(directionPinSouthUp1, HIGH);
digitalWrite(directionPinSouthUp2, LOW);
}
else
{
digitalWrite(directionPinSouthUp1, LOW);
digitalWrite(directionPinSouthUp2, HIGH);
}
}
void thrusterNorthSway(int pwm, int isRight)
{
pwm = abs(pwm);
pwm = btd113(pwm);
analogWrite(pwmPinNorthSway, 255 - pwm);
if (isRight)
{
digitalWrite(directionPinNorthSway1, HIGH);
digitalWrite(directionPinNorthSway2, LOW);
}
else
{
digitalWrite(directionPinNorthSway1, LOW);
digitalWrite(directionPinNorthSway2, HIGH);
}
}
void thrusterSouthSway(int pwm, int isRight)
{
pwm = abs(pwm);
pwm = btd122(pwm);
analogWrite(pwmPinSouthSway, 255 - pwm);
if (isRight)
{
digitalWrite(directionPinSouthSway1, HIGH);
digitalWrite(directionPinSouthSway2, LOW);
}
else
{
digitalWrite(directionPinSouthSway1, LOW);
digitalWrite(directionPinSouthSway2, HIGH);
}
}
void thrusterEast(int pwm, int isForward)
{
pwm = abs(pwm);
pwm = btd092(pwm);
analogWrite(pwmPinEast, 255 - pwm);
if (isForward)
{
digitalWrite(directionPinEast1, HIGH);
digitalWrite(directionPinEast2, LOW);
}
else
{
digitalWrite(directionPinEast1, LOW);
digitalWrite(directionPinEast2, HIGH);
}
}
void thrusterWest(int pwm, int isForward)
{
pwm = abs(pwm);
pwm = btd099(pwm);
analogWrite(pwmPinWest, 255 - pwm);
if (isForward)
{
digitalWrite(directionPinWest1, HIGH);
digitalWrite(directionPinWest2, LOW);
}
else
{
digitalWrite(directionPinWest1, LOW);
digitalWrite(directionPinWest2, HIGH);
}
}
void PWMCbForward(const std_msgs::Int32& msg)
{
if (msg.data > 0)
{
thrusterEast(msg.data, true);
thrusterWest(msg.data, true);
}
else
{
thrusterEast(msg.data, false);
thrusterWest(msg.data, false);
}
isMovingForward = true;
}
void PWMCbSideward(const std_msgs::Int32& msg)
{
if (msg.data > 0)
{
thrusterNorthSway(msg.data, true);
thrusterSouthSway(msg.data, true);
}
else
{
thrusterNorthSway(msg.data, false);
thrusterSouthSway(msg.data, false);
}
isMovingForward = false;
}
void PWMCbUpward(const std_msgs::Int32& msg)
{
int pwm = msg.data;
pwm = pwm + neutral_buoyancy_offset;
if (pwm > 0)
{
thrusterNorthUp(pwm, true);
thrusterSouthUp(pwm, true);
}
else
{
thrusterNorthUp(pwm, false);
thrusterSouthUp(pwm, false);
}
}
void PWMCbTurn(const std_msgs::Int32& msg)
{
if (!isMovingForward)
{
if (msg.data > 0)
{
thrusterEast(msg.data, true);
thrusterWest(msg.data, false);
}
else
{
thrusterEast(msg.data, false);
thrusterWest(msg.data, true);
}
}
else
{
if (msg.data > 0)
{
thrusterNorthSway(msg.data, false);
thrusterSouthSway(msg.data, true);
}
else
{
thrusterNorthSway(msg.data, true);
thrusterSouthSway(msg.data, false);
}
}
}
void setMinUpwardPWM(const std_msgs::Int32& msg)
{
minUpwardPWM = msg.data;
}
void setBiasSouthUp(const std_msgs::Int32& msg)
{
biasSouthUp = msg.data;
}
ros::Subscriber<std_msgs::Int32> subPwmForward("/pwm/forward", &PWMCbForward);
ros::Subscriber<std_msgs::Int32> subPwmSideward("/pwm/sideward", &PWMCbSideward);
ros::Subscriber<std_msgs::Int32> subPwmUpward("/pwm/upward", &PWMCbUpward);
ros::Subscriber<std_msgs::Int32> subPwmTurn("/pwm/turn", &PWMCbTurn);
ros::Subscriber<std_msgs::Int32> subMinUpwardPWM("/pwm/minupwardpwm", &setMinUpwardPWM);
ros::Subscriber<std_msgs::Int32> subBiasSouthUp("/pwm/biassouthup", &setBiasSouthUp);
ros::Publisher ps_voltage("/varun/sensors/pressure_sensor/depth", &voltage);
void setup()
{
nh.initNode();
Wire.begin();
sensor.init();
sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
pinMode(pwmPinEast, OUTPUT);
pinMode(directionPinEast1, OUTPUT);
pinMode(directionPinEast2, OUTPUT);
pinMode(pwmPinWest, OUTPUT);
pinMode(directionPinWest1, OUTPUT);
pinMode(directionPinWest2, OUTPUT);
pinMode(directionPinSouthSway1, OUTPUT);
pinMode(directionPinSouthSway2, OUTPUT);
pinMode(pwmPinNorthSway, OUTPUT);
pinMode(directionPinNorthSway2, OUTPUT);
pinMode(pwmPinSouthSway, OUTPUT);
pinMode(directionPinNorthSway1, OUTPUT);
pinMode(directionPinSouthUp1, OUTPUT);
pinMode(directionPinSouthUp2, OUTPUT);
pinMode(pwmPinNorthUp, OUTPUT);
pinMode(directionPinNorthUp2, OUTPUT);
pinMode(pwmPinSouthUp, OUTPUT);
pinMode(directionPinNorthUp1, OUTPUT);
nh.subscribe(subPwmForward);
nh.subscribe(subPwmSideward);
nh.subscribe(subPwmUpward);
nh.subscribe(subPwmTurn);
nh.subscribe(subMinUpwardPWM);
nh.subscribe(subBiasSouthUp);
nh.advertise(ps_voltage);
Serial.begin(57600);
std_msgs::Int32 msg;
msg.data = 0;
PWMCbForward(msg);
PWMCbSideward(msg);
PWMCbUpward(msg);
PWMCbTurn(msg);
sensor.read();
last_pressure_sensor_value = -(sensor.depth() * 100);
}
void loop()
{
sensor.read();
// voltage.data made -ve because pressure sensor data should increase going up
pressure_sensor_value = -(sensor.depth() * 100);
// to avoid random high values
if (abs(last_pressure_sensor_value - pressure_sensor_value) < 100)
{
voltage.data = 0.7 * pressure_sensor_value + 0.3 * last_pressure_sensor_value;
ps_voltage.publish(&voltage);
last_pressure_sensor_value = pressure_sensor_value;
}
delay(200);
nh.spinOnce();
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkError.h"
#include "SkPath.h"
#include "SkRect.h"
#define CHECK(errcode) \
REPORTER_ASSERT( reporter, (err = SkGetLastError()) == errcode); \
if (err != kNoError_SkError) \
{ \
SkDebugf("Last error string: %s\n", SkGetLastErrorString()); \
SkClearLastError(); \
}
void cb(SkError err, void *context) {
int *context_ptr = static_cast<int *>(context);
SkDebugf("CB (0x%x): %s\n", *context_ptr, SkGetLastErrorString());
}
static void ErrorTest(skiatest::Reporter* reporter) {
SkError err;
CHECK(kNoError_SkError);
SkRect r = SkRect::MakeWH(50, 100);
CHECK(kNoError_SkError);
SkPath path;
path.addRect(r);
CHECK(kNoError_SkError);
path.addRoundRect(r, 10, 10);
CHECK(kNoError_SkError);
// should trigger the default error callback, which just prints to the screen.
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
int test_value = 0xdeadbeef;
SkSetErrorCallback(cb, &test_value);
// should trigger *our* callback.
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
// Should trigger the default one again.
SkSetErrorCallback(NULL, NULL);
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Error", ErrorTestClass, ErrorTest)
<commit_msg>silence android warning<commit_after>
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkError.h"
#include "SkPath.h"
#include "SkRect.h"
#define CHECK(errcode) \
REPORTER_ASSERT( reporter, (err = SkGetLastError()) == errcode); \
if (err != kNoError_SkError) \
{ \
SkDebugf("Last error string: %s\n", SkGetLastErrorString()); \
SkClearLastError(); \
}
static void cb(SkError err, void *context) {
int *context_ptr = static_cast<int *>(context);
SkDebugf("CB (0x%x): %s\n", *context_ptr, SkGetLastErrorString());
}
static void ErrorTest(skiatest::Reporter* reporter) {
SkError err;
CHECK(kNoError_SkError);
SkRect r = SkRect::MakeWH(50, 100);
CHECK(kNoError_SkError);
SkPath path;
path.addRect(r);
CHECK(kNoError_SkError);
path.addRoundRect(r, 10, 10);
CHECK(kNoError_SkError);
// should trigger the default error callback, which just prints to the screen.
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
int test_value = 0xdeadbeef;
SkSetErrorCallback(cb, &test_value);
// should trigger *our* callback.
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
// Should trigger the default one again.
SkSetErrorCallback(NULL, NULL);
path.addRoundRect(r, -10, -10);
CHECK(kInvalidArgument_SkError);
CHECK(kNoError_SkError);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Error", ErrorTestClass, ErrorTest)
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Sacha Refshauge
*
*/
// Qt 4.7 implementation of the framework.
// Currently supports: Symbian, Blackberry, Meego, Linux, Windows
#include <QApplication>
#include <QUrl>
#include <QDir>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QLocale>
#include <QThread>
#ifdef __SYMBIAN32__
#include <e32std.h>
#include <QSystemScreenSaver>
#include <hwrmvibra.h>
#endif
#include "QtMain.h"
InputState* input_state;
std::string System_GetProperty(SystemProperty prop) {
switch (prop) {
case SYSPROP_NAME:
#ifdef __SYMBIAN32__
return "Qt:Symbian";
#elif defined(BLACKBERRY)
return "Qt:Blackberry10";
#elif defined(MEEGO_EDITION_HARMATTAN)
return "Qt:Meego";
#elif defined(Q_OS_LINUX)
return "Qt:Linux";
#elif defined(_WIN32)
return "Qt:Windows";
#else
return "Qt";
#endif
case SYSPROP_LANGREGION:
return QLocale::system().name().toStdString();
default:
return "";
}
}
#ifdef __SYMBIAN32__
CHWRMVibra* vibra;
#endif
void Vibrate(int length_ms) {
if (length_ms == -1 || length_ms == -3)
length_ms = 50;
else if (length_ms == -2)
length_ms = 25;
// Qt 4.8 does not have any cross-platform Vibrate. Symbian-only for now.
#ifdef __SYMBIAN32__
CHWRMVibra::TVibraModeState iState = vibra->VibraSettings();
CHWRMVibra::TVibraStatus iStatus = vibra->VibraStatus();
// User has not enabled vibration in settings.
if(iState != CHWRMVibra::EVibraModeON)
return;
if(iStatus != CHWRMVibra::EVibraStatusStopped)
vibra->StopVibraL();
#endif
#ifdef __SYMBIAN32__
vibra->StartVibraL(length_ms, 20);
#endif
}
void LaunchBrowser(const char *url)
{
QDesktopServices::openUrl(QUrl(url));
}
void SimulateGamepad(InputState *input) {
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
if (input->pad_buttons & PAD_BUTTON_JOY_UP)
input->pad_lstick_y=1;
else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
input->pad_lstick_y=-1;
if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
input->pad_lstick_x=-1;
else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
input->pad_lstick_x=1;
}
float CalculateDPIScale()
{
// Sane default rather than check DPI
#ifdef __SYMBIAN32__
return 1.4f;
#else
return 1.2f;
#endif
}
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
QApplication a(argc, argv);
QSize res = QApplication::desktop()->screenGeometry().size();
if (res.width() < res.height())
res.transpose();
pixel_xres = res.width();
pixel_yres = res.height();
#ifdef ARM
g_dpi_scale = CalculateDPIScale();
#else
g_dpi_scale = 1.0f;
#endif
dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale);
net::Init();
#ifdef __SYMBIAN32__
const char *savegame_dir = "E:/PPSSPP/";
const char *assets_dir = "E:/PPSSPP/";
#elif defined(BLACKBERRY)
const char *savegame_dir = "/accounts/1000/shared/misc/";
const char *assets_dir = "app/native/assets/";
#elif defined(MEEGO_EDITION_HARMATTAN)
const char *savegame_dir = "/home/user/MyDocs/PPSSPP/";
QDir myDocs("/home/user/MyDocs/");
if (!myDocs.exists("PPSSPP"))
myDocs.mkdir("PPSSPP");
const char *assets_dir = "/opt/PPSSPP/";
#else
const char *savegame_dir = "./";
const char *assets_dir = "./";
#endif
NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE");
#if !defined(Q_OS_LINUX) || defined(ARM)
MainUI w;
w.resize(pixel_xres, pixel_yres);
#ifdef ARM
w.showFullScreen();
#else
w.show();
#endif
#endif
#ifdef __SYMBIAN32__
// Set RunFast hardware mode for VFPv2.
User::SetFloatingPointMode(EFpModeRunFast);
// Disable screensaver
QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w);
ssObject->setScreenSaverInhibit();
// Start vibration service
vibra = CHWRMVibra::NewL();
#endif
QThread* thread = new QThread;
MainAudio *audio = new MainAudio();
audio->moveToThread(thread);
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
int ret = a.exec();
delete audio;
thread->quit();
#ifdef __SYMBIAN32__
delete vibra;
#endif
NativeShutdown();
net::Shutdown();
return ret;
}
<commit_msg>Crash fix for Symbian. Will have to put up with crummy music a little bit longer.<commit_after>/*
* Copyright (c) 2012 Sacha Refshauge
*
*/
// Qt 4.7 implementation of the framework.
// Currently supports: Symbian, Blackberry, Meego, Linux, Windows
#include <QApplication>
#include <QUrl>
#include <QDir>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QLocale>
#include <QThread>
#ifdef __SYMBIAN32__
#include <e32std.h>
#include <QSystemScreenSaver>
#include <hwrmvibra.h>
#endif
#include "QtMain.h"
InputState* input_state;
std::string System_GetProperty(SystemProperty prop) {
switch (prop) {
case SYSPROP_NAME:
#ifdef __SYMBIAN32__
return "Qt:Symbian";
#elif defined(BLACKBERRY)
return "Qt:Blackberry10";
#elif defined(MEEGO_EDITION_HARMATTAN)
return "Qt:Meego";
#elif defined(Q_OS_LINUX)
return "Qt:Linux";
#elif defined(_WIN32)
return "Qt:Windows";
#else
return "Qt";
#endif
case SYSPROP_LANGREGION:
return QLocale::system().name().toStdString();
default:
return "";
}
}
#ifdef __SYMBIAN32__
CHWRMVibra* vibra;
#endif
void Vibrate(int length_ms) {
if (length_ms == -1 || length_ms == -3)
length_ms = 50;
else if (length_ms == -2)
length_ms = 25;
// Qt 4.8 does not have any cross-platform Vibrate. Symbian-only for now.
#ifdef __SYMBIAN32__
CHWRMVibra::TVibraModeState iState = vibra->VibraSettings();
CHWRMVibra::TVibraStatus iStatus = vibra->VibraStatus();
// User has not enabled vibration in settings.
if(iState != CHWRMVibra::EVibraModeON)
return;
if(iStatus != CHWRMVibra::EVibraStatusStopped)
vibra->StopVibraL();
#endif
#ifdef __SYMBIAN32__
vibra->StartVibraL(length_ms, 20);
#endif
}
void LaunchBrowser(const char *url)
{
QDesktopServices::openUrl(QUrl(url));
}
void SimulateGamepad(InputState *input) {
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
if (input->pad_buttons & PAD_BUTTON_JOY_UP)
input->pad_lstick_y=1;
else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
input->pad_lstick_y=-1;
if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
input->pad_lstick_x=-1;
else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
input->pad_lstick_x=1;
}
float CalculateDPIScale()
{
// Sane default rather than check DPI
#ifdef __SYMBIAN32__
return 1.4f;
#else
return 1.2f;
#endif
}
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
QApplication a(argc, argv);
QSize res = QApplication::desktop()->screenGeometry().size();
if (res.width() < res.height())
res.transpose();
pixel_xres = res.width();
pixel_yres = res.height();
#ifdef ARM
g_dpi_scale = CalculateDPIScale();
#else
g_dpi_scale = 1.0f;
#endif
dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale);
net::Init();
#ifdef __SYMBIAN32__
const char *savegame_dir = "E:/PPSSPP/";
const char *assets_dir = "E:/PPSSPP/";
#elif defined(BLACKBERRY)
const char *savegame_dir = "/accounts/1000/shared/misc/";
const char *assets_dir = "app/native/assets/";
#elif defined(MEEGO_EDITION_HARMATTAN)
const char *savegame_dir = "/home/user/MyDocs/PPSSPP/";
QDir myDocs("/home/user/MyDocs/");
if (!myDocs.exists("PPSSPP"))
myDocs.mkdir("PPSSPP");
const char *assets_dir = "/opt/PPSSPP/";
#else
const char *savegame_dir = "./";
const char *assets_dir = "./";
#endif
NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE");
#if !defined(Q_OS_LINUX) || defined(ARM)
MainUI w;
w.resize(pixel_xres, pixel_yres);
#ifdef ARM
w.showFullScreen();
#else
w.show();
#endif
#endif
#ifdef __SYMBIAN32__
// Set RunFast hardware mode for VFPv2.
User::SetFloatingPointMode(EFpModeRunFast);
// Disable screensaver
QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w);
ssObject->setScreenSaverInhibit();
// Start vibration service
vibra = CHWRMVibra::NewL();
#endif
#ifdef __SYMBIAN32__
MainAudio *audio = new MainAudio();
#else
QThread* thread = new QThread;
MainAudio *audio = new MainAudio();
audio->moveToThread(thread);
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
#endif
int ret = a.exec();
delete audio;
#ifdef __SYMBIAN32__
delete vibra;
#else
thread->quit();
#endif
NativeShutdown();
net::Shutdown();
return ret;
}
<|endoftext|>
|
<commit_before>#include "App.h"
#include "helpers.h"
/* This function pushes data to the uSockets mock */
extern "C" void us_loop_read_mocked_data(struct us_loop *loop, char *data, unsigned int size);
uWS::TemplatedApp<false> *app;
us_listen_socket_t *listenSocket;
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
app = new uWS::TemplatedApp<false>(uWS::App().get("/*", [](auto *res, auto *req) {
if (req->getHeader("use_write").length()) {
res->writeStatus("200 OK")->writeHeader("write", "true")->write("Hello");
res->write(" world!");
res->end();
} else if (req->getQuery().length()) {
res->close();
} else {
res->end("Hello world!");
}
})/*.post("/*", [](auto *res, auto *req) {
res->onAborted([]() {
});
res->onData([res](std::string_view chunk, bool isEnd) {
if (isEnd) {
res->end(chunk);
}
});
})*/.listen(9001, [](us_listen_socket_t *listenSocket) {
if (listenSocket) {
std::cout << "Listening on port " << 9001 << std::endl;
::listenSocket = listenSocket;
}
}));
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
us_loop_read_mocked_data((struct us_loop *) uWS::Loop::get(), (char *) makePadded(data, size), size);
return 0;
}
<commit_msg>Re-enable mocked post fuzz<commit_after>#include "App.h"
#include "helpers.h"
/* This function pushes data to the uSockets mock */
extern "C" void us_loop_read_mocked_data(struct us_loop *loop, char *data, unsigned int size);
uWS::TemplatedApp<false> *app;
us_listen_socket_t *listenSocket;
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
app = new uWS::TemplatedApp<false>(uWS::App().get("/*", [](auto *res, auto *req) {
if (req->getHeader("use_write").length()) {
res->writeStatus("200 OK")->writeHeader("write", "true")->write("Hello");
res->write(" world!");
res->end();
} else if (req->getQuery().length()) {
res->close();
} else {
res->end("Hello world!");
}
}).post("/*", [](auto *res, auto *req) {
res->onAborted([]() {
});
res->onData([res](std::string_view chunk, bool isEnd) {
if (isEnd) {
res->end(chunk);
}
});
}).listen(9001, [](us_listen_socket_t *listenSocket) {
if (listenSocket) {
std::cout << "Listening on port " << 9001 << std::endl;
::listenSocket = listenSocket;
}
}));
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
us_loop_read_mocked_data((struct us_loop *) uWS::Loop::get(), (char *) makePadded(data, size), size);
return 0;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include "glsl++.h"
namespace glsl {
struct shader {
float eps = 0.0001;
float pi = 3.1415926;
float pi2 = pi/2.0;
float pi4 = pi/4.0;
float time;
uniform vec3 origin;
uniform vec3 up;
uniform vec3 dir;
mat3 rm(float angle, vec3 n)
{
float c = cos(angle), s = sin(angle);
n = normalize(n);
return mat3(c,n.z*s,-n.y*s,
-n.z*s,c,n.x*s,
n.y*s,-n.x*s,c) + outerProduct(n * (1.0-c), n);
}
float hash( float n ) { return fract(sin(n)*43758.5453); }
float mix2(float x, float y, float a)
{
float z = (a - 0.5) * 2.0;
return mix(x, y, pow(abs(z), 1.5) * sign(z) * 0.5 + 0.5);
}
float noise( vec3 x )
{
vec3 p = floor(x);
vec3 f = fract(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + p.z * 43.0;
float res1 = mix2(mix2(hash(n+0.0), hash(n+1.0),f.x), mix2(hash(n+57.0), hash(n+57.0+1.0),f.x),f.y);
float res2 = mix2(mix2(hash(n+43.0), hash(n+43.0+1.0),f.x), mix2(hash(n+43.0+57.0), hash(n+43.0+57.0+1.0),f.x),f.y);
float res = mix2(res1, res2, f.z);
return res;
}
float cloud(vec3 p) {
float f = pow(0.5*(noise(p*1.0)+0.5*(noise(p*2.0)+0.5*(noise(p*4.0)+0.5*noise(p*8.0)))), 2.0);
return f;
}
float DIST_MULTIPLIER = 0.035;
float MAX_DIST = 100.0;
float
min_dist = 0.0001,
ao_eps = 0.0005,
ao_strength = 0.12,
glow_strength = 0.75,
dist_to_color = 0.1;
int
max_steps = 1800;
vec3
surfaceColor1 = vec3(0.95, 0.64, 0.1),
surfaceColor2 = vec3(0.89, 0.95, 0.75),
surfaceColor3 = vec3(0.55, 0.06, 0.03),
specularColor = vec3(1.0, 0.8, 0.4),
glowColor = vec3(0.03, 0.4, 0.4)/1.5,
aoColor = vec3(0, 0, 0),
fogColor = vec3(0.1);
void sphereFold(inout vec3& z, inout float& dz, float fixedRadius2) {
float r2 = dot(z,z) - 0.04;
if (r2<fixedRadius2) {
float temp =(fixedRadius2/r2);
z*=temp;
dz*=temp;
}
}
void boxFold(inout vec3& z, inout float& dz, vec3 foldingLimit) {
z = clamp(z, -foldingLimit, foldingLimit) * 2.0 - z;
}
void powN2(inout vec3& z, float zr0, inout float& dr, float Power2, float ZMUL) {
z.x = abs(z.x);
float zo0 = asin( z.z/zr0 );
float zi0 = atan( z.y,z.x );
float zr = pow( zr0, Power2-1.0 );
float zo = zo0 * Power2;
float zi = zi0 * Power2;
dr = zr*dr*Power2*abs(length(vec3(1.0,1.0,ZMUL)/sqrt(3.0))) + 1.0;
zr *= zr0;
z = zr*vec3( cos(zo)*cos(zi), cos(zo)*sin(zi), ZMUL*sin(zo) );
}
float DE(vec3 z, out vec3& col)
{
int n = 0;
float dr = 1.0;
float r = length(z);
vec4 trap = vec4(1.0f);
while (r<7.5 && n < 4) {
float sc = clamp(pow(z.z, 3.0), 0.75, 50.0);
boxFold(z,dr,vec3(0.5, 0.5, 1.282500));
sphereFold(z,dr,0.5);
r=length(z);
powN2(z,r,dr,2.437598,9.072040);
dr*=abs(sc);
z = sc*z;
r = length(z);
trap = min(trap, (vec4(abs(4.0*z),dot(z,z))));
n++;
}
vec2 c = clamp(vec2( 0.05*log(dot(z,z))-0.25, trap.z ), 0.0, 1.0);
col = mix(mix(surfaceColor1, surfaceColor2, trap.z*trap.w), surfaceColor3, c.x);
return (r * log(r) / abs(dr)) * DIST_MULTIPLIER;
}
float eval(vec3 pos, out vec3& col) {
return DE(pos, col);
}
float normal_eps = 0.000005;
vec3 normal(vec3 pos, float d_pos) {
vec4 Eps = vec4(0, normal_eps, 2.0*normal_eps, 3.0*normal_eps);
vec3 col;
return normalize(vec3(
-eval(pos-Eps.yxx,col)+eval(pos+Eps.yxx,col),
-eval(pos-Eps.xyx,col)+eval(pos+Eps.xyx,col),
-eval(pos-Eps.xxy,col)+eval(pos+Eps.xxy,col)
));
}
vec3 blinn_phong(vec3 normal, vec3 view, vec3 light, vec3 diffuseColor) {
vec3 halfLV = normalize(light + view);
float spe = pow(max( dot(normal, halfLV), 0.0 ), 32.0);
float dif = dot(normal, light) * 0.5 + 0.75;
return dif*diffuseColor + spe*specularColor;
}
float ambient_occlusion(vec3 p, vec3 n) {
float ao = 1.0, w = ao_strength/ao_eps;
float dist = 2.0 * ao_eps;
vec3 col;
for (int i=0; i<5; i++) {
float D = eval(p + n*dist,col);
ao -= (dist-D) * w;
w *= 0.5;
dist = dist*2.0 - ao_eps;
}
return clamp(ao, 0.0, 1.0);
}
float sphere(vec3 p) {
return length(p)-2.5;
}
float f(vec3 p) {
return sphere(p) + cloud(p*5.+time) * 2.0+1.0;
}
vec3 cast(inout vec3& dir, inout vec3& eye) {
vec3 eye_in = eye;
vec3 p = eye_in, dp = normalize(dir);
vec3 color;
float totalD = 0.0, D = 3.4e38, extraD = 0.0, lastD;
int steps;
for (steps=0; steps<max_steps; steps++) {
lastD = D;
D = eval(p + totalD * dp, color);
if (extraD > 0.0 && D < extraD) {
totalD -= extraD;
extraD = 0.0;
D = 3.4e38;
steps--;
continue;
}
if (D < min_dist || D > MAX_DIST) break;
totalD += D;
totalD += extraD = 0.096 * D*(D+extraD)/lastD;
}
vec3 p2 = p;
p2.z -= 12.;
float ld, td= 0.;
float w;
float l, lacc = 0.;
for (float i=0.; (i<1.); i+=1./64.) {
if(td > .95)
break;
l = f(p2) * 0.6;
if (l < .01) {
ld = 0.01 - l;
w = (1. - td) * ld;
td += w;
}
l = max(l, 0.03);
lacc += l;
if (lacc > totalD)
break;
p2 += l*dir;
}
vec3 edir = normalize(dp + p * 0.005);
p += totalD * dp;
vec3 backgroundColor = cloud(edir*10.0) * vec3(0.65, 0.45, 1.0) * 0.6;
backgroundColor += clamp(cloud(edir*150.0)-0.5, 0.0, 1.0)*10.0;
vec3 col = backgroundColor;
if (D < min_dist) {
vec3 n = normal(p, D);
col = color;
col = blinn_phong(n, -dp, normalize(eye_in+vec3(0,1,0)+dp), col);
col = mix(aoColor, col, ambient_occlusion(p, n));
}
col = mix(col, td*1.5*surfaceColor3 + ld*3*surfaceColor1, clamp(td*2, 0.0, 1.0));
col = mix(col, glowColor, float(steps)/float(max_steps) * glow_strength);
return col;
}
void glslmain( void )
{
vec2 p = vec2(gl_FragCoord.x + (gl_TexCoord[0].y - gl_TexCoord[0].x)/2.0, gl_FragCoord.y) / gl_TexCoord[0].yy * 2.0 - 1.0;
vec2 p2 = gl_FragCoord.xy / gl_TexCoord[0].xy * 2.0 - 1.0;
p /= 1.2;
mat3 m = mat3(1.0);
vec3 tr = vec3(0.0);
time = gl_TexCoord[0].z;
vec3 dir = normalize(vec3(1.0, 0.0, 1.5));
vec3 up = vec3(0.0, 1.0, 0.0);
vec3 origin = vec3(-5.0, 0.0, -5.0);
/* vec3 origin = pow(vec3(noise(vec3(time*0.09, 0., 0.)), noise(vec3(0., time*0.13, 0.)), noise(vec3(0., 0., time*0.11)))-0.5, 2.0)*15.0 - vec3(0.0, 0.0, 1.0);
vec3 dir = normalize(vec3(noise(vec3(time*0.17, 0., 0.)), noise(vec3(0., time*0.19, 0.)), noise(vec3(0., 0., time*0.21)))-0.5-origin*0.1);
vec3 up = -normalize(cross(normalize(cross(up, dir)), dir));*/
vec3 sorigin = origin;
vec3 sdir = normalize(p.x * cross(up, dir) + p.y * up + 1 * dir);
vec3 c1 = cast(sdir, sorigin);
vec3 c = c1;
c *= clamp(smoothstep(1.5, 0.5, length(p2)), 0.0, 1.0);
c *= 1.125;
gl_FragColor = vec4(pow(c, vec3(1.0 / 1.0)), 1.0);
}
vec4 gl_TexCoord[8];
vec4 gl_FragCoord;
vec4 gl_FragColor;
};
int main()
{
std::ofstream outfile("out.raw");
int xres = 720, yres = 480;
unsigned char *data = (unsigned char*) malloc(yres*xres*3);
params[0] = vec4(0.8f, 0.8f, 1.0f, 1.0f);
params[1] = vec4(0.2f, 0.4f, 0.01f, 3.0f);
#pragma omp parallel for schedule(dynamic, 4)
for (int y = 0; y < yres; ++y) {
for (int x = 0; x < xres; ++x) {
shader sh;
sh.gl_TexCoord[0] = vec4(xres, yres, 20.0f, 0.0f);
sh.gl_FragCoord = vec4(x, y, 0.0f, 0.0f);
sh.glslmain();
data[((yres-y-1)*xres+x)*3] = clamp(sh.gl_FragColor.r * 255, 0, 255);
data[((yres-y-1)*xres+x)*3+1] = clamp(sh.gl_FragColor.g * 255, 0, 255);
data[((yres-y-1)*xres+x)*3+2] = clamp(sh.gl_FragColor.b * 255, 0, 255);
}
}
// There's probably a better way to do this, something akin to fwrite(), in C++
for (long long i = 0; i < yres*xres*3; ++i) {
outfile << data[i];
}
free(data);
return 0;
}
}
int main()
{
return glsl::main();
}
<commit_msg>Also remove setting of params<commit_after>#include <fstream>
#include "glsl++.h"
namespace glsl {
struct shader {
float eps = 0.0001;
float pi = 3.1415926;
float pi2 = pi/2.0;
float pi4 = pi/4.0;
float time;
uniform vec3 origin;
uniform vec3 up;
uniform vec3 dir;
mat3 rm(float angle, vec3 n)
{
float c = cos(angle), s = sin(angle);
n = normalize(n);
return mat3(c,n.z*s,-n.y*s,
-n.z*s,c,n.x*s,
n.y*s,-n.x*s,c) + outerProduct(n * (1.0-c), n);
}
float hash( float n ) { return fract(sin(n)*43758.5453); }
float mix2(float x, float y, float a)
{
float z = (a - 0.5) * 2.0;
return mix(x, y, pow(abs(z), 1.5) * sign(z) * 0.5 + 0.5);
}
float noise( vec3 x )
{
vec3 p = floor(x);
vec3 f = fract(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + p.z * 43.0;
float res1 = mix2(mix2(hash(n+0.0), hash(n+1.0),f.x), mix2(hash(n+57.0), hash(n+57.0+1.0),f.x),f.y);
float res2 = mix2(mix2(hash(n+43.0), hash(n+43.0+1.0),f.x), mix2(hash(n+43.0+57.0), hash(n+43.0+57.0+1.0),f.x),f.y);
float res = mix2(res1, res2, f.z);
return res;
}
float cloud(vec3 p) {
float f = pow(0.5*(noise(p*1.0)+0.5*(noise(p*2.0)+0.5*(noise(p*4.0)+0.5*noise(p*8.0)))), 2.0);
return f;
}
float DIST_MULTIPLIER = 0.035;
float MAX_DIST = 100.0;
float
min_dist = 0.0001,
ao_eps = 0.0005,
ao_strength = 0.12,
glow_strength = 0.75,
dist_to_color = 0.1;
int
max_steps = 1800;
vec3
surfaceColor1 = vec3(0.95, 0.64, 0.1),
surfaceColor2 = vec3(0.89, 0.95, 0.75),
surfaceColor3 = vec3(0.55, 0.06, 0.03),
specularColor = vec3(1.0, 0.8, 0.4),
glowColor = vec3(0.03, 0.4, 0.4)/1.5,
aoColor = vec3(0, 0, 0),
fogColor = vec3(0.1);
void sphereFold(inout vec3& z, inout float& dz, float fixedRadius2) {
float r2 = dot(z,z) - 0.04;
if (r2<fixedRadius2) {
float temp =(fixedRadius2/r2);
z*=temp;
dz*=temp;
}
}
void boxFold(inout vec3& z, inout float& dz, vec3 foldingLimit) {
z = clamp(z, -foldingLimit, foldingLimit) * 2.0 - z;
}
void powN2(inout vec3& z, float zr0, inout float& dr, float Power2, float ZMUL) {
z.x = abs(z.x);
float zo0 = asin( z.z/zr0 );
float zi0 = atan( z.y,z.x );
float zr = pow( zr0, Power2-1.0 );
float zo = zo0 * Power2;
float zi = zi0 * Power2;
dr = zr*dr*Power2*abs(length(vec3(1.0,1.0,ZMUL)/sqrt(3.0))) + 1.0;
zr *= zr0;
z = zr*vec3( cos(zo)*cos(zi), cos(zo)*sin(zi), ZMUL*sin(zo) );
}
float DE(vec3 z, out vec3& col)
{
int n = 0;
float dr = 1.0;
float r = length(z);
vec4 trap = vec4(1.0f);
while (r<7.5 && n < 4) {
float sc = clamp(pow(z.z, 3.0), 0.75, 50.0);
boxFold(z,dr,vec3(0.5, 0.5, 1.282500));
sphereFold(z,dr,0.5);
r=length(z);
powN2(z,r,dr,2.437598,9.072040);
dr*=abs(sc);
z = sc*z;
r = length(z);
trap = min(trap, (vec4(abs(4.0*z),dot(z,z))));
n++;
}
vec2 c = clamp(vec2( 0.05*log(dot(z,z))-0.25, trap.z ), 0.0, 1.0);
col = mix(mix(surfaceColor1, surfaceColor2, trap.z*trap.w), surfaceColor3, c.x);
return (r * log(r) / abs(dr)) * DIST_MULTIPLIER;
}
float eval(vec3 pos, out vec3& col) {
return DE(pos, col);
}
float normal_eps = 0.000005;
vec3 normal(vec3 pos, float d_pos) {
vec4 Eps = vec4(0, normal_eps, 2.0*normal_eps, 3.0*normal_eps);
vec3 col;
return normalize(vec3(
-eval(pos-Eps.yxx,col)+eval(pos+Eps.yxx,col),
-eval(pos-Eps.xyx,col)+eval(pos+Eps.xyx,col),
-eval(pos-Eps.xxy,col)+eval(pos+Eps.xxy,col)
));
}
vec3 blinn_phong(vec3 normal, vec3 view, vec3 light, vec3 diffuseColor) {
vec3 halfLV = normalize(light + view);
float spe = pow(max( dot(normal, halfLV), 0.0 ), 32.0);
float dif = dot(normal, light) * 0.5 + 0.75;
return dif*diffuseColor + spe*specularColor;
}
float ambient_occlusion(vec3 p, vec3 n) {
float ao = 1.0, w = ao_strength/ao_eps;
float dist = 2.0 * ao_eps;
vec3 col;
for (int i=0; i<5; i++) {
float D = eval(p + n*dist,col);
ao -= (dist-D) * w;
w *= 0.5;
dist = dist*2.0 - ao_eps;
}
return clamp(ao, 0.0, 1.0);
}
float sphere(vec3 p) {
return length(p)-2.5;
}
float f(vec3 p) {
return sphere(p) + cloud(p*5.+time) * 2.0+1.0;
}
vec3 cast(inout vec3& dir, inout vec3& eye) {
vec3 eye_in = eye;
vec3 p = eye_in, dp = normalize(dir);
vec3 color;
float totalD = 0.0, D = 3.4e38, extraD = 0.0, lastD;
int steps;
for (steps=0; steps<max_steps; steps++) {
lastD = D;
D = eval(p + totalD * dp, color);
if (extraD > 0.0 && D < extraD) {
totalD -= extraD;
extraD = 0.0;
D = 3.4e38;
steps--;
continue;
}
if (D < min_dist || D > MAX_DIST) break;
totalD += D;
totalD += extraD = 0.096 * D*(D+extraD)/lastD;
}
vec3 p2 = p;
p2.z -= 12.;
float ld, td= 0.;
float w;
float l, lacc = 0.;
for (float i=0.; (i<1.); i+=1./64.) {
if(td > .95)
break;
l = f(p2) * 0.6;
if (l < .01) {
ld = 0.01 - l;
w = (1. - td) * ld;
td += w;
}
l = max(l, 0.03);
lacc += l;
if (lacc > totalD)
break;
p2 += l*dir;
}
vec3 edir = normalize(dp + p * 0.005);
p += totalD * dp;
vec3 backgroundColor = cloud(edir*10.0) * vec3(0.65, 0.45, 1.0) * 0.6;
backgroundColor += clamp(cloud(edir*150.0)-0.5, 0.0, 1.0)*10.0;
vec3 col = backgroundColor;
if (D < min_dist) {
vec3 n = normal(p, D);
col = color;
col = blinn_phong(n, -dp, normalize(eye_in+vec3(0,1,0)+dp), col);
col = mix(aoColor, col, ambient_occlusion(p, n));
}
col = mix(col, td*1.5*surfaceColor3 + ld*3*surfaceColor1, clamp(td*2, 0.0, 1.0));
col = mix(col, glowColor, float(steps)/float(max_steps) * glow_strength);
return col;
}
void glslmain( void )
{
vec2 p = vec2(gl_FragCoord.x + (gl_TexCoord[0].y - gl_TexCoord[0].x)/2.0, gl_FragCoord.y) / gl_TexCoord[0].yy * 2.0 - 1.0;
vec2 p2 = gl_FragCoord.xy / gl_TexCoord[0].xy * 2.0 - 1.0;
p /= 1.2;
mat3 m = mat3(1.0);
vec3 tr = vec3(0.0);
time = gl_TexCoord[0].z;
vec3 dir = normalize(vec3(1.0, 0.0, 1.5));
vec3 up = vec3(0.0, 1.0, 0.0);
vec3 origin = vec3(-5.0, 0.0, -5.0);
/* vec3 origin = pow(vec3(noise(vec3(time*0.09, 0., 0.)), noise(vec3(0., time*0.13, 0.)), noise(vec3(0., 0., time*0.11)))-0.5, 2.0)*15.0 - vec3(0.0, 0.0, 1.0);
vec3 dir = normalize(vec3(noise(vec3(time*0.17, 0., 0.)), noise(vec3(0., time*0.19, 0.)), noise(vec3(0., 0., time*0.21)))-0.5-origin*0.1);
vec3 up = -normalize(cross(normalize(cross(up, dir)), dir));*/
vec3 sorigin = origin;
vec3 sdir = normalize(p.x * cross(up, dir) + p.y * up + 1 * dir);
vec3 c1 = cast(sdir, sorigin);
vec3 c = c1;
c *= clamp(smoothstep(1.5, 0.5, length(p2)), 0.0, 1.0);
c *= 1.125;
gl_FragColor = vec4(pow(c, vec3(1.0 / 1.0)), 1.0);
}
vec4 gl_TexCoord[8];
vec4 gl_FragCoord;
vec4 gl_FragColor;
};
int main()
{
std::ofstream outfile("out.raw");
int xres = 720, yres = 480;
unsigned char *data = (unsigned char*) malloc(yres*xres*3);
#pragma omp parallel for schedule(dynamic, 4)
for (int y = 0; y < yres; ++y) {
for (int x = 0; x < xres; ++x) {
shader sh;
sh.gl_TexCoord[0] = vec4(xres, yres, 20.0f, 0.0f);
sh.gl_FragCoord = vec4(x, y, 0.0f, 0.0f);
sh.glslmain();
data[((yres-y-1)*xres+x)*3] = clamp(sh.gl_FragColor.r * 255, 0, 255);
data[((yres-y-1)*xres+x)*3+1] = clamp(sh.gl_FragColor.g * 255, 0, 255);
data[((yres-y-1)*xres+x)*3+2] = clamp(sh.gl_FragColor.b * 255, 0, 255);
}
}
// There's probably a better way to do this, something akin to fwrite(), in C++
for (long long i = 0; i < yres*xres*3; ++i) {
outfile << data[i];
}
free(data);
return 0;
}
}
int main()
{
return glsl::main();
}
<|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 "content/common/set_process_title.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "build/build_config.h"
#if defined(OS_POSIX)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#if defined(OS_LINUX)
#include <sys/prctl.h>
// Linux/glibc doesn't natively have setproctitle().
#include "content/common/set_process_title_linux.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS) && \
defined(OS_OPENBSD)
void SetProcessTitleFromCommandLine(const char** main_argv) {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
if (main_argv)
setproctitle_init(main_argv);
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
FilePath target;
FilePath self_exe("/proc/self/exe");
if (file_util::ReadSymbolicLink(self_exe, &target)) {
have_argv0 = true;
title = target.value();
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif
}
#endif
const CommandLine* command_line = CommandLine::ForCurrentProcess();
for (size_t i = 1; i < command_line->argv().size(); ++i) {
if (!title.empty())
title += " ";
title += command_line->argv()[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#else
// All other systems (basically Windows & Mac) have no need or way to implement
// this function.
void SetProcessTitleFromCommandLine(const char** /* main_argv */) {
}
#endif
<commit_msg>Linux: Fix bad #define for SetProcessTitleFromCommandLine().<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/common/set_process_title.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include "base/command_line.h"
#endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
#if defined(OS_LINUX)
#include <sys/prctl.h>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
// Linux/glibc doesn't natively have setproctitle().
#include "content/common/set_process_title_linux.h"
#endif // defined(OS_LINUX)
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
void SetProcessTitleFromCommandLine(const char** main_argv) {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
if (main_argv)
setproctitle_init(main_argv);
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
FilePath target;
FilePath self_exe("/proc/self/exe");
if (file_util::ReadSymbolicLink(self_exe, &target)) {
have_argv0 = true;
title = target.value();
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif // defined(PR_SET_NAME)
}
#endif // defined(OS_LINUX)
const CommandLine* command_line = CommandLine::ForCurrentProcess();
for (size_t i = 1; i < command_line->argv().size(); ++i) {
if (!title.empty())
title += " ";
title += command_line->argv()[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#else
// All other systems (basically Windows & Mac) have no need or way to implement
// this function.
void SetProcessTitleFromCommandLine(const char** /* main_argv */) {
}
#endif
<|endoftext|>
|
<commit_before>#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
#include "LinearImplicitSystem.hpp"
#include "NumericVector.hpp"
using namespace femus;
double InitialValueThom(const std::vector < double >& x) {
return x[0] + x[1];
}
double InitialValueThomAdj(const std::vector < double >& x) {
return x[0];
}
double InitialValueTcont(const std::vector < double >& x) {
return x[1];
}
bool SetBoundaryCondition(const std::vector < double >& x, const char solName[], double& value, const int faceName, const double time) {
bool dirichlet = true; //dirichlet
value = 0;
if (faceName == 2)
dirichlet = false;
return dirichlet;
}
void AssembleLiftRestrProblem(MultiLevelProblem& ml_prob);
int main(int argc, char** args) {
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
// define multilevel mesh
MultiLevelMesh mlMsh;
double scalingFactor = 1.;
// read coarse level mesh and generate finers level meshes
mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
/* "seventh" is the order of accuracy that is used in the gauss integration scheme
probably in the furure it is not going to be an argument of this function */
unsigned numberOfUniformLevels = 3;
unsigned numberOfSelectiveLevels = 0;
mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
mlMsh.PrintInfo();
// define the multilevel solution and attach the mlMsh object to it
MultiLevelSolution mlSol(&mlMsh);
// add variables to mlSol
mlSol.AddSolution("Thom", LAGRANGE, SECOND);
mlSol.AddSolution("ThomAdj", LAGRANGE, SECOND);
mlSol.AddSolution("Tcont", LAGRANGE, SECOND);
mlSol.Initialize("All"); // initialize all varaibles to zero
mlSol.Initialize("Thom", InitialValueThom);
mlSol.Initialize("ThomAdj", InitialValueThomAdj);
mlSol.Initialize("Tcont", InitialValueTcont); // note that this initialization is the same as piecewise constant element
// attach the boundary condition function and generate boundary data
mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol.GenerateBdc("Thom");
mlSol.GenerateBdc("ThomAdj");
mlSol.GenerateBdc("Tcont");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem mlProb(&mlSol);
// add system in mlProb as a Linear Implicit System
LinearImplicitSystem& system = mlProb.add_system < LinearImplicitSystem > ("LiftRestr");
system.AddSolutionToSystemPDE("Thom");
system.AddSolutionToSystemPDE("ThomAdj");
// system.AddSolutionToSystemPDE("Tcont");
// attach the assembling function to system
system.SetAssembleFunction(AssembleLiftRestrProblem);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("Thom");
variablesToBePrinted.push_back("ThomAdj");
variablesToBePrinted.push_back("Tcont");
VTKWriter vtkIO(&mlSol);
vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
GMVWriter gmvIO(&mlSol);
variablesToBePrinted.push_back("all");
gmvIO.SetDebugOutput(false);
gmvIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
return 0;
}
void AssembleLiftRestrProblem(MultiLevelProblem& ml_prob) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem> ("LiftRestr"); // pointer to the linear implicit system named "LiftRestr"
const unsigned level = mlPdeSys->GetLevelToAssemble();
const unsigned levelMax = mlPdeSys->GetLevelMax();
const bool assembleMatrix = mlPdeSys->GetAssembleMatrix();
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned dim2 = (3 * (dim - 1) + !(dim - 1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
const unsigned maxSize = static_cast< unsigned >(ceil(pow(3, dim))); // conservative: based on line3, quad9, hex27
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//***************************
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
for (unsigned i = 0; i < dim; i++) {
x[i].reserve(maxSize);
}
//***************************
//***************************
vector <double> phi; // local test function
vector <double> phi_x; // local test function first order partial derivatives
vector <double> phi_xx; // local test function second order partial derivatives
double weight; // gauss point weight
phi.reserve(maxSize);
phi_x.reserve(maxSize * dim);
phi_xx.reserve(maxSize * dim2);
//***************************
//***************************
unsigned solIndexThom;
solIndexThom = mlSol->GetIndex("Thom"); // get the position of "Thom" in the ml_sol object
unsigned solTypeThom = mlSol->GetSolutionType(solIndexThom); // get the finite element type for "Thom"
unsigned solPdeIndexThom;
solPdeIndexThom = mlPdeSys->GetSolPdeIndex("Thom"); // get the position of "Thom" in the pdeSys object
vector < double > solThom; // local solution
solThom.reserve(maxSize);
vector< int > l2GMap_Thom;
l2GMap_Thom.reserve(maxSize);
//***************************
//***************************
unsigned solIndexThomAdj;
solIndexThom = mlSol->GetIndex("ThomAdj"); // get the position of "Thom" in the ml_sol object
unsigned solTypeThomAdj = mlSol->GetSolutionType(solIndexThomAdj); // get the finite element type for "Thom"
unsigned solPdeIndexThomAdj;
solPdeIndexThomAdj = mlPdeSys->GetSolPdeIndex("ThomAdj"); // get the position of "Thom" in the pdeSys object
vector < double > solThomAdj; // local solution
solThomAdj.reserve(maxSize);
vector< int > l2GMap_ThomAdj;
l2GMap_ThomAdj.reserve(maxSize);
//***************************
const int n_vars = 2;
//***************************
vector< int > l2GMap_AllVars; // local to global mapping
l2GMap_AllVars.reserve(n_vars*maxSize);
vector< double > Res; // local redidual vector
Res.reserve(n_vars*maxSize);
vector < double > Jac;
Jac.reserve( n_vars*maxSize * n_vars*maxSize);
//***************************
if (assembleMatrix)
KK->zero(); // Set to zero all the entries of the Global Matrix
// element loop: each process loops only on the elements that owns
for (int iel = msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc + 1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType(kel); // element geometry type
unsigned nDofx = el->GetElementDofNumber(kel, xType); // number of coordinate element dofs
unsigned nDofThom = el->GetElementDofNumber(kel, solTypeThom); // number of solution element dofs
unsigned nDofThomAdj = el->GetElementDofNumber(kel, solTypeThomAdj); // number of solution element dofs
unsigned nDof_AllVars = nDofThom + nDofThomAdj;
// resize local arrays
solThom .resize(nDofThom);
l2GMap_Thom.resize(nDofThom);
solThomAdj .resize(nDofThomAdj);
l2GMap_ThomAdj.resize(nDofThomAdj);
l2GMap_AllVars.resize(nDof_AllVars);
//***************************
for (int i = 0; i < dim; i++) {
x[i].resize(nDofx);
}
Res.resize(nDof_AllVars); //resize
std::fill(Res.begin(), Res.end(), 0); //set Res to zero
Jac.resize(nDof_AllVars * nDof_AllVars); //resize
std::fill(Jac.begin(), Jac.end(), 0); //set Jac to zero
//***************************
// local storage of global mapping and solution
for (unsigned i = 0; i < nDofThom; i++) {
unsigned iNode = el->GetMeshDof(kel, i, solTypeThom); // local to global solution node
unsigned solDofThom = msh->GetMetisDof(iNode, solTypeThom); // global to global mapping between solution node and solution dof
solThom[i] = (*sol->_Sol[solIndexThom])(solDofThom); // global extraction and local storage for the solution
l2GMap_AllVars[i]/*_Thom*/ = pdeSys->GetKKDof(solIndexThom, solPdeIndexThom, iNode); // global to global mapping between solution node and pdeSys dof
}
//**** dof composition all vars ***********************
// for(int i=0; i < n_vars;i++){
// l2GMap_AllVars.insert( l2GMap_AllVars.end(), dofsVAR[i].begin(), dofsVAR[i].end() );
// }
//***************************
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_Thom.begin(),l2GMap_Thom.end());
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_ThomAdj.begin(),l2GMap_ThomAdj.end());
//***************************
// local storage of coordinates
for (unsigned i = 0; i < nDofx; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for (unsigned jdim = 0; jdim < dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
//***************************
if (level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for (unsigned ig = 0; ig < msh->_finiteElement[kelGeom][solTypeThom]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
msh->_finiteElement[kelGeom][solTypeThom]->Jacobian(x, ig, weight, phi, phi_x, phi_xx);
// evaluate the solution, the solution derivatives and the coordinates in the gauss point
double solThom_gss = 0;
vector < double > gradSolu_gss(dim, 0.);
vector < double > x_gss(dim, 0.);
for (unsigned i = 0; i < nDofThom; i++) {
solThom_gss += phi[i] * solThom[i];
for (unsigned jdim = 0; jdim < dim; jdim++) {
gradSolu_gss[jdim] += phi_x[i * dim + jdim] * solThom[i];
x_gss[jdim] += x[jdim][i] * phi[i];
}
}
// *** phi_i loop ***
for (unsigned i = 0; i < nDofThom; i++) {
double laplace = 0.;
for (unsigned jdim = 0; jdim < dim; jdim++) {
laplace += phi_x[i * dim + jdim] * gradSolu_gss[jdim];
}
double srcTerm = 0.;
Res[i] += (srcTerm * phi[i] - laplace) * weight;
if (assembleMatrix) {
// *** phi_j loop ***
for (unsigned j = 0; j < nDofThom; j++) {
laplace = 0.;
for (unsigned kdim = 0; kdim < dim; kdim++) {
laplace += (phi_x[i * dim + kdim] * phi_x[j * dim + kdim]) * weight;
}
Jac[i * nDofThom + j] += laplace;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
//copy the value of the adept::adoube aRes in double Res and store
RES->add_vector_blocked(Res, l2GMap_AllVars);
if (assembleMatrix) {
//store K in the global matrix KK
KK->add_matrix_blocked(Jac, l2GMap_AllVars, l2GMap_AllVars);
}
} //end element loop for each process
RES->close();
if (assembleMatrix) KK->close();
// ***************** END ASSEMBLY *******************
}
<commit_msg>Laplacian on two blocks runs<commit_after>#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
#include "LinearImplicitSystem.hpp"
#include "NumericVector.hpp"
using namespace femus;
double InitialValueThom(const std::vector < double >& x) {
return 0.;
}
double InitialValueThomAdj(const std::vector < double >& x) {
return 0.;
}
double InitialValueTcont(const std::vector < double >& x) {
return 0.;
}
bool SetBoundaryCondition(const std::vector < double >& x, const char solName[], double& value, const int faceName, const double time) {
bool dirichlet = true; //dirichlet
value = 0;
if (faceName == 2)
dirichlet = false;
return dirichlet;
}
void AssembleLiftRestrProblem(MultiLevelProblem& ml_prob);
int main(int argc, char** args) {
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
// define multilevel mesh
MultiLevelMesh mlMsh;
double scalingFactor = 1.;
// read coarse level mesh and generate finers level meshes
mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
/* "seventh" is the order of accuracy that is used in the gauss integration scheme
probably in the furure it is not going to be an argument of this function */
unsigned numberOfUniformLevels = 3;
unsigned numberOfSelectiveLevels = 0;
mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
mlMsh.PrintInfo();
// define the multilevel solution and attach the mlMsh object to it
MultiLevelSolution mlSol(&mlMsh);
// add variables to mlSol
mlSol.AddSolution("Thom", LAGRANGE, SECOND);
mlSol.AddSolution("ThomAdj", LAGRANGE, SECOND);
mlSol.AddSolution("Tcont", LAGRANGE, SECOND);
mlSol.Initialize("All"); // initialize all varaibles to zero
mlSol.Initialize("Thom", InitialValueThom);
mlSol.Initialize("ThomAdj", InitialValueThomAdj);
mlSol.Initialize("Tcont", InitialValueTcont); // note that this initialization is the same as piecewise constant element
// attach the boundary condition function and generate boundary data
mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol.GenerateBdc("Thom");
mlSol.GenerateBdc("ThomAdj");
mlSol.GenerateBdc("Tcont");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem mlProb(&mlSol);
// add system in mlProb as a Linear Implicit System
LinearImplicitSystem& system = mlProb.add_system < LinearImplicitSystem > ("LiftRestr");
system.AddSolutionToSystemPDE("Thom");
system.AddSolutionToSystemPDE("ThomAdj");
// system.AddSolutionToSystemPDE("Tcont");
// attach the assembling function to system
system.SetAssembleFunction(AssembleLiftRestrProblem);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("Thom");
variablesToBePrinted.push_back("ThomAdj");
variablesToBePrinted.push_back("Tcont");
VTKWriter vtkIO(&mlSol);
vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
GMVWriter gmvIO(&mlSol);
variablesToBePrinted.push_back("all");
gmvIO.SetDebugOutput(false);
gmvIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
return 0;
}
void AssembleLiftRestrProblem(MultiLevelProblem& ml_prob) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem> ("LiftRestr"); // pointer to the linear implicit system named "LiftRestr"
const unsigned level = mlPdeSys->GetLevelToAssemble();
const unsigned levelMax = mlPdeSys->GetLevelMax();
const bool assembleMatrix = mlPdeSys->GetAssembleMatrix();
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned dim2 = (3 * (dim - 1) + !(dim - 1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
const unsigned maxSize = static_cast< unsigned >(ceil(pow(3, dim))); // conservative: based on line3, quad9, hex27
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//***************************
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
for (unsigned i = 0; i < dim; i++) {
x[i].reserve(maxSize);
}
//***************************
//***************************
vector <double> phi; // local test function
vector <double> phi_x; // local test function first order partial derivatives
vector <double> phi_xx; // local test function second order partial derivatives
double weight; // gauss point weight
phi.reserve(maxSize);
phi_x.reserve(maxSize * dim);
phi_xx.reserve(maxSize * dim2);
//***************************
//***************************
unsigned solIndexThom;
solIndexThom = mlSol->GetIndex("Thom"); // get the position of "Thom" in the ml_sol object
unsigned solTypeThom = mlSol->GetSolutionType(solIndexThom); // get the finite element type for "Thom"
unsigned solPdeIndexThom;
solPdeIndexThom = mlPdeSys->GetSolPdeIndex("Thom"); // get the position of "Thom" in the pdeSys object
vector < double > solThom; // local solution
solThom.reserve(maxSize);
vector< int > l2GMap_Thom;
l2GMap_Thom.reserve(maxSize);
//***************************
//***************************
unsigned solIndexThomAdj;
solIndexThomAdj = mlSol->GetIndex("ThomAdj"); // get the position of "Thom" in the ml_sol object
unsigned solTypeThomAdj = mlSol->GetSolutionType(solIndexThomAdj); // get the finite element type for "Thom"
unsigned solPdeIndexThomAdj;
solPdeIndexThomAdj = mlPdeSys->GetSolPdeIndex("ThomAdj"); // get the position of "Thom" in the pdeSys object
vector < double > solThomAdj; // local solution
solThomAdj.reserve(maxSize);
vector< int > l2GMap_ThomAdj;
l2GMap_ThomAdj.reserve(maxSize);
//***************************
const int n_vars = 2;
//***************************
vector< int > l2GMap_AllVars; // local to global mapping
l2GMap_AllVars.reserve(n_vars*maxSize);
vector< double > Res; // local redidual vector
Res.reserve(n_vars*maxSize);
vector < double > Jac;
Jac.reserve( n_vars*maxSize * n_vars*maxSize);
//***************************
if (assembleMatrix)
KK->zero(); // Set to zero all the entries of the Global Matrix
// element loop: each process loops only on the elements that owns
for (int iel = msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc + 1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType(kel); // element geometry type
unsigned nDofx = el->GetElementDofNumber(kel, xType); // number of coordinate element dofs
unsigned nDofThom = el->GetElementDofNumber(kel, solTypeThom); // number of solution element dofs
unsigned nDofThomAdj = el->GetElementDofNumber(kel, solTypeThomAdj); // number of solution element dofs
unsigned nDof_AllVars = nDofThom + nDofThomAdj;
// resize local arrays
solThom .resize(nDofThom);
l2GMap_Thom.resize(nDofThom);
solThomAdj .resize(nDofThomAdj);
l2GMap_ThomAdj.resize(nDofThomAdj);
l2GMap_AllVars.resize(0);
//***************************
for (int i = 0; i < dim; i++) {
x[i].resize(nDofx);
}
Res.resize(nDof_AllVars); //resize
std::fill(Res.begin(), Res.end(), 0); //set Res to zero
Jac.resize(nDof_AllVars * nDof_AllVars); //resize
std::fill(Jac.begin(), Jac.end(), 0); //set Jac to zero
//***************************
// local storage of global mapping and solution
for (unsigned i = 0; i < solThom.size(); i++) {
unsigned iNode = el->GetMeshDof(kel, i, solTypeThom); // local to global solution node
unsigned solDofThom = msh->GetMetisDof(iNode, solTypeThom); // global to global mapping between solution node and solution dof
solThom[i] = (*sol->_Sol[solIndexThom])(solDofThom); // global extraction and local storage for the solution
l2GMap_Thom[i] = pdeSys->GetKKDof(solIndexThom, solPdeIndexThom, iNode); // global to global mapping between solution node and pdeSys dof
}
for (unsigned i = 0; i < solThomAdj.size(); i++) {
unsigned iNode = el->GetMeshDof(kel, i, solTypeThomAdj); // local to global solution node
unsigned solDofThomAdj = msh->GetMetisDof(iNode, solTypeThomAdj); // global to global mapping between solution node and solution dof
solThomAdj[i] = (*sol->_Sol[solIndexThomAdj])(solDofThomAdj); // global extraction and local storage for the solution
l2GMap_ThomAdj[i] = pdeSys->GetKKDof(solIndexThomAdj, solPdeIndexThomAdj, iNode); // global to global mapping between solution node and pdeSys dof
}
//**** dof composition all vars ***********************
// for(int i=0; i < n_vars;i++){
// l2GMap_AllVars.insert( l2GMap_AllVars.end(), dofsVAR[i].begin(), dofsVAR[i].end() );
// }
//***************************
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_Thom.begin(),l2GMap_Thom.end());
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_ThomAdj.begin(),l2GMap_ThomAdj.end());
//***************************
// local storage of coordinates
for (unsigned i = 0; i < nDofx; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for (unsigned jdim = 0; jdim < dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
//***************************
if (level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for (unsigned ig = 0; ig < msh->_finiteElement[kelGeom][solTypeThom]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
msh->_finiteElement[kelGeom][solTypeThom]->Jacobian(x, ig, weight, phi, phi_x, phi_xx);
// evaluate the solution, the solution derivatives and the coordinates in the gauss point
double solThom_gss = 0;
vector < double > gradSolu_gss(dim, 0.);
vector < double > x_gss(dim, 0.);
for (unsigned i = 0; i < nDofThom; i++) {
solThom_gss += phi[i] * solThom[i];
for (unsigned jdim = 0; jdim < dim; jdim++) {
gradSolu_gss[jdim] += phi_x[i * dim + jdim] * solThom[i];
x_gss[jdim] += x[jdim][i] * phi[i];
}
}
// *** phi_i loop ***
for (unsigned i = 0; i < nDofThom; i++) {
double laplace_rhs = 0.;
for (unsigned jdim = 0; jdim < dim; jdim++) {
laplace_rhs += phi_x[i * dim + jdim] * gradSolu_gss[jdim];
}
double srcTerm = 10.;
Res[i] += (srcTerm * phi[i] - laplace_rhs) * weight;
Res[nDofThom + i] += (srcTerm * phi[i] - laplace_rhs) * weight;
if (assembleMatrix) {
// *** phi_j loop ***
for (unsigned j = 0; j < nDofThom; j++) {
double laplace_mat = 0.;
for (unsigned kdim = 0; kdim < dim; kdim++) {
laplace_mat += (phi_x[i * dim + kdim] * phi_x[j * dim + kdim]) * weight;
}
Jac[i * (2*nDofThom) + j] += laplace_mat;
Jac[(2*nDofThom)*(nDofThom) + i * (2* nDofThom) +(nDofThom + j)] += laplace_mat;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
//copy the value of the adept::adoube aRes in double Res and store
RES->add_vector_blocked(Res, l2GMap_AllVars);
if (assembleMatrix) {
//store K in the global matrix KK
KK->add_matrix_blocked(Jac, l2GMap_AllVars, l2GMap_AllVars);
}
} //end element loop for each process
RES->close();
if (assembleMatrix) KK->close();
// ***************** END ASSEMBLY *******************
}
<|endoftext|>
|
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/component.h"
#include "libcellml/units.h"
#include "libcellml/variable.h"
#include "utilities.h"
#include <algorithm>
#include <string>
#include <vector>
namespace libcellml {
/**
* @brief The Component::ComponentImpl struct.
*
* This struct is the private implementation struct for the Component class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Component::ComponentImpl
{
std::string mMath;
std::vector<ResetPtr> mResets;
std::vector<VariablePtr> mVariables;
std::vector<ResetPtr>::iterator findReset(const ResetPtr &reset);
std::vector<VariablePtr>::iterator findVariable(const std::string &name);
std::vector<VariablePtr>::iterator findVariable(const VariablePtr &variable);
};
std::vector<VariablePtr>::iterator Component::ComponentImpl::findVariable(const std::string &name)
{
return std::find_if(mVariables.begin(), mVariables.end(),
[=](const VariablePtr &v) -> bool { return v->name() == name; });
}
std::vector<VariablePtr>::iterator Component::ComponentImpl::findVariable(const VariablePtr &variable)
{
return std::find_if(mVariables.begin(), mVariables.end(),
[=](const VariablePtr &v) -> bool { return v == variable; });
}
std::vector<ResetPtr>::iterator Component::ComponentImpl::findReset(const ResetPtr &reset)
{
return std::find_if(mResets.begin(), mResets.end(),
[=](const ResetPtr &r) -> bool { return r == reset; });
}
Component::Component()
: mPimpl(new ComponentImpl())
{
}
Component::~Component()
{
if (mPimpl != nullptr) {
for (const auto &variable : mPimpl->mVariables) {
variable->clearParent();
}
}
delete mPimpl;
}
Component::Component(const Component &rhs)
: ComponentEntity(rhs)
, ImportedEntity(rhs)
#ifndef SWIG
, std::enable_shared_from_this<Component>(rhs)
#endif
, mPimpl(new ComponentImpl())
{
mPimpl->mVariables = rhs.mPimpl->mVariables;
mPimpl->mResets = rhs.mPimpl->mResets;
mPimpl->mMath = rhs.mPimpl->mMath;
}
Component::Component(Component &&rhs) noexcept
: ComponentEntity(std::move(rhs))
, ImportedEntity(std::move(rhs))
, mPimpl(rhs.mPimpl)
{
rhs.mPimpl = nullptr;
}
Component &Component::operator=(Component rhs)
{
ComponentEntity::operator=(rhs);
ImportedEntity::operator=(rhs);
rhs.swap(*this);
return *this;
}
void Component::swap(Component &rhs)
{
std::swap(mPimpl, rhs.mPimpl);
}
bool Component::doAddComponent(const ComponentPtr &component)
{
bool hasParent = component->hasParent();
if (hasParent) {
if (hasAncestor(component)) {
return false;
}
auto parent = component->parent();
removeComponentFromEntity(parent, component);
} else if (!hasParent && hasAncestor(component)) {
return false;
} else if (shared_from_this() == component) {
return false;
}
component->setParent(shared_from_this());
return ComponentEntity::doAddComponent(component);
}
void Component::setSourceComponent(const ImportSourcePtr &importSource, const std::string &name)
{
setImportSource(importSource);
setImportReference(name);
}
void Component::appendMath(const std::string &math)
{
mPimpl->mMath.append(math);
}
std::string Component::math() const
{
return mPimpl->mMath;
}
void Component::setMath(const std::string &math)
{
mPimpl->mMath = math;
}
void Component::addVariable(const VariablePtr &variable)
{
mPimpl->mVariables.push_back(variable);
variable->setParent(shared_from_this());
}
bool Component::removeVariable(size_t index)
{
if (index < mPimpl->mVariables.size()) {
mPimpl->mVariables.erase(mPimpl->mVariables.begin() + int64_t(index));
return true;
}
return false;
}
bool Component::removeVariable(const std::string &name)
{
auto result = mPimpl->findVariable(name);
if (result != mPimpl->mVariables.end()) {
mPimpl->mVariables.erase(result);
return true;
}
return false;
}
bool Component::removeVariable(const VariablePtr &variable)
{
auto result = mPimpl->findVariable(variable);
if (result != mPimpl->mVariables.end()) {
mPimpl->mVariables.erase(result);
return true;
}
return false;
}
void Component::removeAllVariables()
{
mPimpl->mVariables.clear();
}
VariablePtr Component::variable(size_t index) const
{
if (index < mPimpl->mVariables.size()) {
return mPimpl->mVariables.at(index);
}
return nullptr;
}
VariablePtr Component::variable(const std::string &name) const
{
auto result = mPimpl->findVariable(name);
if (result != mPimpl->mVariables.end()) {
return *result;
}
return nullptr;
}
VariablePtr Component::takeVariable(size_t index)
{
VariablePtr res = nullptr;
res = variable(index);
removeVariable(index);
return res;
}
VariablePtr Component::takeVariable(const std::string &name)
{
VariablePtr res = nullptr;
res = variable(name);
removeVariable(name);
return res;
}
size_t Component::variableCount() const
{
return mPimpl->mVariables.size();
}
bool Component::hasVariable(const VariablePtr &variable) const
{
return mPimpl->findVariable(variable) != mPimpl->mVariables.end();
}
bool Component::hasVariable(const std::string &name) const
{
return mPimpl->findVariable(name) != mPimpl->mVariables.end();
}
void Component::addReset(const ResetPtr &reset)
{
mPimpl->mResets.push_back(reset);
}
bool Component::removeReset(size_t index)
{
if (index < mPimpl->mResets.size()) {
mPimpl->mResets.erase(mPimpl->mResets.begin() + int64_t(index));
return true;
}
return false;
}
bool Component::removeReset(const ResetPtr &reset)
{
auto result = mPimpl->findReset(reset);
if (result != mPimpl->mResets.end()) {
mPimpl->mResets.erase(result);
return true;
}
return false;
}
void Component::removeAllResets()
{
mPimpl->mResets.clear();
}
ResetPtr Component::reset(size_t index) const
{
if (index < mPimpl->mResets.size()) {
return mPimpl->mResets.at(index);
}
return nullptr;
}
size_t Component::resetCount() const
{
return mPimpl->mResets.size();
}
bool Component::hasReset(const ResetPtr &reset) const
{
return mPimpl->findReset(reset) != mPimpl->mResets.end();
}
} // namespace libcellml
<commit_msg>Set order of headers in src/component.cpp to conform to the coding style.<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/component.h"
#include <algorithm>
#include <string>
#include <vector>
#include "libcellml/units.h"
#include "libcellml/variable.h"
#include "utilities.h"
namespace libcellml {
/**
* @brief The Component::ComponentImpl struct.
*
* This struct is the private implementation struct for the Component class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Component::ComponentImpl
{
std::string mMath;
std::vector<ResetPtr> mResets;
std::vector<VariablePtr> mVariables;
std::vector<ResetPtr>::iterator findReset(const ResetPtr &reset);
std::vector<VariablePtr>::iterator findVariable(const std::string &name);
std::vector<VariablePtr>::iterator findVariable(const VariablePtr &variable);
};
std::vector<VariablePtr>::iterator Component::ComponentImpl::findVariable(const std::string &name)
{
return std::find_if(mVariables.begin(), mVariables.end(),
[=](const VariablePtr &v) -> bool { return v->name() == name; });
}
std::vector<VariablePtr>::iterator Component::ComponentImpl::findVariable(const VariablePtr &variable)
{
return std::find_if(mVariables.begin(), mVariables.end(),
[=](const VariablePtr &v) -> bool { return v == variable; });
}
std::vector<ResetPtr>::iterator Component::ComponentImpl::findReset(const ResetPtr &reset)
{
return std::find_if(mResets.begin(), mResets.end(),
[=](const ResetPtr &r) -> bool { return r == reset; });
}
Component::Component()
: mPimpl(new ComponentImpl())
{
}
Component::~Component()
{
if (mPimpl != nullptr) {
for (const auto &variable : mPimpl->mVariables) {
variable->clearParent();
}
}
delete mPimpl;
}
Component::Component(const Component &rhs)
: ComponentEntity(rhs)
, ImportedEntity(rhs)
#ifndef SWIG
, std::enable_shared_from_this<Component>(rhs)
#endif
, mPimpl(new ComponentImpl())
{
mPimpl->mVariables = rhs.mPimpl->mVariables;
mPimpl->mResets = rhs.mPimpl->mResets;
mPimpl->mMath = rhs.mPimpl->mMath;
}
Component::Component(Component &&rhs) noexcept
: ComponentEntity(std::move(rhs))
, ImportedEntity(std::move(rhs))
, mPimpl(rhs.mPimpl)
{
rhs.mPimpl = nullptr;
}
Component &Component::operator=(Component rhs)
{
ComponentEntity::operator=(rhs);
ImportedEntity::operator=(rhs);
rhs.swap(*this);
return *this;
}
void Component::swap(Component &rhs)
{
std::swap(mPimpl, rhs.mPimpl);
}
bool Component::doAddComponent(const ComponentPtr &component)
{
bool hasParent = component->hasParent();
if (hasParent) {
if (hasAncestor(component)) {
return false;
}
auto parent = component->parent();
removeComponentFromEntity(parent, component);
} else if (!hasParent && hasAncestor(component)) {
return false;
} else if (shared_from_this() == component) {
return false;
}
component->setParent(shared_from_this());
return ComponentEntity::doAddComponent(component);
}
void Component::setSourceComponent(const ImportSourcePtr &importSource, const std::string &name)
{
setImportSource(importSource);
setImportReference(name);
}
void Component::appendMath(const std::string &math)
{
mPimpl->mMath.append(math);
}
std::string Component::math() const
{
return mPimpl->mMath;
}
void Component::setMath(const std::string &math)
{
mPimpl->mMath = math;
}
void Component::addVariable(const VariablePtr &variable)
{
mPimpl->mVariables.push_back(variable);
variable->setParent(shared_from_this());
}
bool Component::removeVariable(size_t index)
{
if (index < mPimpl->mVariables.size()) {
mPimpl->mVariables.erase(mPimpl->mVariables.begin() + int64_t(index));
return true;
}
return false;
}
bool Component::removeVariable(const std::string &name)
{
auto result = mPimpl->findVariable(name);
if (result != mPimpl->mVariables.end()) {
mPimpl->mVariables.erase(result);
return true;
}
return false;
}
bool Component::removeVariable(const VariablePtr &variable)
{
auto result = mPimpl->findVariable(variable);
if (result != mPimpl->mVariables.end()) {
mPimpl->mVariables.erase(result);
return true;
}
return false;
}
void Component::removeAllVariables()
{
mPimpl->mVariables.clear();
}
VariablePtr Component::variable(size_t index) const
{
if (index < mPimpl->mVariables.size()) {
return mPimpl->mVariables.at(index);
}
return nullptr;
}
VariablePtr Component::variable(const std::string &name) const
{
auto result = mPimpl->findVariable(name);
if (result != mPimpl->mVariables.end()) {
return *result;
}
return nullptr;
}
VariablePtr Component::takeVariable(size_t index)
{
VariablePtr res = nullptr;
res = variable(index);
removeVariable(index);
return res;
}
VariablePtr Component::takeVariable(const std::string &name)
{
VariablePtr res = nullptr;
res = variable(name);
removeVariable(name);
return res;
}
size_t Component::variableCount() const
{
return mPimpl->mVariables.size();
}
bool Component::hasVariable(const VariablePtr &variable) const
{
return mPimpl->findVariable(variable) != mPimpl->mVariables.end();
}
bool Component::hasVariable(const std::string &name) const
{
return mPimpl->findVariable(name) != mPimpl->mVariables.end();
}
void Component::addReset(const ResetPtr &reset)
{
mPimpl->mResets.push_back(reset);
}
bool Component::removeReset(size_t index)
{
if (index < mPimpl->mResets.size()) {
mPimpl->mResets.erase(mPimpl->mResets.begin() + int64_t(index));
return true;
}
return false;
}
bool Component::removeReset(const ResetPtr &reset)
{
auto result = mPimpl->findReset(reset);
if (result != mPimpl->mResets.end()) {
mPimpl->mResets.erase(result);
return true;
}
return false;
}
void Component::removeAllResets()
{
mPimpl->mResets.clear();
}
ResetPtr Component::reset(size_t index) const
{
if (index < mPimpl->mResets.size()) {
return mPimpl->mResets.at(index);
}
return nullptr;
}
size_t Component::resetCount() const
{
return mPimpl->mResets.size();
}
bool Component::hasReset(const ResetPtr &reset) const
{
return mPimpl->findReset(reset) != mPimpl->mResets.end();
}
} // namespace libcellml
<|endoftext|>
|
<commit_before>// To build this file from scratch, use something like the following:
// g++ -lQtCore -lQtGui -I/usr/include/QtCore -I/usr/include/QtGui main.cpp
#include <QApplication>
#include <QMainWindow>
#include <QDesktopWidget>
#include <QPushButton>
#include <QSize>
void centerApp(QMainWindow& window)
{
QSize appSize(800, 600);
window.resize(appSize);
QDesktopWidget* desktop = QApplication::desktop();
int desktopArea = desktop->width() * desktop->height();
int appArea = appSize.width() * appSize.height();
if (((float)appArea / (float)desktopArea) > 0.75f) {
// Just maximize it if the desktop isn't significantly
// bigger than our app's area.
window.showMaximized();
} else {
// Center the app on the primary monitor.
QPoint windowLocation = desktop->screenGeometry(desktop->primaryScreen()).center();
windowLocation.setX(windowLocation.x() - appSize.width() / 2);
windowLocation.setY(windowLocation.y() - appSize.height() / 2);
window.move(windowLocation);
window.show();
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow gui;
gui.setWindowTitle("@PROJECT@");
centerApp(gui);
QPushButton quit("Quit", &gui);
quit.setGeometry(10, 40, 180, 40);
QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit()));
gui.setCentralWidget(&quit);
return app.exec();
}
<commit_msg>qtmain: minor refactors<commit_after>// To build this file from scratch, use something like the following:
// g++ -lQtCore -lQtGui -I/usr/include/QtCore -I/usr/include/QtGui main.cpp
#include <QApplication>
#include <QMainWindow>
#include <QDesktopWidget>
#include <QPushButton>
#include <QSize>
void centerWindow(QMainWindow& window)
{
QDesktopWidget* desktop = QApplication::desktop();
int desktopArea = desktop->width() * desktop->height();
int appArea = window.width() * window.height();
if (((float)appArea / (float)desktopArea) > 0.75f) {
// Just maximize it if the desktop isn't significantly
// bigger than our app's area.
window.showMaximized();
} else {
// Center the app on the primary monitor.
QPoint windowLocation = desktop->screenGeometry(desktop->primaryScreen()).center();
windowLocation.setX(windowLocation.x() - window.width() / 2);
windowLocation.setY(windowLocation.y() - window.height() / 2);
window.move(windowLocation);
window.show();
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow gui;
gui.setWindowTitle("@PROJECT@");
gui.resize(800, 600);
centerWindow(gui);
QPushButton quit("Quit", &gui);
quit.setGeometry(10, 40, 180, 40);
QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit()));
gui.setCentralWidget(&quit);
return app.exec();
}
<|endoftext|>
|
<commit_before>#include "recursed_range.hpp"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
template<typename Range>
void print_range_recursive(const Range& range)
{
auto rr = recurse_range(range);
using value_type = typename decltype(rr)::value_type;
using output_iterator = std::ostream_iterator<value_type>;
std::cout << "size: " << rr.size() << std::endl;
std::copy(begin(rr),
end(rr),
output_iterator(std::cout, " "));
std::cout << std::endl;
}
int main(int argc, char** argv)
{
{
// same kinds of subranges
std::array<std::array<std::array<int, 2>, 2>, 2> data {
{
{
{ { { 1, 2 } }, { { 3, 4 } } },
},
{
{ { { 5, 6 } }, { { 7, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
{
// different kinds of subranges
std::array<std::array<std::vector<int>, 2>, 2> data {
{
{
{ { { 1, 3 } }, { { 2, 4 } } },
},
{
{ { { 5, 7 } }, { { 6, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
{
// different kinds of subranges with const modifier
std::array<const std::vector<std::array<int, 2>>, 2> data {
{
{
{ { { 1, 2 } }, { { 3, 4 } } },
},
{
{ { { 5, 6 } }, { { 7, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
}
<commit_msg>modified example to remove code repetition<commit_after>#include "recursed_range.hpp"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
template<typename Range>
void print_range_recursive(const Range& range)
{
auto rr = recurse_range(range);
using value_type = typename decltype(rr)::value_type;
using output_iterator = std::ostream_iterator<value_type>;
std::cout << "size: " << rr.size() << std::endl;
std::copy(begin(rr),
end(rr),
output_iterator(std::cout, " "));
std::cout << std::endl;
}
int main(int argc, char** argv)
{
{
// same kinds of subranges
std::array<std::array<std::array<int, 2>, 2>, 2> data {
{
{
{ { { 1, 2 } }, { { 3, 4 } } },
},
{
{ { { 5, 6 } }, { { 7, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
{
// different kinds of subranges
std::array<std::array<std::vector<int>, 2>, 2> data {
{
{
{ { { 1, 3 } }, { { 2, 4 } } },
},
{
{ { { 5, 7 } }, { { 6, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
{
// different kinds of subranges with const modifier
std::array<std::vector<std::array<int, 2>>, 2> data {
{
{
{ { { 1, 2 } }, { { 3, 4 } } },
},
{
{ { { 5, 6 } }, { { 7, 8 } } },
}
},
};
print_range_recursive(data);
}
std::cout << std::endl;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "Binding_BaseState.h"
#include "Binding_BaseObject.h"
using namespace sofa::core::objectmodel;
using namespace sofa::core;
extern "C" PyObject * BaseState_resize(PyObject *self, PyObject * args)
{
BaseState* obj=((PySPtr<Base>*)self)->object->toBaseState();
int newSize;
if (!PyArg_ParseTuple(args, "i",&newSize))
Py_RETURN_NONE;
obj->resize(newSize);
Py_RETURN_NONE;
}
SP_CLASS_METHODS_BEGIN(BaseState)
SP_CLASS_METHOD(BaseState,resize)
SP_CLASS_METHODS_END
SP_CLASS_TYPE_SPTR(BaseState,BaseState,BaseObject)
<commit_msg>[SofaPython] added getSize for mstates<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "Binding_BaseState.h"
#include "Binding_BaseObject.h"
using namespace sofa::core::objectmodel;
using namespace sofa::core;
static PyObject * BaseState_resize(PyObject *self, PyObject * args)
{
BaseState* obj=((PySPtr<Base>*)self)->object->toBaseState();
int newSize;
if (!PyArg_ParseTuple(args, "i", &newSize)) {
PyErr_BadArgument();
return NULL;
}
obj->resize(newSize);
Py_RETURN_NONE;
}
static PyObject * BaseState_getSize(PyObject *self, PyObject * args)
{
BaseState* obj=((PySPtr<Base>*)self)->object->toBaseState();
if (PyTuple_Size(args)) {
PyErr_BadArgument();
return NULL;
}
return PyInt_FromSize_t(obj->getSize());
}
SP_CLASS_METHODS_BEGIN(BaseState)
SP_CLASS_METHOD(BaseState, resize)
SP_CLASS_METHOD(BaseState, getSize)
SP_CLASS_METHODS_END
SP_CLASS_TYPE_SPTR(BaseState, BaseState, BaseObject)
<|endoftext|>
|
<commit_before>#include "compiler.h"
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Options");
desc.add_options()
("input-file,i", po::value<std::string>(), "Set input file.")
("output-file,o", po::value<std::string>()->default_value("a.bf"), "Set output file.")
("help,h", "Print this help message.")
("version,v", "Print version information.");
po::positional_options_description pos;
pos.add("input-file", -1);
po::variables_map variables;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), variables);
po::notify(variables);
if (variables.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl;
std::cout << desc << std::endl;
return 0;
}
if (variables.count("version")) {
std::cout << "Brainfuck compiler, version 0.1" << std::endl;
return 0;
}
std::ifstream in(variables["input-file"].as<std::string>());
const std::string source(std::istreambuf_iterator<char>(in), {});
bf::compiler bfc;
const std::string bf_code = bfc.compile(source);
std::ofstream out(variables["output-file"].as<std::string>());
out << bf_code;
return 0;
}
<commit_msg>Prevent exception on missing input file.<commit_after>#include "compiler.h"
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Options");
desc.add_options()
("input-file,i", po::value<std::string>(), "Set input file.")
("output-file,o", po::value<std::string>()->default_value("a.bf"), "Set output file.")
("help,h", "Print this help message.")
("version,v", "Print version information.");
po::positional_options_description pos;
pos.add("input-file", -1);
po::variables_map variables;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), variables);
po::notify(variables);
if (variables.count("version")) {
std::cout << "Brainfuck compiler, version 0.1" << std::endl;
return 0;
}
if (variables.count("help") || !variables.count("input-file")) {
std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl;
std::cout << desc << std::endl;
return !variables.count("help");
}
std::ifstream in(variables["input-file"].as<std::string>());
const std::string source(std::istreambuf_iterator<char>(in), {});
bf::compiler bfc;
const std::string bf_code = bfc.compile(source);
std::ofstream out(variables["output-file"].as<std::string>());
out << bf_code;
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Assert.h"
#include "World.h"
#include "Allocator.h"
namespace crown
{
//-----------------------------------------------------------------------------
World::World()
: m_allocator(default_allocator(), 1048576)
, m_is_init(false)
{
}
//-----------------------------------------------------------------------------
void World::init()
{
}
//-----------------------------------------------------------------------------
void World::shutdown()
{
}
//-----------------------------------------------------------------------------
UnitId World::spawn_unit(const char* /*name*/, const Vec3& pos, const Quat& rot)
{
const UnitId unit = m_unit_table.create();
m_units[unit.index].create(pos, rot);
// m_units[unit.index].load(ur);
return unit;
}
//-----------------------------------------------------------------------------
void World::kill_unit(UnitId unit)
{
CE_ASSERT(m_unit_table.has(unit), "Unit does not exist");
(void)unit;
}
//-----------------------------------------------------------------------------
void World::link_unit(UnitId child, UnitId parent)
{
CE_ASSERT(m_unit_table.has(child), "Child unit does not exist");
CE_ASSERT(m_unit_table.has(parent), "Parent unit does not exist");
Unit& child_unit = m_units[child.index];
Unit& parent_unit = m_units[parent.index];
parent_unit.m_scene_graph.link(child_unit.m_root_node, parent_unit.m_root_node);
}
//-----------------------------------------------------------------------------
void World::unlink_unit(UnitId child, UnitId parent)
{
CE_ASSERT(m_unit_table.has(child), "Child unit does not exist");
CE_ASSERT(m_unit_table.has(parent), "Parent unit does not exist");
Unit& child_unit = m_units[child.index];
Unit& parent_unit = m_units[parent.index];
parent_unit.m_scene_graph.unlink(child_unit.m_root_node);
}
//-----------------------------------------------------------------------------
Unit* World::unit(UnitId unit)
{
CE_ASSERT(m_unit_table.has(unit), "Unit does not exist");
return &m_units[unit.index];
}
//-----------------------------------------------------------------------------
void World::update(float /*dt*/)
{
}
//-----------------------------------------------------------------------------
SoundWorld& World::sound_world()
{
return m_sound_world;
}
} // namespace crown
<commit_msg>Be explicit when writing numerical values<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Assert.h"
#include "World.h"
#include "Allocator.h"
namespace crown
{
//-----------------------------------------------------------------------------
World::World()
: m_allocator(default_allocator(), 1024 * 1024)
, m_is_init(false)
{
}
//-----------------------------------------------------------------------------
void World::init()
{
}
//-----------------------------------------------------------------------------
void World::shutdown()
{
}
//-----------------------------------------------------------------------------
UnitId World::spawn_unit(const char* /*name*/, const Vec3& pos, const Quat& rot)
{
const UnitId unit = m_unit_table.create();
m_units[unit.index].create(pos, rot);
// m_units[unit.index].load(ur);
return unit;
}
//-----------------------------------------------------------------------------
void World::kill_unit(UnitId unit)
{
CE_ASSERT(m_unit_table.has(unit), "Unit does not exist");
(void)unit;
}
//-----------------------------------------------------------------------------
void World::link_unit(UnitId child, UnitId parent)
{
CE_ASSERT(m_unit_table.has(child), "Child unit does not exist");
CE_ASSERT(m_unit_table.has(parent), "Parent unit does not exist");
Unit& child_unit = m_units[child.index];
Unit& parent_unit = m_units[parent.index];
parent_unit.m_scene_graph.link(child_unit.m_root_node, parent_unit.m_root_node);
}
//-----------------------------------------------------------------------------
void World::unlink_unit(UnitId child, UnitId parent)
{
CE_ASSERT(m_unit_table.has(child), "Child unit does not exist");
CE_ASSERT(m_unit_table.has(parent), "Parent unit does not exist");
Unit& child_unit = m_units[child.index];
Unit& parent_unit = m_units[parent.index];
parent_unit.m_scene_graph.unlink(child_unit.m_root_node);
}
//-----------------------------------------------------------------------------
Unit* World::unit(UnitId unit)
{
CE_ASSERT(m_unit_table.has(unit), "Unit does not exist");
return &m_units[unit.index];
}
//-----------------------------------------------------------------------------
void World::update(float /*dt*/)
{
}
//-----------------------------------------------------------------------------
SoundWorld& World::sound_world()
{
return m_sound_world;
}
} // namespace crown
<|endoftext|>
|
<commit_before>#include "compiler.h"
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Options");
desc.add_options()
("input-file,i", po::value<std::string>(), "Set input file.")
("output-file,o", po::value<std::string>()->default_value("a.bf"), "Set output file.")
("debug,d", "Debug information in output.")
("help,h", "Print this help message.")
("version,v", "Print version information.");
po::positional_options_description pos;
pos.add("input-file", -1);
po::variables_map variables;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), variables);
po::notify(variables);
if (variables.count("version")) {
std::cout << "Brainfuck compiler, version 0.1" << std::endl;
return 0;
}
if (variables.count("help") || !variables.count("input-file")) {
std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl;
std::cout << desc << std::endl;
return !variables.count("help");
}
std::ifstream in(variables["input-file"].as<std::string>());
const std::string source(std::istreambuf_iterator<char>(in), {});
bf::compiler bfc;
if (variables.count("debug"))
bfc.enable_debug_output(true);
const std::string bf_code = bfc.compile(source);
std::ofstream out(variables["output-file"].as<std::string>());
out << bf_code;
return 0;
}
<commit_msg>Catch unhandled exceptions.<commit_after>#include "compiler.h"
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Options");
desc.add_options()
("input-file,i", po::value<std::string>(), "Set input file.")
("output-file,o", po::value<std::string>()->default_value("a.bf"), "Set output file.")
("debug,d", "Debug information in output.")
("help,h", "Print this help message.")
("version,v", "Print version information.");
po::positional_options_description pos;
pos.add("input-file", -1);
po::variables_map variables;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), variables);
po::notify(variables);
if (variables.count("version")) {
std::cout << "Brainfuck compiler, version 0.1" << std::endl;
return 0;
}
if (variables.count("help") || !variables.count("input-file")) {
std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl;
std::cout << desc << std::endl;
return !variables.count("help");
}
try {
std::ifstream in(variables["input-file"].as<std::string>());
const std::string source(std::istreambuf_iterator<char>(in), {});
bf::compiler bfc;
if (variables.count("debug"))
bfc.enable_debug_output(true);
const std::string bf_code = bfc.compile(source);
std::ofstream out(variables["output-file"].as<std::string>());
out << bf_code;
}
catch (const std::exception &e) {
std::cerr << "Oops, something went wrong!\n"
<< "Unhandled Exception: " << e.what() << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "minion_impl.h"
#include <time.h>
#include <unistd.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <cstdlib>
#include <gflags/gflags.h>
#include "logging.h"
#include "proto/app_master.pb.h"
DECLARE_string(master_nexus_path);
DECLARE_string(nexus_addr);
DECLARE_string(work_mode);
DECLARE_string(jobid);
DECLARE_bool(kill_task);
DECLARE_int32(suspend_time);
DECLARE_int64(flow_limit_10gb);
DECLARE_int64(flow_limit_1gb);
using baidu::common::Log;
using baidu::common::FATAL;
using baidu::common::INFO;
using baidu::common::WARNING;
namespace baidu {
namespace shuttle {
const std::string sBreakpointFile = "./task_running";
MinionImpl::MinionImpl() : ins_(FLAGS_nexus_addr),
stop_(false),
task_frozen_(false) {
if (FLAGS_work_mode == "map") {
executor_ = Executor::GetExecutor(kMap);
work_mode_ = kMap;
} else if (FLAGS_work_mode == "reduce") {
executor_ = Executor::GetExecutor(kReduce);
work_mode_ = kReduce;
} else if (FLAGS_work_mode == "map-only") {
executor_ = Executor::GetExecutor(kMapOnly);
work_mode_ = kMapOnly;
} else {
LOG(FATAL, "unkown work mode: %s", FLAGS_work_mode.c_str());
abort();
}
if (FLAGS_kill_task) {
galaxy::ins::sdk::SDKError err;
ins_.Get(FLAGS_master_nexus_path, &master_endpoint_, &err);
if (err == galaxy::ins::sdk::kOK) {
Master_Stub* stub;
rpc_client_.GetStub(master_endpoint_, &stub);
if (stub != NULL) {
boost::scoped_ptr<Master_Stub> stub_guard(stub);
CheckUnfinishedTask(stub);
_exit(0);
}
} else {
LOG(WARNING, "fail to connect nexus");
}
}
cur_task_id_ = -1;
cur_attempt_id_ = -1;
cur_task_state_ = kTaskUnknown;
watch_dog_.AddTask(boost::bind(&MinionImpl::WatchDogTask, this));
}
MinionImpl::~MinionImpl() {
delete executor_;
}
void MinionImpl::WatchDogTask() {
double minute_load = 0.0;
int numCPU = sysconf( _SC_NPROCESSORS_ONLN );
FILE* file = fopen("/proc/loadavg", "r");
fscanf(file, "%lf%*", &minute_load);
fclose(file);
int64_t network_limit = FLAGS_flow_limit_10gb;
if (!netstat_.Is10gb()) {
network_limit = FLAGS_flow_limit_1gb;
}
if (minute_load > 3.5 * numCPU) {
LOG(WARNING, "load average: %f, cores: %d", minute_load, numCPU);
LOG(WARNING, "machine may be overloaded, so froze the task");
system("killall -SIGSTOP input_tool shuffle_tool 2>/dev/null");
task_frozen_ = true;
} else if (netstat_.GetSendSpeed() > network_limit ||
netstat_.GetRecvSpeed() > network_limit) {
LOG(WARNING, "traffic tx:%lld, rx:%lld",
netstat_.GetSendSpeed(), netstat_.GetRecvSpeed());
LOG(WARNING, "network traffic is busy, so froze the task");
system("killall -SIGSTOP input_tool shuffle_tool 2>/dev/null");
task_frozen_ = true;
} else {
if (task_frozen_) {
LOG(INFO, "machine seems healthy, so resume the task");
}
system("killall -SIGCONT input_tool shuffle_tool 2>/dev/null");
task_frozen_ = false;
}
watch_dog_.DelayTask(5000, boost::bind(&MinionImpl::WatchDogTask, this));
}
void MinionImpl::Query(::google::protobuf::RpcController* controller,
const ::baidu::shuttle::QueryRequest* request,
::baidu::shuttle::QueryResponse* response,
::google::protobuf::Closure* done) {
(void)controller;
(void)request;
MutexLock locker(&mu_);
response->set_job_id(jobid_);
response->set_task_id(cur_task_id_);
response->set_attempt_id(cur_attempt_id_);
response->set_task_state(cur_task_state_);
done->Run();
}
void MinionImpl::CancelTask(::google::protobuf::RpcController* controller,
const ::baidu::shuttle::CancelTaskRequest* request,
::baidu::shuttle::CancelTaskResponse* response,
::google::protobuf::Closure* done) {
(void)controller;
int32_t task_id = request->task_id();
{
MutexLock locker(&mu_);
if (task_id != cur_task_id_) {
response->set_status(kNoSuchTask);
} else {
executor_->Stop(task_id);
response->set_status(kOk);
}
}
done->Run();
}
void MinionImpl::SetEndpoint(const std::string& endpoint) {
LOG(INFO, "minon bind endpoint on : %s", endpoint.c_str());
endpoint_ = endpoint;
}
void MinionImpl::SetJobId(const std::string& jobid) {
LOG(INFO, "minion will work on job: %s", jobid.c_str());
jobid_ = jobid;
}
void MinionImpl::SleepRandomTime() {
double rn = rand() / (RAND_MAX+0.0);
int random_period = static_cast<int>(rn * FLAGS_suspend_time);
sleep(5 + random_period);
}
void MinionImpl::Loop() {
srand(time(NULL));
Master_Stub* stub;
rpc_client_.GetStub(master_endpoint_, &stub);
if (stub == NULL) {
LOG(FATAL, "fail to get master stub");
}
boost::scoped_ptr<Master_Stub> stub_guard(stub);
int task_count = 0;
CheckUnfinishedTask(stub);
while (!stop_) {
LOG(INFO, "======== task:%d ========", ++task_count);
::baidu::shuttle::AssignTaskRequest request;
::baidu::shuttle::AssignTaskResponse response;
request.set_endpoint(endpoint_);
request.set_jobid(jobid_);
request.set_work_mode(work_mode_);
LOG(INFO, "endpoint: %s", endpoint_.c_str());
LOG(INFO, "jobid_: %s", jobid_.c_str());
while (!stop_) {
bool ok = rpc_client_.SendRequest(stub, &Master_Stub::AssignTask,
&request, &response, 5, 1);
if (!ok) {
LOG(WARNING, "fail to fetch task from master[%s]", master_endpoint_.c_str());
SleepRandomTime();
continue;
} else {
break;
}
}
if (response.status() == kNoMore) {
LOG(INFO, "master has no more task for minion, so exit.");
break;
} else if (response.status() == kNoSuchJob) {
LOG(INFO, "the job may be finished.");
break;
} else if (response.status() == kSuspend) {
LOG(INFO, "minion will suspend for a while");
SleepRandomTime();
continue;
} else if (response.status() != kOk) {
LOG(FATAL, "invalid response status: %s",
Status_Name(response.status()).c_str());
}
const TaskInfo& task = response.task();
SaveBreakpoint(task);
executor_->SetEnv(jobid_, task);
{
MutexLock locker(&mu_);
cur_task_id_ = task.task_id();
cur_attempt_id_ = task.attempt_id();
cur_task_state_ = kTaskRunning;
}
LOG(INFO, "try exec task: %s, %d, %d", jobid_.c_str(), cur_task_id_, cur_attempt_id_);
TaskState task_state = executor_->Exec(task); //exec here~~
{
MutexLock locker(&mu_);
cur_task_state_ = task_state;
}
LOG(INFO, "exec done, task state: %s", TaskState_Name(task_state).c_str());
std::string error_msg;
if (task_state == kTaskFailed) {
error_msg = executor_->GetErrorMsg(task, (work_mode_ != kReduce));
}
::baidu::shuttle::FinishTaskRequest fn_request;
::baidu::shuttle::FinishTaskResponse fn_response;
fn_request.set_jobid(jobid_);
fn_request.set_task_id(task.task_id());
fn_request.set_attempt_id(task.attempt_id());
fn_request.set_task_state(task_state);
fn_request.set_endpoint(endpoint_);
fn_request.set_work_mode(work_mode_);
fn_request.set_error_msg(error_msg);
while (!stop_) {
bool ok = rpc_client_.SendRequest(stub, &Master_Stub::FinishTask,
&fn_request, &fn_response, 5, 1);
if (!ok) {
LOG(WARNING, "fail to send task state to master");
SleepRandomTime();
continue;
} else {
if (fn_response.status() == kSuspend) {
LOG(WARNING, "wait a moment and then report finish");
SleepRandomTime();
continue;
}
break;
}
}
ClearBreakpoint();
if (task_state == kTaskFailed) {
LOG(WARNING, "task state: %s", TaskState_Name(task_state).c_str());
executor_->UploadErrorMsg(task, (work_mode_ != kReduce), error_msg);
SleepRandomTime();
}
}
{
MutexLock locker(&mu_);
stop_ = true;
}
}
bool MinionImpl::IsStop() {
return stop_;
}
bool MinionImpl::Run() {
galaxy::ins::sdk::SDKError err;
ins_.Get(FLAGS_master_nexus_path, &master_endpoint_, &err);
if (err != galaxy::ins::sdk::kOK) {
LOG(WARNING, "failed to fetch master endpoint from nexus, errno: %d", err);
LOG(WARNING, "master_endpoint (%s) -> %s", FLAGS_master_nexus_path.c_str(),
master_endpoint_.c_str());
return false;
}
pool_.AddTask(boost::bind(&MinionImpl::Loop, this));
return true;
}
void MinionImpl::CheckUnfinishedTask(Master_Stub* master_stub) {
FILE* breakpoint = fopen(sBreakpointFile.c_str(), "r");
int task_id;
int attempt_id;
if (breakpoint) {
int n_ret = fscanf(breakpoint, "%d%d", &task_id, &attempt_id);
if (n_ret != 2) {
LOG(WARNING, "invalid breakpoint file");
return;
}
fclose(breakpoint);
::baidu::shuttle::FinishTaskRequest fn_request;
::baidu::shuttle::FinishTaskResponse fn_response;
LOG(WARNING, "found unfinished task: task_id: %d, attempt_id: %d", task_id, attempt_id);
fn_request.set_jobid(FLAGS_jobid);
fn_request.set_task_id(task_id);
fn_request.set_attempt_id(attempt_id);
fn_request.set_task_state(kTaskKilled);
fn_request.set_endpoint(endpoint_);
fn_request.set_work_mode(work_mode_);
bool ok = rpc_client_.SendRequest(master_stub, &Master_Stub::FinishTask,
&fn_request, &fn_response, 5, 1);
if (!ok) {
LOG(FATAL, "fail to report unfinished task to master");
abort();
}
}
}
void MinionImpl::SaveBreakpoint(const TaskInfo& task) {
FILE* breakpoint = fopen(sBreakpointFile.c_str(), "w");
if (breakpoint) {
fprintf(breakpoint, "%d %d\n", task.task_id(), task.attempt_id());
fclose(breakpoint);
}
}
void MinionImpl::ClearBreakpoint() {
if (remove(sBreakpointFile.c_str()) != 0 ) {
LOG(WARNING, "failed to remove breakponit file");
}
}
}
}
<commit_msg>some machine may be always overloaded<commit_after>#include "minion_impl.h"
#include <time.h>
#include <unistd.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <cstdlib>
#include <gflags/gflags.h>
#include "logging.h"
#include "proto/app_master.pb.h"
DECLARE_string(master_nexus_path);
DECLARE_string(nexus_addr);
DECLARE_string(work_mode);
DECLARE_string(jobid);
DECLARE_bool(kill_task);
DECLARE_int32(suspend_time);
DECLARE_int64(flow_limit_10gb);
DECLARE_int64(flow_limit_1gb);
using baidu::common::Log;
using baidu::common::FATAL;
using baidu::common::INFO;
using baidu::common::WARNING;
namespace baidu {
namespace shuttle {
const std::string sBreakpointFile = "./task_running";
MinionImpl::MinionImpl() : ins_(FLAGS_nexus_addr),
stop_(false),
task_frozen_(false) {
if (FLAGS_work_mode == "map") {
executor_ = Executor::GetExecutor(kMap);
work_mode_ = kMap;
} else if (FLAGS_work_mode == "reduce") {
executor_ = Executor::GetExecutor(kReduce);
work_mode_ = kReduce;
} else if (FLAGS_work_mode == "map-only") {
executor_ = Executor::GetExecutor(kMapOnly);
work_mode_ = kMapOnly;
} else {
LOG(FATAL, "unkown work mode: %s", FLAGS_work_mode.c_str());
abort();
}
if (FLAGS_kill_task) {
galaxy::ins::sdk::SDKError err;
ins_.Get(FLAGS_master_nexus_path, &master_endpoint_, &err);
if (err == galaxy::ins::sdk::kOK) {
Master_Stub* stub;
rpc_client_.GetStub(master_endpoint_, &stub);
if (stub != NULL) {
boost::scoped_ptr<Master_Stub> stub_guard(stub);
CheckUnfinishedTask(stub);
_exit(0);
}
} else {
LOG(WARNING, "fail to connect nexus");
}
}
cur_task_id_ = -1;
cur_attempt_id_ = -1;
cur_task_state_ = kTaskUnknown;
watch_dog_.AddTask(boost::bind(&MinionImpl::WatchDogTask, this));
}
MinionImpl::~MinionImpl() {
delete executor_;
}
void MinionImpl::WatchDogTask() {
double minute_load = 0.0;
int numCPU = sysconf( _SC_NPROCESSORS_ONLN );
FILE* file = fopen("/proc/loadavg", "r");
fscanf(file, "%lf%*", &minute_load);
fclose(file);
int64_t network_limit = FLAGS_flow_limit_10gb;
if (!netstat_.Is10gb()) {
network_limit = FLAGS_flow_limit_1gb;
}
if (minute_load > 3.5 * numCPU) {
LOG(WARNING, "load average: %f, cores: %d", minute_load, numCPU);
LOG(WARNING, "machine may be overloaded, so froze the task");
double rn = rand() / (RAND_MAX+0.0);
if (rn < 0.01) {
_exit(0);
}
system("killall -SIGSTOP input_tool shuffle_tool 2>/dev/null");
task_frozen_ = true;
} else if (netstat_.GetSendSpeed() > network_limit ||
netstat_.GetRecvSpeed() > network_limit) {
LOG(WARNING, "traffic tx:%lld, rx:%lld",
netstat_.GetSendSpeed(), netstat_.GetRecvSpeed());
LOG(WARNING, "network traffic is busy, so froze the task");
system("killall -SIGSTOP input_tool shuffle_tool 2>/dev/null");
task_frozen_ = true;
} else {
if (task_frozen_) {
LOG(INFO, "machine seems healthy, so resume the task");
}
system("killall -SIGCONT input_tool shuffle_tool 2>/dev/null");
task_frozen_ = false;
}
watch_dog_.DelayTask(5000, boost::bind(&MinionImpl::WatchDogTask, this));
}
void MinionImpl::Query(::google::protobuf::RpcController* controller,
const ::baidu::shuttle::QueryRequest* request,
::baidu::shuttle::QueryResponse* response,
::google::protobuf::Closure* done) {
(void)controller;
(void)request;
MutexLock locker(&mu_);
response->set_job_id(jobid_);
response->set_task_id(cur_task_id_);
response->set_attempt_id(cur_attempt_id_);
response->set_task_state(cur_task_state_);
done->Run();
}
void MinionImpl::CancelTask(::google::protobuf::RpcController* controller,
const ::baidu::shuttle::CancelTaskRequest* request,
::baidu::shuttle::CancelTaskResponse* response,
::google::protobuf::Closure* done) {
(void)controller;
int32_t task_id = request->task_id();
{
MutexLock locker(&mu_);
if (task_id != cur_task_id_) {
response->set_status(kNoSuchTask);
} else {
executor_->Stop(task_id);
response->set_status(kOk);
}
}
done->Run();
}
void MinionImpl::SetEndpoint(const std::string& endpoint) {
LOG(INFO, "minon bind endpoint on : %s", endpoint.c_str());
endpoint_ = endpoint;
}
void MinionImpl::SetJobId(const std::string& jobid) {
LOG(INFO, "minion will work on job: %s", jobid.c_str());
jobid_ = jobid;
}
void MinionImpl::SleepRandomTime() {
double rn = rand() / (RAND_MAX+0.0);
int random_period = static_cast<int>(rn * FLAGS_suspend_time);
sleep(5 + random_period);
}
void MinionImpl::Loop() {
srand(time(NULL));
Master_Stub* stub;
rpc_client_.GetStub(master_endpoint_, &stub);
if (stub == NULL) {
LOG(FATAL, "fail to get master stub");
}
boost::scoped_ptr<Master_Stub> stub_guard(stub);
int task_count = 0;
CheckUnfinishedTask(stub);
while (!stop_) {
LOG(INFO, "======== task:%d ========", ++task_count);
::baidu::shuttle::AssignTaskRequest request;
::baidu::shuttle::AssignTaskResponse response;
request.set_endpoint(endpoint_);
request.set_jobid(jobid_);
request.set_work_mode(work_mode_);
LOG(INFO, "endpoint: %s", endpoint_.c_str());
LOG(INFO, "jobid_: %s", jobid_.c_str());
while (!stop_) {
bool ok = rpc_client_.SendRequest(stub, &Master_Stub::AssignTask,
&request, &response, 5, 1);
if (!ok) {
LOG(WARNING, "fail to fetch task from master[%s]", master_endpoint_.c_str());
SleepRandomTime();
continue;
} else {
break;
}
}
if (response.status() == kNoMore) {
LOG(INFO, "master has no more task for minion, so exit.");
break;
} else if (response.status() == kNoSuchJob) {
LOG(INFO, "the job may be finished.");
break;
} else if (response.status() == kSuspend) {
LOG(INFO, "minion will suspend for a while");
SleepRandomTime();
continue;
} else if (response.status() != kOk) {
LOG(FATAL, "invalid response status: %s",
Status_Name(response.status()).c_str());
}
const TaskInfo& task = response.task();
SaveBreakpoint(task);
executor_->SetEnv(jobid_, task);
{
MutexLock locker(&mu_);
cur_task_id_ = task.task_id();
cur_attempt_id_ = task.attempt_id();
cur_task_state_ = kTaskRunning;
}
LOG(INFO, "try exec task: %s, %d, %d", jobid_.c_str(), cur_task_id_, cur_attempt_id_);
TaskState task_state = executor_->Exec(task); //exec here~~
{
MutexLock locker(&mu_);
cur_task_state_ = task_state;
}
LOG(INFO, "exec done, task state: %s", TaskState_Name(task_state).c_str());
std::string error_msg;
if (task_state == kTaskFailed) {
error_msg = executor_->GetErrorMsg(task, (work_mode_ != kReduce));
}
::baidu::shuttle::FinishTaskRequest fn_request;
::baidu::shuttle::FinishTaskResponse fn_response;
fn_request.set_jobid(jobid_);
fn_request.set_task_id(task.task_id());
fn_request.set_attempt_id(task.attempt_id());
fn_request.set_task_state(task_state);
fn_request.set_endpoint(endpoint_);
fn_request.set_work_mode(work_mode_);
fn_request.set_error_msg(error_msg);
while (!stop_) {
bool ok = rpc_client_.SendRequest(stub, &Master_Stub::FinishTask,
&fn_request, &fn_response, 5, 1);
if (!ok) {
LOG(WARNING, "fail to send task state to master");
SleepRandomTime();
continue;
} else {
if (fn_response.status() == kSuspend) {
LOG(WARNING, "wait a moment and then report finish");
SleepRandomTime();
continue;
}
break;
}
}
ClearBreakpoint();
if (task_state == kTaskFailed) {
LOG(WARNING, "task state: %s", TaskState_Name(task_state).c_str());
executor_->UploadErrorMsg(task, (work_mode_ != kReduce), error_msg);
SleepRandomTime();
}
}
{
MutexLock locker(&mu_);
stop_ = true;
}
}
bool MinionImpl::IsStop() {
return stop_;
}
bool MinionImpl::Run() {
galaxy::ins::sdk::SDKError err;
ins_.Get(FLAGS_master_nexus_path, &master_endpoint_, &err);
if (err != galaxy::ins::sdk::kOK) {
LOG(WARNING, "failed to fetch master endpoint from nexus, errno: %d", err);
LOG(WARNING, "master_endpoint (%s) -> %s", FLAGS_master_nexus_path.c_str(),
master_endpoint_.c_str());
return false;
}
pool_.AddTask(boost::bind(&MinionImpl::Loop, this));
return true;
}
void MinionImpl::CheckUnfinishedTask(Master_Stub* master_stub) {
FILE* breakpoint = fopen(sBreakpointFile.c_str(), "r");
int task_id;
int attempt_id;
if (breakpoint) {
int n_ret = fscanf(breakpoint, "%d%d", &task_id, &attempt_id);
if (n_ret != 2) {
LOG(WARNING, "invalid breakpoint file");
return;
}
fclose(breakpoint);
::baidu::shuttle::FinishTaskRequest fn_request;
::baidu::shuttle::FinishTaskResponse fn_response;
LOG(WARNING, "found unfinished task: task_id: %d, attempt_id: %d", task_id, attempt_id);
fn_request.set_jobid(FLAGS_jobid);
fn_request.set_task_id(task_id);
fn_request.set_attempt_id(attempt_id);
fn_request.set_task_state(kTaskKilled);
fn_request.set_endpoint(endpoint_);
fn_request.set_work_mode(work_mode_);
bool ok = rpc_client_.SendRequest(master_stub, &Master_Stub::FinishTask,
&fn_request, &fn_response, 5, 1);
if (!ok) {
LOG(FATAL, "fail to report unfinished task to master");
abort();
}
}
}
void MinionImpl::SaveBreakpoint(const TaskInfo& task) {
FILE* breakpoint = fopen(sBreakpointFile.c_str(), "w");
if (breakpoint) {
fprintf(breakpoint, "%d %d\n", task.task_id(), task.attempt_id());
fclose(breakpoint);
}
}
void MinionImpl::ClearBreakpoint() {
if (remove(sBreakpointFile.c_str()) != 0 ) {
LOG(WARNING, "failed to remove breakponit file");
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Test Driver for Botan
*/
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <memory>
#include <botan/botan.h>
#include <botan/libstate.h>
using namespace Botan;
#include "getopt.h"
#include "bench.h"
#include "validate.h"
#include "common.h"
const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";
int run_test_suite(RandomNumberGenerator& rng);
namespace {
template<typename T>
bool test(const char* type, int digits, bool is_signed)
{
if(std::numeric_limits<T>::is_specialized == false)
{
std::cout << "WARNING: Could not check parameters of " << type
<< " in std::numeric_limits" << std::endl;
// assume it's OK (full tests will catch it later)
return true;
}
// continue checking after failures
bool passed = true;
if(std::numeric_limits<T>::is_integer == false)
{
std::cout << "WARN: std::numeric_limits<> says " << type
<< " is not an integer" << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_signed != is_signed)
{
std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == "
<< std::boolalpha << std::numeric_limits<T>::is_signed
<< std::endl;
passed = false;
}
if(std::numeric_limits<T>::digits != digits && digits != 0)
{
std::cout << "ERROR: numeric_limits<" << type << ">::digits == "
<< std::numeric_limits<T>::digits
<< " expected " << digits << std::endl;
passed = false;
}
return passed;
}
void test_types()
{
bool passed = true;
passed = passed && test<Botan::byte >("byte", 8, false);
passed = passed && test<Botan::u16bit>("u16bit", 16, false);
passed = passed && test<Botan::u32bit>("u32bit", 32, false);
passed = passed && test<Botan::u64bit>("u64bit", 64, false);
passed = passed && test<Botan::s32bit>("s32bit", 31, true);
if(!passed)
std::cout << "Typedefs in include/types.h may be incorrect!\n";
}
}
int main(int argc, char* argv[])
{
try
{
OptionParser opts("help|test|validate|"
"benchmark|bench-type=|bench-algo=|seconds=");
opts.parse(argv);
test_types(); // do this always
Botan::LibraryInitializer init("thread_safe=no");
Botan::AutoSeeded_RNG rng;
if(opts.is_set("help") || argc <= 1)
{
std::cerr << "Test driver for "
<< Botan::version_string() << "\n"
<< "Options:\n"
<< " --test || --validate: Run tests (do this at least once)\n"
<< " --benchmark: Benchmark everything\n"
<< " --seconds=n: Benchmark for n seconds\n"
<< " --init=<str>: Pass <str> to the library\n"
<< " --help: Print this message\n";
return 1;
}
if(opts.is_set("validate") || opts.is_set("test"))
{
return run_test_suite(rng);
}
if(opts.is_set("bench-algo") ||
opts.is_set("benchmark") ||
opts.is_set("bench-type"))
{
double seconds = 2;
if(opts.is_set("seconds"))
{
seconds = std::atof(opts.value("seconds").c_str());
if(seconds < 0.1 || seconds > (5 * 60))
{
std::cout << "Invalid argument to --seconds\n";
return 2;
}
}
if(opts.is_set("benchmark"))
{
benchmark(rng, seconds);
}
else if(opts.is_set("bench-algo"))
{
std::vector<std::string> algs =
Botan::split_on(opts.value("bench-algo"), ',');
for(u32bit j = 0; j != algs.size(); j++)
{
const std::string alg = algs[j];
if(!bench_algo(alg, rng, seconds)) // maybe it's a PK algorithm
bench_pk(rng, alg, seconds);
}
}
}
}
catch(std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
catch(...)
{
std::cerr << "Unknown (...) exception caught" << std::endl;
return 1;
}
return 0;
}
int run_test_suite(RandomNumberGenerator& rng)
{
std::cout << "Beginning tests..." << std::endl;
u32bit errors = 0;
try
{
errors += do_validation_tests(VALIDATION_FILE, rng);
errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false);
errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng);
errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng);
//errors += do_cvc_tests(rng);
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
if(errors)
{
std::cout << errors << " test" << ((errors == 1) ? "" : "s")
<< " failed." << std::endl;
return 1;
}
std::cout << "All tests passed!" << std::endl;
return 0;
}
<commit_msg>Increase default benchmark time to 5 seconds<commit_after>/*
* Test Driver for Botan
*/
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <memory>
#include <botan/botan.h>
#include <botan/libstate.h>
using namespace Botan;
#include "getopt.h"
#include "bench.h"
#include "validate.h"
#include "common.h"
const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";
int run_test_suite(RandomNumberGenerator& rng);
namespace {
template<typename T>
bool test(const char* type, int digits, bool is_signed)
{
if(std::numeric_limits<T>::is_specialized == false)
{
std::cout << "WARNING: Could not check parameters of " << type
<< " in std::numeric_limits" << std::endl;
// assume it's OK (full tests will catch it later)
return true;
}
// continue checking after failures
bool passed = true;
if(std::numeric_limits<T>::is_integer == false)
{
std::cout << "WARN: std::numeric_limits<> says " << type
<< " is not an integer" << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_signed != is_signed)
{
std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == "
<< std::boolalpha << std::numeric_limits<T>::is_signed
<< std::endl;
passed = false;
}
if(std::numeric_limits<T>::digits != digits && digits != 0)
{
std::cout << "ERROR: numeric_limits<" << type << ">::digits == "
<< std::numeric_limits<T>::digits
<< " expected " << digits << std::endl;
passed = false;
}
return passed;
}
void test_types()
{
bool passed = true;
passed = passed && test<Botan::byte >("byte", 8, false);
passed = passed && test<Botan::u16bit>("u16bit", 16, false);
passed = passed && test<Botan::u32bit>("u32bit", 32, false);
passed = passed && test<Botan::u64bit>("u64bit", 64, false);
passed = passed && test<Botan::s32bit>("s32bit", 31, true);
if(!passed)
std::cout << "Typedefs in include/types.h may be incorrect!\n";
}
}
int main(int argc, char* argv[])
{
try
{
OptionParser opts("help|test|validate|"
"benchmark|bench-type=|bench-algo=|seconds=");
opts.parse(argv);
test_types(); // do this always
Botan::LibraryInitializer init("thread_safe=no");
Botan::AutoSeeded_RNG rng;
if(opts.is_set("help") || argc <= 1)
{
std::cerr << "Test driver for "
<< Botan::version_string() << "\n"
<< "Options:\n"
<< " --test || --validate: Run tests (do this at least once)\n"
<< " --benchmark: Benchmark everything\n"
<< " --seconds=n: Benchmark for n seconds\n"
<< " --init=<str>: Pass <str> to the library\n"
<< " --help: Print this message\n";
return 1;
}
if(opts.is_set("validate") || opts.is_set("test"))
{
return run_test_suite(rng);
}
if(opts.is_set("bench-algo") ||
opts.is_set("benchmark") ||
opts.is_set("bench-type"))
{
double seconds = 5;
if(opts.is_set("seconds"))
{
seconds = std::atof(opts.value("seconds").c_str());
if(seconds < 0.1 || seconds > (5 * 60))
{
std::cout << "Invalid argument to --seconds\n";
return 2;
}
}
if(opts.is_set("benchmark"))
{
benchmark(rng, seconds);
}
else if(opts.is_set("bench-algo"))
{
std::vector<std::string> algs =
Botan::split_on(opts.value("bench-algo"), ',');
for(u32bit j = 0; j != algs.size(); j++)
{
const std::string alg = algs[j];
if(!bench_algo(alg, rng, seconds)) // maybe it's a PK algorithm
bench_pk(rng, alg, seconds);
}
}
}
}
catch(std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
catch(...)
{
std::cerr << "Unknown (...) exception caught" << std::endl;
return 1;
}
return 0;
}
int run_test_suite(RandomNumberGenerator& rng)
{
std::cout << "Beginning tests..." << std::endl;
u32bit errors = 0;
try
{
errors += do_validation_tests(VALIDATION_FILE, rng);
errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false);
errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng);
errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng);
//errors += do_cvc_tests(rng);
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
if(errors)
{
std::cout << errors << " test" << ((errors == 1) ? "" : "s")
<< " failed." << std::endl;
return 1;
}
std::cout << "All tests passed!" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <primitives/executor.h>
#include <iostream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#endif
//#include "log.h"
//DECLARE_STATIC_LOGGER(logger, "executor");
size_t get_max_threads(size_t N)
{
return std::max<size_t>(N, std::thread::hardware_concurrency());
}
Executor::Executor(const std::string &name, size_t nThreads)
: Executor(nThreads, name)
{
}
Executor::Executor(size_t nThreads, const std::string &name)
: nThreads(nThreads)
{
thread_pool.resize(nThreads);
for (size_t i = 0; i < nThreads; i++)
{
thread_pool[i].t = std::move(std::thread([this, i, name = name]() mutable
{
name += " " + std::to_string(i);
set_thread_name(name, i);
run(i);
}));
}
}
Executor::~Executor()
{
join();
}
void Executor::run(size_t i)
{
while (!done)
{
std::string error;
try
{
Task t;
const size_t spin_count = nThreads * 4;
for (auto n = 0; n != spin_count; ++n)
{
if (thread_pool[(i + n) % nThreads].q.try_pop(t))
break;
}
// no task popped, probably shutdown command was issues
if (!t && !thread_pool[i].q.pop(t))
break;
thread_pool[i].busy = true;
if (!done) // double check
t();
}
catch (const std::exception &e)
{
error = e.what();
thread_pool[i].eptr = std::current_exception();
}
catch (...)
{
error = "unknown exception";
thread_pool[i].eptr = std::current_exception();
}
thread_pool[i].busy = false;
if (!error.empty())
{
if (throw_exceptions)
done = true;
else if (!silent)
std::cerr << "executor: " << this << ", thread #" << i + 1 << ", error: " << error << "\n";
//LOG_ERROR(logger, "executor: " << this << ", thread #" << i + 1 << ", error: " << error);
}
}
}
void Executor::join()
{
stop();
for (auto &t : thread_pool)
if (t.t.joinable())
t.t.join();
}
void Executor::stop()
{
done = true;
for (auto &t : thread_pool)
t.q.done();
}
void Executor::wait()
{
// wait for empty queues
for (auto &t : thread_pool)
while (!t.q.empty() && !done)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// wait for end of execution
for (auto &t : thread_pool)
while (t.busy && !done)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (throw_exceptions)
for (auto &t : thread_pool)
if (t.eptr)
std::rethrow_exception(t.eptr);
}
void Executor::set_thread_name(const std::string &name, size_t i) const
{
if (name.empty())
return;
#if defined(_MSC_VER)
#pragma pack(push, 8)
struct THREADNAME_INFO
{
DWORD dwType = 0x1000; // Must be 0x1000.
LPCSTR szName; // Pointer to thread name
DWORD dwThreadId = -1; // Thread ID (-1 == current thread)
DWORD dwFlags = 0; // Reserved. Do not use.
};
#pragma pack(pop)
THREADNAME_INFO info;
info.szName = name.c_str();
__try
{
::RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
#endif
}
<commit_msg>Clear exception ptr.<commit_after>#include <primitives/executor.h>
#include <iostream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#endif
//#include "log.h"
//DECLARE_STATIC_LOGGER(logger, "executor");
size_t get_max_threads(size_t N)
{
return std::max<size_t>(N, std::thread::hardware_concurrency());
}
Executor::Executor(const std::string &name, size_t nThreads)
: Executor(nThreads, name)
{
}
Executor::Executor(size_t nThreads, const std::string &name)
: nThreads(nThreads)
{
thread_pool.resize(nThreads);
for (size_t i = 0; i < nThreads; i++)
{
thread_pool[i].t = std::move(std::thread([this, i, name = name]() mutable
{
name += " " + std::to_string(i);
set_thread_name(name, i);
run(i);
}));
}
}
Executor::~Executor()
{
join();
}
void Executor::run(size_t i)
{
while (!done)
{
std::string error;
try
{
Task t;
const size_t spin_count = nThreads * 4;
for (auto n = 0; n != spin_count; ++n)
{
if (thread_pool[(i + n) % nThreads].q.try_pop(t))
break;
}
// no task popped, probably shutdown command was issues
if (!t && !thread_pool[i].q.pop(t))
break;
thread_pool[i].busy = true;
if (!done) // double check
t();
}
catch (const std::exception &e)
{
error = e.what();
thread_pool[i].eptr = std::current_exception();
}
catch (...)
{
error = "unknown exception";
thread_pool[i].eptr = std::current_exception();
}
thread_pool[i].busy = false;
if (!error.empty())
{
if (throw_exceptions)
done = true;
else
{
// clear
thread_pool[i].eptr = std::current_exception();
if (!silent)
std::cerr << "executor: " << this << ", thread #" << i + 1 << ", error: " << error << "\n";
//LOG_ERROR(logger, "executor: " << this << ", thread #" << i + 1 << ", error: " << error);
}
}
}
}
void Executor::join()
{
stop();
for (auto &t : thread_pool)
{
if (t.t.joinable())
t.t.join();
}
}
void Executor::stop()
{
done = true;
for (auto &t : thread_pool)
t.q.done();
}
void Executor::wait()
{
// wait for empty queues
for (auto &t : thread_pool)
{
while (!t.q.empty() && !done)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// wait for end of execution
for (auto &t : thread_pool)
{
while (t.busy && !done)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (throw_exceptions)
{
for (auto &t : thread_pool)
{
if (t.eptr)
std::rethrow_exception(t.eptr);
}
}
}
void Executor::set_thread_name(const std::string &name, size_t i) const
{
if (name.empty())
return;
#if defined(_MSC_VER)
#pragma pack(push, 8)
struct THREADNAME_INFO
{
DWORD dwType = 0x1000; // Must be 0x1000.
LPCSTR szName; // Pointer to thread name
DWORD dwThreadId = -1; // Thread ID (-1 == current thread)
DWORD dwFlags = 0; // Reserved. Do not use.
};
#pragma pack(pop)
THREADNAME_INFO info;
info.szName = name.c_str();
__try
{
::RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
#endif
}
<|endoftext|>
|
<commit_before>//===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
//
// Copyright 2019 The MLIR 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 implements mlir::applyPatternsGreedily.
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/PatternMatch.h"
#include "llvm/ADT/DenseMap.h"
using namespace mlir;
namespace {
/// This is a worklist-driven driver for the PatternMatcher, which repeatedly
/// applies the locally optimal patterns in a roughly "bottom up" way.
class GreedyPatternRewriteDriver : public PatternRewriter {
public:
explicit GreedyPatternRewriteDriver(Function *fn,
OwningRewritePatternList &&patterns)
: PatternRewriter(fn->getContext()), matcher(std::move(patterns)),
builder(fn) {
worklist.reserve(64);
// Add all operations to the worklist.
fn->walk([&](Instruction *inst) { addToWorklist(inst); });
}
/// Perform the rewrites.
void simplifyFunction();
void addToWorklist(Instruction *op) {
// Check to see if the worklist already contains this op.
if (worklistMap.count(op))
return;
worklistMap[op] = worklist.size();
worklist.push_back(op);
}
Instruction *popFromWorklist() {
auto *op = worklist.back();
worklist.pop_back();
// This operation is no longer in the worklist, keep worklistMap up to date.
if (op)
worklistMap.erase(op);
return op;
}
/// If the specified operation is in the worklist, remove it. If not, this is
/// a no-op.
void removeFromWorklist(Instruction *op) {
auto it = worklistMap.find(op);
if (it != worklistMap.end()) {
assert(worklist[it->second] == op && "malformed worklist data structure");
worklist[it->second] = nullptr;
}
}
// These are hooks implemented for PatternRewriter.
protected:
// Implement the hook for creating operations, and make sure that newly
// created ops are added to the worklist for processing.
Instruction *createOperation(const OperationState &state) override {
auto *result = builder.createOperation(state);
addToWorklist(result);
return result;
}
// If an operation is about to be removed, make sure it is not in our
// worklist anymore because we'd get dangling references to it.
void notifyOperationRemoved(Instruction *op) override {
removeFromWorklist(op);
}
// When the root of a pattern is about to be replaced, it can trigger
// simplifications to its users - make sure to add them to the worklist
// before the root is changed.
void notifyRootReplaced(Instruction *op) override {
for (auto *result : op->getResults())
// TODO: Add a result->getUsers() iterator.
for (auto &user : result->getUses())
addToWorklist(user.getOwner());
// TODO: Walk the operand list dropping them as we go. If any of them
// drop to zero uses, then add them to the worklist to allow them to be
// deleted as dead.
}
private:
/// The low-level pattern matcher.
PatternMatcher matcher;
/// This builder is used to create new operations.
FuncBuilder builder;
/// The worklist for this transformation keeps track of the operations that
/// need to be revisited, plus their index in the worklist. This allows us to
/// efficiently remove operations from the worklist when they are erased from
/// the function, even if they aren't the root of a pattern.
std::vector<Instruction *> worklist;
DenseMap<Instruction *, unsigned> worklistMap;
/// As part of canonicalization, we move constants to the top of the entry
/// block of the current function and de-duplicate them. This keeps track of
/// constants we have done this for.
DenseMap<std::pair<Attribute, Type>, Instruction *> uniquedConstants;
};
}; // end anonymous namespace
/// Perform the rewrites.
void GreedyPatternRewriteDriver::simplifyFunction() {
// These are scratch vectors used in the constant folding loop below.
SmallVector<Attribute, 8> operandConstants, resultConstants;
SmallVector<Value *, 8> originalOperands, resultValues;
while (!worklist.empty()) {
auto *op = popFromWorklist();
// Nulls get added to the worklist when operations are removed, ignore them.
if (op == nullptr)
continue;
// If we have a constant op, unique it into the entry block.
if (auto constant = op->dyn_cast<ConstantOp>()) {
// If this constant is dead, remove it, being careful to keep
// uniquedConstants up to date.
if (constant->use_empty()) {
auto it =
uniquedConstants.find({constant->getValue(), constant->getType()});
if (it != uniquedConstants.end() && it->second == op)
uniquedConstants.erase(it);
constant->erase();
continue;
}
// Check to see if we already have a constant with this type and value:
auto &entry = uniquedConstants[std::make_pair(constant->getValue(),
constant->getType())];
if (entry) {
// If this constant is already our uniqued one, then leave it alone.
if (entry == op)
continue;
// Otherwise replace this redundant constant with the uniqued one. We
// know this is safe because we move constants to the top of the
// function when they are uniqued, so we know they dominate all uses.
constant->replaceAllUsesWith(entry->getResult(0));
constant->erase();
continue;
}
// If we have no entry, then we should unique this constant as the
// canonical version. To ensure safe dominance, move the operation to the
// top of the function.
entry = op;
auto &entryBB = builder.getInsertionBlock()->getFunction()->front();
op->moveBefore(&entryBB, entryBB.begin());
continue;
}
// If the operation has no side effects, and no users, then it is trivially
// dead - remove it.
if (op->hasNoSideEffect() && op->use_empty()) {
op->erase();
continue;
}
// Check to see if any operands to the instruction is constant and whether
// the operation knows how to constant fold itself.
operandConstants.clear();
for (auto *operand : op->getOperands()) {
Attribute operandCst;
if (auto *operandOp = operand->getDefiningInst()) {
if (auto operandConstantOp = operandOp->dyn_cast<ConstantOp>())
operandCst = operandConstantOp->getValue();
}
operandConstants.push_back(operandCst);
}
// If this is a commutative binary operation with a constant on the left
// side move it to the right side.
if (operandConstants.size() == 2 && operandConstants[0] &&
!operandConstants[1] && op->isCommutative()) {
std::swap(op->getInstOperand(0), op->getInstOperand(1));
std::swap(operandConstants[0], operandConstants[1]);
}
// If constant folding was successful, create the result constants, RAUW the
// operation and remove it.
resultConstants.clear();
if (!op->constantFold(operandConstants, resultConstants)) {
builder.setInsertionPoint(op);
for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
auto *res = op->getResult(i);
if (res->use_empty()) // ignore dead uses.
continue;
// If we already have a canonicalized version of this constant, just
// reuse it. Otherwise create a new one.
Value *cstValue;
auto it = uniquedConstants.find({resultConstants[i], res->getType()});
if (it != uniquedConstants.end())
cstValue = it->second->getResult(0);
else
cstValue = create<ConstantOp>(op->getLoc(), res->getType(),
resultConstants[i]);
// Add all the users of the result to the worklist so we make sure to
// revisit them.
//
// TODO: Add a result->getUsers() iterator.
for (auto &operand : op->getResult(i)->getUses())
addToWorklist(operand.getOwner());
res->replaceAllUsesWith(cstValue);
}
assert(op->hasNoSideEffect() && "Constant folded op with side effects?");
op->erase();
continue;
}
// Otherwise see if we can use the generic folder API to simplify the
// operation.
originalOperands.assign(op->operand_begin(), op->operand_end());
resultValues.clear();
if (!op->fold(resultValues)) {
// If the result was an in-place simplification (e.g. max(x,x,y) ->
// max(x,y)) then add the original operands to the worklist so we can make
// sure to revisit them.
if (resultValues.empty()) {
// TODO: Walk the original operand list dropping them as we go. If any
// of them drop to zero uses, then add them to the worklist to allow
// them to be deleted as dead.
} else {
// Otherwise, the operation is simplified away completely.
assert(resultValues.size() == op->getNumResults());
// Add all the users of the operation to the worklist so we make sure to
// revisit them.
//
// TODO: Add a result->getUsers() iterator.
for (unsigned i = 0, e = resultValues.size(); i != e; ++i) {
auto *res = op->getResult(i);
if (res->use_empty()) // ignore dead uses.
continue;
for (auto &operand : op->getResult(i)->getUses())
addToWorklist(operand.getOwner());
res->replaceAllUsesWith(resultValues[i]);
}
}
op->erase();
continue;
}
// Check to see if we have any patterns that match this node.
auto match = matcher.findMatch(op);
if (!match.first)
continue;
// Make sure that any new operations are inserted at this point.
builder.setInsertionPoint(op);
// We know that any pattern that matched is RewritePattern because we
// initialized the matcher with RewritePatterns.
auto *rewritePattern = static_cast<RewritePattern *>(match.first);
rewritePattern->rewrite(op, std::move(match.second), *this);
}
uniquedConstants.clear();
}
/// Rewrite the specified function by repeatedly applying the highest benefit
/// patterns in a greedy work-list driven manner.
///
void mlir::applyPatternsGreedily(Function *fn,
OwningRewritePatternList &&patterns) {
GreedyPatternRewriteDriver driver(fn, std::move(patterns));
driver.simplifyFunction();
}
<commit_msg>When canonicalizing only erase the operation after calling the 'fold' hook if replacement results were supplied. This fixes a bug where the operation would always get erased, even if it was modified in place.<commit_after>//===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
//
// Copyright 2019 The MLIR 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 implements mlir::applyPatternsGreedily.
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/PatternMatch.h"
#include "llvm/ADT/DenseMap.h"
using namespace mlir;
namespace {
/// This is a worklist-driven driver for the PatternMatcher, which repeatedly
/// applies the locally optimal patterns in a roughly "bottom up" way.
class GreedyPatternRewriteDriver : public PatternRewriter {
public:
explicit GreedyPatternRewriteDriver(Function *fn,
OwningRewritePatternList &&patterns)
: PatternRewriter(fn->getContext()), matcher(std::move(patterns)),
builder(fn) {
worklist.reserve(64);
// Add all operations to the worklist.
fn->walk([&](Instruction *inst) { addToWorklist(inst); });
}
/// Perform the rewrites.
void simplifyFunction();
void addToWorklist(Instruction *op) {
// Check to see if the worklist already contains this op.
if (worklistMap.count(op))
return;
worklistMap[op] = worklist.size();
worklist.push_back(op);
}
Instruction *popFromWorklist() {
auto *op = worklist.back();
worklist.pop_back();
// This operation is no longer in the worklist, keep worklistMap up to date.
if (op)
worklistMap.erase(op);
return op;
}
/// If the specified operation is in the worklist, remove it. If not, this is
/// a no-op.
void removeFromWorklist(Instruction *op) {
auto it = worklistMap.find(op);
if (it != worklistMap.end()) {
assert(worklist[it->second] == op && "malformed worklist data structure");
worklist[it->second] = nullptr;
}
}
// These are hooks implemented for PatternRewriter.
protected:
// Implement the hook for creating operations, and make sure that newly
// created ops are added to the worklist for processing.
Instruction *createOperation(const OperationState &state) override {
auto *result = builder.createOperation(state);
addToWorklist(result);
return result;
}
// If an operation is about to be removed, make sure it is not in our
// worklist anymore because we'd get dangling references to it.
void notifyOperationRemoved(Instruction *op) override {
removeFromWorklist(op);
}
// When the root of a pattern is about to be replaced, it can trigger
// simplifications to its users - make sure to add them to the worklist
// before the root is changed.
void notifyRootReplaced(Instruction *op) override {
for (auto *result : op->getResults())
// TODO: Add a result->getUsers() iterator.
for (auto &user : result->getUses())
addToWorklist(user.getOwner());
// TODO: Walk the operand list dropping them as we go. If any of them
// drop to zero uses, then add them to the worklist to allow them to be
// deleted as dead.
}
private:
/// The low-level pattern matcher.
PatternMatcher matcher;
/// This builder is used to create new operations.
FuncBuilder builder;
/// The worklist for this transformation keeps track of the operations that
/// need to be revisited, plus their index in the worklist. This allows us to
/// efficiently remove operations from the worklist when they are erased from
/// the function, even if they aren't the root of a pattern.
std::vector<Instruction *> worklist;
DenseMap<Instruction *, unsigned> worklistMap;
/// As part of canonicalization, we move constants to the top of the entry
/// block of the current function and de-duplicate them. This keeps track of
/// constants we have done this for.
DenseMap<std::pair<Attribute, Type>, Instruction *> uniquedConstants;
};
}; // end anonymous namespace
/// Perform the rewrites.
void GreedyPatternRewriteDriver::simplifyFunction() {
// These are scratch vectors used in the constant folding loop below.
SmallVector<Attribute, 8> operandConstants, resultConstants;
SmallVector<Value *, 8> originalOperands, resultValues;
while (!worklist.empty()) {
auto *op = popFromWorklist();
// Nulls get added to the worklist when operations are removed, ignore them.
if (op == nullptr)
continue;
// If we have a constant op, unique it into the entry block.
if (auto constant = op->dyn_cast<ConstantOp>()) {
// If this constant is dead, remove it, being careful to keep
// uniquedConstants up to date.
if (constant->use_empty()) {
auto it =
uniquedConstants.find({constant->getValue(), constant->getType()});
if (it != uniquedConstants.end() && it->second == op)
uniquedConstants.erase(it);
constant->erase();
continue;
}
// Check to see if we already have a constant with this type and value:
auto &entry = uniquedConstants[std::make_pair(constant->getValue(),
constant->getType())];
if (entry) {
// If this constant is already our uniqued one, then leave it alone.
if (entry == op)
continue;
// Otherwise replace this redundant constant with the uniqued one. We
// know this is safe because we move constants to the top of the
// function when they are uniqued, so we know they dominate all uses.
constant->replaceAllUsesWith(entry->getResult(0));
constant->erase();
continue;
}
// If we have no entry, then we should unique this constant as the
// canonical version. To ensure safe dominance, move the operation to the
// top of the function.
entry = op;
auto &entryBB = builder.getInsertionBlock()->getFunction()->front();
op->moveBefore(&entryBB, entryBB.begin());
continue;
}
// If the operation has no side effects, and no users, then it is trivially
// dead - remove it.
if (op->hasNoSideEffect() && op->use_empty()) {
op->erase();
continue;
}
// Check to see if any operands to the instruction is constant and whether
// the operation knows how to constant fold itself.
operandConstants.clear();
for (auto *operand : op->getOperands()) {
Attribute operandCst;
if (auto *operandOp = operand->getDefiningInst()) {
if (auto operandConstantOp = operandOp->dyn_cast<ConstantOp>())
operandCst = operandConstantOp->getValue();
}
operandConstants.push_back(operandCst);
}
// If this is a commutative binary operation with a constant on the left
// side move it to the right side.
if (operandConstants.size() == 2 && operandConstants[0] &&
!operandConstants[1] && op->isCommutative()) {
std::swap(op->getInstOperand(0), op->getInstOperand(1));
std::swap(operandConstants[0], operandConstants[1]);
}
// If constant folding was successful, create the result constants, RAUW the
// operation and remove it.
resultConstants.clear();
if (!op->constantFold(operandConstants, resultConstants)) {
builder.setInsertionPoint(op);
for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
auto *res = op->getResult(i);
if (res->use_empty()) // ignore dead uses.
continue;
// If we already have a canonicalized version of this constant, just
// reuse it. Otherwise create a new one.
Value *cstValue;
auto it = uniquedConstants.find({resultConstants[i], res->getType()});
if (it != uniquedConstants.end())
cstValue = it->second->getResult(0);
else
cstValue = create<ConstantOp>(op->getLoc(), res->getType(),
resultConstants[i]);
// Add all the users of the result to the worklist so we make sure to
// revisit them.
//
// TODO: Add a result->getUsers() iterator.
for (auto &operand : op->getResult(i)->getUses())
addToWorklist(operand.getOwner());
res->replaceAllUsesWith(cstValue);
}
assert(op->hasNoSideEffect() && "Constant folded op with side effects?");
op->erase();
continue;
}
// Otherwise see if we can use the generic folder API to simplify the
// operation.
originalOperands.assign(op->operand_begin(), op->operand_end());
resultValues.clear();
if (!op->fold(resultValues)) {
// If the result was an in-place simplification (e.g. max(x,x,y) ->
// max(x,y)) then add the original operands to the worklist so we can make
// sure to revisit them.
if (resultValues.empty()) {
// TODO: Walk the original operand list dropping them as we go. If any
// of them drop to zero uses, then add them to the worklist to allow
// them to be deleted as dead.
} else {
// Otherwise, the operation is simplified away completely.
assert(resultValues.size() == op->getNumResults());
// Add all the users of the operation to the worklist so we make sure to
// revisit them.
//
// TODO: Add a result->getUsers() iterator.
for (unsigned i = 0, e = resultValues.size(); i != e; ++i) {
auto *res = op->getResult(i);
if (res->use_empty()) // ignore dead uses.
continue;
for (auto &operand : op->getResult(i)->getUses())
addToWorklist(operand.getOwner());
res->replaceAllUsesWith(resultValues[i]);
}
op->erase();
}
continue;
}
// Check to see if we have any patterns that match this node.
auto match = matcher.findMatch(op);
if (!match.first)
continue;
// Make sure that any new operations are inserted at this point.
builder.setInsertionPoint(op);
// We know that any pattern that matched is RewritePattern because we
// initialized the matcher with RewritePatterns.
auto *rewritePattern = static_cast<RewritePattern *>(match.first);
rewritePattern->rewrite(op, std::move(match.second), *this);
}
uniquedConstants.clear();
}
/// Rewrite the specified function by repeatedly applying the highest benefit
/// patterns in a greedy work-list driven manner.
///
void mlir::applyPatternsGreedily(Function *fn,
OwningRewritePatternList &&patterns) {
GreedyPatternRewriteDriver driver(fn, std::move(patterns));
driver.simplifyFunction();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sdattr.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2001-10-22 13:36:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "sdattr.hxx"
using namespace ::com::sun::star;
/*************************************************************************
|*
|* DiaEffectItem
|*
*************************************************************************/
TYPEINIT1( DiaEffectItem, SfxEnumItem );
DiaEffectItem::DiaEffectItem( presentation::FadeEffect eFE ) :
SfxEnumItem( ATTR_DIA_EFFECT, eFE )
{
}
DiaEffectItem::DiaEffectItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_EFFECT, rIn )
{
}
SfxPoolItem* DiaEffectItem::Clone( SfxItemPool* pPool ) const
{
return new DiaEffectItem( *this );
}
SfxPoolItem* DiaEffectItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaEffectItem( rIn );
}
/*************************************************************************
|*
|* DiaSpeedItem
|*
*************************************************************************/
TYPEINIT1( DiaSpeedItem, SfxEnumItem );
DiaSpeedItem::DiaSpeedItem( FadeSpeed eFS ) :
SfxEnumItem( ATTR_DIA_SPEED, eFS )
{
}
DiaSpeedItem::DiaSpeedItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_SPEED, rIn )
{
}
SfxPoolItem* DiaSpeedItem::Clone( SfxItemPool* pPool ) const
{
return new DiaSpeedItem( *this );
}
SfxPoolItem* DiaSpeedItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaSpeedItem( rIn );
}
/*************************************************************************
|*
|* DiaAutoItem
|*
*************************************************************************/
TYPEINIT1( DiaAutoItem, SfxEnumItem );
DiaAutoItem::DiaAutoItem( PresChange eChange ) :
SfxEnumItem( ATTR_DIA_AUTO, eChange )
{
}
DiaAutoItem::DiaAutoItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_AUTO, rIn )
{
}
SfxPoolItem* DiaAutoItem::Clone( SfxItemPool* pPool ) const
{
return new DiaAutoItem( *this );
}
SfxPoolItem* DiaAutoItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaAutoItem( rIn );
}
/*************************************************************************
|*
|* DiaTimeItem
|*
*************************************************************************/
TYPEINIT1( DiaTimeItem, SfxUInt32Item );
DiaTimeItem::DiaTimeItem( UINT32 nValue ) :
SfxUInt32Item( ATTR_DIA_TIME, nValue )
{
}
SfxPoolItem* DiaTimeItem::Clone( SfxItemPool* pPool ) const
{
return new DiaTimeItem( *this );
}
int DiaTimeItem::operator==( const SfxPoolItem& rItem ) const
{
return( ( (DiaTimeItem&) rItem ).GetValue() == GetValue() );
}
<commit_msg>INTEGRATION: CWS docking1 (1.2.390); FILE MERGED 2004/05/04 16:42:46 cd 1.2.390.1: #i26252# Adapt toolbox controller to new implementation<commit_after>/*************************************************************************
*
* $RCSfile: sdattr.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-07-06 12:24:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "sdattr.hxx"
using namespace ::com::sun::star;
/*************************************************************************
|*
|* DiaEffectItem
|*
*************************************************************************/
TYPEINIT1_AUTOFACTORY( DiaEffectItem, SfxEnumItem );
DiaEffectItem::DiaEffectItem( presentation::FadeEffect eFE ) :
SfxEnumItem( ATTR_DIA_EFFECT, eFE )
{
}
DiaEffectItem::DiaEffectItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_EFFECT, rIn )
{
}
SfxPoolItem* DiaEffectItem::Clone( SfxItemPool* pPool ) const
{
return new DiaEffectItem( *this );
}
SfxPoolItem* DiaEffectItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaEffectItem( rIn );
}
/*************************************************************************
|*
|* DiaSpeedItem
|*
*************************************************************************/
TYPEINIT1_AUTOFACTORY( DiaSpeedItem, SfxEnumItem );
DiaSpeedItem::DiaSpeedItem( FadeSpeed eFS ) :
SfxEnumItem( ATTR_DIA_SPEED, eFS )
{
}
DiaSpeedItem::DiaSpeedItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_SPEED, rIn )
{
}
SfxPoolItem* DiaSpeedItem::Clone( SfxItemPool* pPool ) const
{
return new DiaSpeedItem( *this );
}
SfxPoolItem* DiaSpeedItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaSpeedItem( rIn );
}
/*************************************************************************
|*
|* DiaAutoItem
|*
*************************************************************************/
TYPEINIT1_AUTOFACTORY( DiaAutoItem, SfxEnumItem );
DiaAutoItem::DiaAutoItem( PresChange eChange ) :
SfxEnumItem( ATTR_DIA_AUTO, eChange )
{
}
DiaAutoItem::DiaAutoItem( SvStream& rIn ) :
SfxEnumItem( ATTR_DIA_AUTO, rIn )
{
}
SfxPoolItem* DiaAutoItem::Clone( SfxItemPool* pPool ) const
{
return new DiaAutoItem( *this );
}
SfxPoolItem* DiaAutoItem::Create( SvStream& rIn, USHORT nVer ) const
{
return new DiaAutoItem( rIn );
}
/*************************************************************************
|*
|* DiaTimeItem
|*
*************************************************************************/
TYPEINIT1_AUTOFACTORY( DiaTimeItem, SfxUInt32Item );
DiaTimeItem::DiaTimeItem( UINT32 nValue ) :
SfxUInt32Item( ATTR_DIA_TIME, nValue )
{
}
SfxPoolItem* DiaTimeItem::Clone( SfxItemPool* pPool ) const
{
return new DiaTimeItem( *this );
}
int DiaTimeItem::operator==( const SfxPoolItem& rItem ) const
{
return( ( (DiaTimeItem&) rItem ).GetValue() == GetValue() );
}
<|endoftext|>
|
<commit_before>//===--- Trace.cpp - Performance tracing facilities -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Trace.h"
#include "Context.h"
#include "Function.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/FormatProviders.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Threading.h"
#include <atomic>
#include <mutex>
namespace clang {
namespace clangd {
namespace trace {
using namespace llvm;
namespace {
// The current implementation is naive: each thread writes to Out guarded by Mu.
// Perhaps we should replace this by something that disturbs performance less.
class JSONTracer : public EventTracer {
public:
JSONTracer(raw_ostream &Out, bool Pretty)
: Out(Out), Sep(""), Start(std::chrono::system_clock::now()),
JSONFormat(Pretty ? "{0:2}" : "{0}") {
// The displayTimeUnit must be ns to avoid low-precision overlap
// calculations!
Out << R"({"displayTimeUnit":"ns","traceEvents":[)"
<< "\n";
rawEvent("M", json::obj{
{"name", "process_name"},
{"args", json::obj{{"name", "clangd"}}},
});
}
~JSONTracer() {
Out << "\n]}";
Out.flush();
}
// We stash a Span object in the context. It will record the start/end,
// and this also allows us to look up the parent Span's information.
Context beginSpan(llvm::StringRef Name, json::obj *Args) override {
return Context::current().derive(SpanKey,
make_unique<JSONSpan>(this, Name, Args));
}
// Trace viewer requires each thread to properly stack events.
// So we need to mark only duration that the span was active on the thread.
// (Hopefully any off-thread activity will be connected by a flow event).
// Record the end time here, but don't write the event: Args aren't ready yet.
void endSpan() override {
Context::current().getExisting(SpanKey)->markEnded();
}
void instant(llvm::StringRef Name, json::obj &&Args) override {
captureThreadMetadata();
jsonEvent("i", json::obj{{"name", Name}, {"args", std::move(Args)}});
}
// Record an event on the current thread. ph, pid, tid, ts are set.
// Contents must be a list of the other JSON key/values.
void jsonEvent(StringRef Phase, json::obj &&Contents,
uint64_t TID = get_threadid(),
double Timestamp = 0) {
Contents["ts"] = Timestamp ? Timestamp : timestamp();
Contents["tid"] = TID;
std::lock_guard<std::mutex> Lock(Mu);
rawEvent(Phase, std::move(Contents));
}
private:
class JSONSpan {
public:
JSONSpan(JSONTracer *Tracer, llvm::StringRef Name, json::obj *Args)
: StartTime(Tracer->timestamp()), EndTime(0), Name(Name),
TID(get_threadid()), Tracer(Tracer), Args(Args) {
// ~JSONSpan() may run in a different thread, so we need to capture now.
Tracer->captureThreadMetadata();
// We don't record begin events here (and end events in the destructor)
// because B/E pairs have to appear in the right order, which is awkward.
// Instead we send the complete (X) event in the destructor.
// If our parent was on a different thread, add an arrow to this span.
auto *Parent = Context::current().get(SpanKey);
if (Parent && *Parent && (*Parent)->TID != TID) {
// If the parent span ended already, then show this as "following" it.
// Otherwise show us as "parallel".
double OriginTime = (*Parent)->EndTime;
if (!OriginTime)
OriginTime = (*Parent)->StartTime;
auto FlowID = nextID();
Tracer->jsonEvent("s",
json::obj{{"id", FlowID},
{"name", "Context crosses threads"},
{"cat", "dummy"}},
(*Parent)->TID, (*Parent)->StartTime);
Tracer->jsonEvent("f",
json::obj{{"id", FlowID},
{"bp", "e"},
{"name", "Context crosses threads"},
{"cat", "dummy"}},
TID);
}
}
~JSONSpan() {
// Finally, record the event (ending at EndTime, not timestamp())!
Tracer->jsonEvent("X",
json::obj{{"name", std::move(Name)},
{"args", std::move(*Args)},
{"dur", EndTime - StartTime}},
TID, StartTime);
}
// May be called by any thread.
void markEnded() {
EndTime = Tracer->timestamp();
}
private:
static uint64_t nextID() {
static std::atomic<uint64_t> Next = {0};
return Next++;
}
double StartTime;
std::atomic<double> EndTime; // Filled in by markEnded().
std::string Name;
uint64_t TID;
JSONTracer *Tracer;
json::obj *Args;
};
static Key<std::unique_ptr<JSONSpan>> SpanKey;
// Record an event. ph and pid are set.
// Contents must be a list of the other JSON key/values.
void rawEvent(StringRef Phase, json::obj &&Event) /*REQUIRES(Mu)*/ {
// PID 0 represents the clangd process.
Event["pid"] = 0;
Event["ph"] = Phase;
Out << Sep << formatv(JSONFormat, json::Expr(std::move(Event)));
Sep = ",\n";
}
// If we haven't already, emit metadata describing this thread.
void captureThreadMetadata() {
uint64_t TID = get_threadid();
std::lock_guard<std::mutex> Lock(Mu);
if (ThreadsWithMD.insert(TID).second) {
SmallString<32> Name;
get_thread_name(Name);
if (!Name.empty()) {
rawEvent("M", json::obj{
{"tid", TID},
{"name", "thread_name"},
{"args", json::obj{{"name", Name}}},
});
}
}
}
double timestamp() {
using namespace std::chrono;
return duration<double, std::micro>(system_clock::now() - Start).count();
}
std::mutex Mu;
raw_ostream &Out /*GUARDED_BY(Mu)*/;
const char *Sep /*GUARDED_BY(Mu)*/;
DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
const sys::TimePoint<> Start;
const char *JSONFormat;
};
Key<std::unique_ptr<JSONTracer::JSONSpan>> JSONTracer::SpanKey;
EventTracer *T = nullptr;
} // namespace
Session::Session(EventTracer &Tracer) {
assert(!T && "Resetting global tracer is not allowed.");
T = &Tracer;
}
Session::~Session() { T = nullptr; }
std::unique_ptr<EventTracer> createJSONTracer(llvm::raw_ostream &OS,
bool Pretty) {
return llvm::make_unique<JSONTracer>(OS, Pretty);
}
void log(const Twine &Message) {
if (!T)
return;
T->instant("Log", json::obj{{"Message", Message.str()}});
}
// Returned context owns Args.
static Context makeSpanContext(llvm::StringRef Name, json::obj *Args) {
if (!T)
return Context::current().clone();
WithContextValue WithArgs{std::unique_ptr<json::obj>(Args)};
return T->beginSpan(Name, Args);
}
// Span keeps a non-owning pointer to the args, which is how users access them.
// The args are owned by the context though. They stick around until the
// beginSpan() context is destroyed, when the tracing engine will consume them.
Span::Span(llvm::StringRef Name)
: Args(T ? new json::obj() : nullptr),
RestoreCtx(makeSpanContext(Name, Args)) {}
Span::~Span() {
if (T)
T->endSpan();
}
} // namespace trace
} // namespace clangd
} // namespace clang
<commit_msg>[clangd] Fix make_unique ambiguity, NFC<commit_after>//===--- Trace.cpp - Performance tracing facilities -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Trace.h"
#include "Context.h"
#include "Function.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/FormatProviders.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Threading.h"
#include <atomic>
#include <mutex>
namespace clang {
namespace clangd {
namespace trace {
using namespace llvm;
namespace {
// The current implementation is naive: each thread writes to Out guarded by Mu.
// Perhaps we should replace this by something that disturbs performance less.
class JSONTracer : public EventTracer {
public:
JSONTracer(raw_ostream &Out, bool Pretty)
: Out(Out), Sep(""), Start(std::chrono::system_clock::now()),
JSONFormat(Pretty ? "{0:2}" : "{0}") {
// The displayTimeUnit must be ns to avoid low-precision overlap
// calculations!
Out << R"({"displayTimeUnit":"ns","traceEvents":[)"
<< "\n";
rawEvent("M", json::obj{
{"name", "process_name"},
{"args", json::obj{{"name", "clangd"}}},
});
}
~JSONTracer() {
Out << "\n]}";
Out.flush();
}
// We stash a Span object in the context. It will record the start/end,
// and this also allows us to look up the parent Span's information.
Context beginSpan(llvm::StringRef Name, json::obj *Args) override {
return Context::current().derive(
SpanKey, llvm::make_unique<JSONSpan>(this, Name, Args));
}
// Trace viewer requires each thread to properly stack events.
// So we need to mark only duration that the span was active on the thread.
// (Hopefully any off-thread activity will be connected by a flow event).
// Record the end time here, but don't write the event: Args aren't ready yet.
void endSpan() override {
Context::current().getExisting(SpanKey)->markEnded();
}
void instant(llvm::StringRef Name, json::obj &&Args) override {
captureThreadMetadata();
jsonEvent("i", json::obj{{"name", Name}, {"args", std::move(Args)}});
}
// Record an event on the current thread. ph, pid, tid, ts are set.
// Contents must be a list of the other JSON key/values.
void jsonEvent(StringRef Phase, json::obj &&Contents,
uint64_t TID = get_threadid(),
double Timestamp = 0) {
Contents["ts"] = Timestamp ? Timestamp : timestamp();
Contents["tid"] = TID;
std::lock_guard<std::mutex> Lock(Mu);
rawEvent(Phase, std::move(Contents));
}
private:
class JSONSpan {
public:
JSONSpan(JSONTracer *Tracer, llvm::StringRef Name, json::obj *Args)
: StartTime(Tracer->timestamp()), EndTime(0), Name(Name),
TID(get_threadid()), Tracer(Tracer), Args(Args) {
// ~JSONSpan() may run in a different thread, so we need to capture now.
Tracer->captureThreadMetadata();
// We don't record begin events here (and end events in the destructor)
// because B/E pairs have to appear in the right order, which is awkward.
// Instead we send the complete (X) event in the destructor.
// If our parent was on a different thread, add an arrow to this span.
auto *Parent = Context::current().get(SpanKey);
if (Parent && *Parent && (*Parent)->TID != TID) {
// If the parent span ended already, then show this as "following" it.
// Otherwise show us as "parallel".
double OriginTime = (*Parent)->EndTime;
if (!OriginTime)
OriginTime = (*Parent)->StartTime;
auto FlowID = nextID();
Tracer->jsonEvent("s",
json::obj{{"id", FlowID},
{"name", "Context crosses threads"},
{"cat", "dummy"}},
(*Parent)->TID, (*Parent)->StartTime);
Tracer->jsonEvent("f",
json::obj{{"id", FlowID},
{"bp", "e"},
{"name", "Context crosses threads"},
{"cat", "dummy"}},
TID);
}
}
~JSONSpan() {
// Finally, record the event (ending at EndTime, not timestamp())!
Tracer->jsonEvent("X",
json::obj{{"name", std::move(Name)},
{"args", std::move(*Args)},
{"dur", EndTime - StartTime}},
TID, StartTime);
}
// May be called by any thread.
void markEnded() {
EndTime = Tracer->timestamp();
}
private:
static uint64_t nextID() {
static std::atomic<uint64_t> Next = {0};
return Next++;
}
double StartTime;
std::atomic<double> EndTime; // Filled in by markEnded().
std::string Name;
uint64_t TID;
JSONTracer *Tracer;
json::obj *Args;
};
static Key<std::unique_ptr<JSONSpan>> SpanKey;
// Record an event. ph and pid are set.
// Contents must be a list of the other JSON key/values.
void rawEvent(StringRef Phase, json::obj &&Event) /*REQUIRES(Mu)*/ {
// PID 0 represents the clangd process.
Event["pid"] = 0;
Event["ph"] = Phase;
Out << Sep << formatv(JSONFormat, json::Expr(std::move(Event)));
Sep = ",\n";
}
// If we haven't already, emit metadata describing this thread.
void captureThreadMetadata() {
uint64_t TID = get_threadid();
std::lock_guard<std::mutex> Lock(Mu);
if (ThreadsWithMD.insert(TID).second) {
SmallString<32> Name;
get_thread_name(Name);
if (!Name.empty()) {
rawEvent("M", json::obj{
{"tid", TID},
{"name", "thread_name"},
{"args", json::obj{{"name", Name}}},
});
}
}
}
double timestamp() {
using namespace std::chrono;
return duration<double, std::micro>(system_clock::now() - Start).count();
}
std::mutex Mu;
raw_ostream &Out /*GUARDED_BY(Mu)*/;
const char *Sep /*GUARDED_BY(Mu)*/;
DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
const sys::TimePoint<> Start;
const char *JSONFormat;
};
Key<std::unique_ptr<JSONTracer::JSONSpan>> JSONTracer::SpanKey;
EventTracer *T = nullptr;
} // namespace
Session::Session(EventTracer &Tracer) {
assert(!T && "Resetting global tracer is not allowed.");
T = &Tracer;
}
Session::~Session() { T = nullptr; }
std::unique_ptr<EventTracer> createJSONTracer(llvm::raw_ostream &OS,
bool Pretty) {
return llvm::make_unique<JSONTracer>(OS, Pretty);
}
void log(const Twine &Message) {
if (!T)
return;
T->instant("Log", json::obj{{"Message", Message.str()}});
}
// Returned context owns Args.
static Context makeSpanContext(llvm::StringRef Name, json::obj *Args) {
if (!T)
return Context::current().clone();
WithContextValue WithArgs{std::unique_ptr<json::obj>(Args)};
return T->beginSpan(Name, Args);
}
// Span keeps a non-owning pointer to the args, which is how users access them.
// The args are owned by the context though. They stick around until the
// beginSpan() context is destroyed, when the tracing engine will consume them.
Span::Span(llvm::StringRef Name)
: Args(T ? new json::obj() : nullptr),
RestoreCtx(makeSpanContext(Name, Args)) {}
Span::~Span() {
if (T)
T->endSpan();
}
} // namespace trace
} // namespace clangd
} // namespace clang
<|endoftext|>
|
<commit_before>#include <pxp-agent/agent.hpp>
#include <pxp-agent/configuration.hpp>
#include <pxp-agent/util/daemonize.hpp>
#include <cpp-pcp-client/util/thread.hpp>
#include <cpp-pcp-client/util/chrono.hpp>
#include <leatherman/file_util/file.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.main"
#include <leatherman/logging/logging.hpp>
#include <horsewhisperer/horsewhisperer.h>
#include <boost/nowide/args.hpp>
#include <boost/nowide/iostream.hpp>
#include <memory>
namespace PXPAgent {
namespace HW = HorseWhisperer;
namespace lth_file = leatherman::file_util;
// Start a thread that just busy waits to facilitate acceptance testing
void loopIdly() {
PCPClient::Util::thread idle_thread {
[]() {
for (;;) {
PCPClient::Util::this_thread::sleep_for(
PCPClient::Util::chrono::milliseconds(5000));
}
} };
idle_thread.join();
}
int startAgent(std::vector<std::string> arguments) {
#ifndef _WIN32
std::unique_ptr<Util::PIDFile> pidf_ptr;
#endif
try {
// Using HW because configuration may not be initialized at this point
if (!HW::GetFlag<bool>("foreground")) {
#ifdef _WIN32
Util::daemonize();
#else
// Store it for RAII
// NB: pidf_ptr will be nullptr if already a daemon
pidf_ptr = Util::daemonize();
#endif
}
} catch (const std::exception& e) {
LOG_ERROR("Failed to daemonize: %1%", e.what());
return EXIT_FAILURE;
} catch (...) {
LOG_ERROR("Failed to daemonize");
return EXIT_FAILURE;
}
int exit_code { EXIT_SUCCESS };
if (!Configuration::Instance().valid()) {
// pxp-agent will execute in uncofigured mode
loopIdly();
} else {
try {
Agent agent { Configuration::Instance().getAgentConfiguration() };
agent.start();
} catch (const Agent::WebSocketConfigurationError& e) {
LOG_ERROR("WebSocket configuration error (%1%) - pxp-agent will "
"continue executing, but will not attempt to connect to "
"the PCP broker again", e.what());
loopIdly();
} catch (const Agent::FatalError& e) {
exit_code = EXIT_FAILURE;
LOG_ERROR("Fatal error: %1%", e.what());
} catch (const std::exception& e) {
exit_code = EXIT_FAILURE;
LOG_ERROR("Unexpected error: %1%", e.what());
} catch (...) {
exit_code = EXIT_FAILURE;
LOG_ERROR("Unexpected error");
}
}
#ifdef _WIN32
Util::daemon_cleanup();
#endif
return exit_code;
}
int main(int argc, char *argv[]) {
// Initialize
// Fix args on Windows to be UTF-8
boost::nowide::args arg_utf8(argc, argv);
Configuration::Instance().initialize(startAgent);
// Parse options
HW::ParseResult parse_result { HW::ParseResult::OK };
std::string err_msg {};
try {
parse_result = Configuration::Instance().parseOptions(argc, argv);
} catch (const HW::horsewhisperer_error& e) {
// Failed to validate action argument or flag
err_msg = e.what();
} catch(const Configuration::Error& e) {
// Failed to parse the config file
err_msg = e.what();
}
if (!err_msg.empty()) {
boost::nowide::cout << err_msg
<< "\nCannot start pxp-agent"
<< std::endl;
return EXIT_FAILURE;
}
switch (parse_result) {
case HW::ParseResult::OK:
break;
case HW::ParseResult::HELP:
// Show only the global section of HorseWhisperer's help
HW::ShowHelp(false);
return EXIT_SUCCESS;
case HW::ParseResult::VERSION:
HW::ShowVersion();
return EXIT_SUCCESS;
default:
boost::nowide::cout << "An unexpected code was returned when trying "
<< "to parse command line arguments - "
<< static_cast<int>(parse_result)
<< "\nCannot start pxp-agent"
<< std::endl;
return EXIT_FAILURE;
}
// Set up logging
try {
Configuration::Instance().setupLogging();
LOG_INFO("pxp-agent logging has been initialized");
} catch(const Configuration::Error& e) {
boost::nowide::cout << "Failed to configure logging: " << e.what()
<< "\nCannot start pxp-agent"
<< std::endl;
return EXIT_FAILURE;
}
// Validate options
try {
Configuration::Instance().validate();
LOG_INFO("pxp-agent configuration has been validated");
} catch(const Configuration::UnconfiguredError& e) {
LOG_ERROR("WebSocket configuration error (%1%); pxp-agent will start "
"unconfigured and no connection will be attempted", e.what());
} catch(const Configuration::Error& e) {
LOG_ERROR("Fatal configuration error: %1%; cannot start pxp-agent",
e.what());
return EXIT_FAILURE;
}
return HW::Start();
}
} // namespace PXPAgent
int main(int argc, char** argv) {
return PXPAgent::main(argc, argv);
}
<commit_msg>(PCP-134) Log to default logfile and return 2 in case of parse error<commit_after>#include <pxp-agent/agent.hpp>
#include <pxp-agent/configuration.hpp>
#include <pxp-agent/util/daemonize.hpp>
#include <cpp-pcp-client/util/thread.hpp>
#include <cpp-pcp-client/util/chrono.hpp>
#include <leatherman/file_util/file.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.main"
#include <leatherman/logging/logging.hpp>
#include <horsewhisperer/horsewhisperer.h>
#include <boost/nowide/args.hpp>
#include <boost/nowide/iostream.hpp>
#include <memory>
namespace PXPAgent {
namespace HW = HorseWhisperer;
namespace lth_file = leatherman::file_util;
// Exit code returned after a successful execution
static int PXP_AGENT_SUCCESS = 0;
// Exit code returned after a general failure
static int PXP_AGENT_GENERAL_FAILURE = 1;
// Exit code returned after a parsing failure
static int PXP_AGENT_PARSING_FAILURE = 2;
// Start a thread that just busy waits to facilitate acceptance testing
void loopIdly() {
PCPClient::Util::thread idle_thread {
[]() {
for (;;) {
PCPClient::Util::this_thread::sleep_for(
PCPClient::Util::chrono::milliseconds(5000));
}
} };
idle_thread.join();
}
int startAgent(std::vector<std::string> arguments) {
#ifndef _WIN32
std::unique_ptr<Util::PIDFile> pidf_ptr;
#endif
try {
// Using HW because configuration may not be initialized at this point
if (!HW::GetFlag<bool>("foreground")) {
#ifdef _WIN32
Util::daemonize();
#else
// Store it for RAII
// NB: pidf_ptr will be nullptr if already a daemon
pidf_ptr = Util::daemonize();
#endif
}
} catch (const std::exception& e) {
LOG_ERROR("Failed to daemonize: %1%", e.what());
return PXP_AGENT_GENERAL_FAILURE;
} catch (...) {
LOG_ERROR("Failed to daemonize");
return PXP_AGENT_GENERAL_FAILURE;
}
int exit_code { PXP_AGENT_SUCCESS };
if (!Configuration::Instance().valid()) {
// pxp-agent will execute in uncofigured mode
loopIdly();
} else {
try {
Agent agent { Configuration::Instance().getAgentConfiguration() };
agent.start();
} catch (const Agent::WebSocketConfigurationError& e) {
LOG_ERROR("WebSocket configuration error (%1%) - pxp-agent will "
"continue executing, but will not attempt to connect to "
"the PCP broker again", e.what());
loopIdly();
} catch (const Agent::FatalError& e) {
exit_code = PXP_AGENT_GENERAL_FAILURE;
LOG_ERROR("Fatal error: %1%", e.what());
} catch (const std::exception& e) {
exit_code = PXP_AGENT_GENERAL_FAILURE;
LOG_ERROR("Unexpected error: %1%", e.what());
} catch (...) {
exit_code = PXP_AGENT_GENERAL_FAILURE;
LOG_ERROR("Unexpected error");
}
}
#ifdef _WIN32
Util::daemon_cleanup();
#endif
return exit_code;
}
int main(int argc, char *argv[]) {
// Initialize
// Fix args on Windows to be UTF-8
boost::nowide::args arg_utf8(argc, argv);
Configuration::Instance().initialize(startAgent);
// Parse options
HW::ParseResult parse_result { HW::ParseResult::OK };
std::string err_msg {};
try {
parse_result = Configuration::Instance().parseOptions(argc, argv);
} catch (const HW::horsewhisperer_error& e) {
// Failed to validate action argument or flag
err_msg = e.what();
} catch(const Configuration::Error& e) {
// Failed to parse the config file
err_msg = e.what();
}
if (!err_msg.empty()) {
// Try to set up logging with default settings
try {
Configuration::Instance().setupLogging();
LOG_ERROR(err_msg);
} catch(Configuration::Error) {
// pass
}
boost::nowide::cout << err_msg
<< "\nCannot start pxp-agent"
<< std::endl;
return PXP_AGENT_PARSING_FAILURE;
}
switch (parse_result) {
case HW::ParseResult::OK:
break;
case HW::ParseResult::HELP:
// Show only the global section of HorseWhisperer's help
HW::ShowHelp(false);
return PXP_AGENT_SUCCESS;
case HW::ParseResult::VERSION:
HW::ShowVersion();
return PXP_AGENT_SUCCESS;
default:
boost::nowide::cout << "An unexpected code was returned when trying "
<< "to parse command line arguments - "
<< static_cast<int>(parse_result)
<< "\nCannot start pxp-agent"
<< std::endl;
return PXP_AGENT_GENERAL_FAILURE;
}
// Set up logging
try {
Configuration::Instance().setupLogging();
LOG_INFO("pxp-agent logging has been initialized");
} catch(const Configuration::Error& e) {
boost::nowide::cout << "Failed to configure logging: " << e.what()
<< "\nCannot start pxp-agent"
<< std::endl;
return PXP_AGENT_GENERAL_FAILURE;
}
// Validate options
try {
Configuration::Instance().validate();
LOG_INFO("pxp-agent configuration has been validated");
} catch(const Configuration::UnconfiguredError& e) {
LOG_ERROR("WebSocket configuration error (%1%); pxp-agent will start "
"unconfigured and no connection will be attempted", e.what());
} catch(const Configuration::Error& e) {
LOG_ERROR("Fatal configuration error: %1%; cannot start pxp-agent",
e.what());
return PXP_AGENT_GENERAL_FAILURE;
}
return HW::Start();
}
} // namespace PXPAgent
int main(int argc, char** argv) {
return PXPAgent::main(argc, argv);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "vie_frame_provider_base.h"
#include "critical_section_wrapper.h"
#include "tick_util.h"
#include "trace.h"
#include "vie_defines.h"
namespace webrtc {
ViEFrameProviderBase::ViEFrameProviderBase(int Id, int engineId):
_id(Id),
_engineId(engineId),
_frameCallbackMap(),
_providerCritSect(*CriticalSectionWrapper::CreateCriticalSection()),
_ptrExtraFrame(NULL),
_frameDelay(0)
{
}
ViEFrameProviderBase::~ViEFrameProviderBase()
{
if(_frameCallbackMap.Size()>0)
{
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId,_id), "FramCallbacks still exist when Provider deleted %d",_frameCallbackMap.Size());
}
for(MapItem* item=_frameCallbackMap.First();item!=NULL;item=_frameCallbackMap.Next(item))
{
static_cast<ViEFrameCallback*>(item->GetItem())->ProviderDestroyed(_id);
}
while(_frameCallbackMap.Erase(_frameCallbackMap.First()) == 0)
;
delete &_providerCritSect;
delete _ptrExtraFrame;
}
int ViEFrameProviderBase::Id()
{
return _id;
}
void ViEFrameProviderBase::DeliverFrame(webrtc::VideoFrame& videoFrame,int numCSRCs,
const WebRtc_UWord32 CSRC[kRtpCsrcSize])
{
#ifdef _DEBUG
const TickTime startProcessTime=TickTime::Now();
#endif
CriticalSectionScoped cs(_providerCritSect);
// Deliver the frame to all registered callbacks
if (_frameCallbackMap.Size() > 0)
{
if(_frameCallbackMap.Size()==1)
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(_frameCallbackMap.First()->GetItem());
frameObserver->DeliverFrame(_id,videoFrame,numCSRCs,CSRC);
}
else
{
// Make a copy of the frame for all callbacks
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
if (_ptrExtraFrame == NULL)
{
_ptrExtraFrame = new webrtc::VideoFrame();
}
if (mapItem != NULL)
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(mapItem->GetItem());
if (frameObserver != NULL)
{
// We must copy the frame each time since the previous receiver might swap it...
_ptrExtraFrame->CopyFrame(videoFrame);
frameObserver->DeliverFrame(_id, *_ptrExtraFrame,numCSRCs,CSRC);
}
}
}
}
}
#ifdef _DEBUG
const int processTime=(int) (TickTime::Now()-startProcessTime).Milliseconds();
if(processTime>25) // Warn If the delivery time is too long.
{
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId,_id), "%s Too long time: %ums",__FUNCTION__,processTime);
}
#endif
}
void ViEFrameProviderBase::SetFrameDelay(int frameDelay)
{
CriticalSectionScoped cs(_providerCritSect);
_frameDelay=frameDelay;
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(mapItem->GetItem());
assert(frameObserver);
frameObserver->DelayChanged(_id,frameDelay);
}
}
int ViEFrameProviderBase::FrameDelay()
{
return _frameDelay;
}
int ViEFrameProviderBase::GetBestFormat(int& bestWidth,
int& bestHeight,
int& bestFrameRate)
{
int largestWidth = 0;
int largestHeight = 0;
int highestFrameRate = 0;
CriticalSectionScoped cs(_providerCritSect);
// Check if this one already exists...
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
int preferedWidth=0;
int preferedHeight=0;
int preferedFrameRate=0;
ViEFrameCallback* callbackObject = static_cast<ViEFrameCallback*>(mapItem->GetItem());
assert(callbackObject);
if(callbackObject->GetPreferedFrameSettings(preferedWidth,preferedHeight,preferedFrameRate)==0)
{
if (preferedWidth > largestWidth)
{
largestWidth = preferedWidth;
}
if (preferedHeight > largestHeight)
{
largestHeight = preferedHeight;
}
if (preferedFrameRate > highestFrameRate)
{
highestFrameRate = preferedFrameRate;
}
}
}
bestWidth = largestWidth;
bestHeight = largestHeight;
bestFrameRate = highestFrameRate;
return 0;
}
int ViEFrameProviderBase::RegisterFrameCallback(int observerId,ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", callbackObject);
{
CriticalSectionScoped cs(_providerCritSect);
// Check if this one already exists...
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
const ViEFrameCallback* observer=static_cast<ViEFrameCallback*> (mapItem->GetItem());
if (observer == callbackObject)
{
// This callback is already registered
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p already registered", __FUNCTION__, callbackObject);
assert("!frameObserver already registered");
return -1;
}
}
if (_frameCallbackMap.Insert(observerId,callbackObject) != 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: Could not add 0x%p to list", __FUNCTION__, callbackObject);
return -1;
}
}
// Report current capture delay
callbackObject->DelayChanged(_id,_frameDelay);
FrameCallbackChanged(); // Notify implementer of this class that the callback list have changed
return 0;
}
// ----------------------------------------------------------------------------
// DeregisterFrameCallback
// ----------------------------------------------------------------------------
int ViEFrameProviderBase::DeregisterFrameCallback(const ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", callbackObject);
{
CriticalSectionScoped cs(_providerCritSect);
bool itemFound=false;
// Try to find the callback in our list
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
const ViEFrameCallback* observer=static_cast<ViEFrameCallback*> (mapItem->GetItem());
if (observer == callbackObject)
{
// We found it, remove it!
_frameCallbackMap.Erase(mapItem);
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p deregistered", __FUNCTION__, callbackObject);
itemFound=true;
break;
}
}
if(!itemFound)
{
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p not found", __FUNCTION__, callbackObject);
return -1;
}
}
FrameCallbackChanged(); // Notify implementer of this class that the callback list have changed
return 0;
}
// ----------------------------------------------------------------------------
// IsFrameCallbackRegistered
// ----------------------------------------------------------------------------
bool ViEFrameProviderBase::IsFrameCallbackRegistered(const ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return false;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", callbackObject);
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
if (callbackObject == mapItem->GetItem())
{
// We found the callback
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p is registered", __FUNCTION__, callbackObject);
return true;
}
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p not registered", __FUNCTION__, callbackObject);
return false;
}
// ----------------------------------------------------------------------------
// NumberOfRegistersFrameCallbacks
// ----------------------------------------------------------------------------
int ViEFrameProviderBase::NumberOfRegistersFrameCallbacks()
{
CriticalSectionScoped cs(_providerCritSect);
return _frameCallbackMap.Size();
}
} // namespac webrtc
<commit_msg>Incorrect parameters being passed to trace function.<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "vie_frame_provider_base.h"
#include "critical_section_wrapper.h"
#include "tick_util.h"
#include "trace.h"
#include "vie_defines.h"
namespace webrtc {
ViEFrameProviderBase::ViEFrameProviderBase(int Id, int engineId):
_id(Id),
_engineId(engineId),
_frameCallbackMap(),
_providerCritSect(*CriticalSectionWrapper::CreateCriticalSection()),
_ptrExtraFrame(NULL),
_frameDelay(0)
{
}
ViEFrameProviderBase::~ViEFrameProviderBase()
{
if(_frameCallbackMap.Size()>0)
{
WEBRTC_TRACE(webrtc::kTraceWarning,
webrtc::kTraceVideo,
ViEId(_engineId,_id),
"FrameCallbacks still exist when Provider deleted %d",
_frameCallbackMap.Size());
}
for(MapItem* item=_frameCallbackMap.First();item!=NULL;item=_frameCallbackMap.Next(item))
{
static_cast<ViEFrameCallback*>(item->GetItem())->ProviderDestroyed(_id);
}
while(_frameCallbackMap.Erase(_frameCallbackMap.First()) == 0)
;
delete &_providerCritSect;
delete _ptrExtraFrame;
}
int ViEFrameProviderBase::Id()
{
return _id;
}
void ViEFrameProviderBase::DeliverFrame(webrtc::VideoFrame& videoFrame,int numCSRCs,
const WebRtc_UWord32 CSRC[kRtpCsrcSize])
{
#ifdef _DEBUG
const TickTime startProcessTime=TickTime::Now();
#endif
CriticalSectionScoped cs(_providerCritSect);
// Deliver the frame to all registered callbacks
if (_frameCallbackMap.Size() > 0)
{
if(_frameCallbackMap.Size()==1)
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(_frameCallbackMap.First()->GetItem());
frameObserver->DeliverFrame(_id,videoFrame,numCSRCs,CSRC);
}
else
{
// Make a copy of the frame for all callbacks
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
if (_ptrExtraFrame == NULL)
{
_ptrExtraFrame = new webrtc::VideoFrame();
}
if (mapItem != NULL)
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(mapItem->GetItem());
if (frameObserver != NULL)
{
// We must copy the frame each time since the previous receiver might swap it...
_ptrExtraFrame->CopyFrame(videoFrame);
frameObserver->DeliverFrame(_id, *_ptrExtraFrame,numCSRCs,CSRC);
}
}
}
}
}
#ifdef _DEBUG
const int processTime=(int) (TickTime::Now()-startProcessTime).Milliseconds();
if(processTime>25) // Warn If the delivery time is too long.
{
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId,_id), "%s Too long time: %ums",__FUNCTION__,processTime);
}
#endif
}
void ViEFrameProviderBase::SetFrameDelay(int frameDelay)
{
CriticalSectionScoped cs(_providerCritSect);
_frameDelay=frameDelay;
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
ViEFrameCallback* frameObserver = static_cast<ViEFrameCallback*>(mapItem->GetItem());
assert(frameObserver);
frameObserver->DelayChanged(_id,frameDelay);
}
}
int ViEFrameProviderBase::FrameDelay()
{
return _frameDelay;
}
int ViEFrameProviderBase::GetBestFormat(int& bestWidth,
int& bestHeight,
int& bestFrameRate)
{
int largestWidth = 0;
int largestHeight = 0;
int highestFrameRate = 0;
CriticalSectionScoped cs(_providerCritSect);
// Check if this one already exists...
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
int preferedWidth=0;
int preferedHeight=0;
int preferedFrameRate=0;
ViEFrameCallback* callbackObject = static_cast<ViEFrameCallback*>(mapItem->GetItem());
assert(callbackObject);
if(callbackObject->GetPreferedFrameSettings(preferedWidth,preferedHeight,preferedFrameRate)==0)
{
if (preferedWidth > largestWidth)
{
largestWidth = preferedWidth;
}
if (preferedHeight > largestHeight)
{
largestHeight = preferedHeight;
}
if (preferedFrameRate > highestFrameRate)
{
highestFrameRate = preferedFrameRate;
}
}
}
bestWidth = largestWidth;
bestHeight = largestHeight;
bestFrameRate = highestFrameRate;
return 0;
}
int ViEFrameProviderBase::RegisterFrameCallback(int observerId,ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", __FUNCTION__, callbackObject);
{
CriticalSectionScoped cs(_providerCritSect);
// Check if this one already exists...
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
const ViEFrameCallback* observer=static_cast<ViEFrameCallback*> (mapItem->GetItem());
if (observer == callbackObject)
{
// This callback is already registered
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p already registered", __FUNCTION__, callbackObject);
assert("!frameObserver already registered");
return -1;
}
}
if (_frameCallbackMap.Insert(observerId,callbackObject) != 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: Could not add 0x%p to list", __FUNCTION__, callbackObject);
return -1;
}
}
// Report current capture delay
callbackObject->DelayChanged(_id,_frameDelay);
FrameCallbackChanged(); // Notify implementer of this class that the callback list have changed
return 0;
}
// ----------------------------------------------------------------------------
// DeregisterFrameCallback
// ----------------------------------------------------------------------------
int ViEFrameProviderBase::DeregisterFrameCallback(const ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", __FUNCTION__, callbackObject);
{
CriticalSectionScoped cs(_providerCritSect);
bool itemFound=false;
// Try to find the callback in our list
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
const ViEFrameCallback* observer=static_cast<ViEFrameCallback*> (mapItem->GetItem());
if (observer == callbackObject)
{
// We found it, remove it!
_frameCallbackMap.Erase(mapItem);
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p deregistered", __FUNCTION__, callbackObject);
itemFound=true;
break;
}
}
if(!itemFound)
{
WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p not found", __FUNCTION__, callbackObject);
return -1;
}
}
FrameCallbackChanged(); // Notify implementer of this class that the callback list have changed
return 0;
}
// ----------------------------------------------------------------------------
// IsFrameCallbackRegistered
// ----------------------------------------------------------------------------
bool ViEFrameProviderBase::IsFrameCallbackRegistered(const ViEFrameCallback* callbackObject)
{
if (callbackObject == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s: No argument", __FUNCTION__);
return false;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s(0x%p)", __FUNCTION__, callbackObject);
for (MapItem* mapItem = _frameCallbackMap.First();
mapItem != NULL;
mapItem = _frameCallbackMap.Next(mapItem))
{
if (callbackObject == mapItem->GetItem())
{
// We found the callback
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p is registered", __FUNCTION__, callbackObject);
return true;
}
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId, _id),
"%s 0x%p not registered", __FUNCTION__, callbackObject);
return false;
}
// ----------------------------------------------------------------------------
// NumberOfRegistersFrameCallbacks
// ----------------------------------------------------------------------------
int ViEFrameProviderBase::NumberOfRegistersFrameCallbacks()
{
CriticalSectionScoped cs(_providerCritSect);
return _frameCallbackMap.Size();
}
} // namespac webrtc
<|endoftext|>
|
<commit_before>#pragma once
#include <functional>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <assert.h>
namespace autocxxpy
{
class dispatcher
{
public:
using task_type = std::function<void()>;
using task_list_type = std::vector<task_type>;
public:
inline void add(const task_type &f)
{
{
std::lock_guard<std::mutex> l(_m);
_ts.push_back(f);
}
this->_notify_one();
}
void start()
{
_run = true;
_thread = std::thread(&dispatcher::_loop, this);
}
void stop()
{
_run = false;
}
void join()
{
assert(!this->_run);
this->_notify_one();
_thread.join();
}
public:
inline static dispatcher &instance()
{
static dispatcher *_instance = nullptr;
if (_instance != nullptr)
return *_instance;
static std::mutex m;
std::lock_guard<std::mutex> l(m);
if (_instance == nullptr)
_instance = new dispatcher;
return *_instance;
}
protected:
void _loop()
{
while (_run)
{
task_list_type ts;
{
auto l = _wait_and_lock();
ts = this->_ts;
_ts.clear();
l.unlock();
}
_process_all(ts);
}
}
inline void _process_all(const task_list_type &ts)
{
for (const auto &task : ts)
{
task();
}
}
inline void _notify_one()
{
return _cv.notify_one();
}
inline std::unique_lock<std::mutex> _wait_and_lock()
{
std::unique_lock<std::mutex> l(_m);
_cv.wait(l, [this]()
{
return !_run || _ts.size();
});
return std::move(l);
}
protected:
volatile bool _run = false;
std::thread _thread;
std::mutex _m;
std::condition_variable _cv;
task_list_type _ts;
};
}
<commit_msg>Delete dispatcher.hpp<commit_after><|endoftext|>
|
<commit_before>/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/utils/event/EventHeader.h>
#include <aws/core/utils/event/EventMessage.h>
#include <aws/core/utils/event/EventStreamEncoder.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/common/byte_order.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <cassert>
namespace Aws
{
namespace Utils
{
namespace Event
{
static const char TAG[] = "EventStreamEncoder";
static void EncodeHeaders(const Aws::Utils::Event::Message& msg, aws_array_list* headers)
{
aws_array_list_init_dynamic(headers, get_aws_allocator(), msg.GetEventHeaders().size(), sizeof(aws_event_stream_header_value_pair));
for (auto&& header : msg.GetEventHeaders())
{
const uint8_t headerKeyLen = static_cast<uint8_t>(header.first.length());
switch(header.second.GetType())
{
case EventHeaderValue::EventHeaderType::BOOL_TRUE:
case EventHeaderValue::EventHeaderType::BOOL_FALSE:
aws_event_stream_add_bool_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsBoolean());
break;
case EventHeaderValue::EventHeaderType::BYTE:
aws_event_stream_add_bool_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsByte());
break;
case EventHeaderValue::EventHeaderType::INT16:
aws_event_stream_add_int16_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt16());
break;
case EventHeaderValue::EventHeaderType::INT32:
aws_event_stream_add_int32_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt32());
break;
case EventHeaderValue::EventHeaderType::INT64:
aws_event_stream_add_int64_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt64());
break;
case EventHeaderValue::EventHeaderType::BYTE_BUF:
{
const auto& bytes = header.second.GetEventHeaderValueAsBytebuf();
aws_event_stream_add_bytebuf_header(headers, header.first.c_str(), headerKeyLen, bytes.GetUnderlyingData(), static_cast<uint16_t>(bytes.GetLength()), 1 /*copy*/);
}
break;
case EventHeaderValue::EventHeaderType::STRING:
{
const auto& bytes = header.second.GetUnderlyingBuffer();
aws_event_stream_add_string_header(headers, header.first.c_str(), headerKeyLen, reinterpret_cast<char*>(bytes.GetUnderlyingData()), static_cast<uint16_t>(bytes.GetLength()), 0 /*copy*/);
}
break;
case EventHeaderValue::EventHeaderType::TIMESTAMP:
aws_event_stream_add_timestamp_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsTimestamp());
break;
case EventHeaderValue::EventHeaderType::UUID:
{
ByteBuffer uuidBytes = header.second.GetEventHeaderValueAsUuid();
aws_event_stream_add_uuid_header(headers, header.first.c_str(), headerKeyLen, uuidBytes.GetUnderlyingData());
}
break;
default:
AWS_LOG_ERROR(TAG, "Encountered unknown type of header.");
break;
}
}
}
EventStreamEncoder::EventStreamEncoder(Client::AWSAuthSigner* signer) : m_signer(signer)
{
}
Aws::Vector<unsigned char> EventStreamEncoder::EncodeAndSign(const Aws::Utils::Event::Message& msg)
{
aws_event_stream_message encoded = Encode(msg);
aws_event_stream_message signedMessage = Sign(&encoded);
const auto signedMessageLength = signedMessage.message_buffer ? aws_event_stream_message_total_length(&signedMessage) : 0;
Aws::Vector<unsigned char> outputBits(signedMessage.message_buffer, signedMessage.message_buffer + signedMessageLength);
aws_event_stream_message_clean_up(&encoded);
aws_event_stream_message_clean_up(&signedMessage);
return outputBits;
}
aws_event_stream_message EventStreamEncoder::Encode(const Aws::Utils::Event::Message& msg)
{
aws_array_list headers;
EncodeHeaders(msg, &headers);
aws_byte_buf payload;
payload.len = msg.GetEventPayload().size();
// this const_cast is OK because aws_byte_buf will only be "read from" by the following functions.
payload.buffer = const_cast<uint8_t*>(msg.GetEventPayload().data());
payload.capacity = 0;
payload.allocator = nullptr;
aws_event_stream_message encoded;
if(aws_event_stream_message_init(&encoded, get_aws_allocator(), &headers, &payload) == AWS_OP_ERR)
{
AWS_LOGSTREAM_ERROR(TAG, "Error creating event-stream message from payload.");
aws_event_stream_headers_list_cleanup(&headers);
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty{nullptr, nullptr, 0};
return empty;
}
aws_event_stream_headers_list_cleanup(&headers);
return encoded;
}
aws_event_stream_message EventStreamEncoder::Sign(aws_event_stream_message* msg)
{
const auto msglen = msg->message_buffer ? aws_event_stream_message_total_length(msg) : 0;
Event::Message signedMessage;
signedMessage.WriteEventPayload(msg->message_buffer, msglen);
assert(m_signer);
if (!m_signer->SignEventMessage(signedMessage, m_signatureSeed))
{
AWS_LOGSTREAM_ERROR(TAG, "Failed to sign event message frame.");
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty{nullptr, nullptr, 0};
return empty;
}
aws_array_list headers;
EncodeHeaders(signedMessage, &headers);
aws_byte_buf payload;
payload.len = signedMessage.GetEventPayload().size();
payload.buffer = signedMessage.GetEventPayload().data();
payload.capacity = 0;
payload.allocator = nullptr;
aws_event_stream_message signedmsg;
if(aws_event_stream_message_init(&signedmsg, get_aws_allocator(), &headers, &payload))
{
AWS_LOGSTREAM_ERROR(TAG, "Error creating event-stream message from payload.");
aws_event_stream_headers_list_cleanup(&headers);
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty{nullptr, nullptr, 0};
return empty;
}
aws_event_stream_headers_list_cleanup(&headers);
return signedmsg;
}
} // namespace Event
} // namespace Utils
} // namespace Aws
<commit_msg>Don't directly access members of aws_event_stream_message.<commit_after>/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/utils/event/EventHeader.h>
#include <aws/core/utils/event/EventMessage.h>
#include <aws/core/utils/event/EventStreamEncoder.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/common/byte_order.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <cassert>
namespace Aws
{
namespace Utils
{
namespace Event
{
static const char TAG[] = "EventStreamEncoder";
static void EncodeHeaders(const Aws::Utils::Event::Message& msg, aws_array_list* headers)
{
aws_array_list_init_dynamic(headers, get_aws_allocator(), msg.GetEventHeaders().size(), sizeof(aws_event_stream_header_value_pair));
for (auto&& header : msg.GetEventHeaders())
{
const uint8_t headerKeyLen = static_cast<uint8_t>(header.first.length());
switch(header.second.GetType())
{
case EventHeaderValue::EventHeaderType::BOOL_TRUE:
case EventHeaderValue::EventHeaderType::BOOL_FALSE:
aws_event_stream_add_bool_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsBoolean());
break;
case EventHeaderValue::EventHeaderType::BYTE:
aws_event_stream_add_bool_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsByte());
break;
case EventHeaderValue::EventHeaderType::INT16:
aws_event_stream_add_int16_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt16());
break;
case EventHeaderValue::EventHeaderType::INT32:
aws_event_stream_add_int32_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt32());
break;
case EventHeaderValue::EventHeaderType::INT64:
aws_event_stream_add_int64_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsInt64());
break;
case EventHeaderValue::EventHeaderType::BYTE_BUF:
{
const auto& bytes = header.second.GetEventHeaderValueAsBytebuf();
aws_event_stream_add_bytebuf_header(headers, header.first.c_str(), headerKeyLen, bytes.GetUnderlyingData(), static_cast<uint16_t>(bytes.GetLength()), 1 /*copy*/);
}
break;
case EventHeaderValue::EventHeaderType::STRING:
{
const auto& bytes = header.second.GetUnderlyingBuffer();
aws_event_stream_add_string_header(headers, header.first.c_str(), headerKeyLen, reinterpret_cast<char*>(bytes.GetUnderlyingData()), static_cast<uint16_t>(bytes.GetLength()), 0 /*copy*/);
}
break;
case EventHeaderValue::EventHeaderType::TIMESTAMP:
aws_event_stream_add_timestamp_header(headers, header.first.c_str(), headerKeyLen, header.second.GetEventHeaderValueAsTimestamp());
break;
case EventHeaderValue::EventHeaderType::UUID:
{
ByteBuffer uuidBytes = header.second.GetEventHeaderValueAsUuid();
aws_event_stream_add_uuid_header(headers, header.first.c_str(), headerKeyLen, uuidBytes.GetUnderlyingData());
}
break;
default:
AWS_LOG_ERROR(TAG, "Encountered unknown type of header.");
break;
}
}
}
EventStreamEncoder::EventStreamEncoder(Client::AWSAuthSigner* signer) : m_signer(signer)
{
}
Aws::Vector<unsigned char> EventStreamEncoder::EncodeAndSign(const Aws::Utils::Event::Message& msg)
{
aws_event_stream_message encoded = Encode(msg);
aws_event_stream_message signedMessage = Sign(&encoded);
const auto signedMessageBuffer = aws_event_stream_message_buffer(&signedMessage);
const auto signedMessageLength = signedMessageBuffer ? aws_event_stream_message_total_length(&signedMessage) : 0;
Aws::Vector<unsigned char> outputBits(signedMessageBuffer, signedMessageBuffer + signedMessageLength);
aws_event_stream_message_clean_up(&encoded);
aws_event_stream_message_clean_up(&signedMessage);
return outputBits;
}
aws_event_stream_message EventStreamEncoder::Encode(const Aws::Utils::Event::Message& msg)
{
aws_array_list headers;
EncodeHeaders(msg, &headers);
aws_byte_buf payload;
payload.len = msg.GetEventPayload().size();
// this const_cast is OK because aws_byte_buf will only be "read from" by the following functions.
payload.buffer = const_cast<uint8_t*>(msg.GetEventPayload().data());
payload.capacity = 0;
payload.allocator = nullptr;
aws_event_stream_message encoded;
if(aws_event_stream_message_init(&encoded, get_aws_allocator(), &headers, &payload) == AWS_OP_ERR)
{
AWS_LOGSTREAM_ERROR(TAG, "Error creating event-stream message from payload.");
aws_event_stream_headers_list_cleanup(&headers);
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty;
AWS_ZERO_STRUCT(empty);
return empty;
}
aws_event_stream_headers_list_cleanup(&headers);
return encoded;
}
aws_event_stream_message EventStreamEncoder::Sign(aws_event_stream_message* msg)
{
const auto msgbuf = aws_event_stream_message_buffer(msg);
const auto msglen = msgbuf ? aws_event_stream_message_total_length(msg) : 0;
Event::Message signedMessage;
signedMessage.WriteEventPayload(msgbuf, msglen);
assert(m_signer);
if (!m_signer->SignEventMessage(signedMessage, m_signatureSeed))
{
AWS_LOGSTREAM_ERROR(TAG, "Failed to sign event message frame.");
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty;
AWS_ZERO_STRUCT(empty);
return empty;
}
aws_array_list headers;
EncodeHeaders(signedMessage, &headers);
aws_byte_buf payload;
payload.len = signedMessage.GetEventPayload().size();
payload.buffer = signedMessage.GetEventPayload().data();
payload.capacity = 0;
payload.allocator = nullptr;
aws_event_stream_message signedmsg;
if(aws_event_stream_message_init(&signedmsg, get_aws_allocator(), &headers, &payload))
{
AWS_LOGSTREAM_ERROR(TAG, "Error creating event-stream message from payload.");
aws_event_stream_headers_list_cleanup(&headers);
// GCC 4.9.4 issues a warning with -Wextra if we simply do
// return {};
aws_event_stream_message empty;
AWS_ZERO_STRUCT(empty);
return empty;
}
aws_event_stream_headers_list_cleanup(&headers);
return signedmsg;
}
} // namespace Event
} // namespace Utils
} // namespace Aws
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/TestSuite/Tester.h>
#include "Magnum/Version.h"
namespace Magnum { namespace Test {
struct VersionTest: TestSuite::Tester {
explicit VersionTest();
void fromNumber();
void toNumber();
void compare();
};
VersionTest::VersionTest() {
addTests({&VersionTest::fromNumber,
&VersionTest::toNumber,
&VersionTest::compare});
}
void VersionTest::fromNumber() {
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE(version(4, 3), Version::GL430);
#else
CORRADE_COMPARE(version(3, 0), Version::GLES300);
#endif
}
void VersionTest::toNumber() {
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE(version(Version::GL430), std::make_pair(4, 3));
#else
CORRADE_COMPARE(version(Version::GLES300), std::make_pair(3, 0));
#endif
}
void VersionTest::compare() {
CORRADE_VERIFY(version(1, 1) < Version::GL210);
}
}}
CORRADE_TEST_MAIN(Magnum::Test::VersionTest)
<commit_msg>Fix ES build, again.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/TestSuite/Tester.h>
#include "Magnum/Version.h"
namespace Magnum { namespace Test {
struct VersionTest: TestSuite::Tester {
explicit VersionTest();
void fromNumber();
void toNumber();
void compare();
};
VersionTest::VersionTest() {
addTests({&VersionTest::fromNumber,
&VersionTest::toNumber,
&VersionTest::compare});
}
void VersionTest::fromNumber() {
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE(version(4, 3), Version::GL430);
#else
CORRADE_COMPARE(version(3, 0), Version::GLES300);
#endif
}
void VersionTest::toNumber() {
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE(version(Version::GL430), std::make_pair(4, 3));
#else
CORRADE_COMPARE(version(Version::GLES300), std::make_pair(3, 0));
#endif
}
void VersionTest::compare() {
#ifndef MAGNUM_TARGET_GLES
CORRADE_VERIFY(version(1, 1) < Version::GL210);
#else
CORRADE_VERIFY(version(1, 1) < Version::GLES200);
#endif
}
}}
CORRADE_TEST_MAIN(Magnum::Test::VersionTest)
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2012 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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 "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
# include <QTextStream>
#endif
#include "ui_TaskOffset.h"
#include "TaskOffset.h"
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Document.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/ViewProvider.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Base/UnitsApi.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <Mod/Part/App/FeatureOffset.h>
using namespace PartGui;
class OffsetWidget::Private
{
public:
Ui_TaskOffset ui;
Part::Offset* offset;
Private()
{
}
~Private()
{
}
};
/* TRANSLATOR PartGui::OffsetWidget */
OffsetWidget::OffsetWidget(Part::Offset* offset, QWidget* parent)
: d(new Private())
{
Gui::Application::Instance->runPythonCode("from FreeCAD import Base");
Gui::Application::Instance->runPythonCode("import Part");
d->offset = offset;
d->ui.setupUi(this);
d->ui.spinOffset->setUnit(Base::Unit::Length);
d->ui.spinOffset->setRange(-INT_MAX, INT_MAX);
d->ui.spinOffset->setSingleStep(0.1);
d->ui.spinOffset->setValue(d->offset->Value.getValue());
d->ui.facesButton->hide();
}
OffsetWidget::~OffsetWidget()
{
delete d;
}
Part::Offset* OffsetWidget::getObject() const
{
return d->offset;
}
void OffsetWidget::on_spinOffset_valueChanged(double val)
{
d->offset->Value.setValue(val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_modeType_activated(int val)
{
d->offset->Mode.setValue(val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_joinType_activated(int val)
{
d->offset->Join.setValue((long)val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_intersection_toggled(bool on)
{
d->offset->Intersection.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_selfIntersection_toggled(bool on)
{
d->offset->SelfIntersection.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_fillOffset_toggled(bool on)
{
d->offset->Fill.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_updateView_toggled(bool on)
{
if (on) {
d->offset->getDocument()->recomputeFeature(d->offset);
}
}
bool OffsetWidget::accept()
{
std::string name = d->offset->getNameInDocument();
try {
double offsetValue = d->ui.spinOffset->value().getValue();
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Value = %f",
name.c_str(),offsetValue);
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Mode = %i",
name.c_str(),d->ui.modeType->currentIndex());
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Join = %i",
name.c_str(),d->ui.joinType->currentIndex());
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Intersection = %s",
name.c_str(),d->ui.intersection->isChecked() ? "True" : "False");
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.SelfIntersection = %s",
name.c_str(),d->ui.selfIntersection->isChecked() ? "True" : "False");
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");
if (!d->offset->isValid())
throw Base::Exception(d->offset->getStatusString());
Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()");
Gui::Command::commitCommand();
}
catch (const Base::Exception& e) {
QMessageBox::warning(this, tr("Input error"), QString::fromLatin1(e.what()));
return false;
}
return true;
}
bool OffsetWidget::reject()
{
// get the support and Sketch
App::DocumentObject* source = d->offset->Source.getValue();
if (source){
Gui::Application::Instance->getViewProvider(source)->show();
}
// roll back the done things
Gui::Command::abortCommand();
Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()");
Gui::Command::updateActive();
return true;
}
void OffsetWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
d->ui.retranslateUi(this);
}
}
/* TRANSLATOR PartGui::TaskOffset */
TaskOffset::TaskOffset(Part::Offset* offset)
{
widget = new OffsetWidget(offset);
taskbox = new Gui::TaskView::TaskBox(
Gui::BitmapFactory().pixmap("Part_Offset"),
widget->windowTitle(), true, 0);
taskbox->groupLayout()->addWidget(widget);
Content.push_back(taskbox);
}
TaskOffset::~TaskOffset()
{
}
Part::Offset* TaskOffset::getObject() const
{
return widget->getObject();
}
void TaskOffset::open()
{
}
void TaskOffset::clicked(int)
{
}
bool TaskOffset::accept()
{
return widget->accept();
}
bool TaskOffset::reject()
{
return widget->reject();
}
#include "moc_TaskOffset.cpp"
<commit_msg>PartGui: Fixes and updates for Offset2D to task dialog<commit_after>/***************************************************************************
* Copyright (c) 2012 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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 "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
# include <QTextStream>
#endif
#include "ui_TaskOffset.h"
#include "TaskOffset.h"
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Document.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/ViewProvider.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Base/UnitsApi.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <Mod/Part/App/FeatureOffset.h>
using namespace PartGui;
class OffsetWidget::Private
{
public:
Ui_TaskOffset ui;
Part::Offset* offset;
Private()
{
}
~Private()
{
}
};
/* TRANSLATOR PartGui::OffsetWidget */
OffsetWidget::OffsetWidget(Part::Offset* offset, QWidget* parent)
: d(new Private())
{
Gui::Application::Instance->runPythonCode("from FreeCAD import Base");
Gui::Application::Instance->runPythonCode("import Part");
d->offset = offset;
d->ui.setupUi(this);
d->ui.spinOffset->setUnit(Base::Unit::Length);
d->ui.spinOffset->setRange(-INT_MAX, INT_MAX);
d->ui.spinOffset->setSingleStep(0.1);
d->ui.facesButton->hide();
bool is_2d = d->offset->isDerivedFrom(Part::Offset2D::getClassTypeId());
d->ui.selfIntersection->setVisible(!is_2d);
if(is_2d)
d->ui.modeType->removeItem(2);//remove Recto-Verso mode, not supported by 2d offset
//block signals to fill values read out from feature...
bool block = true;
d->ui.fillOffset->blockSignals(block);
d->ui.intersection->blockSignals(block);
d->ui.selfIntersection->blockSignals(block);
d->ui.modeType->blockSignals(block);
d->ui.joinType->blockSignals(block);
d->ui.spinOffset->blockSignals(block);
//read values from feature
d->ui.spinOffset->setValue(d->offset->Value.getValue());
d->ui.fillOffset->setChecked(offset->Fill.getValue());
d->ui.intersection->setChecked(offset->Intersection.getValue());
d->ui.selfIntersection->setChecked(offset->SelfIntersection.getValue());
long mode = offset->Mode.getValue();
if (mode >= 0 && mode < d->ui.modeType->count())
d->ui.modeType->setCurrentIndex(mode);
long join = offset->Join.getValue();
if (join >= 0 && join < d->ui.joinType->count())
d->ui.joinType->setCurrentIndex(join);
//unblock signals
block = false;
d->ui.fillOffset->blockSignals(block);
d->ui.intersection->blockSignals(block);
d->ui.selfIntersection->blockSignals(block);
d->ui.modeType->blockSignals(block);
d->ui.joinType->blockSignals(block);
d->ui.spinOffset->blockSignals(block);
d->ui.spinOffset->bind(d->offset->Value);
}
OffsetWidget::~OffsetWidget()
{
delete d;
}
Part::Offset* OffsetWidget::getObject() const
{
return d->offset;
}
void OffsetWidget::on_spinOffset_valueChanged(double val)
{
d->offset->Value.setValue(val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_modeType_activated(int val)
{
d->offset->Mode.setValue(val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_joinType_activated(int val)
{
d->offset->Join.setValue((long)val);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_intersection_toggled(bool on)
{
d->offset->Intersection.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_selfIntersection_toggled(bool on)
{
d->offset->SelfIntersection.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_fillOffset_toggled(bool on)
{
d->offset->Fill.setValue(on);
if (d->ui.updateView->isChecked())
d->offset->getDocument()->recomputeFeature(d->offset);
}
void OffsetWidget::on_updateView_toggled(bool on)
{
if (on) {
d->offset->getDocument()->recomputeFeature(d->offset);
}
}
bool OffsetWidget::accept()
{
std::string name = d->offset->getNameInDocument();
try {
double offsetValue = d->ui.spinOffset->value().getValue();
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Value = %f",
name.c_str(),offsetValue);
d->ui.spinOffset->apply();
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Mode = %i",
name.c_str(),d->ui.modeType->currentIndex());
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Join = %i",
name.c_str(),d->ui.joinType->currentIndex());
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Intersection = %s",
name.c_str(),d->ui.intersection->isChecked() ? "True" : "False");
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.SelfIntersection = %s",
name.c_str(),d->ui.selfIntersection->isChecked() ? "True" : "False");
Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");
if (!d->offset->isValid())
throw Base::Exception(d->offset->getStatusString());
Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()");
Gui::Command::commitCommand();
}
catch (const Base::Exception& e) {
QMessageBox::warning(this, tr("Input error"), QString::fromLatin1(e.what()));
return false;
}
return true;
}
bool OffsetWidget::reject()
{
// get the support and Sketch
App::DocumentObject* source = d->offset->Source.getValue();
if (source){
Gui::Application::Instance->getViewProvider(source)->show();
}
// roll back the done things
Gui::Command::abortCommand();
Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()");
Gui::Command::updateActive();
return true;
}
void OffsetWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
d->ui.retranslateUi(this);
}
}
/* TRANSLATOR PartGui::TaskOffset */
TaskOffset::TaskOffset(Part::Offset* offset)
{
widget = new OffsetWidget(offset);
taskbox = new Gui::TaskView::TaskBox(
Gui::BitmapFactory().pixmap("Part_Offset"),
widget->windowTitle(), true, 0);
taskbox->groupLayout()->addWidget(widget);
Content.push_back(taskbox);
}
TaskOffset::~TaskOffset()
{
}
Part::Offset* TaskOffset::getObject() const
{
return widget->getObject();
}
void TaskOffset::open()
{
}
void TaskOffset::clicked(int)
{
}
bool TaskOffset::accept()
{
return widget->accept();
}
bool TaskOffset::reject()
{
return widget->reject();
}
#include "moc_TaskOffset.cpp"
<|endoftext|>
|
<commit_before><commit_msg>Sketcher: Force solver to return non-driving angles in [-pi,pi]<commit_after><|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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 "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include "UnitTestPy.h"
#include "UnitTestImp.h"
#include <Gui/Language/Translator.h>
#include <Base/Console.h>
class UnitTestModule : public Py::ExtensionModule<UnitTestModule>
{
public:
UnitTestModule() : Py::ExtensionModule<UnitTestModule>("QtUnitGui")
{
TestGui::UnitTestDialogPy::init_type();
add_varargs_method("UnitTest",&UnitTestModule::new_UnitTest,"UnitTest");
add_varargs_method("setTest",&UnitTestModule::setTest,"setTest");
add_varargs_method("addTest",&UnitTestModule::addTest,"addTest");
initialize("This module is the QtUnitGui module"); // register with Python
}
virtual ~UnitTestModule() {}
private:
Py::Object new_UnitTest(const Py::Tuple& args)
{
return Py::asObject(new TestGui::UnitTestDialogPy());
}
Py::Object setTest(const Py::Tuple& args)
{
char *pstr=0;
if (!PyArg_ParseTuple(args.ptr(), "|s", &pstr))
throw Py::Exception();
TestGui::UnitTestDialog* dlg = TestGui::UnitTestDialog::instance();
if (pstr)
dlg->setUnitTest(QString::fromLatin1(pstr));
dlg->show();
dlg->raise();
return Py::None();
}
Py::Object addTest(const Py::Tuple& args)
{
char *pstr=0;
if (!PyArg_ParseTuple(args.ptr(), "|s", &pstr))
throw Py::Exception();
TestGui::UnitTestDialog* dlg = TestGui::UnitTestDialog::instance();
if (pstr)
dlg->addUnitTest(QString::fromLatin1(pstr));
dlg->show();
dlg->raise();
return Py::None();
}
};
void loadTestResource()
{
// add resources and reloads the translators
Q_INIT_RESOURCE(Test);
Gui::Translator::instance()->refresh();
}
/* Python entry */
extern "C" {
void AppTestGuiExport initQtUnitGui()
{
// the following constructor call registers our extension module
// with the Python runtime system
(void)new UnitTestModule;
Base::Console().Log("Loading GUI of Test module... done\n");
// add resources and reloads the translators
loadTestResource();
return;
}
} // extern "C"
<commit_msg>+ simplify porting of Test module to Python3<commit_after>/***************************************************************************
* Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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 "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include "UnitTestPy.h"
#include "UnitTestImp.h"
#include <Gui/Language/Translator.h>
#include <Base/Console.h>
class UnitTestModule : public Py::ExtensionModule<UnitTestModule>
{
public:
UnitTestModule() : Py::ExtensionModule<UnitTestModule>("QtUnitGui")
{
TestGui::UnitTestDialogPy::init_type();
add_varargs_method("UnitTest",&UnitTestModule::new_UnitTest,"UnitTest");
add_varargs_method("setTest",&UnitTestModule::setTest,"setTest");
add_varargs_method("addTest",&UnitTestModule::addTest,"addTest");
initialize("This module is the QtUnitGui module"); // register with Python
}
virtual ~UnitTestModule() {}
private:
Py::Object new_UnitTest(const Py::Tuple& args)
{
return Py::asObject(new TestGui::UnitTestDialogPy());
}
Py::Object setTest(const Py::Tuple& args)
{
char *pstr=0;
if (!PyArg_ParseTuple(args.ptr(), "|s", &pstr))
throw Py::Exception();
TestGui::UnitTestDialog* dlg = TestGui::UnitTestDialog::instance();
if (pstr)
dlg->setUnitTest(QString::fromLatin1(pstr));
dlg->show();
dlg->raise();
return Py::None();
}
Py::Object addTest(const Py::Tuple& args)
{
char *pstr=0;
if (!PyArg_ParseTuple(args.ptr(), "|s", &pstr))
throw Py::Exception();
TestGui::UnitTestDialog* dlg = TestGui::UnitTestDialog::instance();
if (pstr)
dlg->addUnitTest(QString::fromLatin1(pstr));
dlg->show();
dlg->raise();
return Py::None();
}
};
void loadTestResource()
{
// add resources and reloads the translators
Q_INIT_RESOURCE(Test);
Gui::Translator::instance()->refresh();
}
/* Python entry */
PyMODINIT_FUNC initQtUnitGui()
{
// the following constructor call registers our extension module
// with the Python runtime system
(void)new UnitTestModule;
Base::Console().Log("Loading GUI of Test module... done\n");
// add resources and reloads the translators
loadTestResource();
return;
}
<|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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "webkit/glue/window_open_disposition.h"
class MetricsServiceTest : public InProcessBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
// Enable the metrics service for testing (in recording-only mode).
command_line->AppendSwitch(switches::kMetricsRecordingOnly);
}
// Open a couple of tabs of random content.
void OpenTabs() {
const int kBrowserTestFlags =
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION;
FilePath test_directory;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_directory));
FilePath page1_path = test_directory.AppendASCII("title2.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(),
net::FilePathToFileURL(page1_path),
NEW_FOREGROUND_TAB,
kBrowserTestFlags);
FilePath page2_path = test_directory.AppendASCII("iframe.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(),
net::FilePathToFileURL(page2_path),
NEW_FOREGROUND_TAB,
kBrowserTestFlags);
}
};
IN_PROC_BROWSER_TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, prefs->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, prefs->GetInteger(prefs::kStabilityRendererCrashCount));
// TODO(isherman): We should also verify that prefs::kStabilityExitedCleanly
// is set to true, but this preference isn't set until the browser
// exits... it's not clear to me how to test that.
}
IN_PROC_BROWSER_TEST_F(MetricsServiceTest, CrashRenderers) {
OpenTabs();
// Kill the process for one of the tabs.
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUICrashURL));
observer.Wait();
// The MetricsService listens for the same notification, so the |observer|
// might finish waiting before the MetricsService has a chance to process the
// notification. To avoid racing here, we repeatedly run the message loop
// until the MetricsService catches up. This should happen "real soon now",
// since the notification is posted to all observers essentially
// simultaneously... so busy waiting here shouldn't be too bad.
const PrefService* prefs = g_browser_process->local_state();
while (!prefs->GetInteger(prefs::kStabilityRendererCrashCount)) {
ui_test_utils::RunAllPendingInMessageLoop();
}
// Verify that the expected stability metrics were recorded.
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, prefs->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityRendererCrashCount));
// TODO(isherman): We should also verify that prefs::kStabilityExitedCleanly
// is set to true, but this preference isn't set until the browser
// exits... it's not clear to me how to test that.
}
<commit_msg>Disable MetricsServiceTest.CrashRenderers on Linux.<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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "webkit/glue/window_open_disposition.h"
class MetricsServiceTest : public InProcessBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
// Enable the metrics service for testing (in recording-only mode).
command_line->AppendSwitch(switches::kMetricsRecordingOnly);
}
// Open a couple of tabs of random content.
void OpenTabs() {
const int kBrowserTestFlags =
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION;
FilePath test_directory;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_directory));
FilePath page1_path = test_directory.AppendASCII("title2.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(),
net::FilePathToFileURL(page1_path),
NEW_FOREGROUND_TAB,
kBrowserTestFlags);
FilePath page2_path = test_directory.AppendASCII("iframe.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(),
net::FilePathToFileURL(page2_path),
NEW_FOREGROUND_TAB,
kBrowserTestFlags);
}
};
IN_PROC_BROWSER_TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, prefs->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, prefs->GetInteger(prefs::kStabilityRendererCrashCount));
// TODO(isherman): We should also verify that prefs::kStabilityExitedCleanly
// is set to true, but this preference isn't set until the browser
// exits... it's not clear to me how to test that.
}
// Flaky on Linux. See http://crbug.com/131094
#if defined(OS_LINUX)
#define MAYBE_CrashRenderers DISABLED_CrashRenderers
#else
#define MAYBE_CrashRenderers CrashRenderers
#endif
IN_PROC_BROWSER_TEST_F(MetricsServiceTest, MAYBE_CrashRenderers) {
OpenTabs();
// Kill the process for one of the tabs.
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUICrashURL));
observer.Wait();
// The MetricsService listens for the same notification, so the |observer|
// might finish waiting before the MetricsService has a chance to process the
// notification. To avoid racing here, we repeatedly run the message loop
// until the MetricsService catches up. This should happen "real soon now",
// since the notification is posted to all observers essentially
// simultaneously... so busy waiting here shouldn't be too bad.
const PrefService* prefs = g_browser_process->local_state();
while (!prefs->GetInteger(prefs::kStabilityRendererCrashCount)) {
ui_test_utils::RunAllPendingInMessageLoop();
}
// Verify that the expected stability metrics were recorded.
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, prefs->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(prefs::kStabilityRendererCrashCount));
// TODO(isherman): We should also verify that prefs::kStabilityExitedCleanly
// is set to true, but this preference isn't set until the browser
// exits... it's not clear to me how to test that.
}
<|endoftext|>
|
<commit_before>// File: btBoostDynamicsShapes.hpp
#ifndef _btBoostDynamicsShapes_hpp
#define _btBoostDynamicsShapes_hpp
#include <btBulletDynamicsCommon.h>
#include <BulletCollision/CollisionShapes/btBox2dShape.h>
#include <boost/python.hpp>
#include "array_helpers.hpp"
using namespace boost::python;
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(chullshape_addPoint_overloads,
btConvexHullShape::addPoint,
1, 2)
void defineShapes()
{
// Base classes, not for developer use
class_<btCollisionShape, boost::noncopyable>
("btCollisionShape", no_init)
.def_readonly("polyhedral", &btCollisionShape::isPolyhedral)
.def_readonly("convex2d", &btCollisionShape::isConvex2d)
.def_readonly("convex", &btCollisionShape::isConvex)
.def_readonly("non_moving", &btCollisionShape::isNonMoving)
.def_readonly("concave", &btCollisionShape::isConcave)
.def_readonly("compound", &btCollisionShape::isCompound)
.def_readonly("soft_body", &btCollisionShape::isSoftBody)
.def_readonly("infinite", &btCollisionShape::isInfinite)
.def_readonly("shape_type", &btCollisionShape::getShapeType)
.add_property("margin", &btCollisionShape::getMargin,
&btCollisionShape::setMargin)
.def("get_aabb", &btCollisionShape::getAabb)
.def_readonly("aabb", &btCollisionShape::getAabb)
.def("get_bounding_sphere", &btCollisionShape::getBoundingSphere)
.def_readonly("angular_motion_disc",
&btCollisionShape::getAngularMotionDisc)
.def("get_contact_breaking_threshold",
&btCollisionShape::getContactBreakingThreshold)
.def("calculate_temporal_aabb",
&btCollisionShape::calculateTemporalAabb)
.add_property("local_scaling",
make_function(&btCollisionShape::getLocalScaling,
return_value_policy<copy_const_reference>()),
&btCollisionShape::setLocalScaling)
.def("calculate_local_inertia", &btCollisionShape::calculateLocalInertia)
.def("anisotropic_rolling_friction_direction",
&btCollisionShape::getAnisotropicRollingFrictionDirection)
;
class_<btConvexShape, bases<btCollisionShape>, boost::noncopyable>
("btConvexShape", no_init)
.def("local_get_supporting_vertex",
&btConvexShape::localGetSupportingVertexWithoutMargin)
.def("local_get_supporting_vertex_without_margin_non_virtual",
&btConvexShape::localGetSupportVertexWithoutMarginNonVirtual)
.def("local_get_support_vertex_non_virtual",
&btConvexShape::localGetSupportVertexNonVirtual)
.def("get_margin_non_virtual",
&btConvexShape::getMarginNonVirtual)
.def("get_aabb_non_virtual",
&btConvexShape::getAabbNonVirtual)
.def("project", &btConvexShape::project)
.def("batched_unit_vector_get_supporting_vertex_without_margin",
&btConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin)
.def("get_aabb_slow",
&btConvexShape::getAabbSlow)
;
class_<btConvexInternalShape, bases<btConvexShape>, boost::noncopyable>
("btConvexInternalShape", no_init)
.add_property("implicit_shape_dimensions",
make_function(&btConvexInternalShape::getImplicitShapeDimensions,
return_value_policy<copy_const_reference>()),
&btConvexInternalShape::setImplicitShapeDimensions)
// TODO: wrap setSafeMargin overloads
.def_readonly("local_scaling_non_virtual",
make_function(&btConvexInternalShape::getLocalScalingNV,
return_value_policy<copy_const_reference>()))
.def_readonly("margin_non_virtual",
make_function(&btConvexInternalShape::getMarginNV,
return_value_policy<return_by_value>()))
.def_readonly("num_preferred_penetration_directions",
&btConvexInternalShape::getNumPreferredPenetrationDirections)
.def("get_preferred_penetration_direction",
&btConvexInternalShape::getPreferredPenetrationDirection)
;
class_<btPolyhedralConvexShape, bases<btConvexInternalShape>,
boost::noncopyable>
("btPolyhedralConvexShape", no_init)
.def_readonly("num_vertices", &btPolyhedralConvexShape::getNumVertices)
.def_readonly("num_edges", &btPolyhedralConvexShape::getNumEdges)
.def("get_edge", &btPolyhedralConvexShape::getEdge)
.def("get_vertex", &btPolyhedralConvexShape::getVertex)
.def_readonly("num_planes", &btPolyhedralConvexShape::getNumPlanes)
.def("get_plane", &btPolyhedralConvexShape::getPlane)
.def_readonly("is_inside", &btPolyhedralConvexShape::isInside)
;
class_<btPolyhedralConvexAabbCachingShape, bases<btPolyhedralConvexShape>,
boost::noncopyable>
("btPolyhedralConvexAabbCachingShape", no_init)
.def("get_nonvirtual_aabb",
&btPolyhedralConvexAabbCachingShape::getNonvirtualAabb)
.def("recalc_local_aabb",
&btPolyhedralConvexAabbCachingShape::getAabb)
;
class_<btConcaveShape, bases<btCollisionShape>, boost::noncopyable>
("btConcaveShape", no_init)
;
// End base classes
// TODO: Add tests
class_<btConvexHullShape, bases<btPolyhedralConvexAabbCachingShape> >
("btConvexHullShape")
.def("add_point", &btConvexHullShape::addPoint,
chullshape_addPoint_overloads())
.def("get_unscaled_points",
&btConvexHullShape::getUnscaledPoints_wrap,
return_internal_reference<>())
.def("get_scaled_point", &btConvexHullShape::getScaledPoint)
.def("get_num_points", &btConvexHullShape::getNumPoints)
;
// TODO: Add tests
class_<btBox2dShape, bases<btPolyhedralConvexShape> >
("btBox2dShape", init<const btVector3&>())
.def_readonly("half_extents_with_margin",
make_function(&btBox2dShape::getHalfExtentsWithMargin,
return_value_policy<return_by_value>()))
.def_readonly("half_extents_without_margin",
make_function(&btBox2dShape::getHalfExtentsWithoutMargin,
return_internal_reference<>()))
;
// TODO: Add tests
class_<btBoxShape, bases<btPolyhedralConvexShape> >
("btBoxShape", init<const btVector3&>())
.def_readonly("half_extents_with_margin",
make_function(&btBoxShape::getHalfExtentsWithMargin,
return_value_policy<return_by_value>()))
.def_readonly("half_extents_without_margin",
make_function(&btBoxShape::getHalfExtentsWithoutMargin,
return_internal_reference<>()))
;
}
#endif // _btBoostDynamicsShapes_hpp
<commit_msg>added trianglemeshshape as base class<commit_after>// File: btBoostDynamicsShapes.hpp
#ifndef _btBoostDynamicsShapes_hpp
#define _btBoostDynamicsShapes_hpp
#include <btBulletDynamicsCommon.h>
#include <BulletCollision/CollisionShapes/btBox2dShape.h>
#include <boost/python.hpp>
#include "array_helpers.hpp"
using namespace boost::python;
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(chullshape_addPoint_overloads,
btConvexHullShape::addPoint,
1, 2)
void defineShapes()
{
// Base classes, not for developer use
class_<btCollisionShape, boost::noncopyable>
("btCollisionShape", no_init)
.def_readonly("polyhedral", &btCollisionShape::isPolyhedral)
.def_readonly("convex2d", &btCollisionShape::isConvex2d)
.def_readonly("convex", &btCollisionShape::isConvex)
.def_readonly("non_moving", &btCollisionShape::isNonMoving)
.def_readonly("concave", &btCollisionShape::isConcave)
.def_readonly("compound", &btCollisionShape::isCompound)
.def_readonly("soft_body", &btCollisionShape::isSoftBody)
.def_readonly("infinite", &btCollisionShape::isInfinite)
.def_readonly("shape_type", &btCollisionShape::getShapeType)
.add_property("margin", &btCollisionShape::getMargin,
&btCollisionShape::setMargin)
.def("get_aabb", &btCollisionShape::getAabb)
.def_readonly("aabb", &btCollisionShape::getAabb)
.def("get_bounding_sphere", &btCollisionShape::getBoundingSphere)
.def_readonly("angular_motion_disc",
&btCollisionShape::getAngularMotionDisc)
.def("get_contact_breaking_threshold",
&btCollisionShape::getContactBreakingThreshold)
.def("calculate_temporal_aabb",
&btCollisionShape::calculateTemporalAabb)
.add_property("local_scaling",
make_function(&btCollisionShape::getLocalScaling,
return_value_policy<copy_const_reference>()),
&btCollisionShape::setLocalScaling)
.def("calculate_local_inertia", &btCollisionShape::calculateLocalInertia)
.def("anisotropic_rolling_friction_direction",
&btCollisionShape::getAnisotropicRollingFrictionDirection)
;
class_<btConvexShape, bases<btCollisionShape>, boost::noncopyable>
("btConvexShape", no_init)
.def("local_get_supporting_vertex",
&btConvexShape::localGetSupportingVertexWithoutMargin)
.def("local_get_supporting_vertex_without_margin_non_virtual",
&btConvexShape::localGetSupportVertexWithoutMarginNonVirtual)
.def("local_get_support_vertex_non_virtual",
&btConvexShape::localGetSupportVertexNonVirtual)
.def("get_margin_non_virtual",
&btConvexShape::getMarginNonVirtual)
.def("get_aabb_non_virtual",
&btConvexShape::getAabbNonVirtual)
.def("project", &btConvexShape::project)
.def("batched_unit_vector_get_supporting_vertex_without_margin",
&btConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin)
.def("get_aabb_slow",
&btConvexShape::getAabbSlow)
;
class_<btConvexInternalShape, bases<btConvexShape>, boost::noncopyable>
("btConvexInternalShape", no_init)
.add_property("implicit_shape_dimensions",
make_function(&btConvexInternalShape::getImplicitShapeDimensions,
return_value_policy<copy_const_reference>()),
&btConvexInternalShape::setImplicitShapeDimensions)
// TODO: wrap setSafeMargin overloads
.def_readonly("local_scaling_non_virtual",
make_function(&btConvexInternalShape::getLocalScalingNV,
return_value_policy<copy_const_reference>()))
.def_readonly("margin_non_virtual",
make_function(&btConvexInternalShape::getMarginNV,
return_value_policy<return_by_value>()))
.def_readonly("num_preferred_penetration_directions",
&btConvexInternalShape::getNumPreferredPenetrationDirections)
.def("get_preferred_penetration_direction",
&btConvexInternalShape::getPreferredPenetrationDirection)
;
class_<btPolyhedralConvexShape, bases<btConvexInternalShape>,
boost::noncopyable>
("btPolyhedralConvexShape", no_init)
.def_readonly("num_vertices", &btPolyhedralConvexShape::getNumVertices)
.def_readonly("num_edges", &btPolyhedralConvexShape::getNumEdges)
.def("get_edge", &btPolyhedralConvexShape::getEdge)
.def("get_vertex", &btPolyhedralConvexShape::getVertex)
.def_readonly("num_planes", &btPolyhedralConvexShape::getNumPlanes)
.def("get_plane", &btPolyhedralConvexShape::getPlane)
.def_readonly("is_inside", &btPolyhedralConvexShape::isInside)
;
class_<btPolyhedralConvexAabbCachingShape, bases<btPolyhedralConvexShape>,
boost::noncopyable>
("btPolyhedralConvexAabbCachingShape", no_init)
.def("get_nonvirtual_aabb",
&btPolyhedralConvexAabbCachingShape::getNonvirtualAabb)
.def("recalc_local_aabb",
&btPolyhedralConvexAabbCachingShape::getAabb)
;
class_<btConcaveShape, bases<btCollisionShape>, boost::noncopyable>
("btConcaveShape", no_init)
;
class_<btTriangleMeshShape, bases<btConcaveShape>, boost::noncopyable>
("btTriangleMeshShape", no_init)
;
// End base classes
// TODO: Add tests
class_<btConvexHullShape, bases<btPolyhedralConvexAabbCachingShape> >
("btConvexHullShape")
.def("add_point", &btConvexHullShape::addPoint,
chullshape_addPoint_overloads())
.def("get_unscaled_points",
&btConvexHullShape::getUnscaledPoints_wrap,
return_internal_reference<>())
.def("get_scaled_point", &btConvexHullShape::getScaledPoint)
.def("get_num_points", &btConvexHullShape::getNumPoints)
;
// TODO: Add tests
class_<btBox2dShape, bases<btPolyhedralConvexShape> >
("btBox2dShape", init<const btVector3&>())
.def_readonly("half_extents_with_margin",
make_function(&btBox2dShape::getHalfExtentsWithMargin,
return_value_policy<return_by_value>()))
.def_readonly("half_extents_without_margin",
make_function(&btBox2dShape::getHalfExtentsWithoutMargin,
return_internal_reference<>()))
;
// TODO: Add tests
class_<btBoxShape, bases<btPolyhedralConvexShape> >
("btBoxShape", init<const btVector3&>())
.def_readonly("half_extents_with_margin",
make_function(&btBoxShape::getHalfExtentsWithMargin,
return_value_policy<return_by_value>()))
.def_readonly("half_extents_without_margin",
make_function(&btBoxShape::getHalfExtentsWithoutMargin,
return_internal_reference<>()))
;
}
#endif // _btBoostDynamicsShapes_hpp
<|endoftext|>
|
<commit_before>#include <memory>
#include "math.h"
#include "window.h"
#include "rect.h"
#include "gameobject.h"
#include "camera.h"
Camera::Camera(){
mBox.Set(0, 0, Window::Box().W(), Window::Box().H());
}
Camera::~Camera(){
mFocus.reset();
}
void Camera::SetFocus(std::shared_ptr<GameObject> obj){
mFocus = obj;
}
void Camera::Update(){
//Try to lock the focus weak pointer, ie. check to see if
//the camera should be following something
auto s = mFocus.lock();
//If there's no focus don't have the camera try to follow one
if (!s)
return;
Rectf focBox = s->Box();
//Update width and height to match window size
Rectf winBox = Window::Box();
//TODO: winbox here
mBox.w = winBox.w;
mBox.h = winBox.h;
//Adjust camera position
float x, y;
x = (mBox.w + focBox.w / 2) - mBox.w / 2;
y = (mBox.h + focBox.h / 2) - mBox.h / 2;
//Clamp the camera values to keep them in range
mBox.Set(Math::Clamp(x, 0, winBox.w - mBox.w),
Math::Clamp(y, 0, winBox.h - mBox.h));
}
bool Camera::InCamera(Rectf box) const{
return Math::CheckCollision(mBox, box);
}
void Camera::SetBox(Rectf box){
mBox = box;
}
Rectf Camera::Box() const{
return mBox;
}
Vector2f Camera::Offset() const{
return Vector2f(mBox.X(), mBox.Y());
}
<commit_msg>Added a TODO in Camera about changing the winBox there to be the scene box<commit_after>#include <memory>
#include "math.h"
#include "window.h"
#include "rect.h"
#include "gameobject.h"
#include "camera.h"
Camera::Camera(){
mBox.Set(0, 0, Window::Box().W(), Window::Box().H());
}
Camera::~Camera(){
mFocus.reset();
}
void Camera::SetFocus(std::shared_ptr<GameObject> obj){
mFocus = obj;
}
void Camera::Update(){
//Try to lock the focus weak pointer, ie. check to see if
//the camera should be following something
auto s = mFocus.lock();
//If there's no focus don't have the camera try to follow one
if (!s)
return;
Rectf focBox = s->Box();
//Update width and height to match window size
//TODO: Window size in this context SHOULD be the scene size
Rectf winBox = Window::Box();
mBox.w = winBox.w;
mBox.h = winBox.h;
//Adjust camera position
float x, y;
x = (mBox.w + focBox.w / 2) - mBox.w / 2;
y = (mBox.h + focBox.h / 2) - mBox.h / 2;
//Clamp the camera values to keep them in range
mBox.Set(Math::Clamp(x, 0, winBox.w - mBox.w),
Math::Clamp(y, 0, winBox.h - mBox.h));
}
bool Camera::InCamera(Rectf box) const{
return Math::CheckCollision(mBox, box);
}
void Camera::SetBox(Rectf box){
mBox = box;
}
Rectf Camera::Box() const{
return mBox;
}
Vector2f Camera::Offset() const{
return Vector2f(mBox.X(), mBox.Y());
}
<|endoftext|>
|
<commit_before>#pragma once
#include <bts/blockchain/types.hpp>
#include <bts/blockchain/withdraw_types.hpp>
#include <bts/blockchain/transaction.hpp>
namespace bts { namespace blockchain {
struct asset_record
{
enum
{
market_issued_asset = -2
};
asset_record()
:id(0),issuer_account_id(0),precision(0),current_share_supply(0),maximum_share_supply(0),collected_fees(0){}
share_type available_shares()const;
bool can_issue( const asset& amount )const;
bool can_issue( const share_type& amount )const;
bool is_null()const;
/** the asset is issued by the market and not by any user */
bool is_market_issued()const;
bool is_chip_asset() const;
asset_record make_null()const;
uint64_t get_precision()const;
asset_id_type id;
std::string symbol;
std::string name;
std::string description;
fc::variant public_data;
account_id_type issuer_account_id;
uint64_t precision;
fc::time_point_sec registration_date;
fc::time_point_sec last_update;
share_type current_collateral;
share_type current_share_supply;
share_type maximum_share_supply;
share_type collected_fees;
/**
* Setting these values to a reasonable range helps the
* market filter out garbage data that could result in
* very large ratios. For example, assume a min
* market cap for XTS of $1 Million and a maximum
* market cap of $1 Trillion that gives us a trading
* range of $0.0005 and $500 for the price.
*/
price minimum_xts_price; // in this asset
price maximum_xts_price; // in this asset
};
typedef fc::optional<asset_record> oasset_record;
} } // bts::blockchain
FC_REFLECT( bts::blockchain::asset_record,
(id)(symbol)(name)(description)(public_data)(issuer_account_id)(precision)(current_share_supply)
(maximum_share_supply)(collected_fees)(registration_date)(minimum_xts_price)(maximum_xts_price)
)
<commit_msg>fix current_collateral<commit_after>#pragma once
#include <bts/blockchain/types.hpp>
#include <bts/blockchain/withdraw_types.hpp>
#include <bts/blockchain/transaction.hpp>
namespace bts { namespace blockchain {
struct asset_record
{
enum
{
market_issued_asset = -2
};
asset_record()
:id(0),issuer_account_id(0),precision(0),current_share_supply(0),maximum_share_supply(0),collected_fees(0){}
share_type available_shares()const;
bool can_issue( const asset& amount )const;
bool can_issue( const share_type& amount )const;
bool is_null()const;
/** the asset is issued by the market and not by any user */
bool is_market_issued()const;
bool is_chip_asset() const;
asset_record make_null()const;
uint64_t get_precision()const;
asset_id_type id;
std::string symbol;
std::string name;
std::string description;
fc::variant public_data;
account_id_type issuer_account_id;
uint64_t precision;
fc::time_point_sec registration_date;
fc::time_point_sec last_update;
share_type current_collateral;
share_type current_share_supply;
share_type maximum_share_supply;
share_type collected_fees;
/**
* Setting these values to a reasonable range helps the
* market filter out garbage data that could result in
* very large ratios. For example, assume a min
* market cap for XTS of $1 Million and a maximum
* market cap of $1 Trillion that gives us a trading
* range of $0.0005 and $500 for the price.
*/
price minimum_xts_price; // in this asset
price maximum_xts_price; // in this asset
};
typedef fc::optional<asset_record> oasset_record;
} } // bts::blockchain
FC_REFLECT( bts::blockchain::asset_record,
(id)(symbol)(name)(description)(public_data)(issuer_account_id)(precision)(current_collateral)(current_share_supply)
(maximum_share_supply)(collected_fees)(registration_date)(minimum_xts_price)(maximum_xts_price)
)
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qpulsehelpers.h"
QT_BEGIN_NAMESPACE
namespace QPulseAudioInternal
{
pa_sample_spec audioFormatToSampleSpec(const QAudioFormat &format)
{
pa_sample_spec spec;
spec.rate = format.frequency();
spec.channels = format.channels();
if (format.sampleSize() == 8) {
spec.format = PA_SAMPLE_U8;
} else if (format.sampleSize() == 16) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian: spec.format = PA_SAMPLE_S16BE; break;
case QAudioFormat::LittleEndian: spec.format = PA_SAMPLE_S16LE; break;
}
} else if (format.sampleSize() == 24) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian: spec.format = PA_SAMPLE_S24BE; break;
case QAudioFormat::LittleEndian: spec.format = PA_SAMPLE_S24LE; break;
}
} else if (format.sampleSize() == 32) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian:
format.sampleType() == QAudioFormat::Float ? spec.format = PA_SAMPLE_FLOAT32BE : spec.format = PA_SAMPLE_S32BE;
break;
case QAudioFormat::LittleEndian:
format.sampleType() == QAudioFormat::Float ? spec.format = PA_SAMPLE_FLOAT32LE : spec.format = PA_SAMPLE_S32LE;
break;
}
}
return spec;
}
#ifdef DEBUG_PULSE
QString stateToQString(pa_stream_state_t state)
{
switch (state)
{
case PA_STREAM_UNCONNECTED: return "Unconnected";
case PA_STREAM_CREATING: return "Creating";
case PA_STREAM_READY: return "Ready";
case PA_STREAM_FAILED: return "Failed";
case PA_STREAM_TERMINATED: return "Terminated";
}
return QString("Unknown state: %0").arg(state);
}
QString sampleFormatToQString(pa_sample_format format)
{
switch (format)
{
case PA_SAMPLE_U8: return "Unsigned 8 Bit PCM.";
case PA_SAMPLE_ALAW: return "8 Bit a-Law ";
case PA_SAMPLE_ULAW: return "8 Bit mu-Law";
case PA_SAMPLE_S16LE: return "Signed 16 Bit PCM, little endian (PC).";
case PA_SAMPLE_S16BE: return "Signed 16 Bit PCM, big endian.";
case PA_SAMPLE_FLOAT32LE: return "32 Bit IEEE floating point, little endian (PC), range -1.0 to 1.0";
case PA_SAMPLE_FLOAT32BE: return "32 Bit IEEE floating point, big endian, range -1.0 to 1.0";
case PA_SAMPLE_S32LE: return "Signed 32 Bit PCM, little endian (PC).";
case PA_SAMPLE_S32BE: return "Signed 32 Bit PCM, big endian.";
case PA_SAMPLE_S24LE: return "Signed 24 Bit PCM packed, little endian (PC).";
case PA_SAMPLE_S24BE: return "Signed 24 Bit PCM packed, big endian.";
case PA_SAMPLE_S24_32LE: return "Signed 24 Bit PCM in LSB of 32 Bit words, little endian (PC).";
case PA_SAMPLE_S24_32BE: return "Signed 24 Bit PCM in LSB of 32 Bit words, big endian.";
case PA_SAMPLE_MAX: return "Upper limit of valid sample types.";
case PA_SAMPLE_INVALID: return "Invalid sample format";
}
return QString("Invalid value: %0").arg(format);
}
QString stateToQString(pa_context_state_t state)
{
switch (state)
{
case PA_CONTEXT_UNCONNECTED: return "Unconnected";
case PA_CONTEXT_CONNECTING: return "Connecting";
case PA_CONTEXT_AUTHORIZING: return "Authorizing";
case PA_CONTEXT_SETTING_NAME: return "Setting Name";
case PA_CONTEXT_READY: return "Ready";
case PA_CONTEXT_FAILED: return "Failed";
case PA_CONTEXT_TERMINATED: return "Terminated";
}
return QString("Unknown state: %0").arg(state);
}
#endif
QAudioFormat sampleSpecToAudioFormat(pa_sample_spec spec)
{
QAudioFormat format;
format.setFrequency(spec.rate);
format.setChannelCount(spec.channels);
format.setCodec("audio/pcm");
switch (spec.format) {
case PA_SAMPLE_U8:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
format.setSampleSize(8);
break;
case PA_SAMPLE_ALAW:
// TODO:
break;
case PA_SAMPLE_ULAW:
// TODO:
break;
case PA_SAMPLE_S16LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(16);
break;
case PA_SAMPLE_S16BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(16);
break;
case PA_SAMPLE_FLOAT32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::Float);
format.setSampleSize(32);
break;
case PA_SAMPLE_FLOAT32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::Float);
format.setSampleSize(32);
break;
case PA_SAMPLE_S32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(32);
break;
case PA_SAMPLE_S32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(32);
break;
case PA_SAMPLE_S24LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24_32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24_32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_MAX:
case PA_SAMPLE_INVALID:
default:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::Unknown);
format.setSampleSize(0);
}
return format;
}
}
QT_END_NAMESPACE
<commit_msg>Added default case when converting format to pulse audio spec<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qpulsehelpers.h"
QT_BEGIN_NAMESPACE
namespace QPulseAudioInternal
{
pa_sample_spec audioFormatToSampleSpec(const QAudioFormat &format)
{
pa_sample_spec spec;
spec.rate = format.frequency();
spec.channels = format.channels();
if (format.sampleSize() == 8) {
spec.format = PA_SAMPLE_U8;
} else if (format.sampleSize() == 16) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian: spec.format = PA_SAMPLE_S16BE; break;
case QAudioFormat::LittleEndian: spec.format = PA_SAMPLE_S16LE; break;
}
} else if (format.sampleSize() == 24) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian: spec.format = PA_SAMPLE_S24BE; break;
case QAudioFormat::LittleEndian: spec.format = PA_SAMPLE_S24LE; break;
}
} else if (format.sampleSize() == 32) {
switch (format.byteOrder()) {
case QAudioFormat::BigEndian:
format.sampleType() == QAudioFormat::Float ? spec.format = PA_SAMPLE_FLOAT32BE : spec.format = PA_SAMPLE_S32BE;
break;
case QAudioFormat::LittleEndian:
format.sampleType() == QAudioFormat::Float ? spec.format = PA_SAMPLE_FLOAT32LE : spec.format = PA_SAMPLE_S32LE;
break;
}
} else {
spec.format = PA_SAMPLE_INVALID;
}
return spec;
}
#ifdef DEBUG_PULSE
QString stateToQString(pa_stream_state_t state)
{
switch (state)
{
case PA_STREAM_UNCONNECTED: return "Unconnected";
case PA_STREAM_CREATING: return "Creating";
case PA_STREAM_READY: return "Ready";
case PA_STREAM_FAILED: return "Failed";
case PA_STREAM_TERMINATED: return "Terminated";
}
return QString("Unknown state: %0").arg(state);
}
QString sampleFormatToQString(pa_sample_format format)
{
switch (format)
{
case PA_SAMPLE_U8: return "Unsigned 8 Bit PCM.";
case PA_SAMPLE_ALAW: return "8 Bit a-Law ";
case PA_SAMPLE_ULAW: return "8 Bit mu-Law";
case PA_SAMPLE_S16LE: return "Signed 16 Bit PCM, little endian (PC).";
case PA_SAMPLE_S16BE: return "Signed 16 Bit PCM, big endian.";
case PA_SAMPLE_FLOAT32LE: return "32 Bit IEEE floating point, little endian (PC), range -1.0 to 1.0";
case PA_SAMPLE_FLOAT32BE: return "32 Bit IEEE floating point, big endian, range -1.0 to 1.0";
case PA_SAMPLE_S32LE: return "Signed 32 Bit PCM, little endian (PC).";
case PA_SAMPLE_S32BE: return "Signed 32 Bit PCM, big endian.";
case PA_SAMPLE_S24LE: return "Signed 24 Bit PCM packed, little endian (PC).";
case PA_SAMPLE_S24BE: return "Signed 24 Bit PCM packed, big endian.";
case PA_SAMPLE_S24_32LE: return "Signed 24 Bit PCM in LSB of 32 Bit words, little endian (PC).";
case PA_SAMPLE_S24_32BE: return "Signed 24 Bit PCM in LSB of 32 Bit words, big endian.";
case PA_SAMPLE_MAX: return "Upper limit of valid sample types.";
case PA_SAMPLE_INVALID: return "Invalid sample format";
}
return QString("Invalid value: %0").arg(format);
}
QString stateToQString(pa_context_state_t state)
{
switch (state)
{
case PA_CONTEXT_UNCONNECTED: return "Unconnected";
case PA_CONTEXT_CONNECTING: return "Connecting";
case PA_CONTEXT_AUTHORIZING: return "Authorizing";
case PA_CONTEXT_SETTING_NAME: return "Setting Name";
case PA_CONTEXT_READY: return "Ready";
case PA_CONTEXT_FAILED: return "Failed";
case PA_CONTEXT_TERMINATED: return "Terminated";
}
return QString("Unknown state: %0").arg(state);
}
#endif
QAudioFormat sampleSpecToAudioFormat(pa_sample_spec spec)
{
QAudioFormat format;
format.setFrequency(spec.rate);
format.setChannelCount(spec.channels);
format.setCodec("audio/pcm");
switch (spec.format) {
case PA_SAMPLE_U8:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
format.setSampleSize(8);
break;
case PA_SAMPLE_ALAW:
// TODO:
break;
case PA_SAMPLE_ULAW:
// TODO:
break;
case PA_SAMPLE_S16LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(16);
break;
case PA_SAMPLE_S16BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(16);
break;
case PA_SAMPLE_FLOAT32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::Float);
format.setSampleSize(32);
break;
case PA_SAMPLE_FLOAT32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::Float);
format.setSampleSize(32);
break;
case PA_SAMPLE_S32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(32);
break;
case PA_SAMPLE_S32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(32);
break;
case PA_SAMPLE_S24LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24_32LE:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_S24_32BE:
format.setByteOrder(QAudioFormat::BigEndian);
format.setSampleType(QAudioFormat::SignedInt);
format.setSampleSize(24);
break;
case PA_SAMPLE_MAX:
case PA_SAMPLE_INVALID:
default:
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::Unknown);
format.setSampleSize(0);
}
return format;
}
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/ImagingInterface.h>
// Library/third-party includes
#include <opencv2/core/core.hpp> // for basic OpenCV types
#include <opencv2/core/operations.hpp>
#include <opencv2/highgui/highgui.hpp> // for image capture
#include <opencv2/imgproc/imgproc.hpp> // for image scaling
#include <boost/noncopyable.hpp>
#include <boost/lexical_cast.hpp>
// Standard includes
#include <iostream>
#include <sstream>
namespace {
OSVR_MessageType cameraMessage;
class CameraDevice : boost::noncopyable {
public:
CameraDevice(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0)
: m_camera(cameraNum), m_channel(channel) {
/// Create the initialization options
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
/// Configure an imaging interface (with the default number of sensors,
/// 1)
m_imaging = osvr::pluginkit::ImagingInterface(opts);
/// Come up with a device name
std::ostringstream os;
os << "Camera" << cameraNum << "_" << m_channel;
/// Create an asynchronous (threaded) device
m_dev.initAsync(ctx, os.str(), opts);
// Puts an object in m_dev that knows it's a
// threaded device so osvrDeviceSendData knows
// that it needs to get a connection lock first.
/// Sets the update callback
m_dev.registerUpdateCallback(this);
}
OSVR_ReturnCode update() {
if (!m_camera.isOpened()) {
// Couldn't open the camera. Failing silently for now. Maybe the
// camera will be plugged back in later.
return OSVR_RETURN_SUCCESS;
}
// Trigger a camera grab.
bool grabbed = m_camera.grab();
if (!grabbed) {
// No frame available.
return OSVR_RETURN_SUCCESS;
}
bool retrieved = m_camera.retrieve(m_frame, m_channel);
if (!retrieved) {
return OSVR_RETURN_FAILURE;
}
// Currently limited to just under 64k message size.
// cv::Mat subimage = m_frame(cv::Rect(0, 0, 210, 100));
// m_dev.send(m_imaging, osvr::pluginkit::ImagingMessage(subimage));
// Scale down to something under 160x120 while keeping aspect ratio.
auto xScale = 160.0 / m_frame.cols;
auto yScale = 120.0 / m_frame.rows;
auto finalScale = std::min(xScale, yScale);
cv::resize(m_frame, m_scaledFrame, cv::Size(), finalScale, finalScale,
CV_INTER_AREA);
m_dev.send(m_imaging, osvr::pluginkit::ImagingMessage(m_scaledFrame));
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
osvr::pluginkit::ImagingInterface m_imaging;
cv::VideoCapture m_camera;
int m_channel;
cv::Mat m_frame;
cv::Mat m_scaledFrame;
};
class CameraDetection {
public:
CameraDetection() : m_found(false) {}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
if (m_found) {
return OSVR_RETURN_SUCCESS;
}
{
// Autodetect camera
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
// Failed to find camera
return OSVR_RETURN_FAILURE;
}
}
m_found = true;
/// Create our device object, passing the context, and register
/// the function to call
osvr::pluginkit::registerObjectForDeletion(ctx, new CameraDevice(ctx));
return OSVR_RETURN_SUCCESS;
}
private:
bool m_found;
};
} // end anonymous namespace
OSVR_PLUGIN(com_osvr_VideoCapture_OpenCV) {
osvrDeviceRegisterMessageType(ctx, "CameraMessage", &cameraMessage);
osvr::pluginkit::PluginContext context(ctx);
context.registerHardwareDetectCallback(new CameraDetection());
return OSVR_RETURN_SUCCESS;
}
<commit_msg>Explicitly specify type in a plugin.<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/ImagingInterface.h>
// Library/third-party includes
#include <opencv2/core/core.hpp> // for basic OpenCV types
#include <opencv2/core/operations.hpp>
#include <opencv2/highgui/highgui.hpp> // for image capture
#include <opencv2/imgproc/imgproc.hpp> // for image scaling
#include <boost/noncopyable.hpp>
#include <boost/lexical_cast.hpp>
// Standard includes
#include <iostream>
#include <sstream>
namespace {
OSVR_MessageType cameraMessage;
class CameraDevice : boost::noncopyable {
public:
CameraDevice(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0)
: m_camera(cameraNum), m_channel(channel) {
/// Create the initialization options
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
/// Configure an imaging interface (with the default number of sensors,
/// 1)
m_imaging = osvr::pluginkit::ImagingInterface(opts);
/// Come up with a device name
std::ostringstream os;
os << "Camera" << cameraNum << "_" << m_channel;
/// Create an asynchronous (threaded) device
m_dev.initAsync(ctx, os.str(), opts);
// Puts an object in m_dev that knows it's a
// threaded device so osvrDeviceSendData knows
// that it needs to get a connection lock first.
/// Sets the update callback
m_dev.registerUpdateCallback(this);
}
OSVR_ReturnCode update() {
if (!m_camera.isOpened()) {
// Couldn't open the camera. Failing silently for now. Maybe the
// camera will be plugged back in later.
return OSVR_RETURN_SUCCESS;
}
// Trigger a camera grab.
bool grabbed = m_camera.grab();
if (!grabbed) {
// No frame available.
return OSVR_RETURN_SUCCESS;
}
bool retrieved = m_camera.retrieve(m_frame, m_channel);
if (!retrieved) {
return OSVR_RETURN_FAILURE;
}
// Currently limited to just under 64k message size.
// cv::Mat subimage = m_frame(cv::Rect(0, 0, 210, 100));
// m_dev.send(m_imaging, osvr::pluginkit::ImagingMessage(subimage));
// Scale down to something under 160x120 while keeping aspect ratio.
double xScale = 160.0 / m_frame.cols;
double yScale = 120.0 / m_frame.rows;
double finalScale = std::min(xScale, yScale);
cv::resize(m_frame, m_scaledFrame, cv::Size(), finalScale, finalScale,
CV_INTER_AREA);
m_dev.send(m_imaging, osvr::pluginkit::ImagingMessage(m_scaledFrame));
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
osvr::pluginkit::ImagingInterface m_imaging;
cv::VideoCapture m_camera;
int m_channel;
cv::Mat m_frame;
cv::Mat m_scaledFrame;
};
class CameraDetection {
public:
CameraDetection() : m_found(false) {}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
if (m_found) {
return OSVR_RETURN_SUCCESS;
}
{
// Autodetect camera
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
// Failed to find camera
return OSVR_RETURN_FAILURE;
}
}
m_found = true;
/// Create our device object, passing the context, and register
/// the function to call
osvr::pluginkit::registerObjectForDeletion(ctx, new CameraDevice(ctx));
return OSVR_RETURN_SUCCESS;
}
private:
bool m_found;
};
} // end anonymous namespace
OSVR_PLUGIN(com_osvr_VideoCapture_OpenCV) {
osvrDeviceRegisterMessageType(ctx, "CameraMessage", &cameraMessage);
osvr::pluginkit::PluginContext context(ctx);
context.registerHardwareDetectCallback(new CameraDetection());
return OSVR_RETURN_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cairo_canvascustomsprite.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX
#define _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX
#include <cppuhelper/compbase4.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/rendering/XCustomSprite.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2isize.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/canvascustomspritebase.hxx>
#include "cairo_sprite.hxx"
#include "cairo_cairo.hxx"
#include "cairo_canvashelper.hxx"
#include "cairo_repainttarget.hxx"
#include "cairo_spritehelper.hxx"
#include "cairo_spritecanvas.hxx"
namespace cairocanvas
{
typedef ::cppu::WeakComponentImplHelper4< ::com::sun::star::rendering::XCustomSprite,
::com::sun::star::rendering::XBitmapCanvas,
::com::sun::star::rendering::XIntegerBitmap,
::com::sun::star::lang::XServiceInfo > CanvasCustomSpriteBase_Base;
/** Mixin Sprite
Have to mixin the Sprite interface before deriving from
::canvas::CanvasCustomSpriteBase, as this template should
already implement some of those interface methods.
The reason why this appears kinda convoluted is the fact that
we cannot specify non-IDL types as WeakComponentImplHelperN
template args, and furthermore, don't want to derive
::canvas::CanvasCustomSpriteBase directly from
::canvas::Sprite (because derivees of
::canvas::CanvasCustomSpriteBase have to explicitely forward
the XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
anyway). Basically, ::canvas::CanvasCustomSpriteBase should
remain a base class that provides implementation, not to
enforce any specific interface on its derivees.
*/
class CanvasCustomSpriteSpriteBase_Base : public ::canvas::BaseMutexHelper< CanvasCustomSpriteBase_Base >,
public Sprite
{
};
typedef ::canvas::CanvasCustomSpriteBase< CanvasCustomSpriteSpriteBase_Base,
SpriteHelper,
CanvasHelper,
::osl::MutexGuard,
::cppu::OWeakObject > CanvasCustomSpriteBaseT;
/* Definition of CanvasCustomSprite class */
class CanvasCustomSprite : public CanvasCustomSpriteBaseT,
public RepaintTarget,
public SurfaceProvider
{
public:
/** Create a custom sprite
@param rSpriteSize
Size of the sprite in pixel
@param rRefDevice
Associated output device
@param rSpriteCanvas
Target canvas
@param rDevice
Target DX device
*/
CanvasCustomSprite( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteCanvasRef& rRefDevice );
virtual void SAL_CALL disposing();
// Forwarding the XComponent implementation to the
// cppu::ImplHelper templated base
// Classname Base doing refcount Base implementing the XComponent interface
// | | |
// V V V
DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( CanvasCustomSprite, CanvasCustomSpriteBase_Base, ::cppu::WeakComponentImplHelperBase );
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
// Sprite
virtual void redraw( ::cairo::Cairo* pCairo,
bool bBufferedUpdate ) const;
virtual void redraw( ::cairo::Cairo* pCairo,
const ::basegfx::B2DPoint& rOrigOutputPos,
bool bBufferedUpdate ) const;
// RepaintTarget
virtual bool repaint( ::cairo::Surface* pSurface,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// SurfaceProvider
virtual ::cairo::Surface* changeSurface( bool bHasAlpha, bool bCopyContent );
private:
/** MUST hold here, too, since CanvasHelper only contains a
raw pointer (without refcounting)
*/
SpriteCanvasRef mpSpriteCanvas;
::cairo::Surface* mpBufferSurface;
::basegfx::B2ISize maSize;
};
}
#endif /* _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX */
<commit_msg>INTEGRATION: CWS canvas05 (1.2.94); FILE MERGED 2008/04/21 07:32:01 thb 1.2.94.4: RESYNC: (1.2-1.3); FILE MERGED 2008/04/02 22:56:27 thb 1.2.94.3: Reworked Surface class to abstract interface; changed all manual refcount handling to RAII 2008/03/28 23:38:46 thb 1.2.94.2: Backbuffer-less canvas implementation on top of cairo 2008/03/18 22:00:56 thb 1.2.94.1: Implementing non-backbuffered canvas for cairocanvas as well - reworked to share most of the code<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: cairo_canvascustomsprite.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX
#define _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX
#include <cppuhelper/compbase4.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/rendering/XCustomSprite.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2isize.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/canvascustomspritebase.hxx>
#include "cairo_sprite.hxx"
#include "cairo_cairo.hxx"
#include "cairo_canvashelper.hxx"
#include "cairo_repainttarget.hxx"
#include "cairo_spritehelper.hxx"
#include "cairo_spritecanvas.hxx"
namespace cairocanvas
{
typedef ::cppu::WeakComponentImplHelper4< ::com::sun::star::rendering::XCustomSprite,
::com::sun::star::rendering::XBitmapCanvas,
::com::sun::star::rendering::XIntegerBitmap,
::com::sun::star::lang::XServiceInfo > CanvasCustomSpriteBase_Base;
/** Mixin Sprite
Have to mixin the Sprite interface before deriving from
::canvas::CanvasCustomSpriteBase, as this template should
already implement some of those interface methods.
The reason why this appears kinda convoluted is the fact that
we cannot specify non-IDL types as WeakComponentImplHelperN
template args, and furthermore, don't want to derive
::canvas::CanvasCustomSpriteBase directly from
::canvas::Sprite (because derivees of
::canvas::CanvasCustomSpriteBase have to explicitely forward
the XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
anyway). Basically, ::canvas::CanvasCustomSpriteBase should
remain a base class that provides implementation, not to
enforce any specific interface on its derivees.
*/
class CanvasCustomSpriteSpriteBase_Base : public ::canvas::BaseMutexHelper< CanvasCustomSpriteBase_Base >,
public Sprite,
public SurfaceProvider
{
};
typedef ::canvas::CanvasCustomSpriteBase< CanvasCustomSpriteSpriteBase_Base,
SpriteHelper,
CanvasHelper,
::osl::MutexGuard,
::cppu::OWeakObject > CanvasCustomSpriteBaseT;
/* Definition of CanvasCustomSprite class */
class CanvasCustomSprite : public CanvasCustomSpriteBaseT,
public RepaintTarget
{
public:
/** Create a custom sprite
@param rSpriteSize
Size of the sprite in pixel
@param rRefDevice
Associated output device
@param rSpriteCanvas
Target canvas
@param rDevice
Target DX device
*/
CanvasCustomSprite( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteCanvasRef& rRefDevice );
virtual void SAL_CALL disposing();
// Forwarding the XComponent implementation to the
// cppu::ImplHelper templated base
// Classname Base doing refcount Base implementing the XComponent interface
// | | |
// V V V
DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( CanvasCustomSprite, CanvasCustomSpriteBase_Base, ::cppu::WeakComponentImplHelperBase );
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
// Sprite
virtual void redraw( const ::cairo::CairoSharedPtr& pCairo,
bool bBufferedUpdate ) const;
virtual void redraw( const ::cairo::CairoSharedPtr& pCairo,
const ::basegfx::B2DPoint& rOrigOutputPos,
bool bBufferedUpdate ) const;
// RepaintTarget
virtual bool repaint( const ::cairo::SurfaceSharedPtr& pSurface,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// SurfaceProvider
virtual SurfaceSharedPtr getSurface();
virtual SurfaceSharedPtr createSurface( const ::basegfx::B2ISize& rSize, Content aContent = CAIRO_CONTENT_COLOR_ALPHA );
virtual SurfaceSharedPtr createSurface( ::Bitmap& rBitmap );
virtual SurfaceSharedPtr changeSurface( bool bHasAlpha, bool bCopyContent );
virtual OutputDevice* getOutputDevice();
private:
/** MUST hold here, too, since CanvasHelper only contains a
raw pointer (without refcounting)
*/
SpriteCanvasRef mpSpriteCanvas;
::cairo::SurfaceSharedPtr mpBufferSurface;
::basegfx::B2ISize maSize;
};
}
#endif /* _CAIROCANVAS_CANVASCUSTOMSPRITE_HXX */
<|endoftext|>
|
<commit_before>// @(#)root/foundation:
// Author: Axel Naumann, Enrico Guiraud, June 2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TypeTraits
#define ROOT_TypeTraits
#include <memory> // shared_ptr, unique_ptr for IsSmartOrDumbPtr
#include <type_traits>
#include <vector> // for IsContainer
#include "ROOT/RSpan.hxx" // for IsContainer
namespace ROOT {
/// ROOT type_traits extensions
namespace TypeTraits {
/// Lightweight storage for a collection of types.
/// Differently from std::tuple, no instantiation of objects of stored types is performed
template <typename... Types>
struct TypeList {
static constexpr std::size_t list_size = sizeof...(Types);
};
} // end ns TypeTraits
namespace Detail {
template <typename T> constexpr auto HasCallOp(int /*goodOverload*/) -> decltype(&T::operator(), true) { return true; }
template <typename T> constexpr bool HasCallOp(char /*badOverload*/) { return false; }
/// Extract types from the signature of a callable object. See CallableTraits.
template <typename T, bool HasCallOp = ROOT::Detail::HasCallOp<T>(0)>
struct CallableTraitsImpl {};
// Extract signature of operator() and delegate to the appropriate CallableTraitsImpl overloads
template <typename T>
struct CallableTraitsImpl<T, true> {
using arg_types = typename CallableTraitsImpl<decltype(&T::operator())>::arg_types;
using arg_types_nodecay = typename CallableTraitsImpl<decltype(&T::operator())>::arg_types_nodecay;
using ret_type = typename CallableTraitsImpl<decltype(&T::operator())>::ret_type;
};
// lambdas, std::function, const member functions
template <typename R, typename T, typename... Args>
struct CallableTraitsImpl<R (T::*)(Args...) const, false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// mutable lambdas and functor classes, non-const member functions
template <typename R, typename T, typename... Args>
struct CallableTraitsImpl<R (T::*)(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// function pointers
template <typename R, typename... Args>
struct CallableTraitsImpl<R (*)(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// free functions
template <typename R, typename... Args>
struct CallableTraitsImpl<R(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
} // end ns Detail
namespace TypeTraits {
///\class ROOT::TypeTraits::
template <class T>
class IsSmartOrDumbPtr : public std::integral_constant<bool, std::is_pointer<T>::value> {
};
template <class P>
class IsSmartOrDumbPtr<std::shared_ptr<P>> : public std::true_type {
};
template <class P>
class IsSmartOrDumbPtr<std::unique_ptr<P>> : public std::true_type {
};
/// Check for container traits.
template <typename T>
struct IsContainer {
using Test_t = typename std::decay<T>::type;
template <typename A>
static constexpr bool Test(A *pt, A const *cpt = nullptr, decltype(pt->begin()) * = nullptr,
decltype(pt->end()) * = nullptr, decltype(cpt->begin()) * = nullptr,
decltype(cpt->end()) * = nullptr, typename A::iterator *pi = nullptr,
typename A::const_iterator *pci = nullptr)
{
using It_t = typename A::iterator;
using CIt_t = typename A::const_iterator;
using V_t = typename A::value_type;
return std::is_same<Test_t, std::vector<bool>>::value ||
(std::is_same<decltype(pt->begin()), It_t>::value && std::is_same<decltype(pt->end()), It_t>::value &&
std::is_same<decltype(cpt->begin()), CIt_t>::value && std::is_same<decltype(cpt->end()), CIt_t>::value &&
std::is_same<decltype(**pi), V_t &>::value && std::is_same<decltype(**pci), V_t const &>::value);
}
template <typename A>
static constexpr bool Test(...)
{
return false;
}
static constexpr bool value = Test<Test_t>(nullptr);
};
template<typename T>
struct IsContainer<std::span<T>> {
static constexpr bool value = true;
};
/// Checks for signed integers types that are not characters
template<class T>
struct IsSignedNumeral : std::integral_constant<bool,
std::is_integral<T>::value &&
std::is_signed<T>::value &&
!std::is_same<T, char>::value
> {};
/// Checks for unsigned integer types that are not characters
template<class T>
struct IsUnsignedNumeral : std::integral_constant<bool,
std::is_integral<T>::value &&
!std::is_signed<T>::value &&
!std::is_same<T, char>::value
> {};
/// Checks for floating point types (that are not characters)
template<class T>
using IsFloatNumeral = std::is_floating_point<T>;
/// Extract types from the signature of a callable object.
/// The `CallableTraits` struct contains three type aliases:
/// - arg_types: a `TypeList` of all types in the signature, decayed through std::decay
/// - arg_types_nodecay: a `TypeList` of all types in the signature, including cv-qualifiers
template<typename F>
using CallableTraits = ROOT::Detail::CallableTraitsImpl<F>;
// Return first of a variadic list of types.
template <typename T, typename... Rest>
struct TakeFirstType {
using type = T;
};
template <typename... Types>
using TakeFirstType_t = typename TakeFirstType<Types...>::type;
// Remove first type from a variadic list of types, return a TypeList containing the rest.
// e.g. RemoveFirst_t<A,B,C> is TypeList<B,C>
template <typename T, typename... Rest>
struct RemoveFirst {
using type = TypeList<Rest...>;
};
template <typename... Args>
using RemoveFirst_t = typename RemoveFirst<Args...>::type;
/// Return first of possibly many template parameters.
/// For non-template types, the result is void
/// e.g. TakeFirstParameter<U<A,B>> is A
/// TakeFirstParameter<T> is void
template <typename T>
struct TakeFirstParameter {
using type = void;
};
template <template <typename...> class Template, typename T, typename... Rest>
struct TakeFirstParameter<Template<T, Rest...>> {
using type = T;
};
template <typename T>
using TakeFirstParameter_t = typename TakeFirstParameter<T>::type;
/// Remove first of possibly many template parameters.
/// e.g. RemoveFirstParameter_t<U<A,B>> is U<B>
template <typename>
struct RemoveFirstParameter {
};
template <typename T, template <typename...> class U, typename... Rest>
struct RemoveFirstParameter<U<T, Rest...>> {
using type = U<Rest...>;
};
template <typename T>
using RemoveFirstParameter_t = typename RemoveFirstParameter<T>::type;
} // ns TypeTraits
} // ns ROOT
#endif // ROOT_TTypeTraits
<commit_msg>[Core] Add a static utility to verify if a type is iterable<commit_after>// @(#)root/foundation:
// Author: Axel Naumann, Enrico Guiraud, June 2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TypeTraits
#define ROOT_TypeTraits
#include <memory> // shared_ptr, unique_ptr for IsSmartOrDumbPtr
#include <type_traits>
#include <vector> // for IsContainer
#include "ROOT/RSpan.hxx" // for IsContainer
namespace ROOT {
/// ROOT type_traits extensions
namespace TypeTraits {
/// Lightweight storage for a collection of types.
/// Differently from std::tuple, no instantiation of objects of stored types is performed
template <typename... Types>
struct TypeList {
static constexpr std::size_t list_size = sizeof...(Types);
};
} // end ns TypeTraits
namespace Detail {
template <typename T> constexpr auto HasCallOp(int /*goodOverload*/) -> decltype(&T::operator(), true) { return true; }
template <typename T> constexpr bool HasCallOp(char /*badOverload*/) { return false; }
/// Extract types from the signature of a callable object. See CallableTraits.
template <typename T, bool HasCallOp = ROOT::Detail::HasCallOp<T>(0)>
struct CallableTraitsImpl {};
// Extract signature of operator() and delegate to the appropriate CallableTraitsImpl overloads
template <typename T>
struct CallableTraitsImpl<T, true> {
using arg_types = typename CallableTraitsImpl<decltype(&T::operator())>::arg_types;
using arg_types_nodecay = typename CallableTraitsImpl<decltype(&T::operator())>::arg_types_nodecay;
using ret_type = typename CallableTraitsImpl<decltype(&T::operator())>::ret_type;
};
// lambdas, std::function, const member functions
template <typename R, typename T, typename... Args>
struct CallableTraitsImpl<R (T::*)(Args...) const, false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// mutable lambdas and functor classes, non-const member functions
template <typename R, typename T, typename... Args>
struct CallableTraitsImpl<R (T::*)(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// function pointers
template <typename R, typename... Args>
struct CallableTraitsImpl<R (*)(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
// free functions
template <typename R, typename... Args>
struct CallableTraitsImpl<R(Args...), false> {
using arg_types = ROOT::TypeTraits::TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = ROOT::TypeTraits::TypeList<Args...>;
using ret_type = R;
};
} // end ns Detail
namespace TypeTraits {
///\class ROOT::TypeTraits::
template <class T>
class IsSmartOrDumbPtr : public std::integral_constant<bool, std::is_pointer<T>::value> {
};
template <class P>
class IsSmartOrDumbPtr<std::shared_ptr<P>> : public std::true_type {
};
template <class P>
class IsSmartOrDumbPtr<std::unique_ptr<P>> : public std::true_type {
};
/// Check for container traits.
template <typename T>
struct IsContainer {
using Test_t = typename std::decay<T>::type;
template <typename A>
static constexpr bool Test(A *pt, A const *cpt = nullptr, decltype(pt->begin()) * = nullptr,
decltype(pt->end()) * = nullptr, decltype(cpt->begin()) * = nullptr,
decltype(cpt->end()) * = nullptr, typename A::iterator *pi = nullptr,
typename A::const_iterator *pci = nullptr)
{
using It_t = typename A::iterator;
using CIt_t = typename A::const_iterator;
using V_t = typename A::value_type;
return std::is_same<Test_t, std::vector<bool>>::value ||
(std::is_same<decltype(pt->begin()), It_t>::value && std::is_same<decltype(pt->end()), It_t>::value &&
std::is_same<decltype(cpt->begin()), CIt_t>::value && std::is_same<decltype(cpt->end()), CIt_t>::value &&
std::is_same<decltype(**pi), V_t &>::value && std::is_same<decltype(**pci), V_t const &>::value);
}
template <typename A>
static constexpr bool Test(...)
{
return false;
}
static constexpr bool value = Test<Test_t>(nullptr);
};
template<typename T>
struct IsContainer<std::span<T>> {
static constexpr bool value = true;
};
/// Checks for signed integers types that are not characters
template<class T>
struct IsSignedNumeral : std::integral_constant<bool,
std::is_integral<T>::value &&
std::is_signed<T>::value &&
!std::is_same<T, char>::value
> {};
/// Checks for unsigned integer types that are not characters
template<class T>
struct IsUnsignedNumeral : std::integral_constant<bool,
std::is_integral<T>::value &&
!std::is_signed<T>::value &&
!std::is_same<T, char>::value
> {};
/// Checks for floating point types (that are not characters)
template<class T>
using IsFloatNumeral = std::is_floating_point<T>;
/// Extract types from the signature of a callable object.
/// The `CallableTraits` struct contains three type aliases:
/// - arg_types: a `TypeList` of all types in the signature, decayed through std::decay
/// - arg_types_nodecay: a `TypeList` of all types in the signature, including cv-qualifiers
template<typename F>
using CallableTraits = ROOT::Detail::CallableTraitsImpl<F>;
// Return first of a variadic list of types.
template <typename T, typename... Rest>
struct TakeFirstType {
using type = T;
};
template <typename... Types>
using TakeFirstType_t = typename TakeFirstType<Types...>::type;
// Remove first type from a variadic list of types, return a TypeList containing the rest.
// e.g. RemoveFirst_t<A,B,C> is TypeList<B,C>
template <typename T, typename... Rest>
struct RemoveFirst {
using type = TypeList<Rest...>;
};
template <typename... Args>
using RemoveFirst_t = typename RemoveFirst<Args...>::type;
/// Return first of possibly many template parameters.
/// For non-template types, the result is void
/// e.g. TakeFirstParameter<U<A,B>> is A
/// TakeFirstParameter<T> is void
template <typename T>
struct TakeFirstParameter {
using type = void;
};
template <template <typename...> class Template, typename T, typename... Rest>
struct TakeFirstParameter<Template<T, Rest...>> {
using type = T;
};
template <typename T>
using TakeFirstParameter_t = typename TakeFirstParameter<T>::type;
/// Remove first of possibly many template parameters.
/// e.g. RemoveFirstParameter_t<U<A,B>> is U<B>
template <typename>
struct RemoveFirstParameter {
};
template <typename T, template <typename...> class U, typename... Rest>
struct RemoveFirstParameter<U<T, Rest...>> {
using type = U<Rest...>;
};
template <typename T>
using RemoveFirstParameter_t = typename RemoveFirstParameter<T>::type;
template <typename T>
struct HasBeginAndEnd {
template <typename V>
static char (&b(
typename std::enable_if<std::is_same<decltype(static_cast<typename V::const_iterator (V::*)() const>(&V::begin)),
typename V::const_iterator (V::*)() const>::value,
void>::type *))[1];
template <typename V>
static char (&b(...))[2];
template <typename V>
static char (
&e(typename std::enable_if<std::is_same<decltype(static_cast<typename V::const_iterator (V::*)() const>(&V::end)),
typename V::const_iterator (V::*)() const>::value,
void>::type *))[1];
template <typename V>
static char (&e(...))[2];
static constexpr bool const begin_value = sizeof(b<T>(0)) == 1;
static constexpr bool const end_value = sizeof(e<T>(0)) == 1;
static constexpr bool const value = begin_value && end_value;
};
} // ns TypeTraits
} // ns ROOT
#endif // ROOT_TTypeTraits
<|endoftext|>
|
<commit_before>// @(#)root/foundation:
// Author: Axel Naumann, Enrico Guiraud, June 2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TypeTraits
#define ROOT_TypeTraits
#include <memory> // shared_ptr, unique_ptr for IsSmartOrDumbPtr
#include <type_traits>
#include <vector> // for IsContainer
#include "ROOT/RArrayView.hxx" // for IsContainer
namespace ROOT {
/// ROOT type_traits extensions
namespace TypeTraits {
///\class ROOT::TypeTraits::
template <class T>
class IsSmartOrDumbPtr : public std::integral_constant<bool, std::is_pointer<T>::value> {
};
template <class P>
class IsSmartOrDumbPtr<std::shared_ptr<P>> : public std::true_type {
};
template <class P>
class IsSmartOrDumbPtr<std::unique_ptr<P>> : public std::true_type {
};
/// Check for container traits.
template <typename T>
struct IsContainer {
using Test_t = typename std::decay<T>::type;
template <typename A>
static constexpr bool Test(A *pt, A const *cpt = nullptr, decltype(pt->begin()) * = nullptr,
decltype(pt->end()) * = nullptr, decltype(cpt->begin()) * = nullptr,
decltype(cpt->end()) * = nullptr, typename A::iterator *pi = nullptr,
typename A::const_iterator *pci = nullptr)
{
using It_t = typename A::iterator;
using CIt_t = typename A::const_iterator;
using V_t = typename A::value_type;
return std::is_same<Test_t, std::vector<bool>>::value ||
(std::is_same<decltype(pt->begin()), It_t>::value && std::is_same<decltype(pt->end()), It_t>::value &&
std::is_same<decltype(cpt->begin()), CIt_t>::value && std::is_same<decltype(cpt->end()), CIt_t>::value &&
std::is_same<decltype(**pi), V_t &>::value && std::is_same<decltype(**pci), V_t const &>::value);
}
template <typename A>
static constexpr bool Test(...)
{
return false;
}
static constexpr bool value = Test<Test_t>(nullptr);
};
template<typename T>
struct IsContainer<std::array_view<T>> {
static constexpr bool value = true;
};
/// Lightweight storage for a collection of types.
/// Differently from std::tuple, no instantiation of objects of stored types is performed
template <typename... Types>
struct TypeList {
static constexpr std::size_t list_size = sizeof...(Types);
};
/// Extract types from the signature of a callable object.
template <typename T>
struct CallableTraits {
using arg_types = typename CallableTraits<decltype(&T::operator())>::arg_types;
using arg_types_nodecay = typename CallableTraits<decltype(&T::operator())>::arg_types_nodecay;
using ret_type = typename CallableTraits<decltype(&T::operator())>::ret_type;
};
// lambdas and std::function
template <typename R, typename T, typename... Args>
struct CallableTraits<R (T::*)(Args...) const> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// mutable lambdas and functor classes
template <typename R, typename T, typename... Args>
struct CallableTraits<R (T::*)(Args...)> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// function pointers
template <typename R, typename... Args>
struct CallableTraits<R (*)(Args...)> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// free functions
template <typename R, typename... Args>
struct CallableTraits<R(Args...)> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// Return first of a variadic list of types.
template <typename T, typename... Rest>
struct TakeFirstType {
using type = T;
};
template <typename... Types>
using TakeFirstType_t = typename TakeFirstType<Types...>::type;
// Remove first type from a variadic list of types, return a TypeList containing the rest.
// e.g. RemoveFirst_t<A,B,C> is TypeList<B,C>
template <typename T, typename... Rest>
struct RemoveFirst {
using type = TypeList<Rest...>;
};
template <typename... Args>
using RemoveFirst_t = typename RemoveFirst<Args...>::type;
/// Return first of possibly many template parameters.
/// For non-template types, the result is the type itself.
/// e.g. TakeFirstParameter<U<A,B>> is A
/// TakeFirstParameter<T> is T
template <typename T>
struct TakeFirstParameter {
using type = void;
};
template <template <typename...> class Template, typename T, typename... Rest>
struct TakeFirstParameter<Template<T, Rest...>> {
using type = T;
};
template <typename T>
using TakeFirstParameter_t = typename TakeFirstParameter<T>::type;
/// Remove first of possibly many template parameters.
/// e.g. RemoveFirstParameter_t<U<A,B>> is U<B>
template <typename>
struct RemoveFirstParameter {
};
template <typename T, template <typename...> class U, typename... Rest>
struct RemoveFirstParameter<U<T, Rest...>> {
using type = U<Rest...>;
};
template <typename T>
using RemoveFirstParameter_t = typename RemoveFirstParameter<T>::type;
} // ns TypeTraits
} // ns ROOT
#endif // ROOT_TTypeTraits
<commit_msg>[TypeTraits] Make CallableTraits SFINAE-friendly<commit_after>// @(#)root/foundation:
// Author: Axel Naumann, Enrico Guiraud, June 2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TypeTraits
#define ROOT_TypeTraits
#include <memory> // shared_ptr, unique_ptr for IsSmartOrDumbPtr
#include <type_traits>
#include <vector> // for IsContainer
#include "ROOT/RArrayView.hxx" // for IsContainer
namespace ROOT {
namespace Detail {
template <typename T> constexpr bool HasCallOp(decltype(&T::operator())*) { return true; }
template <typename T> constexpr bool HasCallOp(...) { return false; }
}
/// ROOT type_traits extensions
namespace TypeTraits {
///\class ROOT::TypeTraits::
template <class T>
class IsSmartOrDumbPtr : public std::integral_constant<bool, std::is_pointer<T>::value> {
};
template <class P>
class IsSmartOrDumbPtr<std::shared_ptr<P>> : public std::true_type {
};
template <class P>
class IsSmartOrDumbPtr<std::unique_ptr<P>> : public std::true_type {
};
/// Check for container traits.
template <typename T>
struct IsContainer {
using Test_t = typename std::decay<T>::type;
template <typename A>
static constexpr bool Test(A *pt, A const *cpt = nullptr, decltype(pt->begin()) * = nullptr,
decltype(pt->end()) * = nullptr, decltype(cpt->begin()) * = nullptr,
decltype(cpt->end()) * = nullptr, typename A::iterator *pi = nullptr,
typename A::const_iterator *pci = nullptr)
{
using It_t = typename A::iterator;
using CIt_t = typename A::const_iterator;
using V_t = typename A::value_type;
return std::is_same<Test_t, std::vector<bool>>::value ||
(std::is_same<decltype(pt->begin()), It_t>::value && std::is_same<decltype(pt->end()), It_t>::value &&
std::is_same<decltype(cpt->begin()), CIt_t>::value && std::is_same<decltype(cpt->end()), CIt_t>::value &&
std::is_same<decltype(**pi), V_t &>::value && std::is_same<decltype(**pci), V_t const &>::value);
}
template <typename A>
static constexpr bool Test(...)
{
return false;
}
static constexpr bool value = Test<Test_t>(nullptr);
};
template<typename T>
struct IsContainer<std::array_view<T>> {
static constexpr bool value = true;
};
/// Lightweight storage for a collection of types.
/// Differently from std::tuple, no instantiation of objects of stored types is performed
template <typename... Types>
struct TypeList {
static constexpr std::size_t list_size = sizeof...(Types);
};
/// Extract types from the signature of a callable object.
template <typename T, bool HasCallOp = ROOT::Detail::HasCallOp<T>(nullptr)>
struct CallableTraits {};
// Extract signature of operator() and delegate to the appropriate CallableTraits overloads
template <typename T>
struct CallableTraits<T, true> {
using arg_types = typename CallableTraits<decltype(&T::operator())>::arg_types;
using arg_types_nodecay = typename CallableTraits<decltype(&T::operator())>::arg_types_nodecay;
using ret_type = typename CallableTraits<decltype(&T::operator())>::ret_type;
};
// lambdas, std::function, const member functions
template <typename R, typename T, typename... Args>
struct CallableTraits<R (T::*)(Args...) const, false> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// mutable lambdas and functor classes, non-const member functions
template <typename R, typename T, typename... Args>
struct CallableTraits<R (T::*)(Args...), false> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// function pointers
template <typename R, typename... Args>
struct CallableTraits<R (*)(Args...), false> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// free functions
template <typename R, typename... Args>
struct CallableTraits<R(Args...), false> {
using arg_types = TypeList<typename std::decay<Args>::type...>;
using arg_types_nodecay = TypeList<Args...>;
using ret_type = R;
};
// Return first of a variadic list of types.
template <typename T, typename... Rest>
struct TakeFirstType {
using type = T;
};
template <typename... Types>
using TakeFirstType_t = typename TakeFirstType<Types...>::type;
// Remove first type from a variadic list of types, return a TypeList containing the rest.
// e.g. RemoveFirst_t<A,B,C> is TypeList<B,C>
template <typename T, typename... Rest>
struct RemoveFirst {
using type = TypeList<Rest...>;
};
template <typename... Args>
using RemoveFirst_t = typename RemoveFirst<Args...>::type;
/// Return first of possibly many template parameters.
/// For non-template types, the result is the type itself.
/// e.g. TakeFirstParameter<U<A,B>> is A
/// TakeFirstParameter<T> is T
template <typename T>
struct TakeFirstParameter {
using type = void;
};
template <template <typename...> class Template, typename T, typename... Rest>
struct TakeFirstParameter<Template<T, Rest...>> {
using type = T;
};
template <typename T>
using TakeFirstParameter_t = typename TakeFirstParameter<T>::type;
/// Remove first of possibly many template parameters.
/// e.g. RemoveFirstParameter_t<U<A,B>> is U<B>
template <typename>
struct RemoveFirstParameter {
};
template <typename T, template <typename...> class U, typename... Rest>
struct RemoveFirstParameter<U<T, Rest...>> {
using type = U<Rest...>;
};
template <typename T>
using RemoveFirstParameter_t = typename RemoveFirstParameter<T>::type;
} // ns TypeTraits
} // ns ROOT
#endif // ROOT_TTypeTraits
<|endoftext|>
|
<commit_before>#include "DissentTest.hpp"
#include "RoundTest.hpp"
#include "BulkRoundHelpers.hpp"
#include "ShuffleRoundHelpers.hpp"
namespace Dissent {
namespace Tests {
class BadBlogDropRound : public BlogDropRound, public Triggerable {
public:
explicit BadBlogDropRound(const QSharedPointer<Parameters> ¶ms,
const Group &group,
const PrivateIdentity &ident,
const Id &round_id,
const QSharedPointer<Network> &network,
GetDataCallback &get_data,
const QSharedPointer<BuddyMonitor> &bm,
CreateRound create_shuffle,
bool verify_proofs) :
BlogDropRound(params, group, ident, round_id, network, get_data, bm,
create_shuffle, verify_proofs)
{
}
virtual QString ToString() const
{
return BlogDropRound::ToString() + " BAD!";
}
virtual bool BadClient() const
{
qDebug() << "Bad client called";
const_cast<BadBlogDropRound *>(this)->Triggerable::SetTriggered();
return true;
}
};
template <Crypto::BlogDrop::Parameters::ParameterType TYPE, typename SHUFFLE, bool VERIFY>
QSharedPointer<Round> TCreateBadBlogDropRound(
const Round::Group &group,
const Round::PrivateIdentity &ident,
const Connections::Id &round_id,
const QSharedPointer<Connections::Network> &network,
Messaging::GetDataCallback &get_data,
const QSharedPointer<BuddyMonitor> &bm)
{
QSharedPointer<Round> round(new BadBlogDropRound(
Crypto::BlogDrop::Parameters::GetParameters(TYPE, round_id.GetByteArray()),
group, ident, round_id, network, get_data, bm,
&TCreateRound<SHUFFLE>, VERIFY));
round->SetSharedPointer(round);
return round;
}
TEST(BlogDropRoundTest, BasicManagedReactive)
{
RoundTest_Basic(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, BasicManagedProactive)
{
RoundTest_Basic(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, MultiRoundManaged)
{
RoundTest_MultiRound(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, AddOne)
{
RoundTest_AddOne(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, PeerDisconnectMiddleManaged)
{
RoundTest_PeerDisconnectMiddle(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, PeerTransientIssueMiddle)
{
RoundTest_PeerDisconnectMiddle(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, BadClientReactive)
{
RoundTest_BadGuy(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
SessionCreator(TCreateBadBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup, TBadGuyCB<BadBlogDropRound>);
}
TEST(BlogDropRoundTest, BadClientProactive)
{
RoundTest_BadGuy(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
SessionCreator(TCreateBadBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
Group::ManagedSubgroup, TBadGuyCB<BadBlogDropRound>);
}
}
}
<commit_msg>[Tests] Disabled BlogDropBad* due to issues with test implementation.<commit_after>#include "DissentTest.hpp"
#include "RoundTest.hpp"
#include "BulkRoundHelpers.hpp"
#include "ShuffleRoundHelpers.hpp"
namespace Dissent {
namespace Tests {
class BadBlogDropRound : public BlogDropRound, public Triggerable {
public:
explicit BadBlogDropRound(const QSharedPointer<Parameters> ¶ms,
const Group &group,
const PrivateIdentity &ident,
const Id &round_id,
const QSharedPointer<Network> &network,
GetDataCallback &get_data,
const QSharedPointer<BuddyMonitor> &bm,
CreateRound create_shuffle,
bool verify_proofs) :
BlogDropRound(params, group, ident, round_id, network, get_data, bm,
create_shuffle, verify_proofs)
{
}
virtual QString ToString() const
{
return BlogDropRound::ToString() + " BAD!";
}
virtual bool BadClient() const
{
qDebug() << "Bad client called";
const_cast<BadBlogDropRound *>(this)->Triggerable::SetTriggered();
return true;
}
};
template <Crypto::BlogDrop::Parameters::ParameterType TYPE, typename SHUFFLE, bool VERIFY>
QSharedPointer<Round> TCreateBadBlogDropRound(
const Round::Group &group,
const Round::PrivateIdentity &ident,
const Connections::Id &round_id,
const QSharedPointer<Connections::Network> &network,
Messaging::GetDataCallback &get_data,
const QSharedPointer<BuddyMonitor> &bm)
{
QSharedPointer<Round> round(new BadBlogDropRound(
Crypto::BlogDrop::Parameters::GetParameters(TYPE, round_id.GetByteArray()),
group, ident, round_id, network, get_data, bm,
&TCreateRound<SHUFFLE>, VERIFY));
round->SetSharedPointer(round);
return round;
}
TEST(BlogDropRoundTest, BasicManagedReactive)
{
RoundTest_Basic(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, BasicManagedProactive)
{
RoundTest_Basic(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, MultiRoundManaged)
{
RoundTest_MultiRound(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, AddOne)
{
RoundTest_AddOne(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, PeerDisconnectMiddleManaged)
{
RoundTest_PeerDisconnectMiddle(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
TEST(BlogDropRoundTest, PeerTransientIssueMiddle)
{
RoundTest_PeerDisconnectMiddle(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup);
}
/**
* @TODO these tests are disabled until we fix the session to notify us
* when we attempted to send data but were unsuccessful
TEST(BlogDropRoundTest, BadClientReactive)
{
RoundTest_BadGuy(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
SessionCreator(TCreateBadBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, false>),
Group::ManagedSubgroup, TBadGuyCB<BadBlogDropRound>);
}
TEST(BlogDropRoundTest, BadClientProactive)
{
RoundTest_BadGuy(
SessionCreator(TCreateBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
SessionCreator(TCreateBadBlogDropRound<
Parameters::ParameterType_CppECHashingProduction, NullRound, true>),
Group::ManagedSubgroup, TBadGuyCB<BadBlogDropRound>);
}
*/
}
}
<|endoftext|>
|
<commit_before>#include "TimeWarpEventDispatcher.hpp"
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include <cmath>
#include <limits> // for std::numeric_limits<>::max();
#include <algorithm> // for std::min
#include <chrono> // for std::chrono::steady_clock
#include <cstring> // for std::memset
#include "Event.hpp"
#include "EventDispatcher.hpp"
#include "LTSFQueue.hpp"
#include "Partitioner.hpp"
#include "SimulationObject.hpp"
#include "TimeWarpMPICommunicationManager.hpp"
#include "TimeWarpMatternGVTManager.hpp"
#include "TimeWarpStateManager.hpp"
#include "TimeWarpOutputManager.hpp"
#include "TimeWarpEventSet.hpp"
#include "utility/memory.hpp"
#include "utility/warnings.hpp"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::EventMessage)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::Event)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::NegativeEvent)
namespace warped {
thread_local unsigned int TimeWarpEventDispatcher::thread_id;
TimeWarpEventDispatcher::TimeWarpEventDispatcher(unsigned int max_sim_time,
unsigned int num_worker_threads,
std::shared_ptr<TimeWarpCommunicationManager> comm_manager,
std::unique_ptr<TimeWarpEventSet> event_set,
std::unique_ptr<TimeWarpGVTManager> gvt_manager,
std::unique_ptr<TimeWarpStateManager> state_manager,
std::unique_ptr<TimeWarpOutputManager> output_manager,
std::unique_ptr<TimeWarpFileStreamManager> twfs_manager) :
EventDispatcher(max_sim_time), num_worker_threads_(num_worker_threads),
comm_manager_(comm_manager), event_set_(std::move(event_set)),
gvt_manager_(std::move(gvt_manager)), state_manager_(std::move(state_manager)),
output_manager_(std::move(output_manager)), twfs_manager_(std::move(twfs_manager)) {}
void TimeWarpEventDispatcher::startSimulation(const std::vector<std::vector<SimulationObject*>>&
objects) {
initialize(objects);
thread_id = num_worker_threads_;
unused<unsigned int>(std::move(thread_id));// TODO
// Create worker threads
std::vector<std::thread> threads;
for (unsigned int i = 0; i < num_worker_threads_; ++i) {
auto thread(std::thread {&TimeWarpEventDispatcher::processEvents, this, i});
thread.detach();
threads.push_back(std::move(thread));
}
MessageFlags msg_flags = MessageFlags::None;
auto gvt_start = std::chrono::steady_clock::now();
bool calculate_gvt = false;
// Flag that says we have started calculating minimum lvt of the objects on this node
bool started_min_lvt = false;
// Master thread main loop
while (gvt_manager_->getGVT() < max_sim_time_) {
MessageFlags flags = comm_manager_->dispatchReceivedMessages();
// We may already have a pending token to send
msg_flags |= flags;
if (PENDING_MATTERN_TOKEN(msg_flags) && (min_lvt_flag_.load() == 0) && !started_min_lvt) {
min_lvt_flag_.store(num_worker_threads_);
started_min_lvt = true;
}
if (GVT_UPDATE(msg_flags)) {
fossilCollect(gvt_manager_->getGVT());
msg_flags &= ~MessageFlags::GVTUpdate;
auto mattern_gvt_manager = dynamic_cast<TimeWarpMatternGVTManager*>(gvt_manager_.get());
mattern_gvt_manager->reset();
}
if (calculate_gvt && comm_manager_->getID() == 0) {
// This will only return true if a token is not in circulation and we need to
// start another one.
MessageFlags flags = gvt_manager_->calculateGVT();
msg_flags |= flags;
if (PENDING_MATTERN_TOKEN(msg_flags)) {
min_lvt_flag_.store(num_worker_threads_);
started_min_lvt = true;
calculate_gvt = false;
}
} else if (comm_manager_->getID() == 0) {
auto now = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>
(now - gvt_start).count();
if (elapsed >= gvt_manager_->getGVTPeriod()) {
calculate_gvt = true;
gvt_start = now;
}
}
if (PENDING_MATTERN_TOKEN(msg_flags) && (min_lvt_flag_.load() == 0) && started_min_lvt) {
auto mattern_gvt_manager = dynamic_cast<TimeWarpMatternGVTManager*>(gvt_manager_.get());
unsigned int local_min_lvt = getMinimumLVT();
mattern_gvt_manager->sendMatternGVTToken(local_min_lvt);
msg_flags &= ~MessageFlags::PendingMatternToken;
started_min_lvt = false;
}
sendRemoteEvents();
}
comm_manager_->finalize();
}
void TimeWarpEventDispatcher::processEvents(unsigned int id) {
thread_id = id;
while (gvt_manager_->getGVT() < max_sim_time_) {
local_min_lvt_flag_[thread_id] = min_lvt_flag_.load();
std::shared_ptr<Event> event = nullptr; //TODO, get next event
if (event != nullptr) {
unsigned int current_object_id = local_object_id_by_name_[event->receiverName()];
SimulationObject* current_object = objects_by_name_[event->receiverName()];
// Handle a negative event
if (event->event_type() == EventType::NEGATIVE) {
// event_set_->handleAntiMessage(current_object_id, std::move(event));
continue;
}
// Check to see if straggler and rollback if necessary
if (event->timestamp() < object_simulation_time_[current_object_id]) {
rollback(event->timestamp(), current_object_id, current_object);
} else {
if (local_min_lvt_flag_[thread_id] > 0 && !calculated_min_flag_[thread_id]) {
min_lvt_[thread_id] = std::min(send_min_[thread_id], event->timestamp());
min_lvt_flag_--;
}
}
// Update simulation time
object_simulation_time_[current_object_id] = event->timestamp();
twfs_manager_->setObjectCurrentTime(event->timestamp(), current_object_id);
// Save state
state_manager_->saveState(event->timestamp(), current_object_id, current_object);
// process event and get new events
auto new_events = current_object->receiveEvent(*event);
// Send new events
for (auto& e: new_events) {
auto object_id_it = local_object_id_by_name_.find(e->receiverName());
output_manager_->insertEvent(e, current_object_id);
if (object_id_it != local_object_id_by_name_.end()) {
// Local event
sendLocalEvent(e);
} else {
// Remote event
enqueueRemoteEvent(e, object_node_id_by_name_[e->receiverName()]);
}
}
}
}
}
MessageFlags TimeWarpEventDispatcher::receiveEventMessage(std::unique_ptr<TimeWarpKernelMessage>
kmsg) {
auto msg = unique_cast<TimeWarpKernelMessage, EventMessage>(std::move(kmsg));
gvt_manager_->setGvtInfo(msg->gvt_mattern_color);
unsigned int receiver_object_id = local_object_id_by_name_[msg->event->receiverName()];
unused<unsigned int>(std::move(receiver_object_id));
// event_set_->insertEvent(receiver_object_id, std::move(msg->event));
return MessageFlags::None;
}
void TimeWarpEventDispatcher::sendLocalEvent(std::shared_ptr<Event> event) {
unsigned int receiver_object_id = local_object_id_by_name_[event->receiverName()];
unused<unsigned int>(std::move(receiver_object_id));
//event_set_->insertEvent(receiver_object_id, event);
if (min_lvt_flag_.load() > 0 && !calculated_min_flag_[thread_id]) {
unsigned int send_min = send_min_[thread_id];
send_min_[thread_id] = std::min(send_min, event->timestamp());
}
}
void TimeWarpEventDispatcher::fossilCollect(unsigned int gvt) {
twfs_manager_->fossilCollectAll(gvt);
state_manager_->fossilCollectAll(gvt);
output_manager_->fossilCollectAll(gvt);
// event_set_->fossilCollectAll(gvt);
}
void TimeWarpEventDispatcher::cancelEvents(
std::unique_ptr<std::vector<std::shared_ptr<Event>>> events_to_cancel) {
if (events_to_cancel->empty()) {
return;
}
do {
auto event = events_to_cancel->back();
auto neg_event = std::make_shared<NegativeEvent>(event->receiverName(), event->senderName(),
event->timestamp());
events_to_cancel->pop_back();
unsigned int receiver_id = object_node_id_by_name_[event->receiverName()];
if (receiver_id != comm_manager_->getID()) {
enqueueRemoteEvent(neg_event, receiver_id);
} else {
sendLocalEvent(neg_event);
}
} while (!events_to_cancel->empty());
}
void TimeWarpEventDispatcher::rollback(unsigned int straggler_time, unsigned int local_object_id,
SimulationObject* object) {
twfs_manager_->rollback(straggler_time, local_object_id);
unsigned int restored_timestamp = state_manager_->restoreState(straggler_time, local_object_id,
object);
auto events_to_cancel = output_manager_->rollback(straggler_time, local_object_id);
if (events_to_cancel != nullptr) {
cancelEvents(std::move(events_to_cancel));
}
// event_set_->rollback(local_object_id, restored_timestamp);
coastForward(restored_timestamp, straggler_time);
}
void TimeWarpEventDispatcher::coastForward(unsigned int start_time, unsigned int stop_time) {
unsigned int current_time = start_time;
while (current_time < stop_time) {
std::shared_ptr<Event> event = nullptr; //TODO, get next event
unsigned int current_object_id = local_object_id_by_name_[event->receiverName()];
SimulationObject* current_object = objects_by_name_[event->receiverName()];
object_simulation_time_[current_object_id] = event->timestamp();
twfs_manager_->setObjectCurrentTime(event->timestamp(), current_object_id);
state_manager_->saveState(event->timestamp(), current_object_id, current_object);
current_object->receiveEvent(*event);
}
}
void TimeWarpEventDispatcher::initialize(const std::vector<std::vector<SimulationObject*>>&
objects) {
unsigned int partition_id = 0;
for (auto& partition : objects) {
unsigned int object_id = 0;
for (auto& ob : partition) {
events_->push(ob->createInitialEvents());
if (partition_id == comm_manager_->getID()) {
objects_by_name_[ob->name_] = ob;
local_object_id_by_name_[ob->name_] = object_id++;
}
object_node_id_by_name_[ob->name_] = partition_id;
}
partition_id++;
}
unsigned int num_local_objects = objects[comm_manager_->getID()].size();
object_simulation_time_ = make_unique<unsigned int []>(num_local_objects);
std::memset(object_simulation_time_.get(), 0, num_local_objects*sizeof(unsigned int));
// Creates the state queues, output queues, and filestream queues for each local object
state_manager_->initialize(num_local_objects);
output_manager_->initialize(num_local_objects);
twfs_manager_->initialize(num_local_objects);
// Register message handlers
gvt_manager_->initialize();
std::function<MessageFlags(std::unique_ptr<TimeWarpKernelMessage>)> handler =
std::bind(&TimeWarpEventDispatcher::receiveEventMessage, this,
std::placeholders::_1);
comm_manager_->addRecvMessageHandler(MessageType::EventMessage, handler);
// Prepare local min lvt computation
min_lvt_ = make_unique<unsigned int []>(num_worker_threads_);
send_min_ = make_unique<unsigned int []>(num_worker_threads_);
calculated_min_flag_ = make_unique<bool []>(num_worker_threads_);
}
unsigned int TimeWarpEventDispatcher::getMinimumLVT() {
unsigned int min = std::numeric_limits<unsigned int>::max();;
for (unsigned int i = 0; i < num_worker_threads_; i++) {
min = std::min(min, min_lvt_[i]);
// Reset send_min back to very large number for next calculation
send_min_[i] = std::numeric_limits<unsigned int>::max();
}
return min;
}
unsigned int TimeWarpEventDispatcher::getSimulationTime(SimulationObject* object) {
unsigned int object_id = local_object_id_by_name_[object->name_];
return object_simulation_time_[object_id];
}
FileStream& TimeWarpEventDispatcher::getFileStream(
SimulationObject *object, const std::string& filename, std::ios_base::openmode mode) {
unsigned int local_object_id = local_object_id_by_name_[object->name_];
TimeWarpFileStream* twfs = twfs_manager_->getFileStream(filename, mode, local_object_id);
return *twfs;
}
void TimeWarpEventDispatcher::enqueueRemoteEvent(std::shared_ptr<Event> event,
unsigned int receiver_id) {
remote_event_queue_lock_.lock();
remote_event_queue_.push_back(std::make_pair(event, receiver_id));
remote_event_queue_lock_.unlock();
}
void TimeWarpEventDispatcher::sendRemoteEvents() {
remote_event_queue_lock_.lock();
while (!remote_event_queue_.empty()) {
auto event = std::move(remote_event_queue_.front());
remote_event_queue_.pop_front();
int color = gvt_manager_->getGvtInfo(event.first->timestamp());
unsigned int receiver_id = event.second;
auto event_msg = make_unique<EventMessage>(comm_manager_->getID(), receiver_id,
event.first, color);
comm_manager_->sendMessage(std::move(event_msg));
}
remote_event_queue_lock_.unlock();
}
} // namespace warped
<commit_msg>Added initial state save for all objects<commit_after>#include "TimeWarpEventDispatcher.hpp"
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include <cmath>
#include <limits> // for std::numeric_limits<>::max();
#include <algorithm> // for std::min
#include <chrono> // for std::chrono::steady_clock
#include <cstring> // for std::memset
#include "Event.hpp"
#include "EventDispatcher.hpp"
#include "LTSFQueue.hpp"
#include "Partitioner.hpp"
#include "SimulationObject.hpp"
#include "TimeWarpMPICommunicationManager.hpp"
#include "TimeWarpMatternGVTManager.hpp"
#include "TimeWarpStateManager.hpp"
#include "TimeWarpOutputManager.hpp"
#include "TimeWarpEventSet.hpp"
#include "utility/memory.hpp"
#include "utility/warnings.hpp"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::EventMessage)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::Event)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(warped::NegativeEvent)
namespace warped {
thread_local unsigned int TimeWarpEventDispatcher::thread_id;
TimeWarpEventDispatcher::TimeWarpEventDispatcher(unsigned int max_sim_time,
unsigned int num_worker_threads,
std::shared_ptr<TimeWarpCommunicationManager> comm_manager,
std::unique_ptr<TimeWarpEventSet> event_set,
std::unique_ptr<TimeWarpGVTManager> gvt_manager,
std::unique_ptr<TimeWarpStateManager> state_manager,
std::unique_ptr<TimeWarpOutputManager> output_manager,
std::unique_ptr<TimeWarpFileStreamManager> twfs_manager) :
EventDispatcher(max_sim_time), num_worker_threads_(num_worker_threads),
comm_manager_(comm_manager), event_set_(std::move(event_set)),
gvt_manager_(std::move(gvt_manager)), state_manager_(std::move(state_manager)),
output_manager_(std::move(output_manager)), twfs_manager_(std::move(twfs_manager)) {}
void TimeWarpEventDispatcher::startSimulation(const std::vector<std::vector<SimulationObject*>>&
objects) {
initialize(objects);
thread_id = num_worker_threads_;
unused<unsigned int>(std::move(thread_id));// TODO
// Create worker threads
std::vector<std::thread> threads;
for (unsigned int i = 0; i < num_worker_threads_; ++i) {
auto thread(std::thread {&TimeWarpEventDispatcher::processEvents, this, i});
thread.detach();
threads.push_back(std::move(thread));
}
MessageFlags msg_flags = MessageFlags::None;
auto gvt_start = std::chrono::steady_clock::now();
bool calculate_gvt = false;
// Flag that says we have started calculating minimum lvt of the objects on this node
bool started_min_lvt = false;
// Master thread main loop
while (gvt_manager_->getGVT() < max_sim_time_) {
MessageFlags flags = comm_manager_->dispatchReceivedMessages();
// We may already have a pending token to send
msg_flags |= flags;
if (PENDING_MATTERN_TOKEN(msg_flags) && (min_lvt_flag_.load() == 0) && !started_min_lvt) {
min_lvt_flag_.store(num_worker_threads_);
started_min_lvt = true;
}
if (GVT_UPDATE(msg_flags)) {
fossilCollect(gvt_manager_->getGVT());
msg_flags &= ~MessageFlags::GVTUpdate;
auto mattern_gvt_manager = dynamic_cast<TimeWarpMatternGVTManager*>(gvt_manager_.get());
mattern_gvt_manager->reset();
}
if (calculate_gvt && comm_manager_->getID() == 0) {
// This will only return true if a token is not in circulation and we need to
// start another one.
MessageFlags flags = gvt_manager_->calculateGVT();
msg_flags |= flags;
if (PENDING_MATTERN_TOKEN(msg_flags)) {
min_lvt_flag_.store(num_worker_threads_);
started_min_lvt = true;
calculate_gvt = false;
}
} else if (comm_manager_->getID() == 0) {
auto now = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>
(now - gvt_start).count();
if (elapsed >= gvt_manager_->getGVTPeriod()) {
calculate_gvt = true;
gvt_start = now;
}
}
if (PENDING_MATTERN_TOKEN(msg_flags) && (min_lvt_flag_.load() == 0) && started_min_lvt) {
auto mattern_gvt_manager = dynamic_cast<TimeWarpMatternGVTManager*>(gvt_manager_.get());
unsigned int local_min_lvt = getMinimumLVT();
mattern_gvt_manager->sendMatternGVTToken(local_min_lvt);
msg_flags &= ~MessageFlags::PendingMatternToken;
started_min_lvt = false;
}
sendRemoteEvents();
}
comm_manager_->finalize();
}
void TimeWarpEventDispatcher::processEvents(unsigned int id) {
thread_id = id;
while (gvt_manager_->getGVT() < max_sim_time_) {
local_min_lvt_flag_[thread_id] = min_lvt_flag_.load();
std::shared_ptr<Event> event = nullptr; //TODO, get next event
if (event != nullptr) {
unsigned int current_object_id = local_object_id_by_name_[event->receiverName()];
SimulationObject* current_object = objects_by_name_[event->receiverName()];
// Handle a negative event
if (event->event_type() == EventType::NEGATIVE) {
// event_set_->handleAntiMessage(current_object_id, std::move(event));
continue;
}
// Check to see if straggler and rollback if necessary
if (event->timestamp() < object_simulation_time_[current_object_id]) {
rollback(event->timestamp(), current_object_id, current_object);
} else {
if (local_min_lvt_flag_[thread_id] > 0 && !calculated_min_flag_[thread_id]) {
min_lvt_[thread_id] = std::min(send_min_[thread_id], event->timestamp());
min_lvt_flag_--;
}
}
// Update simulation time
object_simulation_time_[current_object_id] = event->timestamp();
twfs_manager_->setObjectCurrentTime(event->timestamp(), current_object_id);
// Save state
state_manager_->saveState(event->timestamp(), current_object_id, current_object);
// process event and get new events
auto new_events = current_object->receiveEvent(*event);
// Send new events
for (auto& e: new_events) {
auto object_id_it = local_object_id_by_name_.find(e->receiverName());
output_manager_->insertEvent(e, current_object_id);
if (object_id_it != local_object_id_by_name_.end()) {
// Local event
sendLocalEvent(e);
} else {
// Remote event
enqueueRemoteEvent(e, object_node_id_by_name_[e->receiverName()]);
}
}
}
}
}
MessageFlags TimeWarpEventDispatcher::receiveEventMessage(std::unique_ptr<TimeWarpKernelMessage>
kmsg) {
auto msg = unique_cast<TimeWarpKernelMessage, EventMessage>(std::move(kmsg));
gvt_manager_->setGvtInfo(msg->gvt_mattern_color);
unsigned int receiver_object_id = local_object_id_by_name_[msg->event->receiverName()];
unused<unsigned int>(std::move(receiver_object_id));
// event_set_->insertEvent(receiver_object_id, std::move(msg->event));
return MessageFlags::None;
}
void TimeWarpEventDispatcher::sendLocalEvent(std::shared_ptr<Event> event) {
unsigned int receiver_object_id = local_object_id_by_name_[event->receiverName()];
unused<unsigned int>(std::move(receiver_object_id));
//event_set_->insertEvent(receiver_object_id, event);
if (min_lvt_flag_.load() > 0 && !calculated_min_flag_[thread_id]) {
unsigned int send_min = send_min_[thread_id];
send_min_[thread_id] = std::min(send_min, event->timestamp());
}
}
void TimeWarpEventDispatcher::fossilCollect(unsigned int gvt) {
twfs_manager_->fossilCollectAll(gvt);
state_manager_->fossilCollectAll(gvt);
output_manager_->fossilCollectAll(gvt);
// event_set_->fossilCollectAll(gvt);
}
void TimeWarpEventDispatcher::cancelEvents(
std::unique_ptr<std::vector<std::shared_ptr<Event>>> events_to_cancel) {
if (events_to_cancel->empty()) {
return;
}
do {
auto event = events_to_cancel->back();
auto neg_event = std::make_shared<NegativeEvent>(event->receiverName(), event->senderName(),
event->timestamp());
events_to_cancel->pop_back();
unsigned int receiver_id = object_node_id_by_name_[event->receiverName()];
if (receiver_id != comm_manager_->getID()) {
enqueueRemoteEvent(neg_event, receiver_id);
} else {
sendLocalEvent(neg_event);
}
} while (!events_to_cancel->empty());
}
void TimeWarpEventDispatcher::rollback(unsigned int straggler_time, unsigned int local_object_id,
SimulationObject* object) {
twfs_manager_->rollback(straggler_time, local_object_id);
unsigned int restored_timestamp = state_manager_->restoreState(straggler_time, local_object_id,
object);
auto events_to_cancel = output_manager_->rollback(straggler_time, local_object_id);
if (events_to_cancel != nullptr) {
cancelEvents(std::move(events_to_cancel));
}
// event_set_->rollback(local_object_id, restored_timestamp);
coastForward(restored_timestamp, straggler_time);
}
void TimeWarpEventDispatcher::coastForward(unsigned int start_time, unsigned int stop_time) {
unsigned int current_time = start_time;
while (current_time < stop_time) {
std::shared_ptr<Event> event = nullptr; //TODO, get next event
unsigned int current_object_id = local_object_id_by_name_[event->receiverName()];
SimulationObject* current_object = objects_by_name_[event->receiverName()];
object_simulation_time_[current_object_id] = event->timestamp();
twfs_manager_->setObjectCurrentTime(event->timestamp(), current_object_id);
state_manager_->saveState(event->timestamp(), current_object_id, current_object);
current_object->receiveEvent(*event);
}
}
void TimeWarpEventDispatcher::initialize(const std::vector<std::vector<SimulationObject*>>&
objects) {
unsigned int partition_id = 0;
for (auto& partition : objects) {
unsigned int object_id = 0;
for (auto ob : partition) {
events_->push(ob->createInitialEvents());
if (partition_id == comm_manager_->getID()) {
objects_by_name_[ob->name_] = ob;
local_object_id_by_name_[ob->name_] = object_id++;
}
object_node_id_by_name_[ob->name_] = partition_id;
}
partition_id++;
}
unsigned int num_local_objects = objects[comm_manager_->getID()].size();
object_simulation_time_ = make_unique<unsigned int []>(num_local_objects);
std::memset(object_simulation_time_.get(), 0, num_local_objects*sizeof(unsigned int));
// Creates the state queues, output queues, and filestream queues for each local object
state_manager_->initialize(num_local_objects);
for (auto ob: objects_by_name_) {
state_manager_->saveState(0, local_object_id_by_name_[ob.first], ob.second);
}
output_manager_->initialize(num_local_objects);
twfs_manager_->initialize(num_local_objects);
// Register message handlers
gvt_manager_->initialize();
std::function<MessageFlags(std::unique_ptr<TimeWarpKernelMessage>)> handler =
std::bind(&TimeWarpEventDispatcher::receiveEventMessage, this,
std::placeholders::_1);
comm_manager_->addRecvMessageHandler(MessageType::EventMessage, handler);
// Prepare local min lvt computation
min_lvt_ = make_unique<unsigned int []>(num_worker_threads_);
send_min_ = make_unique<unsigned int []>(num_worker_threads_);
calculated_min_flag_ = make_unique<bool []>(num_worker_threads_);
}
unsigned int TimeWarpEventDispatcher::getMinimumLVT() {
unsigned int min = std::numeric_limits<unsigned int>::max();;
for (unsigned int i = 0; i < num_worker_threads_; i++) {
min = std::min(min, min_lvt_[i]);
// Reset send_min back to very large number for next calculation
send_min_[i] = std::numeric_limits<unsigned int>::max();
}
return min;
}
unsigned int TimeWarpEventDispatcher::getSimulationTime(SimulationObject* object) {
unsigned int object_id = local_object_id_by_name_[object->name_];
return object_simulation_time_[object_id];
}
FileStream& TimeWarpEventDispatcher::getFileStream(
SimulationObject *object, const std::string& filename, std::ios_base::openmode mode) {
unsigned int local_object_id = local_object_id_by_name_[object->name_];
TimeWarpFileStream* twfs = twfs_manager_->getFileStream(filename, mode, local_object_id);
return *twfs;
}
void TimeWarpEventDispatcher::enqueueRemoteEvent(std::shared_ptr<Event> event,
unsigned int receiver_id) {
remote_event_queue_lock_.lock();
remote_event_queue_.push_back(std::make_pair(event, receiver_id));
remote_event_queue_lock_.unlock();
}
void TimeWarpEventDispatcher::sendRemoteEvents() {
remote_event_queue_lock_.lock();
while (!remote_event_queue_.empty()) {
auto event = std::move(remote_event_queue_.front());
remote_event_queue_.pop_front();
int color = gvt_manager_->getGvtInfo(event.first->timestamp());
unsigned int receiver_id = event.second;
auto event_msg = make_unique<EventMessage>(comm_manager_->getID(), receiver_id,
event.first, color);
comm_manager_->sendMessage(std::move(event_msg));
}
remote_event_queue_lock_.unlock();
}
} // namespace warped
<|endoftext|>
|
<commit_before>
#pragma once
#include <cstring>
namespace werk {
//Level of the log, ordered to allow simple filtering
enum class LogLevel
{
CRITICAL,
ERROR,
WARNING,
ALERT,
SUCCESS,
CONFIG,
INFO,
DETAIL,
JSON,
TRACE
};
extern const char *logLevels[];
//Used for passing log messages between threads
struct LogMessage
{
private:
//Some controls that no one outside this class should depend on
static const size_t totalMessageSize = 1024;
static const size_t headerSize = 32; //Not actually the size of the header, just has to be at least as big
static const size_t maxLineLength = totalMessageSize - headerSize;
public:
//Header
uint64_t sequenceNumber;
uint64_t time;
LogLevel level;
size_t length;
//Message
char message[maxLineLength];
LogMessage() { }
LogMessage(const LogMessage &m) {
std::memcpy(this, &m, headerSize + m.length);
}
LogMessage &operator=(const LogMessage &m) {
std::memcpy(this, &m, headerSize + m.length);
return *this;
}
};
}
<commit_msg>Fix missing include in log message (#7)<commit_after>
#pragma once
#include <cstdint>
#include <cstring>
namespace werk {
//Level of the log, ordered to allow simple filtering
enum class LogLevel
{
CRITICAL,
ERROR,
WARNING,
ALERT,
SUCCESS,
CONFIG,
INFO,
DETAIL,
JSON,
TRACE
};
extern const char *logLevels[];
//Used for passing log messages between threads
struct LogMessage
{
private:
//Some controls that no one outside this class should depend on
static const size_t totalMessageSize = 1024;
static const size_t headerSize = 32; //Not actually the size of the header, just has to be at least as big
static const size_t maxLineLength = totalMessageSize - headerSize;
public:
//Header
uint64_t sequenceNumber;
uint64_t time;
LogLevel level;
size_t length;
//Message
char message[maxLineLength];
LogMessage() { }
LogMessage(const LogMessage &m) {
std::memcpy(this, &m, headerSize + m.length);
}
LogMessage &operator=(const LogMessage &m) {
std::memcpy(this, &m, headerSize + m.length);
return *this;
}
};
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CommandDispatchContainer.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 "CommandDispatchContainer.hxx"
#include "UndoCommandDispatch.hxx"
#include "StatusBarCommandDispatch.hxx"
#include "DisposeHelper.hxx"
#include "macros.hxx"
#include <comphelper/InlineContainer.hxx>
#include <com/sun/star/frame/XDispatchProvider.hpp>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace chart
{
CommandDispatchContainer::CommandDispatchContainer(
const Reference< uno::XComponentContext > & xContext ) :
m_xContext( xContext )
{
m_aContainerDocumentCommands =
::comphelper::MakeSet< OUString >
( C2U("AddDirect")) ( C2U("NewDoc")) ( C2U("Open"))
( C2U("Save")) ( C2U("SaveAs")) ( C2U("SendMail"))
( C2U("EditDoc")) ( C2U("ExportDirectToPDF")) ( C2U("PrintDefault"))
;
}
void CommandDispatchContainer::setModel(
const Reference< frame::XModel > & xModel )
{
// remove all existing dispatcher that base on the old model
DisposeHelper::DisposeAllMapElements( m_aCachedDispatches );
m_aCachedDispatches.clear();
m_xModel.set( xModel );
}
// void CommandDispatchContainer::setUndoManager(
// const Reference< chart2::XUndoManager > & xUndoManager )
// {
// m_xUndoManager = xUndoManager;
// }
void CommandDispatchContainer::setFallbackDispatch(
const Reference< frame::XDispatch > xFallbackDispatch,
const ::std::set< OUString > & rFallbackCommands )
{
m_xFallbackDispatcher.set( xFallbackDispatch );
m_aFallbackCommands = rFallbackCommands;
}
Reference< frame::XDispatch > CommandDispatchContainer::getDispatchForURL(
const util::URL & rURL )
{
Reference< frame::XDispatch > xResult;
tDispatchMap::const_iterator aIt( m_aCachedDispatches.find( rURL.Complete ));
if( aIt != m_aCachedDispatches.end())
{
xResult.set( (*aIt).second );
}
else
{
if( rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Undo" ))
|| rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Redo" )))
{
CommandDispatch * pDispatch = new UndoCommandDispatch( m_xContext, m_xModel );
xResult.set( pDispatch );
pDispatch->initialize();
m_aCachedDispatches[ C2U(".uno:Undo") ].set( xResult );
m_aCachedDispatches[ C2U(".uno:Redo") ].set( xResult );
}
else if( rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Context" ))
|| rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ModifiedStatus" )))
{
Reference< view::XSelectionSupplier > xSelSupp;
if( m_xModel.is())
xSelSupp.set( m_xModel->getCurrentController(), uno::UNO_QUERY );
CommandDispatch * pDispatch = new StatusBarCommandDispatch( m_xContext, m_xModel, xSelSupp );
xResult.set( pDispatch );
pDispatch->initialize();
m_aCachedDispatches[ C2U(".uno:Context") ].set( xResult );
m_aCachedDispatches[ C2U(".uno:ModifiedStatus") ].set( xResult );
}
else if( m_xModel.is() &&
(m_aContainerDocumentCommands.find( rURL.Path ) != m_aContainerDocumentCommands.end()) )
{
xResult.set( getContainerDispatchForURL( m_xModel->getCurrentController(), rURL ));
// ToDo: can those dispatches be cached?
m_aCachedDispatches[ rURL.Complete ].set( xResult );
}
else if( m_xFallbackDispatcher.is() &&
(m_aFallbackCommands.find( rURL.Path ) != m_aFallbackCommands.end()) )
{
xResult.set( m_xFallbackDispatcher );
m_aCachedDispatches[ rURL.Complete ].set( xResult );
}
}
return xResult;
}
Sequence< Reference< frame::XDispatch > > CommandDispatchContainer::getDispatchesForURLs(
const Sequence< frame::DispatchDescriptor > & aDescriptors )
{
sal_Int32 nCount = aDescriptors.getLength();
uno::Sequence< uno::Reference< frame::XDispatch > > aRet( nCount );
for( sal_Int32 nPos = 0; nPos < nCount; ++nPos )
{
if( aDescriptors[ nPos ].FrameName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("_self")))
aRet[ nPos ] = getDispatchForURL( aDescriptors[ nPos ].FeatureURL );
}
return aRet;
}
void CommandDispatchContainer::DisposeAndClear()
{
DisposeHelper::DisposeAllMapElements( m_aCachedDispatches );
m_aCachedDispatches.clear();
m_xFallbackDispatcher.clear();
m_aFallbackCommands.clear();
}
Reference< frame::XDispatch > CommandDispatchContainer::getContainerDispatchForURL(
const Reference< frame::XController > & xChartController,
const util::URL & rURL )
{
Reference< frame::XDispatch > xResult;
if( xChartController.is())
{
Reference< frame::XFrame > xFrame( xChartController->getFrame());
if( xFrame.is())
{
Reference< frame::XDispatchProvider > xDispProv( xFrame->getCreator(), uno::UNO_QUERY );
if( xDispProv.is())
xResult.set( xDispProv->queryDispatch( rURL, C2U("_self"), 0 ));
}
}
return xResult;
}
} // namespace chart
<commit_msg>INTEGRATION: CWS rptchart02 (1.3.84); FILE MERGED 2008/04/16 06:35:33 oj 1.3.84.2: RESYNC: (1.3-1.4); FILE MERGED 2008/04/15 12:50:18 oj 1.3.84.1: use comphelper copyProperties<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: CommandDispatchContainer.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "CommandDispatchContainer.hxx"
#include "UndoCommandDispatch.hxx"
#include "StatusBarCommandDispatch.hxx"
#include "DisposeHelper.hxx"
#include "macros.hxx"
#include <comphelper/InlineContainer.hxx>
#include <com/sun/star/frame/XDispatchProvider.hpp>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace chart
{
CommandDispatchContainer::CommandDispatchContainer(
const Reference< uno::XComponentContext > & xContext ) :
m_xContext( xContext )
{
m_aContainerDocumentCommands =
::comphelper::MakeSet< OUString >
( C2U("AddDirect")) ( C2U("NewDoc")) ( C2U("Open"))
( C2U("Save")) ( C2U("SaveAs")) ( C2U("SendMail"))
( C2U("EditDoc")) ( C2U("ExportDirectToPDF")) ( C2U("PrintDefault"))
;
}
void CommandDispatchContainer::setModel(
const Reference< frame::XModel > & xModel )
{
// remove all existing dispatcher that base on the old model
m_aCachedDispatches.clear();
DisposeHelper::DisposeAllElements( m_aToBeDisposedDispatches );
m_aToBeDisposedDispatches.clear();
m_xModel.set( xModel );
}
// void CommandDispatchContainer::setUndoManager(
// const Reference< chart2::XUndoManager > & xUndoManager )
// {
// m_xUndoManager = xUndoManager;
// }
void CommandDispatchContainer::setFallbackDispatch(
const Reference< frame::XDispatch > xFallbackDispatch,
const ::std::set< OUString > & rFallbackCommands )
{
OSL_ENSURE(xFallbackDispatch.is(),"Invalid fall back dispatcher!");
m_xFallbackDispatcher.set( xFallbackDispatch );
m_aFallbackCommands = rFallbackCommands;
m_aToBeDisposedDispatches.push_back( m_xFallbackDispatcher );
}
Reference< frame::XDispatch > CommandDispatchContainer::getDispatchForURL(
const util::URL & rURL )
{
Reference< frame::XDispatch > xResult;
tDispatchMap::const_iterator aIt( m_aCachedDispatches.find( rURL.Complete ));
if( aIt != m_aCachedDispatches.end())
{
xResult.set( (*aIt).second );
}
else
{
if( rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Undo" ))
|| rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Redo" )))
{
CommandDispatch * pDispatch = new UndoCommandDispatch( m_xContext, m_xModel );
xResult.set( pDispatch );
pDispatch->initialize();
m_aCachedDispatches[ C2U(".uno:Undo") ].set( xResult );
m_aCachedDispatches[ C2U(".uno:Redo") ].set( xResult );
m_aToBeDisposedDispatches.push_back( xResult );
}
else if( rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Context" ))
|| rURL.Path.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ModifiedStatus" )))
{
Reference< view::XSelectionSupplier > xSelSupp;
if( m_xModel.is())
xSelSupp.set( m_xModel->getCurrentController(), uno::UNO_QUERY );
CommandDispatch * pDispatch = new StatusBarCommandDispatch( m_xContext, m_xModel, xSelSupp );
xResult.set( pDispatch );
pDispatch->initialize();
m_aCachedDispatches[ C2U(".uno:Context") ].set( xResult );
m_aCachedDispatches[ C2U(".uno:ModifiedStatus") ].set( xResult );
m_aToBeDisposedDispatches.push_back( xResult );
}
else if( m_xModel.is() &&
(m_aContainerDocumentCommands.find( rURL.Path ) != m_aContainerDocumentCommands.end()) )
{
xResult.set( getContainerDispatchForURL( m_xModel->getCurrentController(), rURL ));
// ToDo: can those dispatches be cached?
m_aCachedDispatches[ rURL.Complete ].set( xResult );
}
else if( m_xFallbackDispatcher.is() &&
(m_aFallbackCommands.find( rURL.Path ) != m_aFallbackCommands.end()) )
{
xResult.set( m_xFallbackDispatcher );
m_aCachedDispatches[ rURL.Complete ].set( xResult );
}
}
return xResult;
}
Sequence< Reference< frame::XDispatch > > CommandDispatchContainer::getDispatchesForURLs(
const Sequence< frame::DispatchDescriptor > & aDescriptors )
{
sal_Int32 nCount = aDescriptors.getLength();
uno::Sequence< uno::Reference< frame::XDispatch > > aRet( nCount );
for( sal_Int32 nPos = 0; nPos < nCount; ++nPos )
{
if( aDescriptors[ nPos ].FrameName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("_self")))
aRet[ nPos ] = getDispatchForURL( aDescriptors[ nPos ].FeatureURL );
}
return aRet;
}
void CommandDispatchContainer::DisposeAndClear()
{
m_aCachedDispatches.clear();
DisposeHelper::DisposeAllElements( m_aToBeDisposedDispatches );
m_aToBeDisposedDispatches.clear();
m_xFallbackDispatcher.clear();
m_aFallbackCommands.clear();
}
Reference< frame::XDispatch > CommandDispatchContainer::getContainerDispatchForURL(
const Reference< frame::XController > & xChartController,
const util::URL & rURL )
{
Reference< frame::XDispatch > xResult;
if( xChartController.is())
{
Reference< frame::XFrame > xFrame( xChartController->getFrame());
if( xFrame.is())
{
Reference< frame::XDispatchProvider > xDispProv( xFrame->getCreator(), uno::UNO_QUERY );
if( xDispProv.is())
xResult.set( xDispProv->queryDispatch( rURL, C2U("_self"), 0 ));
}
}
return xResult;
}
} // namespace chart
<|endoftext|>
|
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNode.cpp,v $
$Revision: 1.8 $
$Name: $
$Author: gauges $
$Date: 2005/06/09 13:46:28 $
End CVS Header */
#include "copasi.h"
#include "CEvaluationNode.h"
#include "sbml/math/ASTNode.h"
CEvaluationNode::CPrecedence::CPrecedence(const unsigned C_INT32 & left,
const unsigned C_INT32 & right):
left(left),
right(right)
{}
CEvaluationNode::CPrecedence::CPrecedence(const CPrecedence & src):
left(src.left),
right(src.right)
{}
CEvaluationNode::CPrecedence::~CPrecedence() {}
CEvaluationNode * CEvaluationNode::create(const Type & type,
const std::string & contents)
{
CEvaluationNode * pNode = NULL;
switch (CEvaluationNode::type(type))
{
case CEvaluationNode::CONSTANT:
pNode = new CEvaluationNodeConstant((CEvaluationNodeConstant::SubType) subType(type),
contents);
break;
case CEvaluationNode::FUNCTION:
pNode = new CEvaluationNodeFunction((CEvaluationNodeFunction::SubType) subType(type),
contents);
break;
case CEvaluationNode::NUMBER:
pNode = new CEvaluationNodeNumber((CEvaluationNodeNumber::SubType) subType(type),
contents);
break;
case CEvaluationNode::OPERATOR:
pNode = new CEvaluationNodeOperator((CEvaluationNodeOperator::SubType) subType(type),
contents);
break;
case CEvaluationNode::VARIABLE:
pNode = new CEvaluationNodeVariable((CEvaluationNodeVariable::SubType) subType(type),
contents);
break;
default:
break;
}
return pNode;
}
CEvaluationNode::Type CEvaluationNode::subType(const Type & type)
{return (Type) (type & 0x00FFFFFF);}
CEvaluationNode::Type CEvaluationNode::type(const Type & type)
{return (Type) (type & 0xFF000000);}
CEvaluationNode::CEvaluationNode():
CCopasiNode<Data>(),
mType(CEvaluationNode::INVALID),
mValue(0.0),
mData(""),
mPrecedence(PRECEDENCE_DEFAULT)
{}
CEvaluationNode::CEvaluationNode(const Type & type,
const Data & data):
CCopasiNode<Data>(),
mType(type),
mValue(0.0),
mData(data),
mPrecedence(PRECEDENCE_DEFAULT)
{}
CEvaluationNode::CEvaluationNode(const CEvaluationNode & src):
CCopasiNode<Data>(src),
mType(src.mType),
mValue(src.mValue),
mData(src.mData),
mPrecedence(src.mPrecedence)
{}
CEvaluationNode::~CEvaluationNode() {}
bool CEvaluationNode::compile(const CEvaluationTree * /* pTree */)
{return (getChild() == NULL);} // We must not have any children.
CEvaluationNode::Data CEvaluationNode::getData() const
{return mData;}
bool CEvaluationNode::setData(const Data & data)
{
mData = data;
return true;
}
const CEvaluationNode::Type & CEvaluationNode::getType() const
{return mType;}
bool CEvaluationNode::operator < (const CEvaluationNode & rhs)
{return (mPrecedence.right < rhs.mPrecedence.left);}
ASTNode* CEvaluationNode::toASTNode()
{
return new ASTNode();
}
<commit_msg>The attribute mValue is initialized to NaN.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNode.cpp,v $
$Revision: 1.9 $
$Name: $
$Author: shoops $
$Date: 2005/06/14 15:48:44 $
End CVS Header */
#include "copasi.h"
#include "CEvaluationNode.h"
#include "sbml/math/ASTNode.h"
CEvaluationNode::CPrecedence::CPrecedence(const unsigned C_INT32 & left,
const unsigned C_INT32 & right):
left(left),
right(right)
{}
CEvaluationNode::CPrecedence::CPrecedence(const CPrecedence & src):
left(src.left),
right(src.right)
{}
CEvaluationNode::CPrecedence::~CPrecedence() {}
CEvaluationNode * CEvaluationNode::create(const Type & type,
const std::string & contents)
{
CEvaluationNode * pNode = NULL;
switch (CEvaluationNode::type(type))
{
case CEvaluationNode::CONSTANT:
pNode = new CEvaluationNodeConstant((CEvaluationNodeConstant::SubType) subType(type),
contents);
break;
case CEvaluationNode::FUNCTION:
pNode = new CEvaluationNodeFunction((CEvaluationNodeFunction::SubType) subType(type),
contents);
break;
case CEvaluationNode::NUMBER:
pNode = new CEvaluationNodeNumber((CEvaluationNodeNumber::SubType) subType(type),
contents);
break;
case CEvaluationNode::OPERATOR:
pNode = new CEvaluationNodeOperator((CEvaluationNodeOperator::SubType) subType(type),
contents);
break;
case CEvaluationNode::VARIABLE:
pNode = new CEvaluationNodeVariable((CEvaluationNodeVariable::SubType) subType(type),
contents);
break;
default:
break;
}
return pNode;
}
CEvaluationNode::Type CEvaluationNode::subType(const Type & type)
{return (Type) (type & 0x00FFFFFF);}
CEvaluationNode::Type CEvaluationNode::type(const Type & type)
{return (Type) (type & 0xFF000000);}
CEvaluationNode::CEvaluationNode():
CCopasiNode<Data>(),
mType(CEvaluationNode::INVALID),
mValue(std::numeric_limits<C_FLOAT64>::signaling_NaN()),
mData(""),
mPrecedence(PRECEDENCE_DEFAULT)
{}
CEvaluationNode::CEvaluationNode(const Type & type,
const Data & data):
CCopasiNode<Data>(),
mType(type),
mValue(std::numeric_limits<C_FLOAT64>::signaling_NaN()),
mData(data),
mPrecedence(PRECEDENCE_DEFAULT)
{}
CEvaluationNode::CEvaluationNode(const CEvaluationNode & src):
CCopasiNode<Data>(src),
mType(src.mType),
mValue(src.mValue),
mData(src.mData),
mPrecedence(src.mPrecedence)
{}
CEvaluationNode::~CEvaluationNode() {}
bool CEvaluationNode::compile(const CEvaluationTree * /* pTree */)
{return (getChild() == NULL);} // We must not have any children.
CEvaluationNode::Data CEvaluationNode::getData() const
{return mData;}
bool CEvaluationNode::setData(const Data & data)
{
mData = data;
return true;
}
const CEvaluationNode::Type & CEvaluationNode::getType() const
{return mType;}
bool CEvaluationNode::operator < (const CEvaluationNode & rhs)
{return (mPrecedence.right < rhs.mPrecedence.left);}
ASTNode* CEvaluationNode::toASTNode()
{
return new ASTNode();
}
<|endoftext|>
|
<commit_before>#include "UnicornHat.h"
#include "Image.h"
#include "Animation.h"
#include <cstring>
extern "C" {
#include <ws2811.h>
}
#include <unistd.h>
#include <signal.h>
#include <stdexcept>
#include <thread>
#include <chrono>
using namespace std;
namespace Gif2UnicornHat {
bool UnicornHat::alreadyShutdown = false;
ws2811_t ledstring;
UnicornHat& UnicornHat::instance()
{
static UnicornHat hat;
return hat;
}
UnicornHat::UnicornHat()
{
ledstring.freq = WS2811_TARGET_FREQ;
ledstring.dmanum = 5;
ledstring.channel[0].gpionum = 18;
ledstring.channel[0].count = 64;
ledstring.channel[0].invert = 0;
ledstring.channel[0].brightness = 55;
::ws2811_init(&ledstring);
registerExitHandler();
}
UnicornHat::~UnicornHat()
{
shutdown();
}
void UnicornHat::setBrightness(double brightness)
{
if (brightness < 0 || brightness > 1) {
throw invalid_argument("Brightness must be between 0.0 and 1.0");
}
ledstring.channel[0].brightness = (int8_t)(brightness*255);
}
void UnicornHat::showImage(const Image& image)
{
if (image.width() > 8 || image.height() > 8) {
throw invalid_argument("Image is too big for the UnicornHat. An image must be 8x8 pixels to be sent to the hat.");
}
for (Image::Dimension x = 0; x < image.width(); ++x) {
for (Image::Dimension y = 0; y < image.height(); ++y) {
ledstring.channel[0].leds[getPixelIndex(x, y)] = (image[x][y].r << 16) | (image[x][y].g << 8) | image[x][y].b;
}
}
::ws2811_render(&ledstring);
}
void UnicornHat::playAnimation(const Animation& animation)
{
for (int loopNum = 0; loopNum < animation.numLoops() || animation.numLoops() == 0; ++loopNum) {
for (auto&& frame : animation.frames()) {
showImage(frame.image);
this_thread::sleep_for(frame.duration);
}
}
}
int UnicornHat::getPixelIndex(int x, int y) const
{
const static int indicies[8][8] = {
{0, 1, 2, 3, 4, 5, 6, 7},
{15, 14, 13, 12, 11, 10, 9, 8},
{16, 17, 18, 19, 20, 21, 22, 23},
{31, 30, 29, 28, 27, 26, 25, 24},
{32, 33, 34, 35, 36, 37, 38, 39},
{47, 46, 45, 44, 43, 42, 41, 40},
{48, 49, 50, 51, 52, 53, 54, 55},
{63, 62, 61, 60, 59, 58, 57, 56}
};
return indicies[x][y];
}
void UnicornHat::onSignal(int)
{
shutdown();
exit(0);
}
void UnicornHat::registerExitHandler() const
{
const static int signals[] = {
SIGALRM, SIGHUP, SIGINT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2, SIGPOLL, SIGPROF, SIGVTALRM, //< Termination signals.
SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGQUIT, SIGSEGV, SIGSYS, SIGTRAP, SIGXCPU //< Aborting signals.
};
for (auto i = 0u; i < sizeof(signals)/sizeof(signals[0]); ++i) {
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = onSignal;
sigaction(signals[i], &sa, nullptr);
}
}
void UnicornHat::shutdown()
{
// Don't run termination logic more than once.
if (alreadyShutdown) {
return;
}
alreadyShutdown = true;
for (int i = 0; i < 64; ++i) {
ledstring.channel[0].leds[i] = 0;
}
::ws2811_render(&ledstring);
::ws2811_fini(&ledstring);
}
}
<commit_msg>Force GRB pixel order instead of the default RGB. A recent change to rpi-ws281x switched the default to RGB instead of the original GRB.<commit_after>#include "UnicornHat.h"
#include "Image.h"
#include "Animation.h"
#include <cstring>
extern "C" {
#include <ws2811.h>
}
#include <unistd.h>
#include <signal.h>
#include <stdexcept>
#include <thread>
#include <chrono>
using namespace std;
namespace Gif2UnicornHat {
bool UnicornHat::alreadyShutdown = false;
ws2811_t ledstring;
UnicornHat& UnicornHat::instance()
{
static UnicornHat hat;
return hat;
}
UnicornHat::UnicornHat()
{
ledstring.freq = WS2811_TARGET_FREQ;
ledstring.dmanum = 5;
ledstring.channel[0].gpionum = 18;
ledstring.channel[0].count = 64;
ledstring.channel[0].invert = 0;
ledstring.channel[0].brightness = 55;
ledstring.channel[0].strip_type = WS2811_STRIP_GRB;
::ws2811_init(&ledstring);
registerExitHandler();
}
UnicornHat::~UnicornHat()
{
shutdown();
}
void UnicornHat::setBrightness(double brightness)
{
if (brightness < 0 || brightness > 1) {
throw invalid_argument("Brightness must be between 0.0 and 1.0");
}
ledstring.channel[0].brightness = (int8_t)(brightness*255);
}
void UnicornHat::showImage(const Image& image)
{
if (image.width() > 8 || image.height() > 8) {
throw invalid_argument("Image is too big for the UnicornHat. An image must be 8x8 pixels to be sent to the hat.");
}
for (Image::Dimension x = 0; x < image.width(); ++x) {
for (Image::Dimension y = 0; y < image.height(); ++y) {
ledstring.channel[0].leds[getPixelIndex(x, y)] = (image[x][y].r << 16) | (image[x][y].g << 8) | image[x][y].b;
}
}
::ws2811_render(&ledstring);
}
void UnicornHat::playAnimation(const Animation& animation)
{
for (int loopNum = 0; loopNum < animation.numLoops() || animation.numLoops() == 0; ++loopNum) {
for (auto&& frame : animation.frames()) {
showImage(frame.image);
this_thread::sleep_for(frame.duration);
}
}
}
int UnicornHat::getPixelIndex(int x, int y) const
{
const static int indicies[8][8] = {
{0, 1, 2, 3, 4, 5, 6, 7},
{15, 14, 13, 12, 11, 10, 9, 8},
{16, 17, 18, 19, 20, 21, 22, 23},
{31, 30, 29, 28, 27, 26, 25, 24},
{32, 33, 34, 35, 36, 37, 38, 39},
{47, 46, 45, 44, 43, 42, 41, 40},
{48, 49, 50, 51, 52, 53, 54, 55},
{63, 62, 61, 60, 59, 58, 57, 56}
};
return indicies[x][y];
}
void UnicornHat::onSignal(int)
{
shutdown();
exit(0);
}
void UnicornHat::registerExitHandler() const
{
const static int signals[] = {
SIGALRM, SIGHUP, SIGINT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2, SIGPOLL, SIGPROF, SIGVTALRM, //< Termination signals.
SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGQUIT, SIGSEGV, SIGSYS, SIGTRAP, SIGXCPU //< Aborting signals.
};
for (auto i = 0u; i < sizeof(signals)/sizeof(signals[0]); ++i) {
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = onSignal;
sigaction(signals[i], &sa, nullptr);
}
}
void UnicornHat::shutdown()
{
// Don't run termination logic more than once.
if (alreadyShutdown) {
return;
}
alreadyShutdown = true;
for (int i = 0; i < 64; ++i) {
ledstring.channel[0].leds[i] = 0;
}
::ws2811_render(&ledstring);
::ws2811_fini(&ledstring);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <algorithm>
#include "core/reactor.hh"
struct file_test {
file_test(file&& f) : f(std::move(f)) {}
file f;
semaphore sem = { 0 };
semaphore par = { 1000 };
};
int main(int ac, char** av) {
static constexpr auto max = 10000;
engine.open_file_dma("testfile.tmp").then([] (file f) {
auto ft = new file_test{std::move(f)};
for (size_t i = 0; i < max; ++i) {
ft->par.wait().then([ft, i] {
auto wbuf = allocate_aligned_buffer<unsigned char>(4096, 4096);
std::fill(wbuf.get(), wbuf.get() + 4096, i);
auto wb = wbuf.get();
ft->f.dma_write(i * 4096, wb, 4096).then(
[ft, i, wbuf = std::move(wbuf)] (size_t ret) mutable {
assert(ret == 4096);
auto rbuf = allocate_aligned_buffer<unsigned char>(4096, 4096);
auto rb = rbuf.get();
ft->f.dma_read(i * 4096, rb, 4096).then(
[ft, i, rbuf = std::move(rbuf), wbuf = std::move(wbuf)] (size_t) mutable {
bool eq = std::equal(rbuf.get(), rbuf.get() + 4096, wbuf.get());
assert(eq);
ft->sem.signal(1);
ft->par.signal();
});
});
});
}
ft->sem.wait(max).then([ft] () mutable {
return ft->f.flush();
}).then([ft] () mutable {
std::cout << "done\n";
delete ft;
::exit(0);
});
});
engine.run();
return 0;
}
<commit_msg>fileiotest: verify read size<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <algorithm>
#include "core/reactor.hh"
struct file_test {
file_test(file&& f) : f(std::move(f)) {}
file f;
semaphore sem = { 0 };
semaphore par = { 1000 };
};
int main(int ac, char** av) {
static constexpr auto max = 10000;
engine.open_file_dma("testfile.tmp").then([] (file f) {
auto ft = new file_test{std::move(f)};
for (size_t i = 0; i < max; ++i) {
ft->par.wait().then([ft, i] {
auto wbuf = allocate_aligned_buffer<unsigned char>(4096, 4096);
std::fill(wbuf.get(), wbuf.get() + 4096, i);
auto wb = wbuf.get();
ft->f.dma_write(i * 4096, wb, 4096).then(
[ft, i, wbuf = std::move(wbuf)] (size_t ret) mutable {
assert(ret == 4096);
auto rbuf = allocate_aligned_buffer<unsigned char>(4096, 4096);
auto rb = rbuf.get();
ft->f.dma_read(i * 4096, rb, 4096).then(
[ft, i, rbuf = std::move(rbuf), wbuf = std::move(wbuf)] (size_t ret) mutable {
assert(ret == 4096);
bool eq = std::equal(rbuf.get(), rbuf.get() + 4096, wbuf.get());
assert(eq);
ft->sem.signal(1);
ft->par.signal();
});
});
});
}
ft->sem.wait(max).then([ft] () mutable {
return ft->f.flush();
}).then([ft] () mutable {
std::cout << "done\n";
delete ft;
::exit(0);
});
});
engine.run();
return 0;
}
<|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/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
// The extension should have opened 3 new tabs. Including the original blank
// tab, we now have 4 tabs. Two should be part of the extension app, and
// grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
// TODO(creis): This should open in a new process (i.e., false for the last
// argument), but we temporarily avoid swapping processes away from an app
// until we're able to restore window.opener if the page later returns to an
// in-app URL. See crbug.com/65953.
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), true);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
// TODO(creis): This should swap out of the app's process (i.e., EXPECT_NE),
// but we temporarily avoid swapping away from an app in case it needs to
// communicate with window.opener later. See crbug.com/65953.
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// If one of the popup tabs navigates back to the app, window.opener should
// be valid.
NavigateTabHelper(browser()->GetTabContentsAt(6), app_url);
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(6)->render_view_host()->process());
bool windowOpenerValid = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(6)->render_view_host(), L"",
L"window.domAutomationController.send(window.opener != null)",
&windowOpenerValid));
ASSERT_TRUE(windowOpenerValid);
}
// Tests that app process switching works properly in the following scenario:
// 1. navigate to a page1 in the app
// 2. page1 redirects to a page2 outside the app extent (ie, "/server-redirect")
// 3. page2 redirects back to a page in the app
// The final navigation should end up in the app process.
// See http://crbug.com/61757
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcessRedirectBack) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(),
base_url.Resolve("path1/redirect.html"));
// Wait until the second tab finishes its redirect train (2 hops).
NavigationController& controller =
browser()->GetSelectedTabContents()->controller();
while (controller.GetActiveEntry()->url().path() !=
"/files/extensions/api_test/app_process/path1/empty.html") {
ui_test_utils::WaitForNavigation(&controller);
}
// 3 tabs, including the initial about:blank. The last 2 should be the same
// process.
ASSERT_EQ(3, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
}
<commit_msg>Small cleanup for previous CL in AppApiTest.AppProcessRedirectBack.<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/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
// The extension should have opened 3 new tabs. Including the original blank
// tab, we now have 4 tabs. Two should be part of the extension app, and
// grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
// TODO(creis): This should open in a new process (i.e., false for the last
// argument), but we temporarily avoid swapping processes away from an app
// until we're able to restore window.opener if the page later returns to an
// in-app URL. See crbug.com/65953.
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), true);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
// TODO(creis): This should swap out of the app's process (i.e., EXPECT_NE),
// but we temporarily avoid swapping away from an app in case it needs to
// communicate with window.opener later. See crbug.com/65953.
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// If one of the popup tabs navigates back to the app, window.opener should
// be valid.
NavigateTabHelper(browser()->GetTabContentsAt(6), app_url);
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(6)->render_view_host()->process());
bool windowOpenerValid = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(6)->render_view_host(), L"",
L"window.domAutomationController.send(window.opener != null)",
&windowOpenerValid));
ASSERT_TRUE(windowOpenerValid);
}
// Tests that app process switching works properly in the following scenario:
// 1. navigate to a page1 in the app
// 2. page1 redirects to a page2 outside the app extent (ie, "/server-redirect")
// 3. page2 redirects back to a page in the app
// The final navigation should end up in the app process.
// See http://crbug.com/61757
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcessRedirectBack) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
// Wait until the second tab finishes its redirect train (2 hops).
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), base_url.Resolve("path1/redirect.html"), 2);
// 3 tabs, including the initial about:blank. The last 2 should be the same
// process.
ASSERT_EQ(3, browser()->tab_count());
EXPECT_EQ("/files/extensions/api_test/app_process/path1/empty.html",
browser()->GetTabContentsAt(2)->controller().
GetLastCommittedEntry()->url().path());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
}
<|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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath path = user_data_dir().Append(chrome::kLocalStateFilename);
return PrefServiceMockBuilder().WithUserFilePrefs(path).Create();
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
TEST_F(MetricsServiceTest, DISABLED_CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (ProxyLauncher::in_process_renderer())
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We can get crash dumps on Windows always, Linux when breakpad is
// enabled, and all platforms for official Google Chrome builds.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) || \
defined(GOOGLE_CHROME_BUILD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<commit_msg>Fix MetricsServiceTest.CloseRenderersNormally for touchui.<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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath path = user_data_dir().Append(chrome::kLocalStateFilename);
return PrefServiceMockBuilder().WithUserFilePrefs(path).Create();
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
#if defined(TOUCH_UI)
// The keyboard page loads for touchui.
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
#else
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
#endif
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
TEST_F(MetricsServiceTest, DISABLED_CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (ProxyLauncher::in_process_renderer())
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We can get crash dumps on Windows always, Linux when breakpad is
// enabled, and all platforms for official Google Chrome builds.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) || \
defined(GOOGLE_CHROME_BUILD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
#if defined(TOUCH_UI)
// The keyboard page loads for touchui.
EXPECT_EQ(5, local_state->GetInteger(prefs::kStabilityPageLoadCount));
#else
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
#endif
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<|endoftext|>
|
<commit_before><commit_msg>Disable IndexTest BUG=70773 TEST=none<commit_after><|endoftext|>
|
<commit_before>// type wrapper
#include "type_wrapper.h"
#include "nan_macros.h"
std::map<const TypeHandle *, std::shared_ptr<const TypeHandle>> TypeWrapper::type_cache;
NAN_METHOD(TypeWrapper::New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
const TypeHandle *t = static_cast<const TypeHandle *>(handle->Value());
std::shared_ptr<const TypeHandle> ty = type_cache[t];
TypeWrapper *instance = new TypeWrapper(ty);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(TypeWrapper::ToString)
{
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
std::string name = wrapper->Type->toString();
info.GetReturnValue().Set(Nan::New(name).ToLocalChecked());
}
NAN_METHOD(TypeWrapper::IsCompatibleWith)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
if (info.Length() == 0 || !Nan::New(prototype)->HasInstance(info[0]))
{
return Nan::ThrowError("Compatibility check requires a type handle");
}
TypeWrapper *other = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[0].As<Object>());
bool isCompatible = self->Type->isCompatibleWith(other->Type.get());
info.GetReturnValue().Set(isCompatible);
}
#define TYPE_PREDICATE(name, pred) \
NAN_METHOD(TypeWrapper::name) \
{ \
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); \
info.GetReturnValue().Set(self->Type->pred()); \
}
TYPE_PREDICATE(IsVoidType, isVoidType);
TYPE_PREDICATE(IsIntType, isIntType);
TYPE_PREDICATE(IsFloatType, isFloatType);
TYPE_PREDICATE(IsArrayType, isArrayType);
TYPE_PREDICATE(IsVectorType, isVectorType);
TYPE_PREDICATE(IsStructType, isStructType);
TYPE_PREDICATE(IsPointerType, isPointerType);
TYPE_PREDICATE(IsFunctionType, isFunctionType);
#define RETURN_IF_TYPE(cls, pred, ret) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
info.GetReturnValue().Set(ty->ret); \
}
#define RETURN_IF_TYPE_W(cls, pred, ret) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
info.GetReturnValue().Set(wrapType(ty->ret)); \
}
#define RETURN_IF_TYPE_R(cls, pred, source) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
\
Local<Context> ctx = Nan::GetCurrentContext(); \
\
Local<Array> types = Nan::New<Array>();\
for (unsigned i = 0, e = ty->source.size(); i < e; i += 1) \
{ \
types->Set(ctx, i, wrapType(ty->source[i])); \
} \
\
info.GetReturnValue().Set(types); \
}
NAN_GETTER(TypeWrapper::GetBitwidth)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE(IntTypeHandle, isIntType, numBits)
RETURN_IF_TYPE(FloatTypeHandle, isFloatType, numBits)
}
NAN_GETTER(TypeWrapper::GetSize)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE(ArrayTypeHandle, isArrayType, size)
RETURN_IF_TYPE(VectorTypeHandle, isVectorType, size)
}
NAN_GETTER(TypeWrapper::GetElement)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(ArrayTypeHandle, isArrayType, element)
RETURN_IF_TYPE_W(VectorTypeHandle, isVectorType, element)
}
NAN_GETTER(TypeWrapper::GetElements)
{
Nan::EscapableHandleScope scope;
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_R(StructTypeHandle, isStructType, elements)
}
NAN_GETTER(TypeWrapper::GetPointee)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(PointerTypeHandle, isPointerType, pointee)
}
NAN_GETTER(TypeWrapper::GetReturns)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(FunctionTypeHandle, isFunctionType, returns)
}
NAN_GETTER(TypeWrapper::GetParameters)
{
Nan::EscapableHandleScope scope;
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_R(FunctionTypeHandle, isFunctionType, params)
}
Handle<Value> TypeWrapper::wrapType(std::shared_ptr<const TypeHandle> type)
{
const TypeHandle *ptr = type.get();
if (type_cache.count(ptr)) {
type = type_cache[ptr];
}
else {
type_cache[type.get()] = type;
}
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)type.get()) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
NAN_MODULE_INIT(TypeWrapper::Init)
{
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(TypeWrapper::New);
tmpl->SetClassName(Nan::New("Type").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "toString", TypeWrapper::ToString);
Nan::SetPrototypeMethod(tmpl, "isCompatibleWith", TypeWrapper::IsCompatibleWith);
Nan::SetPrototypeMethod(tmpl, "isVoidType", TypeWrapper::IsVoidType);
Nan::SetPrototypeMethod(tmpl, "isIntType", TypeWrapper::IsIntType);
Nan::SetPrototypeMethod(tmpl, "isFloatType", TypeWrapper::IsFloatType);
Nan::SetPrototypeMethod(tmpl, "isArrayType", TypeWrapper::IsArrayType);
Nan::SetPrototypeMethod(tmpl, "isVectorType", TypeWrapper::IsVectorType);
Nan::SetPrototypeMethod(tmpl, "isStructType", TypeWrapper::IsStructType);
Nan::SetPrototypeMethod(tmpl, "isPointerType", TypeWrapper::IsPointerType);
Nan::SetPrototypeMethod(tmpl, "isFunctionType", TypeWrapper::IsFunctionType);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("bitwidth").ToLocalChecked(), GetBitwidth);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("size").ToLocalChecked(), GetSize);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("element").ToLocalChecked(), GetElement);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("elements").ToLocalChecked(), GetElements);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("pointee").ToLocalChecked(), GetPointee);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("returns").ToLocalChecked(), GetReturns);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("parameters").ToLocalChecked(), GetParameters);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("Type").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
prototype.Reset(tmpl);
}
NAN_METHOD(TypeWrapper::GetVoidTy)
{
info.GetReturnValue().Set(wrapType(std::make_shared<VoidTypeHandle>()));
}
NAN_METHOD(TypeWrapper::GetIntTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide integer bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits < MIN_INT_BITS) {
return Nan::ThrowError("Integer bit width below the minimum");
}
if (requestedBits > MAX_INT_BITS) {
return Nan::ThrowError("Integer bit width above the maximum");
}
unsigned bits = (unsigned)requestedBits;
if (bits != requestedBits) {
return Nan::ThrowError("Integer bit width not valid");
}
info.GetReturnValue().Set(wrapType(std::make_shared<IntTypeHandle>(bits)));
}
NAN_METHOD(TypeWrapper::GetFloatTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide float bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits != 16 && requestedBits != 32 && requestedBits != 64)
{
return Nan::ThrowError("Invalid float bit width");
}
unsigned bits = (unsigned)requestedBits;
info.GetReturnValue().Set(wrapType(std::make_shared<FloatTypeHandle>(bits)));
}
NAN_METHOD(TypeWrapper::GetPointerTy)
{
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide pointee type");
}
Local<Object> handle = info[0]->ToObject();
if (!Nan::New(prototype)->HasInstance(handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
info.GetReturnValue().Set(wrapType(std::make_shared<PointerTypeHandle>(wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetVectorTy)
{
unsigned size;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide vector size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
EXPECT_PARAM("GetVectorTy", 1, TypeWrapper, "element type")
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[1]->ToObject());
info.GetReturnValue().Set(wrapType(std::make_shared<VectorTypeHandle>(size, wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetArrayTy)
{
unsigned size;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide array size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
if (info.Length() == 1)
{
return Nan::ThrowError("Must provide array element type");
}
Local<Object> handle = info[1]->ToObject();
if (!Nan::New(prototype)->HasInstance(handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
info.GetReturnValue().Set(wrapType(std::make_shared<ArrayTypeHandle>(size, wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetStructTy)
{
if (info.Length() == 0)
{
return Nan::ThrowError("Struct type expects a list of element types");
}
if (!info[0]->IsArray())
{
return Nan::ThrowError("Struct type expects a list of element types");
}
Local<Array> types = info[0].As<Array>();
std::vector<std::shared_ptr<const TypeHandle>> elementTypes;
unsigned e = types->Length();
elementTypes.reserve(e);
Local<FunctionTemplate> proto = Nan::New(prototype);
for (unsigned i = 0; i < e; i += 1)
{
Local<Value> type = types->Get(i);
if (!proto->HasInstance(type))
{
return Nan::ThrowError("Struct type expects a list of element types");
}
TypeWrapper *el = Nan::ObjectWrap::Unwrap<TypeWrapper>(type.As<Object>());
elementTypes.push_back(el->Type);
}
info.GetReturnValue().Set(wrapType(std::make_shared<StructTypeHandle>(elementTypes)));
}
NAN_METHOD(TypeWrapper::GetFunctionTy)
{
EXTRACT_FUNCTION_PARAMS(0)
info.GetReturnValue().Set(wrapType(std::make_shared<FunctionTypeHandle>(returns, takes)));
}
Nan::Persistent<FunctionTemplate> TypeWrapper::prototype;
<commit_msg>use std::move in TypeWrapper::wrapType<commit_after>// type wrapper
#include "type_wrapper.h"
#include "nan_macros.h"
std::map<const TypeHandle *, std::shared_ptr<const TypeHandle>> TypeWrapper::type_cache;
NAN_METHOD(TypeWrapper::New)
{
if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal())
{
return Nan::ThrowError("Cannot instantiate type directly, use factory");
}
Handle<External> handle = Handle<External>::Cast(info[0]);
const TypeHandle *t = static_cast<const TypeHandle *>(handle->Value());
std::shared_ptr<const TypeHandle> ty = type_cache[t];
TypeWrapper *instance = new TypeWrapper(ty);
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(TypeWrapper::ToString)
{
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
std::string name = wrapper->Type->toString();
info.GetReturnValue().Set(Nan::New(name).ToLocalChecked());
}
NAN_METHOD(TypeWrapper::IsCompatibleWith)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
if (info.Length() == 0 || !Nan::New(prototype)->HasInstance(info[0]))
{
return Nan::ThrowError("Compatibility check requires a type handle");
}
TypeWrapper *other = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[0].As<Object>());
bool isCompatible = self->Type->isCompatibleWith(other->Type.get());
info.GetReturnValue().Set(isCompatible);
}
#define TYPE_PREDICATE(name, pred) \
NAN_METHOD(TypeWrapper::name) \
{ \
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); \
info.GetReturnValue().Set(self->Type->pred()); \
}
TYPE_PREDICATE(IsVoidType, isVoidType);
TYPE_PREDICATE(IsIntType, isIntType);
TYPE_PREDICATE(IsFloatType, isFloatType);
TYPE_PREDICATE(IsArrayType, isArrayType);
TYPE_PREDICATE(IsVectorType, isVectorType);
TYPE_PREDICATE(IsStructType, isStructType);
TYPE_PREDICATE(IsPointerType, isPointerType);
TYPE_PREDICATE(IsFunctionType, isFunctionType);
#define RETURN_IF_TYPE(cls, pred, ret) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
info.GetReturnValue().Set(ty->ret); \
}
#define RETURN_IF_TYPE_W(cls, pred, ret) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
info.GetReturnValue().Set(wrapType(ty->ret)); \
}
#define RETURN_IF_TYPE_R(cls, pred, source) \
if (self->Type->pred()) \
{ \
const cls *ty = static_cast<const cls *>(self->Type.get()); \
\
Local<Context> ctx = Nan::GetCurrentContext(); \
\
Local<Array> types = Nan::New<Array>();\
for (unsigned i = 0, e = ty->source.size(); i < e; i += 1) \
{ \
types->Set(ctx, i, wrapType(ty->source[i])); \
} \
\
info.GetReturnValue().Set(types); \
}
NAN_GETTER(TypeWrapper::GetBitwidth)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE(IntTypeHandle, isIntType, numBits)
RETURN_IF_TYPE(FloatTypeHandle, isFloatType, numBits)
}
NAN_GETTER(TypeWrapper::GetSize)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE(ArrayTypeHandle, isArrayType, size)
RETURN_IF_TYPE(VectorTypeHandle, isVectorType, size)
}
NAN_GETTER(TypeWrapper::GetElement)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(ArrayTypeHandle, isArrayType, element)
RETURN_IF_TYPE_W(VectorTypeHandle, isVectorType, element)
}
NAN_GETTER(TypeWrapper::GetElements)
{
Nan::EscapableHandleScope scope;
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_R(StructTypeHandle, isStructType, elements)
}
NAN_GETTER(TypeWrapper::GetPointee)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(PointerTypeHandle, isPointerType, pointee)
}
NAN_GETTER(TypeWrapper::GetReturns)
{
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_W(FunctionTypeHandle, isFunctionType, returns)
}
NAN_GETTER(TypeWrapper::GetParameters)
{
Nan::EscapableHandleScope scope;
TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This());
RETURN_IF_TYPE_R(FunctionTypeHandle, isFunctionType, params)
}
Handle<Value> TypeWrapper::wrapType(std::shared_ptr<const TypeHandle> type)
{
const TypeHandle *ptr = type.get();
if (!type_cache.count(ptr)) {
type_cache[type.get()] = std::move(type);
}
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { Nan::New<External>((void *)ptr) };
Local<Function> cons = Nan::New(constructor());
return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
NAN_MODULE_INIT(TypeWrapper::Init)
{
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(TypeWrapper::New);
tmpl->SetClassName(Nan::New("Type").ToLocalChecked());
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tmpl, "toString", TypeWrapper::ToString);
Nan::SetPrototypeMethod(tmpl, "isCompatibleWith", TypeWrapper::IsCompatibleWith);
Nan::SetPrototypeMethod(tmpl, "isVoidType", TypeWrapper::IsVoidType);
Nan::SetPrototypeMethod(tmpl, "isIntType", TypeWrapper::IsIntType);
Nan::SetPrototypeMethod(tmpl, "isFloatType", TypeWrapper::IsFloatType);
Nan::SetPrototypeMethod(tmpl, "isArrayType", TypeWrapper::IsArrayType);
Nan::SetPrototypeMethod(tmpl, "isVectorType", TypeWrapper::IsVectorType);
Nan::SetPrototypeMethod(tmpl, "isStructType", TypeWrapper::IsStructType);
Nan::SetPrototypeMethod(tmpl, "isPointerType", TypeWrapper::IsPointerType);
Nan::SetPrototypeMethod(tmpl, "isFunctionType", TypeWrapper::IsFunctionType);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("bitwidth").ToLocalChecked(), GetBitwidth);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("size").ToLocalChecked(), GetSize);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("element").ToLocalChecked(), GetElement);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("elements").ToLocalChecked(), GetElements);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("pointee").ToLocalChecked(), GetPointee);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("returns").ToLocalChecked(), GetReturns);
Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("parameters").ToLocalChecked(), GetParameters);
constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked());
Nan::Set(target, Nan::New("Type").ToLocalChecked(),
Nan::GetFunction(tmpl).ToLocalChecked());
prototype.Reset(tmpl);
}
NAN_METHOD(TypeWrapper::GetVoidTy)
{
info.GetReturnValue().Set(wrapType(std::make_shared<VoidTypeHandle>()));
}
NAN_METHOD(TypeWrapper::GetIntTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide integer bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits < MIN_INT_BITS) {
return Nan::ThrowError("Integer bit width below the minimum");
}
if (requestedBits > MAX_INT_BITS) {
return Nan::ThrowError("Integer bit width above the maximum");
}
unsigned bits = (unsigned)requestedBits;
if (bits != requestedBits) {
return Nan::ThrowError("Integer bit width not valid");
}
info.GetReturnValue().Set(wrapType(std::make_shared<IntTypeHandle>(bits)));
}
NAN_METHOD(TypeWrapper::GetFloatTy)
{
if (info.Length() == 0 || !info[0]->IsNumber()) {
return Nan::ThrowError("Must provide float bit width");
}
Local<Number> bitWidth = info[0].As<Number>();
double requestedBits = bitWidth->Value();
if (requestedBits != 16 && requestedBits != 32 && requestedBits != 64)
{
return Nan::ThrowError("Invalid float bit width");
}
unsigned bits = (unsigned)requestedBits;
info.GetReturnValue().Set(wrapType(std::make_shared<FloatTypeHandle>(bits)));
}
NAN_METHOD(TypeWrapper::GetPointerTy)
{
if (info.Length() == 0)
{
return Nan::ThrowError("Must provide pointee type");
}
Local<Object> handle = info[0]->ToObject();
if (!Nan::New(prototype)->HasInstance(handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
info.GetReturnValue().Set(wrapType(std::make_shared<PointerTypeHandle>(wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetVectorTy)
{
unsigned size;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide vector size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
EXPECT_PARAM("GetVectorTy", 1, TypeWrapper, "element type")
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[1]->ToObject());
info.GetReturnValue().Set(wrapType(std::make_shared<VectorTypeHandle>(size, wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetArrayTy)
{
unsigned size;
if (info.Length() == 0 || !info[0]->IsNumber())
{
return Nan::ThrowError("Must provide array size");
}
Local<Number> sizeNumber = info[0].As<Number>();
double sizeDouble = sizeNumber->Value();
size = (unsigned)sizeDouble;
if (info.Length() == 1)
{
return Nan::ThrowError("Must provide array element type");
}
Local<Object> handle = info[1]->ToObject();
if (!Nan::New(prototype)->HasInstance(handle))
{
return Nan::ThrowError("Argument must be a type specifier");
}
TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle);
info.GetReturnValue().Set(wrapType(std::make_shared<ArrayTypeHandle>(size, wrapper->Type)));
}
NAN_METHOD(TypeWrapper::GetStructTy)
{
if (info.Length() == 0)
{
return Nan::ThrowError("Struct type expects a list of element types");
}
if (!info[0]->IsArray())
{
return Nan::ThrowError("Struct type expects a list of element types");
}
Local<Array> types = info[0].As<Array>();
std::vector<std::shared_ptr<const TypeHandle>> elementTypes;
unsigned e = types->Length();
elementTypes.reserve(e);
Local<FunctionTemplate> proto = Nan::New(prototype);
for (unsigned i = 0; i < e; i += 1)
{
Local<Value> type = types->Get(i);
if (!proto->HasInstance(type))
{
return Nan::ThrowError("Struct type expects a list of element types");
}
TypeWrapper *el = Nan::ObjectWrap::Unwrap<TypeWrapper>(type.As<Object>());
elementTypes.push_back(el->Type);
}
info.GetReturnValue().Set(wrapType(std::make_shared<StructTypeHandle>(elementTypes)));
}
NAN_METHOD(TypeWrapper::GetFunctionTy)
{
EXTRACT_FUNCTION_PARAMS(0)
info.GetReturnValue().Set(wrapType(std::make_shared<FunctionTypeHandle>(returns, takes)));
}
Nan::Persistent<FunctionTemplate> TypeWrapper::prototype;
<|endoftext|>
|
<commit_before>// This code is in the public domain -- castano@gmail.com
#include "FileSystem.h"
#include <nvcore/nvcore.h>
#if NV_OS_WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
using namespace nv;
bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
return access(path, F_OK|R_OK) == 0;
//struct stat buf;
//return stat(path, &buf) == 0;
#else
if (FILE * fp = fopen(path, "r"))
{
fclose(fp);
return true;
}
return false;
#endif
}
bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
return _mkdir(path) != -1;
#else
return mkdir(path, 0777) != -1;
#endif
}
<commit_msg>Implement FileSystem::exists correctly on win32.<commit_after>// This code is in the public domain -- castano@gmail.com
#include "FileSystem.h"
#include <nvcore/nvcore.h>
#if NV_OS_WIN32
//#include <shlwapi.h> // PathFileExists
#include <windows.h> // GetFileAttributes
#include <direct.h> // _mkdir
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
using namespace nv;
bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
return access(path, F_OK|R_OK) == 0;
//struct stat buf;
//return stat(path, &buf) == 0;
#elif NV_OS_WIN32
// PathFileExists requires linking to shlwapi.lib
//return PathFileExists(path) != 0;
return GetFileAttributes(path) != 0xFFFFFFFF;
#else
if (FILE * fp = fopen(path, "r"))
{
fclose(fp);
return true;
}
return false;
#endif
}
bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
return _mkdir(path) != -1;
#else
return mkdir(path, 0777) != -1;
#endif
}
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <qitype/objecttypebuilder.hpp>
#include <boost/thread.hpp>
#include <qitype/genericobject.hpp>
#include "staticobjecttype.hpp"
#include "metaobject_p.hpp"
namespace qi {
class ObjectTypeBuilderPrivate
{
public:
ObjectTypeBuilderPrivate() : type(0) {}
ObjectTypeData data;
ObjectType* type;
MetaObject metaObject;
};
ObjectTypeBuilderBase::ObjectTypeBuilderBase()
: _p(new ObjectTypeBuilderPrivate())
{
}
ObjectTypeBuilderBase::~ObjectTypeBuilderBase()
{
delete _p;
}
int ObjectTypeBuilderBase::xAdvertiseMethod(const std::string &retsig, const std::string& signature, GenericMethod func, int id)
{
unsigned int nextId = _p->metaObject._p->addMethod(retsig, signature, id);
_p->data.methodMap[nextId] = func;
return nextId;
}
int ObjectTypeBuilderBase::xAdvertiseEvent(const std::string& signature, SignalMemberGetter getter, int id)
{
unsigned int nextId = _p->metaObject._p->addSignal(signature, id);
_p->data.signalGetterMap[nextId] = getter;
return nextId;
}
void ObjectTypeBuilderBase::xBuildFor(Type* type, boost::function<Manageable* (void*)> asManageable)
{
_p->data.asManageable = asManageable;
_p->data.classType = type;
}
const MetaObject& ObjectTypeBuilderBase::metaObject()
{
_p->metaObject._p->refreshCache();
return _p->metaObject;
}
ObjectPtr ObjectTypeBuilderBase::object(void* ptr)
{
ObjectPtr ret = ObjectPtr(new GenericObject(type(), ptr));
return ret;
}
ObjectType* ObjectTypeBuilderBase::type()
{
if (!_p->type)
{
StaticObjectTypeBase* t = new StaticObjectTypeBase();
t->initialize(metaObject(), _p->data);
_p->type = t;
registerType();
}
return _p->type;
}
void ObjectTypeBuilderBase::inherits(Type* type, int offset)
{
std::vector<std::pair<Type*, int> >& p = _p->data.parentTypes;
if (type->info() != _p->data.classType->info() && std::find(p.begin(), p.end(),
std::make_pair(type, offset)) == p.end())
{
qiLogVerbose("qi.meta") << "Declaring inheritance "
<< _p->data.classType->infoString() << " <- " << type->infoString();
p.push_back(std::make_pair(type, offset));
}
}
}
<commit_msg>ObjectTypeBuilder: screams when calling advertise* after type()<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <qitype/objecttypebuilder.hpp>
#include <boost/thread.hpp>
#include <qitype/genericobject.hpp>
#include "staticobjecttype.hpp"
#include "metaobject_p.hpp"
namespace qi {
class ObjectTypeBuilderPrivate
{
public:
ObjectTypeBuilderPrivate() : type(0) {}
ObjectTypeData data;
ObjectType* type;
MetaObject metaObject;
};
ObjectTypeBuilderBase::ObjectTypeBuilderBase()
: _p(new ObjectTypeBuilderPrivate())
{
}
ObjectTypeBuilderBase::~ObjectTypeBuilderBase()
{
delete _p;
}
int ObjectTypeBuilderBase::xAdvertiseMethod(const std::string &retsig, const std::string& signature, GenericMethod func, int id)
{
if (_p->type) {
qiLogError("ObjectTypeBuilder") << "ObjectTypeBuilder: Can't call xAdvertiseMethod with method '"
<< retsig << " " << signature << "' because type is already created.";
return -1;
}
unsigned int nextId = _p->metaObject._p->addMethod(retsig, signature, id);
_p->data.methodMap[nextId] = func;
return nextId;
}
int ObjectTypeBuilderBase::xAdvertiseEvent(const std::string& signature, SignalMemberGetter getter, int id)
{
if (_p->type) {
qiLogError("ObjectTypeBuilder") << "ObjectTypeBuilder: Can't call xAdvertiseEvent with event '"
<< signature << "' because type is already created.";
return -1;
}
unsigned int nextId = _p->metaObject._p->addSignal(signature, id);
_p->data.signalGetterMap[nextId] = getter;
return nextId;
}
void ObjectTypeBuilderBase::xBuildFor(Type* type, boost::function<Manageable* (void*)> asManageable)
{
_p->data.asManageable = asManageable;
_p->data.classType = type;
}
const MetaObject& ObjectTypeBuilderBase::metaObject()
{
_p->metaObject._p->refreshCache();
return _p->metaObject;
}
ObjectPtr ObjectTypeBuilderBase::object(void* ptr)
{
ObjectPtr ret = ObjectPtr(new GenericObject(type(), ptr));
return ret;
}
ObjectType* ObjectTypeBuilderBase::type()
{
if (!_p->type)
{
StaticObjectTypeBase* t = new StaticObjectTypeBase();
t->initialize(metaObject(), _p->data);
_p->type = t;
registerType();
}
return _p->type;
}
void ObjectTypeBuilderBase::inherits(Type* type, int offset)
{
std::vector<std::pair<Type*, int> >& p = _p->data.parentTypes;
if (type->info() != _p->data.classType->info() && std::find(p.begin(), p.end(),
std::make_pair(type, offset)) == p.end())
{
qiLogVerbose("qi.meta") << "Declaring inheritance "
<< _p->data.classType->infoString() << " <- " << type->infoString();
p.push_back(std::make_pair(type, offset));
}
}
}
<|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 "ash/wm/app_list_controller.h"
#include "ash/ash_switches.h"
#include "ash/launcher/launcher.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/shell_window_ids.h"
#include "base/command_line.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_view.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/transform_util.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
namespace {
// Duration for show/hide animation in milliseconds.
const int kAnimationDurationMs = 200;
// Offset in pixels to animation away/towards the launcher.
const int kAnimationOffset = 8;
// The maximum shift in pixels when over-scroll happens.
const int kMaxOverScrollShift = 48;
// The minimal anchor position offset to make sure that the bubble is still on
// the screen with 8 pixels spacing on the left / right. This constant is a
// result of minimal bubble arrow sizes and offsets.
const int kMinimalAnchorPositionOffset = 57;
ui::Layer* GetLayer(views::Widget* widget) {
return widget->GetNativeView()->layer();
}
// Gets arrow location based on shelf alignment.
views::BubbleBorder::Arrow GetBubbleArrow(aura::Window* window) {
DCHECK(Shell::HasInstance());
return ShelfLayoutManager::ForLauncher(window)->
SelectValueForShelfAlignment(
views::BubbleBorder::BOTTOM_CENTER,
views::BubbleBorder::LEFT_CENTER,
views::BubbleBorder::RIGHT_CENTER,
views::BubbleBorder::TOP_CENTER);
}
// Offset given |rect| towards shelf.
gfx::Rect OffsetTowardsShelf(const gfx::Rect& rect, views::Widget* widget) {
DCHECK(Shell::HasInstance());
ShelfAlignment shelf_alignment = Shell::GetInstance()->GetShelfAlignment(
widget->GetNativeView()->GetRootWindow());
gfx::Rect offseted(rect);
switch (shelf_alignment) {
case SHELF_ALIGNMENT_BOTTOM:
offseted.Offset(0, kAnimationOffset);
break;
case SHELF_ALIGNMENT_LEFT:
offseted.Offset(-kAnimationOffset, 0);
break;
case SHELF_ALIGNMENT_RIGHT:
offseted.Offset(kAnimationOffset, 0);
break;
case SHELF_ALIGNMENT_TOP:
offseted.Offset(0, -kAnimationOffset);
break;
}
return offseted;
}
// Using |button_bounds|, determine the anchor offset so that the bubble gets
// shown above the shelf (used for the alternate shelf theme).
gfx::Vector2d GetAnchorPositionOffsetToShelf(
const gfx::Rect& button_bounds, views::Widget* widget) {
DCHECK(Shell::HasInstance());
ShelfAlignment shelf_alignment = Shell::GetInstance()->GetShelfAlignment(
widget->GetNativeView()->GetRootWindow());
gfx::Point anchor(button_bounds.CenterPoint());
switch (shelf_alignment) {
case SHELF_ALIGNMENT_TOP:
case SHELF_ALIGNMENT_BOTTOM:
if (base::i18n::IsRTL()) {
int screen_width = widget->GetWorkAreaBoundsInScreen().width();
return gfx::Vector2d(
std::min(screen_width - kMinimalAnchorPositionOffset - anchor.x(),
0), 0);
}
return gfx::Vector2d(
std::max(kMinimalAnchorPositionOffset - anchor.x(), 0), 0);
case SHELF_ALIGNMENT_LEFT:
return gfx::Vector2d(
0, std::max(kMinimalAnchorPositionOffset - anchor.y(), 0));
case SHELF_ALIGNMENT_RIGHT:
return gfx::Vector2d(
0, std::max(kMinimalAnchorPositionOffset - anchor.y(), 0));
default:
NOTREACHED();
return gfx::Vector2d();
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// AppListController, public:
AppListController::AppListController()
: pagination_model_(new app_list::PaginationModel),
is_visible_(false),
view_(NULL),
should_snap_back_(false) {
Shell::GetInstance()->AddShellObserver(this);
pagination_model_->AddObserver(this);
}
AppListController::~AppListController() {
// Ensures app list view goes before the controller since pagination model
// lives in the controller and app list view would access it on destruction.
if (view_ && view_->GetWidget())
view_->GetWidget()->CloseNow();
Shell::GetInstance()->RemoveShellObserver(this);
pagination_model_->RemoveObserver(this);
}
void AppListController::SetVisible(bool visible, aura::Window* window) {
if (visible == is_visible_)
return;
is_visible_ = visible;
// App list needs to know the new shelf layout in order to calculate its
// UI layout when AppListView visibility changes.
Shell::GetPrimaryRootWindowController()->GetShelfLayoutManager()->
UpdateAutoHideState();
if (view_) {
ScheduleAnimation();
} else if (is_visible_) {
// AppListModel and AppListViewDelegate are owned by AppListView. They
// will be released with AppListView on close.
app_list::AppListView* view = new app_list::AppListView(
Shell::GetInstance()->delegate()->CreateAppListViewDelegate());
aura::Window* container = GetRootWindowController(window->GetRootWindow())->
GetContainer(kShellWindowId_AppListContainer);
if (ash::switches::UseAlternateShelfLayout()) {
gfx::Rect applist_button_bounds = Launcher::ForWindow(container)->
GetAppListButtonView()->GetBoundsInScreen();
view->InitAsBubbleAttachedToAnchor(
container,
pagination_model_.get(),
Launcher::ForWindow(container)->GetAppListButtonView(),
GetAnchorPositionOffsetToShelf(applist_button_bounds,
Launcher::ForWindow(container)->GetAppListButtonView()->
GetWidget()),
GetBubbleArrow(container),
true /* border_accepts_events */);
view->SetArrowPaintType(views::BubbleBorder::PAINT_NONE);
} else {
view->InitAsBubbleAttachedToAnchor(
container,
pagination_model_.get(),
Launcher::ForWindow(container)->GetAppListButtonView(),
gfx::Vector2d(),
GetBubbleArrow(container),
true /* border_accepts_events */);
}
SetView(view);
// By setting us as DnD recipient, the app list knows that we can
// handle items.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kAshDisableDragAndDropAppListToLauncher)) {
SetDragAndDropHostOfCurrentAppList(
Launcher::ForWindow(window)->GetDragAndDropHostForAppList());
}
}
// Update applist button status when app list visibility is changed.
Launcher::ForWindow(window)->GetAppListButtonView()->SchedulePaint();
}
bool AppListController::IsVisible() const {
return view_ && view_->GetWidget()->IsVisible();
}
aura::Window* AppListController::GetWindow() {
return is_visible_ && view_ ? view_->GetWidget()->GetNativeWindow() : NULL;
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, private:
void AppListController::SetDragAndDropHostOfCurrentAppList(
app_list::ApplicationDragAndDropHost* drag_and_drop_host) {
if (view_ && is_visible_)
view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}
void AppListController::SetView(app_list::AppListView* view) {
DCHECK(view_ == NULL);
DCHECK(is_visible_);
view_ = view;
views::Widget* widget = view_->GetWidget();
widget->AddObserver(this);
Shell::GetInstance()->AddPreTargetHandler(this);
Launcher::ForWindow(widget->GetNativeWindow())->AddIconObserver(this);
widget->GetNativeView()->GetRootWindow()->AddObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->AddObserver(this);
view_->ShowWhenReady();
}
void AppListController::ResetView() {
if (!view_)
return;
views::Widget* widget = view_->GetWidget();
widget->RemoveObserver(this);
GetLayer(widget)->GetAnimator()->RemoveObserver(this);
Shell::GetInstance()->RemovePreTargetHandler(this);
Launcher::ForWindow(widget->GetNativeWindow())->RemoveIconObserver(this);
widget->GetNativeView()->GetRootWindow()->RemoveObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->RemoveObserver(this);
view_ = NULL;
}
void AppListController::ScheduleAnimation() {
// Stop observing previous animation.
StopObservingImplicitAnimations();
views::Widget* widget = view_->GetWidget();
ui::Layer* layer = GetLayer(widget);
layer->GetAnimator()->StopAnimating();
gfx::Rect target_bounds;
if (is_visible_) {
target_bounds = widget->GetWindowBoundsInScreen();
widget->SetBounds(OffsetTowardsShelf(target_bounds, widget));
} else {
target_bounds = OffsetTowardsShelf(widget->GetWindowBoundsInScreen(),
widget);
}
ui::ScopedLayerAnimationSettings animation(layer->GetAnimator());
animation.SetTransitionDuration(
base::TimeDelta::FromMilliseconds(
is_visible_ ? 0 : kAnimationDurationMs));
animation.AddObserver(this);
layer->SetOpacity(is_visible_ ? 1.0 : 0.0);
widget->SetBounds(target_bounds);
}
void AppListController::ProcessLocatedEvent(ui::LocatedEvent* event) {
// If the event happened on a menu, then the event should not close the app
// list.
aura::Window* target = static_cast<aura::Window*>(event->target());
if (target) {
RootWindowController* root_controller =
GetRootWindowController(target->GetRootWindow());
if (root_controller) {
aura::Window* menu_container = root_controller->GetContainer(
ash::internal::kShellWindowId_MenuContainer);
if (menu_container->Contains(target))
return;
}
}
if (view_ && is_visible_) {
aura::Window* window = view_->GetWidget()->GetNativeView();
gfx::Point window_local_point(event->root_location());
aura::Window::ConvertPointToTarget(window->GetRootWindow(),
window,
&window_local_point);
// Use HitTest to respect the hit test mask of the bubble.
if (!window->HitTest(window_local_point))
SetVisible(false, window);
}
}
void AppListController::UpdateBounds() {
if (view_ && is_visible_)
view_->UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::EventFilter implementation:
void AppListController::OnMouseEvent(ui::MouseEvent* event) {
if (event->type() == ui::ET_MOUSE_PRESSED)
ProcessLocatedEvent(event);
}
void AppListController::OnGestureEvent(ui::GestureEvent* event) {
if (event->type() == ui::ET_GESTURE_TAP_DOWN)
ProcessLocatedEvent(event);
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::FocusObserver implementation:
void AppListController::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
if (gained_focus && view_ && is_visible_) {
aura::Window* applist_container =
GetRootWindowController(gained_focus->GetRootWindow())->GetContainer(
kShellWindowId_AppListContainer);
if (gained_focus->parent() != applist_container)
SetVisible(false, gained_focus);
}
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::WindowObserver implementation:
void AppListController::OnWindowBoundsChanged(aura::Window* root,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, ui::ImplicitAnimationObserver implementation:
void AppListController::OnImplicitAnimationsCompleted() {
if (is_visible_ )
view_->GetWidget()->Activate();
else
view_->GetWidget()->Close();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, views::WidgetObserver implementation:
void AppListController::OnWidgetDestroying(views::Widget* widget) {
DCHECK(view_->GetWidget() == widget);
if (is_visible_)
SetVisible(false, widget->GetNativeView());
ResetView();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, ShellObserver implementation:
void AppListController::OnShelfAlignmentChanged(aura::RootWindow* root_window) {
if (view_)
view_->SetBubbleArrow(GetBubbleArrow(view_->GetWidget()->GetNativeView()));
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, LauncherIconObserver implementation:
void AppListController::OnLauncherIconPositionsChanged() {
UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, PaginationModelObserver implementation:
void AppListController::TotalPagesChanged() {
}
void AppListController::SelectedPageChanged(int old_selected,
int new_selected) {
}
void AppListController::TransitionStarted() {
}
void AppListController::TransitionChanged() {
// |view_| could be NULL when app list is closed with a running transition.
if (!view_)
return;
const app_list::PaginationModel::Transition& transition =
pagination_model_->transition();
if (pagination_model_->is_valid_page(transition.target_page))
return;
views::Widget* widget = view_->GetWidget();
ui::LayerAnimator* widget_animator = GetLayer(widget)->GetAnimator();
if (!pagination_model_->IsRevertingCurrentTransition()) {
// Update cached |view_bounds_| if it is the first over-scroll move and
// widget does not have running animations.
if (!should_snap_back_ && !widget_animator->is_animating())
view_bounds_ = widget->GetWindowBoundsInScreen();
const int current_page = pagination_model_->selected_page();
const int dir = transition.target_page > current_page ? -1 : 1;
const double progress = 1.0 - pow(1.0 - transition.progress, 4);
const int shift = kMaxOverScrollShift * progress * dir;
gfx::Rect shifted(view_bounds_);
shifted.set_x(shifted.x() + shift);
widget->SetBounds(shifted);
should_snap_back_ = true;
} else if (should_snap_back_) {
should_snap_back_ = false;
ui::ScopedLayerAnimationSettings animation(widget_animator);
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
app_list::kOverscrollPageTransitionDurationMs));
widget->SetBounds(view_bounds_);
}
}
} // namespace internal
} // namespace ash
<commit_msg>Fixing problem where opening a menu while closing another can close the new menu unexpectedly<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 "ash/wm/app_list_controller.h"
#include "ash/ash_switches.h"
#include "ash/launcher/launcher.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/shell_window_ids.h"
#include "base/command_line.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_view.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/transform_util.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
namespace {
// Duration for show/hide animation in milliseconds.
const int kAnimationDurationMs = 200;
// Offset in pixels to animation away/towards the launcher.
const int kAnimationOffset = 8;
// The maximum shift in pixels when over-scroll happens.
const int kMaxOverScrollShift = 48;
// The minimal anchor position offset to make sure that the bubble is still on
// the screen with 8 pixels spacing on the left / right. This constant is a
// result of minimal bubble arrow sizes and offsets.
const int kMinimalAnchorPositionOffset = 57;
ui::Layer* GetLayer(views::Widget* widget) {
return widget->GetNativeView()->layer();
}
// Gets arrow location based on shelf alignment.
views::BubbleBorder::Arrow GetBubbleArrow(aura::Window* window) {
DCHECK(Shell::HasInstance());
return ShelfLayoutManager::ForLauncher(window)->
SelectValueForShelfAlignment(
views::BubbleBorder::BOTTOM_CENTER,
views::BubbleBorder::LEFT_CENTER,
views::BubbleBorder::RIGHT_CENTER,
views::BubbleBorder::TOP_CENTER);
}
// Offset given |rect| towards shelf.
gfx::Rect OffsetTowardsShelf(const gfx::Rect& rect, views::Widget* widget) {
DCHECK(Shell::HasInstance());
ShelfAlignment shelf_alignment = Shell::GetInstance()->GetShelfAlignment(
widget->GetNativeView()->GetRootWindow());
gfx::Rect offseted(rect);
switch (shelf_alignment) {
case SHELF_ALIGNMENT_BOTTOM:
offseted.Offset(0, kAnimationOffset);
break;
case SHELF_ALIGNMENT_LEFT:
offseted.Offset(-kAnimationOffset, 0);
break;
case SHELF_ALIGNMENT_RIGHT:
offseted.Offset(kAnimationOffset, 0);
break;
case SHELF_ALIGNMENT_TOP:
offseted.Offset(0, -kAnimationOffset);
break;
}
return offseted;
}
// Using |button_bounds|, determine the anchor offset so that the bubble gets
// shown above the shelf (used for the alternate shelf theme).
gfx::Vector2d GetAnchorPositionOffsetToShelf(
const gfx::Rect& button_bounds, views::Widget* widget) {
DCHECK(Shell::HasInstance());
ShelfAlignment shelf_alignment = Shell::GetInstance()->GetShelfAlignment(
widget->GetNativeView()->GetRootWindow());
gfx::Point anchor(button_bounds.CenterPoint());
switch (shelf_alignment) {
case SHELF_ALIGNMENT_TOP:
case SHELF_ALIGNMENT_BOTTOM:
if (base::i18n::IsRTL()) {
int screen_width = widget->GetWorkAreaBoundsInScreen().width();
return gfx::Vector2d(
std::min(screen_width - kMinimalAnchorPositionOffset - anchor.x(),
0), 0);
}
return gfx::Vector2d(
std::max(kMinimalAnchorPositionOffset - anchor.x(), 0), 0);
case SHELF_ALIGNMENT_LEFT:
return gfx::Vector2d(
0, std::max(kMinimalAnchorPositionOffset - anchor.y(), 0));
case SHELF_ALIGNMENT_RIGHT:
return gfx::Vector2d(
0, std::max(kMinimalAnchorPositionOffset - anchor.y(), 0));
default:
NOTREACHED();
return gfx::Vector2d();
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// AppListController, public:
AppListController::AppListController()
: pagination_model_(new app_list::PaginationModel),
is_visible_(false),
view_(NULL),
should_snap_back_(false) {
Shell::GetInstance()->AddShellObserver(this);
pagination_model_->AddObserver(this);
}
AppListController::~AppListController() {
// Ensures app list view goes before the controller since pagination model
// lives in the controller and app list view would access it on destruction.
if (view_ && view_->GetWidget())
view_->GetWidget()->CloseNow();
Shell::GetInstance()->RemoveShellObserver(this);
pagination_model_->RemoveObserver(this);
}
void AppListController::SetVisible(bool visible, aura::Window* window) {
if (visible == is_visible_)
return;
is_visible_ = visible;
// App list needs to know the new shelf layout in order to calculate its
// UI layout when AppListView visibility changes.
Shell::GetPrimaryRootWindowController()->GetShelfLayoutManager()->
UpdateAutoHideState();
if (view_) {
// Our widget is currently active. When the animation completes we'll hide
// the widget, changing activation. If a menu is shown before the animation
// completes then the activation change triggers the menu to close. By
// deactivating now we ensure there is no activation change when the
// animation completes and any menus stay open.
if (!visible)
view_->GetWidget()->Deactivate();
ScheduleAnimation();
} else if (is_visible_) {
// AppListModel and AppListViewDelegate are owned by AppListView. They
// will be released with AppListView on close.
app_list::AppListView* view = new app_list::AppListView(
Shell::GetInstance()->delegate()->CreateAppListViewDelegate());
aura::Window* container = GetRootWindowController(window->GetRootWindow())->
GetContainer(kShellWindowId_AppListContainer);
if (ash::switches::UseAlternateShelfLayout()) {
gfx::Rect applist_button_bounds = Launcher::ForWindow(container)->
GetAppListButtonView()->GetBoundsInScreen();
view->InitAsBubbleAttachedToAnchor(
container,
pagination_model_.get(),
Launcher::ForWindow(container)->GetAppListButtonView(),
GetAnchorPositionOffsetToShelf(applist_button_bounds,
Launcher::ForWindow(container)->GetAppListButtonView()->
GetWidget()),
GetBubbleArrow(container),
true /* border_accepts_events */);
view->SetArrowPaintType(views::BubbleBorder::PAINT_NONE);
} else {
view->InitAsBubbleAttachedToAnchor(
container,
pagination_model_.get(),
Launcher::ForWindow(container)->GetAppListButtonView(),
gfx::Vector2d(),
GetBubbleArrow(container),
true /* border_accepts_events */);
}
SetView(view);
// By setting us as DnD recipient, the app list knows that we can
// handle items.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kAshDisableDragAndDropAppListToLauncher)) {
SetDragAndDropHostOfCurrentAppList(
Launcher::ForWindow(window)->GetDragAndDropHostForAppList());
}
}
// Update applist button status when app list visibility is changed.
Launcher::ForWindow(window)->GetAppListButtonView()->SchedulePaint();
}
bool AppListController::IsVisible() const {
return view_ && view_->GetWidget()->IsVisible();
}
aura::Window* AppListController::GetWindow() {
return is_visible_ && view_ ? view_->GetWidget()->GetNativeWindow() : NULL;
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, private:
void AppListController::SetDragAndDropHostOfCurrentAppList(
app_list::ApplicationDragAndDropHost* drag_and_drop_host) {
if (view_ && is_visible_)
view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}
void AppListController::SetView(app_list::AppListView* view) {
DCHECK(view_ == NULL);
DCHECK(is_visible_);
view_ = view;
views::Widget* widget = view_->GetWidget();
widget->AddObserver(this);
Shell::GetInstance()->AddPreTargetHandler(this);
Launcher::ForWindow(widget->GetNativeWindow())->AddIconObserver(this);
widget->GetNativeView()->GetRootWindow()->AddObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->AddObserver(this);
view_->ShowWhenReady();
}
void AppListController::ResetView() {
if (!view_)
return;
views::Widget* widget = view_->GetWidget();
widget->RemoveObserver(this);
GetLayer(widget)->GetAnimator()->RemoveObserver(this);
Shell::GetInstance()->RemovePreTargetHandler(this);
Launcher::ForWindow(widget->GetNativeWindow())->RemoveIconObserver(this);
widget->GetNativeView()->GetRootWindow()->RemoveObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->RemoveObserver(this);
view_ = NULL;
}
void AppListController::ScheduleAnimation() {
// Stop observing previous animation.
StopObservingImplicitAnimations();
views::Widget* widget = view_->GetWidget();
ui::Layer* layer = GetLayer(widget);
layer->GetAnimator()->StopAnimating();
gfx::Rect target_bounds;
if (is_visible_) {
target_bounds = widget->GetWindowBoundsInScreen();
widget->SetBounds(OffsetTowardsShelf(target_bounds, widget));
} else {
target_bounds = OffsetTowardsShelf(widget->GetWindowBoundsInScreen(),
widget);
}
ui::ScopedLayerAnimationSettings animation(layer->GetAnimator());
animation.SetTransitionDuration(
base::TimeDelta::FromMilliseconds(
is_visible_ ? 0 : kAnimationDurationMs));
animation.AddObserver(this);
layer->SetOpacity(is_visible_ ? 1.0 : 0.0);
widget->SetBounds(target_bounds);
}
void AppListController::ProcessLocatedEvent(ui::LocatedEvent* event) {
// If the event happened on a menu, then the event should not close the app
// list.
aura::Window* target = static_cast<aura::Window*>(event->target());
if (target) {
RootWindowController* root_controller =
GetRootWindowController(target->GetRootWindow());
if (root_controller) {
aura::Window* menu_container = root_controller->GetContainer(
ash::internal::kShellWindowId_MenuContainer);
if (menu_container->Contains(target))
return;
}
}
if (view_ && is_visible_) {
aura::Window* window = view_->GetWidget()->GetNativeView();
gfx::Point window_local_point(event->root_location());
aura::Window::ConvertPointToTarget(window->GetRootWindow(),
window,
&window_local_point);
// Use HitTest to respect the hit test mask of the bubble.
if (!window->HitTest(window_local_point))
SetVisible(false, window);
}
}
void AppListController::UpdateBounds() {
if (view_ && is_visible_)
view_->UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::EventFilter implementation:
void AppListController::OnMouseEvent(ui::MouseEvent* event) {
if (event->type() == ui::ET_MOUSE_PRESSED)
ProcessLocatedEvent(event);
}
void AppListController::OnGestureEvent(ui::GestureEvent* event) {
if (event->type() == ui::ET_GESTURE_TAP_DOWN)
ProcessLocatedEvent(event);
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::FocusObserver implementation:
void AppListController::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
if (gained_focus && view_ && is_visible_) {
aura::Window* applist_container =
GetRootWindowController(gained_focus->GetRootWindow())->GetContainer(
kShellWindowId_AppListContainer);
if (gained_focus->parent() != applist_container)
SetVisible(false, gained_focus);
}
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, aura::WindowObserver implementation:
void AppListController::OnWindowBoundsChanged(aura::Window* root,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, ui::ImplicitAnimationObserver implementation:
void AppListController::OnImplicitAnimationsCompleted() {
if (is_visible_ )
view_->GetWidget()->Activate();
else
view_->GetWidget()->Close();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, views::WidgetObserver implementation:
void AppListController::OnWidgetDestroying(views::Widget* widget) {
DCHECK(view_->GetWidget() == widget);
if (is_visible_)
SetVisible(false, widget->GetNativeView());
ResetView();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, ShellObserver implementation:
void AppListController::OnShelfAlignmentChanged(aura::RootWindow* root_window) {
if (view_)
view_->SetBubbleArrow(GetBubbleArrow(view_->GetWidget()->GetNativeView()));
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, LauncherIconObserver implementation:
void AppListController::OnLauncherIconPositionsChanged() {
UpdateBounds();
}
////////////////////////////////////////////////////////////////////////////////
// AppListController, PaginationModelObserver implementation:
void AppListController::TotalPagesChanged() {
}
void AppListController::SelectedPageChanged(int old_selected,
int new_selected) {
}
void AppListController::TransitionStarted() {
}
void AppListController::TransitionChanged() {
// |view_| could be NULL when app list is closed with a running transition.
if (!view_)
return;
const app_list::PaginationModel::Transition& transition =
pagination_model_->transition();
if (pagination_model_->is_valid_page(transition.target_page))
return;
views::Widget* widget = view_->GetWidget();
ui::LayerAnimator* widget_animator = GetLayer(widget)->GetAnimator();
if (!pagination_model_->IsRevertingCurrentTransition()) {
// Update cached |view_bounds_| if it is the first over-scroll move and
// widget does not have running animations.
if (!should_snap_back_ && !widget_animator->is_animating())
view_bounds_ = widget->GetWindowBoundsInScreen();
const int current_page = pagination_model_->selected_page();
const int dir = transition.target_page > current_page ? -1 : 1;
const double progress = 1.0 - pow(1.0 - transition.progress, 4);
const int shift = kMaxOverScrollShift * progress * dir;
gfx::Rect shifted(view_bounds_);
shifted.set_x(shifted.x() + shift);
widget->SetBounds(shifted);
should_snap_back_ = true;
} else if (should_snap_back_) {
should_snap_back_ = false;
ui::ScopedLayerAnimationSettings animation(widget_animator);
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
app_list::kOverscrollPageTransitionDurationMs));
widget->SetBounds(view_bounds_);
}
}
} // namespace internal
} // namespace ash
<|endoftext|>
|
<commit_before>#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "formats/osm/BuildingProcessor.hpp"
#include "formats/osm/MultipolygonProcessor.hpp"
#include "formats/osm/RelationProcessor.hpp"
#include "formats/osm/OsmDataVisitor.hpp"
#include "utils/ElementUtils.hpp"
#include "utils/GeometryUtils.hpp"
#include <algorithm>
#include <vector>
using namespace utymap;
using namespace utymap::formats;
using namespace utymap::entities;
using namespace utymap::index;
namespace {
std::unordered_set<std::string> AreaKeys
{
"building",
"building:part",
"landuse",
"amenity",
"harbour",
"historic",
"leisure",
"man_made",
"military",
"natural",
"office",
"place",
"power",
"public_transport",
"shop",
"sport",
"tourism",
"waterway",
"wetland",
"water",
"aeroway",
"addr:housenumber",
"addr:housename"
};
std::unordered_set<std::string> FalseKeys
{
"no", "No", "NO", "false", "False", "FALSE", "0"
};
}
void OsmDataVisitor::visitBounds(BoundingBox bbox)
{
}
void OsmDataVisitor::visitNode(std::uint64_t id, GeoCoordinate& coordinate, utymap::formats::Tags& tags)
{
std::shared_ptr<Node> node(new Node());
node->id = id;
node->coordinate = coordinate;
utymap::utils::setTags(stringTable_, *node, tags);
context_.nodeMap[id] = node;
}
void OsmDataVisitor::visitWay(std::uint64_t id, std::vector<std::uint64_t>& nodeIds, utymap::formats::Tags& tags)
{
std::vector<GeoCoordinate> coordinates;
coordinates.reserve(nodeIds.size());
for (auto nodeId : nodeIds) {
coordinates.push_back(context_.nodeMap[nodeId]->coordinate);
}
if (coordinates.size() > 2 && isArea(tags)) {
coordinates.pop_back();
std::shared_ptr<Area> area(new Area());
area->id = id;
if (!utymap::utils::isClockwise(coordinates)) {
std::reverse(coordinates.begin(), coordinates.end());
}
area->coordinates = std::move(coordinates);
utymap::utils::setTags(stringTable_, *area, tags);
context_.areaMap[id] = area;
} else {
std::shared_ptr<Way> way(new Way());
way->id = id;
way->coordinates = std::move(coordinates);
utymap::utils::setTags(stringTable_, *way, tags);
context_.wayMap[id] = way;
}
}
void OsmDataVisitor::visitRelation(std::uint64_t id, RelationMembers& members, utymap::formats::Tags& tags)
{
std::shared_ptr<utymap::entities::Relation> relation(new utymap::entities::Relation());
relation->id = id;
relation->tags = utymap::utils::convertTags(stringTable_, tags);
// NOTE Assume, relation may refer to another relations which are not yet processed.
// So, store all relation members to resolve them once all relations are visited.
relationMembers_[id] = members;
context_.relationMap[id] = relation;
}
bool OsmDataVisitor::isArea(const utymap::formats::Tags& tags) const
{
for (const auto& tag : tags) {
if (AreaKeys.find(tag.key) != AreaKeys.end() &&
FalseKeys.find(tag.value) == FalseKeys.end())
return true;
}
return false;
}
bool OsmDataVisitor::hasTag(const std::string& key, const std::string& value, const std::vector<utymap::entities::Tag>& tags) const
{
return utymap::utils::hasTag(stringTable_.getId(key), stringTable_.getId(value), tags);
}
void OsmDataVisitor::resolve(Relation& relation)
{
auto membersPair = relationMembers_.find(relation.id);
// already resolved
if (relation.elements.size() == membersPair->second.size())
return;
auto resolveFunc = std::bind(&OsmDataVisitor::resolve, this, std::placeholders::_1);
if (hasTag("type", "multipolygon", relation.tags))
MultipolygonProcessor(relation, membersPair->second, context_, resolveFunc).process();
else if (hasTag("type", "building", relation.tags))
BuildingProcessor(relation, membersPair->second, context_, resolveFunc).process();
else {
RelationProcessor(relation, membersPair->second, context_, resolveFunc).process();
}
}
void OsmDataVisitor::complete()
{
// All relations are visited can start to resolve them
for (auto& membersPair : relationMembers_) {
resolve(*context_.relationMap[membersPair.first]);
}
for (const auto& pair : context_.relationMap) {
add_(*pair.second);
}
for (const auto& pair : context_.nodeMap) {
add_(*pair.second);
}
for (const auto& pair : context_.wayMap) {
add_(*pair.second);
}
for (const auto& pair : context_.areaMap) {
add_(*pair.second);
}
}
OsmDataVisitor::OsmDataVisitor(StringTable& stringTable, std::function<bool(Element&)> add)
: stringTable_(stringTable), add_(add), context_()
{
}
<commit_msg>core: fix relation building processing<commit_after>#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "formats/osm/BuildingProcessor.hpp"
#include "formats/osm/MultipolygonProcessor.hpp"
#include "formats/osm/RelationProcessor.hpp"
#include "formats/osm/OsmDataVisitor.hpp"
#include "utils/ElementUtils.hpp"
#include "utils/GeometryUtils.hpp"
#include <algorithm>
#include <vector>
using namespace utymap;
using namespace utymap::formats;
using namespace utymap::entities;
using namespace utymap::index;
namespace {
std::unordered_set<std::string> AreaKeys
{
"building",
"building:part",
"landuse",
"amenity",
"harbour",
"historic",
"leisure",
"man_made",
"military",
"natural",
"office",
"place",
"power",
"public_transport",
"shop",
"sport",
"tourism",
"waterway",
"wetland",
"water",
"aeroway",
"addr:housenumber",
"addr:housename"
};
std::unordered_set<std::string> FalseKeys
{
"no", "No", "NO", "false", "False", "FALSE", "0"
};
}
void OsmDataVisitor::visitBounds(BoundingBox bbox)
{
}
void OsmDataVisitor::visitNode(std::uint64_t id, GeoCoordinate& coordinate, utymap::formats::Tags& tags)
{
std::shared_ptr<Node> node(new Node());
node->id = id;
node->coordinate = coordinate;
utymap::utils::setTags(stringTable_, *node, tags);
context_.nodeMap[id] = node;
}
void OsmDataVisitor::visitWay(std::uint64_t id, std::vector<std::uint64_t>& nodeIds, utymap::formats::Tags& tags)
{
std::vector<GeoCoordinate> coordinates;
coordinates.reserve(nodeIds.size());
for (auto nodeId : nodeIds) {
coordinates.push_back(context_.nodeMap[nodeId]->coordinate);
}
if (coordinates.size() > 2 && isArea(tags)) {
coordinates.pop_back();
std::shared_ptr<Area> area(new Area());
area->id = id;
if (!utymap::utils::isClockwise(coordinates)) {
std::reverse(coordinates.begin(), coordinates.end());
}
area->coordinates = std::move(coordinates);
utymap::utils::setTags(stringTable_, *area, tags);
context_.areaMap[id] = area;
} else {
std::shared_ptr<Way> way(new Way());
way->id = id;
way->coordinates = std::move(coordinates);
utymap::utils::setTags(stringTable_, *way, tags);
context_.wayMap[id] = way;
}
}
void OsmDataVisitor::visitRelation(std::uint64_t id, RelationMembers& members, utymap::formats::Tags& tags)
{
std::shared_ptr<utymap::entities::Relation> relation(new utymap::entities::Relation());
relation->id = id;
relation->tags = utymap::utils::convertTags(stringTable_, tags);
// NOTE Assume, relation may refer to another relations which are not yet processed.
// So, store all relation members to resolve them once all relations are visited.
relationMembers_[id] = members;
context_.relationMap[id] = relation;
}
bool OsmDataVisitor::isArea(const utymap::formats::Tags& tags) const
{
for (const auto& tag : tags) {
if (AreaKeys.find(tag.key) != AreaKeys.end() &&
FalseKeys.find(tag.value) == FalseKeys.end())
return true;
}
return false;
}
bool OsmDataVisitor::hasTag(const std::string& key, const std::string& value, const std::vector<utymap::entities::Tag>& tags) const
{
return utymap::utils::hasTag(stringTable_.getId(key), stringTable_.getId(value), tags);
}
void OsmDataVisitor::resolve(Relation& relation)
{
auto membersPair = relationMembers_.find(relation.id);
// already resolved
if (relation.elements.size() == membersPair->second.size())
return;
auto resolveFunc = std::bind(&OsmDataVisitor::resolve, this, std::placeholders::_1);
if (hasTag("type", "multipolygon", relation.tags))
MultipolygonProcessor(relation, membersPair->second, context_, resolveFunc).process();
else if (hasTag("type", "building", relation.tags))
BuildingProcessor(relation, membersPair->second, context_, resolveFunc).process();
else {
RelationProcessor(relation, membersPair->second, context_, resolveFunc).process();
}
}
void OsmDataVisitor::complete()
{
// All relations are visited can start to resolve them
for (auto& membersPair : relationMembers_) {
auto relationPair = context_.relationMap.find(membersPair.first);
if (relationPair != context_.relationMap.end())
resolve(*relationPair->second);
}
for (const auto& pair : context_.relationMap) {
add_(*pair.second);
}
for (const auto& pair : context_.nodeMap) {
add_(*pair.second);
}
for (const auto& pair : context_.wayMap) {
add_(*pair.second);
}
for (const auto& pair : context_.areaMap) {
add_(*pair.second);
}
}
OsmDataVisitor::OsmDataVisitor(StringTable& stringTable, std::function<bool(Element&)> add)
: stringTable_(stringTable), add_(add), context_()
{
}
<|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.
*/
#include <thread>
#include <chrono>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <zconf.h>
#include "celix_api.h"
#include <CppUTest/TestHarness.h>
#include <CppUTest/CommandLineTestRunner.h>
TEST_GROUP(CelixBundleContextBundlesTests) {
framework_t* fw = nullptr;
bundle_context_t *ctx = nullptr;
properties_t *properties = nullptr;
const char * const TEST_BND1_LOC = "simple_test_bundle1.zip";
const char * const TEST_BND2_LOC = "simple_test_bundle2.zip";
const char * const TEST_BND3_LOC = "simple_test_bundle3.zip";
const char * const TEST_BND4_LOC = "simple_test_bundle4.zip";
const char * const TEST_BND5_LOC = "simple_test_bundle5.zip";
const char * const TEST_BND_WITH_EXCEPTION_LOC = "bundle_with_exception.zip";
const char * const TEST_BND_UNRESOLVEABLE_LOC = "unresolveable_bundle.zip";
void setup() {
properties = properties_create();
properties_set(properties, "LOGHELPER_ENABLE_STDOUT_FALLBACK", "true");
properties_set(properties, "org.osgi.framework.storage.clean", "onFirstInit");
properties_set(properties, "org.osgi.framework.storage", ".cacheBundleContextTestFramework");
fw = celix_frameworkFactory_createFramework(properties);
ctx = framework_getContext(fw);
}
void teardown() {
celix_frameworkFactory_destroyFramework(fw);
}
};
TEST(CelixBundleContextBundlesTests, installBundlesTest) {
long bndId = celix_bundleContext_installBundle(ctx, "non-existing.zip", true);
CHECK(bndId < 0);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
CHECK(bndId >= 0);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND4_LOC, true); //not loaded in subdir
CHECK(bndId < 0);
setenv(CELIX_BUNDLES_PATH_NAME, "subdir", true);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND4_LOC, true); //subdir now part of CELIX_BUNDLES_PATH
CHECK(bndId >= 0);
}
TEST(CelixBundleContextBundlesTests, useBundlesTest) {
int count = 0;
auto use = [](void *handle, const bundle_t *bnd) {
int *c = (int*)handle;
*c += 1;
long id = celix_bundle_getId(bnd);
CHECK(id >= 0);
};
celix_bundleContext_useBundles(ctx, &count, use);
count = 0;
celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
celix_bundleContext_useBundles(ctx, &count, use);
CHECK_EQUAL(1, count);
};
TEST(CelixBundleContextBundlesTests, startBundleWithException) {
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND_WITH_EXCEPTION_LOC, true);
CHECK(bndId > 0); //bundle is installed, but not started
bool called = celix_framework_useBundle(fw, false, bndId, nullptr, [](void */*handle*/, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_RESOLVED);
});
CHECK_TRUE(called);
}
TEST(CelixBundleContextBundlesTests, startUnresolveableBundle) {
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND_UNRESOLVEABLE_LOC, true);
CHECK(bndId > 0); //bundle is installed, but not resolved
bool called = celix_framework_useBundle(fw, false, bndId, nullptr, [](void */*handle*/, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_INSTALLED);
});
CHECK_TRUE(called);
celix_bundleContext_startBundle(ctx, bndId);
celix_framework_useBundle(fw, false, bndId, nullptr, [](void */*handle*/, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_INSTALLED);
});
CHECK_TRUE(called);
}
TEST(CelixBundleContextBundlesTests, useBundleTest) {
int count = 0;
celix_bundleContext_useBundle(ctx, 0, &count, [](void *handle, const bundle_t *bnd) {
int *c = (int*)handle;
*c += 1;
long id = celix_bundle_getId(bnd);
CHECK_EQUAL(0, id);
});
CHECK_EQUAL(1, count);
};
TEST(CelixBundleContextBundlesTests, StopStartTest) {
celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
celix_bundleContext_installBundle(ctx, TEST_BND3_LOC, true);
celix_array_list_t *ids = celix_bundleContext_listBundles(ctx);
size_t size = arrayList_size(ids);
CHECK_EQUAL(3, size);
int count = 0;
celix_bundleContext_useBundles(ctx, &count, [](void *handle, const celix_bundle_t *bnd) {
auto *c = (int*)handle;
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, celix_bundle_getState(bnd));
*c += 1;
});
CHECK_EQUAL(3, count);
for (size_t i = 0; i < size; ++i) {
bool stopped = celix_bundleContext_stopBundle(ctx, celix_arrayList_getLong(ids, (int)i));
CHECK_TRUE(stopped);
}
bool stopped = celix_bundleContext_stopBundle(ctx, 42 /*non existing*/);
CHECK_FALSE(stopped);
bool started = celix_bundleContext_startBundle(ctx, 42 /*non existing*/);
CHECK_FALSE(started);
for (size_t i = 0; i < size; ++i) {
bool started = celix_bundleContext_startBundle(ctx, celix_arrayList_getLong(ids, (int)i));
CHECK_TRUE(started);
}
count = 0;
celix_bundleContext_useBundles(ctx, &count, [](void *handle, const celix_bundle_t *bnd) {
auto *c = (int*)handle;
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, celix_bundle_getState(bnd));
*c += 1;
});
CHECK_EQUAL(3, count);
celix_arrayList_destroy(ids);
}
TEST(CelixBundleContextBundlesTests, trackBundlesTest) {
struct data {
int count{0};
std::mutex mutex{};
std:: condition_variable cond{};
};
struct data data;
auto started = [](void *handle, const bundle_t *bnd) {
struct data *d = static_cast<struct data*>(handle);
CHECK(bnd != nullptr);
d->mutex.lock();
d->count += 1;
d->cond.notify_all();
d->mutex.unlock();
};
auto stopped = [](void *handle, const bundle_t *bnd) {
struct data *d = static_cast<struct data*>(handle);
CHECK(bnd != nullptr);
d->mutex.lock();
d->count -= 1;
d->cond.notify_all();
d->mutex.unlock();
};
long trackerId = celix_bundleContext_trackBundles(ctx, static_cast<void*>(&data), started, stopped);
CHECK_EQUAL(0, data.count); //note default framework bundle is not tracked
long bundleId1 = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
CHECK(bundleId1 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 2;});
}
CHECK_EQUAL(1, data.count);
long bundleId2 = celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
CHECK(bundleId2 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 3;});
}
CHECK_EQUAL(2, data.count);
/* TODO does not work -> stopping bundle event is never forward to the bundle listener ?? very old bug?
celix_bundleContext_uninstallBundle(ctx, bundleId2);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 2;});
}
CHECK_EQUAL(2, data.count);
long bundleId3 = celix_bundleContext_installBundle(ctx, TEST_BND3_LOC, true);
CHECK(bundleId3 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 3;});
}
CHECK_EQUAL(3, data.count);
bundleId2 = celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
CHECK(bundleId3 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 4;});
}
CHECK_EQUAL(4, data.count);
*/
celix_bundleContext_stopTracker(ctx, trackerId);
};
/* IGNORE TODO need to add locks
TEST(CelixBundleContextBundlesTests, useBundlesConcurrentTest) {
struct data {
std::mutex mutex{};
std::condition_variable cond{};
bool inUse{false};
bool readyToExit{false};
bool called{false};
};
struct data data{};
auto use = [](void *handle, const bundle_t *bnd) {
CHECK(bnd != nullptr);
struct data *d = static_cast<struct data*>(handle);
std::unique_lock<std::mutex> lock(d->mutex);
d->inUse = true;
d->cond.notify_all();
d->cond.wait(lock, [d]{return d->readyToExit;});
lock.unlock();
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, state);
d->called = true;
};
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
auto call = [&] {
celix_bundleContext_useBundle(ctx, bndId, &data, use);
CHECK(data.called);
};
std::thread useThread{call};
std::thread uninstallThread{[&]{
std::unique_lock<std::mutex> lock(data.mutex);
data.cond.wait(lock, [&]{return data.inUse;});
lock.unlock();
std::cout << "trying to uninstall bundle ..." << std::endl;
celix_bundleContext_uninstallBundle(ctx, bndId);
std::cout << "done uninstalling bundle" << std::endl;
}};
//sleep 100 milli to give unregister a change to sink in
std::cout << "before sleep" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "after sleep" << std::endl;
std::cout << "setting readyToExitUseCall and notify" << std::endl;
std::unique_lock<std::mutex> lock(data.mutex);
data.readyToExit = true;
lock.unlock();
data.cond.notify_all();
useThread.join();
std::cout << "use thread joined" << std::endl;
uninstallThread.join();
std::cout << "uninstall thread joined" << std::endl;
};*/<commit_msg>#80: tmp disables a bundle test.<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.
*/
#include <thread>
#include <chrono>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <zconf.h>
#include "celix_api.h"
#include <CppUTest/TestHarness.h>
#include <CppUTest/CommandLineTestRunner.h>
TEST_GROUP(CelixBundleContextBundlesTests) {
framework_t* fw = nullptr;
bundle_context_t *ctx = nullptr;
properties_t *properties = nullptr;
const char * const TEST_BND1_LOC = "simple_test_bundle1.zip";
const char * const TEST_BND2_LOC = "simple_test_bundle2.zip";
const char * const TEST_BND3_LOC = "simple_test_bundle3.zip";
const char * const TEST_BND4_LOC = "simple_test_bundle4.zip";
const char * const TEST_BND5_LOC = "simple_test_bundle5.zip";
const char * const TEST_BND_WITH_EXCEPTION_LOC = "bundle_with_exception.zip";
const char * const TEST_BND_UNRESOLVEABLE_LOC = "unresolveable_bundle.zip";
void setup() {
properties = properties_create();
properties_set(properties, "LOGHELPER_ENABLE_STDOUT_FALLBACK", "true");
properties_set(properties, "org.osgi.framework.storage.clean", "onFirstInit");
properties_set(properties, "org.osgi.framework.storage", ".cacheBundleContextTestFramework");
fw = celix_frameworkFactory_createFramework(properties);
ctx = framework_getContext(fw);
}
void teardown() {
celix_frameworkFactory_destroyFramework(fw);
}
};
TEST(CelixBundleContextBundlesTests, installBundlesTest) {
long bndId = celix_bundleContext_installBundle(ctx, "non-existing.zip", true);
CHECK(bndId < 0);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
CHECK(bndId >= 0);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND4_LOC, true); //not loaded in subdir
CHECK(bndId < 0);
setenv(CELIX_BUNDLES_PATH_NAME, "subdir", true);
bndId = celix_bundleContext_installBundle(ctx, TEST_BND4_LOC, true); //subdir now part of CELIX_BUNDLES_PATH
CHECK(bndId >= 0);
}
TEST(CelixBundleContextBundlesTests, useBundlesTest) {
int count = 0;
auto use = [](void *handle, const bundle_t *bnd) {
int *c = (int*)handle;
*c += 1;
long id = celix_bundle_getId(bnd);
CHECK(id >= 0);
};
celix_bundleContext_useBundles(ctx, &count, use);
count = 0;
celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
celix_bundleContext_useBundles(ctx, &count, use);
CHECK_EQUAL(1, count);
};
TEST(CelixBundleContextBundlesTests, startBundleWithException) {
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND_WITH_EXCEPTION_LOC, true);
CHECK(bndId > 0); //bundle is installed, but not started
bool called = celix_framework_useBundle(fw, false, bndId, nullptr, [](void */*handle*/, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_RESOLVED);
});
CHECK_TRUE(called);
}
/* TODO enable again with newer Ubuntu. For now cannot reproduce this.
* Should be fixed with #121
TEST(CelixBundleContextBundlesTests, startUnresolveableBundle) {
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND_UNRESOLVEABLE_LOC, true);
CHECK(bndId > 0); //bundle is installed, but not resolved
bool called = celix_framework_useBundle(fw, false, bndId, nullptr, [](void *, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_INSTALLED);
});
CHECK_TRUE(called);
celix_bundleContext_startBundle(ctx, bndId);
called = celix_framework_useBundle(fw, false, bndId, nullptr, [](void *, const celix_bundle_t *bnd) {
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(state, OSGI_FRAMEWORK_BUNDLE_INSTALLED);
});
CHECK_TRUE(called);
}
*/
TEST(CelixBundleContextBundlesTests, useBundleTest) {
int count = 0;
celix_bundleContext_useBundle(ctx, 0, &count, [](void *handle, const bundle_t *bnd) {
int *c = (int*)handle;
*c += 1;
long id = celix_bundle_getId(bnd);
CHECK_EQUAL(0, id);
});
CHECK_EQUAL(1, count);
};
TEST(CelixBundleContextBundlesTests, StopStartTest) {
celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
celix_bundleContext_installBundle(ctx, TEST_BND3_LOC, true);
celix_array_list_t *ids = celix_bundleContext_listBundles(ctx);
size_t size = arrayList_size(ids);
CHECK_EQUAL(3, size);
int count = 0;
celix_bundleContext_useBundles(ctx, &count, [](void *handle, const celix_bundle_t *bnd) {
auto *c = (int*)handle;
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, celix_bundle_getState(bnd));
*c += 1;
});
CHECK_EQUAL(3, count);
for (size_t i = 0; i < size; ++i) {
bool stopped = celix_bundleContext_stopBundle(ctx, celix_arrayList_getLong(ids, (int)i));
CHECK_TRUE(stopped);
}
bool stopped = celix_bundleContext_stopBundle(ctx, 42 /*non existing*/);
CHECK_FALSE(stopped);
bool started = celix_bundleContext_startBundle(ctx, 42 /*non existing*/);
CHECK_FALSE(started);
for (size_t i = 0; i < size; ++i) {
bool started = celix_bundleContext_startBundle(ctx, celix_arrayList_getLong(ids, (int)i));
CHECK_TRUE(started);
}
count = 0;
celix_bundleContext_useBundles(ctx, &count, [](void *handle, const celix_bundle_t *bnd) {
auto *c = (int*)handle;
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, celix_bundle_getState(bnd));
*c += 1;
});
CHECK_EQUAL(3, count);
celix_arrayList_destroy(ids);
}
TEST(CelixBundleContextBundlesTests, trackBundlesTest) {
struct data {
int count{0};
std::mutex mutex{};
std:: condition_variable cond{};
};
struct data data;
auto started = [](void *handle, const bundle_t *bnd) {
struct data *d = static_cast<struct data*>(handle);
CHECK(bnd != nullptr);
d->mutex.lock();
d->count += 1;
d->cond.notify_all();
d->mutex.unlock();
};
auto stopped = [](void *handle, const bundle_t *bnd) {
struct data *d = static_cast<struct data*>(handle);
CHECK(bnd != nullptr);
d->mutex.lock();
d->count -= 1;
d->cond.notify_all();
d->mutex.unlock();
};
long trackerId = celix_bundleContext_trackBundles(ctx, static_cast<void*>(&data), started, stopped);
CHECK_EQUAL(0, data.count); //note default framework bundle is not tracked
long bundleId1 = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
CHECK(bundleId1 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 2;});
}
CHECK_EQUAL(1, data.count);
long bundleId2 = celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
CHECK(bundleId2 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 3;});
}
CHECK_EQUAL(2, data.count);
/* TODO does not work -> stopping bundle event is never forward to the bundle listener ?? very old bug?
celix_bundleContext_uninstallBundle(ctx, bundleId2);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 2;});
}
CHECK_EQUAL(2, data.count);
long bundleId3 = celix_bundleContext_installBundle(ctx, TEST_BND3_LOC, true);
CHECK(bundleId3 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 3;});
}
CHECK_EQUAL(3, data.count);
bundleId2 = celix_bundleContext_installBundle(ctx, TEST_BND2_LOC, true);
CHECK(bundleId3 >= 0);
{
std::unique_lock<std::mutex> lock{data.mutex};
data.cond.wait_for(lock, std::chrono::milliseconds(100), [&]{return data.count == 4;});
}
CHECK_EQUAL(4, data.count);
*/
celix_bundleContext_stopTracker(ctx, trackerId);
};
/* IGNORE TODO need to add locks
TEST(CelixBundleContextBundlesTests, useBundlesConcurrentTest) {
struct data {
std::mutex mutex{};
std::condition_variable cond{};
bool inUse{false};
bool readyToExit{false};
bool called{false};
};
struct data data{};
auto use = [](void *handle, const bundle_t *bnd) {
CHECK(bnd != nullptr);
struct data *d = static_cast<struct data*>(handle);
std::unique_lock<std::mutex> lock(d->mutex);
d->inUse = true;
d->cond.notify_all();
d->cond.wait(lock, [d]{return d->readyToExit;});
lock.unlock();
auto state = celix_bundle_getState(bnd);
CHECK_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, state);
d->called = true;
};
long bndId = celix_bundleContext_installBundle(ctx, TEST_BND1_LOC, true);
auto call = [&] {
celix_bundleContext_useBundle(ctx, bndId, &data, use);
CHECK(data.called);
};
std::thread useThread{call};
std::thread uninstallThread{[&]{
std::unique_lock<std::mutex> lock(data.mutex);
data.cond.wait(lock, [&]{return data.inUse;});
lock.unlock();
std::cout << "trying to uninstall bundle ..." << std::endl;
celix_bundleContext_uninstallBundle(ctx, bndId);
std::cout << "done uninstalling bundle" << std::endl;
}};
//sleep 100 milli to give unregister a change to sink in
std::cout << "before sleep" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "after sleep" << std::endl;
std::cout << "setting readyToExitUseCall and notify" << std::endl;
std::unique_lock<std::mutex> lock(data.mutex);
data.readyToExit = true;
lock.unlock();
data.cond.notify_all();
useThread.join();
std::cout << "use thread joined" << std::endl;
uninstallThread.join();
std::cout << "uninstall thread joined" << std::endl;
};*/<|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/common/extensions/manifest_url_handler.h"
#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/api_permission_set.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(USE_AURA)
#include "ui/keyboard/keyboard_constants.h"
#endif
namespace extensions {
namespace keys = manifest_keys;
namespace errors = manifest_errors;
namespace {
const char kOverrideExtentUrlPatternFormat[] = "chrome://%s/*";
const GURL& GetManifestURL(const Extension* extension,
const std::string& key) {
ManifestURL* manifest_url =
static_cast<ManifestURL*>(extension->GetManifestData(key));
return manifest_url ? manifest_url->url_ : GURL::EmptyGURL();
}
} // namespace
// static
const GURL& ManifestURL::GetDevToolsPage(const Extension* extension) {
return GetManifestURL(extension, keys::kDevToolsPage);
}
// static
const GURL ManifestURL::GetHomepageURL(const Extension* extension) {
const GURL& homepage_url = GetManifestURL(extension, keys::kHomepageURL);
if (homepage_url.is_valid())
return homepage_url;
return UpdatesFromGallery(extension) ?
GURL(extension_urls::GetWebstoreItemDetailURLPrefix() + extension->id()) :
GURL::EmptyGURL();
}
// static
const GURL& ManifestURL::GetUpdateURL(const Extension* extension) {
return GetManifestURL(extension, keys::kUpdateURL);
}
// static
bool ManifestURL::UpdatesFromGallery(const Extension* extension) {
return extension_urls::IsWebstoreUpdateUrl(GetUpdateURL(extension));
}
// static
bool ManifestURL::UpdatesFromGallery(const base::DictionaryValue* manifest) {
std::string url;
if (!manifest->GetString(keys::kUpdateURL, &url))
return false;
return extension_urls::IsWebstoreUpdateUrl(GURL(url));
}
// static
const GURL& ManifestURL::GetOptionsPage(const Extension* extension) {
return GetManifestURL(extension, keys::kOptionsPage);
}
// static
const GURL& ManifestURL::GetAboutPage(const Extension* extension) {
return GetManifestURL(extension, keys::kAboutPage);
}
// static
const GURL ManifestURL::GetDetailsURL(const Extension* extension) {
return extension->from_webstore() ?
GURL(extension_urls::GetWebstoreItemDetailURLPrefix() + extension->id()) :
GURL::EmptyGURL();
}
URLOverrides::URLOverrides() {
}
URLOverrides::~URLOverrides() {
}
static base::LazyInstance<URLOverrides::URLOverrideMap> g_empty_url_overrides =
LAZY_INSTANCE_INITIALIZER;
// static
const URLOverrides::URLOverrideMap&
URLOverrides::GetChromeURLOverrides(const Extension* extension) {
URLOverrides* url_overrides = static_cast<URLOverrides*>(
extension->GetManifestData(keys::kChromeURLOverrides));
return url_overrides ?
url_overrides->chrome_url_overrides_ :
g_empty_url_overrides.Get();
}
DevToolsPageHandler::DevToolsPageHandler() {
}
DevToolsPageHandler::~DevToolsPageHandler() {
}
bool DevToolsPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string devtools_str;
if (!extension->manifest()->GetString(keys::kDevToolsPage, &devtools_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidDevToolsPage);
return false;
}
manifest_url->url_ = extension->GetResourceURL(devtools_str);
extension->SetManifestData(keys::kDevToolsPage, manifest_url.release());
PermissionsParser::AddAPIPermission(extension, APIPermission::kDevtools);
return true;
}
const std::vector<std::string> DevToolsPageHandler::Keys() const {
return SingleKey(keys::kDevToolsPage);
}
HomepageURLHandler::HomepageURLHandler() {
}
HomepageURLHandler::~HomepageURLHandler() {
}
bool HomepageURLHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string homepage_url_str;
if (!extension->manifest()->GetString(keys::kHomepageURL,
&homepage_url_str)) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidHomepageURL,
std::string());
return false;
}
manifest_url->url_ = GURL(homepage_url_str);
if (!manifest_url->url_.is_valid() ||
!manifest_url->url_.SchemeIsHTTPOrHTTPS()) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidHomepageURL, homepage_url_str);
return false;
}
extension->SetManifestData(keys::kHomepageURL, manifest_url.release());
return true;
}
const std::vector<std::string> HomepageURLHandler::Keys() const {
return SingleKey(keys::kHomepageURL);
}
UpdateURLHandler::UpdateURLHandler() {
}
UpdateURLHandler::~UpdateURLHandler() {
}
bool UpdateURLHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string tmp_update_url;
if (!extension->manifest()->GetString(keys::kUpdateURL, &tmp_update_url)) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidUpdateURL,
std::string());
return false;
}
manifest_url->url_ = GURL(tmp_update_url);
if (!manifest_url->url_.is_valid() ||
manifest_url->url_.has_ref()) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidUpdateURL, tmp_update_url);
return false;
}
extension->SetManifestData(keys::kUpdateURL, manifest_url.release());
return true;
}
const std::vector<std::string> UpdateURLHandler::Keys() const {
return SingleKey(keys::kUpdateURL);
}
OptionsPageHandler::OptionsPageHandler() {
}
OptionsPageHandler::~OptionsPageHandler() {
}
bool OptionsPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string options_str;
if (!extension->manifest()->GetString(keys::kOptionsPage, &options_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPage);
return false;
}
if (extension->is_hosted_app()) {
// hosted apps require an absolute URL.
GURL options_url(options_str);
if (!options_url.is_valid() ||
!options_url.SchemeIsHTTPOrHTTPS()) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPageInHostedApp);
return false;
}
manifest_url->url_ = options_url;
} else {
GURL absolute(options_str);
if (absolute.is_valid()) {
*error =
base::ASCIIToUTF16(errors::kInvalidOptionsPageExpectUrlInPackage);
return false;
}
manifest_url->url_ = extension->GetResourceURL(options_str);
if (!manifest_url->url_.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPage);
return false;
}
}
extension->SetManifestData(keys::kOptionsPage, manifest_url.release());
return true;
}
bool OptionsPageHandler::Validate(const Extension* extension,
std::string* error,
std::vector<InstallWarning>* warnings) const {
// Validate path to the options page. Don't check the URL for hosted apps,
// because they are expected to refer to an external URL.
if (!extensions::ManifestURL::GetOptionsPage(extension).is_empty() &&
!extension->is_hosted_app()) {
const base::FilePath options_path =
extensions::file_util::ExtensionURLToRelativeFilePath(
extensions::ManifestURL::GetOptionsPage(extension));
const base::FilePath path =
extension->GetResource(options_path).GetFilePath();
if (path.empty() || !base::PathExists(path)) {
*error =
l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_OPTIONS_PAGE_FAILED,
options_path.LossyDisplayName());
return false;
}
}
return true;
}
const std::vector<std::string> OptionsPageHandler::Keys() const {
return SingleKey(keys::kOptionsPage);
}
AboutPageHandler::AboutPageHandler() {
}
AboutPageHandler::~AboutPageHandler() {
}
bool AboutPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string about_str;
if (!extension->manifest()->GetString(keys::kAboutPage, &about_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPage);
return false;
}
GURL absolute(about_str);
if (absolute.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPageExpectRelativePath);
return false;
}
manifest_url->url_ = extension->GetResourceURL(about_str);
if (!manifest_url->url_.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPage);
return false;
}
extension->SetManifestData(keys::kAboutPage, manifest_url.release());
return true;
}
bool AboutPageHandler::Validate(const Extension* extension,
std::string* error,
std::vector<InstallWarning>* warnings) const {
// Validate path to the options page.
if (!extensions::ManifestURL::GetAboutPage(extension).is_empty()) {
const base::FilePath about_path =
extensions::file_util::ExtensionURLToRelativeFilePath(
extensions::ManifestURL::GetAboutPage(extension));
const base::FilePath path =
extension->GetResource(about_path).GetFilePath();
if (path.empty() || !base::PathExists(path)) {
*error = l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_ABOUT_PAGE_FAILED,
about_path.LossyDisplayName());
return false;
}
}
return true;
}
const std::vector<std::string> AboutPageHandler::Keys() const {
return SingleKey(keys::kAboutPage);
}
URLOverridesHandler::URLOverridesHandler() {
}
URLOverridesHandler::~URLOverridesHandler() {
}
bool URLOverridesHandler::Parse(Extension* extension, base::string16* error) {
const base::DictionaryValue* overrides = NULL;
if (!extension->manifest()->GetDictionary(keys::kChromeURLOverrides,
&overrides)) {
*error = base::ASCIIToUTF16(errors::kInvalidChromeURLOverrides);
return false;
}
scoped_ptr<URLOverrides> url_overrides(new URLOverrides);
// Validate that the overrides are all strings
for (base::DictionaryValue::Iterator iter(*overrides); !iter.IsAtEnd();
iter.Advance()) {
std::string page = iter.key();
std::string val;
// Restrict override pages to a list of supported URLs.
bool is_override = (page != chrome::kChromeUINewTabHost &&
page != chrome::kChromeUIBookmarksHost &&
page != chrome::kChromeUIHistoryHost);
#if defined(OS_CHROMEOS)
is_override = (is_override &&
page != chrome::kChromeUIActivationMessageHost);
#endif
#if defined(OS_CHROMEOS)
is_override = (is_override && page != keyboard::kKeyboardHost);
#endif
if (is_override || !iter.value().GetAsString(&val)) {
*error = base::ASCIIToUTF16(errors::kInvalidChromeURLOverrides);
return false;
}
// Replace the entry with a fully qualified chrome-extension:// URL.
url_overrides->chrome_url_overrides_[page] = extension->GetResourceURL(val);
// For component extensions, add override URL to extent patterns.
if (extension->is_legacy_packaged_app() &&
extension->location() == Manifest::COMPONENT) {
URLPattern pattern(URLPattern::SCHEME_CHROMEUI);
std::string url = base::StringPrintf(kOverrideExtentUrlPatternFormat,
page.c_str());
if (pattern.Parse(url) != URLPattern::PARSE_SUCCESS) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, url);
return false;
}
extension->AddWebExtentPattern(pattern);
}
}
// An extension may override at most one page.
if (overrides->size() > 1) {
*error = base::ASCIIToUTF16(errors::kMultipleOverrides);
return false;
}
extension->SetManifestData(keys::kChromeURLOverrides,
url_overrides.release());
return true;
}
const std::vector<std::string> URLOverridesHandler::Keys() const {
return SingleKey(keys::kChromeURLOverrides);
}
} // namespace extensions
<commit_msg>Do not return a homepage URL for shared modules<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/common/extensions/manifest_url_handler.h"
#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/manifest_handlers/shared_module_info.h"
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/api_permission_set.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(USE_AURA)
#include "ui/keyboard/keyboard_constants.h"
#endif
namespace extensions {
namespace keys = manifest_keys;
namespace errors = manifest_errors;
namespace {
const char kOverrideExtentUrlPatternFormat[] = "chrome://%s/*";
const GURL& GetManifestURL(const Extension* extension,
const std::string& key) {
ManifestURL* manifest_url =
static_cast<ManifestURL*>(extension->GetManifestData(key));
return manifest_url ? manifest_url->url_ : GURL::EmptyGURL();
}
} // namespace
// static
const GURL& ManifestURL::GetDevToolsPage(const Extension* extension) {
return GetManifestURL(extension, keys::kDevToolsPage);
}
// static
const GURL ManifestURL::GetHomepageURL(const Extension* extension) {
const GURL& homepage_url = GetManifestURL(extension, keys::kHomepageURL);
if (homepage_url.is_valid())
return homepage_url;
bool use_webstore_url = UpdatesFromGallery(extension) &&
!SharedModuleInfo::IsSharedModule(extension);
return use_webstore_url
? GURL(extension_urls::GetWebstoreItemDetailURLPrefix() +
extension->id())
: GURL::EmptyGURL();
}
// static
const GURL& ManifestURL::GetUpdateURL(const Extension* extension) {
return GetManifestURL(extension, keys::kUpdateURL);
}
// static
bool ManifestURL::UpdatesFromGallery(const Extension* extension) {
return extension_urls::IsWebstoreUpdateUrl(GetUpdateURL(extension));
}
// static
bool ManifestURL::UpdatesFromGallery(const base::DictionaryValue* manifest) {
std::string url;
if (!manifest->GetString(keys::kUpdateURL, &url))
return false;
return extension_urls::IsWebstoreUpdateUrl(GURL(url));
}
// static
const GURL& ManifestURL::GetOptionsPage(const Extension* extension) {
return GetManifestURL(extension, keys::kOptionsPage);
}
// static
const GURL& ManifestURL::GetAboutPage(const Extension* extension) {
return GetManifestURL(extension, keys::kAboutPage);
}
// static
const GURL ManifestURL::GetDetailsURL(const Extension* extension) {
return extension->from_webstore() ?
GURL(extension_urls::GetWebstoreItemDetailURLPrefix() + extension->id()) :
GURL::EmptyGURL();
}
URLOverrides::URLOverrides() {
}
URLOverrides::~URLOverrides() {
}
static base::LazyInstance<URLOverrides::URLOverrideMap> g_empty_url_overrides =
LAZY_INSTANCE_INITIALIZER;
// static
const URLOverrides::URLOverrideMap&
URLOverrides::GetChromeURLOverrides(const Extension* extension) {
URLOverrides* url_overrides = static_cast<URLOverrides*>(
extension->GetManifestData(keys::kChromeURLOverrides));
return url_overrides ?
url_overrides->chrome_url_overrides_ :
g_empty_url_overrides.Get();
}
DevToolsPageHandler::DevToolsPageHandler() {
}
DevToolsPageHandler::~DevToolsPageHandler() {
}
bool DevToolsPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string devtools_str;
if (!extension->manifest()->GetString(keys::kDevToolsPage, &devtools_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidDevToolsPage);
return false;
}
manifest_url->url_ = extension->GetResourceURL(devtools_str);
extension->SetManifestData(keys::kDevToolsPage, manifest_url.release());
PermissionsParser::AddAPIPermission(extension, APIPermission::kDevtools);
return true;
}
const std::vector<std::string> DevToolsPageHandler::Keys() const {
return SingleKey(keys::kDevToolsPage);
}
HomepageURLHandler::HomepageURLHandler() {
}
HomepageURLHandler::~HomepageURLHandler() {
}
bool HomepageURLHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string homepage_url_str;
if (!extension->manifest()->GetString(keys::kHomepageURL,
&homepage_url_str)) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidHomepageURL,
std::string());
return false;
}
manifest_url->url_ = GURL(homepage_url_str);
if (!manifest_url->url_.is_valid() ||
!manifest_url->url_.SchemeIsHTTPOrHTTPS()) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidHomepageURL, homepage_url_str);
return false;
}
extension->SetManifestData(keys::kHomepageURL, manifest_url.release());
return true;
}
const std::vector<std::string> HomepageURLHandler::Keys() const {
return SingleKey(keys::kHomepageURL);
}
UpdateURLHandler::UpdateURLHandler() {
}
UpdateURLHandler::~UpdateURLHandler() {
}
bool UpdateURLHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string tmp_update_url;
if (!extension->manifest()->GetString(keys::kUpdateURL, &tmp_update_url)) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidUpdateURL,
std::string());
return false;
}
manifest_url->url_ = GURL(tmp_update_url);
if (!manifest_url->url_.is_valid() ||
manifest_url->url_.has_ref()) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidUpdateURL, tmp_update_url);
return false;
}
extension->SetManifestData(keys::kUpdateURL, manifest_url.release());
return true;
}
const std::vector<std::string> UpdateURLHandler::Keys() const {
return SingleKey(keys::kUpdateURL);
}
OptionsPageHandler::OptionsPageHandler() {
}
OptionsPageHandler::~OptionsPageHandler() {
}
bool OptionsPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string options_str;
if (!extension->manifest()->GetString(keys::kOptionsPage, &options_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPage);
return false;
}
if (extension->is_hosted_app()) {
// hosted apps require an absolute URL.
GURL options_url(options_str);
if (!options_url.is_valid() ||
!options_url.SchemeIsHTTPOrHTTPS()) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPageInHostedApp);
return false;
}
manifest_url->url_ = options_url;
} else {
GURL absolute(options_str);
if (absolute.is_valid()) {
*error =
base::ASCIIToUTF16(errors::kInvalidOptionsPageExpectUrlInPackage);
return false;
}
manifest_url->url_ = extension->GetResourceURL(options_str);
if (!manifest_url->url_.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidOptionsPage);
return false;
}
}
extension->SetManifestData(keys::kOptionsPage, manifest_url.release());
return true;
}
bool OptionsPageHandler::Validate(const Extension* extension,
std::string* error,
std::vector<InstallWarning>* warnings) const {
// Validate path to the options page. Don't check the URL for hosted apps,
// because they are expected to refer to an external URL.
if (!extensions::ManifestURL::GetOptionsPage(extension).is_empty() &&
!extension->is_hosted_app()) {
const base::FilePath options_path =
extensions::file_util::ExtensionURLToRelativeFilePath(
extensions::ManifestURL::GetOptionsPage(extension));
const base::FilePath path =
extension->GetResource(options_path).GetFilePath();
if (path.empty() || !base::PathExists(path)) {
*error =
l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_OPTIONS_PAGE_FAILED,
options_path.LossyDisplayName());
return false;
}
}
return true;
}
const std::vector<std::string> OptionsPageHandler::Keys() const {
return SingleKey(keys::kOptionsPage);
}
AboutPageHandler::AboutPageHandler() {
}
AboutPageHandler::~AboutPageHandler() {
}
bool AboutPageHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<ManifestURL> manifest_url(new ManifestURL);
std::string about_str;
if (!extension->manifest()->GetString(keys::kAboutPage, &about_str)) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPage);
return false;
}
GURL absolute(about_str);
if (absolute.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPageExpectRelativePath);
return false;
}
manifest_url->url_ = extension->GetResourceURL(about_str);
if (!manifest_url->url_.is_valid()) {
*error = base::ASCIIToUTF16(errors::kInvalidAboutPage);
return false;
}
extension->SetManifestData(keys::kAboutPage, manifest_url.release());
return true;
}
bool AboutPageHandler::Validate(const Extension* extension,
std::string* error,
std::vector<InstallWarning>* warnings) const {
// Validate path to the options page.
if (!extensions::ManifestURL::GetAboutPage(extension).is_empty()) {
const base::FilePath about_path =
extensions::file_util::ExtensionURLToRelativeFilePath(
extensions::ManifestURL::GetAboutPage(extension));
const base::FilePath path =
extension->GetResource(about_path).GetFilePath();
if (path.empty() || !base::PathExists(path)) {
*error = l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_ABOUT_PAGE_FAILED,
about_path.LossyDisplayName());
return false;
}
}
return true;
}
const std::vector<std::string> AboutPageHandler::Keys() const {
return SingleKey(keys::kAboutPage);
}
URLOverridesHandler::URLOverridesHandler() {
}
URLOverridesHandler::~URLOverridesHandler() {
}
bool URLOverridesHandler::Parse(Extension* extension, base::string16* error) {
const base::DictionaryValue* overrides = NULL;
if (!extension->manifest()->GetDictionary(keys::kChromeURLOverrides,
&overrides)) {
*error = base::ASCIIToUTF16(errors::kInvalidChromeURLOverrides);
return false;
}
scoped_ptr<URLOverrides> url_overrides(new URLOverrides);
// Validate that the overrides are all strings
for (base::DictionaryValue::Iterator iter(*overrides); !iter.IsAtEnd();
iter.Advance()) {
std::string page = iter.key();
std::string val;
// Restrict override pages to a list of supported URLs.
bool is_override = (page != chrome::kChromeUINewTabHost &&
page != chrome::kChromeUIBookmarksHost &&
page != chrome::kChromeUIHistoryHost);
#if defined(OS_CHROMEOS)
is_override = (is_override &&
page != chrome::kChromeUIActivationMessageHost);
#endif
#if defined(OS_CHROMEOS)
is_override = (is_override && page != keyboard::kKeyboardHost);
#endif
if (is_override || !iter.value().GetAsString(&val)) {
*error = base::ASCIIToUTF16(errors::kInvalidChromeURLOverrides);
return false;
}
// Replace the entry with a fully qualified chrome-extension:// URL.
url_overrides->chrome_url_overrides_[page] = extension->GetResourceURL(val);
// For component extensions, add override URL to extent patterns.
if (extension->is_legacy_packaged_app() &&
extension->location() == Manifest::COMPONENT) {
URLPattern pattern(URLPattern::SCHEME_CHROMEUI);
std::string url = base::StringPrintf(kOverrideExtentUrlPatternFormat,
page.c_str());
if (pattern.Parse(url) != URLPattern::PARSE_SUCCESS) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, url);
return false;
}
extension->AddWebExtentPattern(pattern);
}
}
// An extension may override at most one page.
if (overrides->size() > 1) {
*error = base::ASCIIToUTF16(errors::kMultipleOverrides);
return false;
}
extension->SetManifestData(keys::kChromeURLOverrides,
url_overrides.release());
return true;
}
const std::vector<std::string> URLOverridesHandler::Keys() const {
return SingleKey(keys::kChromeURLOverrides);
}
} // namespace extensions
<|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/installer/util/duplicate_tree_detector.h"
#include "base/file_util.h"
#include "base/logging.h"
namespace installer {
bool IsIdenticalFileHierarchy(const FilePath& src_path,
const FilePath& dest_path) {
using file_util::FileEnumerator;
base::PlatformFileInfo src_info;
base::PlatformFileInfo dest_info;
bool is_identical = false;
if (file_util::GetFileInfo(src_path, &src_info) &&
file_util::GetFileInfo(dest_path, &dest_info)) {
// Both paths exist, check the types:
if (!src_info.is_directory && !dest_info.is_directory) {
// Two files are "identical" if the file sizes are equivalent.
is_identical = src_info.size == dest_info.size;
#ifndef NDEBUG
// For Debug builds, also check creation time (to make sure version dir
// DLLs are replaced on over-install even if the tested change doesn't
// happen to change a given DLL's size).
if (is_identical)
is_identical = (src_info.creation_time == dest_info.creation_time);
#endif
} else if (src_info.is_directory && dest_info.is_directory) {
// Two directories are "identical" if dest_path contains entries that are
// "identical" to all the entries in src_path.
is_identical = true;
FileEnumerator path_enum(src_path, false /* not recursive */,
FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
for (FilePath path = path_enum.Next(); is_identical && !path.empty();
path = path_enum.Next()) {
is_identical =
IsIdenticalFileHierarchy(path, dest_path.Append(path.BaseName()));
}
} else {
// The two paths are of different types, so they cannot be identical.
DCHECK(!is_identical);
}
}
return is_identical;
}
} // namespace installer
<commit_msg>Revert 161641 - Also check file creation time when deciding whether replacing files is necessary in Debug build installs.<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/installer/util/duplicate_tree_detector.h"
#include "base/file_util.h"
#include "base/logging.h"
namespace installer {
bool IsIdenticalFileHierarchy(const FilePath& src_path,
const FilePath& dest_path) {
using file_util::FileEnumerator;
base::PlatformFileInfo src_info;
base::PlatformFileInfo dest_info;
bool is_identical = false;
if (file_util::GetFileInfo(src_path, &src_info) &&
file_util::GetFileInfo(dest_path, &dest_info)) {
// Both paths exist, check the types:
if (!src_info.is_directory && !dest_info.is_directory) {
// Two files are "identical" if the file sizes are equivalent.
is_identical = src_info.size == dest_info.size;
} else if (src_info.is_directory && dest_info.is_directory) {
// Two directories are "identical" if dest_path contains entries that are
// "identical" to all the entries in src_path.
is_identical = true;
FileEnumerator path_enum(src_path, false /* not recursive */,
FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
for (FilePath path = path_enum.Next(); is_identical && !path.empty();
path = path_enum.Next()) {
is_identical =
IsIdenticalFileHierarchy(path, dest_path.Append(path.BaseName()));
}
} else {
// The two paths are of different types, so they cannot be identical.
DCHECK(!is_identical);
}
}
return is_identical;
}
} // namespace installer
<|endoftext|>
|
<commit_before>#include <franka_hw/service_server.h>
#include <franka/robot.h>
#include <ros/ros.h>
#include <array>
#include <functional>
namespace {
template <typename T1, typename T2>
const boost::function<bool(T1&, T2&)> createErrorFunction(
std::function<void(T1&, T2&)> handler) {
return [handler](T1& request, T2& response) -> bool {
try {
handler(request, response);
response.success = true;
} catch (const franka::Exception& ex) {
ROS_ERROR_STREAM("" << ex.what());
response.success = false;
response.error = ex.what();
}
return true;
};
}
} // anonymous namespace
namespace franka_hw {
ServiceServer::ServiceServer(franka::Robot* robot, ros::NodeHandle& node_handle)
: robot_(robot),
joint_impedance_server_(node_handle.advertiseService(
"set_joint_impedance",
createErrorFunction<SetJointImpedance::Request,
SetJointImpedance::Response>(
std::bind(&ServiceServer::setJointImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
cartesian_impedance_server_(node_handle.advertiseService(
"set_cartesian_impedance",
createErrorFunction<SetCartesianImpedance::Request,
SetCartesianImpedance::Response>(
std::bind(&ServiceServer::setCartesianImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
EE_frame_server_(node_handle.advertiseService(
"set_EE_frame",
createErrorFunction<SetEEFrame::Request, SetEEFrame::Response>(
std::bind(&ServiceServer::setEEFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
K_frame_server_(node_handle.advertiseService(
"set_K_frame",
createErrorFunction<SetKFrame::Request, SetKFrame::Response>(
std::bind(&ServiceServer::setKFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
force_torque_collision_server_(node_handle.advertiseService(
"set_force_torque_collision_behavior",
createErrorFunction<SetForceTorqueCollisionBehavior::Request,
SetForceTorqueCollisionBehavior::Response>(
std::bind(&ServiceServer::setForceTorqueCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
full_collision_server_(node_handle.advertiseService(
"set_full_collision_behavior",
createErrorFunction<SetFullCollisionBehavior::Request,
SetFullCollisionBehavior::Response>(
std::bind(&ServiceServer::setFullCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
load_server_(node_handle.advertiseService(
"set_load",
createErrorFunction<SetLoad::Request, SetLoad::Response>(
std::bind(&ServiceServer::setLoad,
this,
std::placeholders::_1,
std::placeholders::_2)))),
time_scaling_server_(node_handle.advertiseService(
"set_time_scaling_factor",
createErrorFunction<SetTimeScalingFactor::Request,
SetTimeScalingFactor::Response>(
std::bind(&ServiceServer::setTimeScalingFactor,
this,
std::placeholders::_1,
std::placeholders::_2)))),
error_recovery_server_(node_handle.advertiseService(
"error_recovery",
createErrorFunction<ErrorRecovery::Request, ErrorRecovery::Response>(
std::bind(&ServiceServer::errorRecovery,
this,
std::placeholders::_1,
std::placeholders::_2)))) {}
bool ServiceServer::setCartesianImpedance(
SetCartesianImpedance::Request& req,
SetCartesianImpedance::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 6> cartesian_stiffness;
std::copy(req.cartesian_stiffness.cbegin(), req.cartesian_stiffness.cend(),
cartesian_stiffness.begin());
robot_->setCartesianImpedance(cartesian_stiffness);
return true;
}
bool ServiceServer::setJointImpedance(
SetJointImpedance::Request& req,
SetJointImpedance::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> joint_stiffness;
std::copy(req.joint_stiffness.cbegin(), req.joint_stiffness.cend(),
joint_stiffness.begin());
robot_->setJointImpedance(joint_stiffness);
return true;
}
bool ServiceServer::setEEFrame(
SetEEFrame::Request& req,
SetEEFrame::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 16> F_T_EE; // NOLINT [readability-identifier-naming]
std::copy(req.F_T_EE.cbegin(), req.F_T_EE.cend(), F_T_EE.begin());
robot_->setEE(F_T_EE);
return true;
}
bool ServiceServer::setKFrame(
SetKFrame::Request& req,
SetKFrame::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 16> EE_T_K; // NOLINT [readability-identifier-naming]
std::copy(req.EE_T_K.cbegin(), req.EE_T_K.cend(), EE_T_K.begin());
robot_->setK(EE_T_K);
return true;
}
bool ServiceServer::setForceTorqueCollisionBehavior(
SetForceTorqueCollisionBehavior::Request& req,
SetForceTorqueCollisionBehavior::Response&
res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_nominal, upper_torque_thresholds_nominal,
lower_force_thresholds_nominal, upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setFullCollisionBehavior(
SetFullCollisionBehavior::Request& req,
SetFullCollisionBehavior::Response&
res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> lower_torque_thresholds_acceleration;
std::copy(req.lower_torque_thresholds_acceleration.cbegin(),
req.lower_torque_thresholds_acceleration.cend(),
lower_torque_thresholds_acceleration.begin());
std::array<double, 7> upper_torque_thresholds_acceleration;
std::copy(req.upper_torque_thresholds_acceleration.cbegin(),
req.upper_torque_thresholds_acceleration.cend(),
upper_torque_thresholds_acceleration.begin());
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_acceleration;
std::copy(req.lower_force_thresholds_acceleration.cbegin(),
req.lower_force_thresholds_acceleration.cend(),
lower_force_thresholds_acceleration.begin());
std::array<double, 6> upper_force_thresholds_acceleration;
std::copy(req.upper_force_thresholds_acceleration.cbegin(),
req.upper_force_thresholds_acceleration.cend(),
upper_force_thresholds_acceleration.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_acceleration,
upper_torque_thresholds_acceleration, lower_torque_thresholds_nominal,
upper_torque_thresholds_nominal, lower_force_thresholds_acceleration,
upper_force_thresholds_acceleration, lower_force_thresholds_nominal,
upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setLoad(
SetLoad::Request& req,
SetLoad::Response& res) { // NOLINT [misc-unused-parameters]
double mass(req.mass);
std::array<double, 3>
F_x_center_load; // NOLINT [readability-identifier-naming]
std::copy(req.F_x_center_load.cbegin(), req.F_x_center_load.cend(),
F_x_center_load.begin());
std::array<double, 9> load_inertia;
std::copy(req.load_inertia.cbegin(), req.load_inertia.cend(),
load_inertia.begin());
robot_->setLoad(mass, F_x_center_load, load_inertia);
return true;
}
bool ServiceServer::setTimeScalingFactor(
SetTimeScalingFactor::Request& req,
SetTimeScalingFactor::Response& res) { // NOLINT [misc-unused-parameters]
robot_->setTimeScalingFactor(req.time_scaling_factor);
return true;
}
bool ServiceServer::errorRecovery(
ErrorRecovery::Request& req,
ErrorRecovery::Response& res) { // NOLINT [misc-unused-parameters]
robot_->automaticErrorRecovery();
return true;
}
} // namespace franka_hw
<commit_msg>linter fix<commit_after>#include <franka_hw/service_server.h>
#include <franka/robot.h>
#include <ros/ros.h>
#include <array>
#include <functional>
namespace {
template <typename T1, typename T2>
const boost::function<bool(T1&, T2&)> createErrorFunction(
std::function<void(T1&, T2&)> handler) {
return [handler](T1& request, T2& response) -> bool {
try {
handler(request, response);
response.success = true;
} catch (const franka::Exception& ex) {
ROS_ERROR_STREAM("" << ex.what());
response.success = false;
response.error = ex.what();
}
return true;
};
}
} // anonymous namespace
namespace franka_hw {
ServiceServer::ServiceServer(franka::Robot* robot, ros::NodeHandle& node_handle)
: robot_(robot),
joint_impedance_server_(node_handle.advertiseService(
"set_joint_impedance",
createErrorFunction<SetJointImpedance::Request,
SetJointImpedance::Response>(
std::bind(&ServiceServer::setJointImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
cartesian_impedance_server_(node_handle.advertiseService(
"set_cartesian_impedance",
createErrorFunction<SetCartesianImpedance::Request,
SetCartesianImpedance::Response>(
std::bind(&ServiceServer::setCartesianImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
EE_frame_server_(node_handle.advertiseService(
"set_EE_frame",
createErrorFunction<SetEEFrame::Request, SetEEFrame::Response>(
std::bind(&ServiceServer::setEEFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
K_frame_server_(node_handle.advertiseService(
"set_K_frame",
createErrorFunction<SetKFrame::Request, SetKFrame::Response>(
std::bind(&ServiceServer::setKFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
force_torque_collision_server_(node_handle.advertiseService(
"set_force_torque_collision_behavior",
createErrorFunction<SetForceTorqueCollisionBehavior::Request,
SetForceTorqueCollisionBehavior::Response>(
std::bind(&ServiceServer::setForceTorqueCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
full_collision_server_(node_handle.advertiseService(
"set_full_collision_behavior",
createErrorFunction<SetFullCollisionBehavior::Request,
SetFullCollisionBehavior::Response>(
std::bind(&ServiceServer::setFullCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
load_server_(node_handle.advertiseService(
"set_load",
createErrorFunction<SetLoad::Request, SetLoad::Response>(
std::bind(&ServiceServer::setLoad,
this,
std::placeholders::_1,
std::placeholders::_2)))),
time_scaling_server_(node_handle.advertiseService(
"set_time_scaling_factor",
createErrorFunction<SetTimeScalingFactor::Request,
SetTimeScalingFactor::Response>(
std::bind(&ServiceServer::setTimeScalingFactor,
this,
std::placeholders::_1,
std::placeholders::_2)))),
error_recovery_server_(node_handle.advertiseService(
"error_recovery",
createErrorFunction<ErrorRecovery::Request, ErrorRecovery::Response>(
std::bind(&ServiceServer::errorRecovery,
this,
std::placeholders::_1,
std::placeholders::_2)))) {}
bool ServiceServer::setCartesianImpedance(
SetCartesianImpedance::Request& req,
SetCartesianImpedance::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 6> cartesian_stiffness;
std::copy(req.cartesian_stiffness.cbegin(), req.cartesian_stiffness.cend(),
cartesian_stiffness.begin());
robot_->setCartesianImpedance(cartesian_stiffness);
return true;
}
bool ServiceServer::setJointImpedance(
SetJointImpedance::Request& req,
SetJointImpedance::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> joint_stiffness;
std::copy(req.joint_stiffness.cbegin(), req.joint_stiffness.cend(),
joint_stiffness.begin());
robot_->setJointImpedance(joint_stiffness);
return true;
}
bool ServiceServer::setEEFrame(
SetEEFrame::Request& req,
SetEEFrame::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 16> F_T_EE; // NOLINT [readability-identifier-naming]
std::copy(req.F_T_EE.cbegin(), req.F_T_EE.cend(), F_T_EE.begin());
robot_->setEE(F_T_EE);
return true;
}
bool ServiceServer::setKFrame(
SetKFrame::Request& req,
SetKFrame::Response& res) { // NOLINT [misc-unused-parameters]
std::array<double, 16> EE_T_K; // NOLINT [readability-identifier-naming]
std::copy(req.EE_T_K.cbegin(), req.EE_T_K.cend(), EE_T_K.begin());
robot_->setK(EE_T_K);
return true;
}
bool ServiceServer::setForceTorqueCollisionBehavior(
SetForceTorqueCollisionBehavior::Request& req,
SetForceTorqueCollisionBehavior::Response&
res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_nominal, upper_torque_thresholds_nominal,
lower_force_thresholds_nominal, upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setFullCollisionBehavior(
SetFullCollisionBehavior::Request& req,
SetFullCollisionBehavior::Response&
res) { // NOLINT [misc-unused-parameters]
std::array<double, 7> lower_torque_thresholds_acceleration;
std::copy(req.lower_torque_thresholds_acceleration.cbegin(),
req.lower_torque_thresholds_acceleration.cend(),
lower_torque_thresholds_acceleration.begin());
std::array<double, 7> upper_torque_thresholds_acceleration;
std::copy(req.upper_torque_thresholds_acceleration.cbegin(),
req.upper_torque_thresholds_acceleration.cend(),
upper_torque_thresholds_acceleration.begin());
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_acceleration;
std::copy(req.lower_force_thresholds_acceleration.cbegin(),
req.lower_force_thresholds_acceleration.cend(),
lower_force_thresholds_acceleration.begin());
std::array<double, 6> upper_force_thresholds_acceleration;
std::copy(req.upper_force_thresholds_acceleration.cbegin(),
req.upper_force_thresholds_acceleration.cend(),
upper_force_thresholds_acceleration.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_acceleration,
upper_torque_thresholds_acceleration, lower_torque_thresholds_nominal,
upper_torque_thresholds_nominal, lower_force_thresholds_acceleration,
upper_force_thresholds_acceleration, lower_force_thresholds_nominal,
upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setLoad(
SetLoad::Request& req,
SetLoad::Response& res) { // NOLINT [misc-unused-parameters]
double mass(req.mass);
std::array<double, 3>
F_x_center_load; // NOLINT [readability-identifier-naming]
std::copy(req.F_x_center_load.cbegin(), req.F_x_center_load.cend(),
F_x_center_load.begin());
std::array<double, 9> load_inertia;
std::copy(req.load_inertia.cbegin(), req.load_inertia.cend(),
load_inertia.begin());
robot_->setLoad(mass, F_x_center_load, load_inertia);
return true;
}
bool ServiceServer::setTimeScalingFactor(
SetTimeScalingFactor::Request& req,
SetTimeScalingFactor::Response& res) { // NOLINT [misc-unused-parameters]
robot_->setTimeScalingFactor(req.time_scaling_factor);
return true;
}
bool ServiceServer::errorRecovery(
ErrorRecovery::Request& req, // NOLINT [misc-unused-parameters]
ErrorRecovery::Response& res) { // NOLINT [misc-unused-parameters]
robot_->automaticErrorRecovery();
return true;
}
} // namespace franka_hw
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.