text stringlengths 54 60.6k |
|---|
<commit_before>
void AddTaskPIDconfig(Int_t CentralityTriggerSelection = AliVEvent::kMB, Double_t centralityMin=0, Double_t centralityMax=5 ,Double_t FilterBit=1, Bool_t PIDcuts=kFALSE,TString useroutputfile="output"){
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPID", "No analysis manager to connect to.");
return 0x0;
}
// standard with task
printf("========================================================================================\n");
printf("PID: Initialising AliAnalysisTaskPIDconfig\n");
printf("========================================================================================\n");
Double_t centrMin[9] = {0,5,10,20,30,40,50,60,70};
Double_t centrMax[9] = {5,10,20,30,40,50,60,70,80};
Bool_t Pass_Min = kFALSE;
Bool_t Pass_Max = kFALSE;
for(int i=0;i<9;i++)
{
if(centralityMin == centrMin[i]){
const int iMin = i;
Pass_Min = kTRUE;
}
if(centralityMax == centrMax[i]){
const int iMax = i;
Pass_Max = kTRUE;
}
}
if(!Pass_Min || !Pass_Max){
::Error("centrality Min and Max don't match the defined ranges");
return 0x0;
}
const int ncentr = iMax - iMin +1;
TString outputfile[ncentr];
AliAnalysisDataContainer *coutput1[ncentr];
AliAnalysisTaskPIDconfig *pidTask[ncentr];
int icentr = 0;
for(int i=0;i<iMax-iMin+1;i++){
icentr = i + iMin;
outputfile[i] = useroutputfile;
outputfile[i].Append(".root");
pidTask[i] = new AliAnalysisTaskPIDconfig(Form("pidTask_%.f-%.f",centrMin[icentr],centrMax[icentr]));
pidTask[i]->SelectCollisionCandidates(CentralityTriggerSelection);
pidTask[i]->SetCutTPCmultiplicityOutliersAOD(kTRUE);
pidTask[i]->SetData2011(kFALSE);
pidTask[i]->SetFilterBit(FilterBit);
pidTask[i]->SetUseCentrality(kTRUE);
pidTask[i]->SetCentralityPercentileMin(centrMin[icentr]);
pidTask[i]->SetCentralityPercentileMax(centrMax[icentr]);
pidTask[i]->SetCentralityEstimator("V0M");
pidTask[i]->SetDCAxyCut(10);
pidTask[i]->SetDCAzCut(10);
pidTask[i]->SetCuts(PIDcuts);
mgr->AddTask(pidTask[i]);
coutput1[i] = mgr->CreateContainer(Form("PID_%.f-%.f",centrMin[icentr],centrMax[icentr]), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile[i]);
//connect containers
mgr->ConnectInput (pidTask[i], 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (pidTask[i], 1, coutput1[i]);
//return pidTask[icentr];
}
}<commit_msg>NaghmehMohammadi patches<commit_after>
void AddTaskPIDconfig(Int_t CentralityTriggerSelection = AliVEvent::kMB, Double_t centralityMinlimit=0, Double_t centralityMaxlimit=5 ,Double_t FilterBit=1, Bool_t PIDcuts=kFALSE,Bool_t isLHC11h=kFALSE, TString useroutputfile="output"){
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPID", "No analysis manager to connect to.");
return 0x0;
}
// standard with task
printf("========================================================================================\n");
printf("PID: Initialising AliAnalysisTaskPIDconfig\n");
printf("========================================================================================\n");
Double_t centrMin[8] = {0,0,10,20,30,40,60,60};
Double_t centrMax[8] = {1,2,20,30,40,50,70,80};
const int ncentr = centralityMaxlimit - centralityMinlimit ;
TString outputfile[ncentr];
AliAnalysisDataContainer *coutput1[ncentr];
AliAnalysisTaskPIDconfig *pidTask[ncentr];
int icentr = 0;
for(int i=0;i<ncentr;i++){
icentr = i + centralityMinlimit;
outputfile[i] = useroutputfile;
outputfile[i].Append(".root");
pidTask[i] = new AliAnalysisTaskPIDconfig(Form("pidTask_%.f-%.f",centrMin[icentr],centrMax[icentr]));
pidTask[i]->SelectCollisionCandidates(CentralityTriggerSelection);
pidTask[i]->SetCutTPCmultiplicityOutliersAOD(kTRUE);
pidTask[i]->SetData2011(isLHC11h);
pidTask[i]->SetFilterBit(FilterBit);
pidTask[i]->SetUseCentrality(kTRUE);
pidTask[i]->SetCentralityPercentileMin(centrMin[icentr]);
pidTask[i]->SetCentralityPercentileMax(centrMax[icentr]);
pidTask[i]->SetCentralityEstimator("V0M");
pidTask[i]->SetDCAxyCut(10);
pidTask[i]->SetDCAzCut(10);
pidTask[i]->SetCuts(PIDcuts);
mgr->AddTask(pidTask[i]);
coutput1[i] = mgr->CreateContainer(Form("PID_%.f-%.f",centrMin[icentr],centrMax[icentr]), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile[i]);
//connect containers
mgr->ConnectInput (pidTask[i], 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (pidTask[i], 1, coutput1[i]);
//return pidTask[icentr];
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////////
//
// This class contains all code which is used to compute any of the values
// which can be of interest within a resonance analysis. Besides the obvious
// invariant mass, it allows to compute other utility values on all possible
// targets, in order to allow a wide spectrum of binning and checks.
// When needed, this object can also define a binning in the variable which
// it is required to compute, which is used for initializing axes of output
// histograms (see AliRsnFunction).
// The value computation requires this object to be passed the object whose
// informations will be used. This object can be of any allowed input type
// (track, pair, event), then this class must inherit from AliRsnTarget.
// Then, when value computation is attempted, a check on target type is done
// and computation is successful only if expected target matches that of the
// passed object.
// In some cases, the value computation can require a support external object,
// which must then be passed to this class. It can be of any type inheriting
// from TObject.
//
// authors: A. Pulvirenti (alberto.pulvirenti@ct.infn.it)
// M. Vala (martin.vala@cern.ch)
// developers: F. Bellini (fbellini@cern.ch)
//
////////////////////////////////////////////////////////////////////////////////
#include "Riostream.h"
#include "AliLog.h"
#include "AliRsnMiniPair.h"
#include "AliRsnMiniEvent.h"
#include "AliRsnMiniParticle.h"
#include "AliRsnMiniValue.h"
ClassImp(AliRsnMiniValue)
//_____________________________________________________________________________
AliRsnMiniValue::AliRsnMiniValue(EType type, Bool_t useMC) :
TNamed(ValueName(type, useMC), ""),
fType(type),
fUseMCInfo(useMC)
{
//
// Constructor
//
}
//_____________________________________________________________________________
AliRsnMiniValue::AliRsnMiniValue(const AliRsnMiniValue ©) :
TNamed(copy),
fType(copy.fType),
fUseMCInfo(copy.fUseMCInfo)
{
//
// Copy constructor
//
}
//_____________________________________________________________________________
AliRsnMiniValue &AliRsnMiniValue::operator=(const AliRsnMiniValue ©)
{
//
// Assignment operator.
// Works like copy constructor.
//
TNamed::operator=(copy);
if (this == ©)
return *this;
fType = copy.fType;
fUseMCInfo = copy.fUseMCInfo;
return (*this);
}
//_____________________________________________________________________________
const char *AliRsnMiniValue::TypeName(EType type)
{
//
// This method returns a string to give a name to each possible
// computation value.
//
switch (type) {
case kVz: return "EventVz";
case kSpherocity: return "EventSpherocity";
case kMult: return "EventMult";
case kRefMult: return "EventReferenceMult";
case kTracklets: return "EventTracklets";
case kPlaneAngle: return "EventPlane";
case kLeadingPt: return "EventLeadingPt";
case kPt: return "Pt";
case kPz: return "Pz";
case kInvMass: return "InvMass";
case kInvMassMother: return "InvMassMother";
case kInvMassRes: return "InvMassResolution";
case kInvMassDiff: return "InvMassDifference";
case kEta: return "Eta";
case kMt: return "Mt";
case kY: return "Y";
case kPtRatio: return "PtRatio";
case kDipAngle: return "DipAngle";
case kCosThetaStar: return "CosThetaStar";
case kCosThetaJackson: return "CosThetaJackson";
case kCosThetaTransversity: return "CosThetaTransversity";
case kCosThetaToEventPlane: return "CosThetaToEventPlane";
case kAngleLeading: return "AngleToLeading";
case kFirstDaughterPt: return "FirstDaughterPt";
case kSecondDaughterPt: return "SecondDaughterPt";
case kFirstDaughterP: return "FirstDaughterP";
case kSecondDaughterP: return "SecondDaughterP";
case kDCAproduct: return "DaughterDCAproduct";
case kFirstDaughterDCA: return "FirstDaughterDCA";
case kSecondDaughterDCA: return "SecondDaughterDCA";
case kNSisters: return "NumberOfSisters";
case kPairPtRes: return "PairPtResolution";
case kPairYRes: return "PairYResolution";
case kPhiV: return "PhiV";
default: return "Undefined";
}
}
//_____________________________________________________________________________
Float_t AliRsnMiniValue::Eval(AliRsnMiniPair *pair, AliRsnMiniEvent *event)
{
//
// Evaluation of the required value.
// In this implementation, fills the member 4-vectors with data
// coming from the object passed as argument, and then returns the value
//
if (!pair && fType > kEventCuts) {
AliError("Null pair passed!");
return 1E20;
}
// compute value depending on types in the enumeration
// if the type does not match any available choice, or if
// the computation is not doable due to any problem
// (not initialized support object, wrong values, risk of floating point errors)
// the method returng kFALSE and sets the computed value to a meaningless number
Double_t p3[3]= {0.,0.,0.};
AliRsnMiniParticle *l;
TLorentzVector v;
switch (fType) {
// ---- event values -------------------------------------------------------------------------
case kVz:
return event->Vz();
case kSpherocity:
return event->Spherocity();
case kMult:
return event->Mult();
case kRefMult:
return event->RefMult();
case kTracklets:
return event->Tracklets();
case kPlaneAngle:
return event->Angle();
case kLeadingPt:
l = event->LeadingParticle(fUseMCInfo);
if (l) {
l->Set4Vector(v,-1.0,fUseMCInfo);
return v.Pt();
}
return 0.0;
case kPt:
return pair->Pt(fUseMCInfo);
case kInvMass:
return pair->InvMass(fUseMCInfo);
case kInvMassMother:
return pair->InvMass(kTRUE);
case kEta:
return pair->Eta(fUseMCInfo);
case kInvMassRes:
return pair->InvMassRes();
case kInvMassDiff:
return pair->InvMassDiff();
case kMt:
return pair->Mt(fUseMCInfo);
case kY:
return pair->Y(fUseMCInfo);
case kPtRatio:
return pair->PtRatio(fUseMCInfo);
case kDipAngle:
return pair->DipAngle(fUseMCInfo);
case kCosThetaStar:
return pair->CosThetaStar(fUseMCInfo);
case kCosThetaJackson:
return pair->CosThetaJackson(fUseMCInfo);
case kCosThetaTransversity:
return pair->CosThetaTransversity(fUseMCInfo);
case kCosThetaToEventPlane:
return pair->CosThetaToEventPlane(event, fUseMCInfo);
case kAngleLeading:
l = event->LeadingParticle(fUseMCInfo);
if (l) {
l->Set4Vector(v,-1.0,fUseMCInfo);
Double_t angle = v.Phi() - pair->Sum(fUseMCInfo).Phi();
//return angle w.r.t. leading particle in the range -pi/2, 3/2pi
while (angle >= 1.5 * TMath::Pi()) angle -= 2 * TMath::Pi();
while (angle < -0.5 * TMath::Pi()) angle += 2 * TMath::Pi();
return angle;
}
// AliWarning("This method is not yet implemented");
return 1E20;
case kFirstDaughterPt:
return pair->DaughterPt(0,fUseMCInfo);
case kSecondDaughterPt:
return pair->DaughterPt(1,fUseMCInfo);
case kFirstDaughterP:
pair->DaughterPxPyPz(0,fUseMCInfo, p3);
return TMath::Sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
case kSecondDaughterP:
pair->DaughterPxPyPz(1,fUseMCInfo, p3);
return TMath::Sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
case kDCAproduct:
return pair->DCAProduct();
case kFirstDaughterDCA:
return pair->DaughterDCA(0);
case kSecondDaughterDCA:
return pair->DaughterDCA(1);
case kNSisters:
return pair->NSisters();
case kPairPtRes:
return pair->PairPtRes();
case kPairYRes:
return pair->PairYRes();
case kPhiV:
return pair->PhiV(fUseMCInfo);
default:
AliError("Invalid value type");
return 1E20;
}
}
<commit_msg>add pair asymmetry variable<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////////
//
// This class contains all code which is used to compute any of the values
// which can be of interest within a resonance analysis. Besides the obvious
// invariant mass, it allows to compute other utility values on all possible
// targets, in order to allow a wide spectrum of binning and checks.
// When needed, this object can also define a binning in the variable which
// it is required to compute, which is used for initializing axes of output
// histograms (see AliRsnFunction).
// The value computation requires this object to be passed the object whose
// informations will be used. This object can be of any allowed input type
// (track, pair, event), then this class must inherit from AliRsnTarget.
// Then, when value computation is attempted, a check on target type is done
// and computation is successful only if expected target matches that of the
// passed object.
// In some cases, the value computation can require a support external object,
// which must then be passed to this class. It can be of any type inheriting
// from TObject.
//
// authors: A. Pulvirenti (alberto.pulvirenti@ct.infn.it)
// M. Vala (martin.vala@cern.ch)
// developers: F. Bellini (fbellini@cern.ch)
//
////////////////////////////////////////////////////////////////////////////////
#include "Riostream.h"
#include "AliLog.h"
#include "AliRsnMiniPair.h"
#include "AliRsnMiniEvent.h"
#include "AliRsnMiniParticle.h"
#include "AliRsnMiniValue.h"
ClassImp(AliRsnMiniValue)
//_____________________________________________________________________________
AliRsnMiniValue::AliRsnMiniValue(EType type, Bool_t useMC) :
TNamed(ValueName(type, useMC), ""),
fType(type),
fUseMCInfo(useMC)
{
//
// Constructor
//
}
//_____________________________________________________________________________
AliRsnMiniValue::AliRsnMiniValue(const AliRsnMiniValue ©) :
TNamed(copy),
fType(copy.fType),
fUseMCInfo(copy.fUseMCInfo)
{
//
// Copy constructor
//
}
//_____________________________________________________________________________
AliRsnMiniValue &AliRsnMiniValue::operator=(const AliRsnMiniValue ©)
{
//
// Assignment operator.
// Works like copy constructor.
//
TNamed::operator=(copy);
if (this == ©)
return *this;
fType = copy.fType;
fUseMCInfo = copy.fUseMCInfo;
return (*this);
}
//_____________________________________________________________________________
const char *AliRsnMiniValue::TypeName(EType type)
{
//
// This method returns a string to give a name to each possible
// computation value.
//
switch (type) {
case kVz: return "EventVz";
case kSpherocity: return "EventSpherocity";
case kMult: return "EventMult";
case kRefMult: return "EventReferenceMult";
case kTracklets: return "EventTracklets";
case kPlaneAngle: return "EventPlane";
case kLeadingPt: return "EventLeadingPt";
case kPt: return "Pt";
case kPz: return "Pz";
case kInvMass: return "InvMass";
case kInvMassMother: return "InvMassMother";
case kInvMassRes: return "InvMassResolution";
case kInvMassDiff: return "InvMassDifference";
case kEta: return "Eta";
case kMt: return "Mt";
case kY: return "Y";
case kPtRatio: return "PtRatio";
case kDipAngle: return "DipAngle";
case kCosThetaStar: return "CosThetaStar";
case kCosThetaJackson: return "CosThetaJackson";
case kCosThetaTransversity: return "CosThetaTransversity";
case kCosThetaToEventPlane: return "CosThetaToEventPlane";
case kAngleLeading: return "AngleToLeading";
case kFirstDaughterPt: return "FirstDaughterPt";
case kSecondDaughterPt: return "SecondDaughterPt";
case kFirstDaughterP: return "FirstDaughterP";
case kSecondDaughterP: return "SecondDaughterP";
case kDCAproduct: return "DaughterDCAproduct";
case kFirstDaughterDCA: return "FirstDaughterDCA";
case kSecondDaughterDCA: return "SecondDaughterDCA";
case kNSisters: return "NumberOfSisters";
case kPairPtRes: return "PairPtResolution";
case kPairYRes: return "PairYResolution";
case kPhiV: return "PhiV";
case kAsym: return "PairAsymmetry";
default: return "Undefined";
}
}
//_____________________________________________________________________________
Float_t AliRsnMiniValue::Eval(AliRsnMiniPair *pair, AliRsnMiniEvent *event)
{
//
// Evaluation of the required value.
// In this implementation, fills the member 4-vectors with data
// coming from the object passed as argument, and then returns the value
//
if (!pair && fType > kEventCuts) {
AliError("Null pair passed!");
return 1E20;
}
// compute value depending on types in the enumeration
// if the type does not match any available choice, or if
// the computation is not doable due to any problem
// (not initialized support object, wrong values, risk of floating point errors)
// the method returng kFALSE and sets the computed value to a meaningless number
Double_t p3[3]= {0.,0.,0.};
AliRsnMiniParticle *l;
TLorentzVector v;
switch (fType) {
// ---- event values -------------------------------------------------------------------------
case kVz:
return event->Vz();
case kSpherocity:
return event->Spherocity();
case kMult:
return event->Mult();
case kRefMult:
return event->RefMult();
case kTracklets:
return event->Tracklets();
case kPlaneAngle:
return event->Angle();
case kLeadingPt:
l = event->LeadingParticle(fUseMCInfo);
if (l) {
l->Set4Vector(v,-1.0,fUseMCInfo);
return v.Pt();
}
return 0.0;
case kPt:
return pair->Pt(fUseMCInfo);
case kInvMass:
return pair->InvMass(fUseMCInfo);
case kInvMassMother:
return pair->InvMass(kTRUE);
case kEta:
return pair->Eta(fUseMCInfo);
case kInvMassRes:
return pair->InvMassRes();
case kInvMassDiff:
return pair->InvMassDiff();
case kMt:
return pair->Mt(fUseMCInfo);
case kY:
return pair->Y(fUseMCInfo);
case kPtRatio:
return pair->PtRatio(fUseMCInfo);
case kDipAngle:
return pair->DipAngle(fUseMCInfo);
case kCosThetaStar:
return pair->CosThetaStar(fUseMCInfo);
case kCosThetaJackson:
return pair->CosThetaJackson(fUseMCInfo);
case kCosThetaTransversity:
return pair->CosThetaTransversity(fUseMCInfo);
case kCosThetaToEventPlane:
return pair->CosThetaToEventPlane(event, fUseMCInfo);
case kAngleLeading:
l = event->LeadingParticle(fUseMCInfo);
if (l) {
l->Set4Vector(v,-1.0,fUseMCInfo);
Double_t angle = v.Phi() - pair->Sum(fUseMCInfo).Phi();
//return angle w.r.t. leading particle in the range -pi/2, 3/2pi
while (angle >= 1.5 * TMath::Pi()) angle -= 2 * TMath::Pi();
while (angle < -0.5 * TMath::Pi()) angle += 2 * TMath::Pi();
return angle;
}
// AliWarning("This method is not yet implemented");
return 1E20;
case kFirstDaughterPt:
return pair->DaughterPt(0,fUseMCInfo);
case kSecondDaughterPt:
return pair->DaughterPt(1,fUseMCInfo);
case kFirstDaughterP:
pair->DaughterPxPyPz(0,fUseMCInfo, p3);
return TMath::Sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
case kSecondDaughterP:
pair->DaughterPxPyPz(1,fUseMCInfo, p3);
return TMath::Sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
case kDCAproduct:
return pair->DCAProduct();
case kFirstDaughterDCA:
return pair->DaughterDCA(0);
case kSecondDaughterDCA:
return pair->DaughterDCA(1);
case kNSisters:
return pair->NSisters();
case kPairPtRes:
return pair->PairPtRes();
case kPairYRes:
return pair->PairYRes();
case kPhiV:
return pair->PhiV(fUseMCInfo);
case kAsym:
return pair->PairAsymmetry(fUseMCInfo);
default:
AliError("Invalid value type");
return 1E20;
}
}
<|endoftext|> |
<commit_before>/*** Copyright (c) 2010 Data Intensive Cyberinfrastructure Foundation. All rights reserved. ***
*** For full copyright notice please refer to files in the COPYRIGHT directory ***/
/* Written by Jean-Yves Nief of CCIN2P3 and copyright assigned to Data Intensive Cyberinfrastructure Foundation */
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "scanUtil.hpp"
void usage();
int
main( int argc, char **argv ) {
signal( SIGPIPE, SIG_IGN );
rodsArguments_t myRodsArgs;
int status = parseCmdLineOpt( argc, argv, "dhr", 0, &myRodsArgs );
if ( status < 0 ) {
printf( "Use -h for help\n" );
return 1;
}
if ( myRodsArgs.help == True ) {
usage();
return 0;
}
rodsEnv myEnv;
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
return 1;
}
objType_t srcType;
if ( myRodsArgs.dataObjects ) {
srcType = UNKNOWN_OBJ_T;
}
else {
srcType = UNKNOWN_FILE_T;
}
rodsPathInp_t rodsPathInp;
status = parseCmdLinePath( argc, argv, optind, &myEnv,
srcType, NO_INPUT_T, 0, &rodsPathInp );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
usage();
return 1;
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
irods::api_entry_table& api_tbl = irods::get_client_api_table();
init_api_table( api_tbl, pk_tbl );
rErrMsg_t errMsg;
rcComm_t *conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 0, &errMsg );
if ( conn == NULL ) {
return 2;
}
if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
status = clientLogin( conn );
if ( status != 0 ) {
rcDisconnect( conn );
return 7;
}
}
char hostname[LONG_NAME_LEN];
status = gethostname( hostname, LONG_NAME_LEN );
if ( status < 0 ) {
printf( "cannot resolve server name, aborting!\n" );
return 4;
}
status = scanObj( conn, &myRodsArgs, &rodsPathInp, hostname );
printErrorStack( conn->rError );
rcDisconnect( conn );
return status;
}
void
usage() {
char *msgs[] = {
"Usage: iscan [-drh] srcPhysicalFile|srcPhysicalDirectory|srcDataObj|srcCollection",
"If the input is a local data file or a local directory, it checks if the content is registered in iRODS.",
"Full path must be used for local files and directories.",
"If the input is an iRODS file or an iRODS collection, it checks if the physical files corresponding ",
"to the iRODS object does exist on the data servers. Scanning data objects and collections may only be ",
"performed by a rodsadmin."
"If the operation is successful, nothing will be output and 0 will be returned.",
"Options are:",
" -r recursive - scan local subdirectories or subcollections",
" -h this help",
" -d scan data objects in iRODS (default is scan local objects)",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "iscan" );
}
<commit_msg>[#2212] CID26065:<commit_after>/*** Copyright (c) 2010 Data Intensive Cyberinfrastructure Foundation. All rights reserved. ***
*** For full copyright notice please refer to files in the COPYRIGHT directory ***/
/* Written by Jean-Yves Nief of CCIN2P3 and copyright assigned to Data Intensive Cyberinfrastructure Foundation */
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "scanUtil.hpp"
void usage();
int
main( int argc, char **argv ) {
signal( SIGPIPE, SIG_IGN );
rodsArguments_t myRodsArgs;
int status = parseCmdLineOpt( argc, argv, "dhr", 0, &myRodsArgs );
if ( status < 0 ) {
printf( "Use -h for help\n" );
return 1;
}
if ( myRodsArgs.help == True ) {
usage();
return 0;
}
rodsEnv myEnv;
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
return 1;
}
objType_t srcType;
if ( myRodsArgs.dataObjects ) {
srcType = UNKNOWN_OBJ_T;
}
else {
srcType = UNKNOWN_FILE_T;
}
rodsPathInp_t rodsPathInp;
status = parseCmdLinePath( argc, argv, optind, &myEnv,
srcType, NO_INPUT_T, 0, &rodsPathInp );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
usage();
return 1;
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
irods::api_entry_table& api_tbl = irods::get_client_api_table();
init_api_table( api_tbl, pk_tbl );
rErrMsg_t errMsg;
rcComm_t *conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 0, &errMsg );
if ( conn == NULL ) {
return 2;
}
if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
status = clientLogin( conn );
if ( status != 0 ) {
rcDisconnect( conn );
return 7;
}
}
char hostname[LONG_NAME_LEN];
status = gethostname( hostname, LONG_NAME_LEN );
if ( status < 0 ) {
printf( "cannot resolve server name, aborting!\n" );
return 4;
}
status = scanObj( conn, &myRodsArgs, &rodsPathInp, hostname );
printErrorStack( conn->rError );
rcDisconnect( conn );
return status;
}
void
usage() {
char *msgs[] = {
"Usage: iscan [-drh] srcPhysicalFile|srcPhysicalDirectory|srcDataObj|srcCollection",
"If the input is a local data file or a local directory, it checks if the content is registered in iRODS.",
"Full path must be used for local files and directories.",
"If the input is an iRODS file or an iRODS collection, it checks if the physical files corresponding ",
"to the iRODS object does exist on the data servers. Scanning data objects and collections may only be ",
"performed by a rodsadmin.",
"If the operation is successful, nothing will be output and 0 will be returned.",
"Options are:",
" -r recursive - scan local subdirectories or subcollections",
" -h this help",
" -d scan data objects in iRODS (default is scan local objects)",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "iscan" );
}
<|endoftext|> |
<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/testcases.h"
#include <limits>
using namespace cpputil;
using namespace std;
namespace stoke {
namespace {
set<size_t> create_default_testcase_set() {
vector<size_t> n(10000);
iota(n.begin(), n.end(), 0);
return set<size_t>(n.begin(), n.end());
}
}
Heading& testcases_heading =
Heading::create("Testcase Options:");
FileArg<CpuStates, CpuStatesReader, CpuStatesWriter>& testcases_arg =
FileArg<CpuStates, CpuStatesReader, CpuStatesWriter>::create("testcases")
.usage("<path/to/file>")
.description("Testcases")
.default_val({});
FlagArg& shuffle_tc_arg =
FlagArg::create("shuffle_testcases")
.description("Shuffle testcase ordering");
const set<size_t> default_set = create_default_testcase_set();
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>& training_set_arg =
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>::create("training_set")
.usage("{ 0 1 ... 9 }")
.description("Subset of testcase indices to use for training sets")
.default_val(default_set);
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>& test_set_arg =
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>::create("test_set")
.usage("{ 0 1 ... 9 }")
.description("Subset of testcase indices to use for test sets")
.default_val(default_set);
ValueArg<size_t>& testcase_idx_arg =
ValueArg<size_t>::create("index")
.usage("<int>")
.description("Testcase index")
.default_val(numeric_limits<size_t>::max());
} // namespace stoke
<commit_msg>whitespace<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/testcases.h"
#include <limits>
using namespace cpputil;
using namespace std;
namespace stoke {
namespace {
set<size_t> create_default_testcase_set() {
vector<size_t> n(10000);
iota(n.begin(), n.end(), 0);
return set<size_t>(n.begin(), n.end());
}
}
Heading& testcases_heading =
Heading::create("Testcase Options:");
FileArg<CpuStates, CpuStatesReader, CpuStatesWriter>& testcases_arg =
FileArg<CpuStates, CpuStatesReader, CpuStatesWriter>::create("testcases")
.usage("<path/to/file>")
.description("Testcases")
.default_val({});
FlagArg& shuffle_tc_arg =
FlagArg::create("shuffle_testcases")
.description("Shuffle testcase ordering");
const set<size_t> default_set = create_default_testcase_set();
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>& training_set_arg =
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>::create("training_set")
.usage("{ 0 1 ... 9 }")
.description("Subset of testcase indices to use for training sets")
.default_val(default_set);
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>& test_set_arg =
ValueArg<set<size_t>, SpanReader<set<size_t>, Range<size_t, 0, 1024 * 1024>>>::create("test_set")
.usage("{ 0 1 ... 9 }")
.description("Subset of testcase indices to use for test sets")
.default_val(default_set);
ValueArg<size_t>& testcase_idx_arg =
ValueArg<size_t>::create("index")
.usage("<int>")
.description("Testcase index")
.default_val(numeric_limits<size_t>::max());
} // namespace stoke
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012-2013 Matt Broadstone
* Contact: http://bitbucket.org/devonit/qjsonrpc
*
* This file is part of the QJsonRpc Library.
*
* 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.
*/
#include <QtCore/QVariant>
#include <QtTest/QtTest>
#include "json/qjsondocument.h"
#include "qjsonrpcmessage.h"
class TestQJsonRpcMessage: public QObject
{
Q_OBJECT
private slots:
void testInvalidData();
void testInvalidDataResponseWithId();
void testInvalidDataResponseWithoutId();
void testResponseSameId();
void testNotificationNoId();
void testMessageTypes();
void testPositionalParameters();
void testEquivalence();
void testWithVariantListArgs();
};
void TestQJsonRpcMessage::testInvalidData()
{
QJsonObject invalidData;
QJsonRpcMessage message(invalidData);
QCOMPARE(message.type(), QJsonRpcMessage::Invalid);
}
void TestQJsonRpcMessage::testInvalidDataResponseWithId()
{
// invalid with id
const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": [], \"id\": 666}";
QJsonDocument doc = QJsonDocument::fromJson(invalid);
QJsonRpcMessage request(doc.object());
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString());
QJsonRpcMessage response = request.createResponse(QString());
QCOMPARE(request.type(), QJsonRpcMessage::Invalid);
QCOMPARE(response.id(), request.id());
QCOMPARE(error.type(), QJsonRpcMessage::Error);
}
void TestQJsonRpcMessage::testInvalidDataResponseWithoutId()
{
// invalid without id
const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": []}";
QJsonDocument doc = QJsonDocument::fromJson(invalid);
QJsonRpcMessage request(doc.object());
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString());
QJsonRpcMessage response = request.createResponse(QString());
QCOMPARE(request.type(), QJsonRpcMessage::Invalid);
QCOMPARE(response.type(), QJsonRpcMessage::Invalid);
QCOMPARE(error.id(), 0);
}
void TestQJsonRpcMessage::testResponseSameId()
{
QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod");
QJsonRpcMessage response = request.createResponse("testResponse");
QCOMPARE(response.id(), request.id());
}
void TestQJsonRpcMessage::testNotificationNoId()
{
QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification");
QCOMPARE(notification.id(), -1);
}
void TestQJsonRpcMessage::testMessageTypes()
{
QJsonRpcMessage invalid;
QCOMPARE(invalid.type(), QJsonRpcMessage::Invalid);
QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod");
QCOMPARE(request.type(), QJsonRpcMessage::Request);
QJsonRpcMessage response = request.createResponse("testResponse");
QCOMPARE(response.type(), QJsonRpcMessage::Response);
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError);
QCOMPARE(error.type(), QJsonRpcMessage::Error);
QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification");
QCOMPARE(notification.type(), QJsonRpcMessage::Notification);
}
// this is from the spec, I don't think it proves much..
void TestQJsonRpcMessage::testPositionalParameters()
{
const char *first = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}";
QJsonObject firstObject = QJsonDocument::fromJson(first).object();
const char *second = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [23, 42], \"id\": 2}";
QJsonObject secondObject = QJsonDocument::fromJson(second).object();
QVERIFY2(firstObject.value("params").toArray() != secondObject.value("params").toArray(), "params should maintain order");
}
void TestQJsonRpcMessage::testEquivalence()
{
// request (same as error)
QJsonRpcMessage firstRequest = QJsonRpcMessage::createRequest("testRequest");
QJsonRpcMessage secondRequest(firstRequest);
QJsonRpcMessage thirdRequest = QJsonRpcMessage::createRequest("testRequest", QVariantList() << "with" << "parameters");
QJsonRpcMessage fourthRequest = thirdRequest;
QCOMPARE(firstRequest, secondRequest);
QVERIFY(secondRequest != thirdRequest);
QCOMPARE(thirdRequest, fourthRequest);
// notification (no id)
QJsonRpcMessage firstNotification = QJsonRpcMessage::createNotification("testNotification");
QJsonRpcMessage secondNotification = QJsonRpcMessage::createNotification("testNotification");
QJsonRpcMessage thirdNotification = QJsonRpcMessage::createNotification("testNotification", QVariantList() << "first");
QJsonRpcMessage fourthNotification = QJsonRpcMessage::createNotification("testNotification", QVariantList() << "first");
QCOMPARE(firstNotification, secondNotification);
QVERIFY(firstNotification != thirdNotification);
QCOMPARE(thirdNotification, fourthNotification);
QJsonRpcMessage invalid;
QVERIFY(firstRequest != invalid);
QVERIFY(secondRequest != invalid);
QVERIFY(thirdRequest != invalid);
QVERIFY(fourthRequest != invalid);
QVERIFY(firstNotification != invalid);
QVERIFY(secondNotification != invalid);
QVERIFY(thirdNotification != invalid);
QVERIFY(fourthNotification != invalid);
}
void TestQJsonRpcMessage::testWithVariantListArgs()
{
const char *varListArgs = "{ " \
"\"id\": 5, " \
"\"jsonrpc\": \"2.0\", " \
"\"method\": \"service.variantListParameter\", " \
"\"params\": [[ 1, 20, \"hello\", false ]] " \
"}";
QJsonRpcMessage requestFromQJsonRpc =
QJsonRpcMessage::createRequest("service.variantListParameter", QVariantList() << 1 << 20 << "hello" << false);
QJsonDocument doc = QJsonDocument::fromJson(varListArgs);
QJsonRpcMessage requestFromData(doc.object());
QCOMPARE(requestFromQJsonRpc, requestFromData);
}
QTEST_MAIN(TestQJsonRpcMessage)
#include "tst_qjsonrpcmessage.moc"
<commit_msg>fix qjsonrpcmessage test for variant list parameter<commit_after>/*
* Copyright (C) 2012-2013 Matt Broadstone
* Contact: http://bitbucket.org/devonit/qjsonrpc
*
* This file is part of the QJsonRpc Library.
*
* 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.
*/
#include <QtCore/QVariant>
#include <QtTest/QtTest>
#include "json/qjsondocument.h"
#include "qjsonrpcmessage.h"
class TestQJsonRpcMessage: public QObject
{
Q_OBJECT
private slots:
void testInvalidData();
void testInvalidDataResponseWithId();
void testInvalidDataResponseWithoutId();
void testResponseSameId();
void testNotificationNoId();
void testMessageTypes();
void testPositionalParameters();
void testEquivalence();
void testWithVariantListArgs();
};
void TestQJsonRpcMessage::testInvalidData()
{
QJsonObject invalidData;
QJsonRpcMessage message(invalidData);
QCOMPARE(message.type(), QJsonRpcMessage::Invalid);
}
void TestQJsonRpcMessage::testInvalidDataResponseWithId()
{
// invalid with id
const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": [], \"id\": 666}";
QJsonDocument doc = QJsonDocument::fromJson(invalid);
QJsonRpcMessage request(doc.object());
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString());
QJsonRpcMessage response = request.createResponse(QString());
QCOMPARE(request.type(), QJsonRpcMessage::Invalid);
QCOMPARE(response.id(), request.id());
QCOMPARE(error.type(), QJsonRpcMessage::Error);
}
void TestQJsonRpcMessage::testInvalidDataResponseWithoutId()
{
// invalid without id
const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": []}";
QJsonDocument doc = QJsonDocument::fromJson(invalid);
QJsonRpcMessage request(doc.object());
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString());
QJsonRpcMessage response = request.createResponse(QString());
QCOMPARE(request.type(), QJsonRpcMessage::Invalid);
QCOMPARE(response.type(), QJsonRpcMessage::Invalid);
QCOMPARE(error.id(), 0);
}
void TestQJsonRpcMessage::testResponseSameId()
{
QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod");
QJsonRpcMessage response = request.createResponse("testResponse");
QCOMPARE(response.id(), request.id());
}
void TestQJsonRpcMessage::testNotificationNoId()
{
QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification");
QCOMPARE(notification.id(), -1);
}
void TestQJsonRpcMessage::testMessageTypes()
{
QJsonRpcMessage invalid;
QCOMPARE(invalid.type(), QJsonRpcMessage::Invalid);
QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod");
QCOMPARE(request.type(), QJsonRpcMessage::Request);
QJsonRpcMessage response = request.createResponse("testResponse");
QCOMPARE(response.type(), QJsonRpcMessage::Response);
QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError);
QCOMPARE(error.type(), QJsonRpcMessage::Error);
QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification");
QCOMPARE(notification.type(), QJsonRpcMessage::Notification);
}
// this is from the spec, I don't think it proves much..
void TestQJsonRpcMessage::testPositionalParameters()
{
const char *first = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}";
QJsonObject firstObject = QJsonDocument::fromJson(first).object();
const char *second = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [23, 42], \"id\": 2}";
QJsonObject secondObject = QJsonDocument::fromJson(second).object();
QVERIFY2(firstObject.value("params").toArray() != secondObject.value("params").toArray(), "params should maintain order");
}
void TestQJsonRpcMessage::testEquivalence()
{
// request (same as error)
QJsonRpcMessage firstRequest = QJsonRpcMessage::createRequest("testRequest");
QJsonRpcMessage secondRequest(firstRequest);
QJsonRpcMessage thirdRequest = QJsonRpcMessage::createRequest("testRequest", QVariantList() << "with" << "parameters");
QJsonRpcMessage fourthRequest = thirdRequest;
QCOMPARE(firstRequest, secondRequest);
QVERIFY(secondRequest != thirdRequest);
QCOMPARE(thirdRequest, fourthRequest);
// notification (no id)
QJsonRpcMessage firstNotification = QJsonRpcMessage::createNotification("testNotification");
QJsonRpcMessage secondNotification = QJsonRpcMessage::createNotification("testNotification");
QJsonRpcMessage thirdNotification = QJsonRpcMessage::createNotification("testNotification", QVariantList() << "first");
QJsonRpcMessage fourthNotification = QJsonRpcMessage::createNotification("testNotification", QVariantList() << "first");
QCOMPARE(firstNotification, secondNotification);
QVERIFY(firstNotification != thirdNotification);
QCOMPARE(thirdNotification, fourthNotification);
QJsonRpcMessage invalid;
QVERIFY(firstRequest != invalid);
QVERIFY(secondRequest != invalid);
QVERIFY(thirdRequest != invalid);
QVERIFY(fourthRequest != invalid);
QVERIFY(firstNotification != invalid);
QVERIFY(secondNotification != invalid);
QVERIFY(thirdNotification != invalid);
QVERIFY(fourthNotification != invalid);
}
void TestQJsonRpcMessage::testWithVariantListArgs()
{
const char *varListArgs = "{ " \
"\"id\": 5, " \
"\"jsonrpc\": \"2.0\", " \
"\"method\": \"service.variantListParameter\", " \
"\"params\": [[ 1, 20, \"hello\", false ]] " \
"}";
QVariantList firstParameter;
firstParameter << 1 << 20 << "hello" << false;
QJsonRpcMessage requestFromQJsonRpc =
QJsonRpcMessage::createRequest("service.variantListParameter", QVariant(firstParameter));
QJsonDocument doc = QJsonDocument::fromJson(varListArgs);
QJsonRpcMessage requestFromData(doc.object());
QCOMPARE(requestFromQJsonRpc, requestFromData);
}
QTEST_MAIN(TestQJsonRpcMessage)
#include "tst_qjsonrpcmessage.moc"
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <QtCore/QSocketNotifier>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <private/qnativesocketengine_p.h>
class tst_QSocketNotifier : public QObject
{
Q_OBJECT
public:
tst_QSocketNotifier();
~tst_QSocketNotifier();
private slots:
void unexpectedDisconnection();
void mixingWithTimers();
};
tst_QSocketNotifier::tst_QSocketNotifier()
{ }
tst_QSocketNotifier::~tst_QSocketNotifier()
{
}
class UnexpectedDisconnectTester : public QObject
{
Q_OBJECT
int sequence;
public:
QNativeSocketEngine *readEnd1, *readEnd2;
UnexpectedDisconnectTester(QNativeSocketEngine *s1, QNativeSocketEngine *s2)
: readEnd1(s1), readEnd2(s2), sequence(0)
{
QSocketNotifier *notifier1 =
new QSocketNotifier(readEnd1->socketDescriptor(), QSocketNotifier::Read, this);
connect(notifier1, SIGNAL(activated(int)), SLOT(handleActivated()));
QSocketNotifier *notifier2 =
new QSocketNotifier(readEnd2->socketDescriptor(), QSocketNotifier::Read, this);
connect(notifier2, SIGNAL(activated(int)), SLOT(handleActivated()));
}
const int getSequence() {
return sequence;
}
void incSequence() {
++sequence;
}
public slots:
void handleActivated()
{
char data1[1], data2[1];
incSequence();
if (getSequence() == 1) {
// read from both ends
(void) readEnd1->read(data1, sizeof(data1));
(void) readEnd2->read(data2, sizeof(data2));
emit finished();
} else if (getSequence() == 2) {
QCOMPARE(readEnd2->read(data2, sizeof(data2)), qint64(-2));
QVERIFY(readEnd2->isValid());
}
}
signals:
void finished();
};
void tst_QSocketNotifier::unexpectedDisconnection()
{
/*
Given two sockets and two QSocketNotifiers registered on each
their socket. If both sockets receive data, and the first slot
invoked by one of the socket notifiers empties both sockets, the
other notifier will also emit activated(). This results in
unexpected disconnection in QAbstractSocket.
The use case is that somebody calls one of the
waitFor... functions in a QSocketNotifier activated slot, and
the waitFor... functions do local selects that can empty both
stdin and stderr while waiting for fex bytes to be written.
*/
QTcpServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
QNativeSocketEngine readEnd1;
readEnd1.initialize(QAbstractSocket::TcpSocket);
bool b = readEnd1.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd1.waitForWrite());
// while (!b && readEnd1.state() != QAbstractSocket::ConnectedState)
// b = readEnd1.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
QVERIFY(server.waitForNewConnection());
QTcpSocket *writeEnd1 = server.nextPendingConnection();
QVERIFY(writeEnd1 != 0);
QNativeSocketEngine readEnd2;
readEnd2.initialize(QAbstractSocket::TcpSocket);
b = readEnd2.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd2.waitForWrite());
// while (!b)
// b = readEnd2.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);
QVERIFY(server.waitForNewConnection());
QTcpSocket *writeEnd2 = server.nextPendingConnection();
QVERIFY(writeEnd2 != 0);
writeEnd1->write("1", 1);
writeEnd2->write("2", 1);
writeEnd1->waitForBytesWritten();
writeEnd2->waitForBytesWritten();
writeEnd1->flush();
writeEnd2->flush();
UnexpectedDisconnectTester tester(&readEnd1, &readEnd2);
do {
// we have to wait until sequence value changes
// as any event can make us jump out processing
QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
} while(tester.getSequence() <= 0);
QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);
#if defined(Q_OS_WIN)
qWarning("### Windows returns 1 activation, Unix returns 2.");
QCOMPARE(tester.sequence, 1);
#else
QCOMPARE(tester.getSequence(), 2);
#endif
readEnd1.close();
readEnd2.close();
writeEnd1->close();
writeEnd2->close();
server.close();
}
class MixingWithTimersHelper : public QObject
{
Q_OBJECT
public:
MixingWithTimersHelper(QTimer *timer, QTcpServer *server);
bool timerActivated;
bool socketActivated;
private slots:
void timerFired();
void socketFired();
};
MixingWithTimersHelper::MixingWithTimersHelper(QTimer *timer, QTcpServer *server)
{
timerActivated = false;
socketActivated = false;
connect(timer, SIGNAL(timeout()), SLOT(timerFired()));
connect(server, SIGNAL(newConnection()), SLOT(socketFired()));
}
void MixingWithTimersHelper::timerFired()
{
timerActivated = true;
}
void MixingWithTimersHelper::socketFired()
{
socketActivated = true;
}
void tst_QSocketNotifier::mixingWithTimers()
{
QTimer timer;
timer.setInterval(0);
timer.start();
QTcpServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
MixingWithTimersHelper helper(&timer, &server);
QCoreApplication::processEvents();
QCOMPARE(helper.timerActivated, true);
QCOMPARE(helper.socketActivated, false);
helper.timerActivated = false;
helper.socketActivated = false;
QTcpSocket socket;
socket.connectToHost(server.serverAddress(), server.serverPort());
QCoreApplication::processEvents();
QCOMPARE(helper.timerActivated, true);
QCOMPARE(helper.socketActivated, true);
}
QTEST_MAIN(tst_QSocketNotifier)
#include <tst_qsocketnotifier.moc>
<commit_msg>Fixed qsocketnotifier autotest compilation for win32-msvc2008 platform.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <QtCore/QSocketNotifier>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <private/qnativesocketengine_p.h>
class tst_QSocketNotifier : public QObject
{
Q_OBJECT
public:
tst_QSocketNotifier();
~tst_QSocketNotifier();
private slots:
void unexpectedDisconnection();
void mixingWithTimers();
};
tst_QSocketNotifier::tst_QSocketNotifier()
{ }
tst_QSocketNotifier::~tst_QSocketNotifier()
{
}
class UnexpectedDisconnectTester : public QObject
{
Q_OBJECT
int sequence;
public:
QNativeSocketEngine *readEnd1, *readEnd2;
UnexpectedDisconnectTester(QNativeSocketEngine *s1, QNativeSocketEngine *s2)
: readEnd1(s1), readEnd2(s2), sequence(0)
{
QSocketNotifier *notifier1 =
new QSocketNotifier(readEnd1->socketDescriptor(), QSocketNotifier::Read, this);
connect(notifier1, SIGNAL(activated(int)), SLOT(handleActivated()));
QSocketNotifier *notifier2 =
new QSocketNotifier(readEnd2->socketDescriptor(), QSocketNotifier::Read, this);
connect(notifier2, SIGNAL(activated(int)), SLOT(handleActivated()));
}
const int getSequence() {
return sequence;
}
void incSequence() {
++sequence;
}
public slots:
void handleActivated()
{
char data1[1], data2[1];
incSequence();
if (getSequence() == 1) {
// read from both ends
(void) readEnd1->read(data1, sizeof(data1));
(void) readEnd2->read(data2, sizeof(data2));
emit finished();
} else if (getSequence() == 2) {
QCOMPARE(readEnd2->read(data2, sizeof(data2)), qint64(-2));
QVERIFY(readEnd2->isValid());
}
}
signals:
void finished();
};
void tst_QSocketNotifier::unexpectedDisconnection()
{
/*
Given two sockets and two QSocketNotifiers registered on each
their socket. If both sockets receive data, and the first slot
invoked by one of the socket notifiers empties both sockets, the
other notifier will also emit activated(). This results in
unexpected disconnection in QAbstractSocket.
The use case is that somebody calls one of the
waitFor... functions in a QSocketNotifier activated slot, and
the waitFor... functions do local selects that can empty both
stdin and stderr while waiting for fex bytes to be written.
*/
QTcpServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
QNativeSocketEngine readEnd1;
readEnd1.initialize(QAbstractSocket::TcpSocket);
bool b = readEnd1.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd1.waitForWrite());
// while (!b && readEnd1.state() != QAbstractSocket::ConnectedState)
// b = readEnd1.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
QVERIFY(server.waitForNewConnection());
QTcpSocket *writeEnd1 = server.nextPendingConnection();
QVERIFY(writeEnd1 != 0);
QNativeSocketEngine readEnd2;
readEnd2.initialize(QAbstractSocket::TcpSocket);
b = readEnd2.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd2.waitForWrite());
// while (!b)
// b = readEnd2.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);
QVERIFY(server.waitForNewConnection());
QTcpSocket *writeEnd2 = server.nextPendingConnection();
QVERIFY(writeEnd2 != 0);
writeEnd1->write("1", 1);
writeEnd2->write("2", 1);
writeEnd1->waitForBytesWritten();
writeEnd2->waitForBytesWritten();
writeEnd1->flush();
writeEnd2->flush();
UnexpectedDisconnectTester tester(&readEnd1, &readEnd2);
do {
// we have to wait until sequence value changes
// as any event can make us jump out processing
QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
} while(tester.getSequence() <= 0);
QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);
#if defined(Q_OS_WIN)
qWarning("### Windows returns 1 activation, Unix returns 2.");
QCOMPARE(tester.getSequence(), 1);
#else
QCOMPARE(tester.getSequence(), 2);
#endif
readEnd1.close();
readEnd2.close();
writeEnd1->close();
writeEnd2->close();
server.close();
}
class MixingWithTimersHelper : public QObject
{
Q_OBJECT
public:
MixingWithTimersHelper(QTimer *timer, QTcpServer *server);
bool timerActivated;
bool socketActivated;
private slots:
void timerFired();
void socketFired();
};
MixingWithTimersHelper::MixingWithTimersHelper(QTimer *timer, QTcpServer *server)
{
timerActivated = false;
socketActivated = false;
connect(timer, SIGNAL(timeout()), SLOT(timerFired()));
connect(server, SIGNAL(newConnection()), SLOT(socketFired()));
}
void MixingWithTimersHelper::timerFired()
{
timerActivated = true;
}
void MixingWithTimersHelper::socketFired()
{
socketActivated = true;
}
void tst_QSocketNotifier::mixingWithTimers()
{
QTimer timer;
timer.setInterval(0);
timer.start();
QTcpServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
MixingWithTimersHelper helper(&timer, &server);
QCoreApplication::processEvents();
QCOMPARE(helper.timerActivated, true);
QCOMPARE(helper.socketActivated, false);
helper.timerActivated = false;
helper.socketActivated = false;
QTcpSocket socket;
socket.connectToHost(server.serverAddress(), server.serverPort());
QCoreApplication::processEvents();
QCOMPARE(helper.timerActivated, true);
QCOMPARE(helper.socketActivated, true);
}
QTEST_MAIN(tst_QSocketNotifier)
#include <tst_qsocketnotifier.moc>
<|endoftext|> |
<commit_before>/**
* \file dcs/testbed/system_experiment.hpp
*
* \brief Performs system experiment experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
#define DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
//#include <boost/chrono.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
//#include <dcs/testbed/base_application.hpp>
//#include <dcs/testbed/base_application_manager.hpp>
//#include <dcs/testbed/base_experiment_monitor.hpp>
//#include <dcs/testbed/base_workload_driver.hpp>
//#include <dcs/testbed/detail/application_experiment_runner.hpp>
#include <dcs/testbed/application_experiment.hpp>
#include <dcs/testbed/detail/runnable.hpp>
#include <stdexcept>
#include <vector>
//#ifdef DCS_DEBUG
//# include <boost/numeric/ublas/io.hpp>
//#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename TraitsT>
class system_experiment
{
private: typedef system_experiment<TraitsT> self_type;
public: typedef TraitsT traits_type;
//public: typedef typename traits_type::real_type real_type;
// private: typedef base_application<traits_type> app_type;
// public: typedef ::boost::shared_ptr<app_type> app_pointer;
// private: typedef base_application_manager<traits_type> app_manager_type;
// public: typedef ::boost::shared_ptr<app_manager_type> app_manager_pointer;
// private: typedef base_workload_driver<traits_type> app_driver_type;
// public: typedef ::boost::shared_ptr<app_driver_type> app_driver_pointer;
private: typedef application_experiment<traits_type> app_experiment_type;
private: typedef ::boost::shared_ptr<app_experiment_type> app_experiment_pointer;
private: typedef ::std::vector<app_experiment_pointer> app_experiment_container;
private: typedef ::boost::signals2::signal<void (self_type const&)> signal_type;
private: typedef ::boost::shared_ptr<signal_type> signal_pointer;
public: system_experiment()
: running_(false),
p_sta_sig_(new signal_type()),
p_sto_sig_(new signal_type())
{
}
public: void add_app_experiment(app_experiment_pointer const& p_exp)
{
app_exps_.push_back(p_exp);
}
public: ::std::vector<app_experiment_pointer> experiments() const
{
return app_exps_;
}
public: template <typename FuncT>
void add_on_start_handler(FuncT f)
{
p_sta_sig_->connect(f);
}
public: template <typename FuncT>
void add_on_stop_handler(FuncT f)
{
p_sto_sig_->connect(f);
}
// public: void add_app(app_pointer const& p_app,
// app_driver_pointer const& p_drv,
// app_manager_pointer const& p_mgr,
// monitor_pointer const& p_mon)
// {
// app_exps_.push_back(::boost::make_shared<app_experiment_type>(p_app, p_drv, p_mgr, p_mon));
// }
// public: template <typename MonIterT>
// void add_app(app_pointer const& p_app,
// app_driver_pointer const& p_drv,
// app_manager_pointer const& p_mgr,
// MonIterT first_mon,
// MonIterT last_mon)
// {
// app_exps_.push_back(::boost::make_shared<app_experiment_type>(p_app, p_drv, p_mgr, first_mon, last_mon));
// }
/**
* \brief Perform system experiment.
*/
public: void run()
{
typedef typename app_experiment_container::const_iterator app_experiment_iterator;
// typedef typename monitor_container::const_iterator monitor_iterator;
DCS_DEBUG_TRACE( "BEGIN Execution of System EXPERIMENT" );
app_experiment_iterator app_exp_end_it(app_exps_.end());
app_experiment_iterator app_exp_beg_it(app_exps_.begin());
(*p_sta_sig_)(*this);
if (app_exp_beg_it != app_exp_end_it)
{
// There is some experiment to run
::boost::thread_group exp_thds;
// Create threads for application experiments
for (app_experiment_iterator app_exp_it = app_exp_beg_it;
app_exp_it != app_exp_end_it;
++app_exp_it)
{
app_experiment_pointer p_app_exp(*app_exp_it);
detail::runnable<app_experiment_type> exp_runner(*app_exp_it);
//::boost::thread exp_thd(exp_runner);
exp_thds.create_thread(exp_runner);
//::boost::this_thread::sleep_for(::boost::chrono::seconds(2));
}
// // Create threads for experiment monitors
// system_experiment_context<traits_type> ctx(this);
// monitor_iterator mon_end_it(mons_.end());
// for (monitor_iterator mon_it = mons_.begin();
// mon_it != mon_end_it;
// ++mon_it)
// {
// monitor_pointer p_mon(*mon_it);
//
// detail::monitor_runnable<monitor_type> mon_runner(p_mon, ctx);
// exp_thds.create_thread(mon_runner);
// }
running_ = true;
exp_thds.join_all();
running_ = false;
}
(*p_sto_sig_)(*this);
DCS_DEBUG_TRACE( "END Execution of System EXPERIMENT" );
}
public: bool running() const
{
return running_;
}
private: bool running_; ///< Tells if this system experiment is running
private: app_experiment_container app_exps_; ///< Application experiments container
// private: monitor_container mons_; ///< Experiment monitors container
private: signal_pointer p_sta_sig_;
private: signal_pointer p_sto_sig_;
}; // system_experiment
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
<commit_msg>(change) Random number generator is now embedded inside a system_experiment class<commit_after>/**
* \file dcs/testbed/system_experiment.hpp
*
* \brief Performs system experiment experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
#define DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
//#include <boost/chrono.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
//#include <dcs/testbed/base_application.hpp>
//#include <dcs/testbed/base_application_manager.hpp>
//#include <dcs/testbed/base_experiment_monitor.hpp>
//#include <dcs/testbed/base_workload_driver.hpp>
//#include <dcs/testbed/detail/application_experiment_runner.hpp>
#include <dcs/testbed/application_experiment.hpp>
#include <dcs/testbed/detail/runnable.hpp>
#include <stdexcept>
#include <vector>
//#ifdef DCS_DEBUG
//# include <boost/numeric/ublas/io.hpp>
//#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename TraitsT>
class system_experiment
{
private: typedef system_experiment<TraitsT> self_type;
public: typedef TraitsT traits_type;
public: typedef typename traits_type::rng_type rng_type;
//public: typedef typename traits_type::real_type real_type;
// private: typedef base_application<traits_type> app_type;
// public: typedef ::boost::shared_ptr<app_type> app_pointer;
// private: typedef base_application_manager<traits_type> app_manager_type;
// public: typedef ::boost::shared_ptr<app_manager_type> app_manager_pointer;
// private: typedef base_workload_driver<traits_type> app_driver_type;
// public: typedef ::boost::shared_ptr<app_driver_type> app_driver_pointer;
private: typedef application_experiment<traits_type> app_experiment_type;
private: typedef ::boost::shared_ptr<app_experiment_type> app_experiment_pointer;
private: typedef ::std::vector<app_experiment_pointer> app_experiment_container;
private: typedef ::boost::signals2::signal<void (self_type const&)> signal_type;
private: typedef ::boost::shared_ptr<signal_type> signal_pointer;
public: system_experiment()
: running_(false),
p_sta_sig_(new signal_type()),
p_sto_sig_(new signal_type()),
p_rng_(new rng_type())
{
}
public: void add_app_experiment(app_experiment_pointer const& p_exp)
{
app_exps_.push_back(p_exp);
}
public: ::std::vector<app_experiment_pointer> experiments() const
{
return app_exps_;
}
public: template <typename FuncT>
void add_on_start_handler(FuncT f)
{
p_sta_sig_->connect(f);
}
public: template <typename FuncT>
void add_on_stop_handler(FuncT f)
{
p_sto_sig_->connect(f);
}
// public: void add_app(app_pointer const& p_app,
// app_driver_pointer const& p_drv,
// app_manager_pointer const& p_mgr,
// monitor_pointer const& p_mon)
// {
// app_exps_.push_back(::boost::make_shared<app_experiment_type>(p_app, p_drv, p_mgr, p_mon));
// }
// public: template <typename MonIterT>
// void add_app(app_pointer const& p_app,
// app_driver_pointer const& p_drv,
// app_manager_pointer const& p_mgr,
// MonIterT first_mon,
// MonIterT last_mon)
// {
// app_exps_.push_back(::boost::make_shared<app_experiment_type>(p_app, p_drv, p_mgr, first_mon, last_mon));
// }
public: void rng(boost::shared_ptr<rng_type> const& p_rng)
{
p_rng_ = p_rng;
}
public: boost::shared_ptr<rng_type> const& rng_ptr() const
{
return p_rng_;
}
/**
* \brief Perform system experiment.
*/
public: void run()
{
typedef typename app_experiment_container::const_iterator app_experiment_iterator;
// typedef typename monitor_container::const_iterator monitor_iterator;
DCS_DEBUG_TRACE( "BEGIN Execution of System EXPERIMENT" );
app_experiment_iterator app_exp_end_it(app_exps_.end());
app_experiment_iterator app_exp_beg_it(app_exps_.begin());
(*p_sta_sig_)(*this);
if (app_exp_beg_it != app_exp_end_it)
{
// There is some experiment to run
::boost::thread_group exp_thds;
// Create threads for application experiments
for (app_experiment_iterator app_exp_it = app_exp_beg_it;
app_exp_it != app_exp_end_it;
++app_exp_it)
{
app_experiment_pointer p_app_exp(*app_exp_it);
detail::runnable<app_experiment_type> exp_runner(*app_exp_it);
//::boost::thread exp_thd(exp_runner);
exp_thds.create_thread(exp_runner);
//::boost::this_thread::sleep_for(::boost::chrono::seconds(2));
}
// // Create threads for experiment monitors
// system_experiment_context<traits_type> ctx(this);
// monitor_iterator mon_end_it(mons_.end());
// for (monitor_iterator mon_it = mons_.begin();
// mon_it != mon_end_it;
// ++mon_it)
// {
// monitor_pointer p_mon(*mon_it);
//
// detail::monitor_runnable<monitor_type> mon_runner(p_mon, ctx);
// exp_thds.create_thread(mon_runner);
// }
running_ = true;
exp_thds.join_all();
running_ = false;
}
(*p_sto_sig_)(*this);
DCS_DEBUG_TRACE( "END Execution of System EXPERIMENT" );
}
public: bool running() const
{
return running_;
}
private: bool running_; ///< Tells if this system experiment is running
private: app_experiment_container app_exps_; ///< Application experiments container
// private: monitor_container mons_; ///< Experiment monitors container
private: signal_pointer p_sta_sig_;
private: signal_pointer p_sto_sig_;
private: boost::shared_ptr<rng_type> p_rng_;
}; // system_experiment
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_EXPERIMENT_HPP
<|endoftext|> |
<commit_before>
#include <iostream>
#include "drake/systems/plants/collision/DrakeCollision.h"
#ifdef BULLET_COLLISION
#include "drake/systems/plants/collision/bullet_model.h"
#endif
using namespace std;
using namespace Eigen;
namespace DrakeCollision {
const bitmask ALL_MASK(bitmask(0).set());
const bitmask NONE_MASK(0);
const bitmask DEFAULT_GROUP(1);
enum DRAKECOLLISION_EXPORT ModelType { NONE, AUTO, BULLET };
unique_ptr<Model> newModel(ModelType model_type) {
switch (model_type) {
case NONE:
return nullptr;
break;
case BULLET:
#ifdef BULLET_COLLISION
return unique_ptr<Model>(new BulletModel());
#else
cerr << "Recompile with Bullet enabled (-DBULLET_COLLISION) to use "
"Bullet collision models." << endl;
#endif
break;
default:
cerr << model_type << " is not a recognized collision model type."
<< endl;
}
return unique_ptr<Model>();
}
unique_ptr<Model> newModel() {
#ifdef BULLET_COLLISION
return newModel(BULLET);
#else
DRAKE_ABORT_UNLESS("DrakeCollision must be compiled with Bullet.");
#endif
}
};
<commit_msg>Fixes DRAKE_ABORT condition<commit_after>
#include <iostream>
#include "drake/systems/plants/collision/DrakeCollision.h"
#ifdef BULLET_COLLISION
#include "drake/systems/plants/collision/bullet_model.h"
#endif
using namespace std;
using namespace Eigen;
namespace DrakeCollision {
const bitmask ALL_MASK(bitmask(0).set());
const bitmask NONE_MASK(0);
const bitmask DEFAULT_GROUP(1);
enum DRAKECOLLISION_EXPORT ModelType { NONE, AUTO, BULLET };
unique_ptr<Model> newModel(ModelType model_type) {
switch (model_type) {
case NONE:
return nullptr;
break;
case BULLET:
#ifdef BULLET_COLLISION
return unique_ptr<Model>(new BulletModel());
#else
cerr << "Recompile with Bullet enabled (-DBULLET_COLLISION) to use "
"Bullet collision models." << endl;
#endif
break;
default:
cerr << model_type << " is not a recognized collision model type."
<< endl;
}
return unique_ptr<Model>();
}
unique_ptr<Model> newModel() {
#ifdef BULLET_COLLISION
return newModel(BULLET);
#else
DRAKE_ABORT_UNLESS(!"DrakeCollision must be compiled with Bullet.");
#endif
}
};
<|endoftext|> |
<commit_before>#include "terminal.h"
#include "mqttError.h"
#include "frame.h"
#include <random>
#include <chrono>
#include <string.h>
#include <unistd.h>
Terminal::Terminal(const std::string id, const User* u, uint32_t keepAlive, const Will* w) : isConnecting(false), cleanSession(false), ID(id), user(u), will(w), keepAlive(keepAlive*1000000) {
std::random_device rnd;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
mt(); // TODO: apply seed
}
Terminal::~Terminal() {
delete this->user;
delete this->will;
}
MQTT_ERROR Terminal::ackMessage(uint16_t pID) {
if (this->packetIDMap.find(pID) == this->packetIDMap.end()) {
return PACKET_ID_DOES_NOT_EXIST; // packet id does not exist
}
Message* m = this->packetIDMap[pID];
delete m;
this->packetIDMap.erase(pID);
return NO_ERROR;
}
MQTT_ERROR Terminal::sendMessage(Message* m) {
if (!this->isConnecting) {
return NOT_CONNECTED;
}
uint16_t packetID = m->fh->packetID;
if (this->packetIDMap.find(packetID) != this->packetIDMap.end()) {
return PACKET_ID_IS_USED_ALREADY;
}
MQTT_ERROR err = this->ct->sendMessage(m);
if (err == NO_ERROR) {
if (m->fh->type == PUBLISH_MESSAGE_TYPE) {
if (packetID > 0) {
this->packetIDMap[packetID] = m;
}
} else if (m->fh->type == PUBREC_MESSAGE_TYPE || m->fh->type == SUBSCRIBE_MESSAGE_TYPE || m->fh->type == UNSUBSCRIBE_MESSAGE_TYPE || m->fh->type == PUBREL_MESSAGE_TYPE) {
if (packetID == 0) {
return PACKET_ID_SHOULD_NOT_BE_ZERO;
}
this->packetIDMap[packetID] = m;
}
}
return err;
}
MQTT_ERROR Terminal::redelivery() {
MQTT_ERROR err;
if (!this->cleanSession && this->packetIDMap.size() > 0) {
for (std::map<uint16_t, Message*>::iterator itPair = this->packetIDMap.begin(); itPair != this->packetIDMap.end(); itPair++) {
if (itPair->second->fh->type == PUBLISH_MESSAGE_TYPE) {
itPair->second->fh->dup = true;
}
err = this->sendMessage(itPair->second);
if (err != NO_ERROR) {
return err;
}
}
}
return NO_ERROR;
}
MQTT_ERROR Terminal::getUsablePacketID(uint16_t* id) {
bool exists = true;
for (int trial = 0; exists; trial++) {
if (trial == 5) {
*id = -1;
return FAIL_TO_SET_PACKET_ID;
}
*id = randPacketID(mt);
exists = !(this->packetIDMap.find(*id) == this->packetIDMap.end());
}
return NO_ERROR;
}
MQTT_ERROR Terminal::disconnectBase() {
if (this->isConnecting) {
this->isConnecting = false;
this->will = NULL;
}
close(this->ct->sock);
return NO_ERROR;
}
MQTT_ERROR readLoop(Terminal* c) {
MQTT_ERROR err = NO_ERROR;
bool first = true;
while (first || c->isConnecting) {
first = false;
err = c->ct->readMessage();
if (err == NO_ERROR) {
FixedHeader* fh = new FixedHeader();
int len = fh->parseHeader(c->ct->readBuff, err);
switch (fh->type) {
case CONNECT_MESSAGE_TYPE:
{
ConnectMessage* m = new ConnectMessage(fh, c->ct->readBuff+len, err);
err = c->recvConnectMessage(m);
break;
}
case CONNACK_MESSAGE_TYPE:
{
ConnackMessage* m = new ConnackMessage(fh, c->ct->readBuff+len, err);
err = c->recvConnackMessage(m);
break;
}
case PUBLISH_MESSAGE_TYPE:
{
PublishMessage* m = new PublishMessage(fh, c->ct->readBuff+len, err);
err = c->recvPublishMessage(m);
break;
}
case PUBACK_MESSAGE_TYPE:
{
PubackMessage* m = new PubackMessage(fh, c->ct->readBuff+len, err);
err = c->recvPubackMessage(m);
break;
}
case PUBREC_MESSAGE_TYPE:
{
PubrecMessage* m = new PubrecMessage(fh, c->ct->readBuff+len, err);
err = c->recvPubrecMessage(m);
break;
}
case PUBREL_MESSAGE_TYPE:
{
PubrelMessage* m = new PubrelMessage(fh, c->ct->readBuff+len, err);
err = c->recvPubrelMessage(m);
break;
}
case PUBCOMP_MESSAGE_TYPE:
{
PubcompMessage* m = new PubcompMessage(fh, c->ct->readBuff+len, err);
err = c->recvPubcompMessage(m);
break;
}
case SUBSCRIBE_MESSAGE_TYPE:
{
SubscribeMessage* m = new SubscribeMessage(fh, c->ct->readBuff+len, err);
err = c->recvSubscribeMessage(m);
break;
}
case SUBACK_MESSAGE_TYPE:
{
SubackMessage* m = new SubackMessage(fh, c->ct->readBuff+len, err);
err = c->recvSubackMessage(m);
break;
}
case UNSUBSCRIBE_MESSAGE_TYPE:
{
UnsubscribeMessage* m = new UnsubscribeMessage(fh, c->ct->readBuff+len, err);
err = c->recvUnsubscribeMessage(m);
break;
}
case UNSUBACK_MESSAGE_TYPE:
{
UnsubackMessage* m = new UnsubackMessage(fh, c->ct->readBuff+len, err);
err = c->recvUnsubackMessage(m);
break;
}
case PINGREQ_MESSAGE_TYPE:
{
PingreqMessage* m = new PingreqMessage(fh, c->ct->readBuff+len, err);
err = c->recvPingreqMessage(m);
break;
}
case PINGRESP_MESSAGE_TYPE:
{
PingrespMessage* m = new PingrespMessage(fh, c->ct->readBuff+len, err);
err = c->recvPingrespMessage(m);
break;
}
case DISCONNECT_MESSAGE_TYPE:
{
DisconnectMessage* m = new DisconnectMessage(fh, c->ct->readBuff+len, err);
err = c->recvDisconnectMessage(m);
break;
}
default:
err = INVALID_MESSAGE_TYPE;
break;
}
if (err != NO_ERROR) {
return err;
}
}
}
return err;
}
<commit_msg>more flexible way(still not cool)<commit_after>#include "terminal.h"
#include "mqttError.h"
#include "frame.h"
#include <random>
#include <chrono>
#include <string.h>
#include <unistd.h>
Terminal::Terminal(const std::string id, const User* u, uint32_t keepAlive, const Will* w) : isConnecting(false), cleanSession(false), ID(id), user(u), will(w), keepAlive(keepAlive*1000000) {
std::random_device rnd;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
mt(); // TODO: apply seed
}
Terminal::~Terminal() {
delete this->user;
delete this->will;
}
MQTT_ERROR Terminal::ackMessage(uint16_t pID) {
if (this->packetIDMap.find(pID) == this->packetIDMap.end()) {
return PACKET_ID_DOES_NOT_EXIST; // packet id does not exist
}
Message* m = this->packetIDMap[pID];
delete m;
this->packetIDMap.erase(pID);
return NO_ERROR;
}
MQTT_ERROR Terminal::sendMessage(Message* m) {
if (!this->isConnecting) {
return NOT_CONNECTED;
}
uint16_t packetID = m->fh->packetID;
if (this->packetIDMap.find(packetID) != this->packetIDMap.end()) {
return PACKET_ID_IS_USED_ALREADY;
}
MQTT_ERROR err = this->ct->sendMessage(m);
if (err == NO_ERROR) {
if (m->fh->type == PUBLISH_MESSAGE_TYPE) {
if (packetID > 0) {
this->packetIDMap[packetID] = m;
}
} else if (m->fh->type == PUBREC_MESSAGE_TYPE || m->fh->type == SUBSCRIBE_MESSAGE_TYPE || m->fh->type == UNSUBSCRIBE_MESSAGE_TYPE || m->fh->type == PUBREL_MESSAGE_TYPE) {
if (packetID == 0) {
return PACKET_ID_SHOULD_NOT_BE_ZERO;
}
this->packetIDMap[packetID] = m;
}
}
return err;
}
MQTT_ERROR Terminal::redelivery() {
MQTT_ERROR err;
if (!this->cleanSession && this->packetIDMap.size() > 0) {
for (std::map<uint16_t, Message*>::iterator itPair = this->packetIDMap.begin(); itPair != this->packetIDMap.end(); itPair++) {
if (itPair->second->fh->type == PUBLISH_MESSAGE_TYPE) {
itPair->second->fh->dup = true;
}
err = this->sendMessage(itPair->second);
if (err != NO_ERROR) {
return err;
}
}
}
return NO_ERROR;
}
MQTT_ERROR Terminal::getUsablePacketID(uint16_t* id) {
bool exists = true;
for (int trial = 0; exists; trial++) {
if (trial == 5) {
*id = -1;
return FAIL_TO_SET_PACKET_ID;
}
*id = randPacketID(mt);
exists = !(this->packetIDMap.find(*id) == this->packetIDMap.end());
}
return NO_ERROR;
}
MQTT_ERROR Terminal::disconnectBase() {
if (this->isConnecting) {
this->isConnecting = false;
this->will = NULL;
}
close(this->ct->sock);
return NO_ERROR;
}
MQTT_ERROR readLoop(Terminal* c) {
MQTT_ERROR err = NO_ERROR;
bool first = true;
while (first || c->isConnecting) {
first = false;
err = c->ct->readMessage();
if (err == NO_ERROR) {
FixedHeader* fh = new FixedHeader();
int len = fh->parseHeader(c->ct->readBuff, err);
Message* m;
switch (fh->type) {
case CONNECT_MESSAGE_TYPE:
{
m = new ConnectMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvConnectMessage((ConnectMessage*)m);
break;
}
case CONNACK_MESSAGE_TYPE:
{
m = new ConnackMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvConnackMessage((ConnackMessage*)m);
break;
}
case PUBLISH_MESSAGE_TYPE:
{
m = new PublishMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPublishMessage((PublishMessage*)m);
break;
}
case PUBACK_MESSAGE_TYPE:
{
m = new PubackMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPubackMessage((PubackMessage*)m);
break;
}
case PUBREC_MESSAGE_TYPE:
{
m = new PubrecMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPubrecMessage((PubrecMessage*)m);
break;
}
case PUBREL_MESSAGE_TYPE:
{
m = new PubrelMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPubrelMessage((PubrelMessage*)m);
break;
}
case PUBCOMP_MESSAGE_TYPE:
{
m = new PubcompMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPubcompMessage((PubcompMessage*)m);
break;
}
case SUBSCRIBE_MESSAGE_TYPE:
{
m = new SubscribeMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvSubscribeMessage((SubscribeMessage*)m);
break;
}
case SUBACK_MESSAGE_TYPE:
{
m = new SubackMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvSubackMessage((SubackMessage*)m);
break;
}
case UNSUBSCRIBE_MESSAGE_TYPE:
{
m = new UnsubscribeMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvUnsubscribeMessage((UnsubscribeMessage*)m);
break;
}
case UNSUBACK_MESSAGE_TYPE:
{
m = new UnsubackMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvUnsubackMessage((UnsubackMessage*)m);
break;
}
case PINGREQ_MESSAGE_TYPE:
{
m = new PingreqMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPingreqMessage((PingreqMessage*)m);
break;
}
case PINGRESP_MESSAGE_TYPE:
{
m = new PingrespMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvPingrespMessage((PingrespMessage*)m);
break;
}
case DISCONNECT_MESSAGE_TYPE:
{
m = new DisconnectMessage(fh, c->ct->readBuff+len, err);
std::cout << "[RECV]" << m->getString() << std::endl;
err = c->recvDisconnectMessage((DisconnectMessage*)m);
break;
}
default:
err = INVALID_MESSAGE_TYPE;
break;
}
if (err != NO_ERROR) {
return err;
}
}
}
return err;
}
<|endoftext|> |
<commit_before>#include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
using namespace sqlite_orm;
#if SQLITE_VERSION_NUMBER >= 3006019
TEST_CASE("statement_serializator foreign key") {
SECTION("one to one") {
struct User {
int id = 0;
std::string name;
};
struct Visit {
int id = 0;
decltype(User::id) userId;
long time = 0;
};
auto usersTable = make_table("users",
make_column("id", &User::id, primary_key(), autoincrement()),
make_column("name", &User::name));
SECTION("simple") {
auto fk = foreign_key(&Visit::userId).references(&User::id);
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id)");
}
SECTION("on update") {
SECTION("no_action") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.no_action();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON UPDATE NO ACTION");
}
SECTION("restrict_") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.restrict_();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON UPDATE RESTRICT");
}
SECTION("set_null") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.set_null();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON UPDATE SET NULL");
}
SECTION("set_default") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.set_default();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON UPDATE SET DEFAULT");
}
SECTION("cascade") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.cascade();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON UPDATE CASCADE");
}
}
SECTION("on delete") {
SECTION("no_action") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.no_action();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE NO ACTION");
}
SECTION("restrict_") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.restrict_();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE RESTRICT");
}
SECTION("set_null") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.set_null();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE SET NULL");
}
SECTION("set_default") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.set_default();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE SET DEFAULT");
}
SECTION("cascade") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.cascade();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE");
}
}
}
SECTION("one to explicit one") {
struct Object {
int id = 0;
};
struct User : Object {
std::string name;
User(decltype(id) id_, decltype(name) name_) : Object{id_}, name(move(name_)) {}
};
struct Token : Object {
std::string token;
int usedId = 0;
Token(decltype(id) id_, decltype(token) token_, decltype(usedId) usedId_) :
Object{id_}, token(std::move(token_)), usedId(usedId_) {}
};
auto fk = foreign_key(&Token::usedId).references(column<User>(&User::id));
auto usersTable =
make_table<User>("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name));
auto tokensTable = make_table<Token>("tokens",
make_column("id", &Token::id, primary_key()),
make_column("token", &Token::token),
make_column("user_id", &Token::usedId),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(tokensTable)>;
storage_impl_t storageImpl{usersTable, tokensTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id) REFERENCES users(id)");
}
SECTION("composite key") {
struct User {
int id = 0;
std::string firstName;
std::string lastName;
};
struct UserVisit {
int userId = 0;
std::string userFirstName;
time_t time = 0;
};
auto fk = foreign_key(&UserVisit::userId, &UserVisit::userFirstName).references(&User::id, &User::firstName);
auto usersTable = make_table("users",
make_column("id", &User::id),
make_column("first_name", &User::firstName),
make_column("last_name", &User::lastName),
primary_key(&User::id, &User::firstName));
auto visitsTable = make_table("visits",
make_column("user_id", &UserVisit::userId),
make_column("user_first_name", &UserVisit::userFirstName),
make_column("time", &UserVisit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY(user_id, user_first_name) REFERENCES users(id, first_name)");
}
}
#endif // SQLITE_VERSION_NUMBER
<commit_msg>update tests<commit_after>#include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
using namespace sqlite_orm;
#if SQLITE_VERSION_NUMBER >= 3006019
TEST_CASE("statement_serializator foreign key") {
SECTION("one to one") {
struct User {
int id = 0;
std::string name;
};
struct Visit {
int id = 0;
decltype(User::id) userId;
long time = 0;
};
auto usersTable = make_table("users",
make_column("id", &User::id, primary_key(), autoincrement()),
make_column("name", &User::name));
SECTION("simple") {
auto fk = foreign_key(&Visit::userId).references(&User::id);
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id')");
}
SECTION("on update") {
SECTION("no_action") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.no_action();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON UPDATE NO ACTION");
}
SECTION("restrict_") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.restrict_();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON UPDATE RESTRICT");
}
SECTION("set_null") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.set_null();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON UPDATE SET NULL");
}
SECTION("set_default") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.set_default();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON UPDATE SET DEFAULT");
}
SECTION("cascade") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_update.cascade();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON UPDATE CASCADE");
}
}
SECTION("on delete") {
SECTION("no_action") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.no_action();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON DELETE NO ACTION");
}
SECTION("restrict_") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.restrict_();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON DELETE RESTRICT");
}
SECTION("set_null") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.set_null();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON DELETE SET NULL");
}
SECTION("set_default") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.set_default();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON DELETE SET DEFAULT");
}
SECTION("cascade") {
auto fk = foreign_key(&Visit::userId).references(&User::id).on_delete.cascade();
auto visitsTable = make_table("visits",
make_column("id", &Visit::id, primary_key(), autoincrement()),
make_column("user_id", &Visit::userId),
make_column("time", &Visit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id') ON DELETE CASCADE");
}
}
}
SECTION("one to explicit one") {
struct Object {
int id = 0;
};
struct User : Object {
std::string name;
User(decltype(id) id_, decltype(name) name_) : Object{id_}, name(move(name_)) {}
};
struct Token : Object {
std::string token;
int usedId = 0;
Token(decltype(id) id_, decltype(token) token_, decltype(usedId) usedId_) :
Object{id_}, token(std::move(token_)), usedId(usedId_) {}
};
auto fk = foreign_key(&Token::usedId).references(column<User>(&User::id));
auto usersTable =
make_table<User>("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name));
auto tokensTable = make_table<Token>("tokens",
make_column("id", &Token::id, primary_key()),
make_column("token", &Token::token),
make_column("user_id", &Token::usedId),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(tokensTable)>;
storage_impl_t storageImpl{usersTable, tokensTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id') REFERENCES users('id')");
}
SECTION("composite key") {
struct User {
int id = 0;
std::string firstName;
std::string lastName;
};
struct UserVisit {
int userId = 0;
std::string userFirstName;
time_t time = 0;
};
auto fk = foreign_key(&UserVisit::userId, &UserVisit::userFirstName).references(&User::id, &User::firstName);
auto usersTable = make_table("users",
make_column("id", &User::id),
make_column("first_name", &User::firstName),
make_column("last_name", &User::lastName),
primary_key(&User::id, &User::firstName));
auto visitsTable = make_table("visits",
make_column("user_id", &UserVisit::userId),
make_column("user_first_name", &UserVisit::userFirstName),
make_column("time", &UserVisit::time),
fk);
using storage_impl_t = internal::storage_impl<decltype(usersTable), decltype(visitsTable)>;
storage_impl_t storageImpl{usersTable, visitsTable};
using context_t = internal::serializator_context<storage_impl_t>;
context_t context{storageImpl};
auto value = serialize(fk, context);
REQUIRE(value == "FOREIGN KEY('user_id', 'user_first_name') REFERENCES users('id', 'first_name')");
}
}
#endif // SQLITE_VERSION_NUMBER
<|endoftext|> |
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP
#define INCLUDE_AL_GRAPHICS_MESH_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
A generic mesh object for vertex-based geometry
File author(s):
Wesley Smith, 2010, wesley.hoke@gmail.com
Lance Putnam, 2010, putnam.lance@gmail.com
Graham Wakefield, 2010, grrrwaaa@gmail.com
*/
#include "allocore/math/al_Vec.hpp"
#include "allocore/math/al_Matrix4.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Color.hpp"
namespace al{
/// Stores buffers related to rendering graphical objects
/// A mesh is a collection of buffers storing vertices, colors, indices, etc.
/// that define the geometry and coloring/shading of a graphical object.
class Mesh {
public:
typedef Vec3f Vertex;
typedef Vec3f Normal;
//typedef Vec4f Color;
typedef Vec2f TexCoord2;
typedef Vec3f TexCoord3;
typedef unsigned int Index;
typedef Vec3i TriFace;
typedef Vec4i QuadFace;
/// @param[in] primitive renderer-dependent primitive number
Mesh(int primitive=0): mPrimitive(primitive){}
Mesh(const Mesh& cpy) :
mVertices(cpy.mVertices),
mNormals(cpy.mNormals),
mColors(cpy.mColors),
mColoris(cpy.mColoris),
mTexCoord2s(cpy.mTexCoord2s),
mTexCoord3s(cpy.mTexCoord3s),
mIndices(cpy.mIndices),
mPrimitive(cpy.mPrimitive)
{}
/// Get corners of bounding box of vertices
/// @param[out] min minimum corner of bounding box
/// @param[out] max maximum corner of bounding box
void getBounds(Vec3f& min, Vec3f& max) const;
/// Get center of vertices
Vertex getCenter() const;
// destructive edits to internal vertices:
/// Convert indices (if any) to flat vertex buffers
void decompress();
/// Extend buffers to match number of vertices
/// This will resize all populated buffers to match the size of the vertex
/// buffer. Buffers are extended by copying their last element.
void equalizeBuffers();
/// Append buffers from another mesh:
void merge(const Mesh& src);
/// Reset all buffers
Mesh& reset();
/// Scale all vertices to lie in [-1,1]
void unitize(bool proportional=true);
/// Scale all vertices
Mesh& scale(float x, float y, float z);
Mesh& scale(float s){ return scale(s,s,s); }
template <class T>
Mesh& scale(const Vec<3,T>& v){ return scale(v[0],v[1],v[2]); }
/// Translate all vertices
Mesh& translate(float x, float y, float z);
template <class T>
Mesh& translate(const Vec<3,T>& v){ return translate(v[0],v[1],v[2]); }
/// Transform vertices by projective transform matrix
/// @param[in] m projective transform matrix
/// @param[in] begin beginning index of vertices
/// @param[in] end ending index of vertices, negative amount specify distance from one past last element
template <class T>
Mesh& transform(const Mat<4,T>& m, int begin=0, int end=-1);
/// Generates indices for a set of vertices
void compress();
/// Generates normals for a set of vertices
/// This method will generate a normal for each vertex in the buffer
/// assuming the drawing primitive is a triangle. Face normals are generated
/// if no indices are present, and averaged vertex normals are generated
/// if indices are present. This will replace any normals currently in use.
///
/// @param[in] normalize whether to normalize normals
void generateNormals(bool normalize=true, bool equalWeightPerFace=false);
void invertNormals();
/// Creates a mesh filled with lines for each normal of the source
/// @param[out] mesh normal lines
/// @param[in] length length of normals
/// @param[in] perFace whether normals line should be generated per
/// face rather than per vertex
void createNormalsMesh(Mesh& mesh, float length=0.1, bool perFace=false);
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] width Width of ribbon
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float width=0.04, bool faceBinormal=false){
ribbonize(&width, 0, faceBinormal);
}
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] widths Array specifying width of ribbon at each point along curve
/// @param[in] widthsStride Stride factor of width array
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float * widths, int widthsStride=1, bool faceBinormal=false);
int primitive() const { return mPrimitive; }
const Buffer<Vertex>& vertices() const { return mVertices; }
const Buffer<Normal>& normals() const { return mNormals; }
const Buffer<Color>& colors() const { return mColors; }
const Buffer<Colori>& coloris() const { return mColoris; }
const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }
const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }
const Buffer<Index>& indices() const { return mIndices; }
/// Set geometric primitive
Mesh& primitive(int prim){ mPrimitive=prim; return *this; }
/// Repeat last vertex element(s)
Mesh& repeatLast();
/// Append index to index buffer
void index(unsigned int i){ indices().append(i); }
/// Append indices to index buffer
template <class Tindex>
void index(const Tindex * buf, int size, Tindex indexOffset=0){
for(int i=0; i<size; ++i) index((Index)(buf[i] + indexOffset)); }
/// Append color to color buffer
void color(const Color& v) { colors().append(v); }
/// Append color to color buffer
void color(const Colori& v) { coloris().append(v); }
/// Append color to color buffer
void color(const HSV& v) { colors().append(v); }
/// Append color to color buffer
void color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }
/// Append color to color buffer
template <class T>
void color(const Vec<4,T>& v) { color(v[0], v[1], v[2], v[3]); }
/// Append floating-point color to integer color buffer
void colori(const Color& v) { coloris().append(Colori(v)); }
/// Append normal to normal buffer
void normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }
/// Append normal to normal buffer
void normal(const Normal& v) { normals().append(v); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(float u, float v){ texCoord(TexCoord2(u,v)); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(const TexCoord2& v){ texCoord2s().append(v); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(float u, float v, float w){ texCoord(TexCoord3(u,v,w)); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(const TexCoord3& v){ texCoord3s().append(v); }
/// Append vertex to vertex buffer
void vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }
/// Append vertex to vertex buffer
void vertex(const Vertex& v){ vertices().append(v); }
/// Append vertices to vertex buffer
template <class T>
void vertex(const T * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);
}
/// Append vertices to vertex buffer
template <class T>
void vertex(const Vec<3,T> * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);
}
/// Get number of faces (assumes triangles or quads)
// int numFaces() const { return mIndices.size() / ( ( mPrimitive == Graphics::TRIANGLES ) ? 3 : 4 ); }
/// Get indices as triangles
// TriFace& indexAsTri(){ return (TriFace*) indices(); }
/// Get indices as quads
// QuadFace& indexAsQuad(){ return (QuadFace*) indices(); }
Buffer<Vertex>& vertices(){ return mVertices; }
Buffer<Normal>& normals(){ return mNormals; }
Buffer<Color>& colors(){ return mColors; }
Buffer<Colori>& coloris(){ return mColoris; }
Buffer<TexCoord2>& texCoord2s(){ return mTexCoord2s; }
Buffer<TexCoord3>& texCoord3s(){ return mTexCoord3s; }
Buffer<Index>& indices(){ return mIndices; }
protected:
// Only populated (size>0) buffers will be used
Buffer<Vertex> mVertices;
Buffer<Normal> mNormals;
Buffer<Color> mColors;
Buffer<Colori> mColoris;
Buffer<TexCoord2> mTexCoord2s;
Buffer<TexCoord3> mTexCoord3s;
Buffer<Index> mIndices;
int mPrimitive;
};
template <class T>
Mesh& Mesh::transform(const Mat<4,T>& m, int begin, int end){
if(end<0) end += vertices().size()+1; // negative index wraps to end of array
for(int i=begin; i<end; ++i){
Vertex& v = vertices()[i];
v.set(m * Vec<4,T>(v, 1));
}
return *this;
}
} // al::
#endif
<commit_msg>typedef Buffers<commit_after>#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP
#define INCLUDE_AL_GRAPHICS_MESH_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
A generic mesh object for vertex-based geometry
File author(s):
Wesley Smith, 2010, wesley.hoke@gmail.com
Lance Putnam, 2010, putnam.lance@gmail.com
Graham Wakefield, 2010, grrrwaaa@gmail.com
*/
#include "allocore/math/al_Vec.hpp"
#include "allocore/math/al_Matrix4.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Color.hpp"
namespace al{
/// Stores buffers related to rendering graphical objects
/// A mesh is a collection of buffers storing vertices, colors, indices, etc.
/// that define the geometry and coloring/shading of a graphical object.
class Mesh {
public:
typedef Vec3f Vertex;
typedef Vec3f Normal;
//typedef Vec4f Color;
typedef Vec2f TexCoord2;
typedef Vec3f TexCoord3;
typedef unsigned int Index;
typedef Vec3i TriFace;
typedef Vec4i QuadFace;
typedef Buffer<Vertex> Vertices;
typedef Buffer<Normal> Normals;
typedef Buffer<Color> Colors;
typedef Buffer<Colori> Coloris;
typedef Buffer<TexCoord2> TexCoord2s;
typedef Buffer<TexCoord3> TexCoord3s;
typedef Buffer<Index> Indices;
/// @param[in] primitive renderer-dependent primitive number
Mesh(int primitive=0): mPrimitive(primitive){}
Mesh(const Mesh& cpy) :
mVertices(cpy.mVertices),
mNormals(cpy.mNormals),
mColors(cpy.mColors),
mColoris(cpy.mColoris),
mTexCoord2s(cpy.mTexCoord2s),
mTexCoord3s(cpy.mTexCoord3s),
mIndices(cpy.mIndices),
mPrimitive(cpy.mPrimitive)
{}
/// Get corners of bounding box of vertices
/// @param[out] min minimum corner of bounding box
/// @param[out] max maximum corner of bounding box
void getBounds(Vec3f& min, Vec3f& max) const;
/// Get center of vertices
Vertex getCenter() const;
// destructive edits to internal vertices:
/// Convert indices (if any) to flat vertex buffers
void decompress();
/// Extend buffers to match number of vertices
/// This will resize all populated buffers to match the size of the vertex
/// buffer. Buffers are extended by copying their last element.
void equalizeBuffers();
/// Append buffers from another mesh:
void merge(const Mesh& src);
/// Reset all buffers
Mesh& reset();
/// Scale all vertices to lie in [-1,1]
void unitize(bool proportional=true);
/// Scale all vertices
Mesh& scale(float x, float y, float z);
Mesh& scale(float s){ return scale(s,s,s); }
template <class T>
Mesh& scale(const Vec<3,T>& v){ return scale(v[0],v[1],v[2]); }
/// Translate all vertices
Mesh& translate(float x, float y, float z);
template <class T>
Mesh& translate(const Vec<3,T>& v){ return translate(v[0],v[1],v[2]); }
/// Transform vertices by projective transform matrix
/// @param[in] m projective transform matrix
/// @param[in] begin beginning index of vertices
/// @param[in] end ending index of vertices, negative amount specify distance from one past last element
template <class T>
Mesh& transform(const Mat<4,T>& m, int begin=0, int end=-1);
/// Generates indices for a set of vertices
void compress();
/// Generates normals for a set of vertices
/// This method will generate a normal for each vertex in the buffer
/// assuming the drawing primitive is a triangle. Face normals are generated
/// if no indices are present, and averaged vertex normals are generated
/// if indices are present. This will replace any normals currently in use.
///
/// @param[in] normalize whether to normalize normals
void generateNormals(bool normalize=true, bool equalWeightPerFace=false);
/// Invert direction of normals
void invertNormals();
/// Creates a mesh filled with lines for each normal of the source
/// @param[out] mesh normal lines
/// @param[in] length length of normals
/// @param[in] perFace whether normals line should be generated per
/// face rather than per vertex
void createNormalsMesh(Mesh& mesh, float length=0.1, bool perFace=false);
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] width Width of ribbon
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float width=0.04, bool faceBinormal=false){
ribbonize(&width, 0, faceBinormal);
}
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] widths Array specifying width of ribbon at each point along curve
/// @param[in] widthsStride Stride factor of width array
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float * widths, int widthsStride=1, bool faceBinormal=false);
int primitive() const { return mPrimitive; }
const Buffer<Vertex>& vertices() const { return mVertices; }
const Buffer<Normal>& normals() const { return mNormals; }
const Buffer<Color>& colors() const { return mColors; }
const Buffer<Colori>& coloris() const { return mColoris; }
const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }
const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }
const Buffer<Index>& indices() const { return mIndices; }
/// Set geometric primitive
Mesh& primitive(int prim){ mPrimitive=prim; return *this; }
/// Repeat last vertex element(s)
Mesh& repeatLast();
/// Append index to index buffer
void index(unsigned int i){ indices().append(i); }
/// Append indices to index buffer
template <class Tindex>
void index(const Tindex * buf, int size, Tindex indexOffset=0){
for(int i=0; i<size; ++i) index((Index)(buf[i] + indexOffset)); }
/// Append color to color buffer
void color(const Color& v) { colors().append(v); }
/// Append color to color buffer
void color(const Colori& v) { coloris().append(v); }
/// Append color to color buffer
void color(const HSV& v) { colors().append(v); }
/// Append color to color buffer
void color(const RGB& v) { colors().append(v); }
/// Append color to color buffer
void color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }
/// Append color to color buffer
template <class T>
void color(const Vec<4,T>& v) { color(v[0], v[1], v[2], v[3]); }
/// Append floating-point color to integer color buffer
void colori(const Color& v) { coloris().append(Colori(v)); }
/// Append normal to normal buffer
void normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }
/// Append normal to normal buffer
void normal(const Normal& v) { normals().append(v); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(float u, float v){ texCoord(TexCoord2(u,v)); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(const TexCoord2& v){ texCoord2s().append(v); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(float u, float v, float w){ texCoord(TexCoord3(u,v,w)); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(const TexCoord3& v){ texCoord3s().append(v); }
/// Append vertex to vertex buffer
void vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }
/// Append vertex to vertex buffer
void vertex(const Vertex& v){ vertices().append(v); }
/// Append vertices to vertex buffer
template <class T>
void vertex(const T * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);
}
/// Append vertices to vertex buffer
template <class T>
void vertex(const Vec<3,T> * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);
}
/// Get number of faces (assumes triangles or quads)
// int numFaces() const { return mIndices.size() / ( ( mPrimitive == Graphics::TRIANGLES ) ? 3 : 4 ); }
/// Get indices as triangles
// TriFace& indexAsTri(){ return (TriFace*) indices(); }
/// Get indices as quads
// QuadFace& indexAsQuad(){ return (QuadFace*) indices(); }
Vertices& vertices(){ return mVertices; }
Normals& normals(){ return mNormals; }
Colors& colors(){ return mColors; }
Coloris& coloris(){ return mColoris; }
TexCoord2s& texCoord2s(){ return mTexCoord2s; }
TexCoord3s& texCoord3s(){ return mTexCoord3s; }
Indices& indices(){ return mIndices; }
protected:
// Only populated (size>0) buffers will be used
Vertices mVertices;
Normals mNormals;
Colors mColors;
Coloris mColoris;
TexCoord2s mTexCoord2s;
TexCoord3s mTexCoord3s;
Indices mIndices;
int mPrimitive;
};
template <class T>
Mesh& Mesh::transform(const Mat<4,T>& m, int begin, int end){
if(end<0) end += vertices().size()+1; // negative index wraps to end of array
for(int i=begin; i<end; ++i){
Vertex& v = vertices()[i];
v.set(m * Vec<4,T>(v, 1));
}
return *this;
}
} // al::
#endif
<|endoftext|> |
<commit_before>#include "model_view_animation.hpp"
namespace df
{
ModelViewAnimation::ModelViewAnimation(m2::AnyRectD const & startRect, m2::AnyRectD const & endRect,
double aDuration, double mDuration, double sDuration)
: BaseInterpolator(max(max(aDuration, mDuration), sDuration))
, m_angleInterpolator(startRect.Angle().val(), endRect.Angle().val())
, m_startZero(startRect.GlobalZero())
, m_endZero(endRect.GlobalZero())
, m_startRect(startRect.GetLocalRect())
, m_endRect(endRect.GetLocalRect())
, m_angleDuration(aDuration)
, m_moveDuration(mDuration)
, m_scaleDuration(sDuration)
{
}
m2::AnyRectD ModelViewAnimation::GetCurrentRect() const
{
return GetRect(GetElapsedTime());
}
m2::AnyRectD ModelViewAnimation::GetTargetRect() const
{
return GetRect(GetDuration());
}
namespace
{
double GetSafeT(double elapsed, double duration)
{
if (my::AlmostEqualAbs(duration, 0.0, 1e-5))
return 0.0;
return elapsed / duration;
}
} // namespace
m2::AnyRectD ModelViewAnimation::GetRect(double elapsedTime) const
{
double const angleElapsed = min(elapsedTime, m_angleDuration);
double const moveElapsed = min(elapsedTime, m_moveDuration);
double const scaleElapsed = min(elapsedTime, m_scaleDuration);
double dstAngle = m_angleInterpolator.Interpolate(GetSafeT(angleElapsed, m_angleDuration));
m2::PointD dstZero = InterpolatePoint(m_startZero, m_endZero, GetSafeT(moveElapsed, m_moveDuration));
m2::RectD dstRect = InterpolateRect(m_startRect, m_endRect, GetSafeT(scaleElapsed, m_scaleDuration));
return m2::AnyRectD(dstZero, dstAngle, dstRect);
}
double ModelViewAnimation::GetRotateDuration(double startAngle, double endAngle)
{
return 0.5 * fabs(ang::GetShortestDistance(startAngle, endAngle)) / math::pi;
}
namespace
{
double CalcAnimSpeedDuration(double pxDiff, double pxSpeed)
{
if (my::AlmostEqualAbs(pxDiff, 0.0, 1e-5))
return 0.0;
return fabs(pxDiff) / pxSpeed;
}
}
double ModelViewAnimation::GetMoveDuration(m2::PointD const & startPt, m2::PointD const & endPt, ScreenBase const & convertor)
{
m2::RectD const & dispPxRect = convertor.PixelRect();
double pixelLength = convertor.GtoP(endPt).Length(convertor.GtoP(startPt));
if (pixelLength < 0.2 * min(dispPxRect.SizeX(), dispPxRect.SizeY()))
return 0.2;
double const pixelSpeed = 1.5 * min(dispPxRect.SizeX(), dispPxRect.SizeY());
return CalcAnimSpeedDuration(pixelLength, pixelSpeed);
}
double ModelViewAnimation::GetScaleDuration(double startSize, double endSize)
{
if (startSize > endSize)
swap(startSize, endSize);
double const SCALE_FACTOR = 2.0;
double const ONE_DIV_SCALE_TIME = 2.0;
static double const pixelSpeed = ONE_DIV_SCALE_TIME * SCALE_FACTOR;
return CalcAnimSpeedDuration(endSize / startSize, pixelSpeed);
}
} // namespace df
<commit_msg>review fixes<commit_after>#include "model_view_animation.hpp"
namespace df
{
ModelViewAnimation::ModelViewAnimation(m2::AnyRectD const & startRect, m2::AnyRectD const & endRect,
double aDuration, double mDuration, double sDuration)
: BaseInterpolator(max(max(aDuration, mDuration), sDuration))
, m_angleInterpolator(startRect.Angle().val(), endRect.Angle().val())
, m_startZero(startRect.GlobalZero())
, m_endZero(endRect.GlobalZero())
, m_startRect(startRect.GetLocalRect())
, m_endRect(endRect.GetLocalRect())
, m_angleDuration(aDuration)
, m_moveDuration(mDuration)
, m_scaleDuration(sDuration)
{
}
m2::AnyRectD ModelViewAnimation::GetCurrentRect() const
{
return GetRect(GetElapsedTime());
}
m2::AnyRectD ModelViewAnimation::GetTargetRect() const
{
return GetRect(GetDuration());
}
namespace
{
double GetSafeT(double elapsed, double duration)
{
if (duration <= 0.0 || elapsed > duration)
return 1.0;
return elapsed / duration;
}
} // namespace
m2::AnyRectD ModelViewAnimation::GetRect(double elapsedTime) const
{
double dstAngle = m_angleInterpolator.Interpolate(GetSafeT(elapsedTime, m_angleDuration));
m2::PointD dstZero = InterpolatePoint(m_startZero, m_endZero, GetSafeT(elapsedTime, m_moveDuration));
m2::RectD dstRect = InterpolateRect(m_startRect, m_endRect, GetSafeT(elapsedTime, m_scaleDuration));
return m2::AnyRectD(dstZero, dstAngle, dstRect);
}
double ModelViewAnimation::GetRotateDuration(double startAngle, double endAngle)
{
return 0.5 * fabs(ang::GetShortestDistance(startAngle, endAngle)) / math::pi;
}
namespace
{
double CalcAnimSpeedDuration(double pxDiff, double pxSpeed)
{
if (my::AlmostEqualAbs(pxDiff, 0.0, 1e-5))
return 0.0;
return fabs(pxDiff) / pxSpeed;
}
}
double ModelViewAnimation::GetMoveDuration(m2::PointD const & startPt, m2::PointD const & endPt, ScreenBase const & convertor)
{
m2::RectD const & dispPxRect = convertor.PixelRect();
double pixelLength = convertor.GtoP(endPt).Length(convertor.GtoP(startPt));
if (pixelLength < 0.2 * min(dispPxRect.SizeX(), dispPxRect.SizeY()))
return 0.2;
double const pixelSpeed = 1.5 * min(dispPxRect.SizeX(), dispPxRect.SizeY());
return CalcAnimSpeedDuration(pixelLength, pixelSpeed);
}
double ModelViewAnimation::GetScaleDuration(double startSize, double endSize)
{
if (startSize > endSize)
swap(startSize, endSize);
// Resize 2.0 times should be done for 0.5 seconds.
static double const pixelSpeed = 2.0 / 0.5;
return CalcAnimSpeedDuration(endSize / startSize, pixelSpeed);
}
} // namespace df
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <memory>
#include <ncurses.h>
#include <optional>
#include <unistd.h>
#include <variant>
#include <vector>
// Not a header file.... Mostly just lazy. The ncurses stuff is not
// namespaced either, so it is not very clean anyway.
using namespace std;
/* todo/thoughts for improvement:
Make a nice clock somehow. maybe just figlet.
prettifying box?
*/
// RAII driven NCurses init and exit
class CursesWrap {
private:
int maxx, maxy;
public:
CursesWrap() {
initscr();
raw();
keypad(stdscr, TRUE);
curs_set(0);
noecho();
timeout(100);
Update();
}
~CursesWrap() {
noraw();
echo();
endwin();
}
void Update() { getmaxyx(stdscr, maxy, maxx); }
pair<int, int> GetBounds() { return {maxx, maxy}; }
};
enum class Style { CenterEachLine, LeftAdjust };
// https://stackoverflow.com/a/478960
string Exec(char const *cmd) {
array<char, 128> buffer;
string result;
shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
bool EndsWith(std::string const &str, std::string const &ending) {
if (ending.size() > str.size()) {
return false;
}
return equal(ending.rbegin(), ending.rend(), str.rbegin());
}
class Command {
public:
bool active = true;
char toggle_key = 0;
string command_string;
Style style;
optional<string> MaybeExec() {
if (!active) {
return {};
}
auto combined_string = command_string + " 2>&1";
auto output = Exec(combined_string.c_str());
if (EndsWith(output, "command not found\n")) {
return {};
}
return output;
}
Command(string command_string_, Style style_, char toggle_key_ = 0)
: command_string(command_string_), style(style_) {
if (toggle_key_ != 0) {
active = false;
toggle_key = toggle_key_;
}
}
};
class State {
public:
bool should_exit = false;
vector<Command> commands;
};
size_t LongestLine(string const &str) {
size_t res = 0, cur = 0;
auto it = str.cbegin(), end = str.cend();
while (it != end) {
if (*it == '\n') {
res = cur > res ? cur : res;
cur = 0;
} else {
++cur;
}
++it;
}
return res;
}
// Prints the entire str (which may be multiline), such that each new
// line still starts on column startx. Returns the number of the next
// empty line. The meaning of x depends on the style.
int PrintBuf(int starty, int midx, string const &str, Style stl) {
auto *start = str.c_str(), *end = str.c_str() + str.size(),
*line_start = start, *line_end = start;
size_t longest_line;
if (stl == Style::LeftAdjust) {
longest_line = LongestLine(str);
}
while (line_start != end) {
line_end = find(line_start, end, '\n');
int startx;
switch (stl) {
case Style::CenterEachLine:
startx = midx - (line_end - line_start) / 2;
break;
case Style::LeftAdjust:
startx = midx - longest_line / 2;
break;
}
if (startx < 0) {
startx = 0;
}
mvaddnstr(starty, startx, line_start, line_end - line_start);
++starty;
line_start = line_end + 1;
}
return starty;
}
int GetKeyOrWait() {
int c = getch();
switch (c) {
case ERR:
return 0;
default:
return c;
}
}
constexpr char Ctrl(char c) { return c & 31; }
void ActOnKey(State *state, int key) {
switch (key) {
case 'q':
case Ctrl('c'):
state->should_exit = true;
return;
case 'x':
clear();
return;
}
for (auto &c : state->commands) {
if (c.toggle_key && c.toggle_key == key) {
c.active = !c.active;
return;
}
}
}
int main() {
CursesWrap curses;
State state;
state.commands.emplace_back("toilet `date '+%T'`", Style::LeftAdjust, 'c');
state.commands.emplace_back("date '+%T%n%F'", Style::CenterEachLine);
state.commands.emplace_back("acpi", Style::CenterEachLine);
state.commands.emplace_back("ip a", Style::LeftAdjust, 'i');
state.commands.emplace_back("wpa_cli -i wlp4s0 status",
Style::LeftAdjust, 'w');
while (!state.should_exit) {
curses.Update();
auto [maxx, maxy] = curses.GetBounds();
vector<optional<string>> output;
erase();
for (auto &c : state.commands) {
auto out = c.MaybeExec();
output.push_back(out);
}
size_t num_lines = 0;
for (auto const &c : output) {
if (c) {
num_lines += count(c->cbegin(), c->cend(), '\n') + 2;
}
}
int y = maxy / 2 - num_lines / 2;
for (int i = 0; i < state.commands.size(); ++i) {
if (output[i]) {
y = PrintBuf(y, maxx / 2, *output[i], state.commands[i].style) + 1;
}
}
refresh();
int key = GetKeyOrWait();
if (key) {
ActOnKey(&state, key);
}
}
}
<commit_msg>Seems like clearing helps with an intermittent drawing error<commit_after>#include <algorithm>
#include <iostream>
#include <memory>
#include <ncurses.h>
#include <optional>
#include <unistd.h>
#include <variant>
#include <vector>
// Not a header file.... Mostly just lazy. The ncurses stuff is not
// namespaced either, so it is not very clean anyway.
using namespace std;
/* todo/thoughts for improvement:
Make a nice clock somehow. maybe just figlet.
prettifying box?
*/
// RAII driven NCurses init and exit
class CursesWrap {
private:
int maxx, maxy;
public:
CursesWrap() {
initscr();
raw();
keypad(stdscr, TRUE);
curs_set(0);
noecho();
timeout(100);
Update();
clear();
}
~CursesWrap() {
noraw();
echo();
endwin();
}
void Update() { getmaxyx(stdscr, maxy, maxx); }
pair<int, int> GetBounds() { return {maxx, maxy}; }
};
enum class Style { CenterEachLine, LeftAdjust };
// https://stackoverflow.com/a/478960
string Exec(char const *cmd) {
array<char, 128> buffer;
string result;
shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
bool EndsWith(std::string const &str, std::string const &ending) {
if (ending.size() > str.size()) {
return false;
}
return equal(ending.rbegin(), ending.rend(), str.rbegin());
}
class Command {
public:
bool active = true;
char toggle_key = 0;
string command_string;
Style style;
optional<string> MaybeExec() {
if (!active) {
return {};
}
auto combined_string = command_string + " 2>&1";
auto output = Exec(combined_string.c_str());
if (EndsWith(output, "command not found\n")) {
return {};
}
return output;
}
Command(string command_string_, Style style_, char toggle_key_ = 0)
: command_string(command_string_), style(style_) {
if (toggle_key_ != 0) {
active = false;
toggle_key = toggle_key_;
}
}
};
class State {
public:
bool should_exit = false;
vector<Command> commands;
};
size_t LongestLine(string const &str) {
size_t res = 0, cur = 0;
auto it = str.cbegin(), end = str.cend();
while (it != end) {
if (*it == '\n') {
res = cur > res ? cur : res;
cur = 0;
} else {
++cur;
}
++it;
}
return res;
}
// Prints the entire str (which may be multiline), such that each new
// line still starts on column startx. Returns the number of the next
// empty line. The meaning of x depends on the style.
int PrintBuf(int starty, int midx, string const &str, Style stl) {
auto *start = str.c_str(), *end = str.c_str() + str.size(),
*line_start = start, *line_end = start;
size_t longest_line;
if (stl == Style::LeftAdjust) {
longest_line = LongestLine(str);
}
while (line_start != end) {
line_end = find(line_start, end, '\n');
int startx;
switch (stl) {
case Style::CenterEachLine:
startx = midx - (line_end - line_start) / 2;
break;
case Style::LeftAdjust:
startx = midx - longest_line / 2;
break;
}
if (startx < 0) {
startx = 0;
}
mvaddnstr(starty, startx, line_start, line_end - line_start);
++starty;
line_start = line_end + 1;
}
return starty;
}
int GetKeyOrWait() {
int c = getch();
switch (c) {
case ERR:
return 0;
default:
return c;
}
}
constexpr char Ctrl(char c) { return c & 31; }
void ActOnKey(State *state, int key) {
switch (key) {
case 'q':
case Ctrl('c'):
state->should_exit = true;
return;
case 'x':
clear();
return;
}
for (auto &c : state->commands) {
if (c.toggle_key && c.toggle_key == key) {
c.active = !c.active;
return;
}
}
}
int main() {
CursesWrap curses;
State state;
state.commands.emplace_back("toilet `date '+%T'`", Style::LeftAdjust, 'c');
state.commands.emplace_back("date '+%T%n%F'", Style::CenterEachLine);
state.commands.emplace_back("acpi", Style::CenterEachLine);
state.commands.emplace_back("ip a", Style::LeftAdjust, 'i');
state.commands.emplace_back("wpa_cli -i wlp4s0 status",
Style::LeftAdjust, 'w');
while (!state.should_exit) {
curses.Update();
auto [maxx, maxy] = curses.GetBounds();
vector<optional<string>> output;
erase();
for (auto &c : state.commands) {
auto out = c.MaybeExec();
output.push_back(out);
}
size_t num_lines = 0;
for (auto const &c : output) {
if (c) {
num_lines += count(c->cbegin(), c->cend(), '\n') + 2;
}
}
int y = maxy / 2 - num_lines / 2;
for (int i = 0; i < state.commands.size(); ++i) {
if (output[i]) {
y = PrintBuf(y, maxx / 2, *output[i], state.commands[i].style) + 1;
}
}
refresh();
int key = GetKeyOrWait();
if (key) {
ActOnKey(&state, key);
}
}
}
<|endoftext|> |
<commit_before><commit_msg>operate on UTF-8 encoded string, tdf#76870 follow-up<commit_after><|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <ros/callback_queue.h>
#ifndef ROS_HELPERS_HPP
#define ROS_HELPERS_HPP
namespace ROSHelpers
{
inline Spin(const double loop_period)
{
while (ros::ok())
{
ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(loop_period));
}
}
template <typename T>
inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, const T& default_val)
{
T param_val;
if (nh.getParam(param_name, param_val))
{
ROS_INFO_STREAM("Setting " << param_name << " to " << param_val);
}
else
{
param_val = default_val;
ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val);
}
return param_val;
}
template <typename T>
inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, T&& default_val)
{
T param_val;
if (nh.getParam(param_name, param_val))
{
ROS_INFO_STREAM("Setting " << param_name << " to " << param_val);
}
else
{
param_val = default_val;
ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val);
}
return param_val;
}
}
#endif // ROS_HELPERS_HPP
<commit_msg>Added a GetParamRequired that uses a Maybe as a return type.<commit_after>#include <ros/ros.h>
#include <ros/callback_queue.h>
#include "arc_utilities/maybe.hpp"
#ifndef ROS_HELPERS_HPP
#define ROS_HELPERS_HPP
namespace ROSHelpers
{
inline Spin(const double loop_period)
{
while (ros::ok())
{
ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(loop_period));
}
}
template <typename T>
inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, const T& default_val)
{
T param_val;
if (nh.getParam(param_name, param_val))
{
ROS_INFO_STREAM("Setting " << param_name << " to " << param_val);
}
else
{
param_val = default_val;
ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val);
}
return param_val;
}
template <typename T>
inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, T&& default_val)
{
T param_val;
if (nh.getParam(param_name, param_val))
{
ROS_INFO_STREAM("Setting " << param_name << " to " << param_val);
}
else
{
param_val = default_val;
ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val);
}
return param_val;
}
template <typename T>
inline Maybe::Maybe<T> GetParamRequired(ros::NodeHandle& nh, const std::string& param_name, const std::string& calling_fn_name)
{
ROS_ERROR_STREAM("No default value for " << param_name << ": Value must be on paramter sever");
T param_val;
if (nh.getParam(param_name, param_val))
{
ROS_INFO_STREAM("Setting " << param_name << " to " << param_val);
return Maybe::Maybe<T>(param_val);
}
else
{
ROS_FATAL_STREAM("Cannot find " << param_name << " on parameter server for " << calling_fn_name << ": Value must be on paramter sever");
return Maybe::Maybe<T>();
}
}
}
#endif // ROS_HELPERS_HPP
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MVS_CONSTANTS_HPP
#define MVS_CONSTANTS_HPP
#include <cstddef>
#include <cstdint>
#include <bitcoin/bitcoin/compat.hpp>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/message/network_address.hpp>
#include <bitcoin/bitcoin/math/hash_number.hpp>
namespace libbitcoin {
#define BC_USER_AGENT "/metaverse:" MVS_VERSION "/"
// Generic constants.
BC_CONSTEXPR size_t command_size = 12;
BC_CONSTEXPR int64_t min_int64 = MIN_INT64;
BC_CONSTEXPR int64_t max_int64 = MAX_INT64;
BC_CONSTEXPR int32_t min_int32 = MIN_INT32;
BC_CONSTEXPR int32_t max_int32 = MAX_INT32;
BC_CONSTEXPR uint64_t max_uint64 = MAX_UINT64;
BC_CONSTEXPR uint32_t max_uint32 = MAX_UINT32;
BC_CONSTEXPR uint16_t max_uint16 = MAX_UINT16;
BC_CONSTEXPR uint8_t max_uint8 = MAX_UINT8;
BC_CONSTEXPR uint64_t max_size_t = BC_MAX_SIZE;
BC_CONSTEXPR uint8_t byte_bits = 8;
BC_CONSTEXPR uint8_t coinage_reward_lock_block_heigth = 50;
// Consensus constants.
BC_CONSTEXPR uint32_t reward_interval = 210000;
BC_CONSTEXPR uint32_t coinbase_maturity = 1; // todo -- chenhao modify later
BC_CONSTEXPR uint32_t initial_block_reward = 50;
BC_CONSTEXPR uint32_t max_work_bits = 0x1d00ffff;
BC_CONSTEXPR uint32_t max_input_sequence = max_uint32;
BC_CONSTEXPR uint32_t total_reward = 100000000;
BC_CONSTEXPR uint32_t max_reward_block_number = total_reward / initial_block_reward;
// Threshold for nLockTime: below this value it is interpreted as block number,
// otherwise as UNIX timestamp. [Tue Nov 5 00:53:20 1985 UTC]
BC_CONSTEXPR uint32_t locktime_threshold = 500000000;
BC_CONSTFUNC uint64_t max_money_recursive(uint64_t current)
{
return (current > 0) ? current + max_money_recursive(current >> 1) : 0;
}
BC_CONSTFUNC uint64_t coin_price(uint64_t value=1)
{
return value * 100000000;
}
BC_CONSTFUNC uint64_t max_money()
{
return coin_price(total_reward);
}
// For configuration settings initialization.
enum class settings
{
none,
mainnet,
testnet
};
enum services: uint64_t
{
// The node is capable of serving the block chain.
node_network = (1 << 0),
// Requires version >= 70004 (bip64)
// The node is capable of responding to the getutxo protocol request.
node_utxo = (1 << 1),
// Requires version >= 70011 (proposed)
// The node is capable and willing to handle bloom-filtered connections.
bloom_filters = (1 << 2)
};
BC_CONSTEXPR uint32_t no_timestamp = 0;
BC_CONSTEXPR uint16_t unspecified_ip_port = 0;
BC_CONSTEXPR message::ip_address unspecified_ip_address
{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00
}
};
BC_CONSTEXPR message::network_address unspecified_network_address
{
no_timestamp,
services::node_network,
unspecified_ip_address,
unspecified_ip_port
};
// TODO: make static.
BC_API hash_number max_target();
} // namespace libbitcoin
#endif
<commit_msg>modify coinbase_maturity value<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MVS_CONSTANTS_HPP
#define MVS_CONSTANTS_HPP
#include <cstddef>
#include <cstdint>
#include <bitcoin/bitcoin/compat.hpp>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/message/network_address.hpp>
#include <bitcoin/bitcoin/math/hash_number.hpp>
namespace libbitcoin {
#define BC_USER_AGENT "/metaverse:" MVS_VERSION "/"
// Generic constants.
BC_CONSTEXPR size_t command_size = 12;
BC_CONSTEXPR int64_t min_int64 = MIN_INT64;
BC_CONSTEXPR int64_t max_int64 = MAX_INT64;
BC_CONSTEXPR int32_t min_int32 = MIN_INT32;
BC_CONSTEXPR int32_t max_int32 = MAX_INT32;
BC_CONSTEXPR uint64_t max_uint64 = MAX_UINT64;
BC_CONSTEXPR uint32_t max_uint32 = MAX_UINT32;
BC_CONSTEXPR uint16_t max_uint16 = MAX_UINT16;
BC_CONSTEXPR uint8_t max_uint8 = MAX_UINT8;
BC_CONSTEXPR uint64_t max_size_t = BC_MAX_SIZE;
BC_CONSTEXPR uint8_t byte_bits = 8;
// Consensus constants.
BC_CONSTEXPR uint32_t reward_interval = 210000;
BC_CONSTEXPR uint32_t coinbase_maturity = 1000;
BC_CONSTEXPR uint32_t initial_block_reward = 50;
BC_CONSTEXPR uint32_t max_work_bits = 0x1d00ffff;
BC_CONSTEXPR uint32_t max_input_sequence = max_uint32;
BC_CONSTEXPR uint32_t total_reward = 100000000;
// Threshold for nLockTime: below this value it is interpreted as block number,
// otherwise as UNIX timestamp. [Tue Nov 5 00:53:20 1985 UTC]
BC_CONSTEXPR uint32_t locktime_threshold = 500000000;
BC_CONSTFUNC uint64_t max_money_recursive(uint64_t current)
{
return (current > 0) ? current + max_money_recursive(current >> 1) : 0;
}
BC_CONSTFUNC uint64_t coin_price(uint64_t value=1)
{
return value * 100000000;
}
BC_CONSTFUNC uint64_t max_money()
{
return coin_price(total_reward);
}
// For configuration settings initialization.
enum class settings
{
none,
mainnet,
testnet
};
enum services: uint64_t
{
// The node is capable of serving the block chain.
node_network = (1 << 0),
// Requires version >= 70004 (bip64)
// The node is capable of responding to the getutxo protocol request.
node_utxo = (1 << 1),
// Requires version >= 70011 (proposed)
// The node is capable and willing to handle bloom-filtered connections.
bloom_filters = (1 << 2)
};
BC_CONSTEXPR uint32_t no_timestamp = 0;
BC_CONSTEXPR uint16_t unspecified_ip_port = 0;
BC_CONSTEXPR message::ip_address unspecified_ip_address
{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00
}
};
BC_CONSTEXPR message::network_address unspecified_network_address
{
no_timestamp,
services::node_network,
unspecified_ip_address,
unspecified_ip_port
};
// TODO: make static.
BC_API hash_number max_target();
} // namespace libbitcoin
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: excdefs.hxx,v $
*
* $Revision: 1.37 $
*
* last change: $Author: hr $ $Date: 2003-03-26 18:04:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _EXCDEFS_HXX
#define _EXCDEFS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// Supbooks, ExcETabNumBuffer =================================================
#define EXC_TABBUF_INVALID 0xFFFF
// (0x001C) NOTE ==============================================================
#define EXC_NOTE5_MAXTEXT 2048
// (0x0031) FONT ==============================================================
// color
#define EXC_FONTCOL_IGNORE 0x7FFF
// height
#define EXC_FONTHGHT_COEFF 20.0
// (0x005D) OBJ ===============================================================
#define EXC_OBJT_LINE 0x01
#define EXC_OBJT_RECT 0x02
#define EXC_OBJT_ELLIP 0x03
#define EXC_OBJT_ARC 0x04
#define EXC_OBJT_CHART 0x05
#define EXC_OBJT_TEXT 0x06
#define EXC_OBJT_PICT 0x08
#define EXC_OBJT_POLYGON 0x09
#define EXC_OBJT_NOTE 0x19
#define EXC_OBJT_DRAWING 0x1E
// (0x0092) PALETTE ===========================================================
// special color indices
#define EXC_COLIND_AUTOTEXT 77
#define EXC_COLIND_AUTOLINE 77
#define EXC_COLIND_AUTOFILLBG 77
#define EXC_COLIND_AUTOFILLFG 78
// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================
// flags
#define EXC_AFFLAG_AND 0x0000
#define EXC_AFFLAG_OR 0x0001
#define EXC_AFFLAG_ANDORMASK 0x0003
#define EXC_AFFLAG_SIMPLE1 0x0004
#define EXC_AFFLAG_SIMPLE2 0x0008
#define EXC_AFFLAG_TOP10 0x0010
#define EXC_AFFLAG_TOP10TOP 0x0020
#define EXC_AFFLAG_TOP10PERC 0x0040
// data types
#define EXC_AFTYPE_NOTUSED 0x00
#define EXC_AFTYPE_RK 0x02
#define EXC_AFTYPE_DOUBLE 0x04
#define EXC_AFTYPE_STRING 0x06
#define EXC_AFTYPE_BOOLERR 0x08
#define EXC_AFTYPE_INVALID 0x0A
#define EXC_AFTYPE_EMPTY 0x0C
#define EXC_AFTYPE_NOTEMPTY 0x0E
// comparison operands
#define EXC_AFOPER_NONE 0x00
#define EXC_AFOPER_LESS 0x01
#define EXC_AFOPER_EQUAL 0x02
#define EXC_AFOPER_LESSEQUAL 0x03
#define EXC_AFOPER_GREATER 0x04
#define EXC_AFOPER_NOTEQUAL 0x05
#define EXC_AFOPER_GREATEREQUAL 0x06
// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================
#define EXC_SCEN_MAXCELL 32
// (0x00E5) CELLMERGING =======================================================
#define EXC_MERGE_MAXCOUNT 1024
// (0x007D) COLINFO ===========================================================
// flags
#define EXC_COL_HIDDEN 0x0001
#define EXC_COL_COLLAPSED 0x1000
// outline
#define EXC_COL_LEVELFLAGS(nOL) ((nOL & 0x0007) << 8)
#define EXC_COL_GETLEVEL(nFlag) ((nFlag & 0x0700) >> 8)
// (0x0208) ROW ===============================================================
// flags
#define EXC_ROW_COLLAPSED 0x0010
#define EXC_ROW_ZEROHEIGHT 0x0020
#define EXC_ROW_UNSYNCED 0x0040
#define EXC_ROW_GHOSTDIRTY 0x0080
#define EXC_ROW_XFMASK 0x0FFF
// outline
#define EXC_ROW_LEVELFLAGS(nOL) (nOL & 0x0007)
#define EXC_ROW_GETLEVEL(nFlag) (nFlag & 0x0007)
// unknown, always save
#define EXC_ROW_FLAGCOMMON 0x0100
// row height
#define EXC_ROW_VALZEROHEIGHT 0x00FF
#define EXC_ROW_FLAGDEFHEIGHT 0x8000
// (0x0236) TABLE =============================================================
#define EXC_TABOP_CALCULATE 0x0003
#define EXC_TABOP_ROW 0x0004
#define EXC_TABOP_BOTH 0x0008
// (0x023E) WINDOW2 ===========================================================
#define EXC_WIN2_SHOWFORMULAS 0x0001
#define EXC_WIN2_SHOWGRID 0x0002
#define EXC_WIN2_SHOWHEADINGS 0x0004
#define EXC_WIN2_FROZEN 0x0008
#define EXC_WIN2_SHOWZEROS 0x0010
#define EXC_WIN2_DEFAULTCOLOR 0x0020
#define EXC_WIN2_OUTLINE 0x0080
#define EXC_WIN2_FROZENNOSPLIT 0x0100
#define EXC_WIN2_SELECTED 0x0200
#define EXC_WIN2_DISPLAYED 0x0400
// Specials for outlines ======================================================
#define EXC_OUTLINE_MAX 7
#define EXC_OUTLINE_COUNT (EXC_OUTLINE_MAX + 1)
// data pilot / pivot tables ==================================================
// subtotal functions
#define EXC_PIVOT_SUBT_SUM 0x0000
#define EXC_PIVOT_SUBT_COUNT 0x0001
#define EXC_PIVOT_SUBT_AVERAGE 0x0002
#define EXC_PIVOT_SUBT_MAX 0x0003
#define EXC_PIVOT_SUBT_MIN 0x0004
#define EXC_PIVOT_SUBT_PROD 0x0005
#define EXC_PIVOT_SUBT_COUNTNUM 0x0006
#define EXC_PIVOT_SUBT_STDDEV 0x0007
#define EXC_PIVOT_SUBT_STDDEVP 0x0008
#define EXC_PIVOT_SUBT_VAR 0x0009
#define EXC_PIVOT_SUBT_VARP 0x000A
// field orientation
#define EXC_PIVOT_AXIS_NONE 0x0000
#define EXC_PIVOT_AXIS_ROW 0x0001
#define EXC_PIVOT_AXIS_COL 0x0002
#define EXC_PIVOT_AXIS_PAGE 0x0004
#define EXC_PIVOT_AXIS_DATA 0x0008
#define EXC_PIVOT_AXIS_RCP_MASK (EXC_PIVOT_AXIS_ROW|EXC_PIVOT_AXIS_COL|EXC_PIVOT_AXIS_PAGE)
// misc xcl record flags
#define EXC_SXVIEW_COMMON 0x0208
#define EXC_SXVIEW_ROWGRAND 0x0001
#define EXC_SXVIEW_COLGRAND 0x0002
#define EXC_SXVDEX_COMMON 0x0A00141E
#define EXC_SXVDEX_SHOWALL 0x00000001
#define EXC_SXVI_HIDDEN 0x0001
#define EXC_SXVI_HIDEDETAIL 0x0002
#define EXC_SXVI_FORMULA 0x0004
#define EXC_SXVI_MISSING 0x0008
#define EXC_SXVS_EXCEL 0x0001
#define EXC_SXVS_EXTERN 0x0002
#define EXC_SXVS_MULTICONSR 0x0004
#define EXC_SXVS_PIVOTTAB 0x0008
#define EXC_SXVS_SCENMAN 0x0010
#define EXC_SXIVD_IDDATA 0xFFFE
// pivot cache record flags
#define EXC_SXFIELD_COMMON 0x0001
#define EXC_SXFIELD_READLATER 0x0002
#define EXC_SXFIELD_16BIT 0x0200
#define EXC_SXITEM_
// defines for change tracking ================================================
// opcodes
#define EXC_CHTR_OP_COLFLAG 0x0001
#define EXC_CHTR_OP_DELFLAG 0x0002
#define EXC_CHTR_OP_INSROW 0x0000
#define EXC_CHTR_OP_INSCOL EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE 0x0004
#define EXC_CHTR_OP_INSTAB 0x0005
#define EXC_CHTR_OP_CELL 0x0008
#define EXC_CHTR_OP_RENAME 0x0009
#define EXC_CHTR_OP_NAME 0x000A
#define EXC_CHTR_OP_FORMAT 0x000B
#define EXC_CHTR_OP_UNKNOWN 0xFFFF
// data types
#define EXC_CHTR_TYPE_MASK 0x0007
#define EXC_CHTR_TYPE_FORMATMASK 0xFF00
#define EXC_CHTR_TYPE_EMPTY 0x0000
#define EXC_CHTR_TYPE_RK 0x0001
#define EXC_CHTR_TYPE_DOUBLE 0x0002
#define EXC_CHTR_TYPE_STRING 0x0003
#define EXC_CHTR_TYPE_BOOL 0x0004
#define EXC_CHTR_TYPE_FORMULA 0x0005
// accept flags
#define EXC_CHTR_NOTHING 0x0000
#define EXC_CHTR_ACCEPT 0x0001
#define EXC_CHTR_REJECT 0x0003
// ============================================================================
#endif // _EXCDEFS_HXX
<commit_msg>INTEGRATION: CWS apps61beta2 (1.35.4.2.24); FILE MERGED 2003/04/11 11:43:42 dr 1.35.4.2.24.1: #108487# export of column width<commit_after>/*************************************************************************
*
* $RCSfile: excdefs.hxx,v $
*
* $Revision: 1.38 $
*
* last change: $Author: hr $ $Date: 2003-04-28 15:36:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _EXCDEFS_HXX
#define _EXCDEFS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// Supbooks, ExcETabNumBuffer =================================================
#define EXC_TABBUF_INVALID 0xFFFF
// (0x001C) NOTE ==============================================================
#define EXC_NOTE5_MAXTEXT 2048
// (0x0031) FONT ==============================================================
// color
#define EXC_FONTCOL_IGNORE 0x7FFF
// height
#define EXC_FONTHGHT_COEFF 20.0
// (0x005D) OBJ ===============================================================
#define EXC_OBJT_LINE 0x01
#define EXC_OBJT_RECT 0x02
#define EXC_OBJT_ELLIP 0x03
#define EXC_OBJT_ARC 0x04
#define EXC_OBJT_CHART 0x05
#define EXC_OBJT_TEXT 0x06
#define EXC_OBJT_PICT 0x08
#define EXC_OBJT_POLYGON 0x09
#define EXC_OBJT_NOTE 0x19
#define EXC_OBJT_DRAWING 0x1E
// (0x0092) PALETTE ===========================================================
// special color indices
#define EXC_COLIND_AUTOTEXT 77
#define EXC_COLIND_AUTOLINE 77
#define EXC_COLIND_AUTOFILLBG 77
#define EXC_COLIND_AUTOFILLFG 78
// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================
// flags
#define EXC_AFFLAG_AND 0x0000
#define EXC_AFFLAG_OR 0x0001
#define EXC_AFFLAG_ANDORMASK 0x0003
#define EXC_AFFLAG_SIMPLE1 0x0004
#define EXC_AFFLAG_SIMPLE2 0x0008
#define EXC_AFFLAG_TOP10 0x0010
#define EXC_AFFLAG_TOP10TOP 0x0020
#define EXC_AFFLAG_TOP10PERC 0x0040
// data types
#define EXC_AFTYPE_NOTUSED 0x00
#define EXC_AFTYPE_RK 0x02
#define EXC_AFTYPE_DOUBLE 0x04
#define EXC_AFTYPE_STRING 0x06
#define EXC_AFTYPE_BOOLERR 0x08
#define EXC_AFTYPE_INVALID 0x0A
#define EXC_AFTYPE_EMPTY 0x0C
#define EXC_AFTYPE_NOTEMPTY 0x0E
// comparison operands
#define EXC_AFOPER_NONE 0x00
#define EXC_AFOPER_LESS 0x01
#define EXC_AFOPER_EQUAL 0x02
#define EXC_AFOPER_LESSEQUAL 0x03
#define EXC_AFOPER_GREATER 0x04
#define EXC_AFOPER_NOTEQUAL 0x05
#define EXC_AFOPER_GREATEREQUAL 0x06
// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================
#define EXC_SCEN_MAXCELL 32
// (0x00E5) CELLMERGING =======================================================
#define EXC_MERGE_MAXCOUNT 1024
// (0x0208) ROW ===============================================================
// flags
#define EXC_ROW_COLLAPSED 0x0010
#define EXC_ROW_ZEROHEIGHT 0x0020
#define EXC_ROW_UNSYNCED 0x0040
#define EXC_ROW_GHOSTDIRTY 0x0080
#define EXC_ROW_XFMASK 0x0FFF
// outline
#define EXC_ROW_LEVELFLAGS(nOL) (nOL & 0x0007)
#define EXC_ROW_GETLEVEL(nFlag) (nFlag & 0x0007)
// unknown, always save
#define EXC_ROW_FLAGCOMMON 0x0100
// row height
#define EXC_ROW_VALZEROHEIGHT 0x00FF
#define EXC_ROW_FLAGDEFHEIGHT 0x8000
// (0x0236) TABLE =============================================================
#define EXC_TABOP_CALCULATE 0x0003
#define EXC_TABOP_ROW 0x0004
#define EXC_TABOP_BOTH 0x0008
// (0x023E) WINDOW2 ===========================================================
#define EXC_WIN2_SHOWFORMULAS 0x0001
#define EXC_WIN2_SHOWGRID 0x0002
#define EXC_WIN2_SHOWHEADINGS 0x0004
#define EXC_WIN2_FROZEN 0x0008
#define EXC_WIN2_SHOWZEROS 0x0010
#define EXC_WIN2_DEFAULTCOLOR 0x0020
#define EXC_WIN2_OUTLINE 0x0080
#define EXC_WIN2_FROZENNOSPLIT 0x0100
#define EXC_WIN2_SELECTED 0x0200
#define EXC_WIN2_DISPLAYED 0x0400
// Specials for outlines ======================================================
#define EXC_OUTLINE_MAX 7
#define EXC_OUTLINE_COUNT (EXC_OUTLINE_MAX + 1)
// data pilot / pivot tables ==================================================
// subtotal functions
#define EXC_PIVOT_SUBT_SUM 0x0000
#define EXC_PIVOT_SUBT_COUNT 0x0001
#define EXC_PIVOT_SUBT_AVERAGE 0x0002
#define EXC_PIVOT_SUBT_MAX 0x0003
#define EXC_PIVOT_SUBT_MIN 0x0004
#define EXC_PIVOT_SUBT_PROD 0x0005
#define EXC_PIVOT_SUBT_COUNTNUM 0x0006
#define EXC_PIVOT_SUBT_STDDEV 0x0007
#define EXC_PIVOT_SUBT_STDDEVP 0x0008
#define EXC_PIVOT_SUBT_VAR 0x0009
#define EXC_PIVOT_SUBT_VARP 0x000A
// field orientation
#define EXC_PIVOT_AXIS_NONE 0x0000
#define EXC_PIVOT_AXIS_ROW 0x0001
#define EXC_PIVOT_AXIS_COL 0x0002
#define EXC_PIVOT_AXIS_PAGE 0x0004
#define EXC_PIVOT_AXIS_DATA 0x0008
#define EXC_PIVOT_AXIS_RCP_MASK (EXC_PIVOT_AXIS_ROW|EXC_PIVOT_AXIS_COL|EXC_PIVOT_AXIS_PAGE)
// misc xcl record flags
#define EXC_SXVIEW_COMMON 0x0208
#define EXC_SXVIEW_ROWGRAND 0x0001
#define EXC_SXVIEW_COLGRAND 0x0002
#define EXC_SXVDEX_COMMON 0x0A00141E
#define EXC_SXVDEX_SHOWALL 0x00000001
#define EXC_SXVI_HIDDEN 0x0001
#define EXC_SXVI_HIDEDETAIL 0x0002
#define EXC_SXVI_FORMULA 0x0004
#define EXC_SXVI_MISSING 0x0008
#define EXC_SXVS_EXCEL 0x0001
#define EXC_SXVS_EXTERN 0x0002
#define EXC_SXVS_MULTICONSR 0x0004
#define EXC_SXVS_PIVOTTAB 0x0008
#define EXC_SXVS_SCENMAN 0x0010
#define EXC_SXIVD_IDDATA 0xFFFE
// pivot cache record flags
#define EXC_SXFIELD_COMMON 0x0001
#define EXC_SXFIELD_READLATER 0x0002
#define EXC_SXFIELD_16BIT 0x0200
#define EXC_SXITEM_
// defines for change tracking ================================================
// opcodes
#define EXC_CHTR_OP_COLFLAG 0x0001
#define EXC_CHTR_OP_DELFLAG 0x0002
#define EXC_CHTR_OP_INSROW 0x0000
#define EXC_CHTR_OP_INSCOL EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE 0x0004
#define EXC_CHTR_OP_INSTAB 0x0005
#define EXC_CHTR_OP_CELL 0x0008
#define EXC_CHTR_OP_RENAME 0x0009
#define EXC_CHTR_OP_NAME 0x000A
#define EXC_CHTR_OP_FORMAT 0x000B
#define EXC_CHTR_OP_UNKNOWN 0xFFFF
// data types
#define EXC_CHTR_TYPE_MASK 0x0007
#define EXC_CHTR_TYPE_FORMATMASK 0xFF00
#define EXC_CHTR_TYPE_EMPTY 0x0000
#define EXC_CHTR_TYPE_RK 0x0001
#define EXC_CHTR_TYPE_DOUBLE 0x0002
#define EXC_CHTR_TYPE_STRING 0x0003
#define EXC_CHTR_TYPE_BOOL 0x0004
#define EXC_CHTR_TYPE_FORMULA 0x0005
// accept flags
#define EXC_CHTR_NOTHING 0x0000
#define EXC_CHTR_ACCEPT 0x0001
#define EXC_CHTR_REJECT 0x0003
// ============================================================================
#endif // _EXCDEFS_HXX
<|endoftext|> |
<commit_before>#include "tidyup_actions/actionExecutorDetectObjects.h"
#include <pluginlib/class_list_macros.h>
#include <tidyup_msgs/RequestObjectsGraspability.h>
#include "tidyup_utils/planning_scene_interface.h"
PLUGINLIB_DECLARE_CLASS(tidyup_actions, action_executor_detect_objects,
tidyup_actions::ActionExecutorDetectObjects,
continual_planning_executive::ActionExecutorInterface)
namespace tidyup_actions
{
void ActionExecutorDetectObjects::initialize(const std::deque<std::string> & arguments)
{
ActionExecutorService<tidyup_msgs::DetectGraspableObjects>::initialize(arguments);
requestGraspability = false;
string graspabilityServiceName = "/learned_grasping/request_objects_graspability";
tidyLocationName = "table1";
if (arguments.size() >= 3)
{
if (arguments[2] == "NULL")
{
requestGraspability = false;
} else {
graspabilityServiceName = arguments[2];
}
}
if (arguments.size() >= 4)
{
tidyLocationName = arguments[3];
}
ROS_ASSERT(_nh);
if(requestGraspability) {
serviceClientGraspability = _nh->serviceClient<tidyup_msgs::RequestObjectsGraspability>(
graspabilityServiceName);
if(!serviceClientGraspability) {
ROS_FATAL("Could not initialize service for RequestObjectsGraspability.");
}
}
}
bool ActionExecutorDetectObjects::fillGoal(tidyup_msgs::DetectGraspableObjects::Request & goal,
const DurativeAction & a, const SymbolicState & current)
{
if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways?
ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__);
ROS_ASSERT(a.parameters.size() == 1);
goal.static_object = findStaticObjectForLocation(a.parameters[0], current);
return true;
}
void ActionExecutorDetectObjects::updateState(bool success,
tidyup_msgs::DetectGraspableObjects::Response & response,
const DurativeAction & a, SymbolicState & current)
{
ROS_INFO("DetectObjects returned result");
if(success) {
ROS_INFO("DetectObjects succeeded.");
ROS_ASSERT(a.parameters.size() == 1);
std::string location = a.parameters[0];
current.setBooleanPredicate("searched", location, true);
current.setBooleanPredicate("recent-detected-objects", location, true);
std::vector<tidyup_msgs::GraspableObject>& objects = response.objects;
if(requestGraspability && false) {
ROS_INFO("Requesting graspability.");
tidyup_msgs::RequestObjectsGraspability request;
request.request.objects = objects;
if(!serviceClientGraspability.call(request)) {
ROS_ERROR("Failed to call RequestObjectsGraspability service.");
} else {
objects = request.response.objects;
}
}
// find correct static object and set the "on" predicate
string static_object = findStaticObjectForLocation(location, current);
ROS_ASSERT(static_object != "");
// remove objects form state, which were previously detected from this location
Predicate p;
p.name = "on";
p.parameters.push_back("object");
p.parameters.push_back(static_object);
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange =
current.getTypedObjects().equal_range("movable_object");
for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first;
objectIterator != objectRange.second; objectIterator++)
{
string object = objectIterator->second;
p.parameters[0] = object;
string detection_location;
if (current.hasObjectFluent(p, &detection_location))
{
if (location == detection_location)
{
current.removeObject(object, true);
}
}
}
for(std::vector<tidyup_msgs::GraspableObject>::iterator it = objects.begin(); it != objects.end(); it++)
{
tidyup_msgs::GraspableObject & object = *it;
current.addObject(object.name, "movable_object");
if(object.pose.header.frame_id.empty()) {
ROS_ERROR("DetectGraspableObjects returned empty frame_id for object: %s", object.name.c_str());
object.pose.header.frame_id = "INVALID_FRAME_ID";
}
current.addObject(object.pose.header.frame_id, "frameid");
current.addObject(object.name, "pose");
current.setObjectFluent("frame-id", object.name, object.pose.header.frame_id);
current.setNumericalFluent("x", object.name, object.pose.pose.position.x);
current.setNumericalFluent("y", object.name, object.pose.pose.position.y);
current.setNumericalFluent("z", object.name, object.pose.pose.position.z);
current.setNumericalFluent("qx", object.name, object.pose.pose.orientation.x);
current.setNumericalFluent("qy", object.name, object.pose.pose.orientation.y);
current.setNumericalFluent("qz", object.name, object.pose.pose.orientation.z);
current.setNumericalFluent("qw", object.name, object.pose.pose.orientation.w);
current.setNumericalFluent("timestamp", object.name, object.pose.header.stamp.toSec());
current.setBooleanPredicate("on", object.name + " " + static_object, true);
//current.setObjectFluent("object-detected-from", object.name, location);
// tidy-location: (tidy-location ?o ?s)
current.setBooleanPredicate("tidy-location", object.name + " " + tidyLocationName, true);
// add graspable predicates from current location
if(requestGraspability || true)
{
current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm",
object.reachable_left_arm);
current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm",
object.reachable_right_arm);
}
else
{
current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", true);
current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", true);
}
}
if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways?
ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__);
}
}
std::string ActionExecutorDetectObjects::findStaticObjectForLocation(const std::string& location, const SymbolicState & current) const
{
Predicate p;
string static_object;
p.name = "static-object-at-location";
p.parameters.push_back("object");
p.parameters.push_back(location);
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange =
current.getTypedObjects().equal_range("static_object");
for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first;
objectIterator != objectRange.second; objectIterator++)
{
string object = objectIterator->second;
p.parameters[0] = object;
bool value = false;
if (current.hasBooleanPredicate(p, &value))
{
if (value)
{
static_object = object;
break;
}
}
}
return static_object;
}
};
<commit_msg>actionExecutorDetectObjects adds wipe goals to state<commit_after>#include "tidyup_actions/actionExecutorDetectObjects.h"
#include <pluginlib/class_list_macros.h>
#include <tidyup_msgs/RequestObjectsGraspability.h>
#include "tidyup_utils/planning_scene_interface.h"
PLUGINLIB_DECLARE_CLASS(tidyup_actions, action_executor_detect_objects,
tidyup_actions::ActionExecutorDetectObjects,
continual_planning_executive::ActionExecutorInterface)
namespace tidyup_actions
{
void ActionExecutorDetectObjects::initialize(const std::deque<std::string> & arguments)
{
ActionExecutorService<tidyup_msgs::DetectGraspableObjects>::initialize(arguments);
requestGraspability = false;
string graspabilityServiceName = "/learned_grasping/request_objects_graspability";
tidyLocationName = "table1";
if (arguments.size() >= 3)
{
if (arguments[2] == "NULL")
{
requestGraspability = false;
} else {
graspabilityServiceName = arguments[2];
}
}
if (arguments.size() >= 4)
{
tidyLocationName = arguments[3];
}
ROS_ASSERT(_nh);
if(requestGraspability) {
serviceClientGraspability = _nh->serviceClient<tidyup_msgs::RequestObjectsGraspability>(
graspabilityServiceName);
if(!serviceClientGraspability) {
ROS_FATAL("Could not initialize service for RequestObjectsGraspability.");
}
}
}
bool ActionExecutorDetectObjects::fillGoal(tidyup_msgs::DetectGraspableObjects::Request & goal,
const DurativeAction & a, const SymbolicState & current)
{
if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways?
ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__);
ROS_ASSERT(a.parameters.size() == 1);
goal.static_object = findStaticObjectForLocation(a.parameters[0], current);
return true;
}
void ActionExecutorDetectObjects::updateState(bool success,
tidyup_msgs::DetectGraspableObjects::Response & response,
const DurativeAction & a, SymbolicState & current)
{
ROS_INFO("DetectObjects returned result");
if(success) {
ROS_INFO("DetectObjects succeeded.");
ROS_ASSERT(a.parameters.size() == 1);
std::string location = a.parameters[0];
current.setBooleanPredicate("searched", location, true);
current.setBooleanPredicate("recent-detected-objects", location, true);
std::vector<tidyup_msgs::GraspableObject>& objects = response.objects;
if(requestGraspability && false) {
ROS_INFO("Requesting graspability.");
tidyup_msgs::RequestObjectsGraspability request;
request.request.objects = objects;
if(!serviceClientGraspability.call(request)) {
ROS_ERROR("Failed to call RequestObjectsGraspability service.");
} else {
objects = request.response.objects;
}
}
// find correct static object and set the "on" predicate
string static_object = findStaticObjectForLocation(location, current);
ROS_ASSERT(static_object != "");
// remove objects form state, which were previously detected from this location
Predicate p;
p.name = "on";
p.parameters.push_back("object");
p.parameters.push_back(static_object);
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange =
current.getTypedObjects().equal_range("movable_object");
for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first;
objectIterator != objectRange.second; objectIterator++)
{
string object = objectIterator->second;
p.parameters[0] = object;
string detection_location;
if (current.hasObjectFluent(p, &detection_location))
{
if (location == detection_location)
{
current.removeObject(object, true);
}
}
}
for(std::vector<tidyup_msgs::GraspableObject>::iterator it = objects.begin(); it != objects.end(); it++)
{
tidyup_msgs::GraspableObject & object = *it;
current.addObject(object.name, "movable_object");
if(object.pose.header.frame_id.empty()) {
ROS_ERROR("DetectGraspableObjects returned empty frame_id for object: %s", object.name.c_str());
object.pose.header.frame_id = "INVALID_FRAME_ID";
}
current.addObject(object.pose.header.frame_id, "frameid");
current.addObject(object.name, "pose");
current.setObjectFluent("frame-id", object.name, object.pose.header.frame_id);
current.setNumericalFluent("x", object.name, object.pose.pose.position.x);
current.setNumericalFluent("y", object.name, object.pose.pose.position.y);
current.setNumericalFluent("z", object.name, object.pose.pose.position.z);
current.setNumericalFluent("qx", object.name, object.pose.pose.orientation.x);
current.setNumericalFluent("qy", object.name, object.pose.pose.orientation.y);
current.setNumericalFluent("qz", object.name, object.pose.pose.orientation.z);
current.setNumericalFluent("qw", object.name, object.pose.pose.orientation.w);
current.setNumericalFluent("timestamp", object.name, object.pose.header.stamp.toSec());
current.setBooleanPredicate("on", object.name + " " + static_object, true);
//current.setObjectFluent("object-detected-from", object.name, location);
// tidy-location: (tidy-location ?o ?s)
current.setBooleanPredicate("tidy-location", object.name + " " + tidyLocationName, true);
// add graspable predicates from current location
if(requestGraspability || true)
{
current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm",
object.reachable_left_arm);
current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm",
object.reachable_right_arm);
}
else
{
current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", true);
current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", true);
}
}
std::set<std::string> wipeGoalNames;
for(std::vector<tidyup_msgs::WipeGoal>::iterator it = response.wipe_goals.begin(); it != response.wipe_goals.end(); it++) {
tidyup_msgs::WipeGoal & wg = *it;
wipeGoalNames.insert(wg.name);
// add/update this wipe goal
current.addObject(wg.name, "wipe_point"); // this should never hurt, even if it's in there
if(wg.spot.header.frame_id.empty()) {
ROS_ERROR("DetectGraspableObjects returned empty frame_id for wipe goal: %s", wg.name.c_str());
wg.spot.header.frame_id = "INVALID_FRAME_ID";
}
current.addObject(wg.spot.header.frame_id, "frameid");
current.setObjectFluent("frame-id", wg.name, wg.spot.header.frame_id);
current.setNumericalFluent("x", wg.name, wg.spot.point.x);
current.setNumericalFluent("y", wg.name, wg.spot.point.y);
current.setNumericalFluent("z", wg.name, wg.spot.point.z);
current.setNumericalFluent("timestamp", wg.name, wg.spot.header.stamp.toSec());
// if not known, set initially false
Predicate wipedPred;
wipedPred.name = "wiped";
wipedPred.parameters.push_back(wg.name);
bool wiped;
if(!current.hasBooleanPredicate(wipedPred, &wiped)) { // only set if unknown
current.setBooleanPredicate("wiped", wg.name, false);
}
current.setBooleanPredicate("wipe-point-on", wg.name + " " + static_object, true);
}
// remove all the wipe goals at this static object that were not send in this detection
// (i.e. that are not in wipeGoalNames)
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> wipePointRange =
current.getTypedObjects().equal_range("wipe_point");
std::set<std::string> nonMatchedWipePoints;
for(SymbolicState::TypedObjectConstIterator objectIterator = wipePointRange.first;
objectIterator != wipePointRange.second; objectIterator++) {
// first check if this object is a wipe-point-on static_object
Predicate p;
p.name = "wipe-point-on";
string object = objectIterator->second;
p.parameters.push_back(object);
p.parameters.push_back(static_object);
bool wpOn = false;
if(!current.hasBooleanPredicate(p, &wpOn))
continue;
if(!wpOn)
continue;
// it is on static_object, next check if it was contained in this detection
if(wipeGoalNames.find(object) == wipeGoalNames.end()) {
nonMatchedWipePoints.insert(object);
}
}
for(std::set<std::string>::iterator it = nonMatchedWipePoints.begin(); it != nonMatchedWipePoints.end(); it++) {
ROS_WARN("Removing non matched wipe point: %s.", it->c_str());
current.removeObject(*it, false); // FIXME: do not remove the predicates
// this will remember that we wiped a spot, when we for some reason manage
// to find it again
}
if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways?
ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__);
}
}
std::string ActionExecutorDetectObjects::findStaticObjectForLocation(const std::string& location, const SymbolicState & current) const
{
Predicate p;
string static_object;
p.name = "static-object-at-location";
p.parameters.push_back("object");
p.parameters.push_back(location);
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange =
current.getTypedObjects().equal_range("static_object");
for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first;
objectIterator != objectRange.second; objectIterator++)
{
string object = objectIterator->second;
p.parameters[0] = object;
bool value = false;
if (current.hasBooleanPredicate(p, &value))
{
if (value)
{
static_object = object;
break;
}
}
}
return static_object;
}
};
<|endoftext|> |
<commit_before>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include "libmesh/mesh.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/checkpoint_io.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/metis_partitioner.h"
#include "test_comm.h"
// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings. These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas. We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point. We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>
using namespace libMesh;
class CheckpointIOTest : public CppUnit::TestCase {
/**
* This test verifies that we can write files with the CheckpointIO object.
*/
public:
CPPUNIT_TEST_SUITE( CheckpointIOTest );
CPPUNIT_TEST( testSplitter );
CPPUNIT_TEST_SUITE_END();
protected:
public:
void setUp()
{
}
void tearDown()
{
}
// Test that we can write multiple checkpoint files from a single processor.
void testSplitter()
{
// In this test, we partition the mesh into n_procs parts.
const unsigned int n_procs = 2;
// The number of elements in the original mesh. For verification
// later.
dof_id_type original_n_elem = 0;
{
MetisPartitioner partitioner;
ReplicatedMesh mesh(*TestCommWorld);
MeshTools::Generation::build_square(mesh,
4, 4,
0., 1.,
0., 1.,
QUAD4);
// Store the number of elements that were in the original mesh.
original_n_elem = mesh.n_elem();
// Partition the mesh into n_procs pieces
partitioner.partition(mesh, n_procs);
// Write out checkpoint files for each processor.
for (unsigned i=0; i<n_procs; ++i)
{
CheckpointIO cpr(mesh);
cpr.current_processor_id() = i;
cpr.current_n_processors() = n_procs;
cpr.binary() = true;
cpr.parallel() = true;
cpr.write("checkpoint_splitter.cpr");
}
}
TestCommWorld->barrier();
// Test that we can read in the files we wrote and sum up to the
// same total number of elements.
{
unsigned int read_in_elements = 0;
for (unsigned i=0; i<n_procs; ++i)
{
Mesh mesh(*TestCommWorld);
CheckpointIO cpr(mesh);
cpr.current_processor_id() = i;
cpr.current_n_processors() = n_procs;
cpr.binary() = true;
cpr.parallel() = true;
cpr.read("checkpoint_splitter.cpr");
read_in_elements += std::distance(mesh.pid_elements_begin(i),
mesh.pid_elements_end(i));
}
// Verify that we read in exactly as many elements on each proc as we started with.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(read_in_elements), original_n_elem);
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( CheckpointIOTest );
<commit_msg>Unit test both binary and ASCII CheckpointIO<commit_after>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include "libmesh/mesh.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/checkpoint_io.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/metis_partitioner.h"
#include "test_comm.h"
// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings. These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas. We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point. We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>
using namespace libMesh;
class CheckpointIOTest : public CppUnit::TestCase {
/**
* This test verifies that we can write files with the CheckpointIO object.
*/
public:
CPPUNIT_TEST_SUITE( CheckpointIOTest );
CPPUNIT_TEST( testAsciiSplitter );
CPPUNIT_TEST( testBinarySplitter );
CPPUNIT_TEST_SUITE_END();
protected:
public:
void setUp()
{
}
void tearDown()
{
}
// Test that we can write multiple checkpoint files from a single processor.
void testSplitter(bool binary)
{
// In this test, we partition the mesh into n_procs parts.
const unsigned int n_procs = 2;
// The number of elements in the original mesh. For verification
// later.
dof_id_type original_n_elem = 0;
const std::string filename =
std::string("checkpoint_splitter.cp") + (binary ? "r" : "a");
{
MetisPartitioner partitioner;
ReplicatedMesh mesh(*TestCommWorld);
MeshTools::Generation::build_square(mesh,
4, 4,
0., 1.,
0., 1.,
QUAD4);
// Store the number of elements that were in the original mesh.
original_n_elem = mesh.n_elem();
// Partition the mesh into n_procs pieces
partitioner.partition(mesh, n_procs);
// Write out checkpoint files for each processor.
for (unsigned i=0; i<n_procs; ++i)
{
CheckpointIO cpr(mesh);
cpr.current_processor_id() = i;
cpr.current_n_processors() = n_procs;
cpr.binary() = binary;
cpr.parallel() = true;
cpr.write(filename);
}
}
TestCommWorld->barrier();
// Test that we can read in the files we wrote and sum up to the
// same total number of elements.
{
unsigned int read_in_elements = 0;
for (unsigned i=0; i<n_procs; ++i)
{
Mesh mesh(*TestCommWorld);
CheckpointIO cpr(mesh);
cpr.current_processor_id() = i;
cpr.current_n_processors() = n_procs;
cpr.binary() = binary;
cpr.parallel() = true;
cpr.read(filename);
read_in_elements += std::distance(mesh.pid_elements_begin(i),
mesh.pid_elements_end(i));
}
// Verify that we read in exactly as many elements on each proc as we started with.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(read_in_elements), original_n_elem);
}
}
void testAsciiSplitter()
{
testSplitter(false);
}
void testBinarySplitter()
{
testSplitter(true);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( CheckpointIOTest );
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: csvtablebox.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:18:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// ============================================================================
#ifndef _SC_CSVTABLEBOX_HXX
#define _SC_CSVTABLEBOX_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _SC_CSVRULER_HXX
#include "csvruler.hxx"
#endif
#ifndef _SC_CSVGRID_HXX
#include "csvgrid.hxx"
#endif
class ListBox;
class ScAsciiOptions;
/* ============================================================================
Position: Positions between the characters (the dots in the ruler).
Character: The characters (the range from one position to the next).
Split: Positions which contain a split to divide characters into groups (columns).
Column: The range between two splits.
============================================================================ */
/** The control in the CSV import dialog that contains a ruler and a data grid
to visualize and modify the current import settings. */
class SC_DLLPUBLIC ScCsvTableBox : public ScCsvControl
{
private:
ScCsvLayoutData maData; /// Current layout data of the controls.
ScCsvRuler maRuler; /// The ruler for fixed width mode.
ScCsvGrid maGrid; /// Calc-like data table for fixed width mode.
ScrollBar maHScroll; /// Horizontal scroll bar.
ScrollBar maVScroll; /// Vertical scroll bar.
ScrollBarBox maScrollBox; /// For the bottom right edge.
Link maUpdateTextHdl; /// Updates all cell texts.
Link maColTypeHdl; /// Handler for exporting the column type.
ScCsvColStateVec maFixColStates; /// Column states in fixed width mode.
ScCsvColStateVec maSepColStates; /// Column states in separators mode.
sal_Int32 mnFixedWidth; /// Cached total width for fixed width mode.
bool mbFixedMode; /// false = Separators, true = Fixed width.
// ------------------------------------------------------------------------
public:
explicit ScCsvTableBox( Window* pParent );
explicit ScCsvTableBox( Window* pParent, const ResId& rResId );
// common table box handling ----------------------------------------------
public:
/** Sets the control to separators mode. */
void SetSeparatorsMode();
/** Sets the control to fixed width mode. */
void SetFixedWidthMode();
private:
/** Initialisation on construction. */
SC_DLLPRIVATE void Init();
/** Initializes the children controls (pos/size, scroll bars, ...). */
SC_DLLPRIVATE void InitControls();
/** Initializes size and position data of horizontal scrollbar. */
SC_DLLPRIVATE void InitHScrollBar();
/** Initializes size and position data of vertical scrollbar. */
SC_DLLPRIVATE void InitVScrollBar();
/** Calculates and sets valid position offset nearest to nPos. */
SC_DLLPRIVATE inline void ImplSetPosOffset( sal_Int32 nPos )
{ maData.mnPosOffset = Max( Min( nPos, GetMaxPosOffset() ), 0L ); }
/** Calculates and sets valid line offset nearest to nLine. */
SC_DLLPRIVATE inline void ImplSetLineOffset( sal_Int32 nLine )
{ maData.mnLineOffset = Max( Min( nLine, GetMaxLineOffset() ), 0L ); }
/** Moves controls (not cursors!) so that nPos becomes visible. */
SC_DLLPRIVATE void MakePosVisible( sal_Int32 nPos );
// cell contents ----------------------------------------------------------
public:
/** Fills all cells of all lines with the passed texts (Unicode strings). */
void SetUniStrings(
const String* pTextLines, const String& rSepChars,
sal_Unicode cTextSep, bool bMergeSep );
/** Fills all cells of all lines with the passed texts (ByteStrings). */
void SetByteStrings(
const ByteString* pLineTexts, CharSet eCharSet,
const String& rSepChars, sal_Unicode cTextSep, bool bMergeSep );
// column settings --------------------------------------------------------
public:
/** Reads UI strings for data types from the list box. */
void InitTypes( const ListBox& rListBox );
/** Returns the data type of the selected columns. */
inline sal_Int32 GetSelColumnType() const { return maGrid.GetSelColumnType(); }
/** Fills the options object with current column data. */
void FillColumnData( ScAsciiOptions& rOptions ) const;
// event handling ---------------------------------------------------------
public:
/** Sets a new handler for "update cell texts" requests. */
inline void SetUpdateTextHdl( const Link& rHdl ) { maUpdateTextHdl = rHdl; }
/** Returns the handler for "update cell texts" requests. */
inline const Link& GetUpdateTextHdl() const { return maUpdateTextHdl; }
/** Sets a new handler for "column selection changed" events. */
inline void SetColTypeHdl( const Link& rHdl ) { maColTypeHdl = rHdl; }
/** Returns the handler for "column selection changed" events. */
inline const Link& GetColTypeHdl() const { return maColTypeHdl; }
protected:
virtual void Resize();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
private:
SC_DLLPRIVATE DECL_LINK( CsvCmdHdl, ScCsvControl* );
SC_DLLPRIVATE DECL_LINK( ScrollHdl, ScrollBar* );
SC_DLLPRIVATE DECL_LINK( ScrollEndHdl, ScrollBar* );
// accessibility ----------------------------------------------------------
public:
/** Creates and returns the accessible object of this control. */
virtual XAccessibleRef CreateAccessible();
protected:
/** Creates a new accessible object. */
virtual ScAccessibleCsvControl* ImplCreateAccessible();
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS sixtyfour05 (1.6.150); FILE MERGED 2006/04/10 16:22:01 kendy 1.6.150.1: #i63758# Min()/Max() has to have both arguments of the same type<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: csvtablebox.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-04-19 14:05:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// ============================================================================
#ifndef _SC_CSVTABLEBOX_HXX
#define _SC_CSVTABLEBOX_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _SC_CSVRULER_HXX
#include "csvruler.hxx"
#endif
#ifndef _SC_CSVGRID_HXX
#include "csvgrid.hxx"
#endif
class ListBox;
class ScAsciiOptions;
/* ============================================================================
Position: Positions between the characters (the dots in the ruler).
Character: The characters (the range from one position to the next).
Split: Positions which contain a split to divide characters into groups (columns).
Column: The range between two splits.
============================================================================ */
/** The control in the CSV import dialog that contains a ruler and a data grid
to visualize and modify the current import settings. */
class SC_DLLPUBLIC ScCsvTableBox : public ScCsvControl
{
private:
ScCsvLayoutData maData; /// Current layout data of the controls.
ScCsvRuler maRuler; /// The ruler for fixed width mode.
ScCsvGrid maGrid; /// Calc-like data table for fixed width mode.
ScrollBar maHScroll; /// Horizontal scroll bar.
ScrollBar maVScroll; /// Vertical scroll bar.
ScrollBarBox maScrollBox; /// For the bottom right edge.
Link maUpdateTextHdl; /// Updates all cell texts.
Link maColTypeHdl; /// Handler for exporting the column type.
ScCsvColStateVec maFixColStates; /// Column states in fixed width mode.
ScCsvColStateVec maSepColStates; /// Column states in separators mode.
sal_Int32 mnFixedWidth; /// Cached total width for fixed width mode.
bool mbFixedMode; /// false = Separators, true = Fixed width.
// ------------------------------------------------------------------------
public:
explicit ScCsvTableBox( Window* pParent );
explicit ScCsvTableBox( Window* pParent, const ResId& rResId );
// common table box handling ----------------------------------------------
public:
/** Sets the control to separators mode. */
void SetSeparatorsMode();
/** Sets the control to fixed width mode. */
void SetFixedWidthMode();
private:
/** Initialisation on construction. */
SC_DLLPRIVATE void Init();
/** Initializes the children controls (pos/size, scroll bars, ...). */
SC_DLLPRIVATE void InitControls();
/** Initializes size and position data of horizontal scrollbar. */
SC_DLLPRIVATE void InitHScrollBar();
/** Initializes size and position data of vertical scrollbar. */
SC_DLLPRIVATE void InitVScrollBar();
/** Calculates and sets valid position offset nearest to nPos. */
SC_DLLPRIVATE inline void ImplSetPosOffset( sal_Int32 nPos )
{ maData.mnPosOffset = Max( Min( nPos, GetMaxPosOffset() ), sal_Int32( 0 ) ); }
/** Calculates and sets valid line offset nearest to nLine. */
SC_DLLPRIVATE inline void ImplSetLineOffset( sal_Int32 nLine )
{ maData.mnLineOffset = Max( Min( nLine, GetMaxLineOffset() ), sal_Int32( 0 ) ); }
/** Moves controls (not cursors!) so that nPos becomes visible. */
SC_DLLPRIVATE void MakePosVisible( sal_Int32 nPos );
// cell contents ----------------------------------------------------------
public:
/** Fills all cells of all lines with the passed texts (Unicode strings). */
void SetUniStrings(
const String* pTextLines, const String& rSepChars,
sal_Unicode cTextSep, bool bMergeSep );
/** Fills all cells of all lines with the passed texts (ByteStrings). */
void SetByteStrings(
const ByteString* pLineTexts, CharSet eCharSet,
const String& rSepChars, sal_Unicode cTextSep, bool bMergeSep );
// column settings --------------------------------------------------------
public:
/** Reads UI strings for data types from the list box. */
void InitTypes( const ListBox& rListBox );
/** Returns the data type of the selected columns. */
inline sal_Int32 GetSelColumnType() const { return maGrid.GetSelColumnType(); }
/** Fills the options object with current column data. */
void FillColumnData( ScAsciiOptions& rOptions ) const;
// event handling ---------------------------------------------------------
public:
/** Sets a new handler for "update cell texts" requests. */
inline void SetUpdateTextHdl( const Link& rHdl ) { maUpdateTextHdl = rHdl; }
/** Returns the handler for "update cell texts" requests. */
inline const Link& GetUpdateTextHdl() const { return maUpdateTextHdl; }
/** Sets a new handler for "column selection changed" events. */
inline void SetColTypeHdl( const Link& rHdl ) { maColTypeHdl = rHdl; }
/** Returns the handler for "column selection changed" events. */
inline const Link& GetColTypeHdl() const { return maColTypeHdl; }
protected:
virtual void Resize();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
private:
SC_DLLPRIVATE DECL_LINK( CsvCmdHdl, ScCsvControl* );
SC_DLLPRIVATE DECL_LINK( ScrollHdl, ScrollBar* );
SC_DLLPRIVATE DECL_LINK( ScrollEndHdl, ScrollBar* );
// accessibility ----------------------------------------------------------
public:
/** Creates and returns the accessible object of this control. */
virtual XAccessibleRef CreateAccessible();
protected:
/** Creates a new accessible object. */
virtual ScAccessibleCsvControl* ImplCreateAccessible();
};
// ============================================================================
#endif
<|endoftext|> |
<commit_before>//
// yas_audio_kernel.cpp
//
#include "yas_audio_engine_node.h"
using namespace yas;
#pragma mark - audio::engine::kernel::impl
struct audio::engine::kernel::impl : base::impl, manageable_kernel::impl {
audio::engine::connection input_connection(uint32_t const bus_idx) {
if (_input_connections.count(bus_idx) > 0) {
return _input_connections.at(bus_idx).lock();
}
return nullptr;
}
audio::engine::connection output_connection(uint32_t const bus_idx) {
if (_output_connections.count(bus_idx) > 0) {
return _output_connections.at(bus_idx).lock();
}
return nullptr;
}
audio::engine::connection_smap input_connections() {
return lock_values(_input_connections);
}
audio::engine::connection_smap output_connections() {
return lock_values(_output_connections);
}
void set_input_connections(audio::engine::connection_wmap &&connections) {
_input_connections = std::move(connections);
}
void set_output_connections(audio::engine::connection_wmap &&connections) {
_output_connections = std::move(connections);
}
void set_decorator(base &&decor) {
_decorator = std::move(decor);
}
base &decorator() {
return _decorator;
}
private:
engine::connection_wmap _input_connections;
engine::connection_wmap _output_connections;
base _decorator = nullptr;
};
#pragma mark - audio::engine::kernel
audio::engine::kernel::kernel() : base(std::make_unique<impl>()) {
}
audio::engine::kernel::kernel(std::nullptr_t) : base(nullptr) {
}
audio::engine::kernel::~kernel() = default;
audio::engine::connection_smap audio::engine::kernel::input_connections() const {
return impl_ptr<impl>()->input_connections();
}
audio::engine::connection_smap audio::engine::kernel::output_connections() const {
return impl_ptr<impl>()->output_connections();
}
audio::engine::connection audio::engine::kernel::input_connection(uint32_t const bus_idx) const {
return impl_ptr<impl>()->input_connection(bus_idx);
}
audio::engine::connection audio::engine::kernel::output_connection(uint32_t const bus_idx) const {
return impl_ptr<impl>()->output_connection(bus_idx);
}
void audio::engine::kernel::set_decorator(base decor) {
impl_ptr<impl>()->set_decorator(std::move(decor));
}
base const &audio::engine::kernel::decorator() const {
return impl_ptr<impl>()->decorator();
}
base &audio::engine::kernel::decorator() {
return impl_ptr<impl>()->decorator();
}
audio::engine::manageable_kernel &audio::engine::kernel::manageable() {
if (!_manageable) {
_manageable = audio::engine::manageable_kernel{impl_ptr<audio::engine::manageable_kernel::impl>()};
}
return _manageable;
}
<commit_msg>engine_kernel this<commit_after>//
// yas_audio_kernel.cpp
//
#include "yas_audio_engine_node.h"
using namespace yas;
#pragma mark - audio::engine::kernel::impl
struct audio::engine::kernel::impl : base::impl, manageable_kernel::impl {
audio::engine::connection input_connection(uint32_t const bus_idx) {
if (this->_input_connections.count(bus_idx) > 0) {
return this->_input_connections.at(bus_idx).lock();
}
return nullptr;
}
audio::engine::connection output_connection(uint32_t const bus_idx) {
if (this->_output_connections.count(bus_idx) > 0) {
return this->_output_connections.at(bus_idx).lock();
}
return nullptr;
}
audio::engine::connection_smap input_connections() {
return lock_values(this->_input_connections);
}
audio::engine::connection_smap output_connections() {
return lock_values(this->_output_connections);
}
void set_input_connections(audio::engine::connection_wmap &&connections) {
this->_input_connections = std::move(connections);
}
void set_output_connections(audio::engine::connection_wmap &&connections) {
this->_output_connections = std::move(connections);
}
void set_decorator(base &&decor) {
this->_decorator = std::move(decor);
}
base &decorator() {
return this->_decorator;
}
private:
engine::connection_wmap _input_connections;
engine::connection_wmap _output_connections;
base _decorator = nullptr;
};
#pragma mark - audio::engine::kernel
audio::engine::kernel::kernel() : base(std::make_unique<impl>()) {
}
audio::engine::kernel::kernel(std::nullptr_t) : base(nullptr) {
}
audio::engine::kernel::~kernel() = default;
audio::engine::connection_smap audio::engine::kernel::input_connections() const {
return impl_ptr<impl>()->input_connections();
}
audio::engine::connection_smap audio::engine::kernel::output_connections() const {
return impl_ptr<impl>()->output_connections();
}
audio::engine::connection audio::engine::kernel::input_connection(uint32_t const bus_idx) const {
return impl_ptr<impl>()->input_connection(bus_idx);
}
audio::engine::connection audio::engine::kernel::output_connection(uint32_t const bus_idx) const {
return impl_ptr<impl>()->output_connection(bus_idx);
}
void audio::engine::kernel::set_decorator(base decor) {
impl_ptr<impl>()->set_decorator(std::move(decor));
}
base const &audio::engine::kernel::decorator() const {
return impl_ptr<impl>()->decorator();
}
base &audio::engine::kernel::decorator() {
return impl_ptr<impl>()->decorator();
}
audio::engine::manageable_kernel &audio::engine::kernel::manageable() {
if (!_manageable) {
_manageable = audio::engine::manageable_kernel{impl_ptr<audio::engine::manageable_kernel::impl>()};
}
return _manageable;
}
<|endoftext|> |
<commit_before>#pragma once
// standard
#include <map>
#include <memory>
#include <unordered_set>
#include <vector>
// project
#include "AssetManager.hpp"
#include "Node.hpp"
#include "depthai/openvino/OpenVINO.hpp"
// shared
#include "depthai-shared/pipeline/PipelineSchema.hpp"
#include "depthai-shared/properties/GlobalProperties.hpp"
namespace dai {
class PipelineImpl {
friend class Pipeline;
friend class Node;
// static functions
static bool isSamePipeline(const Node::Output& out, const Node::Input& in);
static bool canConnect(const Node::Output& out, const Node::Input& in);
// Functions
Node::Id getNextUniqueId();
PipelineSchema getPipelineSchema() const;
OpenVINO::Version getPipelineOpenVINOVersion() const;
AssetManager getAllAssets() const;
// Access to nodes
std::vector<std::shared_ptr<const Node>> getAllNodes() const;
std::vector<std::shared_ptr<Node>> getAllNodes();
std::shared_ptr<const Node> getNode(Node::Id id) const;
std::shared_ptr<Node> getNode(Node::Id id);
void serialize(PipelineSchema& schema, Assets& assets, std::vector<std::uint8_t>& assetStorage, OpenVINO::Version& version) const;
void remove(std::shared_ptr<Node> node);
std::vector<Node::Connection> getConnections() const;
void link(const Node::Output& out, const Node::Input& in);
void unlink(const Node::Output& out, const Node::Input& in);
// Must be incremented and unique for each node
Node::Id latestId = 0;
// Pipeline asset manager
AssetManager assetManager;
// Default version
constexpr static auto DEFAULT_OPENVINO_VERSION = OpenVINO::Version::VERSION_2020_1;
// Optionally forced version
tl::optional<OpenVINO::Version> forceRequiredOpenVINOVersion;
// Global pipeline properties
GlobalProperties globalProperties;
// Optimized for adding, searching and removing connections
using NodeMap = std::unordered_map<Node::Id, std::shared_ptr<Node>>;
NodeMap nodeMap;
using NodeConnectionMap = std::unordered_map<Node::Id, std::unordered_set<Node::Connection>>;
// Connection map, NodeId represents id of node connected TO (input)
NodeConnectionMap nodeConnectionMap;
// Template create function
template <class N>
std::shared_ptr<N> create(const std::shared_ptr<PipelineImpl>& itself) {
// Check that passed type 'N' is subclass of Node
static_assert(std::is_base_of<Node, N>::value, "Specified class is not a subclass of Node");
// Get unique id for this new node
auto id = getNextUniqueId();
// Create and store the node in the map
auto node = std::make_shared<N>(itself, id);
nodeMap[id] = node;
// Return shared pointer to this node
return node;
}
};
/**
* @brief Represents the pipeline, set of nodes and connections between them
*/
class Pipeline {
std::shared_ptr<PipelineImpl> pimpl;
PipelineImpl* impl() {
return pimpl.get();
}
const PipelineImpl* impl() const {
return pimpl.get();
}
public:
/**
* Constructs a new pipeline
*/
Pipeline();
explicit Pipeline(const std::shared_ptr<PipelineImpl>& pimpl);
/// Default Pipeline openvino version
constexpr static auto DEFAULT_OPENVINO_VERSION = PipelineImpl::DEFAULT_OPENVINO_VERSION;
/**
* @returns Global properties of current pipeline
*/
GlobalProperties getGlobalProperties() const;
/**
* @returns Pipeline schema
*/
PipelineSchema getPipelineSchema();
// void loadAssets(AssetManager& assetManager);
void serialize(PipelineSchema& schema, Assets& assets, std::vector<std::uint8_t>& assetStorage, OpenVINO::Version& version) const {
impl()->serialize(schema, assets, assetStorage, version);
}
/**
* Adds a node to pipeline.
*
* Node is specified by template argument N
*/
template <class N>
std::shared_ptr<N> create() {
return impl()->create<N>(pimpl);
}
/// Removes a node from pipeline
void remove(std::shared_ptr<Node> node) {
impl()->remove(node);
}
/// Get a vector of all nodes
std::vector<std::shared_ptr<const Node>> getAllNodes() const {
return impl()->getAllNodes();
}
/// Get a vector of all nodes
std::vector<std::shared_ptr<Node>> getAllNodes() {
return impl()->getAllNodes();
}
/// Get node with id if it exists, nullptr otherwise
std::shared_ptr<const Node> getNode(Node::Id id) const {
return impl()->getNode(id);
}
/// Get node with id if it exists, nullptr otherwise
std::shared_ptr<Node> getNode(Node::Id id) {
return impl()->getNode(id);
}
/// Get all connections
std::vector<Node::Connection> getConnections() const {
return impl()->getConnections();
}
using NodeConnectionMap = PipelineImpl::NodeConnectionMap;
/// Get a reference to internal connection representation
const NodeConnectionMap& getConnectionMap() const {
return impl()->nodeConnectionMap;
}
using NodeMap = PipelineImpl::NodeMap;
/// Get a reference to internal node map
const NodeMap& getNodeMap() const {
return impl()->nodeMap;
}
/**
* Link output to an input. Both nodes must be on the same pipeline
*
* Throws an error if they aren't or cannot be connected
*
* @param out Nodes output to connect from
* @param in Nodes input to connect to
*/
void link(const Node::Output& out, const Node::Input& in) {
impl()->link(out, in);
}
/**
* Unlink output from an input.
*
* Throws an error if link doesn't exists
*
* @param out Nodes output to unlink from
* @param in Nodes input to unlink to
*/
void unlink(const Node::Output& out, const Node::Input& in) {
impl()->unlink(out, in);
}
/// Get assets on the pipeline includes nodes assets
AssetManager getAllAssets() const {
return impl()->getAllAssets();
}
/// Get pipelines AssetManager as reference
const AssetManager& getAssetManager() const {
return impl()->assetManager;
}
/// Get pipelines AssetManager as reference
AssetManager& getAssetManager() {
return impl()->assetManager;
}
/// Set a specific OpenVINO version to use with this pipeline
void setOpenVINOVersion(OpenVINO::Version version) {
impl()->forceRequiredOpenVINOVersion = version;
}
};
} // namespace dai
<commit_msg>Set default OpenVino version to 2020.3<commit_after>#pragma once
// standard
#include <map>
#include <memory>
#include <unordered_set>
#include <vector>
// project
#include "AssetManager.hpp"
#include "Node.hpp"
#include "depthai/openvino/OpenVINO.hpp"
// shared
#include "depthai-shared/pipeline/PipelineSchema.hpp"
#include "depthai-shared/properties/GlobalProperties.hpp"
namespace dai {
class PipelineImpl {
friend class Pipeline;
friend class Node;
// static functions
static bool isSamePipeline(const Node::Output& out, const Node::Input& in);
static bool canConnect(const Node::Output& out, const Node::Input& in);
// Functions
Node::Id getNextUniqueId();
PipelineSchema getPipelineSchema() const;
OpenVINO::Version getPipelineOpenVINOVersion() const;
AssetManager getAllAssets() const;
// Access to nodes
std::vector<std::shared_ptr<const Node>> getAllNodes() const;
std::vector<std::shared_ptr<Node>> getAllNodes();
std::shared_ptr<const Node> getNode(Node::Id id) const;
std::shared_ptr<Node> getNode(Node::Id id);
void serialize(PipelineSchema& schema, Assets& assets, std::vector<std::uint8_t>& assetStorage, OpenVINO::Version& version) const;
void remove(std::shared_ptr<Node> node);
std::vector<Node::Connection> getConnections() const;
void link(const Node::Output& out, const Node::Input& in);
void unlink(const Node::Output& out, const Node::Input& in);
// Must be incremented and unique for each node
Node::Id latestId = 0;
// Pipeline asset manager
AssetManager assetManager;
// Default version
constexpr static auto DEFAULT_OPENVINO_VERSION = OpenVINO::Version::VERSION_2020_3;
// Optionally forced version
tl::optional<OpenVINO::Version> forceRequiredOpenVINOVersion;
// Global pipeline properties
GlobalProperties globalProperties;
// Optimized for adding, searching and removing connections
using NodeMap = std::unordered_map<Node::Id, std::shared_ptr<Node>>;
NodeMap nodeMap;
using NodeConnectionMap = std::unordered_map<Node::Id, std::unordered_set<Node::Connection>>;
// Connection map, NodeId represents id of node connected TO (input)
NodeConnectionMap nodeConnectionMap;
// Template create function
template <class N>
std::shared_ptr<N> create(const std::shared_ptr<PipelineImpl>& itself) {
// Check that passed type 'N' is subclass of Node
static_assert(std::is_base_of<Node, N>::value, "Specified class is not a subclass of Node");
// Get unique id for this new node
auto id = getNextUniqueId();
// Create and store the node in the map
auto node = std::make_shared<N>(itself, id);
nodeMap[id] = node;
// Return shared pointer to this node
return node;
}
};
/**
* @brief Represents the pipeline, set of nodes and connections between them
*/
class Pipeline {
std::shared_ptr<PipelineImpl> pimpl;
PipelineImpl* impl() {
return pimpl.get();
}
const PipelineImpl* impl() const {
return pimpl.get();
}
public:
/**
* Constructs a new pipeline
*/
Pipeline();
explicit Pipeline(const std::shared_ptr<PipelineImpl>& pimpl);
/// Default Pipeline openvino version
constexpr static auto DEFAULT_OPENVINO_VERSION = PipelineImpl::DEFAULT_OPENVINO_VERSION;
/**
* @returns Global properties of current pipeline
*/
GlobalProperties getGlobalProperties() const;
/**
* @returns Pipeline schema
*/
PipelineSchema getPipelineSchema();
// void loadAssets(AssetManager& assetManager);
void serialize(PipelineSchema& schema, Assets& assets, std::vector<std::uint8_t>& assetStorage, OpenVINO::Version& version) const {
impl()->serialize(schema, assets, assetStorage, version);
}
/**
* Adds a node to pipeline.
*
* Node is specified by template argument N
*/
template <class N>
std::shared_ptr<N> create() {
return impl()->create<N>(pimpl);
}
/// Removes a node from pipeline
void remove(std::shared_ptr<Node> node) {
impl()->remove(node);
}
/// Get a vector of all nodes
std::vector<std::shared_ptr<const Node>> getAllNodes() const {
return impl()->getAllNodes();
}
/// Get a vector of all nodes
std::vector<std::shared_ptr<Node>> getAllNodes() {
return impl()->getAllNodes();
}
/// Get node with id if it exists, nullptr otherwise
std::shared_ptr<const Node> getNode(Node::Id id) const {
return impl()->getNode(id);
}
/// Get node with id if it exists, nullptr otherwise
std::shared_ptr<Node> getNode(Node::Id id) {
return impl()->getNode(id);
}
/// Get all connections
std::vector<Node::Connection> getConnections() const {
return impl()->getConnections();
}
using NodeConnectionMap = PipelineImpl::NodeConnectionMap;
/// Get a reference to internal connection representation
const NodeConnectionMap& getConnectionMap() const {
return impl()->nodeConnectionMap;
}
using NodeMap = PipelineImpl::NodeMap;
/// Get a reference to internal node map
const NodeMap& getNodeMap() const {
return impl()->nodeMap;
}
/**
* Link output to an input. Both nodes must be on the same pipeline
*
* Throws an error if they aren't or cannot be connected
*
* @param out Nodes output to connect from
* @param in Nodes input to connect to
*/
void link(const Node::Output& out, const Node::Input& in) {
impl()->link(out, in);
}
/**
* Unlink output from an input.
*
* Throws an error if link doesn't exists
*
* @param out Nodes output to unlink from
* @param in Nodes input to unlink to
*/
void unlink(const Node::Output& out, const Node::Input& in) {
impl()->unlink(out, in);
}
/// Get assets on the pipeline includes nodes assets
AssetManager getAllAssets() const {
return impl()->getAllAssets();
}
/// Get pipelines AssetManager as reference
const AssetManager& getAssetManager() const {
return impl()->assetManager;
}
/// Get pipelines AssetManager as reference
AssetManager& getAssetManager() {
return impl()->assetManager;
}
/// Set a specific OpenVINO version to use with this pipeline
void setOpenVINOVersion(OpenVINO::Version version) {
impl()->forceRequiredOpenVINOVersion = version;
}
};
} // namespace dai
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include <boost/function/function1.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <string.h> // for memcpy
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0)
{
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
m_destructed = false;
#endif
}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop);
void append_buffer(char* buffer, int s, int used_size
, boost::function<void(char*)> const& destructor);
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer();
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
char* append(char const* buf, int s);
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int s);
std::list<asio::const_buffer> const& build_iovec(int to_send);
~chained_buffer();
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
bool m_destructed;
#endif
};
}
#endif
<commit_msg>fix test_buffer build when linking dynamically<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include "libtorrent/config.hpp"
#include <boost/function/function1.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <string.h> // for memcpy
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct TORRENT_EXPORT chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0)
{
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
m_destructed = false;
#endif
}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop);
void append_buffer(char* buffer, int s, int used_size
, boost::function<void(char*)> const& destructor);
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer();
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
char* append(char const* buf, int s);
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int s);
std::list<asio::const_buffer> const& build_iovec(int to_send);
~chained_buffer();
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
bool m_destructed;
#endif
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef TEXT_VIEW_CONCEPTS_HPP // {
#define TEXT_VIEW_CONCEPTS_HPP
#include <utility>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_traits.hpp>
#include <range/v3/utility/concepts.hpp>
#include <range/v3/utility/iterator_concepts.hpp>
#include <range/v3/utility/iterator_traits.hpp>
#include <text_view_detail/traits.hpp>
#include <text_view_detail/character_set_id.hpp>
namespace std {
namespace experimental {
inline namespace text {
namespace text_detail {
template<typename T, T t1, T t2>
concept bool SameValue() {
return t1 == t2;
}
// FIXME: gcc bug 67565, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67565
// FIXME: Compile time performance is negatively impacted by concept definitions
// FIXME: specified with disjunction constraints. Performance is significantly
// FIXME: improved by rewriting such constraints in terms of constexpr function
// FIXME: or variable templates. Rewriting the CodeUnit and CodePoint concepts
// FIXME: in terms of is_code_unit_v and is_code_point_v dropped build times
// FIXME: from 5m50s to 2m00s. Once the performance issues in the compiler are
// FIXME: addressed, is_code_unit_v and is_code_point_v can be removed and
// FIXME: the original CodeUnit and CodePoint concept definitions restored.
template<typename T>
constexpr bool is_code_unit_v =
std::is_integral<T>::value
&& (std::is_unsigned<T>::value
|| std::is_same<std::remove_cv_t<T>, char>::value
|| std::is_same<std::remove_cv_t<T>, wchar_t>::value);
template<typename T>
constexpr bool is_code_point_v =
std::is_integral<T>::value
&& (std::is_unsigned<T>::value
|| std::is_same<std::remove_cv_t<T>, char>::value
|| std::is_same<std::remove_cv_t<T>, wchar_t>::value);
} // text_detail namespace
/*
* Code unit concept
*/
template<typename T>
concept bool CodeUnit() {
return text_detail::is_code_unit_v<T>;
}
/*
* Code point concept
*/
template<typename T>
concept bool CodePoint() {
return text_detail::is_code_point_v<T>;
}
/*
* Character set concept
*/
template<typename T>
concept bool CharacterSet() {
return requires () {
{ T::get_name() } noexcept -> const char *;
}
&& CodePoint<code_point_type_t<T>>();
}
/*
* Character concept
*/
template<typename T>
concept bool Character() {
return CharacterSet<character_set_type_t<T>>()
&& ranges::Regular<T>()
&& requires (T t,
const T ct,
code_point_type_t<character_set_type_t<T>> cp)
{
t.set_code_point(cp);
{ ct.get_code_point() } noexcept
-> code_point_type_t<character_set_type_t<T>>;
{ ct.get_character_set_id() }
-> character_set_id;
};
}
/*
* Code unit iterator concept
*/
template<typename T>
concept bool CodeUnitIterator() {
return ranges::Iterator<T>()
&& CodeUnit<ranges::value_type_t<T>>();
}
/*
* Code unit output iterator concept
*/
template<typename T, typename V>
concept bool CodeUnitOutputIterator() {
return ranges::OutputIterator<T, V>()
&& CodeUnit<V>();
}
/*
* Text encoding state concept
* These requirements are intended to match the char_traits<T>::state_type
* requirements described in C++11 [char.traits.typedefs] 21.2.2p4.
*/
template<typename T>
concept bool TextEncodingState() {
return ranges::Semiregular<T>();
}
/*
* Text encoding state transition concept
*/
template<typename T>
concept bool TextEncodingStateTransition() {
return ranges::Semiregular<T>();
}
/*
* Text encoding concept
*/
template<typename T>
concept bool TextEncoding() {
return requires () {
{ T::min_code_units } noexcept -> int;
{ T::max_code_units } noexcept -> int;
}
&& TextEncodingState<typename T::state_type>()
&& TextEncodingStateTransition<typename T::state_transition_type>()
&& CodeUnit<code_unit_type_t<T>>()
&& Character<character_type_t<T>>()
&& requires () {
{ T::initial_state() } noexcept
-> const typename T::state_type&;
};
}
/*
* Text encoder concept
*/
template<typename T, typename CUIT>
concept bool TextEncoder() {
return TextEncoding<T>()
&& CodeUnitOutputIterator<CUIT, code_unit_type_t<T>>()
&& requires (
typename T::state_type &state,
CUIT &out,
typename T::state_transition_type stt,
int &encoded_code_units)
{
T::encode_state_transition(state, out, stt, encoded_code_units);
}
&& requires (
typename T::state_type &state,
CUIT &out,
character_type_t<T> c,
int &encoded_code_units)
{
T::encode(state, out, c, encoded_code_units);
};
}
/*
* Text decoder concept
*/
template<typename T, typename CUIT>
concept bool TextDecoder() {
return TextEncoding<T>()
&& ranges::InputIterator<CUIT>()
&& ranges::ConvertibleTo<ranges::value_type_t<CUIT>,
code_unit_type_t<T>>()
&& requires (
typename T::state_type &state,
CUIT &in_next,
CUIT in_end,
character_type_t<T> &c,
int &decoded_code_units)
{
{ T::decode(state, in_next, in_end, c, decoded_code_units) } -> bool;
};
}
/*
* Text forward decoder concept
*/
template<typename T, typename CUIT>
concept bool TextForwardDecoder() {
return TextDecoder<T, CUIT>()
&& ranges::ForwardIterator<CUIT>();
}
/*
* Text bidirectional decoder concept
*/
template<typename T, typename CUIT>
concept bool TextBidirectionalDecoder() {
return TextForwardDecoder<T, CUIT>()
&& ranges::BidirectionalIterator<CUIT>()
&& requires (
typename T::state_type &state,
CUIT &in_next,
CUIT in_end,
character_type_t<T> &c,
int &decoded_code_units)
{
{ T::rdecode(state, in_next, in_end, c, decoded_code_units) } -> bool;
};
}
/*
* Text random access decoder concept
*/
template<typename T, typename CUIT>
concept bool TextRandomAccessDecoder() {
return TextBidirectionalDecoder<T, CUIT>()
&& ranges::RandomAccessIterator<CUIT>()
&& text_detail::SameValue<int, T::min_code_units, T::max_code_units>()
&& std::is_empty<typename T::state_type>::value;
}
/*
* Text iterator concept
*/
template<typename T>
concept bool TextIterator() {
return ranges::Iterator<T>()
&& Character<ranges::value_type_t<T>>()
&& TextEncoding<encoding_type_t<T>>()
&& TextEncodingState<typename T::state_type>()
&& requires (const T ct) {
{ ct.state() } noexcept
-> const typename encoding_type_t<T>::state_type&;
};
}
/*
* Text sentinel concept
*/
template<typename T, typename I>
concept bool TextSentinel() {
return ranges::Sentinel<T, I>()
&& TextIterator<I>();
}
/*
* Text output iterator concept
*/
template<typename T>
concept bool TextOutputIterator() {
return ranges::OutputIterator<T, character_type_t<encoding_type_t<T>>>()
&& TextEncoding<encoding_type_t<T>>()
&& TextEncodingState<typename T::state_type>()
&& requires (const T ct) {
{ ct.state() } noexcept
-> const typename encoding_type_t<T>::state_type&;
};
}
/*
* Text input iterator concept
*/
template<typename T>
concept bool TextInputIterator() {
return TextIterator<T>()
&& ranges::InputIterator<T>();
}
/*
* Text forward iterator concept
*/
template<typename T>
concept bool TextForwardIterator() {
return TextInputIterator<T>()
&& ranges::ForwardIterator<T>();
}
/*
* Text bidirectional iterator concept
*/
template<typename T>
concept bool TextBidirectionalIterator() {
return TextForwardIterator<T>()
&& ranges::BidirectionalIterator<T>();
}
/*
* Text random access iterator concept
*/
template<typename T>
concept bool TextRandomAccessIterator() {
return TextBidirectionalIterator<T>()
&& ranges::RandomAccessIterator<T>();
}
/*
* Text view concept
*/
template<typename T>
concept bool TextView() {
return ranges::View<T>()
&& TextIterator<ranges::iterator_t<T>>()
&& TextEncoding<encoding_type_t<T>>()
&& ranges::View<typename T::view_type>()
&& TextEncodingState<typename T::state_type>()
&& CodeUnitIterator<typename T::code_unit_iterator>()
&& requires (T t, const T ct) {
{ t.base() } noexcept
-> typename T::view_type&;
{ ct.base() } noexcept
-> const typename T::view_type&;
{ ct.initial_state() } noexcept
-> const typename T::state_type&;
};
}
/*
* Text input view concept
*/
template<typename T>
concept bool TextInputView() {
return TextView<T>()
&& TextInputIterator<ranges::iterator_t<T>>();
}
/*
* Text forward view concept
*/
template<typename T>
concept bool TextForwardView() {
return TextInputView<T>()
&& TextForwardIterator<ranges::iterator_t<T>>();
}
/*
* Text bidirectional view concept
*/
template<typename T>
concept bool TextBidirectionalView() {
return TextForwardView<T>()
&& TextBidirectionalIterator<ranges::iterator_t<T>>();
}
/*
* Text random access view concept
*/
template<typename T>
concept bool TextRandomAccessView() {
return TextBidirectionalView<T>()
&& TextRandomAccessIterator<ranges::iterator_t<T>>();
}
} // inline namespace text
} // namespace experimental
} // namespace std
#endif // } TEXT_VIEW_CONCEPTS_HPP
<commit_msg>range-v3 port: Replaced variable templates with C++11 conforming function templates.<commit_after>// Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef TEXT_VIEW_CONCEPTS_HPP // {
#define TEXT_VIEW_CONCEPTS_HPP
#include <utility>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_traits.hpp>
#include <range/v3/utility/concepts.hpp>
#include <range/v3/utility/iterator_concepts.hpp>
#include <range/v3/utility/iterator_traits.hpp>
#include <text_view_detail/traits.hpp>
#include <text_view_detail/character_set_id.hpp>
namespace std {
namespace experimental {
inline namespace text {
namespace text_detail {
template<typename T, T t1, T t2>
concept bool SameValue() {
return t1 == t2;
}
// FIXME: gcc bug 67565, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67565
// FIXME: Compile time performance is negatively impacted by concept definitions
// FIXME: specified with disjunction constraints. Performance is significantly
// FIXME: improved by rewriting such constraints in terms of constexpr function
// FIXME: or variable templates. Rewriting the CodeUnit and CodePoint concepts
// FIXME: in terms of is_code_unit_v and is_code_point_v dropped build times
// FIXME: from 5m50s to 2m00s. Once the performance issues in the compiler are
// FIXME: addressed, is_code_unit_v and is_code_point_v can be removed and
// FIXME: the original CodeUnit and CodePoint concept definitions restored.
template<typename T>
constexpr bool is_code_unit() {
return std::is_integral<T>::value
&& (std::is_unsigned<T>::value
|| std::is_same<typename std::remove_cv<T>::type, char>::value
|| std::is_same<typename std::remove_cv<T>::type, wchar_t>::value);
}
template<typename T>
constexpr bool is_code_point() {
return std::is_integral<T>::value
&& (std::is_unsigned<T>::value
|| std::is_same<typename std::remove_cv<T>::type, char>::value
|| std::is_same<typename std::remove_cv<T>::type, wchar_t>::value);
}
} // text_detail namespace
/*
* Code unit concept
*/
template<typename T>
concept bool CodeUnit() {
return text_detail::is_code_unit_v<T>;
}
/*
* Code point concept
*/
template<typename T>
concept bool CodePoint() {
return text_detail::is_code_point_v<T>;
}
/*
* Character set concept
*/
template<typename T>
concept bool CharacterSet() {
return requires () {
{ T::get_name() } noexcept -> const char *;
}
&& CodePoint<code_point_type_t<T>>();
}
/*
* Character concept
*/
template<typename T>
concept bool Character() {
return CharacterSet<character_set_type_t<T>>()
&& ranges::Regular<T>()
&& requires (T t,
const T ct,
code_point_type_t<character_set_type_t<T>> cp)
{
t.set_code_point(cp);
{ ct.get_code_point() } noexcept
-> code_point_type_t<character_set_type_t<T>>;
{ ct.get_character_set_id() }
-> character_set_id;
};
}
/*
* Code unit iterator concept
*/
template<typename T>
concept bool CodeUnitIterator() {
return ranges::Iterator<T>()
&& CodeUnit<ranges::value_type_t<T>>();
}
/*
* Code unit output iterator concept
*/
template<typename T, typename V>
concept bool CodeUnitOutputIterator() {
return ranges::OutputIterator<T, V>()
&& CodeUnit<V>();
}
/*
* Text encoding state concept
* These requirements are intended to match the char_traits<T>::state_type
* requirements described in C++11 [char.traits.typedefs] 21.2.2p4.
*/
template<typename T>
concept bool TextEncodingState() {
return ranges::Semiregular<T>();
}
/*
* Text encoding state transition concept
*/
template<typename T>
concept bool TextEncodingStateTransition() {
return ranges::Semiregular<T>();
}
/*
* Text encoding concept
*/
template<typename T>
concept bool TextEncoding() {
return requires () {
{ T::min_code_units } noexcept -> int;
{ T::max_code_units } noexcept -> int;
}
&& TextEncodingState<typename T::state_type>()
&& TextEncodingStateTransition<typename T::state_transition_type>()
&& CodeUnit<code_unit_type_t<T>>()
&& Character<character_type_t<T>>()
&& requires () {
{ T::initial_state() } noexcept
-> const typename T::state_type&;
};
}
/*
* Text encoder concept
*/
template<typename T, typename CUIT>
concept bool TextEncoder() {
return TextEncoding<T>()
&& CodeUnitOutputIterator<CUIT, code_unit_type_t<T>>()
&& requires (
typename T::state_type &state,
CUIT &out,
typename T::state_transition_type stt,
int &encoded_code_units)
{
T::encode_state_transition(state, out, stt, encoded_code_units);
}
&& requires (
typename T::state_type &state,
CUIT &out,
character_type_t<T> c,
int &encoded_code_units)
{
T::encode(state, out, c, encoded_code_units);
};
}
/*
* Text decoder concept
*/
template<typename T, typename CUIT>
concept bool TextDecoder() {
return TextEncoding<T>()
&& ranges::InputIterator<CUIT>()
&& ranges::ConvertibleTo<ranges::value_type_t<CUIT>,
code_unit_type_t<T>>()
&& requires (
typename T::state_type &state,
CUIT &in_next,
CUIT in_end,
character_type_t<T> &c,
int &decoded_code_units)
{
{ T::decode(state, in_next, in_end, c, decoded_code_units) } -> bool;
};
}
/*
* Text forward decoder concept
*/
template<typename T, typename CUIT>
concept bool TextForwardDecoder() {
return TextDecoder<T, CUIT>()
&& ranges::ForwardIterator<CUIT>();
}
/*
* Text bidirectional decoder concept
*/
template<typename T, typename CUIT>
concept bool TextBidirectionalDecoder() {
return TextForwardDecoder<T, CUIT>()
&& ranges::BidirectionalIterator<CUIT>()
&& requires (
typename T::state_type &state,
CUIT &in_next,
CUIT in_end,
character_type_t<T> &c,
int &decoded_code_units)
{
{ T::rdecode(state, in_next, in_end, c, decoded_code_units) } -> bool;
};
}
/*
* Text random access decoder concept
*/
template<typename T, typename CUIT>
concept bool TextRandomAccessDecoder() {
return TextBidirectionalDecoder<T, CUIT>()
&& ranges::RandomAccessIterator<CUIT>()
&& text_detail::SameValue<int, T::min_code_units, T::max_code_units>()
&& std::is_empty<typename T::state_type>::value;
}
/*
* Text iterator concept
*/
template<typename T>
concept bool TextIterator() {
return ranges::Iterator<T>()
&& Character<ranges::value_type_t<T>>()
&& TextEncoding<encoding_type_t<T>>()
&& TextEncodingState<typename T::state_type>()
&& requires (const T ct) {
{ ct.state() } noexcept
-> const typename encoding_type_t<T>::state_type&;
};
}
/*
* Text sentinel concept
*/
template<typename T, typename I>
concept bool TextSentinel() {
return ranges::Sentinel<T, I>()
&& TextIterator<I>();
}
/*
* Text output iterator concept
*/
template<typename T>
concept bool TextOutputIterator() {
return ranges::OutputIterator<T, character_type_t<encoding_type_t<T>>>()
&& TextEncoding<encoding_type_t<T>>()
&& TextEncodingState<typename T::state_type>()
&& requires (const T ct) {
{ ct.state() } noexcept
-> const typename encoding_type_t<T>::state_type&;
};
}
/*
* Text input iterator concept
*/
template<typename T>
concept bool TextInputIterator() {
return TextIterator<T>()
&& ranges::InputIterator<T>();
}
/*
* Text forward iterator concept
*/
template<typename T>
concept bool TextForwardIterator() {
return TextInputIterator<T>()
&& ranges::ForwardIterator<T>();
}
/*
* Text bidirectional iterator concept
*/
template<typename T>
concept bool TextBidirectionalIterator() {
return TextForwardIterator<T>()
&& ranges::BidirectionalIterator<T>();
}
/*
* Text random access iterator concept
*/
template<typename T>
concept bool TextRandomAccessIterator() {
return TextBidirectionalIterator<T>()
&& ranges::RandomAccessIterator<T>();
}
/*
* Text view concept
*/
template<typename T>
concept bool TextView() {
return ranges::View<T>()
&& TextIterator<ranges::iterator_t<T>>()
&& TextEncoding<encoding_type_t<T>>()
&& ranges::View<typename T::view_type>()
&& TextEncodingState<typename T::state_type>()
&& CodeUnitIterator<typename T::code_unit_iterator>()
&& requires (T t, const T ct) {
{ t.base() } noexcept
-> typename T::view_type&;
{ ct.base() } noexcept
-> const typename T::view_type&;
{ ct.initial_state() } noexcept
-> const typename T::state_type&;
};
}
/*
* Text input view concept
*/
template<typename T>
concept bool TextInputView() {
return TextView<T>()
&& TextInputIterator<ranges::iterator_t<T>>();
}
/*
* Text forward view concept
*/
template<typename T>
concept bool TextForwardView() {
return TextInputView<T>()
&& TextForwardIterator<ranges::iterator_t<T>>();
}
/*
* Text bidirectional view concept
*/
template<typename T>
concept bool TextBidirectionalView() {
return TextForwardView<T>()
&& TextBidirectionalIterator<ranges::iterator_t<T>>();
}
/*
* Text random access view concept
*/
template<typename T>
concept bool TextRandomAccessView() {
return TextBidirectionalView<T>()
&& TextRandomAccessIterator<ranges::iterator_t<T>>();
}
} // inline namespace text
} // namespace experimental
} // namespace std
#endif // } TEXT_VIEW_CONCEPTS_HPP
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_CONFIG_HPP
#define XSIMD_CONFIG_HPP
#include "xsimd_align.hpp"
#define XSIMD_VERSION_MAJOR 7
#define XSIMD_VERSION_MINOR 4
#define XSIMD_VERSION_PATCH 7
#ifndef XSIMD_DEFAULT_ALLOCATOR
#if XSIMD_X86_INSTR_SET_AVAILABLE
#define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT>
#else
#define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T>
#endif
#endif
#ifndef XSIMD_STACK_ALLOCATION_LIMIT
#define XSIMD_STACK_ALLOCATION_LIMIT 20000
#endif
#if defined(__LP64__) || defined(_WIN64)
#define XSIMD_64_BIT_ABI
#else
#define XSIMD_32_BIT_ABI
#endif
#endif
<commit_msg>Release 7.4.8<commit_after>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_CONFIG_HPP
#define XSIMD_CONFIG_HPP
#include "xsimd_align.hpp"
#define XSIMD_VERSION_MAJOR 7
#define XSIMD_VERSION_MINOR 4
#define XSIMD_VERSION_PATCH 8
#ifndef XSIMD_DEFAULT_ALLOCATOR
#if XSIMD_X86_INSTR_SET_AVAILABLE
#define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT>
#else
#define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T>
#endif
#endif
#ifndef XSIMD_STACK_ALLOCATION_LIMIT
#define XSIMD_STACK_ALLOCATION_LIMIT 20000
#endif
#if defined(__LP64__) || defined(_WIN64)
#define XSIMD_64_BIT_ABI
#else
#define XSIMD_32_BIT_ABI
#endif
#endif
<|endoftext|> |
<commit_before>#include "ride/wx.h"
#include <wx/stc/stc.h>
#include <wx/aui/aui.h>
#include <wx/filename.h>
#include "ride/mainwindow.h"
#include "ride/fileedit.h"
#include "ride/settingsdlg.h"
enum
{
ID_FIRST = wxID_HIGHEST,
ID_FILE_RIDE_SETTINGS,
ID_EDIT_MATCH_BRACE,
ID_EDIT_SELECT_BRACE,
ID_EDIT_GOTO_LINE,
ID_EDIT_SELECT_LINE,
ID_EDIT_TOUPPER,
ID_EDIT_TOLOWER,
ID_EDIT_MOVELINESUP,
ID_EDIT_MOVELINESDOWN,
ID_EDIT_SHOW_PROPERTIES,
ID_PROJECT_NEW,
ID_PROJECT_OPEN,
ID_PROJECT_SETTINGS,
ID_PROJECT_BUILD,
ID_PROJECT_CLEAN,
ID_PROJECT_REBUILD,
ID_PROJECT_DOC,
ID_PROJECT_RUN,
ID_PROJECT_TEST,
ID_PROJECT_BENCH,
ID_PROJECT_UPDATE
};
wxBEGIN_EVENT_TABLE(MainWindow, wxFrame)
EVT_MENU(wxID_OPEN , MainWindow::OnFileOpen)
EVT_MENU(wxID_EXIT , MainWindow::OnFileExit)
EVT_MENU(ID_FILE_RIDE_SETTINGS , MainWindow::OnFileShowSettings)
EVT_MENU(wxID_SAVE , MainWindow::OnFileSave)
EVT_MENU(wxID_SAVEAS , MainWindow::OnFileSaveAs)
EVT_MENU(wxID_UNDO , MainWindow::OnEditUndo)
EVT_MENU(wxID_REDO , MainWindow::OnEditRedo)
EVT_MENU(wxID_CUT , MainWindow::OnEditCut)
EVT_MENU(wxID_COPY , MainWindow::OnEditCopy)
EVT_MENU(wxID_PASTE , MainWindow::OnEditPaste)
EVT_MENU(wxID_DUPLICATE , MainWindow::OnEditDuplicate)
EVT_MENU(wxID_DELETE , MainWindow::OnEditDelete)
EVT_MENU(wxID_FIND , MainWindow::OnEditFind)
EVT_MENU(wxID_REPLACE , MainWindow::OnEditReplace)
EVT_MENU(ID_EDIT_MATCH_BRACE , MainWindow::OnEditMatchBrace)
EVT_MENU(ID_EDIT_SELECT_BRACE , MainWindow::OnEditSelectBrace)
EVT_MENU(ID_EDIT_GOTO_LINE , MainWindow::OnEditGotoLine)
EVT_MENU(wxID_INDENT , MainWindow::OnEditIndent)
EVT_MENU(wxID_UNINDENT , MainWindow::OnEditUnIndent)
EVT_MENU(wxID_SELECTALL , MainWindow::OnEditSelectAll)
EVT_MENU(ID_EDIT_SELECT_LINE , MainWindow::OnEditSelectLine)
EVT_MENU(ID_EDIT_TOUPPER , MainWindow::OnEditToUpper)
EVT_MENU(ID_EDIT_TOLOWER , MainWindow::OnEditToLower)
EVT_MENU(ID_EDIT_MOVELINESUP , MainWindow::OnEditMoveLinesUp)
EVT_MENU(ID_EDIT_MOVELINESDOWN , MainWindow::OnEditMoveLinesDown)
EVT_MENU(ID_EDIT_SHOW_PROPERTIES, MainWindow::OnEditShowProperties)
EVT_MENU(ID_PROJECT_NEW , MainWindow::OnProjectNew )
EVT_MENU(ID_PROJECT_OPEN , MainWindow::OnProjectOpen )
EVT_MENU(ID_PROJECT_SETTINGS , MainWindow::OnProjectSettings)
EVT_MENU(ID_PROJECT_BUILD , MainWindow::OnProjectBuild )
EVT_MENU(ID_PROJECT_CLEAN , MainWindow::OnProjectClean )
EVT_MENU(ID_PROJECT_REBUILD , MainWindow::OnProjectRebuild )
EVT_MENU(ID_PROJECT_DOC , MainWindow::OnProjectDoc )
EVT_MENU(ID_PROJECT_RUN , MainWindow::OnProjectRun )
EVT_MENU(ID_PROJECT_TEST , MainWindow::OnProjectTest )
EVT_MENU(ID_PROJECT_BENCH , MainWindow::OnProjectBench )
EVT_MENU(ID_PROJECT_UPDATE , MainWindow::OnProjectUpdate )
EVT_MENU(wxID_ABOUT , MainWindow::OnAbout)
EVT_CLOSE(MainWindow::OnClose)
EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, MainWindow::OnNotebookPageClose)
EVT_AUINOTEBOOK_PAGE_CLOSED(wxID_ANY, MainWindow::OnNotebookPageClosed)
wxEND_EVENT_TABLE()
MainWindow::MainWindow(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
, output_window(new wxTextCtrl())
, project(output_window, wxEmptyString)
, title_(title)
{
aui.SetManagedWindow(this);
LoadSettings(settings);
//////////////////////////////////////////////////////////////////////////
wxMenu *menuFile = new wxMenu;
menuFile->Append(wxID_OPEN, "&Open...\tCtrl-O", "Open a file");
menuFile->Append(wxID_SAVE, "&Save...\tCtrl-S", "Save the file");
menuFile->Append(wxID_SAVEAS, "Save &as...\tCtrl-Shift-S", "Save the file as a new file");
menuFile->AppendSeparator();
menuFile->Append(ID_FILE_RIDE_SETTINGS, "S&ettings...", "Change the settings of RIDE");
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
//////////////////////////////////////////////////////////////////////////
wxMenu *menuEdit = new wxMenu;
menuEdit->Append(wxID_UNDO, "Undo\tCtrl-Z", "");
menuEdit->Append(wxID_REDO, "Redo\tCtrl-Shift-Z", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT, "Cut\tCtrl-X", "");
menuEdit->Append(wxID_COPY, "Copy\tCtrl-C", "");
menuEdit->Append(wxID_PASTE, "Paste\tCtrl-V", "");
menuEdit->Append(wxID_DUPLICATE, "Duplicate selection or line\tCtrl-D", "");
menuEdit->Append(wxID_DELETE, "Delete\tDel", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND, "Find\tCtrl-F", "");
// menuEdit->Append(wxID_OPEN, "Find next\tF3", "");
menuEdit->Append(wxID_REPLACE, "Replace\tCtrl-H", "");
// menuEdit->Append(wxID_OPEN, "Replace again\tShift-F4", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_MATCH_BRACE, "Match brace\tCtrl-M", "");
menuEdit->Append(ID_EDIT_SELECT_BRACE, "Select to matching brace\tCtrl-Shift-M", "");
menuEdit->Append(ID_EDIT_GOTO_LINE, "Goto line\tCtrl-G", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_INDENT, "Increase indent\tTab", "");
menuEdit->Append(wxID_UNINDENT, "Reduce indent\tShift-Tab", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_SELECTALL, "Select all\tCtrl-A", "");
menuEdit->Append(ID_EDIT_SELECT_LINE, "Select line\tCtrl-L", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_TOUPPER, "Make UPPERCASE\tCtrl-Shift-U", "");
menuEdit->Append(ID_EDIT_TOLOWER, "Make lowercase\tCtrl-U", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_MOVELINESUP, "Move selected lines up\tAlt-Up", "");
menuEdit->Append(ID_EDIT_MOVELINESDOWN, "Move selected lines down\tAlt-Down", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_SHOW_PROPERTIES, "File properties\tAlt-Enter", "");
//////////////////////////////////////////////////////////////////////////
wxMenu *menuProject = new wxMenu;
menuProject->Append(ID_PROJECT_NEW, "New project...", "Create a new cargo project");
menuProject->Append(ID_PROJECT_OPEN, "Open project...", "Open a existing cargo or ride project");
menuProject->Append(ID_PROJECT_SETTINGS, "Project settings...", "Change the ride project settings");
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_BUILD, "Build\tCtrl-B", "Compile the current project");
menuProject->Append(ID_PROJECT_CLEAN, "Clean", "Remove the target directory");
menuProject->Append(ID_PROJECT_REBUILD, "Rebuild\tCtrl-Shift-B", "Clean + Build");
menuProject->Append(ID_PROJECT_DOC, "Doc", "Build this project's and its dependencies' documentation");
menuProject->Append(ID_PROJECT_RUN, "Run\tF5", "Build and execute src/main.rs");
menuProject->Append(ID_PROJECT_TEST, "Test", "Run the tests");
menuProject->Append(ID_PROJECT_BENCH, "Bench", "Run the benchmarks");
menuProject->Append(ID_PROJECT_UPDATE, "Update", "Update dependencies listed in Cargo.lock");
//////////////////////////////////////////////////////////////////////////
wxMenu *menuHelp = new wxMenu;
menuHelp->Append(wxID_ABOUT);
//////////////////////////////////////////////////////////////////////////
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(menuFile, "&File");
menuBar->Append(menuEdit, "&Edit");
menuBar->Append(menuProject, "&Project");
menuBar->Append(menuHelp, "&Help");
SetMenuBar(menuBar);
CreateStatusBar();
SetStatusText("");
createNotebook();
// output
output_window->Create(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_MULTILINE | wxHSCROLL);
aui.AddPane(output_window, wxAuiPaneInfo().Name("output").Caption("Output").Bottom().CloseButton(false));
aui.Update();
updateTitle();
}
void MainWindow::createNotebook() {
wxSize client_size = GetClientSize();
wxAuiNotebook* ctrl = new wxAuiNotebook(this, wxID_ANY,
wxPoint(client_size.x, client_size.y),
wxSize(430, 200),
wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER);
ctrl->Freeze();
ctrl->Thaw();
notebook = ctrl;
aui.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).PaneBorder(false).CloseButton(false).Movable(false) );
}
const ride::Settings& MainWindow::getSettings() const {
return settings;
}
MainWindow::~MainWindow() {
aui.UnInit();
}
void MainWindow::OnFileExit(wxCommandEvent& event)
{
Close(true);
}
void MainWindow::OnAbout(wxCommandEvent& event)
{
wxMessageBox("Ride is a Rust IDE. It's named after concatenating R from rust and IDE.\nFor more information: https://github.com/madeso/ride", "About Ride", wxOK | wxICON_INFORMATION);
}
void MainWindow::OnFileOpen(wxCommandEvent& event)
{
wxFileDialog
openFileDialog(this, _("Open file"), "", "",
FILE_PATTERN, wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
if (openFileDialog.ShowModal() == wxID_CANCEL)
return;
wxArrayString paths;
openFileDialog.GetPaths(paths);
for (wxArrayString::iterator path = paths.begin(); path != paths.end(); ++path) {
wxFileName w(*path);
w.Normalize();
new FileEdit(notebook, this, "", w.GetFullPath());
}
}
FileEdit* MainWindow::getSelectedEditorNull() {
const int selected = notebook->GetSelection();
if (selected == -1) {
return NULL;
}
wxWindow* window = notebook->GetPage(selected);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
return edit;
}
else {
return NULL;
}
}
void MainWindow::OnNotebookPageClose(wxAuiNotebookEvent& evt) {
wxWindow* window = notebook->GetPage(evt.GetSelection());
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
if (edit->canClose(true) == false) {
evt.Veto();
}
}
}
void MainWindow::OnClose(wxCloseEvent& evt) {
for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
wxWindow* window = notebook->GetPage(i);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
const bool canAbort = evt.CanVeto();
if (edit->canClose(canAbort) == false) {
evt.Veto();
return;
}
}
}
// shutdown protobuf now, to avoid spewing out memory leaks...
google::protobuf::ShutdownProtobufLibrary();
evt.Skip();
}
void MainWindow::setSettings(const ride::Settings& settings) {
assert(this);
this->settings = settings;
updateAllEdits();
}
void MainWindow::OnNotebookPageClosed(wxAuiNotebookEvent& evt) {
}
void MainWindow::updateAllEdits() {
for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
wxWindow* window = notebook->GetPage(i);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
edit->UpdateTextControl();
}
}
}
void MainWindow::OnFileShowSettings(wxCommandEvent& event) {
SettingsDlg settingsdlg(this, this);
settingsdlg.ShowModal();
}
void MainWindow::OnFileSave(wxCommandEvent& event) {
FileEdit* selected = getSelectedEditorNull();
if (selected == NULL) return;
selected->Save();
}
void MainWindow::OnFileSaveAs(wxCommandEvent& event) {
FileEdit* selected = getSelectedEditorNull();
if (selected == NULL) return;
selected->SaveAs();
}
//////////////////////////////////////////////////////////////////////////
#define MEM_FUN(X) \
void MainWindow::OnEdit ## X(wxCommandEvent& event) {\
FileEdit* selected = getSelectedEditorNull();\
if (selected == NULL) return;\
selected->X();\
}
MEM_FUN(Undo)
MEM_FUN(Redo)
MEM_FUN(Cut)
MEM_FUN(Copy)
MEM_FUN(Paste)
MEM_FUN(Duplicate)
MEM_FUN(Delete)
MEM_FUN(Find)
MEM_FUN(Replace)
MEM_FUN(MatchBrace)
MEM_FUN(SelectBrace)
MEM_FUN(GotoLine)
MEM_FUN(Indent)
MEM_FUN(UnIndent)
MEM_FUN(SelectAll)
MEM_FUN(SelectLine)
MEM_FUN(ToUpper)
MEM_FUN(ToLower)
MEM_FUN(MoveLinesUp)
MEM_FUN(MoveLinesDown)
MEM_FUN(ShowProperties)
#undef MEM_FUN
//////////////////////////////////////////////////////////////////////////
void MainWindow::updateTitle() {
const wxString new_title = project.root_folder().IsEmpty()
? title_
// todo: only display project folder name instead of the whole path?
: wxString::Format("%s - %s", project.root_folder(), title_);
this->SetTitle(new_title);
}
void MainWindow::OnProjectNew(wxCommandEvent& event) {
// todo: implement me
updateTitle();
}
void MainWindow::OnProjectOpen(wxCommandEvent& event) {
wxFileDialog
openFileDialog(this, _("Open project"), "", "",
"Cargo files|Cargo.toml", wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (openFileDialog.ShowModal() == wxID_CANCEL)
return;
wxFileName file(openFileDialog.GetPath());
file.Normalize();
project = Project(output_window, file.GetPathWithSep());
updateTitle();
}
#define MEM_FUN(X) \
void MainWindow::OnProject ## X(wxCommandEvent& event) {\
project. ## X ();\
}
MEM_FUN(Settings)
MEM_FUN(Build )
MEM_FUN(Clean )
MEM_FUN(Rebuild )
MEM_FUN(Doc )
MEM_FUN(Run )
MEM_FUN(Test )
MEM_FUN(Bench )
MEM_FUN(Update )
#undef MEM_FUN<commit_msg>Fixed width in output<commit_after>#include "ride/wx.h"
#include <wx/stc/stc.h>
#include <wx/aui/aui.h>
#include <wx/filename.h>
#include "ride/mainwindow.h"
#include "ride/fileedit.h"
#include "ride/settingsdlg.h"
enum
{
ID_FIRST = wxID_HIGHEST,
ID_FILE_RIDE_SETTINGS,
ID_EDIT_MATCH_BRACE,
ID_EDIT_SELECT_BRACE,
ID_EDIT_GOTO_LINE,
ID_EDIT_SELECT_LINE,
ID_EDIT_TOUPPER,
ID_EDIT_TOLOWER,
ID_EDIT_MOVELINESUP,
ID_EDIT_MOVELINESDOWN,
ID_EDIT_SHOW_PROPERTIES,
ID_PROJECT_NEW,
ID_PROJECT_OPEN,
ID_PROJECT_SETTINGS,
ID_PROJECT_BUILD,
ID_PROJECT_CLEAN,
ID_PROJECT_REBUILD,
ID_PROJECT_DOC,
ID_PROJECT_RUN,
ID_PROJECT_TEST,
ID_PROJECT_BENCH,
ID_PROJECT_UPDATE
};
wxBEGIN_EVENT_TABLE(MainWindow, wxFrame)
EVT_MENU(wxID_OPEN , MainWindow::OnFileOpen)
EVT_MENU(wxID_EXIT , MainWindow::OnFileExit)
EVT_MENU(ID_FILE_RIDE_SETTINGS , MainWindow::OnFileShowSettings)
EVT_MENU(wxID_SAVE , MainWindow::OnFileSave)
EVT_MENU(wxID_SAVEAS , MainWindow::OnFileSaveAs)
EVT_MENU(wxID_UNDO , MainWindow::OnEditUndo)
EVT_MENU(wxID_REDO , MainWindow::OnEditRedo)
EVT_MENU(wxID_CUT , MainWindow::OnEditCut)
EVT_MENU(wxID_COPY , MainWindow::OnEditCopy)
EVT_MENU(wxID_PASTE , MainWindow::OnEditPaste)
EVT_MENU(wxID_DUPLICATE , MainWindow::OnEditDuplicate)
EVT_MENU(wxID_DELETE , MainWindow::OnEditDelete)
EVT_MENU(wxID_FIND , MainWindow::OnEditFind)
EVT_MENU(wxID_REPLACE , MainWindow::OnEditReplace)
EVT_MENU(ID_EDIT_MATCH_BRACE , MainWindow::OnEditMatchBrace)
EVT_MENU(ID_EDIT_SELECT_BRACE , MainWindow::OnEditSelectBrace)
EVT_MENU(ID_EDIT_GOTO_LINE , MainWindow::OnEditGotoLine)
EVT_MENU(wxID_INDENT , MainWindow::OnEditIndent)
EVT_MENU(wxID_UNINDENT , MainWindow::OnEditUnIndent)
EVT_MENU(wxID_SELECTALL , MainWindow::OnEditSelectAll)
EVT_MENU(ID_EDIT_SELECT_LINE , MainWindow::OnEditSelectLine)
EVT_MENU(ID_EDIT_TOUPPER , MainWindow::OnEditToUpper)
EVT_MENU(ID_EDIT_TOLOWER , MainWindow::OnEditToLower)
EVT_MENU(ID_EDIT_MOVELINESUP , MainWindow::OnEditMoveLinesUp)
EVT_MENU(ID_EDIT_MOVELINESDOWN , MainWindow::OnEditMoveLinesDown)
EVT_MENU(ID_EDIT_SHOW_PROPERTIES, MainWindow::OnEditShowProperties)
EVT_MENU(ID_PROJECT_NEW , MainWindow::OnProjectNew )
EVT_MENU(ID_PROJECT_OPEN , MainWindow::OnProjectOpen )
EVT_MENU(ID_PROJECT_SETTINGS , MainWindow::OnProjectSettings)
EVT_MENU(ID_PROJECT_BUILD , MainWindow::OnProjectBuild )
EVT_MENU(ID_PROJECT_CLEAN , MainWindow::OnProjectClean )
EVT_MENU(ID_PROJECT_REBUILD , MainWindow::OnProjectRebuild )
EVT_MENU(ID_PROJECT_DOC , MainWindow::OnProjectDoc )
EVT_MENU(ID_PROJECT_RUN , MainWindow::OnProjectRun )
EVT_MENU(ID_PROJECT_TEST , MainWindow::OnProjectTest )
EVT_MENU(ID_PROJECT_BENCH , MainWindow::OnProjectBench )
EVT_MENU(ID_PROJECT_UPDATE , MainWindow::OnProjectUpdate )
EVT_MENU(wxID_ABOUT , MainWindow::OnAbout)
EVT_CLOSE(MainWindow::OnClose)
EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, MainWindow::OnNotebookPageClose)
EVT_AUINOTEBOOK_PAGE_CLOSED(wxID_ANY, MainWindow::OnNotebookPageClosed)
wxEND_EVENT_TABLE()
MainWindow::MainWindow(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
, output_window(new wxTextCtrl())
, project(output_window, wxEmptyString)
, title_(title)
{
aui.SetManagedWindow(this);
LoadSettings(settings);
//////////////////////////////////////////////////////////////////////////
wxMenu *menuFile = new wxMenu;
menuFile->Append(wxID_OPEN, "&Open...\tCtrl-O", "Open a file");
menuFile->Append(wxID_SAVE, "&Save...\tCtrl-S", "Save the file");
menuFile->Append(wxID_SAVEAS, "Save &as...\tCtrl-Shift-S", "Save the file as a new file");
menuFile->AppendSeparator();
menuFile->Append(ID_FILE_RIDE_SETTINGS, "S&ettings...", "Change the settings of RIDE");
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
//////////////////////////////////////////////////////////////////////////
wxMenu *menuEdit = new wxMenu;
menuEdit->Append(wxID_UNDO, "Undo\tCtrl-Z", "");
menuEdit->Append(wxID_REDO, "Redo\tCtrl-Shift-Z", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT, "Cut\tCtrl-X", "");
menuEdit->Append(wxID_COPY, "Copy\tCtrl-C", "");
menuEdit->Append(wxID_PASTE, "Paste\tCtrl-V", "");
menuEdit->Append(wxID_DUPLICATE, "Duplicate selection or line\tCtrl-D", "");
menuEdit->Append(wxID_DELETE, "Delete\tDel", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND, "Find\tCtrl-F", "");
// menuEdit->Append(wxID_OPEN, "Find next\tF3", "");
menuEdit->Append(wxID_REPLACE, "Replace\tCtrl-H", "");
// menuEdit->Append(wxID_OPEN, "Replace again\tShift-F4", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_MATCH_BRACE, "Match brace\tCtrl-M", "");
menuEdit->Append(ID_EDIT_SELECT_BRACE, "Select to matching brace\tCtrl-Shift-M", "");
menuEdit->Append(ID_EDIT_GOTO_LINE, "Goto line\tCtrl-G", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_INDENT, "Increase indent\tTab", "");
menuEdit->Append(wxID_UNINDENT, "Reduce indent\tShift-Tab", "");
menuEdit->AppendSeparator();
menuEdit->Append(wxID_SELECTALL, "Select all\tCtrl-A", "");
menuEdit->Append(ID_EDIT_SELECT_LINE, "Select line\tCtrl-L", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_TOUPPER, "Make UPPERCASE\tCtrl-Shift-U", "");
menuEdit->Append(ID_EDIT_TOLOWER, "Make lowercase\tCtrl-U", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_MOVELINESUP, "Move selected lines up\tAlt-Up", "");
menuEdit->Append(ID_EDIT_MOVELINESDOWN, "Move selected lines down\tAlt-Down", "");
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_SHOW_PROPERTIES, "File properties\tAlt-Enter", "");
//////////////////////////////////////////////////////////////////////////
wxMenu *menuProject = new wxMenu;
menuProject->Append(ID_PROJECT_NEW, "New project...", "Create a new cargo project");
menuProject->Append(ID_PROJECT_OPEN, "Open project...", "Open a existing cargo or ride project");
menuProject->Append(ID_PROJECT_SETTINGS, "Project settings...", "Change the ride project settings");
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_BUILD, "Build\tCtrl-B", "Compile the current project");
menuProject->Append(ID_PROJECT_CLEAN, "Clean", "Remove the target directory");
menuProject->Append(ID_PROJECT_REBUILD, "Rebuild\tCtrl-Shift-B", "Clean + Build");
menuProject->Append(ID_PROJECT_DOC, "Doc", "Build this project's and its dependencies' documentation");
menuProject->Append(ID_PROJECT_RUN, "Run\tF5", "Build and execute src/main.rs");
menuProject->Append(ID_PROJECT_TEST, "Test", "Run the tests");
menuProject->Append(ID_PROJECT_BENCH, "Bench", "Run the benchmarks");
menuProject->Append(ID_PROJECT_UPDATE, "Update", "Update dependencies listed in Cargo.lock");
//////////////////////////////////////////////////////////////////////////
wxMenu *menuHelp = new wxMenu;
menuHelp->Append(wxID_ABOUT);
//////////////////////////////////////////////////////////////////////////
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(menuFile, "&File");
menuBar->Append(menuEdit, "&Edit");
menuBar->Append(menuProject, "&Project");
menuBar->Append(menuHelp, "&Help");
SetMenuBar(menuBar);
CreateStatusBar();
SetStatusText("");
createNotebook();
// output
output_window->Create(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_MULTILINE | wxHSCROLL);
output_window->SetFont(wxFontInfo(10).Family(wxFONTFAMILY_TELETYPE));
aui.AddPane(output_window, wxAuiPaneInfo().Name("output").Caption("Output").Bottom().CloseButton(false));
aui.Update();
updateTitle();
}
void MainWindow::createNotebook() {
wxSize client_size = GetClientSize();
wxAuiNotebook* ctrl = new wxAuiNotebook(this, wxID_ANY,
wxPoint(client_size.x, client_size.y),
wxSize(430, 200),
wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER);
ctrl->Freeze();
ctrl->Thaw();
notebook = ctrl;
aui.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).PaneBorder(false).CloseButton(false).Movable(false) );
}
const ride::Settings& MainWindow::getSettings() const {
return settings;
}
MainWindow::~MainWindow() {
aui.UnInit();
}
void MainWindow::OnFileExit(wxCommandEvent& event)
{
Close(true);
}
void MainWindow::OnAbout(wxCommandEvent& event)
{
wxMessageBox("Ride is a Rust IDE. It's named after concatenating R from rust and IDE.\nFor more information: https://github.com/madeso/ride", "About Ride", wxOK | wxICON_INFORMATION);
}
void MainWindow::OnFileOpen(wxCommandEvent& event)
{
wxFileDialog
openFileDialog(this, _("Open file"), "", "",
FILE_PATTERN, wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
if (openFileDialog.ShowModal() == wxID_CANCEL)
return;
wxArrayString paths;
openFileDialog.GetPaths(paths);
for (wxArrayString::iterator path = paths.begin(); path != paths.end(); ++path) {
wxFileName w(*path);
w.Normalize();
new FileEdit(notebook, this, "", w.GetFullPath());
}
}
FileEdit* MainWindow::getSelectedEditorNull() {
const int selected = notebook->GetSelection();
if (selected == -1) {
return NULL;
}
wxWindow* window = notebook->GetPage(selected);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
return edit;
}
else {
return NULL;
}
}
void MainWindow::OnNotebookPageClose(wxAuiNotebookEvent& evt) {
wxWindow* window = notebook->GetPage(evt.GetSelection());
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
if (edit->canClose(true) == false) {
evt.Veto();
}
}
}
void MainWindow::OnClose(wxCloseEvent& evt) {
for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
wxWindow* window = notebook->GetPage(i);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
const bool canAbort = evt.CanVeto();
if (edit->canClose(canAbort) == false) {
evt.Veto();
return;
}
}
}
// shutdown protobuf now, to avoid spewing out memory leaks...
google::protobuf::ShutdownProtobufLibrary();
evt.Skip();
}
void MainWindow::setSettings(const ride::Settings& settings) {
assert(this);
this->settings = settings;
updateAllEdits();
}
void MainWindow::OnNotebookPageClosed(wxAuiNotebookEvent& evt) {
}
void MainWindow::updateAllEdits() {
for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
wxWindow* window = notebook->GetPage(i);
if (window->IsKindOf(CLASSINFO(FileEdit))) {
FileEdit* edit = reinterpret_cast<FileEdit*>(window);
edit->UpdateTextControl();
}
}
}
void MainWindow::OnFileShowSettings(wxCommandEvent& event) {
SettingsDlg settingsdlg(this, this);
settingsdlg.ShowModal();
}
void MainWindow::OnFileSave(wxCommandEvent& event) {
FileEdit* selected = getSelectedEditorNull();
if (selected == NULL) return;
selected->Save();
}
void MainWindow::OnFileSaveAs(wxCommandEvent& event) {
FileEdit* selected = getSelectedEditorNull();
if (selected == NULL) return;
selected->SaveAs();
}
//////////////////////////////////////////////////////////////////////////
#define MEM_FUN(X) \
void MainWindow::OnEdit ## X(wxCommandEvent& event) {\
FileEdit* selected = getSelectedEditorNull();\
if (selected == NULL) return;\
selected->X();\
}
MEM_FUN(Undo)
MEM_FUN(Redo)
MEM_FUN(Cut)
MEM_FUN(Copy)
MEM_FUN(Paste)
MEM_FUN(Duplicate)
MEM_FUN(Delete)
MEM_FUN(Find)
MEM_FUN(Replace)
MEM_FUN(MatchBrace)
MEM_FUN(SelectBrace)
MEM_FUN(GotoLine)
MEM_FUN(Indent)
MEM_FUN(UnIndent)
MEM_FUN(SelectAll)
MEM_FUN(SelectLine)
MEM_FUN(ToUpper)
MEM_FUN(ToLower)
MEM_FUN(MoveLinesUp)
MEM_FUN(MoveLinesDown)
MEM_FUN(ShowProperties)
#undef MEM_FUN
//////////////////////////////////////////////////////////////////////////
void MainWindow::updateTitle() {
const wxString new_title = project.root_folder().IsEmpty()
? title_
// todo: only display project folder name instead of the whole path?
: wxString::Format("%s - %s", project.root_folder(), title_);
this->SetTitle(new_title);
}
void MainWindow::OnProjectNew(wxCommandEvent& event) {
// todo: implement me
updateTitle();
}
void MainWindow::OnProjectOpen(wxCommandEvent& event) {
wxFileDialog
openFileDialog(this, _("Open project"), "", "",
"Cargo files|Cargo.toml", wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (openFileDialog.ShowModal() == wxID_CANCEL)
return;
wxFileName file(openFileDialog.GetPath());
file.Normalize();
project = Project(output_window, file.GetPathWithSep());
updateTitle();
}
#define MEM_FUN(X) \
void MainWindow::OnProject ## X(wxCommandEvent& event) {\
project. ## X ();\
}
MEM_FUN(Settings)
MEM_FUN(Build )
MEM_FUN(Clean )
MEM_FUN(Rebuild )
MEM_FUN(Doc )
MEM_FUN(Run )
MEM_FUN(Test )
MEM_FUN(Bench )
MEM_FUN(Update )
#undef MEM_FUN<|endoftext|> |
<commit_before>#include <iostream>
#include <functional>
#include <atomic>
#include <future>
#include "dronecode_sdk.h"
#include "system.h"
#include "integration_test_helper.h"
#include "camera_test_helpers.h"
using namespace dronecode_sdk;
using namespace std::placeholders; // for `_1`
// To run specific tests for Yuneec cameras.
const static bool is_e90 = false;
const static bool is_e50 = false;
const static bool is_et = false;
TEST(CameraTest, ShowSettingsAndOptions)
{
DronecodeSDK dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// Wait for download to happen.
std::this_thread::sleep_for(std::chrono::seconds(2));
if (is_e90 || is_e50 || is_et) {
// Set to photo mode
set_mode_async(camera, Camera::Mode::PHOTO);
std::vector<std::string> settings;
EXPECT_TRUE(camera->get_possible_setting_options(settings));
LogDebug() << "Possible settings in photo mode: ";
for (auto setting : settings) {
LogDebug() << "- " << setting;
}
if (is_e90) {
EXPECT_EQ(settings.size(), 9);
} else if (is_e50) {
EXPECT_EQ(settings.size(), 6);
} else if (is_et) {
EXPECT_EQ(settings.size(), 5);
}
set_mode_async(camera, Camera::Mode::VIDEO);
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_TRUE(camera->get_possible_setting_options(settings));
LogDebug() << "Possible settings in video mode: ";
for (auto setting : settings) {
LogDebug() << "-" << setting;
}
if (is_e90) {
EXPECT_EQ(settings.size(), 6);
} else if (is_e50) {
EXPECT_EQ(settings.size(), 5);
} else if (is_et) {
EXPECT_EQ(settings.size(), 5);
}
std::vector<Camera::Option> options;
if (is_e90) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 32);
} else if (is_e50) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 12);
}
if (is_e90) {
// This param is not applicable, so we should get an empty vector back.
EXPECT_FALSE(camera->get_possible_options("CAM_PHOTOQUAL", options));
EXPECT_EQ(options.size(), 0);
}
// The same should happen with a param that does not exist at all.
EXPECT_FALSE(camera->get_possible_options("CAM_BLABLA", options));
EXPECT_EQ(options.size(), 0);
set_mode_async(camera, Camera::Mode::PHOTO);
if (is_e90) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_PHOTOQUAL", options));
EXPECT_EQ(options.size(), 4);
}
// This param is not applicable, so we should get an empty vector back.
EXPECT_FALSE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 0);
// The same should happen with a param that does not exist at all.
EXPECT_FALSE(camera->get_possible_options("CAM_BLABLA", options));
EXPECT_EQ(options.size(), 0);
}
}
TEST(CameraTest, SetSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
set_mode_async(camera, Camera::Mode::PHOTO);
// Try setting garbage first
EXPECT_EQ(set_setting(camera, "DOES_NOT", "EXIST"), Camera::Result::ERROR);
if (is_e90) {
std::string value_set;
EXPECT_EQ(set_setting(camera, "CAM_PHOTOQUAL", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_PHOTOQUAL", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
EXPECT_EQ(set_setting(camera, "CAM_COLORMODE", "5"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_COLORMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("5", value_set.c_str());
// Let's check the manual exposure mode first.
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
// We should now be able to set shutter speed and ISO.
std::vector<Camera::Option> options;
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 19);
EXPECT_TRUE(camera->get_possible_options("CAM_ISO", options));
EXPECT_EQ(options.size(), 10);
// But not EV and metering
EXPECT_FALSE(camera->get_possible_options("CAM_EV", options));
EXPECT_EQ(options.size(), 0);
EXPECT_FALSE(camera->get_possible_options("CAM_METERING", options));
EXPECT_EQ(options.size(), 0);
// Now we'll try the same for Auto exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_FALSE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 0);
EXPECT_FALSE(camera->get_possible_options("CAM_ISO", options));
EXPECT_EQ(options.size(), 0);
// But not EV and metering
EXPECT_TRUE(camera->get_possible_options("CAM_EV", options));
EXPECT_EQ(options.size(), 13);
EXPECT_TRUE(camera->get_possible_options("CAM_METERING", options));
EXPECT_EQ(options.size(), 3);
set_mode_async(camera, Camera::Mode::VIDEO);
// This should fail in video mode.
EXPECT_EQ(set_setting(camera, "CAM_PHOTOQUAL", "1"), Camera::Result::ERROR);
// Let's check the manual exposure mode first.
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
// FIXME: otherwise the camera is too slow
std::this_thread::sleep_for(std::chrono::seconds(1));
// But a video setting should work
EXPECT_EQ(set_setting(camera, "CAM_VIDRES", "30"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_VIDRES", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("30", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 15);
// FIXME: otherwise the camera is too slow
std::this_thread::sleep_for(std::chrono::seconds(1));
// But a video setting should work
EXPECT_EQ(set_setting(camera, "CAM_VIDRES", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_VIDRES", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 12);
// Back to auto exposure mode
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
}
}
static void receive_current_settings(bool &subscription_called,
const std::vector<Camera::Setting> settings)
{
LogDebug() << "Received current options:";
EXPECT_TRUE(settings.size() > 0);
for (auto &setting : settings) {
LogDebug() << "Got setting '" << setting.setting_description << "' with selected option '"
<< setting.option.option_description << "'";
// Check human readable strings too.
if (setting.setting_id == "CAM_SHUTTERSPD") {
EXPECT_STREQ(setting.setting_description.c_str(), "Shutter Speed");
} else if (setting.setting_id == "CAM_EXPMODE") {
EXPECT_STREQ(setting.setting_description.c_str(), "Exposure Mode");
}
}
subscription_called = true;
}
TEST(CameraTest, SubscribeCurrentSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
// Reset exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
bool subscription_called = false;
camera->subscribe_current_settings(
std::bind(receive_current_settings, std::ref(subscription_called), _1));
EXPECT_EQ(camera->set_mode(Camera::Mode::PHOTO), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
subscription_called = false;
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
}
static void
receive_possible_setting_options(bool &subscription_called,
const std::vector<Camera::SettingOptions> settings_options)
{
LogDebug() << "Received possible options:";
EXPECT_TRUE(settings_options.size() > 0);
for (auto &setting_options : settings_options) {
LogDebug() << "Got setting '" << setting_options.setting_description << "' with options:";
// Check human readable strings too.
if (setting_options.setting_id == "CAM_SHUTTERSPD") {
EXPECT_STREQ(setting_options.setting_description.c_str(), "Shutter Speed");
} else if (setting_options.setting_id == "CAM_EXPMODE") {
EXPECT_STREQ(setting_options.setting_description.c_str(), "Exposure Mode");
}
EXPECT_TRUE(setting_options.options.size() > 0);
for (auto &option : setting_options.options) {
LogDebug() << " - '" << option.option_description << "'";
if (setting_options.setting_id == "CAM_SHUTTERSPD" && option.option_id == "0.0025") {
EXPECT_STREQ(option.option_description.c_str(), "1/400");
} else if (setting_options.setting_id == "CAM_WBMODE" && option.option_id == "2") {
EXPECT_STREQ(option.option_description.c_str(), "Sunrise");
}
}
}
subscription_called = true;
}
TEST(CameraTest, SubscribePossibleSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
// Reset exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
bool subscription_called = false;
camera->subscribe_possible_setting_options(
std::bind(receive_possible_setting_options, std::ref(subscription_called), _1));
EXPECT_EQ(camera->set_mode(Camera::Mode::PHOTO), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
subscription_called = false;
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
}
<commit_msg>camera: the number of settings must have changed<commit_after>#include <iostream>
#include <functional>
#include <atomic>
#include <future>
#include "dronecode_sdk.h"
#include "system.h"
#include "integration_test_helper.h"
#include "camera_test_helpers.h"
using namespace dronecode_sdk;
using namespace std::placeholders; // for `_1`
// To run specific tests for Yuneec cameras.
const static bool is_e90 = false;
const static bool is_e50 = false;
const static bool is_et = false;
TEST(CameraTest, ShowSettingsAndOptions)
{
DronecodeSDK dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// Wait for download to happen.
std::this_thread::sleep_for(std::chrono::seconds(2));
if (is_e90 || is_e50 || is_et) {
// Set to photo mode
set_mode_async(camera, Camera::Mode::PHOTO);
std::vector<std::string> settings;
EXPECT_TRUE(camera->get_possible_setting_options(settings));
LogDebug() << "Possible settings in photo mode: ";
for (auto setting : settings) {
LogDebug() << "- " << setting;
}
if (is_e90) {
EXPECT_EQ(settings.size(), 9);
} else if (is_e50) {
EXPECT_EQ(settings.size(), 6);
} else if (is_et) {
EXPECT_EQ(settings.size(), 5);
}
set_mode_async(camera, Camera::Mode::VIDEO);
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_TRUE(camera->get_possible_setting_options(settings));
LogDebug() << "Possible settings in video mode: ";
for (auto setting : settings) {
LogDebug() << "-" << setting;
}
if (is_e90) {
EXPECT_EQ(settings.size(), 7);
} else if (is_e50) {
EXPECT_EQ(settings.size(), 5);
} else if (is_et) {
EXPECT_EQ(settings.size(), 5);
}
std::vector<Camera::Option> options;
if (is_e90) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 32);
} else if (is_e50) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 12);
}
if (is_e90) {
// This param is not applicable, so we should get an empty vector back.
EXPECT_FALSE(camera->get_possible_options("CAM_PHOTOQUAL", options));
EXPECT_EQ(options.size(), 0);
}
// The same should happen with a param that does not exist at all.
EXPECT_FALSE(camera->get_possible_options("CAM_BLABLA", options));
EXPECT_EQ(options.size(), 0);
set_mode_async(camera, Camera::Mode::PHOTO);
if (is_e90) {
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_PHOTOQUAL", options));
EXPECT_EQ(options.size(), 4);
}
// This param is not applicable, so we should get an empty vector back.
EXPECT_FALSE(camera->get_possible_options("CAM_VIDRES", options));
EXPECT_EQ(options.size(), 0);
// The same should happen with a param that does not exist at all.
EXPECT_FALSE(camera->get_possible_options("CAM_BLABLA", options));
EXPECT_EQ(options.size(), 0);
}
}
TEST(CameraTest, SetSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
set_mode_async(camera, Camera::Mode::PHOTO);
// Try setting garbage first
EXPECT_EQ(set_setting(camera, "DOES_NOT", "EXIST"), Camera::Result::ERROR);
if (is_e90) {
std::string value_set;
EXPECT_EQ(set_setting(camera, "CAM_PHOTOQUAL", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_PHOTOQUAL", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
EXPECT_EQ(set_setting(camera, "CAM_COLORMODE", "5"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_COLORMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("5", value_set.c_str());
// Let's check the manual exposure mode first.
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
// We should now be able to set shutter speed and ISO.
std::vector<Camera::Option> options;
// Try something that is specific to the camera mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 19);
EXPECT_TRUE(camera->get_possible_options("CAM_ISO", options));
EXPECT_EQ(options.size(), 10);
// But not EV and metering
EXPECT_FALSE(camera->get_possible_options("CAM_EV", options));
EXPECT_EQ(options.size(), 0);
EXPECT_FALSE(camera->get_possible_options("CAM_METERING", options));
EXPECT_EQ(options.size(), 0);
// Now we'll try the same for Auto exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_FALSE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 0);
EXPECT_FALSE(camera->get_possible_options("CAM_ISO", options));
EXPECT_EQ(options.size(), 0);
// But not EV and metering
EXPECT_TRUE(camera->get_possible_options("CAM_EV", options));
EXPECT_EQ(options.size(), 13);
EXPECT_TRUE(camera->get_possible_options("CAM_METERING", options));
EXPECT_EQ(options.size(), 3);
set_mode_async(camera, Camera::Mode::VIDEO);
// This should fail in video mode.
EXPECT_EQ(set_setting(camera, "CAM_PHOTOQUAL", "1"), Camera::Result::ERROR);
// Let's check the manual exposure mode first.
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("1", value_set.c_str());
// FIXME: otherwise the camera is too slow
std::this_thread::sleep_for(std::chrono::seconds(1));
// But a video setting should work
EXPECT_EQ(set_setting(camera, "CAM_VIDRES", "30"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_VIDRES", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("30", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 15);
// FIXME: otherwise the camera is too slow
std::this_thread::sleep_for(std::chrono::seconds(1));
// But a video setting should work
EXPECT_EQ(set_setting(camera, "CAM_VIDRES", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_VIDRES", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
// Shutter speed and ISO don't have options in Auto mode.
EXPECT_TRUE(camera->get_possible_options("CAM_SHUTTERSPD", options));
EXPECT_EQ(options.size(), 12);
// Back to auto exposure mode
std::this_thread::sleep_for(std::chrono::seconds(2));
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
EXPECT_EQ(get_setting(camera, "CAM_EXPMODE", value_set), Camera::Result::SUCCESS);
EXPECT_STREQ("0", value_set.c_str());
}
}
static void receive_current_settings(bool &subscription_called,
const std::vector<Camera::Setting> settings)
{
LogDebug() << "Received current options:";
EXPECT_TRUE(settings.size() > 0);
for (auto &setting : settings) {
LogDebug() << "Got setting '" << setting.setting_description << "' with selected option '"
<< setting.option.option_description << "'";
// Check human readable strings too.
if (setting.setting_id == "CAM_SHUTTERSPD") {
EXPECT_STREQ(setting.setting_description.c_str(), "Shutter Speed");
} else if (setting.setting_id == "CAM_EXPMODE") {
EXPECT_STREQ(setting.setting_description.c_str(), "Exposure Mode");
}
}
subscription_called = true;
}
TEST(CameraTest, SubscribeCurrentSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
// Reset exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
bool subscription_called = false;
camera->subscribe_current_settings(
std::bind(receive_current_settings, std::ref(subscription_called), _1));
EXPECT_EQ(camera->set_mode(Camera::Mode::PHOTO), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
subscription_called = false;
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
}
static void
receive_possible_setting_options(bool &subscription_called,
const std::vector<Camera::SettingOptions> settings_options)
{
LogDebug() << "Received possible options:";
EXPECT_TRUE(settings_options.size() > 0);
for (auto &setting_options : settings_options) {
LogDebug() << "Got setting '" << setting_options.setting_description << "' with options:";
// Check human readable strings too.
if (setting_options.setting_id == "CAM_SHUTTERSPD") {
EXPECT_STREQ(setting_options.setting_description.c_str(), "Shutter Speed");
} else if (setting_options.setting_id == "CAM_EXPMODE") {
EXPECT_STREQ(setting_options.setting_description.c_str(), "Exposure Mode");
}
EXPECT_TRUE(setting_options.options.size() > 0);
for (auto &option : setting_options.options) {
LogDebug() << " - '" << option.option_description << "'";
if (setting_options.setting_id == "CAM_SHUTTERSPD" && option.option_id == "0.0025") {
EXPECT_STREQ(option.option_description.c_str(), "1/400");
} else if (setting_options.setting_id == "CAM_WBMODE" && option.option_id == "2") {
EXPECT_STREQ(option.option_description.c_str(), "Sunrise");
}
}
}
subscription_called = true;
}
TEST(CameraTest, SubscribePossibleSettings)
{
DronecodeSDK dc;
ConnectionResult connection_ret = dc.add_udp_connection();
ASSERT_EQ(connection_ret, ConnectionResult::SUCCESS);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System &system = dc.system();
ASSERT_TRUE(system.has_camera());
auto camera = std::make_shared<Camera>(system);
// We need to wait for the camera definition to be ready
// because we don't have a check yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
// Reset exposure mode
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "0"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
bool subscription_called = false;
camera->subscribe_possible_setting_options(
std::bind(receive_possible_setting_options, std::ref(subscription_called), _1));
EXPECT_EQ(camera->set_mode(Camera::Mode::PHOTO), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
subscription_called = false;
EXPECT_EQ(set_setting(camera, "CAM_EXPMODE", "1"), Camera::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(subscription_called);
}
<|endoftext|> |
<commit_before>#include <config.h>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
#include <sstream>
#include "dune/multiscale/msfem/msfem_traits.hh"
#include "coarse_scale_operator.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
template <class MatrixObject, template <class,class> class StencilType = Dune::Fem::DiagonalAndNeighborStencil>
StencilType<typename MatrixObject::DomainSpaceType,
typename MatrixObject::DomainSpaceType>
diagonalAndNeighborStencil(const MatrixObject& object)
{
return StencilType<typename MatrixObject::DomainSpaceType,
typename MatrixObject::RangeSpaceType>(object.domainSpace(), object.rangeSpace());
}
class EllipticCGMsFEM;
class EllipticCGMsFEMTraits
{
public:
typedef EllipticCGMsFEM derived_type;
typedef CommonTraits::LinearOperatorType MatrixType;
typedef CommonTraits::GdtSpaceType SourceSpaceType;
typedef CommonTraits::GdtSpaceType RangeSpaceType;
typedef CommonTraits::GridViewType GridViewType;
}; // class EllipticCGTraits
class EllipticCGMsFEM
: public GDT::Operators::MatrixBased< EllipticCGMsFEMTraits >
, public GDT::SystemAssembler< EllipticCGMsFEMTraits::RangeSpaceType, EllipticCGMsFEMTraits::GridViewType,
EllipticCGMsFEMTraits::SourceSpaceType>
{
typedef GDT::SystemAssembler< EllipticCGMsFEMTraits::RangeSpaceType, EllipticCGMsFEMTraits::GridViewType,
EllipticCGMsFEMTraits::SourceSpaceType > AssemblerBaseType;
typedef GDT::Operators::MatrixBased< EllipticCGMsFEMTraits > OperatorBaseType;
typedef GDT::LocalOperator::Codim0Integral<
GDT::LocalEvaluation::Elliptic< CommonTraits::DiffusionType > > LocalOperatorType;
typedef GDT::LocalAssembler::Codim0Matrix< LocalOperatorType > LocalAssemblerType;
public:
typedef EllipticCGMsFEMTraits Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
using OperatorBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_volume_pattern(grid_view, source_space);
}
EllipticCGMsFEM(const CommonTraits::DiffusionType& diffusion,
MatrixType& mtrx,
const SourceSpaceType& src_spc)
: OperatorBaseType(mtrx, src_spc)
, AssemblerBaseType(src_spc)
, diffusion_(diffusion)
, local_operator_(diffusion_)
, local_assembler_(local_operator_)
{
this->add(local_assembler_, this->matrix());
}
virtual ~EllipticCGMsFEM() {}
virtual void assemble() DS_OVERRIDE DS_FINAL
{
AssemblerBaseType::assemble();
}
private:
const CommonTraits::DiffusionType& diffusion_;
const LocalOperatorType local_operator_;
const LocalAssemblerType local_assembler_;
}; // class EllipticCG
CoarseScaleOperator::CoarseScaleOperator(const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
LocalGridList& subgrid_list, const CommonTraits::DiffusionType& diffusion_op)
: coarseDiscreteFunctionSpace_(coarseDiscreteFunctionSpace)
, subgrid_list_(subgrid_list)
, diffusion_operator_(diffusion_op)
, petrovGalerkin_(false)
, global_matrix_(coarseDiscreteFunctionSpace.mapper().size(), coarseDiscreteFunctionSpace.mapper().size(),
CommonTraits::EllipticOperatorType::pattern(coarseDiscreteFunctionSpace))
{
DSC_PROFILER.startTiming("msfem.assembleMatrix");
const bool is_simplex_grid = DSG::is_simplex_grid(coarseDiscreteFunctionSpace_);
GDT::SystemAssembler<CommonTraits::DiscreteFunctionSpaceType> global_system_assembler_(coarseDiscreteFunctionSpace_);
EllipticCGMsFEM elliptic_operator(diffusion_operator_, global_matrix_, coarseDiscreteFunctionSpace_);
global_system_assembler_.add(elliptic_operator);
global_system_assembler_.assemble();
#if 0 //alter referenzcode
for (const auto& coarse_grid_entity : DSC::viewRange(*coarseDiscreteFunctionSpace_.grid_view())) {
int cacheCounter = 0;
const auto& coarse_grid_geometry = coarse_grid_entity.geometry();
assert(coarse_grid_entity.partitionType() == InteriorEntity);
// DSFe::LocalMatrixProxy<MatrixType> local_matrix(global_matrix_, coarse_grid_entity, coarse_grid_entity);
auto local_matrix = nullptr;
const auto& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
const auto numMacroBaseFunctions = coarse_grid_baseSet.size();
Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarseDiscreteFunctionSpace_,
coarse_grid_entity,
subgrid_list_);
localSolutionManager.load();
const auto& localSolutions = localSolutionManager.getLocalSolutions();
assert(localSolutions.size() > 0);
for (const auto& localGridEntity : DSC::viewRange(*localSolutionManager.space().grid_view())) {
// ignore overlay elements
if (!subgrid_list_.covers(coarse_grid_entity, localGridEntity))
continue;
const auto& local_grid_geometry = localGridEntity.geometry();
// higher order quadrature, since A^{\epsilon} is highly variable
const auto localQuadrature = DSFe::make_quadrature(localGridEntity, localSolutionManager.space());
const auto numQuadraturePoints = localQuadrature.nop();
// number of local solutions without the boundary correctors. Those are only needed for the right hand side
const auto numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
// evaluate the jacobians of all local solutions in all quadrature points
std::vector<std::vector<JacobianRangeType>> allLocalSolutionEvaluations(
numLocalSolutions, std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0)));
for (auto lsNum : DSC::valueRange(numLocalSolutions)) {
auto& sll = localSolutions[lsNum];
assert(sll.get());
//! \todo re-enable
// assert(localSolutionManager.space().indexSet().contains(localGridEntity));
auto localFunction = sll->local_function(localGridEntity);
localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
}
for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
// local (barycentric) coordinates (with respect to entity)
const auto& local_subgrid_point = localQuadrature.point(localQuadraturePoint);
auto global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) *
local_grid_geometry.integrationElement(local_subgrid_point);
// evaluate the jacobian of the coarse grid base set
const auto& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi);
for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
CoarseDiscreteFunctionSpace::RangeType local_integral(0.0);
// Compute the gradients of the i'th and j'th local problem solutions
JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
if (is_simplex_grid) {
assert(allLocalSolutionEvaluations.size() == CommonTraits::GridType::dimension);
// ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
for (int k = 0; k < CommonTraits::GridType::dimension; ++k) {
gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
}
} else {
assert(allLocalSolutionEvaluations.size() == numMacroBaseFunctions);
gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
}
JacobianRangeType reconstructionGradPhii(coarseBaseJacs_[cacheCounter][i]);
reconstructionGradPhii += gradLocProbSoli;
JacobianRangeType reconstructionGradPhij(coarseBaseJacs_[cacheCounter][j]);
reconstructionGradPhij += gradLocProbSolj;
JacobianRangeType diffusive_flux(0.0);
diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
if (petrovGalerkin_)
local_integral += weight_local_quadrature * (diffusive_flux[0] * coarseBaseJacs_[cacheCounter][j][0]);
else
local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);
// add entries
local_matrix.add(j, i, local_integral);
}
}
}
}
} // for
// set unit rows for dirichlet dofs
Dune::Multiscale::getConstraintsCoarse(coarseDiscreteFunctionSpace_).applyToOperator(global_matrix_);
#endif
DSC_PROFILER.stopTiming("msfem.assembleMatrix");
DSC_LOG_DEBUG << "Time to assemble and communicate MsFEM matrix: " << DSC_PROFILER.getTiming("msfem.assembleMatrix") << "ms\n";
}
void CoarseScaleOperator::apply_inverse(const CoarseScaleOperator::CoarseDiscreteFunction& rhs,
CoarseScaleOperator::CoarseDiscreteFunction& solution) {
BOOST_ASSERT_MSG(rhs.dofs_valid(), "Coarse scale RHS DOFs need to be valid!");
DSC_PROFILER.startTiming("msfem.solveCoarse");
const typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType inverse(
global_matrix_, rhs.space().communicator());/*, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", rhs.size()),
DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs",
DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor")));*/
inverse.apply(rhs.vector(), solution.vector());
if (!solution.dofs_valid())
DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
DSC_PROFILER.stopTiming("msfem.solveCoarse");
DSC_LOG_DEBUG << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.solveCoarse") << "ms."
<< std::endl;
} // constructor
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>coarse_scale op gets own assembler<commit_after>#include <config.h>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
#include <sstream>
#include "dune/multiscale/msfem/msfem_traits.hh"
#include "coarse_scale_operator.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
// forward, to be used in the traits
template< class LocalOperatorImp >
class MsFemCodim0Matrix;
template< class LocalOperatorImp >
class MsFemCodim0MatrixTraits
{
public:
typedef MsFemCodim0Matrix< LocalOperatorImp > derived_type;
typedef GDT::LocalOperator::Codim0Interface< typename LocalOperatorImp::Traits > LocalOperatorType;
}; // class LocalAssemblerCodim0MatrixTraits
template< class LocalOperatorImp >
class MsFemCodim0Matrix
{
public:
typedef MsFemCodim0MatrixTraits< LocalOperatorImp > Traits;
typedef typename Traits::LocalOperatorType LocalOperatorType;
MsFemCodim0Matrix(const LocalOperatorType& op)
: localOperator_(op)
{}
const LocalOperatorType& localOperator() const
{
return localOperator_;
}
private:
static const size_t numTmpObjectsRequired_ = 1;
public:
std::vector< size_t > numTmpObjectsRequired() const
{
return { numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired() };
}
/**
* \tparam T Traits of the SpaceInterface implementation, representing the type of testSpace
* \tparam A Traits of the SpaceInterface implementation, representing the type of ansatzSpace
* \tparam EntityType A model of Dune::Entity< 0 >
* \tparam M Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the type of systemMatrix
* \tparam R RangeFieldType, i.e. double
*/
template< class T, class A, class EntityType, class M, class R >
void assembleLocal(const GDT::SpaceInterface< T >& testSpace,
const GDT::SpaceInterface< A >& ansatzSpace,
const EntityType& entity,
Dune::Stuff::LA::MatrixInterface< M >& systemMatrix,
std::vector< std::vector< Dune::DynamicMatrix< R > > >& tmpLocalMatricesContainer,
std::vector< Dune::DynamicVector< size_t > >& tmpIndicesContainer) const
{
// check
assert(tmpLocalMatricesContainer.size() >= 1);
assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
assert(tmpIndicesContainer.size() >= 2);
// get and clear matrix
Dune::DynamicMatrix< R >& localMatrix = tmpLocalMatricesContainer[0][0];
Dune::Stuff::Common::clear(localMatrix);
auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
// apply local operator (result is in localMatrix)
localOperator_.apply(testSpace.base_function_set(entity),
ansatzSpace.base_function_set(entity),
localMatrix,
tmpOperatorMatrices);
// write local matrix to global
Dune::DynamicVector< size_t >& globalRows = tmpIndicesContainer[0];
Dune::DynamicVector< size_t >& globalCols = tmpIndicesContainer[1];
const size_t rows = testSpace.mapper().numDofs(entity);
const size_t cols = ansatzSpace.mapper().numDofs(entity);
assert(globalRows.size() >= rows);
assert(globalCols.size() >= cols);
testSpace.mapper().globalIndices(entity, globalRows);
ansatzSpace.mapper().globalIndices(entity, globalCols);
for (size_t ii = 0; ii < rows; ++ii) {
const auto& localRow = localMatrix[ii];
const size_t globalII = globalRows[ii];
for (size_t jj = 0; jj < cols; ++jj) {
const size_t globalJJ = globalCols[jj];
systemMatrix.add_to_entry(globalII, globalJJ, localRow[jj]);
}
} // write local matrix to global
} // ... assembleLocal(...)
private:
const LocalOperatorType& localOperator_;
}; // class LocalAssemblerCodim0Matrix
class EllipticCGMsFEM;
class EllipticCGMsFEMTraits
{
public:
typedef EllipticCGMsFEM derived_type;
typedef CommonTraits::LinearOperatorType MatrixType;
typedef CommonTraits::GdtSpaceType SourceSpaceType;
typedef CommonTraits::GdtSpaceType RangeSpaceType;
typedef CommonTraits::GridViewType GridViewType;
}; // class EllipticCGTraits
class EllipticCGMsFEM
: public GDT::Operators::MatrixBased< EllipticCGMsFEMTraits >
, public GDT::SystemAssembler< EllipticCGMsFEMTraits::RangeSpaceType, EllipticCGMsFEMTraits::GridViewType,
EllipticCGMsFEMTraits::SourceSpaceType, MsFemCodim0Matrix>
{
typedef GDT::Operators::MatrixBased< EllipticCGMsFEMTraits > OperatorBaseType;
typedef GDT::LocalOperator::Codim0Integral<
GDT::LocalEvaluation::Elliptic< CommonTraits::DiffusionType > > LocalOperatorType;
typedef MsFemCodim0Matrix< LocalOperatorType > LocalAssemblerType;
typedef GDT::SystemAssembler< EllipticCGMsFEMTraits::RangeSpaceType, EllipticCGMsFEMTraits::GridViewType,
EllipticCGMsFEMTraits::SourceSpaceType, MsFemCodim0Matrix> AssemblerBaseType;
public:
typedef EllipticCGMsFEMTraits Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
using OperatorBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_volume_pattern(grid_view, source_space);
}
EllipticCGMsFEM(const CommonTraits::DiffusionType& diffusion,
MatrixType& mtrx,
const SourceSpaceType& src_spc)
: OperatorBaseType(mtrx, src_spc)
, AssemblerBaseType(src_spc)
, diffusion_(diffusion)
, local_operator_(diffusion_)
, local_assembler_(local_operator_)
{
this->add(local_assembler_, this->matrix());
}
virtual ~EllipticCGMsFEM() {}
virtual void assemble() DS_OVERRIDE DS_FINAL
{
AssemblerBaseType::assemble();
}
private:
const CommonTraits::DiffusionType& diffusion_;
const LocalOperatorType local_operator_;
const LocalAssemblerType local_assembler_;
}; // class EllipticCG
CoarseScaleOperator::CoarseScaleOperator(const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
LocalGridList& subgrid_list, const CommonTraits::DiffusionType& diffusion_op)
: coarseDiscreteFunctionSpace_(coarseDiscreteFunctionSpace)
, subgrid_list_(subgrid_list)
, diffusion_operator_(diffusion_op)
, petrovGalerkin_(false)
, global_matrix_(coarseDiscreteFunctionSpace.mapper().size(), coarseDiscreteFunctionSpace.mapper().size(),
CommonTraits::EllipticOperatorType::pattern(coarseDiscreteFunctionSpace))
{
DSC_PROFILER.startTiming("msfem.assembleMatrix");
const bool is_simplex_grid = DSG::is_simplex_grid(coarseDiscreteFunctionSpace_);
GDT::SystemAssembler<CommonTraits::DiscreteFunctionSpaceType> global_system_assembler_(coarseDiscreteFunctionSpace_);
EllipticCGMsFEM elliptic_operator(diffusion_operator_, global_matrix_, coarseDiscreteFunctionSpace_);
global_system_assembler_.add(elliptic_operator);
global_system_assembler_.assemble();
#if 0 //alter referenzcode
for (const auto& coarse_grid_entity : DSC::viewRange(*coarseDiscreteFunctionSpace_.grid_view())) {
int cacheCounter = 0;
const auto& coarse_grid_geometry = coarse_grid_entity.geometry();
assert(coarse_grid_entity.partitionType() == InteriorEntity);
// DSFe::LocalMatrixProxy<MatrixType> local_matrix(global_matrix_, coarse_grid_entity, coarse_grid_entity);
auto local_matrix = nullptr;
const auto& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
const auto numMacroBaseFunctions = coarse_grid_baseSet.size();
Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarseDiscreteFunctionSpace_,
coarse_grid_entity,
subgrid_list_);
localSolutionManager.load();
const auto& localSolutions = localSolutionManager.getLocalSolutions();
assert(localSolutions.size() > 0);
for (const auto& localGridEntity : DSC::viewRange(*localSolutionManager.space().grid_view())) {
// ignore overlay elements
if (!subgrid_list_.covers(coarse_grid_entity, localGridEntity))
continue;
const auto& local_grid_geometry = localGridEntity.geometry();
// higher order quadrature, since A^{\epsilon} is highly variable
const auto localQuadrature = DSFe::make_quadrature(localGridEntity, localSolutionManager.space());
const auto numQuadraturePoints = localQuadrature.nop();
// number of local solutions without the boundary correctors. Those are only needed for the right hand side
const auto numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
// evaluate the jacobians of all local solutions in all quadrature points
std::vector<std::vector<JacobianRangeType>> allLocalSolutionEvaluations(
numLocalSolutions, std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0)));
for (auto lsNum : DSC::valueRange(numLocalSolutions)) {
auto& sll = localSolutions[lsNum];
assert(sll.get());
//! \todo re-enable
// assert(localSolutionManager.space().indexSet().contains(localGridEntity));
auto localFunction = sll->local_function(localGridEntity);
localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
}
for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
// local (barycentric) coordinates (with respect to entity)
const auto& local_subgrid_point = localQuadrature.point(localQuadraturePoint);
auto global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) *
local_grid_geometry.integrationElement(local_subgrid_point);
// evaluate the jacobian of the coarse grid base set
const auto& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi);
for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
CoarseDiscreteFunctionSpace::RangeType local_integral(0.0);
// Compute the gradients of the i'th and j'th local problem solutions
JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
if (is_simplex_grid) {
assert(allLocalSolutionEvaluations.size() == CommonTraits::GridType::dimension);
// ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
for (int k = 0; k < CommonTraits::GridType::dimension; ++k) {
gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
}
} else {
assert(allLocalSolutionEvaluations.size() == numMacroBaseFunctions);
gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
}
JacobianRangeType reconstructionGradPhii(coarseBaseJacs_[cacheCounter][i]);
reconstructionGradPhii += gradLocProbSoli;
JacobianRangeType reconstructionGradPhij(coarseBaseJacs_[cacheCounter][j]);
reconstructionGradPhij += gradLocProbSolj;
JacobianRangeType diffusive_flux(0.0);
diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
if (petrovGalerkin_)
local_integral += weight_local_quadrature * (diffusive_flux[0] * coarseBaseJacs_[cacheCounter][j][0]);
else
local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);
// add entries
local_matrix.add(j, i, local_integral);
}
}
}
}
} // for
// set unit rows for dirichlet dofs
Dune::Multiscale::getConstraintsCoarse(coarseDiscreteFunctionSpace_).applyToOperator(global_matrix_);
#endif
DSC_PROFILER.stopTiming("msfem.assembleMatrix");
DSC_LOG_DEBUG << "Time to assemble and communicate MsFEM matrix: " << DSC_PROFILER.getTiming("msfem.assembleMatrix") << "ms\n";
}
void CoarseScaleOperator::apply_inverse(const CoarseScaleOperator::CoarseDiscreteFunction& rhs,
CoarseScaleOperator::CoarseDiscreteFunction& solution) {
BOOST_ASSERT_MSG(rhs.dofs_valid(), "Coarse scale RHS DOFs need to be valid!");
DSC_PROFILER.startTiming("msfem.solveCoarse");
const typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType inverse(
global_matrix_, rhs.space().communicator());/*, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", rhs.size()),
DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs",
DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor")));*/
inverse.apply(rhs.vector(), solution.vector());
if (!solution.dofs_valid())
DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
DSC_PROFILER.stopTiming("msfem.solveCoarse");
DSC_LOG_DEBUG << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.solveCoarse") << "ms."
<< std::endl;
} // constructor
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include <mmsystem.h>
#include <process.h>
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
namespace {
class MockTimeTicks : public TimeTicks {
public:
static DWORD Ticker() {
return static_cast<int>(InterlockedIncrement(&ticker_));
}
static void InstallTicker() {
old_tick_function_ = SetMockTickFunction(&Ticker);
ticker_ = -5;
}
static void UninstallTicker() {
SetMockTickFunction(old_tick_function_);
}
private:
static volatile LONG ticker_;
static TickFunctionType old_tick_function_;
};
volatile LONG MockTimeTicks::ticker_;
MockTimeTicks::TickFunctionType MockTimeTicks::old_tick_function_;
HANDLE g_rollover_test_start;
unsigned __stdcall RolloverTestThreadMain(void* param) {
int64 counter = reinterpret_cast<int64>(param);
DWORD rv = WaitForSingleObject(g_rollover_test_start, INFINITE);
EXPECT_EQ(rv, WAIT_OBJECT_0);
TimeTicks last = TimeTicks::Now();
for (int index = 0; index < counter; index++) {
TimeTicks now = TimeTicks::Now();
int64 milliseconds = (now - last).InMilliseconds();
// This is a tight loop; we could have looped faster than our
// measurements, so the time might be 0 millis.
EXPECT_GE(milliseconds, 0);
EXPECT_LT(milliseconds, 250);
last = now;
}
return 0;
}
} // namespace
TEST(TimeTicks, WinRollover) {
// The internal counter rolls over at ~49days. We'll use a mock
// timer to test this case.
// Basic test algorithm:
// 1) Set clock to rollover - N
// 2) Create N threads
// 3) Start the threads
// 4) Each thread loops through TimeTicks() N times
// 5) Each thread verifies integrity of result.
const int kThreads = 8;
// Use int64 so we can cast into a void* without a compiler warning.
const int64 kChecks = 10;
// It takes a lot of iterations to reproduce the bug!
// (See bug 1081395)
for (int loop = 0; loop < 4096; loop++) {
// Setup
MockTimeTicks::InstallTicker();
g_rollover_test_start = CreateEvent(0, TRUE, FALSE, 0);
HANDLE threads[kThreads];
for (int index = 0; index < kThreads; index++) {
void* argument = reinterpret_cast<void*>(kChecks);
unsigned thread_id;
threads[index] = reinterpret_cast<HANDLE>(
_beginthreadex(NULL, 0, RolloverTestThreadMain, argument, 0,
&thread_id));
EXPECT_NE((HANDLE)NULL, threads[index]);
}
// Start!
SetEvent(g_rollover_test_start);
// Wait for threads to finish
for (int index = 0; index < kThreads; index++) {
DWORD rv = WaitForSingleObject(threads[index], INFINITE);
EXPECT_EQ(rv, WAIT_OBJECT_0);
}
CloseHandle(g_rollover_test_start);
// Teardown
MockTimeTicks::UninstallTicker();
}
}
TEST(TimeTicks, SubMillisecondTimers) {
// Loop for a bit getting timers quickly. We want to
// see at least one case where we get a new sample in
// less than one millisecond.
bool saw_submillisecond_timer = false;
int64 min_timer = 1000;
TimeTicks last_time = TimeTicks::HighResNow();
for (int index = 0; index < 1000; index++) {
TimeTicks now = TimeTicks::HighResNow();
TimeDelta delta = now - last_time;
if (delta.InMicroseconds() > 0 &&
delta.InMicroseconds() < 1000) {
if (min_timer > delta.InMicroseconds())
min_timer = delta.InMicroseconds();
saw_submillisecond_timer = true;
}
last_time = now;
}
EXPECT_TRUE(saw_submillisecond_timer);
printf("Min timer is: %ldus\n", static_cast<long>(min_timer));
}
TEST(TimeTicks, TimeGetTimeCaps) {
// Test some basic assumptions that we expect about how timeGetDevCaps works.
TIMECAPS caps;
MMRESULT status = timeGetDevCaps(&caps, sizeof(caps));
EXPECT_EQ(TIMERR_NOERROR, status);
if (status != TIMERR_NOERROR) {
printf("Could not get timeGetDevCaps\n");
return;
}
EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
printf("timeGetTime range is %d to %dms\n", caps.wPeriodMin,
caps.wPeriodMax);
}
TEST(TimeTicks, QueryPerformanceFrequency) {
// Test some basic assumptions that we expect about QPC.
LARGE_INTEGER frequency;
BOOL rv = QueryPerformanceFrequency(&frequency);
EXPECT_EQ(TRUE, rv);
EXPECT_GT(frequency.QuadPart, 1000000); // Expect at least 1MHz
printf("QueryPerformanceFrequency is %5.2fMHz\n",
frequency.QuadPart / 1000000.0);
}
TEST(TimeTicks, TimerPerformance) {
// Verify that various timer mechanisms can always complete quickly.
// Note: This is a somewhat arbitrary test.
const int kLoops = 10000;
// Due to the fact that these run on bbots, which are horribly slow,
// we can't really make any guarantees about minimum runtime.
// Really, we want these to finish in ~10ms, and that is generous.
const int kMaxTime = 35; // Maximum acceptible milliseconds for test.
typedef TimeTicks (*TestFunc)();
struct TestCase {
TestFunc func;
char *description;
};
// Cheating a bit here: assumes sizeof(TimeTicks) == sizeof(Time)
// in order to create a single test case list.
COMPILE_ASSERT(sizeof(TimeTicks) == sizeof(Time),
test_only_works_with_same_sizes);
TestCase cases[] = {
{ reinterpret_cast<TestFunc>(Time::Now), "Time::Now" },
{ TimeTicks::Now, "TimeTicks::Now" },
{ TimeTicks::HighResNow, "TimeTicks::HighResNow" },
{ NULL, "" }
};
int test_case = 0;
while (cases[test_case].func) {
TimeTicks start = TimeTicks::HighResNow();
for (int index = 0; index < kLoops; index++)
cases[test_case].func();
TimeTicks stop = TimeTicks::HighResNow();
// Turning off the check for acceptible delays. Without this check,
// the test really doesn't do much other than measure. But the
// measurements are still useful for testing timers on various platforms.
// The reason to remove the check is because the tests run on many
// buildbots, some of which are VMs. These machines can run horribly
// slow, and there is really no value for checking against a max timer.
//EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
printf("%s: %1.2fus per call\n", cases[test_case].description,
(stop - start).InMillisecondsF() * 1000 / kLoops);
test_case++;
}
}
<commit_msg>Mark TimeTicks.SubMillisecondTimers as flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include <mmsystem.h>
#include <process.h>
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
namespace {
class MockTimeTicks : public TimeTicks {
public:
static DWORD Ticker() {
return static_cast<int>(InterlockedIncrement(&ticker_));
}
static void InstallTicker() {
old_tick_function_ = SetMockTickFunction(&Ticker);
ticker_ = -5;
}
static void UninstallTicker() {
SetMockTickFunction(old_tick_function_);
}
private:
static volatile LONG ticker_;
static TickFunctionType old_tick_function_;
};
volatile LONG MockTimeTicks::ticker_;
MockTimeTicks::TickFunctionType MockTimeTicks::old_tick_function_;
HANDLE g_rollover_test_start;
unsigned __stdcall RolloverTestThreadMain(void* param) {
int64 counter = reinterpret_cast<int64>(param);
DWORD rv = WaitForSingleObject(g_rollover_test_start, INFINITE);
EXPECT_EQ(rv, WAIT_OBJECT_0);
TimeTicks last = TimeTicks::Now();
for (int index = 0; index < counter; index++) {
TimeTicks now = TimeTicks::Now();
int64 milliseconds = (now - last).InMilliseconds();
// This is a tight loop; we could have looped faster than our
// measurements, so the time might be 0 millis.
EXPECT_GE(milliseconds, 0);
EXPECT_LT(milliseconds, 250);
last = now;
}
return 0;
}
} // namespace
TEST(TimeTicks, WinRollover) {
// The internal counter rolls over at ~49days. We'll use a mock
// timer to test this case.
// Basic test algorithm:
// 1) Set clock to rollover - N
// 2) Create N threads
// 3) Start the threads
// 4) Each thread loops through TimeTicks() N times
// 5) Each thread verifies integrity of result.
const int kThreads = 8;
// Use int64 so we can cast into a void* without a compiler warning.
const int64 kChecks = 10;
// It takes a lot of iterations to reproduce the bug!
// (See bug 1081395)
for (int loop = 0; loop < 4096; loop++) {
// Setup
MockTimeTicks::InstallTicker();
g_rollover_test_start = CreateEvent(0, TRUE, FALSE, 0);
HANDLE threads[kThreads];
for (int index = 0; index < kThreads; index++) {
void* argument = reinterpret_cast<void*>(kChecks);
unsigned thread_id;
threads[index] = reinterpret_cast<HANDLE>(
_beginthreadex(NULL, 0, RolloverTestThreadMain, argument, 0,
&thread_id));
EXPECT_NE((HANDLE)NULL, threads[index]);
}
// Start!
SetEvent(g_rollover_test_start);
// Wait for threads to finish
for (int index = 0; index < kThreads; index++) {
DWORD rv = WaitForSingleObject(threads[index], INFINITE);
EXPECT_EQ(rv, WAIT_OBJECT_0);
}
CloseHandle(g_rollover_test_start);
// Teardown
MockTimeTicks::UninstallTicker();
}
}
// Flaky, http://crbug.com/42850.
TEST(TimeTicks, FLAKY_SubMillisecondTimers) {
// Loop for a bit getting timers quickly. We want to
// see at least one case where we get a new sample in
// less than one millisecond.
bool saw_submillisecond_timer = false;
int64 min_timer = 1000;
TimeTicks last_time = TimeTicks::HighResNow();
for (int index = 0; index < 1000; index++) {
TimeTicks now = TimeTicks::HighResNow();
TimeDelta delta = now - last_time;
if (delta.InMicroseconds() > 0 &&
delta.InMicroseconds() < 1000) {
if (min_timer > delta.InMicroseconds())
min_timer = delta.InMicroseconds();
saw_submillisecond_timer = true;
}
last_time = now;
}
EXPECT_TRUE(saw_submillisecond_timer);
printf("Min timer is: %ldus\n", static_cast<long>(min_timer));
}
TEST(TimeTicks, TimeGetTimeCaps) {
// Test some basic assumptions that we expect about how timeGetDevCaps works.
TIMECAPS caps;
MMRESULT status = timeGetDevCaps(&caps, sizeof(caps));
EXPECT_EQ(TIMERR_NOERROR, status);
if (status != TIMERR_NOERROR) {
printf("Could not get timeGetDevCaps\n");
return;
}
EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
printf("timeGetTime range is %d to %dms\n", caps.wPeriodMin,
caps.wPeriodMax);
}
TEST(TimeTicks, QueryPerformanceFrequency) {
// Test some basic assumptions that we expect about QPC.
LARGE_INTEGER frequency;
BOOL rv = QueryPerformanceFrequency(&frequency);
EXPECT_EQ(TRUE, rv);
EXPECT_GT(frequency.QuadPart, 1000000); // Expect at least 1MHz
printf("QueryPerformanceFrequency is %5.2fMHz\n",
frequency.QuadPart / 1000000.0);
}
TEST(TimeTicks, TimerPerformance) {
// Verify that various timer mechanisms can always complete quickly.
// Note: This is a somewhat arbitrary test.
const int kLoops = 10000;
// Due to the fact that these run on bbots, which are horribly slow,
// we can't really make any guarantees about minimum runtime.
// Really, we want these to finish in ~10ms, and that is generous.
const int kMaxTime = 35; // Maximum acceptible milliseconds for test.
typedef TimeTicks (*TestFunc)();
struct TestCase {
TestFunc func;
char *description;
};
// Cheating a bit here: assumes sizeof(TimeTicks) == sizeof(Time)
// in order to create a single test case list.
COMPILE_ASSERT(sizeof(TimeTicks) == sizeof(Time),
test_only_works_with_same_sizes);
TestCase cases[] = {
{ reinterpret_cast<TestFunc>(Time::Now), "Time::Now" },
{ TimeTicks::Now, "TimeTicks::Now" },
{ TimeTicks::HighResNow, "TimeTicks::HighResNow" },
{ NULL, "" }
};
int test_case = 0;
while (cases[test_case].func) {
TimeTicks start = TimeTicks::HighResNow();
for (int index = 0; index < kLoops; index++)
cases[test_case].func();
TimeTicks stop = TimeTicks::HighResNow();
// Turning off the check for acceptible delays. Without this check,
// the test really doesn't do much other than measure. But the
// measurements are still useful for testing timers on various platforms.
// The reason to remove the check is because the tests run on many
// buildbots, some of which are VMs. These machines can run horribly
// slow, and there is really no value for checking against a max timer.
//EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
printf("%s: %1.2fus per call\n", cases[test_case].description,
(stop - start).InMillisecondsF() * 1000 / kLoops);
test_case++;
}
}
<|endoftext|> |
<commit_before><commit_msg>IMPALA-2470: Enable quadratic probing on hash tables.<commit_after><|endoftext|> |
<commit_before>#pragma once
// simple testing framework
// TODO: manual
#include <vector>
#include <string>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <chrono>
#define _CC(a, b) a ## b
#define _MCC(a, b) _CC(a, b)
#define STF_TEST(name) \
static void _MCC(_test_func_, __LINE__)(stf::runner&, stf::test&); \
static stf::test _MCC(_test_, __LINE__)(_stf_runner, name, _MCC(_test_func_, __LINE__)); \
static void _MCC(_test_func_, __LINE__)(stf::runner &__R, stf::test &__T)
#define STF_SUITE_NAME(name) \
static stf::name_setter _MCC(_name_setter_, __LINE__)(_stf_runner, name);
#define STF_LOGF(...) __R.logf(__LINE__, __FILE__, __VA_ARGS__)
#define STF_RAW_LOGF(...) __R.logf(0, nullptr, __VA_ARGS__)
#define STF_PRINTF(...) __R.printf(__LINE__, __FILE__, __VA_ARGS__)
#define STF_RAW_PRINTF(...) __R.printf(0, nullptr, __VA_ARGS__)
#define STF_ERRORF(...) \
do { \
__R.printf(__LINE__, __FILE__, __VA_ARGS__); \
__T.status = false; \
} while (0)
#define STF_ASSERT(expr) \
do { \
if (!(expr)) { \
__R.printf(__LINE__, __FILE__, "assertion failed: %s", #expr); \
__T.status = false; \
} \
} while (0)
namespace stf {
struct runner;
struct test;
typedef void (*functype)(runner&, test&);
struct test {
std::string name;
functype func;
bool status = true;
test(runner &r, std::string name, functype);
};
struct name_setter {
name_setter(runner &r, std::string name);
};
struct runner {
std::string suite_name;
std::vector<test> tests;
int failed = 0;
// copy & paste from logf, without verbosity check
void printf(int line, const char *filename, const char *format, ...) {
if (filename != nullptr) {
fprintf(stderr, "%s:%d: ", filename, line);
}
va_list vl;
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
int run() {
runner &__R = *this; // for macros
auto start = std::chrono::system_clock::now();
for (auto &t: tests) {
STF_RAW_PRINTF("=== Running %s", t.name.c_str());
(*t.func)(*this, t);
if (t.status) {
STF_RAW_PRINTF("--- PASS");
} else {
failed++;
STF_RAW_PRINTF("--- FAIL");
}
}
auto end = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
(end-start).count();
auto s_part = ms / 1000;
auto ms_part = ms - s_part * 1000;
if (failed > 0) {
STF_RAW_PRINTF("%d out of %d test(s) failed", failed, tests.size());
}
if (failed > 0) {
STF_RAW_PRINTF("FAIL\t%s\t%d.%03ds", suite_name.c_str(), s_part, ms_part);
return 1;
} else {
STF_RAW_PRINTF("ok\t%s\t%d.%03ds", suite_name.c_str(), s_part, ms_part);
return 0;
}
}
};
test::test(runner &r, std::string name, functype func): name(name), func(func) {
r.tests.push_back(*this);
}
name_setter::name_setter(runner &r, std::string name) {
r.suite_name = name;
}
} // namespace stf
static stf::runner _stf_runner;
int main(int argc, char **argv) {
return _stf_runner.run();
}
<commit_msg>Make "simple testing framework" less verbose.<commit_after>#pragma once
// simple testing framework
// TODO: manual
#include <vector>
#include <string>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <chrono>
#define _CC(a, b) a ## b
#define _MCC(a, b) _CC(a, b)
#define STF_TEST(name) \
static void _MCC(_test_func_, __LINE__)(stf::runner&, stf::test&); \
static stf::test _MCC(_test_, __LINE__)(_stf_runner, name, _MCC(_test_func_, __LINE__)); \
static void _MCC(_test_func_, __LINE__)(stf::runner &__R, stf::test &__T)
#define STF_SUITE_NAME(name) \
static stf::name_setter _MCC(_name_setter_, __LINE__)(_stf_runner, name);
#define STF_PRINTF(...) __T.printf(__LINE__, __FILE__, __VA_ARGS__)
#define STF_RAW_PRINTF(...) __T.printf(0, nullptr, __VA_ARGS__)
#define STF_ERRORF(...) \
do { \
__T.printf(__LINE__, __FILE__, __VA_ARGS__); \
__T.status = false; \
} while (0)
#define STF_ASSERT(expr) \
do { \
if (!(expr)) { \
__T.printf(__LINE__, __FILE__, "assertion failed: %s", #expr); \
__T.status = false; \
} \
} while (0)
namespace stf {
struct runner;
struct test;
typedef void (*functype)(runner&, test&);
struct test {
std::string name = "<unnamed>";
std::vector<std::string> messages;
functype func;
bool status = true;
test(runner &r, std::string name, functype);
void printf(int line, const char *filename, const char *format, ...) {
char fileline[256];
char message[8192];
if (filename != nullptr) {
snprintf(fileline, sizeof(fileline), "%s:%d: ", filename, line);
}
va_list vl;
va_start(vl, format);
vsnprintf(message, sizeof(message), format, vl);
va_end(vl);
// just in case
fileline[sizeof(fileline)-1] = '\0';
message[sizeof(message)-1] = '\0';
messages.push_back(std::string(fileline) + message);
}
};
struct name_setter {
name_setter(runner &r, std::string name);
};
struct runner {
std::string suite_name;
std::vector<test> tests;
int failed = 0;
bool verbose = false;
void init(int argc, char **argv) {
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-v") == 0) {
verbose = true;
}
}
}
void logf_force(const char *format, ...) {
va_list vl;
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
}
void logf(const char *format, ...) {
if (!verbose) {
return;
}
va_list vl;
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
}
int run() {
runner &__R = *this; // for macros
auto start = std::chrono::system_clock::now();
for (auto &t: tests) {
logf("%s... ", t.name.c_str());
(*t.func)(*this, t);
if (t.status) {
logf("PASS\n");
} else {
failed++;
if (verbose) {
logf("FAIL\n");
} else {
logf_force("%s... FAIL\n", t.name.c_str());
}
for (auto const &msg: t.messages) {
logf_force(" %s\n", msg.c_str());
}
}
}
auto end = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
(end-start).count();
auto s_part = ms / 1000;
auto ms_part = ms - s_part * 1000;
if (failed > 0) {
logf("%d out of %d test(s) failed", failed, tests.size());
}
if (failed > 0) {
logf_force("FAIL\t%s\t%d.%03ds\n", suite_name.c_str(), s_part, ms_part);
return 1;
} else {
logf_force("ok\t%s\t%d.%03ds\n", suite_name.c_str(), s_part, ms_part);
return 0;
}
}
};
test::test(runner &r, std::string name, functype func): name(name), func(func) {
r.tests.push_back(*this);
}
name_setter::name_setter(runner &r, std::string name) {
r.suite_name = name;
}
} // namespace stf
static stf::runner _stf_runner;
int main(int argc, char **argv) {
_stf_runner.init(argc, argv);
return _stf_runner.run();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-11-06 14:49: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 INCLUDED_SHARABLE_BASETYPES_HXX
#define INCLUDED_SHARABLE_BASETYPES_HXX
#ifndef CONFIGMGR_MEMORYMODEL_HXX
#include "memorymodel.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
//-----------------------------------------------------------------------------
namespace rtl { class OUString; }
//-----------------------------------------------------------------------------
namespace configmgr
{
namespace sharable
{
//-----------------------------------------------------------------------------
// some base types
typedef memory::Address Address; // points to absolute location in memory segment
typedef memory::HeapSize HeapSize; // size of memory block within heap
typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes
typedef sal_uInt8 Byte;
// some derived types
typedef rtl_uString * Name;
typedef rtl_uString * String;
typedef Address List; // singly linked intrusive, used for set elements
typedef Address Vector; // points to counted sequence of some type
//-----------------------------------------------------------------------------
Name allocName(::rtl::OUString const & _sString);
void freeName(Name _aName);
::rtl::OUString readName(Name _aName);
//-----------------------------------------------------------------------------
String allocString(::rtl::OUString const & _sString);
void freeString(String _aString);
::rtl::OUString readString(String _aString);
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_BASETYPES_HXX
<commit_msg>INTEGRATION: CWS configrefactor01 (1.4.14); FILE MERGED 2007/01/11 10:35:31 mmeeks 1.4.14.2: Submitted by: mmeeks<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:26:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SHARABLE_BASETYPES_HXX
#define INCLUDED_SHARABLE_BASETYPES_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
//-----------------------------------------------------------------------------
namespace rtl { class OUString; }
//-----------------------------------------------------------------------------
namespace configmgr
{
namespace sharable
{
//-----------------------------------------------------------------------------
// some base types
typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes
// some derived types
typedef rtl_uString * Name;
typedef rtl_uString * String;
typedef struct TreeFragment * List; // singly linked intrusive, used for set elements
typedef sal_uInt8 * Vector; // points to counted sequence of some type
//-----------------------------------------------------------------------------
inline String allocString(::rtl::OUString const & _sString)
{
rtl_uString_acquire(_sString.pData);
return _sString.pData;
}
inline void freeString(String _aString)
{ rtl_uString_release(_aString); }
inline ::rtl::OUString readString(String _aString)
{ return rtl::OUString(_aString); }
//-----------------------------------------------------------------------------
inline Name allocName(::rtl::OUString const & _aName)
{ return allocString(_aName); }
inline void freeName(Name _aName)
{ freeString(_aName); }
inline ::rtl::OUString readName(Name _aName)
{ return readString(_aName); }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_BASETYPES_HXX
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "blackhole/error.hpp"
#include "blackhole/repository/config/formatter.hpp"
#include "blackhole/repository/config/sink.hpp"
#include "blackhole/repository/factory/factory.hpp"
namespace blackhole {
template<typename T>
struct traits {
typedef std::unique_ptr<base_frontend_t> return_type;
typedef return_type(*function_type)(const formatter_config_t&, std::unique_ptr<T>);
};
//! Keeps frontend factory functions using type erasure idiom.
//! For each desired Formatter-Sink pair a function created and registered.
//! Later that function can be extracted by Sink type parameter.
template<typename Level>
struct function_keeper_t {
std::unordered_map<std::string, boost::any> functions;
template<typename Sink, typename Formatter>
void add() {
typedef typename traits<Sink>::function_type function_type;
function_type function = static_cast<function_type>(&factory_t<Level>::template create<Formatter>);
functions[Sink::name()] = function;
}
template<typename Sink>
bool has() const {
return functions.find(Sink::name()) != functions.end();
}
template<typename Sink>
typename traits<Sink>::function_type get() const {
boost::any any = functions.at(Sink::name());
return boost::any_cast<typename traits<Sink>::function_type>(any);
}
};
template<typename Level>
class frontend_factory_t {
mutable std::mutex mutex;
std::unordered_map<std::string, function_keeper_t<Level>> factories;
public:
template<typename Sink, typename Formatter>
void add() {
std::lock_guard<std::mutex> lock(mutex);
auto it = factories.find(Formatter::name());
if (it != factories.end()) {
function_keeper_t<Level>& keeper = it->second;
keeper.template add<Sink, Formatter>();
} else {
function_keeper_t<Level> keeper;
keeper.template add<Sink, Formatter>();
factories[Formatter::name()] = keeper;
}
}
template<typename Sink, typename Formatter>
bool has() const {
std::lock_guard<std::mutex> lock(mutex);
auto it = factories.find(Formatter::name());
return it != factories.end() && it->second.template has<Sink>();
}
template<typename Sink>
typename traits<Sink>::return_type
create(const formatter_config_t& formatter_config, std::unique_ptr<Sink> sink) const {
typedef typename traits<Sink>::return_type return_type;
try {
std::lock_guard<std::mutex> lock(mutex);
const function_keeper_t<Level>& keeper = factories.at(formatter_config.type);
auto factory = keeper.template get<Sink>();
return factory(formatter_config, std::move(sink));
} catch (const std::exception&) {
throw error_t("there are no registered formatter '%s' for sink '%s", formatter_config.type, Sink::name());
}
return return_type();
}
void clear() {
std::lock_guard<std::mutex> lock(mutex);
factories.clear();
}
};
} // namespace blackhole
<commit_msg>Code style.<commit_after>#pragma once
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "blackhole/error.hpp"
#include "blackhole/repository/config/formatter.hpp"
#include "blackhole/repository/config/sink.hpp"
#include "blackhole/repository/factory/factory.hpp"
namespace blackhole {
template<class T>
struct traits {
typedef std::unique_ptr<base_frontend_t> return_type;
typedef return_type(*function_type)(const formatter_config_t&, std::unique_ptr<T>);
};
//! Keeps frontend factory functions using type erasure idiom.
//! For each desired Formatter-Sink pair a function created and registered.
//! Later that function can be extracted by Sink type parameter.
template<typename Level>
struct function_keeper_t {
std::unordered_map<std::string, boost::any> functions;
template<class Sink, class Formatter>
void add() {
typedef typename traits<Sink>::function_type function_type;
function_type function = static_cast<function_type>(&factory_t<Level>::template create<Formatter>);
functions[Sink::name()] = function;
}
template<class Sink>
bool has() const {
return functions.find(Sink::name()) != functions.end();
}
template<class Sink>
typename traits<Sink>::function_type get() const {
boost::any any = functions.at(Sink::name());
return boost::any_cast<typename traits<Sink>::function_type>(any);
}
};
template<typename Level>
class frontend_factory_t {
mutable std::mutex mutex;
std::unordered_map<std::string, function_keeper_t<Level>> factories;
public:
template<class Sink, class Formatter>
void add() {
std::lock_guard<std::mutex> lock(mutex);
auto it = factories.find(Formatter::name());
if (it != factories.end()) {
function_keeper_t<Level>& keeper = it->second;
keeper.template add<Sink, Formatter>();
} else {
function_keeper_t<Level> keeper;
keeper.template add<Sink, Formatter>();
factories[Formatter::name()] = keeper;
}
}
template<class Sink, class Formatter>
bool has() const {
std::lock_guard<std::mutex> lock(mutex);
auto it = factories.find(Formatter::name());
return it != factories.end() && it->second.template has<Sink>();
}
template<class Sink>
typename traits<Sink>::return_type
create(const formatter_config_t& formatter_config, std::unique_ptr<Sink> sink) const {
typedef typename traits<Sink>::return_type return_type;
try {
std::lock_guard<std::mutex> lock(mutex);
const function_keeper_t<Level>& keeper = factories.at(formatter_config.type);
auto factory = keeper.template get<Sink>();
return factory(formatter_config, std::move(sink));
} catch (const std::exception&) {
throw error_t("there are no registered formatter '%s' for sink '%s", formatter_config.type, Sink::name());
}
return return_type();
}
void clear() {
std::lock_guard<std::mutex> lock(mutex);
factories.clear();
}
};
} // namespace blackhole
<|endoftext|> |
<commit_before>#include <config.h>
#include <rsspp_internal.h>
#include <utils.h>
#include <cstring>
namespace rsspp {
void atom_parser::parse_feed(feed& f, xmlNode * rootNode) {
if (!rootNode)
throw exception(_("XML root node is NULL"));
switch (f.rss_version) {
case ATOM_0_3:
ns = ATOM_0_3_URI;
break;
case ATOM_1_0:
ns = ATOM_1_0_URI;
break;
case ATOM_0_3_NONS:
ns = nullptr;
break;
default:
ns = nullptr;
break;
}
f.language = get_prop(rootNode, "lang");
globalbase = get_prop(rootNode, "base", XML_URI);
for (xmlNode * node = rootNode->children; node != nullptr; node = node->next) {
if (node_is(node, "title", ns)) {
f.title = get_content(node);
f.title_type = get_prop(node, "type");
if (f.title_type == "")
f.title_type = "text";
} else if (node_is(node, "subtitle", ns)) {
f.description = get_content(node);
} else if (node_is(node, "link", ns)) {
std::string rel = get_prop(node, "rel");
if (rel == "alternate") {
f.link = newsboat::utils::absolute_url(globalbase, get_prop(node, "href"));
}
} else if (node_is(node, "updated", ns)) {
f.pubDate = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "entry", ns)) {
f.items.push_back(parse_entry(node));
}
}
}
item atom_parser::parse_entry(xmlNode * entryNode) {
item it;
std::string summary;
std::string summary_type;
std::string updated;
std::string base = get_prop(entryNode, "base", XML_URI);
if (base == "")
base = globalbase;
for (xmlNode * node = entryNode->children; node != nullptr; node = node->next) {
if (node_is(node, "author", ns)) {
for (xmlNode * authornode = node->children; authornode != nullptr; authornode = authornode->next) {
if (node_is(authornode, "name", ns)) {
it.author = get_content(authornode);
} // TODO: is there more?
}
} else if (node_is(node, "title", ns)) {
it.title = get_content(node);
it.title_type = get_prop(node, "type");
if (it.title_type == "")
it.title_type = "text";
} else if (node_is(node, "content", ns)) {
std::string mode = get_prop(node, "mode");
std::string type = get_prop(node, "type");
if (mode == "xml" || mode == "") {
if (type == "html" || type == "text") {
it.description = get_content(node);
} else {
it.description = get_xml_content(node);
}
} else if (mode == "escaped") {
it.description = get_content(node);
}
it.description_type = type;
if (it.description_type == "")
it.description_type = "text";
it.base = get_prop(node, "base", XML_URI);
if (it.base.empty())
it.base = base;
} else if (node_is(node, "id", ns)) {
it.guid = get_content(node);
it.guid_isPermaLink = false;
} else if (node_is(node, "published", ns)) {
it.pubDate = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "updated", ns)) {
updated = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "link", ns)) {
std::string rel = get_prop(node, "rel");
if (rel == "" || rel == "alternate") {
it.link = newsboat::utils::absolute_url(base, get_prop(node, "href"));
} else if (rel == "enclosure") {
const std::string type = get_prop(node, "type");
if (utils::is_valid_podcast_type(type)) {
it.enclosure_url = get_prop(node, "href");
it.enclosure_type = std::move(type);
}
}
} else if (node_is(node, "summary", ns)) {
std::string mode = get_prop(node, "mode");
summary_type = get_prop(node, "type");
if (mode == "xml" || mode == "") {
if (summary_type == "html" || summary_type == "text") {
summary = get_content(node);
} else {
summary = get_xml_content(node);
}
} else if (mode == "escaped") {
summary = get_content(node);
}
if (summary_type == "")
summary_type = "text";
} else if (node_is(node, "category", ns) && get_prop(node, "scheme")=="http://www.google.com/reader/") {
it.labels.push_back(get_prop(node, "label"));
}
} // for
if (it.description == "") {
it.description = summary;
it.description_type = summary_type;
}
if (it.pubDate == "") {
it.pubDate = updated;
}
return it;
}
}
<commit_msg>Add missing newsboat namespace<commit_after>#include <config.h>
#include <rsspp_internal.h>
#include <utils.h>
#include <cstring>
namespace rsspp {
void atom_parser::parse_feed(feed& f, xmlNode * rootNode) {
if (!rootNode)
throw exception(_("XML root node is NULL"));
switch (f.rss_version) {
case ATOM_0_3:
ns = ATOM_0_3_URI;
break;
case ATOM_1_0:
ns = ATOM_1_0_URI;
break;
case ATOM_0_3_NONS:
ns = nullptr;
break;
default:
ns = nullptr;
break;
}
f.language = get_prop(rootNode, "lang");
globalbase = get_prop(rootNode, "base", XML_URI);
for (xmlNode * node = rootNode->children; node != nullptr; node = node->next) {
if (node_is(node, "title", ns)) {
f.title = get_content(node);
f.title_type = get_prop(node, "type");
if (f.title_type == "")
f.title_type = "text";
} else if (node_is(node, "subtitle", ns)) {
f.description = get_content(node);
} else if (node_is(node, "link", ns)) {
std::string rel = get_prop(node, "rel");
if (rel == "alternate") {
f.link = newsboat::utils::absolute_url(globalbase, get_prop(node, "href"));
}
} else if (node_is(node, "updated", ns)) {
f.pubDate = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "entry", ns)) {
f.items.push_back(parse_entry(node));
}
}
}
item atom_parser::parse_entry(xmlNode * entryNode) {
item it;
std::string summary;
std::string summary_type;
std::string updated;
std::string base = get_prop(entryNode, "base", XML_URI);
if (base == "")
base = globalbase;
for (xmlNode * node = entryNode->children; node != nullptr; node = node->next) {
if (node_is(node, "author", ns)) {
for (xmlNode * authornode = node->children; authornode != nullptr; authornode = authornode->next) {
if (node_is(authornode, "name", ns)) {
it.author = get_content(authornode);
} // TODO: is there more?
}
} else if (node_is(node, "title", ns)) {
it.title = get_content(node);
it.title_type = get_prop(node, "type");
if (it.title_type == "")
it.title_type = "text";
} else if (node_is(node, "content", ns)) {
std::string mode = get_prop(node, "mode");
std::string type = get_prop(node, "type");
if (mode == "xml" || mode == "") {
if (type == "html" || type == "text") {
it.description = get_content(node);
} else {
it.description = get_xml_content(node);
}
} else if (mode == "escaped") {
it.description = get_content(node);
}
it.description_type = type;
if (it.description_type == "")
it.description_type = "text";
it.base = get_prop(node, "base", XML_URI);
if (it.base.empty())
it.base = base;
} else if (node_is(node, "id", ns)) {
it.guid = get_content(node);
it.guid_isPermaLink = false;
} else if (node_is(node, "published", ns)) {
it.pubDate = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "updated", ns)) {
updated = w3cdtf_to_rfc822(get_content(node));
} else if (node_is(node, "link", ns)) {
std::string rel = get_prop(node, "rel");
if (rel == "" || rel == "alternate") {
it.link = newsboat::utils::absolute_url(base, get_prop(node, "href"));
} else if (rel == "enclosure") {
const std::string type = get_prop(node, "type");
if (newsboat::utils::is_valid_podcast_type(type)) {
it.enclosure_url = get_prop(node, "href");
it.enclosure_type = std::move(type);
}
}
} else if (node_is(node, "summary", ns)) {
std::string mode = get_prop(node, "mode");
summary_type = get_prop(node, "type");
if (mode == "xml" || mode == "") {
if (summary_type == "html" || summary_type == "text") {
summary = get_content(node);
} else {
summary = get_xml_content(node);
}
} else if (mode == "escaped") {
summary = get_content(node);
}
if (summary_type == "")
summary_type = "text";
} else if (node_is(node, "category", ns) && get_prop(node, "scheme")=="http://www.google.com/reader/") {
it.labels.push_back(get_prop(node, "label"));
}
} // for
if (it.description == "") {
it.description = summary;
it.description_type = summary_type;
}
if (it.pubDate == "") {
it.pubDate = updated;
}
return it;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "sk_tool_utils.h"
#include "SkCanvas.h"
#include "SkColorFilter.h"
#include "SkColorPriv.h"
#include "SkFlattenablePriv.h"
#include "SkImageFilterPriv.h"
#include "SkShader.h"
#include "SkBlurImageFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkDropShadowImageFilter.h"
#include "SkSpecialImage.h"
class FailImageFilter : public SkImageFilter {
public:
class Registrar {
public:
Registrar() {
SkFlattenable::Register("FailImageFilter",
FailImageFilter::CreateProc,
FailImageFilter::GetFlattenableType());
}
};
static sk_sp<SkImageFilter> Make() {
return sk_sp<SkImageFilter>(new FailImageFilter);
}
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(FailImageFilter)
protected:
FailImageFilter() : INHERITED(nullptr, 0, nullptr) {}
sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
SkIPoint* offset) const override {
return nullptr;
}
sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override {
return nullptr;
}
private:
typedef SkImageFilter INHERITED;
};
static FailImageFilter::Registrar gReg0;
sk_sp<SkFlattenable> FailImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 0);
return FailImageFilter::Make();
}
class IdentityImageFilter : public SkImageFilter {
public:
class Registrar {
public:
Registrar() {
SkFlattenable::Register("IdentityImageFilter",
IdentityImageFilter::CreateProc,
IdentityImageFilter::GetFlattenableType());
}
};
static sk_sp<SkImageFilter> Make(sk_sp<SkImageFilter> input) {
return sk_sp<SkImageFilter>(new IdentityImageFilter(std::move(input)));
}
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(IdentityImageFilter)
protected:
sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
SkIPoint* offset) const override {
offset->set(0, 0);
return sk_ref_sp<SkSpecialImage>(source);
}
sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override {
return sk_ref_sp(const_cast<IdentityImageFilter*>(this));
}
private:
IdentityImageFilter(sk_sp<SkImageFilter> input) : INHERITED(&input, 1, nullptr) {}
typedef SkImageFilter INHERITED;
};
static IdentityImageFilter::Registrar gReg1;
sk_sp<SkFlattenable> IdentityImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
return IdentityImageFilter::Make(common.getInput(0));
}
///////////////////////////////////////////////////////////////////////////////
static void draw_paint(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(std::move(imf));
paint.setColor(SK_ColorGREEN);
canvas->save();
canvas->clipRect(r);
canvas->drawPaint(paint);
canvas->restore();
}
static void draw_line(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorBLUE);
paint.setImageFilter(imf);
paint.setStrokeWidth(r.width()/10);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void draw_rect(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorYELLOW);
paint.setImageFilter(imf);
SkRect rr(r);
rr.inset(r.width()/10, r.height()/10);
canvas->drawRect(rr, paint);
}
static void draw_path(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorMAGENTA);
paint.setImageFilter(imf);
paint.setAntiAlias(true);
canvas->drawCircle(r.centerX(), r.centerY(), r.width()*2/5, paint);
}
static void draw_text(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(imf);
paint.setColor(SK_ColorCYAN);
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(r.height()/2);
paint.setTextAlign(SkPaint::kCenter_Align);
canvas->drawString("Text", r.centerX(), r.centerY(), paint);
}
static void draw_bitmap(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(std::move(imf));
SkIRect bounds;
r.roundOut(&bounds);
SkBitmap bm;
bm.allocN32Pixels(bounds.width(), bounds.height());
bm.eraseColor(SK_ColorTRANSPARENT);
SkCanvas c(bm);
draw_path(&c, r, nullptr);
canvas->drawBitmap(bm, 0, 0, &paint);
}
///////////////////////////////////////////////////////////////////////////////
class ImageFiltersBaseGM : public skiagm::GM {
public:
ImageFiltersBaseGM () {}
protected:
SkString onShortName() override {
return SkString("imagefiltersbase");
}
SkISize onISize() override { return SkISize::Make(700, 500); }
void draw_frame(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(SK_ColorRED);
canvas->drawRect(r, paint);
}
void onDraw(SkCanvas* canvas) override {
void (*drawProc[])(SkCanvas*, const SkRect&, sk_sp<SkImageFilter>) = {
draw_paint,
draw_line, draw_rect, draw_path, draw_text,
draw_bitmap,
};
auto cf = SkColorFilter::MakeModeFilter(SK_ColorRED, SkBlendMode::kSrcIn);
sk_sp<SkImageFilter> filters[] = {
nullptr,
IdentityImageFilter::Make(nullptr),
FailImageFilter::Make(),
SkColorFilterImageFilter::Make(std::move(cf), nullptr),
// The strage 0.29 value tickles an edge case where crop rect calculates
// a small border, but the blur really needs no border. This tickels
// an msan uninitialized value bug.
SkBlurImageFilter::Make(12.0f, 0.29f, nullptr),
SkDropShadowImageFilter::Make(
10.0f, 5.0f, 3.0f, 3.0f, SK_ColorBLUE,
SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode,
nullptr),
};
SkRect r = SkRect::MakeWH(SkIntToScalar(64), SkIntToScalar(64));
SkScalar MARGIN = SkIntToScalar(16);
SkScalar DX = r.width() + MARGIN;
SkScalar DY = r.height() + MARGIN;
canvas->translate(MARGIN, MARGIN);
for (size_t i = 0; i < SK_ARRAY_COUNT(drawProc); ++i) {
canvas->save();
for (size_t j = 0; j < SK_ARRAY_COUNT(filters); ++j) {
drawProc[i](canvas, r, filters[j]);
draw_frame(canvas, r);
canvas->translate(0, DY);
}
canvas->restore();
canvas->translate(DX, 0);
}
}
private:
typedef GM INHERITED;
};
DEF_GM( return new ImageFiltersBaseGM; )
///////////////////////////////////////////////////////////////////////////////
/*
* Want to test combos of filter and LCD text, to be sure we disable LCD in the presence of
* a filter.
*/
class ImageFiltersTextBaseGM : public skiagm::GM {
SkString fSuffix;
public:
ImageFiltersTextBaseGM(const char suffix[]) : fSuffix(suffix) {}
protected:
SkString onShortName() override {
SkString name;
name.printf("%s_%s", "textfilter", fSuffix.c_str());
return name;
}
SkISize onISize() override { return SkISize::Make(512, 342); }
void drawWaterfall(SkCanvas* canvas, const SkPaint& origPaint) {
const uint32_t flags[] = {
0,
SkPaint::kAntiAlias_Flag,
SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag,
};
SkPaint paint(origPaint);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(30);
SkAutoCanvasRestore acr(canvas, true);
for (size_t i = 0; i < SK_ARRAY_COUNT(flags); ++i) {
paint.setFlags(flags[i]);
canvas->drawString("Hamburgefon", 0, 0, paint);
canvas->translate(0, 40);
}
}
virtual void installFilter(SkPaint* paint) = 0;
void onDraw(SkCanvas* canvas) override {
SkPaint paint;
canvas->translate(20, 40);
for (int doSaveLayer = 0; doSaveLayer <= 1; ++doSaveLayer) {
SkAutoCanvasRestore acr(canvas, true);
for (int useFilter = 0; useFilter <= 1; ++useFilter) {
SkAutoCanvasRestore acr2(canvas, true);
SkPaint paint;
if (useFilter) {
this->installFilter(&paint);
}
if (doSaveLayer) {
canvas->saveLayer(nullptr, &paint);
paint.setImageFilter(nullptr);
}
this->drawWaterfall(canvas, paint);
acr2.restore();
canvas->translate(250, 0);
}
acr.restore();
canvas->translate(0, 200);
}
}
private:
typedef GM INHERITED;
};
class ImageFiltersText_IF : public ImageFiltersTextBaseGM {
public:
ImageFiltersText_IF() : ImageFiltersTextBaseGM("image") {}
void installFilter(SkPaint* paint) override {
paint->setImageFilter(SkBlurImageFilter::Make(1.5f, 1.5f, nullptr));
}
};
DEF_GM( return new ImageFiltersText_IF; )
class ImageFiltersText_CF : public ImageFiltersTextBaseGM {
public:
ImageFiltersText_CF() : ImageFiltersTextBaseGM("color") {}
void installFilter(SkPaint* paint) override {
paint->setColorFilter(SkColorFilter::MakeModeFilter(SK_ColorBLUE, SkBlendMode::kSrcIn));
}
};
DEF_GM( return new ImageFiltersText_CF; )
<commit_msg>Fix imagefiltersbase GM in ColorSpaceXformCanvas configs<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "sk_tool_utils.h"
#include "SkCanvas.h"
#include "SkColorFilter.h"
#include "SkColorPriv.h"
#include "SkFlattenablePriv.h"
#include "SkImageFilterPriv.h"
#include "SkShader.h"
#include "SkBlurImageFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkDropShadowImageFilter.h"
#include "SkSpecialImage.h"
class FailImageFilter : public SkImageFilter {
public:
class Registrar {
public:
Registrar() {
SkFlattenable::Register("FailImageFilter",
FailImageFilter::CreateProc,
FailImageFilter::GetFlattenableType());
}
};
static sk_sp<SkImageFilter> Make() {
return sk_sp<SkImageFilter>(new FailImageFilter);
}
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(FailImageFilter)
protected:
FailImageFilter() : INHERITED(nullptr, 0, nullptr) {}
sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
SkIPoint* offset) const override {
return nullptr;
}
sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override {
return sk_ref_sp(this);
}
private:
typedef SkImageFilter INHERITED;
};
static FailImageFilter::Registrar gReg0;
sk_sp<SkFlattenable> FailImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 0);
return FailImageFilter::Make();
}
class IdentityImageFilter : public SkImageFilter {
public:
class Registrar {
public:
Registrar() {
SkFlattenable::Register("IdentityImageFilter",
IdentityImageFilter::CreateProc,
IdentityImageFilter::GetFlattenableType());
}
};
static sk_sp<SkImageFilter> Make(sk_sp<SkImageFilter> input) {
return sk_sp<SkImageFilter>(new IdentityImageFilter(std::move(input)));
}
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(IdentityImageFilter)
protected:
sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
SkIPoint* offset) const override {
offset->set(0, 0);
return sk_ref_sp<SkSpecialImage>(source);
}
sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override {
return sk_ref_sp(const_cast<IdentityImageFilter*>(this));
}
private:
IdentityImageFilter(sk_sp<SkImageFilter> input) : INHERITED(&input, 1, nullptr) {}
typedef SkImageFilter INHERITED;
};
static IdentityImageFilter::Registrar gReg1;
sk_sp<SkFlattenable> IdentityImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
return IdentityImageFilter::Make(common.getInput(0));
}
///////////////////////////////////////////////////////////////////////////////
static void draw_paint(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(std::move(imf));
paint.setColor(SK_ColorGREEN);
canvas->save();
canvas->clipRect(r);
canvas->drawPaint(paint);
canvas->restore();
}
static void draw_line(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorBLUE);
paint.setImageFilter(imf);
paint.setStrokeWidth(r.width()/10);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void draw_rect(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorYELLOW);
paint.setImageFilter(imf);
SkRect rr(r);
rr.inset(r.width()/10, r.height()/10);
canvas->drawRect(rr, paint);
}
static void draw_path(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setColor(SK_ColorMAGENTA);
paint.setImageFilter(imf);
paint.setAntiAlias(true);
canvas->drawCircle(r.centerX(), r.centerY(), r.width()*2/5, paint);
}
static void draw_text(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(imf);
paint.setColor(SK_ColorCYAN);
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(r.height()/2);
paint.setTextAlign(SkPaint::kCenter_Align);
canvas->drawString("Text", r.centerX(), r.centerY(), paint);
}
static void draw_bitmap(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imf) {
SkPaint paint;
paint.setImageFilter(std::move(imf));
SkIRect bounds;
r.roundOut(&bounds);
SkBitmap bm;
bm.allocN32Pixels(bounds.width(), bounds.height());
bm.eraseColor(SK_ColorTRANSPARENT);
SkCanvas c(bm);
draw_path(&c, r, nullptr);
canvas->drawBitmap(bm, 0, 0, &paint);
}
///////////////////////////////////////////////////////////////////////////////
class ImageFiltersBaseGM : public skiagm::GM {
public:
ImageFiltersBaseGM () {}
protected:
SkString onShortName() override {
return SkString("imagefiltersbase");
}
SkISize onISize() override { return SkISize::Make(700, 500); }
void draw_frame(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(SK_ColorRED);
canvas->drawRect(r, paint);
}
void onDraw(SkCanvas* canvas) override {
void (*drawProc[])(SkCanvas*, const SkRect&, sk_sp<SkImageFilter>) = {
draw_paint,
draw_line, draw_rect, draw_path, draw_text,
draw_bitmap,
};
auto cf = SkColorFilter::MakeModeFilter(SK_ColorRED, SkBlendMode::kSrcIn);
sk_sp<SkImageFilter> filters[] = {
nullptr,
IdentityImageFilter::Make(nullptr),
FailImageFilter::Make(),
SkColorFilterImageFilter::Make(std::move(cf), nullptr),
// The strage 0.29 value tickles an edge case where crop rect calculates
// a small border, but the blur really needs no border. This tickels
// an msan uninitialized value bug.
SkBlurImageFilter::Make(12.0f, 0.29f, nullptr),
SkDropShadowImageFilter::Make(
10.0f, 5.0f, 3.0f, 3.0f, SK_ColorBLUE,
SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode,
nullptr),
};
SkRect r = SkRect::MakeWH(SkIntToScalar(64), SkIntToScalar(64));
SkScalar MARGIN = SkIntToScalar(16);
SkScalar DX = r.width() + MARGIN;
SkScalar DY = r.height() + MARGIN;
canvas->translate(MARGIN, MARGIN);
for (size_t i = 0; i < SK_ARRAY_COUNT(drawProc); ++i) {
canvas->save();
for (size_t j = 0; j < SK_ARRAY_COUNT(filters); ++j) {
drawProc[i](canvas, r, filters[j]);
draw_frame(canvas, r);
canvas->translate(0, DY);
}
canvas->restore();
canvas->translate(DX, 0);
}
}
private:
typedef GM INHERITED;
};
DEF_GM( return new ImageFiltersBaseGM; )
///////////////////////////////////////////////////////////////////////////////
/*
* Want to test combos of filter and LCD text, to be sure we disable LCD in the presence of
* a filter.
*/
class ImageFiltersTextBaseGM : public skiagm::GM {
SkString fSuffix;
public:
ImageFiltersTextBaseGM(const char suffix[]) : fSuffix(suffix) {}
protected:
SkString onShortName() override {
SkString name;
name.printf("%s_%s", "textfilter", fSuffix.c_str());
return name;
}
SkISize onISize() override { return SkISize::Make(512, 342); }
void drawWaterfall(SkCanvas* canvas, const SkPaint& origPaint) {
const uint32_t flags[] = {
0,
SkPaint::kAntiAlias_Flag,
SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag,
};
SkPaint paint(origPaint);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(30);
SkAutoCanvasRestore acr(canvas, true);
for (size_t i = 0; i < SK_ARRAY_COUNT(flags); ++i) {
paint.setFlags(flags[i]);
canvas->drawString("Hamburgefon", 0, 0, paint);
canvas->translate(0, 40);
}
}
virtual void installFilter(SkPaint* paint) = 0;
void onDraw(SkCanvas* canvas) override {
SkPaint paint;
canvas->translate(20, 40);
for (int doSaveLayer = 0; doSaveLayer <= 1; ++doSaveLayer) {
SkAutoCanvasRestore acr(canvas, true);
for (int useFilter = 0; useFilter <= 1; ++useFilter) {
SkAutoCanvasRestore acr2(canvas, true);
SkPaint paint;
if (useFilter) {
this->installFilter(&paint);
}
if (doSaveLayer) {
canvas->saveLayer(nullptr, &paint);
paint.setImageFilter(nullptr);
}
this->drawWaterfall(canvas, paint);
acr2.restore();
canvas->translate(250, 0);
}
acr.restore();
canvas->translate(0, 200);
}
}
private:
typedef GM INHERITED;
};
class ImageFiltersText_IF : public ImageFiltersTextBaseGM {
public:
ImageFiltersText_IF() : ImageFiltersTextBaseGM("image") {}
void installFilter(SkPaint* paint) override {
paint->setImageFilter(SkBlurImageFilter::Make(1.5f, 1.5f, nullptr));
}
};
DEF_GM( return new ImageFiltersText_IF; )
class ImageFiltersText_CF : public ImageFiltersTextBaseGM {
public:
ImageFiltersText_CF() : ImageFiltersTextBaseGM("color") {}
void installFilter(SkPaint* paint) override {
paint->setColorFilter(SkColorFilter::MakeModeFilter(SK_ColorBLUE, SkBlendMode::kSrcIn));
}
};
DEF_GM( return new ImageFiltersText_CF; )
<|endoftext|> |
<commit_before>#include "move_manipulator.h"
#include "util.h"
#include <limits>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnManip3D.h>
#include <maya/MGLFunctionTable.h>
#include <maya/MHardwareRenderer.h>
const MTypeId MannequinMoveManipulator::id = MTypeId(0xcafebee);
MannequinMoveManipulator::MannequinMoveManipulator() {}
void MannequinMoveManipulator::postConstructor() {
addPointValue("translate", MPoint(0, 0, 0), _translateIndex);
glFirstHandle(_glPickableItem);
}
MStatus
MannequinMoveManipulator::connectToDependNode(const MObject &dependNode) {
MStatus status;
MFnDependencyNode nodeFn(dependNode, &status);
if (!status)
return MS::kFailure;
MPlug translatePlug = nodeFn.findPlug("translate", &status);
if (!status)
return MS::kFailure;
int plugIndex = 0;
status = connectPlugToValue(translatePlug, _translateIndex, plugIndex);
if (!status)
return MS::kFailure;
MFnDagNode dagNodeFn(dependNode);
MDagPath nodePath;
dagNodeFn.getPath(nodePath);
MTransformationMatrix m(nodePath.exclusiveMatrix());
_parentXform = m;
MTransformationMatrix n(nodePath.inclusiveMatrix());
_childXform = n;
finishAddingManips();
return MPxManipulatorNode::connectToDependNode(dependNode);
}
void MannequinMoveManipulator::draw(M3dView &view,
const MDagPath &path,
M3dView::DisplayStyle style,
M3dView::DisplayStatus status) {
static MGLFunctionTable *gGLFT = 0;
if (0 == gGLFT) {
gGLFT = MHardwareRenderer::theRenderer()->glFunctionTable();
}
recalcMetrics();
float size = _manipScale * MFnManip3D::globalSize();
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = size * handleSize * 0.5f;
float handleOfs = size - handleHeight;
float handleRadius = handleHeight * 0.25f;
float origin[4];
float x[4], y[4], z[4];
_origin.get(origin);
(_origin + (_x * size)).get(x);
(_origin + (_y * size)).get(y);
(_origin + (_z * size)).get(z);
bool selected[3];
shouldDrawHandleAsSelected(_glPickableItem + 0, selected[0]);
shouldDrawHandleAsSelected(_glPickableItem + 1, selected[1]);
shouldDrawHandleAsSelected(_glPickableItem + 2, selected[2]);
view.beginGL();
colorAndName(view, _glPickableItem + 0, true,
selected[0] ? selectedColor() : xColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(x);
gGLFT->glEnd();
colorAndName(view, _glPickableItem + 1, true,
selected[1] ? selectedColor() : yColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(y);
gGLFT->glEnd();
colorAndName(view, _glPickableItem + 2, true,
selected[2] ? selectedColor() : zColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(z);
gGLFT->glEnd();
view.endGL();
}
void MannequinMoveManipulator::preDrawUI(const M3dView &view) {
recalcMetrics();
_xColor = xColor();
_yColor = yColor();
_zColor = zColor();
_selColor = selectedColor();
}
void MannequinMoveManipulator::drawUI(MHWRender::MUIDrawManager &drawManager,
const MHWRender::MFrameContext &frameContext) const {
float size = _manipScale * MFnManip3D::globalSize();
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = size * handleSize * 0.5f;
float handleOfs = size - handleHeight;
float handleRadius = handleHeight * 0.25f;
bool selected[3];
shouldDrawHandleAsSelected(_glPickableItem + 0, selected[0]);
shouldDrawHandleAsSelected(_glPickableItem + 1, selected[1]);
shouldDrawHandleAsSelected(_glPickableItem + 2, selected[2]);
drawManager.beginDrawable(_glPickableItem + 0, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[0] ? _selColor : _xColor);
drawManager.line(_origin, _origin + (_x * size));
drawManager.cone(_origin + (_x * handleOfs), _x, handleRadius, handleHeight,
true);
drawManager.endDrawable();
drawManager.beginDrawable(_glPickableItem + 1, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[1] ? _selColor : _yColor);
drawManager.line(_origin, _origin + (_y * size));
drawManager.cone(_origin + (_y * handleOfs), _y, handleRadius, handleHeight,
true);
drawManager.endDrawable();
drawManager.beginDrawable(_glPickableItem + 2, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[2] ? _selColor : _zColor);
drawManager.line(_origin, _origin + (_z * size));
drawManager.cone(_origin + (_z * handleOfs), _z, handleRadius, handleHeight,
true);
drawManager.endDrawable();
#ifdef MANIPULATOR_TEST
drawManager.beginDrawable();
drawManager.setColor(MColor(1.0, 0.0, 1.0));
drawManager.line(_opHitBegin, _opHitCurrent);
drawManager.line(_opHitBegin, _opHitBegin + _opDiffProj);
drawManager.endDrawable();
#endif
};
MStatus MannequinMoveManipulator::doPress(M3dView& view) {
getPointValue(_translateIndex, false, _opValueBegin);
GLuint activeAxis;
glActiveName(activeAxis);
if (activeAxis == _glPickableItem + 0) {
_opAxis = _x;
_opAxisIndex = 0;
} else if (activeAxis == _glPickableItem + 1) {
_opAxis = _y;
_opAxisIndex = 1;
} else if (activeAxis == _glPickableItem + 2) {
_opAxis = _z;
_opAxisIndex = 2;
} else {
_opAxis = MVector::zero;
_opValid = false;
return MS::kUnknownParameter;
}
_opOrigin = _origin;
// Determine the translation "plane"; it is orthogonal to the axis and faces
// the view as best as possible.
short originX, originY;
view.worldToView(_opOrigin, originX, originY);
MPoint rayNear;
MVector dirToOrigin;
view.viewToWorld(originX, originY, rayNear, dirToOrigin);
MVector dirInPlane = dirToOrigin ^ _opAxis;
_opPlaneNormal = dirInPlane ^ _opAxis;
// Determine where the current mouse ray hits the plane.
MPoint rayOrigin;
MVector rayDirection;
mouseRayWorld(rayOrigin, rayDirection);
MPoint isect;
bool didIsect = Util::rayPlaneIntersection(rayOrigin,
rayDirection,
_opOrigin,
_opPlaneNormal,
&isect);
if (!didIsect) {
_opValid = false;
return MS::kUnknownParameter;
}
_opHitBegin = isect;
_opValid = true;
// We need to calculate the handle directions in parent space. This is
// because the handle positions align with the child pivot rotation, so they
// DO NOT correspond to the child's X, Y, and Z-position, which are
// indicated in terms of the parent's coordinate space.
MMatrix parentInverse = _parentXform.asMatrixInverse();
_xInParentSpace = _x * parentInverse;
_yInParentSpace = _y * parentInverse;
_zInParentSpace = _z * parentInverse;
return MS::kSuccess;
}
MStatus MannequinMoveManipulator::doDrag(M3dView& view) {
if (!_opValid) {
return MS::kUnknownParameter;
}
MPoint rayOrigin;
MVector rayDirection;
mouseRayWorld(rayOrigin, rayDirection);
MPoint isect;
bool didIsect = Util::rayPlaneIntersection(rayOrigin,
rayDirection,
_opOrigin,
_opPlaneNormal,
&isect);
if (!didIsect) {
// Leave the point where it is. The user's probably gone past the horizon.
return MS::kSuccess;
}
_opHitCurrent = isect;
MVector diff = _opHitCurrent - _opHitBegin;
// Now let's project diff onto the axis!
MVector axisNormal = _opAxis.normal();
double ofs = (diff * axisNormal) / _opAxis.length();
_opDiffProj = (diff * axisNormal) * axisNormal;
MPoint newTranslate;
if (_opAxisIndex == 0) {
newTranslate = _opValueBegin + ofs * _xInParentSpace;
} else if (_opAxisIndex == 1) {
newTranslate = _opValueBegin + ofs * _yInParentSpace;
} else if (_opAxisIndex == 2) {
newTranslate = _opValueBegin + ofs * _zInParentSpace;
} else {
newTranslate = _opValueBegin;
}
setPointValue(_translateIndex, newTranslate);
return MS::kSuccess;
}
MStatus MannequinMoveManipulator::doRelease(M3dView& view) {
return MS::kSuccess;
}
void MannequinMoveManipulator::setManipScale(float scale) {
_manipScale = scale;
}
float MannequinMoveManipulator::manipScale() const {
return _manipScale;
}
void MannequinMoveManipulator::recalcMetrics() {
MPoint translate;
getPointValue(_translateIndex, false, translate);
MMatrix childMatrix = _childXform.asMatrix();
_x = (MVector::xAxis * childMatrix).normal();
_y = (MVector::yAxis * childMatrix).normal();
_z = (MVector::zAxis * childMatrix).normal();
_origin = translate * _parentXform.asMatrix();
}
bool MannequinMoveManipulator::intersectManip(MPxManipulatorNode* manip) const {
M3dView view = M3dView::active3dView();
float size = _manipScale * MFnManip3D::globalSize();
MPoint xEnd = _origin + (_x * size);
MPoint yEnd = _origin + (_y * size);
MPoint zEnd = _origin + (_z * size);
short mx, my;
manip->mousePosition(mx, my);
short ox, oy, xx, xy, yx, yy, zx, zy;
view.worldToView(_origin, ox, oy);
view.worldToView(xEnd, xx, xy);
view.worldToView(yEnd, yx, yy);
view.worldToView(zEnd, zx, zy);
// Calculate approximate handle size in view space.
float viewLength = 0.0f;
viewLength = std::max(viewLength,
sqrtf(pow(float(xx) - float(ox), 2) + pow(float(xy) - float(oy), 2)));
viewLength = std::max(viewLength,
sqrtf(pow(float(yx) - float(ox), 2) + pow(float(yy) - float(oy), 2)));
viewLength = std::max(viewLength,
sqrtf(pow(float(zx) - float(ox), 2) + pow(float(zy) - float(oy), 2)));
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = viewLength * handleSize * 0.5f;
float handleRadius = std::max(handleHeight * 0.5f, 2.0f);
// Determine if we're in range to any of the lines.
float curDist, t;
curDist = Util::distanceToLine(ox, oy, xx, xy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
curDist = Util::distanceToLine(ox, oy, yx, yy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
curDist = Util::distanceToLine(ox, oy, zx, zy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
return false;
}
void* MannequinMoveManipulator::creator() {
return new MannequinMoveManipulator;
}
MStatus MannequinMoveManipulator::initialize() {
return MS::kSuccess;
}
<commit_msg>improve manipulator hover precision<commit_after>#include "move_manipulator.h"
#include "util.h"
#include <limits>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnManip3D.h>
#include <maya/MGLFunctionTable.h>
#include <maya/MHardwareRenderer.h>
const MTypeId MannequinMoveManipulator::id = MTypeId(0xcafebee);
MannequinMoveManipulator::MannequinMoveManipulator() {}
void MannequinMoveManipulator::postConstructor() {
addPointValue("translate", MPoint(0, 0, 0), _translateIndex);
glFirstHandle(_glPickableItem);
}
MStatus
MannequinMoveManipulator::connectToDependNode(const MObject &dependNode) {
MStatus status;
MFnDependencyNode nodeFn(dependNode, &status);
if (!status)
return MS::kFailure;
MPlug translatePlug = nodeFn.findPlug("translate", &status);
if (!status)
return MS::kFailure;
int plugIndex = 0;
status = connectPlugToValue(translatePlug, _translateIndex, plugIndex);
if (!status)
return MS::kFailure;
MFnDagNode dagNodeFn(dependNode);
MDagPath nodePath;
dagNodeFn.getPath(nodePath);
MTransformationMatrix m(nodePath.exclusiveMatrix());
_parentXform = m;
MTransformationMatrix n(nodePath.inclusiveMatrix());
_childXform = n;
finishAddingManips();
return MPxManipulatorNode::connectToDependNode(dependNode);
}
void MannequinMoveManipulator::draw(M3dView &view,
const MDagPath &path,
M3dView::DisplayStyle style,
M3dView::DisplayStatus status) {
static MGLFunctionTable *gGLFT = 0;
if (0 == gGLFT) {
gGLFT = MHardwareRenderer::theRenderer()->glFunctionTable();
}
recalcMetrics();
float size = _manipScale * MFnManip3D::globalSize();
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = size * handleSize * 0.5f;
float handleOfs = size - handleHeight;
float handleRadius = handleHeight * 0.25f;
float origin[4];
float x[4], y[4], z[4];
_origin.get(origin);
(_origin + (_x * size)).get(x);
(_origin + (_y * size)).get(y);
(_origin + (_z * size)).get(z);
bool selected[3];
shouldDrawHandleAsSelected(_glPickableItem + 0, selected[0]);
shouldDrawHandleAsSelected(_glPickableItem + 1, selected[1]);
shouldDrawHandleAsSelected(_glPickableItem + 2, selected[2]);
view.beginGL();
colorAndName(view, _glPickableItem + 0, true,
selected[0] ? selectedColor() : xColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(x);
gGLFT->glEnd();
colorAndName(view, _glPickableItem + 1, true,
selected[1] ? selectedColor() : yColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(y);
gGLFT->glEnd();
colorAndName(view, _glPickableItem + 2, true,
selected[2] ? selectedColor() : zColor());
gGLFT->glBegin(MGL_LINES);
gGLFT->glVertex3fv(origin);
gGLFT->glVertex3fv(z);
gGLFT->glEnd();
view.endGL();
}
void MannequinMoveManipulator::preDrawUI(const M3dView &view) {
recalcMetrics();
_xColor = xColor();
_yColor = yColor();
_zColor = zColor();
_selColor = selectedColor();
}
void MannequinMoveManipulator::drawUI(MHWRender::MUIDrawManager &drawManager,
const MHWRender::MFrameContext &frameContext) const {
float size = _manipScale * MFnManip3D::globalSize();
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = size * handleSize * 0.5f;
float handleOfs = size - handleHeight;
float handleRadius = handleHeight * 0.25f;
bool selected[3];
shouldDrawHandleAsSelected(_glPickableItem + 0, selected[0]);
shouldDrawHandleAsSelected(_glPickableItem + 1, selected[1]);
shouldDrawHandleAsSelected(_glPickableItem + 2, selected[2]);
drawManager.beginDrawable(_glPickableItem + 0, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[0] ? _selColor : _xColor);
drawManager.line(_origin, _origin + (_x * size));
drawManager.cone(_origin + (_x * handleOfs), _x, handleRadius, handleHeight,
true);
drawManager.endDrawable();
drawManager.beginDrawable(_glPickableItem + 1, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[1] ? _selColor : _yColor);
drawManager.line(_origin, _origin + (_y * size));
drawManager.cone(_origin + (_y * handleOfs), _y, handleRadius, handleHeight,
true);
drawManager.endDrawable();
drawManager.beginDrawable(_glPickableItem + 2, true);
drawManager.setLineWidth(MFnManip3D::lineSize());
drawManager.setColorIndex(selected[2] ? _selColor : _zColor);
drawManager.line(_origin, _origin + (_z * size));
drawManager.cone(_origin + (_z * handleOfs), _z, handleRadius, handleHeight,
true);
drawManager.endDrawable();
#ifdef MANIPULATOR_TEST
drawManager.beginDrawable();
drawManager.setColor(MColor(1.0, 0.0, 1.0));
drawManager.line(_opHitBegin, _opHitCurrent);
drawManager.line(_opHitBegin, _opHitBegin + _opDiffProj);
drawManager.endDrawable();
#endif
};
MStatus MannequinMoveManipulator::doPress(M3dView& view) {
getPointValue(_translateIndex, false, _opValueBegin);
GLuint activeAxis;
glActiveName(activeAxis);
if (activeAxis == _glPickableItem + 0) {
_opAxis = _x;
_opAxisIndex = 0;
} else if (activeAxis == _glPickableItem + 1) {
_opAxis = _y;
_opAxisIndex = 1;
} else if (activeAxis == _glPickableItem + 2) {
_opAxis = _z;
_opAxisIndex = 2;
} else {
_opAxis = MVector::zero;
_opValid = false;
return MS::kUnknownParameter;
}
_opOrigin = _origin;
// Determine the translation "plane"; it is orthogonal to the axis and faces
// the view as best as possible.
short originX, originY;
view.worldToView(_opOrigin, originX, originY);
MPoint rayNear;
MVector dirToOrigin;
view.viewToWorld(originX, originY, rayNear, dirToOrigin);
MVector dirInPlane = dirToOrigin ^ _opAxis;
_opPlaneNormal = dirInPlane ^ _opAxis;
// Determine where the current mouse ray hits the plane.
MPoint rayOrigin;
MVector rayDirection;
mouseRayWorld(rayOrigin, rayDirection);
MPoint isect;
bool didIsect = Util::rayPlaneIntersection(rayOrigin,
rayDirection,
_opOrigin,
_opPlaneNormal,
&isect);
if (!didIsect) {
_opValid = false;
return MS::kUnknownParameter;
}
_opHitBegin = isect;
_opValid = true;
// We need to calculate the handle directions in parent space. This is
// because the handle positions align with the child pivot rotation, so they
// DO NOT correspond to the child's X, Y, and Z-position, which are
// indicated in terms of the parent's coordinate space.
MMatrix parentInverse = _parentXform.asMatrixInverse();
_xInParentSpace = _x * parentInverse;
_yInParentSpace = _y * parentInverse;
_zInParentSpace = _z * parentInverse;
return MS::kSuccess;
}
MStatus MannequinMoveManipulator::doDrag(M3dView& view) {
if (!_opValid) {
return MS::kUnknownParameter;
}
MPoint rayOrigin;
MVector rayDirection;
mouseRayWorld(rayOrigin, rayDirection);
MPoint isect;
bool didIsect = Util::rayPlaneIntersection(rayOrigin,
rayDirection,
_opOrigin,
_opPlaneNormal,
&isect);
if (!didIsect) {
// Leave the point where it is. The user's probably gone past the horizon.
return MS::kSuccess;
}
_opHitCurrent = isect;
MVector diff = _opHitCurrent - _opHitBegin;
// Now let's project diff onto the axis!
MVector axisNormal = _opAxis.normal();
double ofs = (diff * axisNormal) / _opAxis.length();
_opDiffProj = (diff * axisNormal) * axisNormal;
MPoint newTranslate;
if (_opAxisIndex == 0) {
newTranslate = _opValueBegin + ofs * _xInParentSpace;
} else if (_opAxisIndex == 1) {
newTranslate = _opValueBegin + ofs * _yInParentSpace;
} else if (_opAxisIndex == 2) {
newTranslate = _opValueBegin + ofs * _zInParentSpace;
} else {
newTranslate = _opValueBegin;
}
setPointValue(_translateIndex, newTranslate);
return MS::kSuccess;
}
MStatus MannequinMoveManipulator::doRelease(M3dView& view) {
return MS::kSuccess;
}
void MannequinMoveManipulator::setManipScale(float scale) {
_manipScale = scale;
}
float MannequinMoveManipulator::manipScale() const {
return _manipScale;
}
void MannequinMoveManipulator::recalcMetrics() {
MPoint translate;
getPointValue(_translateIndex, false, translate);
MMatrix childMatrix = _childXform.asMatrix();
_x = (MVector::xAxis * childMatrix).normal();
_y = (MVector::yAxis * childMatrix).normal();
_z = (MVector::zAxis * childMatrix).normal();
_origin = translate * _parentXform.asMatrix();
}
bool MannequinMoveManipulator::intersectManip(MPxManipulatorNode* manip) const {
M3dView view = M3dView::active3dView();
float size = _manipScale * MFnManip3D::globalSize();
MPoint xEnd = _origin + (_x * size);
MPoint yEnd = _origin + (_y * size);
MPoint zEnd = _origin + (_z * size);
short mx, my;
manip->mousePosition(mx, my);
short ox, oy, xx, xy, yx, yy, zx, zy;
view.worldToView(_origin, ox, oy);
view.worldToView(xEnd, xx, xy);
view.worldToView(yEnd, yx, yy);
view.worldToView(zEnd, zx, zy);
// Calculate approximate handle size in view space.
float viewLength = 0.0f;
viewLength = std::max(viewLength,
sqrtf(pow(float(xx) - float(ox), 2) + pow(float(xy) - float(oy), 2)));
viewLength = std::max(viewLength,
sqrtf(pow(float(yx) - float(ox), 2) + pow(float(yy) - float(oy), 2)));
viewLength = std::max(viewLength,
sqrtf(pow(float(zx) - float(ox), 2) + pow(float(zy) - float(oy), 2)));
float handleSize = MFnManip3D::handleSize() / 100.0f; // Probably on [0, 100].
float handleHeight = viewLength * handleSize * 0.5f;
float handleRadius = std::max(handleHeight * 0.25f, 4.0f);
// Determine if we're in range to any of the lines.
float curDist, t;
curDist = Util::distanceToLine(ox, oy, xx, xy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
curDist = Util::distanceToLine(ox, oy, yx, yy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
curDist = Util::distanceToLine(ox, oy, zx, zy, mx, my, &t);
if (curDist < handleRadius && t >= 0.0f && t <= 1.0f) {
return true;
}
return false;
}
void* MannequinMoveManipulator::creator() {
return new MannequinMoveManipulator;
}
MStatus MannequinMoveManipulator::initialize() {
return MS::kSuccess;
}
<|endoftext|> |
<commit_before>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrPathUtils.h"
#include "GrPoint.h"
const GrScalar GrPathUtils::gTolerance = GR_Scalar1;
static const uint32_t MAX_POINTS_PER_CURVE = 1 << 10;
uint32_t GrPathUtils::quadraticPointCount(const GrPoint points[],
GrScalar tol) {
GrScalar d = points[1].distanceToLineSegmentBetween(points[0], points[2]);
if (d < tol) {
return 1;
} else {
// Each time we subdivide, d should be cut in 4. So we need to
// subdivide x = log4(d/tol) times. x subdivisions creates 2^(x)
// points.
// 2^(log4(x)) = sqrt(x);
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
return GrMin(GrNextPow2(temp), MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateQuadraticPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
GrScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p2)) < tolSqd) {
(*points)[0] = p2;
*points += 1;
return 1;
}
GrPoint q[] = {
{ GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) },
{ GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) },
};
GrPoint r = { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateQuadraticPoints(p0, q[0], r, tolSqd, points, pointsLeft);
uint32_t b = generateQuadraticPoints(r, q[1], p2, tolSqd, points, pointsLeft);
return a + b;
}
uint32_t GrPathUtils::cubicPointCount(const GrPoint points[],
GrScalar tol) {
GrScalar d = GrMax(points[1].distanceToLineSegmentBetweenSqd(points[0], points[3]),
points[2].distanceToLineSegmentBetweenSqd(points[0], points[3]));
d = SkScalarSqrt(d);
if (d < tol) {
return 1;
} else {
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
return GrMin(GrNextPow2(temp), MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateCubicPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
const GrPoint& p3,
GrScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd &&
p2.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd)) {
(*points)[0] = p3;
*points += 1;
return 1;
}
GrPoint q[] = {
{ GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) },
{ GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) },
{ GrScalarAve(p2.fX, p3.fX), GrScalarAve(p2.fY, p3.fY) }
};
GrPoint r[] = {
{ GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) },
{ GrScalarAve(q[1].fX, q[2].fX), GrScalarAve(q[1].fY, q[2].fY) }
};
GrPoint s = { GrScalarAve(r[0].fX, r[1].fX), GrScalarAve(r[0].fY, r[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateCubicPoints(p0, q[0], r[0], s, tolSqd, points, pointsLeft);
uint32_t b = generateCubicPoints(s, r[1], q[2], p3, tolSqd, points, pointsLeft);
return a + b;
}
int GrPathUtils::worstCasePointCount(const GrPath& path, int* subpaths,
GrScalar tol) {
int pointCount = 0;
*subpaths = 1;
bool first = true;
SkPath::Iter iter(path, false);
GrPathCmd cmd;
GrPoint pts[4];
while ((cmd = (GrPathCmd)iter.next(pts)) != kEnd_PathCmd) {
switch (cmd) {
case kLine_PathCmd:
pointCount += 1;
break;
case kQuadratic_PathCmd:
pointCount += quadraticPointCount(pts, tol);
break;
case kCubic_PathCmd:
pointCount += cubicPointCount(pts, tol);
break;
case kMove_PathCmd:
pointCount += 1;
if (!first) {
++(*subpaths);
}
break;
default:
break;
}
first = false;
}
return pointCount;
}
<commit_msg>Pass forceClose "true" to SkPath::Iter constructor in GrPathUtils::worstCasePointCount(). worstCasePointCount() is sometimes returning a lower value than the number of points subsequently generated by the path renderers. This is because it constructs the SkPath::Iter with forceClose set to "false", while the path renderers use one with forceClose set to "true". They should both be the same, and since we're filling paths, I think it should be set "true".<commit_after>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrPathUtils.h"
#include "GrPoint.h"
const GrScalar GrPathUtils::gTolerance = GR_Scalar1;
static const uint32_t MAX_POINTS_PER_CURVE = 1 << 10;
uint32_t GrPathUtils::quadraticPointCount(const GrPoint points[],
GrScalar tol) {
GrScalar d = points[1].distanceToLineSegmentBetween(points[0], points[2]);
if (d < tol) {
return 1;
} else {
// Each time we subdivide, d should be cut in 4. So we need to
// subdivide x = log4(d/tol) times. x subdivisions creates 2^(x)
// points.
// 2^(log4(x)) = sqrt(x);
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
return GrMin(GrNextPow2(temp), MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateQuadraticPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
GrScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p2)) < tolSqd) {
(*points)[0] = p2;
*points += 1;
return 1;
}
GrPoint q[] = {
{ GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) },
{ GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) },
};
GrPoint r = { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateQuadraticPoints(p0, q[0], r, tolSqd, points, pointsLeft);
uint32_t b = generateQuadraticPoints(r, q[1], p2, tolSqd, points, pointsLeft);
return a + b;
}
uint32_t GrPathUtils::cubicPointCount(const GrPoint points[],
GrScalar tol) {
GrScalar d = GrMax(points[1].distanceToLineSegmentBetweenSqd(points[0], points[3]),
points[2].distanceToLineSegmentBetweenSqd(points[0], points[3]));
d = SkScalarSqrt(d);
if (d < tol) {
return 1;
} else {
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
return GrMin(GrNextPow2(temp), MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateCubicPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
const GrPoint& p3,
GrScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd &&
p2.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd)) {
(*points)[0] = p3;
*points += 1;
return 1;
}
GrPoint q[] = {
{ GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) },
{ GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) },
{ GrScalarAve(p2.fX, p3.fX), GrScalarAve(p2.fY, p3.fY) }
};
GrPoint r[] = {
{ GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) },
{ GrScalarAve(q[1].fX, q[2].fX), GrScalarAve(q[1].fY, q[2].fY) }
};
GrPoint s = { GrScalarAve(r[0].fX, r[1].fX), GrScalarAve(r[0].fY, r[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateCubicPoints(p0, q[0], r[0], s, tolSqd, points, pointsLeft);
uint32_t b = generateCubicPoints(s, r[1], q[2], p3, tolSqd, points, pointsLeft);
return a + b;
}
int GrPathUtils::worstCasePointCount(const GrPath& path, int* subpaths,
GrScalar tol) {
int pointCount = 0;
*subpaths = 1;
bool first = true;
SkPath::Iter iter(path, true);
GrPathCmd cmd;
GrPoint pts[4];
while ((cmd = (GrPathCmd)iter.next(pts)) != kEnd_PathCmd) {
switch (cmd) {
case kLine_PathCmd:
pointCount += 1;
break;
case kQuadratic_PathCmd:
pointCount += quadraticPointCount(pts, tol);
break;
case kCubic_PathCmd:
pointCount += cubicPointCount(pts, tol);
break;
case kMove_PathCmd:
pointCount += 1;
if (!first) {
++(*subpaths);
}
break;
default:
break;
}
first = false;
}
return pointCount;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 (RX64M) コア
@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "main.hpp"
#include "common/cmt_io.hpp"
#include "common/tpu_io.hpp"
#include "common/fifo.hpp"
#include "common/sci_io.hpp"
#ifdef WATCH_DOG
#include "common/wdt_man.hpp"
#endif
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief コア・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct core {
class timer_task {
volatile unsigned long millis_;
volatile unsigned long delay_;
public:
timer_task() : millis_(0), delay_(0) { }
volatile unsigned long get_millis() const { return millis_; }
volatile unsigned long get_delay() const { return delay_; }
void set_delay(volatile unsigned long n) { delay_ = n; }
void operator() ()
{
// LED::P = !LED::P();
// LED::P = 1;
eadc_server();
++millis_;
if(delay_ != 0) {
--delay_;
}
// LED::P = 0;
}
};
typedef device::tpu_io<device::TPU0, timer_task> TPU0;
TPU0 tpu0_;
class cmt_task {
void (*task_10ms_)();
volatile uint32_t millis10x_;
#ifdef WATCH_DOG
utils::wdt_man<device::WDT> wdt_man_;
volatile uint32_t wdt_count_;
volatile uint32_t wdt_limit_;
volatile bool wdt_enable_;
volatile bool wdt_stop_;
#endif
public:
cmt_task() : task_10ms_(nullptr),
millis10x_(0)
#ifdef WATCH_DOG
, wdt_man_(), wdt_count_(0), wdt_limit_(10 * 60 * 100), wdt_enable_(false), wdt_stop_(false)
#endif
{ }
void set_task_10ms(void (*task)(void)) {
task_10ms_ = task;
}
void sync()
{
volatile uint32_t tmp = millis10x_;
while(tmp == millis10x_) ;
}
#ifdef WATCH_DOG
void start_wdt() { wdt_man_.start(); }
void clear_wdt() { wdt_count_ = 0; }
void stop_wdt(bool stop = true) { wdt_stop_ = stop; }
void enable_wdt(bool ena = true) { wdt_enable_ = ena; }
void limit_wdt(uint32_t lim) { wdt_limit_ = lim; }
#endif
void operator() ()
{
#ifdef WATCH_DOG
if(wdt_stop_) {
// リフレッシュが止まり、強制リセット
} else if(wdt_enable_) {
++wdt_count_;
if(wdt_count_ < wdt_limit_) {
wdt_man_.refresh();
}
} else {
// WDT 無効: 常にリフレッシュ
wdt_man_.refresh();
}
#endif
if(task_10ms_ != nullptr) (*task_10ms_)();
++millis10x_;
}
};
typedef device::cmt_io<device::CMT0, cmt_task> CMT0;
CMT0 cmt0_;
typedef utils::fifo<uint8_t, 1024> BUFFER;
#ifdef SEEDA
typedef device::sci_io<device::SCI12, BUFFER, BUFFER> SCI;
#else
typedef device::sci_io<device::SCI7, BUFFER, BUFFER> SCI;
#endif
SCI sci_;
typedef device::S12AD ADC;
typedef device::adc_io<ADC, utils::null_task> ADC_IO;
ADC_IO adc_io_;
uint32_t list_cnt_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
core() : list_cnt_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init()
{
#ifdef SEEDA
{ // DIP-SW プルアップ
SW1::DIR = 0; // input
SW2::DIR = 0; // input
SW1::PU = 1;
SW2::PU = 1;
}
#endif
{ // SCI 設定
uint8_t int_level = 1;
sci_.start(115200, int_level);
}
{ // タイマー設定、100Hz(10ms)
uint8_t int_level = 5;
cmt0_.start(100, int_level);
#ifdef WATCH_DOG
cmt0_.at_task().start_wdt();
#endif
}
{ // タイマー設定、1000Hz(1ms)
uint8_t int_level = 6;
if(!tpu0_.start(1000, int_level)) {
utils::format("TPU0 not start ...\n");
}
}
{ // 内臓 A/D 変換設定
uint8_t intr_level = 0;
adc_io_.start(ADC::analog::AIN005, intr_level);
adc_io_.start(ADC::analog::AIN006, intr_level);
adc_io_.start(ADC::analog::AIN007, intr_level);
}
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void title()
{
// タイトル・コール
#ifdef SEEDA
utils::format("\nStart Seeda03 Build: %u Version %d.%02d\n") % build_id_
% (seeda_version_ / 100) % (seeda_version_ % 100);
#else
utils::format("\nStart GR-KAEDE Build: %u\n") % build_id_;
#endif
uint8_t mde = device::SYSTEM::MDE.MDE();
utils::format("Endian: %3b (%s)") % static_cast<uint32_t>(mde) % (mde == 0b111 ? "Little" : "Big");
utils::format(", PCLKA: %u [Hz]") % static_cast<uint32_t>(F_PCLKA);
utils::format(", PCLKB: %u [Hz]\n") % static_cast<uint32_t>(F_PCLKB);
utils::format("DIP-Switch-2 (Dev): %s\n") % (get_develope() ? "Enable" : "Disable");
utils::format("DIP-Switch-1 (CH): %d\n") % get_channel_num();
}
//-----------------------------------------------------------------//
/*!
@brief サービス同期
*/
//-----------------------------------------------------------------//
void sync()
{
cmt0_.at_task().sync();
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
#if 0
++list_cnt_;
if(list_cnt_ >= 100) {
auto val = adc_io_.get(ADC::analog::AIN005);
utils::format("AIN005: %d\n") % static_cast<int>(val);
list_cnt_ = 0;
}
#endif
adc_io_.scan();
}
//-----------------------------------------------------------------//
/*!
@brief A/D 変換値の取得
@param[in] ch チャネル(5、6、7)
@return A/D 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_adc(uint32_t ch) const {
return adc_io_.get(static_cast<ADC::analog>(ch));
}
//-----------------------------------------------------------------//
/*!
@brief タイマークラスのカウンター値の取得(1ms)
@return カウンター値
*/
//-----------------------------------------------------------------//
uint32_t get_cmt_counter() const {
return cmt0_.get_counter();
}
#ifdef WATCH_DOG
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグをクリア
*/
//-----------------------------------------------------------------//
void clear_wdt()
{
cmt0_.at_task().clear_wdt();
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグ、リフレッシュを停止 @n
※強制リセット
*/
//-----------------------------------------------------------------//
void stop_wdt()
{
cmt0_.at_task().stop_wdt();
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグを許可
@param[in] ena 「false」の場合無効
*/
//-----------------------------------------------------------------//
void enable_wdt(bool ena = true)
{
cmt0_.at_task().enable_wdt(ena);
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグ制限時間の設定
@param[in] lim 制限時間「ミリ秒」
*/
//-----------------------------------------------------------------//
void limit_wdt(uint32_t lim)
{
cmt0_.at_task().limit_wdt(lim);
}
#endif
};
}
<commit_msg>update: list OFS1 register for reset<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 (RX64M) コア
@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "main.hpp"
#include "common/cmt_io.hpp"
#include "common/tpu_io.hpp"
#include "common/fifo.hpp"
#include "common/sci_io.hpp"
#ifdef WATCH_DOG
#include "common/wdt_man.hpp"
#endif
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief コア・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct core {
class timer_task {
volatile unsigned long millis_;
volatile unsigned long delay_;
public:
timer_task() : millis_(0), delay_(0) { }
volatile unsigned long get_millis() const { return millis_; }
volatile unsigned long get_delay() const { return delay_; }
void set_delay(volatile unsigned long n) { delay_ = n; }
void operator() ()
{
// LED::P = !LED::P();
// LED::P = 1;
eadc_server();
++millis_;
if(delay_ != 0) {
--delay_;
}
// LED::P = 0;
}
};
typedef device::tpu_io<device::TPU0, timer_task> TPU0;
TPU0 tpu0_;
class cmt_task {
void (*task_10ms_)();
volatile uint32_t millis10x_;
#ifdef WATCH_DOG
utils::wdt_man<device::WDT> wdt_man_;
volatile uint32_t wdt_count_;
volatile uint32_t wdt_limit_;
volatile bool wdt_enable_;
volatile bool wdt_stop_;
#endif
public:
cmt_task() : task_10ms_(nullptr),
millis10x_(0)
#ifdef WATCH_DOG
, wdt_man_(), wdt_count_(0), wdt_limit_(10 * 60 * 100), wdt_enable_(false), wdt_stop_(false)
#endif
{ }
void set_task_10ms(void (*task)(void)) {
task_10ms_ = task;
}
void sync()
{
volatile uint32_t tmp = millis10x_;
while(tmp == millis10x_) ;
}
#ifdef WATCH_DOG
void start_wdt() { wdt_man_.start(); }
void clear_wdt() { wdt_count_ = 0; }
void stop_wdt(bool stop = true) { wdt_stop_ = stop; }
void enable_wdt(bool ena = true) { wdt_enable_ = ena; }
void limit_wdt(uint32_t lim) { wdt_limit_ = lim; }
#endif
void operator() ()
{
#ifdef WATCH_DOG
if(wdt_stop_) {
// リフレッシュが止まり、強制リセット
} else if(wdt_enable_) {
++wdt_count_;
if(wdt_count_ < wdt_limit_) {
wdt_man_.refresh();
}
} else {
// WDT 無効: 常にリフレッシュ
wdt_man_.refresh();
}
#endif
if(task_10ms_ != nullptr) (*task_10ms_)();
++millis10x_;
}
};
typedef device::cmt_io<device::CMT0, cmt_task> CMT0;
CMT0 cmt0_;
typedef utils::fifo<uint8_t, 1024> BUFFER;
#ifdef SEEDA
typedef device::sci_io<device::SCI12, BUFFER, BUFFER> SCI;
#else
typedef device::sci_io<device::SCI7, BUFFER, BUFFER> SCI;
#endif
SCI sci_;
typedef device::S12AD ADC;
typedef device::adc_io<ADC, utils::null_task> ADC_IO;
ADC_IO adc_io_;
uint32_t list_cnt_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
core() : list_cnt_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init()
{
#ifdef SEEDA
{ // DIP-SW プルアップ
SW1::DIR = 0; // input
SW2::DIR = 0; // input
SW1::PU = 1;
SW2::PU = 1;
}
#endif
{ // SCI 設定
uint8_t int_level = 1;
sci_.start(115200, int_level);
}
{ // タイマー設定、100Hz(10ms)
uint8_t int_level = 5;
cmt0_.start(100, int_level);
#ifdef WATCH_DOG
cmt0_.at_task().start_wdt();
#endif
}
{ // タイマー設定、1000Hz(1ms)
uint8_t int_level = 6;
if(!tpu0_.start(1000, int_level)) {
utils::format("TPU0 not start ...\n");
}
}
{ // 内臓 A/D 変換設定
uint8_t intr_level = 0;
adc_io_.start(ADC::analog::AIN005, intr_level);
adc_io_.start(ADC::analog::AIN006, intr_level);
adc_io_.start(ADC::analog::AIN007, intr_level);
}
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void title()
{
// タイトル・コール
#ifdef SEEDA
utils::format("\nStart Seeda03 Build: %u Version %d.%02d\n") % build_id_
% (seeda_version_ / 100) % (seeda_version_ % 100);
#else
utils::format("\nStart GR-KAEDE Build: %u\n") % build_id_;
#endif
uint8_t mde = device::SYSTEM::MDE.MDE();
utils::format("Endian: %3b (%s)")
% static_cast<uint32_t>(mde) % (mde == 0b111 ? "Little" : "Big");
utils::format(", PCLKA: %u [Hz]") % static_cast<uint32_t>(F_PCLKA);
utils::format(", PCLKB: %u [Hz]\n") % static_cast<uint32_t>(F_PCLKB);
static const char* vdsel[4] = { "---", "2.94V", "2.87V", "2.80V" };
utils::format("OFS1: VDSEL: %s, LVDAS: %s, HOCOEN: %s\n")
% vdsel[device::SYSTEM::OFS1.VDSEL()]
% (device::SYSTEM::OFS1.LVDAS() ? "Disable" : "Enable")
% (device::SYSTEM::OFS1.HOCOEN() ? "Disable" : "Enable");
utils::format("DIP-Switch-2 (Dev): %s\n") % (get_develope() ? "Enable" : "Disable");
utils::format("DIP-Switch-1 (CH): %d\n") % get_channel_num();
}
//-----------------------------------------------------------------//
/*!
@brief サービス同期
*/
//-----------------------------------------------------------------//
void sync()
{
cmt0_.at_task().sync();
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
#if 0
++list_cnt_;
if(list_cnt_ >= 100) {
auto val = adc_io_.get(ADC::analog::AIN005);
utils::format("AIN005: %d\n") % static_cast<int>(val);
list_cnt_ = 0;
}
#endif
adc_io_.scan();
}
//-----------------------------------------------------------------//
/*!
@brief A/D 変換値の取得
@param[in] ch チャネル(5、6、7)
@return A/D 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_adc(uint32_t ch) const {
return adc_io_.get(static_cast<ADC::analog>(ch));
}
//-----------------------------------------------------------------//
/*!
@brief タイマークラスのカウンター値の取得(1ms)
@return カウンター値
*/
//-----------------------------------------------------------------//
uint32_t get_cmt_counter() const {
return cmt0_.get_counter();
}
#ifdef WATCH_DOG
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグをクリア
*/
//-----------------------------------------------------------------//
void clear_wdt()
{
cmt0_.at_task().clear_wdt();
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグ、リフレッシュを停止 @n
※強制リセット
*/
//-----------------------------------------------------------------//
void stop_wdt()
{
cmt0_.at_task().stop_wdt();
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグを許可
@param[in] ena 「false」の場合無効
*/
//-----------------------------------------------------------------//
void enable_wdt(bool ena = true)
{
cmt0_.at_task().enable_wdt(ena);
}
//-----------------------------------------------------------------//
/*!
@brief ウオッチ・ドッグ制限時間の設定
@param[in] lim 制限時間「ミリ秒」
*/
//-----------------------------------------------------------------//
void limit_wdt(uint32_t lim)
{
cmt0_.at_task().limit_wdt(lim);
}
#endif
};
}
<|endoftext|> |
<commit_before>#include "physics/barycentric_rotating_dynamic_frame.hpp"
#include <memory>
#include "astronomy/frames.hpp"
#include "geometry/frame.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/rotation.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/constants.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/geometry.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::Bivector;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Time;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AbsoluteError;
using testing_utilities::AlmostEquals;
using ::testing::Lt;
namespace physics {
namespace {
constexpr char kBig[] = "Big";
constexpr char kSmall[] = "Small";
} // namespace
class BarycentricRotatingDynamicFrameTest : public ::testing::Test {
protected:
// The rotating frame centred on the barycentre of the two bodies.
using BigSmall = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, false /*inertial*/>;
BarycentricRotatingDynamicFrameTest()
: period_(10 * π * sqrt(5.0 / 7.0) * Second),
centre_of_mass_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
big_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
small_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()) {
solar_system_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model_two_bodies_test.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_two_bodies_test.proto.txt");
t0_ = solar_system_.epoch();
ephemeris_ = solar_system_.MakeEphemeris(
integrators::McLachlanAtela1992Order4Optimal<
Position<ICRFJ2000Equator>>(),
10 * Milli(Second),
1 * Milli(Metre));
ephemeris_->Prolong(t0_ + 2 * period_);
big_initial_state_ = solar_system_.initial_state(kBig);
big_gravitational_parameter_ = solar_system_.gravitational_parameter(kBig);
small_initial_state_ = solar_system_.initial_state(kSmall);
small_gravitational_parameter_ =
solar_system_.gravitational_parameter(kSmall);
centre_of_mass_initial_state_ =
Barycentre<ICRFJ2000Equator, GravitationalParameter>(
{big_initial_state_, small_initial_state_},
{big_gravitational_parameter_, small_gravitational_parameter_});
big_small_frame_ =
std::make_unique<
BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>(
ephemeris_.get(),
solar_system_.massive_body(*ephemeris_, kBig),
solar_system_.massive_body(*ephemeris_, kSmall));
}
Time const period_;
Instant t0_;
DegreesOfFreedom<ICRFJ2000Equator> centre_of_mass_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> big_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> small_initial_state_;
GravitationalParameter big_gravitational_parameter_;
GravitationalParameter small_gravitational_parameter_;
std::unique_ptr<BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>
big_small_frame_;
std::unique_ptr<Ephemeris<ICRFJ2000Equator>> ephemeris_;
SolarSystem<ICRFJ2000Equator> solar_system_;
};
TEST_F(BarycentricRotatingDynamicFrameTest, ToBigSmallFrameAtTime) {
int const kSteps = 100;
ContinuousTrajectory<ICRFJ2000Equator>::Hint big_hint;
ContinuousTrajectory<ICRFJ2000Equator>::Hint small_hint;
for (Instant t = t0_; t < t0_ + 1 * period_; t += period_ / kSteps) {
auto const to_big_small_frame_at_t = big_small_frame_->ToThisFrameAtTime(t);
// Check that the centre of mass is at the origin and doesn't move.
DegreesOfFreedom<BigSmall> const centre_of_mass_in_big_small_at_t =
to_big_small_frame_at_t(centre_of_mass_initial_state_);
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>()),
Lt(1.0E-11 * Metre));
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-11 * Metre / Second));
// Check that the bodies don't move and are at the right locations.
DegreesOfFreedom<ICRFJ2000Equator> const big_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kBig).
EvaluateDegreesOfFreedom(t, &big_hint);
DegreesOfFreedom<ICRFJ2000Equator> const small_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kSmall).
EvaluateDegreesOfFreedom(t, &small_hint);
DegreesOfFreedom<BigSmall> const big_in_big_small_at_t =
to_big_small_frame_at_t(big_in_inertial_frame_at_t);
DegreesOfFreedom<BigSmall> const small_in_big_small_at_t =
to_big_small_frame_at_t(small_in_inertial_frame_at_t);
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({15.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-6 * Metre));
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({-20.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-5 * Metre));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
}
}
} // namespace physics
} // namespace principia
<commit_msg>Inverse test.<commit_after>#include "physics/barycentric_rotating_dynamic_frame.hpp"
#include <memory>
#include "astronomy/frames.hpp"
#include "geometry/frame.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/rotation.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/constants.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/geometry.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::Bivector;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Time;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AbsoluteError;
using testing_utilities::AlmostEquals;
using ::testing::Lt;
namespace physics {
namespace {
constexpr char kBig[] = "Big";
constexpr char kSmall[] = "Small";
} // namespace
class BarycentricRotatingDynamicFrameTest : public ::testing::Test {
protected:
// The rotating frame centred on the barycentre of the two bodies.
using BigSmall = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, false /*inertial*/>;
BarycentricRotatingDynamicFrameTest()
: period_(10 * π * sqrt(5.0 / 7.0) * Second),
centre_of_mass_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
big_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
small_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()) {
solar_system_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model_two_bodies_test.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_two_bodies_test.proto.txt");
t0_ = solar_system_.epoch();
ephemeris_ = solar_system_.MakeEphemeris(
integrators::McLachlanAtela1992Order4Optimal<
Position<ICRFJ2000Equator>>(),
10 * Milli(Second),
1 * Milli(Metre));
ephemeris_->Prolong(t0_ + 2 * period_);
big_initial_state_ = solar_system_.initial_state(kBig);
big_gravitational_parameter_ = solar_system_.gravitational_parameter(kBig);
small_initial_state_ = solar_system_.initial_state(kSmall);
small_gravitational_parameter_ =
solar_system_.gravitational_parameter(kSmall);
centre_of_mass_initial_state_ =
Barycentre<ICRFJ2000Equator, GravitationalParameter>(
{big_initial_state_, small_initial_state_},
{big_gravitational_parameter_, small_gravitational_parameter_});
big_small_frame_ =
std::make_unique<
BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>(
ephemeris_.get(),
solar_system_.massive_body(*ephemeris_, kBig),
solar_system_.massive_body(*ephemeris_, kSmall));
}
Time const period_;
Instant t0_;
DegreesOfFreedom<ICRFJ2000Equator> centre_of_mass_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> big_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> small_initial_state_;
GravitationalParameter big_gravitational_parameter_;
GravitationalParameter small_gravitational_parameter_;
std::unique_ptr<BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>
big_small_frame_;
std::unique_ptr<Ephemeris<ICRFJ2000Equator>> ephemeris_;
SolarSystem<ICRFJ2000Equator> solar_system_;
};
TEST_F(BarycentricRotatingDynamicFrameTest, ToBigSmallFrameAtTime) {
int const kSteps = 100;
ContinuousTrajectory<ICRFJ2000Equator>::Hint big_hint;
ContinuousTrajectory<ICRFJ2000Equator>::Hint small_hint;
for (Instant t = t0_; t < t0_ + 1 * period_; t += period_ / kSteps) {
auto const to_big_small_frame_at_t = big_small_frame_->ToThisFrameAtTime(t);
// Check that the centre of mass is at the origin and doesn't move.
DegreesOfFreedom<BigSmall> const centre_of_mass_in_big_small_at_t =
to_big_small_frame_at_t(centre_of_mass_initial_state_);
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>()),
Lt(1.0E-11 * Metre));
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-11 * Metre / Second));
// Check that the bodies don't move and are at the right locations.
DegreesOfFreedom<ICRFJ2000Equator> const big_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kBig).
EvaluateDegreesOfFreedom(t, &big_hint);
DegreesOfFreedom<ICRFJ2000Equator> const small_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kSmall).
EvaluateDegreesOfFreedom(t, &small_hint);
DegreesOfFreedom<BigSmall> const big_in_big_small_at_t =
to_big_small_frame_at_t(big_in_inertial_frame_at_t);
DegreesOfFreedom<BigSmall> const small_in_big_small_at_t =
to_big_small_frame_at_t(small_in_inertial_frame_at_t);
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({15.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-6 * Metre));
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({-20.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-5 * Metre));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
}
}
TEST_F(BarycentricRotatingDynamicFrameTest, Inverse) {
int const kSteps = 100;
for (Instant t = t0_; t < t0_ + 1 * period_; t += period_ / kSteps) {
auto const from_big_small_frame_at_t =
big_small_frame_->FromThisFrameAtTime(t);
auto const to_big_small_frame_at_t = big_small_frame_->ToThisFrameAtTime(t);
auto const small_initial_state_transformed_and_back =
from_big_small_frame_at_t(to_big_small_frame_at_t(
small_initial_state_));
EXPECT_THAT(
AbsoluteError(small_initial_state_transformed_and_back.position() -
ICRFJ2000Equator::origin,
small_initial_state_.position() -
ICRFJ2000Equator::origin),
Lt(1.0E-11 * Metre));
EXPECT_THAT(
AbsoluteError(small_initial_state_transformed_and_back.velocity(),
small_initial_state_.velocity()),
Lt(1.0E-11 * Metre / Second));
}
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>#include <cassert>
#include <stdexcept>
#include "triton/ir/type.h"
#include "triton/ir/context.h"
#include "triton/ir/context_impl.h"
#include "triton/ir/value.h"
#include "triton/ir/constant.h"
namespace triton{
namespace ir{
//===----------------------------------------------------------------------===//
// type class
//===----------------------------------------------------------------------===//
// attributes
type *type::get_scalar_ty() const {
if(is_block_ty())
return get_tile_element_ty();
return const_cast<type*>(this);
}
unsigned type::get_primitive_size_in_bits() const {
switch (id_) {
case FP8TyID: return 8;
case FP16TyID: return 16;
case BF16TyID: return 16;
case FP32TyID: return 32;
case FP64TyID: return 64;
case IntegerTyID: return ((integer_type*)(this))->get_bitwidth();
case BlockTyID: return ((block_type*)(this))->get_bitwidth();
default: return 0;
}
}
unsigned type::get_integer_bitwidth() const
{ assert(id_ == IntegerTyID); return ((integer_type*)(this))->get_bitwidth(); }
unsigned type::get_tile_bitwidth() const
{ return ((block_type*)(this))->get_bitwidth(); }
unsigned type::get_fp_mantissa_width() const {
id_t id = get_scalar_ty()->id_;
assert(is_floating_point_ty() && "Not a floating point type!");
if (id == FP8TyID) return 3;
if (id == FP16TyID) return 10;
if (id == BF16TyID) return 7;
if (id == FP32TyID) return 23;
if (id == FP64TyID) return 53;
throw std::runtime_error("unreachable");
}
type* type::get_tile_element_ty() const {
assert(is_block_ty());
return contained_tys_[0];
}
unsigned type::get_pointer_address_space() const {
assert(is_pointer_ty());
return ((pointer_type*)this)->get_address_space();
}
type * type::get_pointer_element_ty() const {
type *ptr_ty = get_scalar_ty();
assert(ptr_ty->is_pointer_ty());
type *scalar_ty = ((pointer_type*)ptr_ty)->get_element_ty();
if(is_block_ty())
return block_type::get_same_shapes(scalar_ty, (type*)this);
return scalar_ty;
}
type::block_shapes_t type::get_block_shapes() const {
assert(is_block_ty());
return ((block_type*)this)->get_shapes();
}
const size_t type::get_tile_rank() const {
return get_block_shapes().size();
}
const size_t type::get_tile_ranks1() const {
int ret = 0;
for(int s: get_block_shapes())
ret += s > 1;
return ret;
}
unsigned type::get_tile_num_elements() const {
const block_shapes_t& shapes = get_block_shapes();
unsigned result = 1;
for(auto shape: shapes)
result *= shape;
return result;
}
// composite predicates
bool type::is_int_or_tileint_ty()
{ return get_scalar_ty()->is_integer_ty(); }
bool type::is_integer_ty(unsigned width) const
{ return is_integer_ty() && get_integer_bitwidth()== width; }
bool type::is_floating_point_ty() const
{ return is_fp8_ty() || is_fp16_ty() || is_bf16_ty() || is_fp32_ty() || is_fp64_ty(); }
bool type::is_sized() const {
// primitive types are sized
if(is_integer_ty() || is_floating_point_ty() ||
is_pointer_ty()){
return true;
}
// tile types are sizes
if(is_block_ty())
return get_scalar_ty()->is_sized();
return false;
}
// primitive types
type *type::get_void_ty(context &ctx) { return &ctx.p_impl->void_ty; }
type *type::get_label_ty(context &ctx) { return &ctx.p_impl->label_ty; }
// floating point
type *type::get_fp8_ty(context &ctx) { return &ctx.p_impl->fp8_ty; }
type *type::get_fp16_ty(context &ctx) { return &ctx.p_impl->fp16_ty; }
type *type::get_bf16_ty(context &ctx) { return &ctx.p_impl->bf16_ty; }
type *type::get_fp32_ty(context &ctx) { return &ctx.p_impl->fp32_ty; }
type *type::get_fp64_ty(context &ctx) { return &ctx.p_impl->fp64_ty; }
// integer types
integer_type *type::get_int1_ty(context &ctx) { return &ctx.p_impl->int1_ty; }
integer_type *type::get_int8_ty(context &ctx) { return &ctx.p_impl->int8_ty; }
integer_type *type::get_int16_ty(context &ctx) { return &ctx.p_impl->int16_ty; }
integer_type *type::get_int32_ty(context &ctx) { return &ctx.p_impl->int32_ty; }
integer_type *type::get_int64_ty(context &ctx) { return &ctx.p_impl->int64_ty; }
integer_type *type::get_int128_ty(context &ctx) { return &ctx.p_impl->int128_ty; }
pointer_type::pointer_type(type *ty, unsigned address_space)
: type(ty->get_context(), PointerTyID), address_space_(address_space){
contained_tys_.push_back(ty);
}
bool pointer_type::is_valid_elt_ty(type *ty){
return !ty->is_void_ty() && !ty->is_label_ty() &&
!ty->is_metadata_ty() && !ty->is_token_ty();
}
pointer_type* pointer_type::get(type *elt_ty, unsigned address_space){
assert(elt_ty && "Can't get a pointer to <null> type!");
assert(is_valid_elt_ty(elt_ty) && "Invalid type for pointer element!");
// look-up
context_impl *impl = elt_ty->get_context().p_impl.get();
std::unique_ptr<pointer_type> &entry = impl->ptr_tys[std::make_pair(elt_ty, address_space)];
if(!entry)
entry.reset(new pointer_type(elt_ty, address_space));
return entry.get();
}
//===----------------------------------------------------------------------===//
// composite_type class
//===----------------------------------------------------------------------===//
type* composite_type::get_type_at_index(value *) const{
assert(is_block_ty());
return get_scalar_ty();
}
bool composite_type::index_valid(value *idx) const{
assert(is_block_ty());
return idx->get_type()->is_int_or_tileint_ty();
}
//===----------------------------------------------------------------------===//
// struct_type class
//===----------------------------------------------------------------------===//
struct_type::struct_type(const contained_tys_vec_t& tys, bool is_packed)
: composite_type(tys[0]->get_context(), StructTyID), is_packed_(is_packed) {
contained_tys_ = tys;
}
struct_type* struct_type::get(const contained_tys_vec_t& tys, bool is_packed) {
assert(tys.size());
context_impl* impl = tys[0]->get_context().p_impl.get();
struct_type *& entry = impl->struct_tys[tys];
if(!entry)
entry = new struct_type(tys, is_packed);
return entry;
}
//===----------------------------------------------------------------------===//
// block_type class
//===----------------------------------------------------------------------===//
block_type::block_type(type *ty, const block_shapes_t &shapes)
: composite_type(ty->get_context(), BlockTyID), shapes_(shapes) {
contained_tys_.push_back(ty);
}
bool block_type::is_valid_elt_ty(type *ty) {
return ty->is_pointer_ty() || ty->is_floating_point_ty() || ty->is_integer_ty();
}
unsigned block_type::get_num_elements() const {
unsigned res = 1;
for(auto shape: shapes_)
res *= shape;
return res;
}
unsigned block_type::get_bitwidth() const {
return get_num_elements() * get_tile_element_ty()->get_primitive_size_in_bits();
}
block_type* block_type::get(type *elt_ty, const block_shapes_t &shapes) {
assert(elt_ty && "Can't get a tile of <null> type!");
assert(shapes.size() && "Can't create a tile with empty shapes!");
assert(is_valid_elt_ty(elt_ty) && "Invalid type for tile element!");
// look-up
context_impl *impl = elt_ty->get_context().p_impl.get();
std::unique_ptr<block_type> &entry = impl->block_tys[std::make_pair(elt_ty, shapes)];
if(!entry)
entry.reset(new block_type(elt_ty, shapes));
return entry.get();
}
block_type* block_type::get_same_shapes(type *ty, type *ref){
assert(ref->is_block_ty());
return get(ty, ref->get_block_shapes());
}
//===----------------------------------------------------------------------===//
// function_type class
//===----------------------------------------------------------------------===//
function_type::function_type(type *ret_ty, const std::vector<type*> ¶m_tys):
type(ret_ty->get_context(), FunctionTyID) {
contained_tys_.push_back(ret_ty);
for(type *ty: param_tys)
contained_tys_.push_back(ty);
}
function_type* function_type::get(type *ret_ty, const std::vector<type *> ¶m_tys) {
return new function_type(ret_ty, param_tys);
}
}
}
<commit_msg>[BACKEND][IR] Fixed up internal dtype size for booleans (1bit -> 8bit) (#600)<commit_after>#include <cassert>
#include <stdexcept>
#include "triton/ir/type.h"
#include "triton/ir/context.h"
#include "triton/ir/context_impl.h"
#include "triton/ir/value.h"
#include "triton/ir/constant.h"
namespace triton{
namespace ir{
//===----------------------------------------------------------------------===//
// type class
//===----------------------------------------------------------------------===//
// attributes
type *type::get_scalar_ty() const {
if(is_block_ty())
return get_tile_element_ty();
return const_cast<type*>(this);
}
unsigned type::get_primitive_size_in_bits() const {
switch (id_) {
case FP8TyID: return 8;
case FP16TyID: return 16;
case BF16TyID: return 16;
case FP32TyID: return 32;
case FP64TyID: return 64;
case IntegerTyID: return std::max<int>(8, ((integer_type*)(this))->get_bitwidth());
case BlockTyID: return ((block_type*)(this))->get_bitwidth();
default: return 0;
}
}
unsigned type::get_integer_bitwidth() const
{ assert(id_ == IntegerTyID); return ((integer_type*)(this))->get_bitwidth(); }
unsigned type::get_tile_bitwidth() const
{ return ((block_type*)(this))->get_bitwidth(); }
unsigned type::get_fp_mantissa_width() const {
id_t id = get_scalar_ty()->id_;
assert(is_floating_point_ty() && "Not a floating point type!");
if (id == FP8TyID) return 3;
if (id == FP16TyID) return 10;
if (id == BF16TyID) return 7;
if (id == FP32TyID) return 23;
if (id == FP64TyID) return 53;
throw std::runtime_error("unreachable");
}
type* type::get_tile_element_ty() const {
assert(is_block_ty());
return contained_tys_[0];
}
unsigned type::get_pointer_address_space() const {
assert(is_pointer_ty());
return ((pointer_type*)this)->get_address_space();
}
type * type::get_pointer_element_ty() const {
type *ptr_ty = get_scalar_ty();
assert(ptr_ty->is_pointer_ty());
type *scalar_ty = ((pointer_type*)ptr_ty)->get_element_ty();
if(is_block_ty())
return block_type::get_same_shapes(scalar_ty, (type*)this);
return scalar_ty;
}
type::block_shapes_t type::get_block_shapes() const {
assert(is_block_ty());
return ((block_type*)this)->get_shapes();
}
const size_t type::get_tile_rank() const {
return get_block_shapes().size();
}
const size_t type::get_tile_ranks1() const {
int ret = 0;
for(int s: get_block_shapes())
ret += s > 1;
return ret;
}
unsigned type::get_tile_num_elements() const {
const block_shapes_t& shapes = get_block_shapes();
unsigned result = 1;
for(auto shape: shapes)
result *= shape;
return result;
}
// composite predicates
bool type::is_int_or_tileint_ty()
{ return get_scalar_ty()->is_integer_ty(); }
bool type::is_integer_ty(unsigned width) const
{ return is_integer_ty() && get_integer_bitwidth()== width; }
bool type::is_floating_point_ty() const
{ return is_fp8_ty() || is_fp16_ty() || is_bf16_ty() || is_fp32_ty() || is_fp64_ty(); }
bool type::is_sized() const {
// primitive types are sized
if(is_integer_ty() || is_floating_point_ty() ||
is_pointer_ty()){
return true;
}
// tile types are sizes
if(is_block_ty())
return get_scalar_ty()->is_sized();
return false;
}
// primitive types
type *type::get_void_ty(context &ctx) { return &ctx.p_impl->void_ty; }
type *type::get_label_ty(context &ctx) { return &ctx.p_impl->label_ty; }
// floating point
type *type::get_fp8_ty(context &ctx) { return &ctx.p_impl->fp8_ty; }
type *type::get_fp16_ty(context &ctx) { return &ctx.p_impl->fp16_ty; }
type *type::get_bf16_ty(context &ctx) { return &ctx.p_impl->bf16_ty; }
type *type::get_fp32_ty(context &ctx) { return &ctx.p_impl->fp32_ty; }
type *type::get_fp64_ty(context &ctx) { return &ctx.p_impl->fp64_ty; }
// integer types
integer_type *type::get_int1_ty(context &ctx) { return &ctx.p_impl->int1_ty; }
integer_type *type::get_int8_ty(context &ctx) { return &ctx.p_impl->int8_ty; }
integer_type *type::get_int16_ty(context &ctx) { return &ctx.p_impl->int16_ty; }
integer_type *type::get_int32_ty(context &ctx) { return &ctx.p_impl->int32_ty; }
integer_type *type::get_int64_ty(context &ctx) { return &ctx.p_impl->int64_ty; }
integer_type *type::get_int128_ty(context &ctx) { return &ctx.p_impl->int128_ty; }
pointer_type::pointer_type(type *ty, unsigned address_space)
: type(ty->get_context(), PointerTyID), address_space_(address_space){
contained_tys_.push_back(ty);
}
bool pointer_type::is_valid_elt_ty(type *ty){
return !ty->is_void_ty() && !ty->is_label_ty() &&
!ty->is_metadata_ty() && !ty->is_token_ty();
}
pointer_type* pointer_type::get(type *elt_ty, unsigned address_space){
assert(elt_ty && "Can't get a pointer to <null> type!");
assert(is_valid_elt_ty(elt_ty) && "Invalid type for pointer element!");
// look-up
context_impl *impl = elt_ty->get_context().p_impl.get();
std::unique_ptr<pointer_type> &entry = impl->ptr_tys[std::make_pair(elt_ty, address_space)];
if(!entry)
entry.reset(new pointer_type(elt_ty, address_space));
return entry.get();
}
//===----------------------------------------------------------------------===//
// composite_type class
//===----------------------------------------------------------------------===//
type* composite_type::get_type_at_index(value *) const{
assert(is_block_ty());
return get_scalar_ty();
}
bool composite_type::index_valid(value *idx) const{
assert(is_block_ty());
return idx->get_type()->is_int_or_tileint_ty();
}
//===----------------------------------------------------------------------===//
// struct_type class
//===----------------------------------------------------------------------===//
struct_type::struct_type(const contained_tys_vec_t& tys, bool is_packed)
: composite_type(tys[0]->get_context(), StructTyID), is_packed_(is_packed) {
contained_tys_ = tys;
}
struct_type* struct_type::get(const contained_tys_vec_t& tys, bool is_packed) {
assert(tys.size());
context_impl* impl = tys[0]->get_context().p_impl.get();
struct_type *& entry = impl->struct_tys[tys];
if(!entry)
entry = new struct_type(tys, is_packed);
return entry;
}
//===----------------------------------------------------------------------===//
// block_type class
//===----------------------------------------------------------------------===//
block_type::block_type(type *ty, const block_shapes_t &shapes)
: composite_type(ty->get_context(), BlockTyID), shapes_(shapes) {
contained_tys_.push_back(ty);
}
bool block_type::is_valid_elt_ty(type *ty) {
return ty->is_pointer_ty() || ty->is_floating_point_ty() || ty->is_integer_ty();
}
unsigned block_type::get_num_elements() const {
unsigned res = 1;
for(auto shape: shapes_)
res *= shape;
return res;
}
unsigned block_type::get_bitwidth() const {
return get_num_elements() * get_tile_element_ty()->get_primitive_size_in_bits();
}
block_type* block_type::get(type *elt_ty, const block_shapes_t &shapes) {
assert(elt_ty && "Can't get a tile of <null> type!");
assert(shapes.size() && "Can't create a tile with empty shapes!");
assert(is_valid_elt_ty(elt_ty) && "Invalid type for tile element!");
// look-up
context_impl *impl = elt_ty->get_context().p_impl.get();
std::unique_ptr<block_type> &entry = impl->block_tys[std::make_pair(elt_ty, shapes)];
if(!entry)
entry.reset(new block_type(elt_ty, shapes));
return entry.get();
}
block_type* block_type::get_same_shapes(type *ty, type *ref){
assert(ref->is_block_ty());
return get(ty, ref->get_block_shapes());
}
//===----------------------------------------------------------------------===//
// function_type class
//===----------------------------------------------------------------------===//
function_type::function_type(type *ret_ty, const std::vector<type*> ¶m_tys):
type(ret_ty->get_context(), FunctionTyID) {
contained_tys_.push_back(ret_ty);
for(type *ty: param_tys)
contained_tys_.push_back(ty);
}
function_type* function_type::get(type *ret_ty, const std::vector<type *> ¶m_tys) {
return new function_type(ret_ty, param_tys);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
// Use of this source code is governed by the BSD license that can be found in
// the LICENSE file.
#include "logger.h"
namespace kl {
namespace logging {
const char *kLogLevelString[5] = {"INFO", "DEBUG", "WARN", "ERROR", "FATAL"};
Logger::Logger(std::function<void(const char *)> &&output)
: log_level_(kInfo), output_(std::move(output)) {}
Logger::Logger(int log_level, std::function<void(const char *)> &&output)
: log_level_(log_level), output_(std::move(output)) {}
std::unique_ptr<Logger> Logger::default_logger_(new Logger([](const char *msg) {
std::fprintf(stderr, "%s\n", msg);
}));
void Logger::Logging(int log_level, const char *file, const char *func,
int line, const char *fmt, ...) {
if (log_level < log_level_) {
return;
}
va_list ap;
va_start(ap, fmt);
Logging(log_level, file, func, line, fmt, ap);
va_end(ap);
}
void Logger::Logging(int log_level, const char *file, const char *func,
int line, const char *fmt, va_list ap) {
int prefix_size = std::snprintf(nullptr, 0, "[%s %s:%s:%d] ",
kLogLevelString[log_level], file, func, line);
va_list backup_ap;
va_copy(backup_ap, ap);
int msg_size = std::vsnprintf(nullptr, 0, fmt, backup_ap);
va_end(backup_ap);
int buf_size = prefix_size + msg_size + 1;
char *buf = new char[buf_size];
const char *base = buf;
prefix_size = std::snprintf(buf, buf_size, "[%s %s:%s:%d] ",
kLogLevelString[log_level], file, func, line);
buf += prefix_size;
assert(buf_size >= prefix_size);
std::vsnprintf(buf, buf_size - prefix_size, fmt, ap);
output_(base);
delete[] base;
}
Logger &Logger::DefaultLogger() {
assert(default_logger_);
return *default_logger_;
}
void Logger::SetDefaultLogger(Logger &&logger) {
default_logger_ = std::make_unique<Logger>(std::move(logger));
}
void Logger::SetLogLevel(int log_level) { log_level_ = log_level; }
} // namespace logging
} // namespace kl
<commit_msg>add timestamp<commit_after>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
// Use of this source code is governed by the BSD license that can be found in
// the LICENSE file.
#include <sys/time.h>
#include "logger.h"
namespace kl {
namespace logging {
const char *kLogLevelString[5] = {"INFO", "DEBUG", "WARN", "ERROR", "FATAL"};
Logger::Logger(std::function<void(const char *)> &&output)
: log_level_(kInfo), output_(std::move(output)) {}
Logger::Logger(int log_level, std::function<void(const char *)> &&output)
: log_level_(log_level), output_(std::move(output)) {}
std::unique_ptr<Logger> Logger::default_logger_(new Logger([](const char *msg) {
std::fprintf(stderr, "%s\n", msg);
}));
void Logger::Logging(int log_level, const char *file, const char *func,
int line, const char *fmt, ...) {
if (log_level < log_level_) {
return;
}
va_list ap;
va_start(ap, fmt);
Logging(log_level, file, func, line, fmt, ap);
va_end(ap);
}
void Logger::Logging(int log_level, const char *file, const char *func,
int line, const char *fmt, va_list ap) {
if (log_level < log_level_) {
return;
}
struct timeval now;
::gettimeofday(&now, nullptr);
struct tm t;
::localtime_r(&now.tv_sec, &t);
int prefix_size = std::snprintf(
nullptr, 0, "[%s %04d/%02d/%02d-%02d:%02d:%02d.%06ld %s:%s:%d] ",
kLogLevelString[log_level], t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec, now.tv_usec, file, func, line);
va_list backup_ap;
va_copy(backup_ap, ap);
int msg_size = std::vsnprintf(nullptr, 0, fmt, backup_ap);
va_end(backup_ap);
int buf_size = prefix_size + msg_size + 1;
char *buf = new char[buf_size];
const char *base = buf;
prefix_size = std::snprintf(
buf, buf_size, "[%s %04d/%02d/%02d-%02d:%02d:%02d.%06ld %s:%s:%d] ",
kLogLevelString[log_level], t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec, now.tv_usec, file, func, line);
buf += prefix_size;
assert(buf_size >= prefix_size);
std::vsnprintf(buf, buf_size - prefix_size, fmt, ap);
output_(base);
delete[] base;
}
Logger &Logger::DefaultLogger() {
assert(default_logger_);
return *default_logger_;
}
void Logger::SetDefaultLogger(Logger &&logger) {
default_logger_ = std::make_unique<Logger>(std::move(logger));
}
void Logger::SetLogLevel(int log_level) { log_level_ = log_level; }
} // namespace logging
} // namespace kl
<|endoftext|> |
<commit_before>#include "xchainer/python/device.h"
#include <sstream>
#include "xchainer/device.h"
namespace xchainer {
namespace py = pybind11; // standard convention
void InitXchainerDevice(pybind11::module& m) {
py::class_<Device>(m, "Device").def("__repr__", [](Device device) {
std::ostringstream os;
os << "<Device " << device.name << ">";
return os.str();
});
m.def("get_current_device", []() { return GetCurrentDevice(); });
m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}
} // namespace xchainer
<commit_msg>Support Python-level Device ctor and comparison<commit_after>#include "xchainer/python/device.h"
#include <sstream>
#include "xchainer/device.h"
namespace xchainer {
namespace py = pybind11; // standard convention
void InitXchainerDevice(pybind11::module& m) {
py::class_<Device>(m, "Device")
.def(py::init(&MakeDevice))
.def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==))
.def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=))
.def("__repr__",
[](Device device) {
std::ostringstream os;
os << "<Device " << device.name << ">";
return os.str();
});
m.def("get_current_device", []() { return GetCurrentDevice(); });
m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}
} // namespace xchainer
<|endoftext|> |
<commit_before>#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/types.h>
#include <dirent.h>
#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus/natus.hpp>
using namespace natus;
#define ENGINEDIR "../engines/.libs"
int doTest(Engine& engine, Value& global);
int main() {
int retval = 0;
DIR* dir = opendir(ENGINEDIR);
if (!dir) return 1;
struct dirent *ent = NULL;
while ((ent = readdir(dir))) {
if (retval != 0) break;
size_t flen = strlen(ent->d_name);
size_t slen = strlen(MODSUFFIX);
if (!strcmp(".", ent->d_name) || !strcmp("..", ent->d_name)) continue;
if (flen < slen || strcmp(ent->d_name + flen - slen, MODSUFFIX)) continue;
char *tmp = (char *) new char[flen + strlen(ENGINEDIR) + 2];
if (!tmp) {
retval = 1;
break;
}
strcpy(tmp, ENGINEDIR);
strcat(tmp, "/");
strcat(tmp, ent->d_name);
Engine engine;
if (!engine.initialize(tmp)) {
retval = 1;
fprintf(stderr, "Unable to init engine! %s\n",tmp);
}
printf("Engine: %s\n", engine.getName());
if (retval == 0) {
Value global = engine.newGlobal();
// Run each test 100 times to check for incremental memory corruption
for (int i=0 ; i < 1 ; i++) {
if ((retval = doTest(engine, global)))
break;
}
}
delete[] tmp;
}
closedir(dir);
return retval;
}
<commit_msg>remove debug printf<commit_after>#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/types.h>
#include <dirent.h>
#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus/natus.hpp>
using namespace natus;
#define ENGINEDIR "../engines/.libs"
int doTest(Engine& engine, Value& global);
int main() {
int retval = 0;
DIR* dir = opendir(ENGINEDIR);
if (!dir) return 1;
struct dirent *ent = NULL;
while ((ent = readdir(dir))) {
if (retval != 0) break;
size_t flen = strlen(ent->d_name);
size_t slen = strlen(MODSUFFIX);
if (!strcmp(".", ent->d_name) || !strcmp("..", ent->d_name)) continue;
if (flen < slen || strcmp(ent->d_name + flen - slen, MODSUFFIX)) continue;
char *tmp = (char *) new char[flen + strlen(ENGINEDIR) + 2];
if (!tmp) {
retval = 1;
break;
}
strcpy(tmp, ENGINEDIR);
strcat(tmp, "/");
strcat(tmp, ent->d_name);
Engine engine;
if (!engine.initialize(tmp)) {
retval = 1;
fprintf(stderr, "Unable to init engine! %s\n",tmp);
}
//printf("Engine: %s\n", engine.getName());
if (retval == 0) {
Value global = engine.newGlobal();
// Run each test 100 times to check for incremental memory corruption
for (int i=0 ; i < 1 ; i++) {
if ((retval = doTest(engine, global)))
break;
}
}
delete[] tmp;
}
closedir(dir);
return retval;
}
<|endoftext|> |
<commit_before>#include "stack.h"
namespace BMF {
/*
* TODO:
* 1. Decide which info/format fields for each variant.
* 2. Decide to have a number of fields
*/
SampleVCFPos::SampleVCFPos(std::unordered_map<std::string, UniqueObservation>& obs, int32_t tid, int32_t pos):
size(obs.size()),
pos(pos),
tid(tid) {
templates.reserve(4);
for(auto& pair: obs) templates[pair.second.base_call].push_back(&pair.second);
}
void SampleVCFPos::to_bcf(bcf1_t *vrec, bcf_hdr_t *hdr, char refbase) {
std::vector<int> counts;
std::vector<int> duplex_counts;
std::vector<int> overlap_counts;
int count_index = 0;
vrec->rid = tid;
vrec->pos = pos;
vrec->qual = 0;
kstring_t allele_str = {0, 0, nullptr};
ks_resize(&allele_str, 20uL);
kputc(refbase, &allele_str);
auto match = templates.find(refbase);
if(match == templates.end()) {
counts.resize(templates.size() + 1);
duplex_counts.resize(templates.size() + 1);
overlap_counts.resize(templates.size() + 1);
bcf_update_info_flag(hdr, vrec, "NOREF", nullptr, 1);
// No reference calls? Add appropriate info fields.
} else {
counts.resize(templates.size());
duplex_counts.resize(templates.size());
overlap_counts.resize(templates.size());
counts[0] = match->second.size();
for(auto uni: templates[refbase]) {
duplex_counts[0] += uni->get_duplex();
overlap_counts[0] += uni->get_overlap();
}
}
for(auto& pair: templates) {
if(pair.first != refbase)
kputc(',', &allele_str), kputc((int)pair.first, &allele_str);
counts[++count_index] = pair.second.size();
for(auto uni: templates[pair.first]) {
duplex_counts[count_index] += uni->get_duplex();
overlap_counts[count_index] += uni->get_overlap();
}
// Update records
}
bcf_update_alleles_str(hdr, vrec, allele_str.s);
bcf_update_format(hdr, vrec, "ADP", (const void *)counts.data(), counts.size(), 'i');
bcf_update_format(hdr, vrec, "ADPD", (const void *)duplex_counts.data(), duplex_counts.size(), 'i');
bcf_update_format(hdr, vrec, "ADPO", (const void *)overlap_counts.data(), overlap_counts.size(), 'i');
}
void UniqueObservation::add_obs(const bam_pileup1_t& plp) {
LOG_ASSERT(strcmp(qname.c_str(), bam_get_qname(plp.b)) == 0);
size += bam_itag(plp.b, "FM");
base2 = seq_nt16_str[bam_seqi(bam_get_seq(plp.b), plp.qpos)];
cycle2 = dlib::arr_qpos(&plp);
mq2 = (uint32_t)plp.b->core.qual;
is_reverse2 = bam_is_rev(plp.b);
is_overlap = 1;
if(base2 == base1) {
discordant = 0;
agreed += ((uint32_t *)dlib::array_tag(plp.b, "FA"))[cycle2];
quality = agreed_pvalues(quality, ((uint32_t *)dlib::array_tag(plp.b, "PV"))[cycle2]);
pvalue = std::pow(10, -0.1 * quality);
rv += bam_itag(plp.b, "RV");
} else if(base1 == 'N') {
discordant = 0;
// Basically, throw out
base_call = base2;
agreed = ((uint32_t *)dlib::array_tag(plp.b, "FA"))[cycle2];
quality = ((uint32_t *)dlib::array_tag(plp.b, "PV"))[cycle2];
pvalue = std::pow(10, -0.1 * quality);
rv = (uint32_t)bam_itag(plp.b, "RV");
} else if(base2 != 'N') {
discordant = 1;
base_call = 'N';
agreed = 0;
quality = 0;
pvalue = 1.;
}
}
void PairVCFPos::to_bcf(bcf1_t *vrec, stack_aux_t *aux, int ttid, int tpos) {
const char refbase = aux->get_ref_base(ttid, tpos);
int ambig[2] = {0, 0};
std::unordered_set<char> base_set{refbase};
for(auto& pair: tumor.templates) {
if(pair.first == 'N') {
ambig[0] = pair.second.size();
continue;
}
base_set.insert(pair.first);
}
for(auto& pair: normal.templates) {
if(pair.first == 'N') {
ambig[1] = pair.second.size();
continue;
}
base_set.insert(pair.first);
}
std::vector<char> base_calls(base_set.begin(), base_set.end());
const size_t n_base_calls = base_calls.size();
#if 0
std::string tmp;
for(auto call: base_calls) tmp.push_back((char)call);
LOG_DEBUG("N base calls: %i. string: %s\n", (int)n_base_calls, tmp.c_str());
#endif
// Sort lexicographically AFTER putting the reference base first.
std::sort(base_calls.begin(), base_calls.end(), [refbase](const char a, const char b) {
return (a == refbase) ? true : (b == refbase) ? false: a < b;
});
std::vector<int> counts(n_base_calls * 2);
std::vector<int> duplex_counts(n_base_calls * 2);
std::vector<int> overlap_counts(n_base_calls * 2);
std::vector<int> reverse_counts(n_base_calls * 2);
std::vector<int> failed_counts(n_base_calls * 2);
std::vector<int> allele_passes(n_base_calls * 2);
std::vector<int> qscore_sums(n_base_calls * 2);
std::vector<int> somatic(n_base_calls);
vrec->rid = tumor.tid;
vrec->pos = tumor.pos;
vrec->qual = 0;
vrec->n_sample = 2;
auto match = tumor.templates.find(refbase);
if(match != tumor.templates.end()) {
// Already 0-initialized if not found.
counts[0] = match->second.size();
// auto without "reference" because auto is pointers.
for(auto uni: tumor.templates[refbase]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[0];
continue;
}
duplex_counts[0] += uni->get_duplex();
overlap_counts[0] += uni->get_overlap();
reverse_counts[0] += uni->get_reverse();
qscore_sums[0] += uni->get_quality();
allele_passes[0] = (duplex_counts[0] >= aux->conf.minDuplex &&
counts[0] >= aux->conf.minCount &&
overlap_counts[0] >= aux->conf.minOverlap);
}
}
if((match = normal.templates.find(refbase)) != normal.templates.end()) {
counts[n_base_calls] = match->second.size();
// auto without "reference" because auto is pointers.
for(auto uni: normal.templates[refbase]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[n_base_calls];
continue;
}
duplex_counts[n_base_calls] += uni->get_duplex();
overlap_counts[n_base_calls] += uni->get_overlap();
reverse_counts[n_base_calls] += uni->get_reverse();
qscore_sums[n_base_calls] += uni->get_quality();
}
allele_passes[n_base_calls] = (duplex_counts[n_base_calls] >= aux->conf.minDuplex &&
counts[n_base_calls] >= aux->conf.minCount &&
overlap_counts[n_base_calls] >= aux->conf.minOverlap);
}
kstring_t allele_str = {0, 0, nullptr};
ks_resize(&allele_str, 8uL);
kputc(refbase, &allele_str);
for(unsigned i = 1; i < n_base_calls; ++i) {
kputc(',', &allele_str), kputc(base_calls[i], &allele_str);
if((match = normal.templates.find(base_calls[i])) != normal.templates.end()) {
counts[i + n_base_calls] = match->second.size();
for(auto uni: normal.templates[base_calls[i]]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[i];
continue;
}
duplex_counts[i + n_base_calls] += uni->get_duplex();
overlap_counts[i + n_base_calls] += uni->get_overlap();
reverse_counts[i + n_base_calls] += uni->get_reverse();
qscore_sums[i + n_base_calls] += uni->get_quality();
}
allele_passes[i + n_base_calls] = (duplex_counts[i + n_base_calls] >= aux->conf.minDuplex &&
counts[i + n_base_calls] >= aux->conf.minCount &&
overlap_counts[i + n_base_calls] >= aux->conf.minOverlap);
}
if((match = tumor.templates.find(base_calls[i])) != tumor.templates.end()) {
counts[i] = match->second.size();
for(auto uni: tumor.templates[base_calls[i]]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[i];
continue;
}
duplex_counts[i] += uni->get_duplex();
overlap_counts[i] += uni->get_overlap();
reverse_counts[i] += uni->get_reverse();
qscore_sums[i] += uni->get_quality();
}
allele_passes[i] = (duplex_counts[i] >= aux->conf.minDuplex &&
counts[i] >= aux->conf.minCount &&
overlap_counts[i] >= aux->conf.minOverlap);
if(allele_passes[i] && !allele_passes[i + n_base_calls]) {
bcf_update_info_flag(aux->vcf.vh, vrec, "SOMATIC", nullptr, 1);
somatic[i] = 1;
}
}
}
const int total_depth_tumor(std::accumulate(counts.begin(), counts.begin() + n_base_calls, 0));
const int total_depth_normal(std::accumulate(counts.begin() + n_base_calls, counts.end(), 0));
//LOG_DEBUG("Got total depths %i,%i.\n", total_depth_tumor, total_depth_normal);
std::vector<float> rv_fractions(reverse_counts.size());
std::vector<float> allele_fractions(reverse_counts.size());
for(unsigned i = 0; i < n_base_calls; ++i) {
rv_fractions[i] = (float)counts[i] / reverse_counts[i];
rv_fractions[i + n_base_calls] = (float)counts[i + n_base_calls] / reverse_counts[i + n_base_calls];
allele_fractions[i] = (float)counts[i] / total_depth_tumor;
allele_fractions[i + n_base_calls] = (float)counts[i + n_base_calls] / total_depth_normal;
}
bcf_update_alleles_str(aux->vcf.vh, vrec, allele_str.s), free(allele_str.s);
bcf_update_format_int32(aux->vcf.vh, vrec, "ADP", static_cast<const void *>(counts.data()), counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPD", static_cast<const void *>(duplex_counts.data()), duplex_counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPO", static_cast<const void *>(overlap_counts.data()), overlap_counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPR", static_cast<const void *>(reverse_counts.data()), reverse_counts.size());
#if !NDEBUG
for(auto i: reverse_counts)
LOG_DEBUG("Reverse count: %i.\n", i);
#endif
bcf_update_format_float(aux->vcf.vh, vrec, "RVF", static_cast<const void *>(rv_fractions.data()), rv_fractions.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "BMF_PASS", static_cast<const void *>(allele_passes.data()), allele_passes.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "QSS", static_cast<const void *>(qscore_sums.data()), qscore_sums.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "AMBIG", static_cast<const void *>(ambig), sizeof(ambig));
bcf_update_format_float(aux->vcf.vh, vrec, "AFR", static_cast<const void *>(allele_fractions.data()), allele_fractions.size());
bcf_update_info_int32(aux->vcf.vh, vrec, "SOMATIC_CALL", static_cast<const void *>(somatic.data()), somatic.size());
} /* PairVCFLine::to_bcf */
void add_hdr_lines(bcf_hdr_t *hdr, const char *lines[], size_t n) {
while(n)
if(bcf_hdr_append(hdr, lines[--n]))
LOG_EXIT("Could not add header line %s. Abort!\n");
}
void add_stack_lines(bcf_hdr_t *hdr) {
add_hdr_lines(hdr, stack_vcf_lines, sizeof(stack_vcf_lines) / sizeof(stack_vcf_lines[0]));
}
} /* namespace BMF */
<commit_msg>Initialization vs resizing<commit_after>#include "stack.h"
namespace BMF {
/*
* TODO:
* 1. Decide which info/format fields for each variant.
* 2. Decide to have a number of fields
*/
SampleVCFPos::SampleVCFPos(std::unordered_map<std::string, UniqueObservation>& obs, int32_t tid, int32_t pos):
size(obs.size()),
pos(pos),
tid(tid) {
templates.reserve(4);
for(auto& pair: obs) templates[pair.second.base_call].push_back(&pair.second);
}
void SampleVCFPos::to_bcf(bcf1_t *vrec, bcf_hdr_t *hdr, char refbase) {
std::vector<int> counts;
std::vector<int> duplex_counts;
std::vector<int> overlap_counts;
int count_index = 0;
vrec->rid = tid;
vrec->pos = pos;
vrec->qual = 0;
kstring_t allele_str = {0, 10uL, (char *)malloc(10uL * sizeof(char))};
kputc(refbase, &allele_str);
auto match = templates.find(refbase);
if(match == templates.end()) {
counts.resize(templates.size() + 1);
duplex_counts.resize(templates.size() + 1);
overlap_counts.resize(templates.size() + 1);
bcf_update_info_flag(hdr, vrec, "NOREF", nullptr, 1);
// No reference calls? Add appropriate info fields.
} else {
counts.resize(templates.size());
duplex_counts.resize(templates.size());
overlap_counts.resize(templates.size());
counts[0] = match->second.size();
for(auto uni: templates[refbase]) {
duplex_counts[0] += uni->get_duplex();
overlap_counts[0] += uni->get_overlap();
}
}
for(auto& pair: templates) {
if(pair.first != refbase)
kputc(',', &allele_str), kputc((int)pair.first, &allele_str);
counts[++count_index] = pair.second.size();
for(auto uni: templates[pair.first]) {
duplex_counts[count_index] += uni->get_duplex();
overlap_counts[count_index] += uni->get_overlap();
}
// Update records
}
bcf_update_alleles_str(hdr, vrec, allele_str.s);
bcf_update_format(hdr, vrec, "ADP", (const void *)counts.data(), counts.size(), 'i');
bcf_update_format(hdr, vrec, "ADPD", (const void *)duplex_counts.data(), duplex_counts.size(), 'i');
bcf_update_format(hdr, vrec, "ADPO", (const void *)overlap_counts.data(), overlap_counts.size(), 'i');
}
void UniqueObservation::add_obs(const bam_pileup1_t& plp) {
LOG_ASSERT(strcmp(qname.c_str(), bam_get_qname(plp.b)) == 0);
size += bam_itag(plp.b, "FM");
base2 = seq_nt16_str[bam_seqi(bam_get_seq(plp.b), plp.qpos)];
cycle2 = dlib::arr_qpos(&plp);
mq2 = (uint32_t)plp.b->core.qual;
is_reverse2 = bam_is_rev(plp.b);
is_overlap = 1;
if(base2 == base1) {
discordant = 0;
agreed += ((uint32_t *)dlib::array_tag(plp.b, "FA"))[cycle2];
quality = agreed_pvalues(quality, ((uint32_t *)dlib::array_tag(plp.b, "PV"))[cycle2]);
pvalue = std::pow(10, -0.1 * quality);
rv += bam_itag(plp.b, "RV");
} else if(base1 == 'N') {
discordant = 0;
// Basically, throw out
base_call = base2;
agreed = ((uint32_t *)dlib::array_tag(plp.b, "FA"))[cycle2];
quality = ((uint32_t *)dlib::array_tag(plp.b, "PV"))[cycle2];
pvalue = std::pow(10, -0.1 * quality);
rv = (uint32_t)bam_itag(plp.b, "RV");
} else if(base2 != 'N') {
discordant = 1;
base_call = 'N';
agreed = 0;
quality = 0;
pvalue = 1.;
}
}
void PairVCFPos::to_bcf(bcf1_t *vrec, stack_aux_t *aux, int ttid, int tpos) {
const char refbase = aux->get_ref_base(ttid, tpos);
int ambig[2] = {0, 0};
std::unordered_set<char> base_set{refbase};
for(auto& pair: tumor.templates) {
if(pair.first == 'N') {
ambig[0] = pair.second.size();
continue;
}
base_set.insert(pair.first);
}
for(auto& pair: normal.templates) {
if(pair.first == 'N') {
ambig[1] = pair.second.size();
continue;
}
base_set.insert(pair.first);
}
std::vector<char> base_calls(base_set.begin(), base_set.end());
const size_t n_base_calls = base_calls.size();
#if 0
std::string tmp;
for(auto call: base_calls) tmp.push_back((char)call);
LOG_DEBUG("N base calls: %i. string: %s\n", (int)n_base_calls, tmp.c_str());
#endif
// Sort lexicographically AFTER putting the reference base first.
std::sort(base_calls.begin(), base_calls.end(), [refbase](const char a, const char b) {
return (a == refbase) ? true : (b == refbase) ? false: a < b;
});
std::vector<int> counts(n_base_calls * 2);
std::vector<int> duplex_counts(n_base_calls * 2);
std::vector<int> overlap_counts(n_base_calls * 2);
std::vector<int> reverse_counts(n_base_calls * 2);
std::vector<int> failed_counts(n_base_calls * 2);
std::vector<int> allele_passes(n_base_calls * 2);
std::vector<int> qscore_sums(n_base_calls * 2);
std::vector<int> somatic(n_base_calls);
vrec->rid = tumor.tid;
vrec->pos = tumor.pos;
vrec->qual = 0;
vrec->n_sample = 2;
auto match = tumor.templates.find(refbase);
if(match != tumor.templates.end()) {
// Already 0-initialized if not found.
counts[0] = match->second.size();
// auto without "reference" because auto is pointers.
for(auto uni: tumor.templates[refbase]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[0];
continue;
}
duplex_counts[0] += uni->get_duplex();
overlap_counts[0] += uni->get_overlap();
reverse_counts[0] += uni->get_reverse();
qscore_sums[0] += uni->get_quality();
allele_passes[0] = (duplex_counts[0] >= aux->conf.minDuplex &&
counts[0] >= aux->conf.minCount &&
overlap_counts[0] >= aux->conf.minOverlap);
}
}
if((match = normal.templates.find(refbase)) != normal.templates.end()) {
counts[n_base_calls] = match->second.size();
// auto without "reference" because auto is pointers.
for(auto uni: normal.templates[refbase]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[n_base_calls];
continue;
}
duplex_counts[n_base_calls] += uni->get_duplex();
overlap_counts[n_base_calls] += uni->get_overlap();
reverse_counts[n_base_calls] += uni->get_reverse();
qscore_sums[n_base_calls] += uni->get_quality();
}
allele_passes[n_base_calls] = (duplex_counts[n_base_calls] >= aux->conf.minDuplex &&
counts[n_base_calls] >= aux->conf.minCount &&
overlap_counts[n_base_calls] >= aux->conf.minOverlap);
}
kstring_t allele_str = {0, 0, nullptr};
ks_resize(&allele_str, 8uL);
kputc(refbase, &allele_str);
for(unsigned i = 1; i < n_base_calls; ++i) {
kputc(',', &allele_str), kputc(base_calls[i], &allele_str);
if((match = normal.templates.find(base_calls[i])) != normal.templates.end()) {
counts[i + n_base_calls] = match->second.size();
for(auto uni: normal.templates[base_calls[i]]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[i];
continue;
}
duplex_counts[i + n_base_calls] += uni->get_duplex();
overlap_counts[i + n_base_calls] += uni->get_overlap();
reverse_counts[i + n_base_calls] += uni->get_reverse();
qscore_sums[i + n_base_calls] += uni->get_quality();
}
allele_passes[i + n_base_calls] = (duplex_counts[i + n_base_calls] >= aux->conf.minDuplex &&
counts[i + n_base_calls] >= aux->conf.minCount &&
overlap_counts[i + n_base_calls] >= aux->conf.minOverlap);
}
if((match = tumor.templates.find(base_calls[i])) != tumor.templates.end()) {
counts[i] = match->second.size();
for(auto uni: tumor.templates[base_calls[i]]) {
if(uni->get_quality() < aux->conf.minPV || uni->get_agreed() < aux->conf.minFA
|| (float)uni->get_agreed() / uni->get_size() < aux->conf.minFR) {
uni->set_pass(0);
++failed_counts[i];
continue;
}
duplex_counts[i] += uni->get_duplex();
overlap_counts[i] += uni->get_overlap();
reverse_counts[i] += uni->get_reverse();
qscore_sums[i] += uni->get_quality();
}
allele_passes[i] = (duplex_counts[i] >= aux->conf.minDuplex &&
counts[i] >= aux->conf.minCount &&
overlap_counts[i] >= aux->conf.minOverlap);
if(allele_passes[i] && !allele_passes[i + n_base_calls]) {
bcf_update_info_flag(aux->vcf.vh, vrec, "SOMATIC", nullptr, 1);
somatic[i] = 1;
}
}
}
const int total_depth_tumor(std::accumulate(counts.begin(), counts.begin() + n_base_calls, 0));
const int total_depth_normal(std::accumulate(counts.begin() + n_base_calls, counts.end(), 0));
//LOG_DEBUG("Got total depths %i,%i.\n", total_depth_tumor, total_depth_normal);
std::vector<float> rv_fractions(reverse_counts.size());
std::vector<float> allele_fractions(reverse_counts.size());
for(unsigned i = 0; i < n_base_calls; ++i) {
rv_fractions[i] = (float)counts[i] / reverse_counts[i];
rv_fractions[i + n_base_calls] = (float)counts[i + n_base_calls] / reverse_counts[i + n_base_calls];
allele_fractions[i] = (float)counts[i] / total_depth_tumor;
allele_fractions[i + n_base_calls] = (float)counts[i + n_base_calls] / total_depth_normal;
}
bcf_update_alleles_str(aux->vcf.vh, vrec, allele_str.s), free(allele_str.s);
bcf_update_format_int32(aux->vcf.vh, vrec, "ADP", static_cast<const void *>(counts.data()), counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPD", static_cast<const void *>(duplex_counts.data()), duplex_counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPO", static_cast<const void *>(overlap_counts.data()), overlap_counts.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "ADPR", static_cast<const void *>(reverse_counts.data()), reverse_counts.size());
#if !NDEBUG
for(auto i: reverse_counts)
LOG_DEBUG("Reverse count: %i.\n", i);
#endif
bcf_update_format_float(aux->vcf.vh, vrec, "RVF", static_cast<const void *>(rv_fractions.data()), rv_fractions.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "BMF_PASS", static_cast<const void *>(allele_passes.data()), allele_passes.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "QSS", static_cast<const void *>(qscore_sums.data()), qscore_sums.size());
bcf_update_format_int32(aux->vcf.vh, vrec, "AMBIG", static_cast<const void *>(ambig), sizeof(ambig));
bcf_update_format_float(aux->vcf.vh, vrec, "AFR", static_cast<const void *>(allele_fractions.data()), allele_fractions.size());
bcf_update_info_int32(aux->vcf.vh, vrec, "SOMATIC_CALL", static_cast<const void *>(somatic.data()), somatic.size());
} /* PairVCFLine::to_bcf */
void add_hdr_lines(bcf_hdr_t *hdr, const char *lines[], size_t n) {
while(n)
if(bcf_hdr_append(hdr, lines[--n]))
LOG_EXIT("Could not add header line %s. Abort!\n");
}
void add_stack_lines(bcf_hdr_t *hdr) {
add_hdr_lines(hdr, stack_vcf_lines, sizeof(stack_vcf_lines) / sizeof(stack_vcf_lines[0]));
}
} /* namespace BMF */
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
namespace libtest {
bool lookup(const char* host)
{
bool success= false;
assert(host and host[0]);
if (host and host[0])
{
struct addrinfo *addrinfo= NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
int limit= 5;
while (--limit and success == false)
{
if (addrinfo)
{
freeaddrinfo(addrinfo);
addrinfo= NULL;
}
int ret;
if ((ret= getaddrinfo(host, "echo", &hints, &addrinfo)) == 0)
{
success= true;
break;
}
switch (ret)
{
case EAI_AGAIN:
continue;
case EAI_NONAME:
default:
break;
}
break;
}
if (addrinfo)
{
freeaddrinfo(addrinfo);
}
}
return success;
}
bool check_dns()
{
if (lookup("exist.gearman.info") == false)
{
return false;
}
if (lookup("does_not_exist.gearman.info")) // This should fail, if it passes,...
{
fatal_assert("Your service provider sucks and is providing bogus DNS. You might be in an airport.");
}
return true;
}
} // namespace libtest
<commit_msg>Second attempt to quiet valgrind.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
namespace libtest {
bool lookup(const char* host)
{
bool success= false;
assert(host and host[0]);
if (host and host[0])
{
struct addrinfo *addrinfo= NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype= SOCK_STREAM;
hints.ai_protocol= IPPROTO_TCP;
int limit= 5;
while (--limit and success == false)
{
if (addrinfo)
{
freeaddrinfo(addrinfo);
addrinfo= NULL;
}
int ret;
if ((ret= getaddrinfo(host, "echo", &hints, &addrinfo)) == 0)
{
success= true;
break;
}
switch (ret)
{
case EAI_AGAIN:
continue;
case EAI_NONAME:
default:
break;
}
break;
}
if (addrinfo)
{
freeaddrinfo(addrinfo);
}
}
return success;
}
bool check_dns()
{
if (lookup("exist.gearman.info") == false)
{
return false;
}
if (lookup("does_not_exist.gearman.info")) // This should fail, if it passes,...
{
fatal_assert("Your service provider sucks and is providing bogus DNS. You might be in an airport.");
}
return true;
}
} // namespace libtest
<|endoftext|> |
<commit_before>#include <iostream>
#include <libwatcher/client.h>
#include <libwatcher/labelMessage.h>
#include <libwatcher/edgeMessage.h>
#include <libwatcher/gpsMessage.h>
#include <libwatcher/colorMessage.h>
#include <libwatcher/colors.h>
#include <libwatcher/watcherColors.h>
#include <libwatcher/connectivityMessage.h>
#include <libwatcher/sendMessageHandler.h>
#include <logger.h>
#include "configuration.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
namespace po=boost::program_options;
namespace rs=randomScenario;
typedef struct {
double x, y, z; // in positive meters from 0,0,0 in cartiesian space
double speed;
double theta;
double phi;
} NodePos;
void computeEdges(unsigned int *edges, const NodePos *nodes, const unsigned int nodeNum);
void doMobility(NodePos *nodes, const unsigned int nodeNum);
static bool debug=false;
static unsigned int maxEastWest=0;
static unsigned int maxNorthSouth=0;
static unsigned int maxUpDown=0;
static unsigned int radius=0;
int main(int argc, char **argv)
{
// Load config and bail on error.
if (!rs::loadConfiguration(argc, argv))
return EXIT_FAILURE;
rs::printConfiguration(cout);
srand(time(NULL));
po::variables_map &config=rs::getConfig();
unsigned int nodeNum=config["nodeNum"].as<unsigned int>();
float nodeDegreePercentage=config["nodeDegreePercentage"].as<float>();
float nodeLabelPercentage=config["nodeLabelPercentage"].as<float>();
unsigned int layerNum=config["layerNum"].as<unsigned int>();
int duration=config["duration"].as<int>();
string server=config["server"].as<string>();
maxEastWest=config["eastWest"].as<unsigned int>();
maxNorthSouth=config["northSouth"].as<unsigned int>();
maxUpDown=config["upDown"].as<unsigned int>();
radius=config["radius"].as<unsigned int>();
debug=config["debug"].as<bool>();
const int maxSpeed=10;
const int minSpeed=2;
LOAD_LOG_PROPS(config["logproperties"].as<string>());
cout << "Connecting to watcherd on " << server << endl;
watcher::Client client(server);
client.addMessageHandler(MultipleMessageHandler::create());
NodePos *positions=new NodePos[nodeNum];
if (!positions) {
cerr << "Unable to allocate memory to hold " << nodeNum << " nodes." << endl;
return EXIT_FAILURE;
}
// init positions
for (int i=0; i<nodeNum; i++) {
positions[i].x=rand()%maxEastWest;
positions[i].y=rand()%maxNorthSouth;
positions[i].z=rand()%maxUpDown;
positions[i].speed=(rand()%(maxSpeed-minSpeed))+minSpeed;
positions[i].theta=((rand()%(((int)M_PI*100)*2))-((int)M_PI*100))/100.0; // random # between -PI..PI w/2 sig digits
positions[i].phi=((rand()%(((int)M_PI*50)*2))-((int)M_PI*50))/100.0; // random # between -PI/2..PI/2 w/2 sig digits
cout << "Placed node " << i+1 << " at intial position " << positions[i].x << ", " << positions[i].y << ", " << positions[i].z;
cout << " at speed " << positions[i].speed << " and direction (" << positions[i].theta << ", " << positions[i].phi << ")" << endl;
}
unsigned int *edges=new unsigned int[nodeNum*nodeNum];
memset(edges, 0, nodeNum*nodeNum);
while (duration) {
doMobility(positions, nodeNum);
computeEdges(edges, positions, nodeNum);
GPSMessagePtr gpsMess(GPSMessagePtr(new GPSMessage));
ConnectivityMessagePtr connMess(ConnectivityMessagePtr(new ConnectivityMessage));
for (int i=0; i<nodeNum; i++) {
NodeIdentifier nid=boost::asio::ip::address_v4::address_v4(i+1);
gpsMess->x=positions[i].x/60000.0; // make it look like GPS data.
gpsMess->y=positions[i].y/60000.0;
gpsMess->z=positions[i].z;
gpsMess->fromNodeID=nid;
if (!client.sendMessage(gpsMess))
cerr << "Error sending gps message #" << i << endl;
if (rand()%100 <= (unsigned int)nodeLabelPercentage) {
LabelMessagePtr lm(new LabelMessage("Label", nid));
if (!client.sendMessage(lm))
cerr << "Error sending node label message";
}
// All layers have the same edges. How to fix this? radius per layer maybe?
for (unsigned int l=0; l<layerNum; l++) {
connMess->fromNodeID=nid;
connMess->layer="RandScenConn" + boost::lexical_cast<string>(l);
for (int j=0; j<nodeNum; j++)
if (*(edges+(i*nodeNum)+j))
connMess->neighbors.push_back(boost::asio::ip::address_v4::address_v4(j+1));
if (debug) {
cout << "Nbrs of node " << i+1 << ": ";
for (ConnectivityMessage::NeighborList::const_iterator nbr=connMess->neighbors.begin(); nbr!=connMess->neighbors.end(); nbr++)
cout << nbr->to_string() << " ";
cout << endl;
}
if (!client.sendMessage(connMess))
cerr << "Error sending connectivity message." << endl;
connMess->neighbors.clear();
}
}
if (duration>0)
duration--;
sleep(1);
}
client.wait();
client.close();
return EXIT_SUCCESS;
}
int dumpEdges(unsigned int *edges, const unsigned int nodeNum)
{
cout << "Edges:" << endl;
for (int i=0; i<nodeNum; i++) {
for (int j=0; j<nodeNum; j++)
cout << *(edges+(i*nodeNum)+j) << " ";
cout << endl;
}
}
double computeDistance(const NodePos &n1, const NodePos &n2)
{
return sqrt( ((n2.x-n1.x)*(n2.x-n1.x)) + ((n2.y-n1.y)*(n2.y-n1.y)) + ((n2.z-n1.z)*(n2.z-n1.z)) );
}
void computeEdges(unsigned int *edges, const NodePos *nodes, const unsigned int nodeNum)
{
for (int i=0; i<nodeNum; i++)
for (int j=0; j<nodeNum; j++) {
if (i==j)
continue;
double dist=computeDistance(nodes[i], nodes[j]);
// if (debug)
// cout << "Distance between " << i+1 << " <--> " << j+1 << " is " << dist << endl;
*(edges+(i*nodeNum)+j)=(radius>=dist)?1:0;
}
if (debug)
dumpEdges(edges, nodeNum);
}
void doMobility(NodePos *nodes, const unsigned int nodeNum)
{
if (debug)
cout << "node 1 old position: " << nodes[0].x << ", " << nodes[0].y << ", " << nodes[0].z << endl;
for (int i=0; i<nodeNum; i++) {
nodes[i].x+=cos(nodes[i].theta)*nodes[i].speed;
nodes[i].y+=sin(nodes[i].theta)*nodes[i].speed;
nodes[i].z+=sin(nodes[i].phi)*nodes[i].speed;
nodes[i].x=nodes[i].x>maxEastWest ?nodes[i].x-maxEastWest :nodes[i].x<0? maxEastWest-nodes[i].x:nodes[i].x;
nodes[i].y=nodes[i].y>maxNorthSouth ?nodes[i].y-maxNorthSouth :nodes[i].y<0? maxNorthSouth-nodes[i].y:nodes[i].y;
nodes[i].z=nodes[i].z>maxUpDown?nodes[i].z-maxUpDown:nodes[i].z<0?maxUpDown-nodes[i].z:nodes[i].z;
}
if (debug)
cout << "node 1 new position: " << nodes[0].x << ", " << nodes[0].y << ", " << nodes[0].z << endl;
}
<commit_msg>jitter the messages a bit by tweaking the message timestamps. Make sure the label message has a layer.<commit_after>#include <iostream>
#include <libwatcher/client.h>
#include <libwatcher/labelMessage.h>
#include <libwatcher/edgeMessage.h>
#include <libwatcher/gpsMessage.h>
#include <libwatcher/colorMessage.h>
#include <libwatcher/colors.h>
#include <libwatcher/watcherColors.h>
#include <libwatcher/connectivityMessage.h>
#include <libwatcher/sendMessageHandler.h>
#include <logger.h>
#include "configuration.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
namespace po=boost::program_options;
namespace rs=randomScenario;
typedef struct {
double x, y, z; // in positive meters from 0,0,0 in cartiesian space
double speed;
double theta;
double phi;
} NodePos;
void computeEdges(unsigned int *edges, const NodePos *nodes, const unsigned int nodeNum);
void doMobility(NodePos *nodes, const unsigned int nodeNum);
static bool debug=false;
static unsigned int maxEastWest=0;
static unsigned int maxNorthSouth=0;
static unsigned int maxUpDown=0;
static unsigned int radius=0;
int main(int argc, char **argv)
{
// Load config and bail on error.
if (!rs::loadConfiguration(argc, argv))
return EXIT_FAILURE;
rs::printConfiguration(cout);
srand(time(NULL));
po::variables_map &config=rs::getConfig();
unsigned int nodeNum=config["nodeNum"].as<unsigned int>();
float nodeDegreePercentage=config["nodeDegreePercentage"].as<float>();
float nodeLabelPercentage=config["nodeLabelPercentage"].as<float>();
unsigned int layerNum=config["layerNum"].as<unsigned int>();
int duration=config["duration"].as<int>();
string server=config["server"].as<string>();
maxEastWest=config["eastWest"].as<unsigned int>();
maxNorthSouth=config["northSouth"].as<unsigned int>();
maxUpDown=config["upDown"].as<unsigned int>();
radius=config["radius"].as<unsigned int>();
debug=config["debug"].as<bool>();
const int maxSpeed=10;
const int minSpeed=2;
LOAD_LOG_PROPS(config["logproperties"].as<string>());
cout << "Connecting to watcherd on " << server << endl;
watcher::Client client(server);
client.addMessageHandler(MultipleMessageHandler::create());
NodePos *positions=new NodePos[nodeNum];
if (!positions) {
cerr << "Unable to allocate memory to hold " << nodeNum << " nodes." << endl;
return EXIT_FAILURE;
}
// init positions
for (int i=0; i<nodeNum; i++) {
positions[i].x=rand()%maxEastWest;
positions[i].y=rand()%maxNorthSouth;
positions[i].z=rand()%maxUpDown;
positions[i].speed=(rand()%(maxSpeed-minSpeed))+minSpeed;
positions[i].theta=((rand()%(((int)M_PI*100)*2))-((int)M_PI*100))/100.0; // random # between -PI..PI w/2 sig digits
positions[i].phi=((rand()%(((int)M_PI*50)*2))-((int)M_PI*50))/100.0; // random # between -PI/2..PI/2 w/2 sig digits
cout << "Placed node " << i+1 << " at intial position " << positions[i].x << ", " << positions[i].y << ", " << positions[i].z;
cout << " at speed " << positions[i].speed << " and direction (" << positions[i].theta << ", " << positions[i].phi << ")" << endl;
}
unsigned int *edges=new unsigned int[nodeNum*nodeNum];
memset(edges, 0, nodeNum*nodeNum);
while (duration) {
doMobility(positions, nodeNum);
computeEdges(edges, positions, nodeNum);
GPSMessagePtr gpsMess(GPSMessagePtr(new GPSMessage));
ConnectivityMessagePtr connMess(ConnectivityMessagePtr(new ConnectivityMessage));
struct timeval now;
gettimeofday(&now, NULL);
for (int i=0; i<nodeNum; i++) {
NodeIdentifier nid=boost::asio::ip::address_v4::address_v4(i+1);
gpsMess->x=positions[i].x/60000.0; // make it look like GPS data.
gpsMess->y=positions[i].y/60000.0;
gpsMess->z=positions[i].z;
gpsMess->fromNodeID=nid;
gpsMess->timestamp=((long long int)now.tv_sec*1000)+((long long int)now.tv_usec/1000)-(rand()%500); // introduce some jitter.
if (!client.sendMessage(gpsMess))
cerr << "Error sending gps message #" << i << endl;
if (rand()%100 <= (unsigned int)nodeLabelPercentage) {
LabelMessagePtr lm(new LabelMessage("Label", nid));
lm->layer="RandomLabels";
if (!client.sendMessage(lm))
cerr << "Error sending node label message";
}
// All layers have the same edges. How to fix this? radius per layer maybe?
for (unsigned int l=0; l<layerNum; l++) {
connMess->fromNodeID=nid;
connMess->layer="RandScenConn" + boost::lexical_cast<string>(l);
for (int j=0; j<nodeNum; j++)
if (*(edges+(i*nodeNum)+j))
connMess->neighbors.push_back(boost::asio::ip::address_v4::address_v4(j+1));
if (debug) {
cout << "Nbrs of node " << i+1 << ": ";
for (ConnectivityMessage::NeighborList::const_iterator nbr=connMess->neighbors.begin(); nbr!=connMess->neighbors.end(); nbr++)
cout << nbr->to_string() << " ";
cout << endl;
}
connMess->timestamp=gpsMess->timestamp;
if (!client.sendMessage(connMess))
cerr << "Error sending connectivity message." << endl;
connMess->neighbors.clear();
}
}
if (duration>0)
duration--;
sleep(1);
}
client.wait();
client.close();
return EXIT_SUCCESS;
}
int dumpEdges(unsigned int *edges, const unsigned int nodeNum)
{
cout << "Edges:" << endl;
for (int i=0; i<nodeNum; i++) {
for (int j=0; j<nodeNum; j++)
cout << *(edges+(i*nodeNum)+j) << " ";
cout << endl;
}
}
double computeDistance(const NodePos &n1, const NodePos &n2)
{
return sqrt( ((n2.x-n1.x)*(n2.x-n1.x)) + ((n2.y-n1.y)*(n2.y-n1.y)) + ((n2.z-n1.z)*(n2.z-n1.z)) );
}
void computeEdges(unsigned int *edges, const NodePos *nodes, const unsigned int nodeNum)
{
for (int i=0; i<nodeNum; i++)
for (int j=0; j<nodeNum; j++) {
if (i==j)
continue;
double dist=computeDistance(nodes[i], nodes[j]);
// if (debug)
// cout << "Distance between " << i+1 << " <--> " << j+1 << " is " << dist << endl;
*(edges+(i*nodeNum)+j)=(radius>=dist)?1:0;
}
if (debug)
dumpEdges(edges, nodeNum);
}
void doMobility(NodePos *nodes, const unsigned int nodeNum)
{
if (debug)
cout << "node 1 old position: " << nodes[0].x << ", " << nodes[0].y << ", " << nodes[0].z << endl;
for (int i=0; i<nodeNum; i++) {
nodes[i].x+=cos(nodes[i].theta)*nodes[i].speed;
nodes[i].y+=sin(nodes[i].theta)*nodes[i].speed;
nodes[i].z+=sin(nodes[i].phi)*nodes[i].speed;
nodes[i].x=nodes[i].x>maxEastWest ?nodes[i].x-maxEastWest :nodes[i].x<0? maxEastWest-nodes[i].x:nodes[i].x;
nodes[i].y=nodes[i].y>maxNorthSouth ?nodes[i].y-maxNorthSouth :nodes[i].y<0? maxNorthSouth-nodes[i].y:nodes[i].y;
nodes[i].z=nodes[i].z>maxUpDown?nodes[i].z-maxUpDown:nodes[i].z<0?maxUpDown-nodes[i].z:nodes[i].z;
}
if (debug)
cout << "node 1 new position: " << nodes[0].x << ", " << nodes[0].y << ", " << nodes[0].z << endl;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) LinBox
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#include <linbox/matrix/random-matrix.h>
#include <linbox/solutions/solve.h>
using namespace LinBox;
template <class Matrix>
struct matrixName;
template <class MatrixArgs>
struct matrixName<DenseMatrix<MatrixArgs>> {
static constexpr const char* value = "DenseMatrix";
};
template <class... MatrixArgs>
struct matrixName<SparseMatrix<MatrixArgs...>> {
static constexpr const char* value = "SparseMatrix";
};
template <class SolveMethod, class ResultVector, class Matrix, class Vector>
void print_error(const ResultVector& x, const Matrix& A, const Vector& b, bool verboseEnabled, std::string reason)
{
if (verboseEnabled) {
A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl;
std::cerr << "b: " << b << std::endl;
std::cerr << "x: " << x << std::endl;
}
// @note Within our tests A square implies non-singular
bool singular = (A.rowdim() != A.coldim());
std::cerr << "==> " << SolveMethod::name() << " on " << (singular ? "" : "non-");
std::cerr << "singular " << matrixName<Matrix>::value << " over ";
A.field().write(std::cerr);
std::cerr << " FAILS (" << reason << ")" << std::endl;
}
template <class Ring, class SolveMethod>
void run_integer(Communicator& communicator, bool verboseEnabled, size_t dimension)
{
// @fixme Test non-singular
// @fixme Test singular (rectangular)
Ring R;
BlasVector<Ring> b(R, dimension);
b.setEntry(0, 4);
b.setEntry(1, 6);
DenseMatrix<Ring> A(R, dimension, dimension);
A.setEntry(0, 0, 4);
A.setEntry(0, 1, 0);
A.setEntry(1, 0, 0);
A.setEntry(1, 1, 4);
SolveMethod method;
method.pCommunicator = &communicator;
// Rational vector interface will call (num, den) one
using RationalDomain = Givaro::QField<Givaro::Rational>;
RationalDomain F;
BlasVector<RationalDomain> x(F, dimension);
if (verboseEnabled) {
A.field().write(std::cout << "--------------- Testing " << SolveMethod::name() << " on DenseMatrix over ") << std::endl;
}
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "throws error");
return;
}
if (x[0].nume() != 1 || x[0].deno() != 1 || x[1].nume() != 3 || x[1].deno() != 2) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "Ax != b");
}
}
template <class Matrix, class Method>
void run_modular(bool verboseEnabled)
{
using Field = typename Matrix::Field;
Field F(101);
BlasVector<Field> b(F, 2);
b.setEntry(0, 4);
b.setEntry(1, 6);
Matrix A(F, 2, 2);
A.setEntry(0, 0, 4);
A.setEntry(0, 1, 0);
A.setEntry(1, 0, 0);
A.setEntry(1, 1, 4);
Method method;
method.blockingFactor = 1;
if (verboseEnabled) {
A.field().write(std::cout << "--------------- Testing " << Method::name() << " on DenseMatrix over ") << std::endl;
}
BlasVector<Field> x(F, 2);
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
return;
}
if (x[0] != 1 || x[1] != 52) {
}
}
template <class SolveMethod, class Matrix>
bool test_rational_solve_with_matrix(Communicator& communicator, bool verboseEnabled)
{
// @fixme Get m, n from arguments
size_t m = 2;
size_t n = 2;
using RationalDomain = Givaro::QField<Givaro::Rational>;
using IntegerDomain = typename Matrix::Field;
using Vector = DenseVector<IntegerDomain>;
using RationalVector = DenseVector<RationalDomain>;
IntegerDomain ID;
Matrix A(ID, m, n);
Vector b(ID, m);
// @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0.
typename IntegerDomain::RandIter randIter(ID, 10, 0); // @fixme Set seed, bits
LinBox::RandomDenseMatrix<typename IntegerDomain::RandIter, IntegerDomain> RDM(ID, randIter);
RDM.randomFullRank(A);
b.random();
RationalDomain RD;
RationalVector x(RD, n);
if (verboseEnabled) {
std::cout << "--- Testing " << SolveMethod::name() << " on " << matrixName<Matrix>::value << " over ";
ID.write(std::cout) << " of size " << m << "x" << n << std::endl;
}
SolveMethod method;
method.pCommunicator = &communicator;
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "throws error");
return false;
}
// @fixme CHECK
// if (x[0] != 1 || x[1] != 52) {
// print_error<SolveMethod>(x, A, b, verboseEnabled, "Ax != b");
// return false;
// }
return true;
}
// Testing rational solve over the integers
template <class SolveMethod>
void test_rational_solve(Communicator& communicator, bool verboseEnabled)
{
using IntegerDomain = Givaro::ZRing<Integer>;
// Testing invertible matrix (@fixme should it be pre-generated?)
test_rational_solve_with_matrix<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, verboseEnabled);
test_rational_solve_with_matrix<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, verboseEnabled);
//
// Testing singular matrix
//
// @fixme To do
// run_integer<Givaro::ZRing<Integer>, SolveMethod>(communicator, verboseEnabled, 3);
}
int main(int argc, char** argv)
{
bool verboseEnabled = false;
static Argument args[] = {{'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verboseEnabled}, END_OF_ARGUMENTS};
parseArguments(argc, argv, args);
if (verboseEnabled) {
commentator().setReportStream(std::cout);
}
Communicator communicator(0, nullptr);
test_rational_solve<Method::Auto>(communicator, verboseEnabled);
test_rational_solve<Method::CraAuto>(communicator, verboseEnabled);
test_rational_solve<Method::Dixon>(communicator, verboseEnabled);
test_rational_solve<Method::NumericSymbolicOverlap>(communicator, verboseEnabled); // @fixme Singular case fails
test_rational_solve<Method::NumericSymbolicNorm>(communicator, verboseEnabled); // @fixme Fails
run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Auto>(verboseEnabled);
run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Auto>(verboseEnabled);
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::DenseElimination>();
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::DenseElimination>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::SparseElimination>();
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::SparseElimination>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Wiedemann>(); // @fixme Can't compile
run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Wiedemann>(verboseEnabled);
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Lanczos>(); // @fixme Segmentation fault
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Lanczos>(); // @fixme Segmentation fault
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::BlockLanczos>(); // @fixme Can't compile
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::BlockLanczos>(); // @fixme Segmentation fault
// @deprecated These do not compile anymore
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::BlockWiedemann>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Coppersmith>();
// @fixme Test rectangular matrices...
return 0;
}
<commit_msg>Generating singular cases<commit_after>/*
* Copyright (C) LinBox
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#include <linbox/matrix/random-matrix.h>
#include <linbox/solutions/solve.h>
using namespace LinBox;
template <class Matrix>
struct matrixName;
template <class MatrixArgs>
struct matrixName<DenseMatrix<MatrixArgs>> {
static constexpr const char* value = "DenseMatrix";
};
template <class... MatrixArgs>
struct matrixName<SparseMatrix<MatrixArgs...>> {
static constexpr const char* value = "SparseMatrix";
};
template <class SolveMethod, class ResultVector, class Matrix, class Vector>
void print_error(const ResultVector& x, const Matrix& A, const Vector& b, bool verboseEnabled, std::string reason)
{
if (verboseEnabled) {
A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl;
std::cerr << "b: " << b << std::endl;
std::cerr << "x: " << x << std::endl;
}
// @note Within our tests A square implies non-singular
bool singular = (A.rowdim() != A.coldim());
std::cerr << "==> " << SolveMethod::name() << " on " << (singular ? "" : "non-");
std::cerr << "singular " << matrixName<Matrix>::value << " over ";
A.field().write(std::cerr);
std::cerr << " FAILS (" << reason << ")" << std::endl;
}
template <class Ring, class SolveMethod>
void run_integer(Communicator& communicator, bool verboseEnabled, size_t dimension)
{
// @fixme Test non-singular
// @fixme Test singular (rectangular)
Ring R;
BlasVector<Ring> b(R, dimension);
b.setEntry(0, 4);
b.setEntry(1, 6);
DenseMatrix<Ring> A(R, dimension, dimension);
A.setEntry(0, 0, 4);
A.setEntry(0, 1, 0);
A.setEntry(1, 0, 0);
A.setEntry(1, 1, 4);
SolveMethod method;
method.pCommunicator = &communicator;
// Rational vector interface will call (num, den) one
using RationalDomain = Givaro::QField<Givaro::Rational>;
RationalDomain F;
BlasVector<RationalDomain> x(F, dimension);
if (verboseEnabled) {
A.field().write(std::cout << "--------------- Testing " << SolveMethod::name() << " on DenseMatrix over ") << std::endl;
}
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "throws error");
return;
}
if (x[0].nume() != 1 || x[0].deno() != 1 || x[1].nume() != 3 || x[1].deno() != 2) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "Ax != b");
}
}
template <class SolveMethod, class Matrix>
bool test_rational_solve_with_matrix(Communicator& communicator, bool verboseEnabled, size_t m, size_t n)
{
using RationalDomain = Givaro::QField<Givaro::Rational>;
using IntegerDomain = typename Matrix::Field;
using Vector = DenseVector<IntegerDomain>;
using RationalVector = DenseVector<RationalDomain>;
IntegerDomain ID;
Matrix A(ID, m, n);
Vector b(ID, m);
RationalDomain RD;
RationalVector x(RD, n);
// @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0.
typename IntegerDomain::RandIter randIter(ID, 10, 0); // @fixme Set seed, bits
LinBox::RandomDenseMatrix<typename IntegerDomain::RandIter, IntegerDomain> RDM(ID, randIter);
b.random();
// @note Within our test m == n implies invertible,
// but for the rectangular case, we pass whatever.
if (m == n) {
RDM.randomFullRank(A);
}
else {
RDM.random(A);
}
if (verboseEnabled) {
std::cout << "--- Testing " << SolveMethod::name() << " on " << matrixName<Matrix>::value << " over ";
ID.write(std::cout) << " of size " << m << "x" << n << std::endl;
}
SolveMethod method;
method.pCommunicator = &communicator;
try {
solve(x, A, b, method);
solveInPlace(x, A, b, method);
} catch (...) {
print_error<SolveMethod>(x, A, b, verboseEnabled, "throws error");
return false;
}
// @fixme CHECK RESULT IS CORRECT
// if (x[0] != 1 || x[1] != 52) {
// print_error<SolveMethod>(x, A, b, verboseEnabled, "Ax != b");
// return false;
// }
return true;
}
// Testing rational solve over the integers
template <class SolveMethod>
void test_rational_solve(Communicator& communicator, bool verboseEnabled)
{
using IntegerDomain = Givaro::ZRing<Integer>;
// Testing invertible matrix
test_rational_solve_with_matrix<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, verboseEnabled, 2, 2);
test_rational_solve_with_matrix<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, verboseEnabled, 2, 2);
// Testing singular matrix
test_rational_solve_with_matrix<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, verboseEnabled, 2, 3);
test_rational_solve_with_matrix<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, verboseEnabled, 2, 3);
}
int main(int argc, char** argv)
{
bool verboseEnabled = false;
bool loop = false;
static Argument args[] = {{'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verboseEnabled},
{'l', "-l", "Infinite loop of tests.", TYPE_BOOL, &loop},
END_OF_ARGUMENTS};
parseArguments(argc, argv, args);
if (verboseEnabled) {
commentator().setReportStream(std::cout);
}
Communicator communicator(0, nullptr);
do {
test_rational_solve<Method::Auto>(communicator, verboseEnabled);
test_rational_solve<Method::CraAuto>(communicator, verboseEnabled);
test_rational_solve<Method::Dixon>(communicator, verboseEnabled);
test_rational_solve<Method::NumericSymbolicOverlap>(communicator, verboseEnabled); // @fixme Singular case fails
test_rational_solve<Method::NumericSymbolicNorm>(communicator, verboseEnabled); // @fixme Fails
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Auto>(verboseEnabled);
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Auto>(verboseEnabled);
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::DenseElimination>();
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::DenseElimination>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::SparseElimination>();
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::SparseElimination>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Wiedemann>(); // @fixme Can't compile
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Wiedemann>(verboseEnabled);
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Lanczos>(); // @fixme Segmentation fault
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::Lanczos>(); // @fixme Segmentation fault
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::BlockLanczos>(); // @fixme Can't compile
// run_modular<SparseMatrix<Givaro::Modular<double>>, Method::BlockLanczos>(); // @fixme Segmentation fault
// @deprecated These do not compile anymore
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::BlockWiedemann>();
// run_modular<DenseMatrix<Givaro::Modular<double>>, Method::Coppersmith>();
// @fixme Test rectangular matrices...
} while (loop);
return 0;
}
<|endoftext|> |
<commit_before>#include "test.h"
class fenwick_tree
{
public:
fenwick_tree(int capacity);
~fenwick_tree();
void update(int index, int delta);
int running_sum(int index) const;
private:
int m_capacity;
int* m_elements;
};
fenwick_tree::fenwick_tree(int capacity) : m_capacity(capacity)
{
this->m_elements = new int[this->m_capacity];
for (int i = 0; i < this->m_capacity; i++)
{
this->m_elements[i] = 0;
}
}
fenwick_tree::~fenwick_tree()
{
delete this->m_elements;
}
void fenwick_tree::update(int index, int delta)
{
int tree_index = index + 1;
while (tree_index > 0)
{
int array_index = tree_index - 1;
this->m_elements[array_index] += delta;
tree_index = tree_index - (tree_index & -tree_index);
}
}
int fenwick_tree::running_sum(int index) const
{
int sum = 0;
int tree_index = index + 1;
while (tree_index > 0)
{
int array_index = tree_index - 1;
sum += this->m_elements[array_index];
tree_index = tree_index - (tree_index & -tree_index);
}
return sum;
}
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
// min_max_heap_test();
fenwick_tree tree(10);
for (int i = 0; i < 10; i++)
{
tree.update(i, i);
}
cout << tree.running_sum(9) << endl;
return 0;
}<commit_msg>Bug fixed<commit_after>#include "test.h"
class fenwick_tree
{
public:
fenwick_tree(int capacity);
~fenwick_tree();
void update(int index, int delta);
int running_sum(int index) const;
private:
int m_capacity;
int* m_elements;
};
fenwick_tree::fenwick_tree(int capacity) : m_capacity(capacity)
{
this->m_elements = new int[this->m_capacity];
for (int i = 0; i < this->m_capacity; i++)
{
this->m_elements[i] = 0;
}
}
fenwick_tree::~fenwick_tree()
{
delete this->m_elements;
}
void fenwick_tree::update(int index, int delta)
{
int tree_index = index + 1;
while (tree_index <= this->m_capacity)
{
int array_index = tree_index - 1;
this->m_elements[array_index] += delta;
tree_index = tree_index + (tree_index & -tree_index);
}
}
int fenwick_tree::running_sum(int index) const
{
int sum = 0;
int tree_index = index + 1;
while (tree_index > 0)
{
int array_index = tree_index - 1;
sum += this->m_elements[array_index];
tree_index = tree_index - (tree_index & -tree_index);
}
return sum;
}
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
// min_max_heap_test();
fenwick_tree tree(10);
for (int i = 0; i < 10; i++)
{
tree.update(i, i);
}
for (int i = 1; i < 10; i++)
{
cout << tree.running_sum(i) << endl;
}
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: addincol.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-08-04 12:10:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_ADDINCOL_HXX
#define SC_ADDINCOL_HXX
#ifndef _COM_SUN_STAR_SHEET_XVOLATILERESULT_HPP_
#include <com/sun/star/sheet/XVolatileResult.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XADDIN_HPP_
#include <com/sun/star/sheet/XAddIn.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XRESULTLISTENER_HPP_
#include <com/sun/star/sheet/XResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_RESULTEVENT_HPP_
#include <com/sun/star/sheet/ResultEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_REFLECTION_XIDLMETHOD_HPP_
#include <com/sun/star/reflection/XIdlMethod.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_LOCALIZEDNAME_HPP_
#include <com/sun/star/sheet/LocalizedName.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#include <hash_map>
class String;
class SfxObjectShell;
class ScUnoAddInFuncData;
class ScMatrix;
class ScFuncDesc;
struct ScAddInStringHashCode
{
size_t operator()( const String& rStr ) const
{
return rtl_ustr_hashCode_WithLength( rStr.GetBuffer(), rStr.Len() );
}
};
typedef ::std::hash_map< String, const ScUnoAddInFuncData*, ScAddInStringHashCode, ::std::equal_to< String > > ScAddInHashMap;
enum ScAddInArgumentType
{
SC_ADDINARG_NONE, // -
SC_ADDINARG_INTEGER, // long
SC_ADDINARG_DOUBLE, // double
SC_ADDINARG_STRING, // string
SC_ADDINARG_INTEGER_ARRAY, // sequence<sequence<long>>
SC_ADDINARG_DOUBLE_ARRAY, // sequence<sequence<double>>
SC_ADDINARG_STRING_ARRAY, // sequence<sequence<string>>
SC_ADDINARG_MIXED_ARRAY, // sequence<sequence<any>>
SC_ADDINARG_VALUE_OR_ARRAY, // any
SC_ADDINARG_CELLRANGE, // XCellRange
SC_ADDINARG_CALLER, // XPropertySet
SC_ADDINARG_VARARGS // sequence<any>
};
//------------------------------------------------------------------------
struct ScAddInArgDesc
{
String aInternalName; // used to match configuration and reflection information
String aName;
String aDescription;
ScAddInArgumentType eType;
BOOL bOptional;
};
class ScUnoAddInFuncData
{
private:
String aOriginalName; // kept in formula
String aLocalName; // for display
String aUpperName; // for entering formulas
String aUpperLocal; // for entering formulas
String aDescription;
com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod> xFunction;
com::sun::star::uno::Any aObject;
long nArgCount;
ScAddInArgDesc* pArgDescs;
long nCallerPos;
USHORT nCategory;
USHORT nHelpId;
mutable com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName> aCompNames;
mutable BOOL bCompInitialized;
public:
ScUnoAddInFuncData( const String& rNam, const String& rLoc,
const String& rDesc,
USHORT nCat, USHORT nHelp,
const com::sun::star::uno::Reference<
com::sun::star::reflection::XIdlMethod>& rFunc,
const com::sun::star::uno::Any& rO,
long nAC, const ScAddInArgDesc* pAD,
long nCP );
~ScUnoAddInFuncData();
const String& GetOriginalName() const { return aOriginalName; }
const String& GetLocalName() const { return aLocalName; }
const String& GetUpperName() const { return aUpperName; }
const String& GetUpperLocal() const { return aUpperLocal; }
const com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod>& GetFunction() const
{ return xFunction; }
const com::sun::star::uno::Any& GetObject() const { return aObject; }
long GetArgumentCount() const { return nArgCount; }
const ScAddInArgDesc* GetArguments() const { return pArgDescs; }
long GetCallerPos() const { return nCallerPos; }
const String& GetDescription() const { return aDescription; }
USHORT GetCategory() const { return nCategory; }
USHORT GetHelpId() const { return nHelpId; }
const com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName>& GetCompNames() const;
void SetFunction( const com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod>& rNewFunc,
const com::sun::star::uno::Any& rNewObj );
void SetArguments( long nNewCount, const ScAddInArgDesc* pNewDescs );
void SetCallerPos( long nNewPos );
void SetCompNames( const com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName>& rNew );
};
//------------------------------------------------------------------------
class ScUnoAddInCollection
{
private:
long nFuncCount;
ScUnoAddInFuncData** ppFuncData;
ScAddInHashMap* pExactHashMap; // exact internal name
ScAddInHashMap* pNameHashMap; // internal name upper
ScAddInHashMap* pLocalHashMap; // localized name upper
BOOL bInitialized;
void Initialize();
void ReadConfiguration();
void ReadFromAddIn( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& xInterface );
void UpdateFromAddIn( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& xInterface,
const String& rServiceName );
void LoadComponent( const ScUnoAddInFuncData& rFuncData );
public:
ScUnoAddInCollection();
~ScUnoAddInCollection();
/// User enetered name. rUpperName MUST already be upper case!
String FindFunction( const String& rUpperName, BOOL bLocalFirst );
// rName is the exact Name.
// Only if bComplete is set, the function reference and argument types
// are initialized (component may have to be loaded).
const ScUnoAddInFuncData* GetFuncData( const String& rName, bool bComplete = false );
void Clear();
void LocalizeString( String& rName ); // modify rName - input: exact name
long GetFuncCount();
BOOL FillFunctionDesc( long nFunc, ScFuncDesc& rDesc );
static BOOL FillFunctionDescFromData( const ScUnoAddInFuncData& rFuncData, ScFuncDesc& rDesc );
BOOL GetExcelName( const String& rCalcName, LanguageType eDestLang, String& rRetExcelName );
BOOL GetCalcName( const String& rExcelName, String& rRetCalcName );
// both leave rRet... unchanged, if no matching name is found
};
class ScUnoAddInCall
{
private:
const ScUnoAddInFuncData* pFuncData;
com::sun::star::uno::Sequence<com::sun::star::uno::Any> aArgs;
com::sun::star::uno::Sequence<com::sun::star::uno::Any> aVarArg;
com::sun::star::uno::Reference<com::sun::star::uno::XInterface> xCaller;
BOOL bValidCount;
// result:
USHORT nErrCode;
BOOL bHasString;
double fValue;
String aString;
ScMatrix* pMatrix;
com::sun::star::uno::Reference<com::sun::star::sheet::XVolatileResult> xVarRes;
void ExecuteCallWithArgs(
com::sun::star::uno::Sequence<com::sun::star::uno::Any>& rCallArgs);
public:
// exact name
ScUnoAddInCall( ScUnoAddInCollection& rColl, const String& rName,
long nParamCount );
~ScUnoAddInCall();
BOOL NeedsCaller() const;
void SetCaller( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& rInterface );
void SetCallerFromObjectShell( SfxObjectShell* pSh );
BOOL ValidParamCount();
ScAddInArgumentType GetArgType( long nPos );
void SetParam( long nPos, const com::sun::star::uno::Any& rValue );
void ExecuteCall();
void SetResult( const com::sun::star::uno::Any& rNewRes );
USHORT GetErrCode() const { return nErrCode; }
BOOL HasString() const { return bHasString; }
BOOL HasMatrix() const { return ( pMatrix != NULL ); }
BOOL HasVarRes() const { return ( xVarRes.is() ); }
double GetValue() const { return fValue; }
const String& GetString() const { return aString; }
const ScMatrix* GetMatrix() const { return pMatrix; }
com::sun::star::uno::Reference<com::sun::star::sheet::XVolatileResult>
GetVarRes() const { return xVarRes; }
};
#endif
<commit_msg>INTEGRATION: CWS calc44 (1.9.302); FILE MERGED 2007/09/17 13:34:44 nn 1.9.302.1: #i81594# Remove duplicate hash code function<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: addincol.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-09-27 13:50:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_ADDINCOL_HXX
#define SC_ADDINCOL_HXX
#include "global.hxx"
#ifndef _COM_SUN_STAR_SHEET_XVOLATILERESULT_HPP_
#include <com/sun/star/sheet/XVolatileResult.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XADDIN_HPP_
#include <com/sun/star/sheet/XAddIn.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XRESULTLISTENER_HPP_
#include <com/sun/star/sheet/XResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_RESULTEVENT_HPP_
#include <com/sun/star/sheet/ResultEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_REFLECTION_XIDLMETHOD_HPP_
#include <com/sun/star/reflection/XIdlMethod.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_LOCALIZEDNAME_HPP_
#include <com/sun/star/sheet/LocalizedName.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#include <hash_map>
class String;
class SfxObjectShell;
class ScUnoAddInFuncData;
class ScMatrix;
class ScFuncDesc;
typedef ::std::hash_map< String, const ScUnoAddInFuncData*, ScStringHashCode, ::std::equal_to< String > > ScAddInHashMap;
enum ScAddInArgumentType
{
SC_ADDINARG_NONE, // -
SC_ADDINARG_INTEGER, // long
SC_ADDINARG_DOUBLE, // double
SC_ADDINARG_STRING, // string
SC_ADDINARG_INTEGER_ARRAY, // sequence<sequence<long>>
SC_ADDINARG_DOUBLE_ARRAY, // sequence<sequence<double>>
SC_ADDINARG_STRING_ARRAY, // sequence<sequence<string>>
SC_ADDINARG_MIXED_ARRAY, // sequence<sequence<any>>
SC_ADDINARG_VALUE_OR_ARRAY, // any
SC_ADDINARG_CELLRANGE, // XCellRange
SC_ADDINARG_CALLER, // XPropertySet
SC_ADDINARG_VARARGS // sequence<any>
};
//------------------------------------------------------------------------
struct ScAddInArgDesc
{
String aInternalName; // used to match configuration and reflection information
String aName;
String aDescription;
ScAddInArgumentType eType;
BOOL bOptional;
};
class ScUnoAddInFuncData
{
private:
String aOriginalName; // kept in formula
String aLocalName; // for display
String aUpperName; // for entering formulas
String aUpperLocal; // for entering formulas
String aDescription;
com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod> xFunction;
com::sun::star::uno::Any aObject;
long nArgCount;
ScAddInArgDesc* pArgDescs;
long nCallerPos;
USHORT nCategory;
USHORT nHelpId;
mutable com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName> aCompNames;
mutable BOOL bCompInitialized;
public:
ScUnoAddInFuncData( const String& rNam, const String& rLoc,
const String& rDesc,
USHORT nCat, USHORT nHelp,
const com::sun::star::uno::Reference<
com::sun::star::reflection::XIdlMethod>& rFunc,
const com::sun::star::uno::Any& rO,
long nAC, const ScAddInArgDesc* pAD,
long nCP );
~ScUnoAddInFuncData();
const String& GetOriginalName() const { return aOriginalName; }
const String& GetLocalName() const { return aLocalName; }
const String& GetUpperName() const { return aUpperName; }
const String& GetUpperLocal() const { return aUpperLocal; }
const com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod>& GetFunction() const
{ return xFunction; }
const com::sun::star::uno::Any& GetObject() const { return aObject; }
long GetArgumentCount() const { return nArgCount; }
const ScAddInArgDesc* GetArguments() const { return pArgDescs; }
long GetCallerPos() const { return nCallerPos; }
const String& GetDescription() const { return aDescription; }
USHORT GetCategory() const { return nCategory; }
USHORT GetHelpId() const { return nHelpId; }
const com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName>& GetCompNames() const;
void SetFunction( const com::sun::star::uno::Reference< com::sun::star::reflection::XIdlMethod>& rNewFunc,
const com::sun::star::uno::Any& rNewObj );
void SetArguments( long nNewCount, const ScAddInArgDesc* pNewDescs );
void SetCallerPos( long nNewPos );
void SetCompNames( const com::sun::star::uno::Sequence< com::sun::star::sheet::LocalizedName>& rNew );
};
//------------------------------------------------------------------------
class ScUnoAddInCollection
{
private:
long nFuncCount;
ScUnoAddInFuncData** ppFuncData;
ScAddInHashMap* pExactHashMap; // exact internal name
ScAddInHashMap* pNameHashMap; // internal name upper
ScAddInHashMap* pLocalHashMap; // localized name upper
BOOL bInitialized;
void Initialize();
void ReadConfiguration();
void ReadFromAddIn( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& xInterface );
void UpdateFromAddIn( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& xInterface,
const String& rServiceName );
void LoadComponent( const ScUnoAddInFuncData& rFuncData );
public:
ScUnoAddInCollection();
~ScUnoAddInCollection();
/// User enetered name. rUpperName MUST already be upper case!
String FindFunction( const String& rUpperName, BOOL bLocalFirst );
// rName is the exact Name.
// Only if bComplete is set, the function reference and argument types
// are initialized (component may have to be loaded).
const ScUnoAddInFuncData* GetFuncData( const String& rName, bool bComplete = false );
void Clear();
void LocalizeString( String& rName ); // modify rName - input: exact name
long GetFuncCount();
BOOL FillFunctionDesc( long nFunc, ScFuncDesc& rDesc );
static BOOL FillFunctionDescFromData( const ScUnoAddInFuncData& rFuncData, ScFuncDesc& rDesc );
BOOL GetExcelName( const String& rCalcName, LanguageType eDestLang, String& rRetExcelName );
BOOL GetCalcName( const String& rExcelName, String& rRetCalcName );
// both leave rRet... unchanged, if no matching name is found
};
class ScUnoAddInCall
{
private:
const ScUnoAddInFuncData* pFuncData;
com::sun::star::uno::Sequence<com::sun::star::uno::Any> aArgs;
com::sun::star::uno::Sequence<com::sun::star::uno::Any> aVarArg;
com::sun::star::uno::Reference<com::sun::star::uno::XInterface> xCaller;
BOOL bValidCount;
// result:
USHORT nErrCode;
BOOL bHasString;
double fValue;
String aString;
ScMatrix* pMatrix;
com::sun::star::uno::Reference<com::sun::star::sheet::XVolatileResult> xVarRes;
void ExecuteCallWithArgs(
com::sun::star::uno::Sequence<com::sun::star::uno::Any>& rCallArgs);
public:
// exact name
ScUnoAddInCall( ScUnoAddInCollection& rColl, const String& rName,
long nParamCount );
~ScUnoAddInCall();
BOOL NeedsCaller() const;
void SetCaller( const com::sun::star::uno::Reference<
com::sun::star::uno::XInterface>& rInterface );
void SetCallerFromObjectShell( SfxObjectShell* pSh );
BOOL ValidParamCount();
ScAddInArgumentType GetArgType( long nPos );
void SetParam( long nPos, const com::sun::star::uno::Any& rValue );
void ExecuteCall();
void SetResult( const com::sun::star::uno::Any& rNewRes );
USHORT GetErrCode() const { return nErrCode; }
BOOL HasString() const { return bHasString; }
BOOL HasMatrix() const { return ( pMatrix != NULL ); }
BOOL HasVarRes() const { return ( xVarRes.is() ); }
double GetValue() const { return fValue; }
const String& GetString() const { return aString; }
const ScMatrix* GetMatrix() const { return pMatrix; }
com::sun::star::uno::Reference<com::sun::star::sheet::XVolatileResult>
GetVarRes() const { return xVarRes; }
};
#endif
<|endoftext|> |
<commit_before>#include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(oflag, [&]() {
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace("s3 authentication hostname: " + tokens[1]);
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
S3ProtocolHTTP,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
S3ProtocolHTTP,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
logr.Debug("Reading from host=" + fileInformation.file_server + " bucket=" + bucket + " key=" + key + " " +
std::to_string(offset) + ":" + std::to_string(length) + " (" + S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
S3ProtocolHTTP,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
S3ProtocolHTTP,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
logr.Debug("Writing to host=" + std::string(host) + " bucket=" + bucket + " key=" + key + " (" +
S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info("Wrote " + std::to_string(size) + "MB in " + std::to_string(time) + " ms (" +
std::to_string(size / time) + " MB/s)");
}
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
<commit_msg>Support setting S3 protocol through environment variable<commit_after>#include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
S3Protocol protocol = S3ProtocolHTTP;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(oflag, [&]() {
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
try
{
const auto envproto = himan::util::GetEnv("S3_PROTOCOL");
if (envproto == "https")
{
protocol = S3ProtocolHTTPS;
}
else if (envproto == "http")
{
protocol = S3ProtocolHTTP;
}
else
{
logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto));
}
}
catch (const std::invalid_argument& e)
{
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace("s3 authentication hostname: " + tokens[1]);
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
logr.Debug("Reading from host=" + fileInformation.file_server + " bucket=" + bucket + " key=" + key + " " +
std::to_string(offset) + ":" + std::to_string(length) + " (" + S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
logr.Debug("Writing to host=" + std::string(host) + " bucket=" + bucket + " key=" + key + " (" +
S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info("Wrote " + std::to_string(size) + "MB in " + std::to_string(time) + " ms (" +
std::to_string(size / time) + " MB/s)");
}
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
<|endoftext|> |
<commit_before>/*
* An implementation of Markov chains for text generation using C++11 and STL
* methods.
*
* Copyright (c) 2014 Bastian Rieck
*
* 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 <algorithm>
#include <fstream>
#include <iterator>
#include <iostream>
#include <list>
#include <map>
#include <random>
#include <sstream>
#include <string>
#include <vector>
const std::string punctuation = ",;:.!?";
typedef std::map< std::string, std::vector<std::string> > database_type;
/**
Joins a sequence of tokens and returns a single string. If one of the tokens
is a punctuation mark, spurious punctuation will be avoided.
*/
template <class InputIterator> std::string join( InputIterator begin, InputIterator end )
{
std::string result;
for( auto it = begin; it != end; ++it )
{
// Is this punctuation? If so, do not add any whitespace.
if( it->length() == 1 && it->find_first_of( punctuation ) != std::string::npos )
result += *it;
else
{
if( it != begin )
result += " ";
result += *it;
}
}
return result;
}
/** Splits a string into its sequence of tokens. */
template <class OutputIterator> void split( const std::string& string, OutputIterator result )
{
std::istringstream buffer( string );
std::vector<std::string> rawTokens;
std::copy( std::istream_iterator<std::string>( buffer ),
std::istream_iterator<std::string>(),
std::back_inserter( rawTokens ) );
for( auto&& rawToken : rawTokens )
{
// Only use the _last_ punctuation that may be found in the token. We do
// not want to split a chapter number or a word.
auto pos = rawToken.find_last_of( punctuation );
if( rawToken.length() > 1 && pos != std::string::npos && pos + 1 == rawToken.length() )
{
*result++ = rawToken.substr( 0, pos );
*result++ = rawToken.substr( pos );
}
// Simply copy the token
else
*result++ = rawToken;
}
}
/**
Tokenizes a given file. Any punctuation mark and any whitespace character is
considered a token. The function returns a container of all tokens in the
order in which they appear in the text. By concatenating subsequent entries
with a whitespace character, the original text may be formed again.
*/
std::vector<std::string> getTokens( const std::string& filename )
{
std::ifstream in( filename );
std::vector<std::string> rawTokens;
std::copy( std::istream_iterator<std::string>( in ),
std::istream_iterator<std::string>(),
std::back_inserter( rawTokens ) );
std::vector<std::string> tokens;
tokens.reserve( rawTokens.size() );
for( auto&& rawToken : rawTokens )
split( rawToken, std::back_inserter( tokens ) );
return tokens;
}
/**
Given a vector of tokens and a prefix length, traverses the vector and stores
the appropriate suffix of the token. The model for updating the suffixes is
very simple --- subsequent words are merely added to a list of known words.
This makes choosing the next word easier.
*/
database_type buildDatabase( const std::vector<std::string>& tokens, unsigned int prefixLength )
{
database_type database;
std::list<std::string> prefixWords( prefixLength );
for( std::size_t i = 0; i < tokens.size(); i++ )
{
prefixWords.pop_front();
prefixWords.push_back( tokens.at(i) );
if( i + 1 < tokens.size() )
{
std::string prefix = join( prefixWords.begin(),
prefixWords.end() );
database[prefix].push_back( tokens.at(i+1) );
}
}
return database;
}
/**
Starts creating text from the database of tokens, using a Markov chain. The
function will choose a prefix at random from the database, then select a
subsequent word from the word list at random, thereby creating a new prefix.
This process will be repeated until a number of pre-defined iterations has
been reached.
*/
std::string spew( const database_type& database, unsigned int numIterations )
{
std::random_device rd;
std::default_random_engine engine( rd() );
std::ostringstream output;
std::string prefix;
{
std::uniform_int_distribution<std::size_t> distribution( 0, database.size() - 1 );
std::size_t index = distribution( engine );
auto it = database.begin();
std::advance( it, index );
prefix = it->first;
output << prefix;
}
for( unsigned int i = 1; i < numIterations; i++ )
{
auto&& words = database.at( prefix );
std::uniform_int_distribution<std::size_t> distribution( 0, words.size() - 1 );
std::size_t index = distribution( engine );
std::string word = words.at( index );
// Choose a new prefix. We do this by splitting the old prefix into a list
// of tokens, deleting the first one, and appending the current word.
std::list<std::string> prefixTokens;
split( prefix,
std::back_inserter( prefixTokens ) );
prefixTokens.pop_front();
prefixTokens.push_back( word );
prefix = join( prefixTokens.begin(), prefixTokens.end() );
if( !( word.length() == 1 && word.find_first_of( punctuation ) != std::string::npos ) )
output << " ";
output << word;
}
return output.str();
}
int main( int, char** )
{
auto tokens = getTokens( "../King_James.txt" );
auto database = buildDatabase( tokens, 2 );
std::cout << spew( database, 100 );
return 0;
}
<commit_msg>Punctuation predicate<commit_after>/*
* An implementation of Markov chains for text generation using C++11 and STL
* methods.
*
* Copyright (c) 2014 Bastian Rieck
*
* 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 <algorithm>
#include <fstream>
#include <iterator>
#include <iostream>
#include <list>
#include <map>
#include <random>
#include <sstream>
#include <string>
#include <vector>
const std::string punctuation = ",;:.!?";
typedef std::map< std::string, std::vector<std::string> > database_type;
/** Checks whether a string is a punctuation string */
bool isPunctuation( const std::string& string )
{
return string.length() == 1
&& string.find_first_of( punctuation ) != std::string::npos;
}
/**
Joins a sequence of tokens and returns a single string. If one of the tokens
is a punctuation mark, spurious punctuation will be avoided.
*/
template <class InputIterator> std::string join( InputIterator begin, InputIterator end )
{
std::string result;
for( auto it = begin; it != end; ++it )
{
// Is this punctuation? If so, do not add any whitespace.
if( isPunctuation( *it ) )
result += *it;
else
{
if( it != begin )
result += " ";
result += *it;
}
}
return result;
}
/** Splits a string into its sequence of tokens. */
template <class OutputIterator> void split( const std::string& string, OutputIterator result )
{
std::istringstream buffer( string );
std::vector<std::string> rawTokens;
std::copy( std::istream_iterator<std::string>( buffer ),
std::istream_iterator<std::string>(),
std::back_inserter( rawTokens ) );
for( auto&& rawToken : rawTokens )
{
// Only use the _last_ punctuation that may be found in the token. We do
// not want to split a chapter number or a word.
auto pos = rawToken.find_last_of( punctuation );
if( rawToken.length() > 1 && pos != std::string::npos && pos + 1 == rawToken.length() )
{
*result++ = rawToken.substr( 0, pos );
*result++ = rawToken.substr( pos );
}
// Simply copy the token
else
*result++ = rawToken;
}
}
/**
Tokenizes a given file. Any punctuation mark and any whitespace character is
considered a token. The function returns a container of all tokens in the
order in which they appear in the text. By concatenating subsequent entries
with a whitespace character, the original text may be formed again.
*/
std::vector<std::string> getTokens( const std::string& filename )
{
std::ifstream in( filename );
std::vector<std::string> rawTokens;
std::copy( std::istream_iterator<std::string>( in ),
std::istream_iterator<std::string>(),
std::back_inserter( rawTokens ) );
std::vector<std::string> tokens;
tokens.reserve( rawTokens.size() );
for( auto&& rawToken : rawTokens )
split( rawToken, std::back_inserter( tokens ) );
return tokens;
}
/**
Given a vector of tokens and a prefix length, traverses the vector and stores
the appropriate suffix of the token. The model for updating the suffixes is
very simple --- subsequent words are merely added to a list of known words.
This makes choosing the next word easier.
*/
database_type buildDatabase( const std::vector<std::string>& tokens, unsigned int prefixLength )
{
database_type database;
std::list<std::string> prefixWords( prefixLength );
for( std::size_t i = 0; i < tokens.size(); i++ )
{
prefixWords.pop_front();
prefixWords.push_back( tokens.at(i) );
if( i + 1 < tokens.size() )
{
std::string prefix = join( prefixWords.begin(),
prefixWords.end() );
database[prefix].push_back( tokens.at(i+1) );
}
}
return database;
}
/**
Starts creating text from the database of tokens, using a Markov chain. The
function will choose a prefix at random from the database, then select a
subsequent word from the word list at random, thereby creating a new prefix.
This process will be repeated until a number of pre-defined iterations has
been reached.
*/
std::string spew( const database_type& database, unsigned int numIterations )
{
std::random_device rd;
std::default_random_engine engine( rd() );
std::ostringstream output;
std::string prefix;
{
std::uniform_int_distribution<std::size_t> distribution( 0, database.size() - 1 );
std::size_t index = distribution( engine );
auto it = database.begin();
std::advance( it, index );
prefix = it->first;
output << prefix;
}
for( unsigned int i = 1; i < numIterations; i++ )
{
auto&& words = database.at( prefix );
std::uniform_int_distribution<std::size_t> distribution( 0, words.size() - 1 );
std::size_t index = distribution( engine );
std::string word = words.at( index );
// Choose a new prefix. We do this by splitting the old prefix into a list
// of tokens, deleting the first one, and appending the current word.
std::list<std::string> prefixTokens;
split( prefix,
std::back_inserter( prefixTokens ) );
prefixTokens.pop_front();
prefixTokens.push_back( word );
prefix = join( prefixTokens.begin(), prefixTokens.end() );
if( !isPunctuation( word ) )
output << " ";
output << word;
}
return output.str();
}
int main( int, char** )
{
auto tokens = getTokens( "../King_James.txt" );
auto database = buildDatabase( tokens, 2 );
std::cout << spew( database, 100 ) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <memory>
#include <gui/application.h>
#include <gui/dark_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/background_color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
#include <gui/color_picker.h>
constexpr double padding = 12;
std::shared_ptr<gui::application> app;
std::shared_ptr<gui::window> extra;
namespace {
struct test_record : public model::record
{
field<std::string> title = field<std::string>( this );
field<double> rating = field<double>( this, 1.0 );
};
std::shared_ptr<test_record> testrec = std::make_shared<test_record>();
////////////////////////////////////////
std::shared_ptr<gui::form> build_form( direction dir )
{
auto container = std::make_shared<gui::form>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
auto button = std::make_shared<gui::button>( "Click Me" );
button->when_activated.connect( []()
{
testrec->title = "Goodbye World";
} );
auto popup = std::make_shared<gui::button>( "Pop up" );
popup->when_activated.connect( []()
{
extra = app->new_popup();
extra->show();
} );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
container->add( std::make_shared<gui::label>( "Button" ), popup );
container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::background> build_grid( direction dir )
{
auto container = std::make_shared<gui::grid>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
for ( size_t y = 0; y < 5; ++y )
{
row.clear();
for ( size_t x = 0; x < 5; ++x )
{
row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
container->add_row( row, weights[y] );
}
for ( size_t y = 0; y < 5; ++y )
container->set_column_weight( y, weights[y] );
auto bg = std::make_shared<gui::background_color>();// { 1, 0, 1, 1 }, container );
bg->set_color( { 1, 0, 1, 1 } );
bg->set_widget( container );
return bg;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_box( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
for ( size_t y = 0; y < 5; ++y )
{
container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
auto container = std::make_shared<gui::tree_node>( 24.0, dir );
container->set_root( std::make_shared<gui::label>( "Root" ) );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
for ( size_t y = 0; y < 3; ++y )
{
auto node = std::make_shared<gui::tree_node>( 24.0, dir );
if( y == 1 )
{
auto button = std::make_shared<gui::button>( "+" );
button->when_activated.connect( [=]( void )
{
node->set_collapsed( !node->collapsed() );
} );
node->set_root( button );
}
else
node->set_root( std::make_shared<gui::label>( name ) );
std::string sub( "1" );
for ( size_t x = 0; x < 3; ++x )
{
node->add( std::make_shared<gui::label>( sub ) );
node->set_spacing( 12, 6 );
++sub[0];
}
container->add( node );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::widget> build_all( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };
for ( auto c: list )
container->add( c );
container->set_weight( 1, 1.0 );
auto scroll = std::make_shared<gui::scroll_area>( gui::scroll_behavior::NONE, gui::scroll_behavior::BOUND );
scroll->set_widget( container );
return scroll;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_color( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
container->add( std::make_shared<gui::color_picker>( base::color::space::HSL ), 1.0 );
container->add( std::make_shared<gui::color_picker>( base::color::space::LAB ), 1.0 );
return container;
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
testrec->title = "Hello World";
app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::dark_style>() );
auto win = app->new_window();
win->set_title( app->active_platform() );
std::string test = "form";
if ( argc > 1 )
test = argv[1];
std::string dirname = "box";
if ( argc > 2 )
dirname = argv[2];
direction dir = direction::DOWN;
if ( dirname == "down" )
dir = direction::DOWN;
else if ( dirname == "up" )
dir = direction::UP;
else if ( dirname == "left" )
dir = direction::LEFT;
else if ( dirname == "right" )
dir = direction::RIGHT;
if ( test == "form" )
win->set_widget( build_form( dir ) );
else if ( test == "grid" )
win->set_widget( build_grid( dir ) );
else if ( test == "box" )
win->set_widget( build_box( dir ) );
else if ( test == "tree" )
win->set_widget( build_tree( dir ) );
else if ( test == "edit" )
win->set_widget( build_edit( dir ) );
else if ( test == "color" )
win->set_widget( build_color( dir ) );
else if ( test == "all" )
win->set_widget( build_all( dir ) );
else
throw std::runtime_error( "unknown test" );
win->show();
int code = app->run();
app->pop();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
base::print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<commit_msg>Delete application when terminating.<commit_after>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <memory>
#include <gui/application.h>
#include <gui/dark_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/background_color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
#include <gui/color_picker.h>
constexpr double padding = 12;
std::shared_ptr<gui::application> app;
std::shared_ptr<gui::window> extra;
namespace {
struct test_record : public model::record
{
field<std::string> title = field<std::string>( this );
field<double> rating = field<double>( this, 1.0 );
};
std::shared_ptr<test_record> testrec = std::make_shared<test_record>();
////////////////////////////////////////
std::shared_ptr<gui::form> build_form( direction dir )
{
auto container = std::make_shared<gui::form>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
auto button = std::make_shared<gui::button>( "Click Me" );
button->when_activated.connect( []()
{
testrec->title = "Goodbye World";
} );
auto popup = std::make_shared<gui::button>( "Pop up" );
popup->when_activated.connect( []()
{
extra = app->new_popup();
extra->show();
} );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
container->add( std::make_shared<gui::label>( "Button" ), popup );
container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::background> build_grid( direction dir )
{
auto container = std::make_shared<gui::grid>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
for ( size_t y = 0; y < 5; ++y )
{
row.clear();
for ( size_t x = 0; x < 5; ++x )
{
row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
container->add_row( row, weights[y] );
}
for ( size_t y = 0; y < 5; ++y )
container->set_column_weight( y, weights[y] );
auto bg = std::make_shared<gui::background_color>();// { 1, 0, 1, 1 }, container );
bg->set_color( { 1, 0, 1, 1 } );
bg->set_widget( container );
return bg;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_box( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
for ( size_t y = 0; y < 5; ++y )
{
container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
auto container = std::make_shared<gui::tree_node>( 24.0, dir );
container->set_root( std::make_shared<gui::label>( "Root" ) );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
std::string name( "A" );
for ( size_t y = 0; y < 3; ++y )
{
auto node = std::make_shared<gui::tree_node>( 24.0, dir );
if( y == 1 )
{
auto button = std::make_shared<gui::button>( "+" );
button->when_activated.connect( [=]( void )
{
node->set_collapsed( !node->collapsed() );
} );
node->set_root( button );
}
else
node->set_root( std::make_shared<gui::label>( name ) );
std::string sub( "1" );
for ( size_t x = 0; x < 3; ++x )
{
node->add( std::make_shared<gui::label>( sub ) );
node->set_spacing( 12, 6 );
++sub[0];
}
container->add( node );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::widget> build_all( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };
for ( auto c: list )
container->add( c );
container->set_weight( 1, 1.0 );
auto scroll = std::make_shared<gui::scroll_area>( gui::scroll_behavior::NONE, gui::scroll_behavior::BOUND );
scroll->set_widget( container );
return scroll;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_color( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( padding, padding, padding, padding );
container->add( std::make_shared<gui::color_picker>( base::color::space::HSL ), 1.0 );
container->add( std::make_shared<gui::color_picker>( base::color::space::LAB ), 1.0 );
return container;
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
testrec->title = "Hello World";
app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::dark_style>() );
auto win = app->new_window();
win->set_title( app->active_platform() );
std::string test = "form";
if ( argc > 1 )
test = argv[1];
std::string dirname = "box";
if ( argc > 2 )
dirname = argv[2];
direction dir = direction::DOWN;
if ( dirname == "down" )
dir = direction::DOWN;
else if ( dirname == "up" )
dir = direction::UP;
else if ( dirname == "left" )
dir = direction::LEFT;
else if ( dirname == "right" )
dir = direction::RIGHT;
if ( test == "form" )
win->set_widget( build_form( dir ) );
else if ( test == "grid" )
win->set_widget( build_grid( dir ) );
else if ( test == "box" )
win->set_widget( build_box( dir ) );
else if ( test == "tree" )
win->set_widget( build_tree( dir ) );
else if ( test == "edit" )
win->set_widget( build_edit( dir ) );
else if ( test == "color" )
win->set_widget( build_color( dir ) );
else if ( test == "all" )
win->set_widget( build_all( dir ) );
else
throw std::runtime_error( "unknown test" );
win->show();
int code = app->run();
app->pop();
app.reset();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
base::print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "markertracker.h"
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
MarkerTracker::MarkerTracker() {
thresh = 100;
max_value = 255;
}
void MarkerTracker::find(cv::Mat &img_bgr) {
Mat img_grey, img_thresh;
cv::vector<cv::vector<cv::Point>> contours0;
cv::vector<cv::Vec4i> hierarchy;
vector<vector<Point>> sampledOnLinePoints;
// make the image B/W
cvtColor(img_bgr, img_grey, CV_RGB2GRAY);
blur(img_grey,img_grey, Size(3,3));
threshold(img_grey,img_thresh,this->thresh,this->max_value,cv::THRESH_BINARY);
// Find contours
findContours(img_thresh,
contours0,
hierarchy,
RETR_TREE,
CHAIN_APPROX_SIMPLE,
Point(0,0));
contours.resize(contours0.size());
// we want bounding rectangles now around our stuff - new var here.
vector<Rect> boundRect( contours.size() );
for (size_t i = 0; i < contours0.size(); ++i) {
// Process Polygons here
approxPolyDP(Mat(contours0[i]), contours[i], 3, true);
boundRect[i] = boundingRect( Mat(contours[i]) );
// Filter all the wrong polygons
if (
// the poly should have 4 or 5 borders
contours[i].size() == 4 && contours[i].size() <= 5
// size of rectangle around
&& boundRect[i].width >= 40
&& boundRect[i].height >= 40
)
{
// Debug Text
putText(img_bgr,
std::to_string(contours[i].size()) + "h" + std::to_string(boundRect[i].height) + "w" + std::to_string(boundRect[i].width),
boundRect[i].br(),
FONT_HERSHEY_PLAIN,
1,
cvScalar(200,200,250), 1, CV_AA);
Scalar circlecolor = Scalar(84,223,93);
//circle(img_bgr, contours[i][0], 5, circlecolor, 5);
//circle(img_bgr, contours[i][1], 5, circlecolor, 5);
//circle(img_bgr, contours[i][2], 5, circlecolor, 5);
//circle(img_bgr, contours[i][3], 5, circlecolor, 5);
// Circle in the middle
//sampledOnLinePoints.push_back(getSeventh(7, contours[i][0], contours[i][1]));
//cout << sampledOnLinePoints[0].size() << " - ";
for (int kk = 0; kk < 4; kk++ )
{
Point point1 = contours[i][kk];
Point point2;
if (kk < 3)
point2 = contours[i][kk+1];
else
point2 = contours[i][0];
int distanceX = point2.x - point1.x;
int distanceY = point2.y - point1.y;
//cout << "\n\n" << point1.x << " : " << point1.y << " \n ";
//cout << point2.x << " : " << point2.y << " \n ";
//cout << distanceX << " \n ";
//cout << distanceY << " \n ";
for (int j = 1; j < 7; j++)
{
//circle(img_bgr, Point(distanceX/7*j+point1.x, distanceY/7*j+point1.y), 1, circlecolor, 5);
line(img_bgr,
Point(distanceX/7.0*j+point1.x+distanceY/14.0,
distanceY/7.0*j+point1.y-distanceX/14.0),
Point(distanceX/7.0*j+point1.x-distanceY/14.0,
distanceY/7.0*j+point1.y+distanceX/14.0),
Scalar(0,165,255),
1,
8
);
//cout << "(" << distanceX/7*j+point1.x << ":";
//cout << distanceY/7*j+point1.y << ")";
}
}
/*
for (int i = 0; i < sampledOnLinePoints[0].size(); i++)
{
circle(img_bgr, sampledOnLinePoints[0][i], 5, circlecolor, 5);
}
*/
drawContours(img_bgr,contours,i,Scalar(93,239,255),1,8,hierarchy, 0, cv::Point());
//rectangle( img_bgr, boundRect[i].tl(), boundRect[i].br(), Scalar(100,165,255), 2, 8, 0 );
}
}
}
int sampleSubPix(const cv::Mat &pSrc, const cv::Point2f &p)
{
int x = int(floorf(p.x));
int y = int(floorf(p.y));
if (x < 0 || x >= pSrc.cols - 1 ||
y < 0 || y >= pSrc.rows - 1)
return 127;
int dx = int(256 * (p.x - floorf(p.x)));
int dy = int(256 * (p.y - floorf(p.y)));
unsigned char* i = (unsigned char*)((pSrc.data + y * pSrc.step) + x);
int a = i[0] + ((dx * (i[1] - i[0])) / 256);
i += pSrc.step;
int b = i[0] + ((dx * (i[1] - i[0])) / 256);
return a + ((dy * (b - a)) / 256);
}
/*
What does this code do?
This function solves the following problem: The image is stored as an OpenCV matrix pSrc.
Now, what we are doing is trying to get the intensity at a certain location p in the image.
If p = (x,y) and x,y are natural numbers we can simply access the image pSrc.at<uchar>(y,x).
But since we are interested in non integer locations p, we can use this function.
So what it does is bilinear interpolation (http://en.wikipedia.org/wiki/Bilinear_interpolation)
of the image pSrc at location p.
*/
int getDelta( int value1, int value2)
{
if (value1 > value2)
return value1-value2;
else
return value2-value1;
}
int getMiddle( int value1, int value2){
if (value1 > value2)
return value2 + (value1-value2)/2;
else
return value1 + (value2-value1)/2;
}
cv::vector<Point> getSeventh(int divider, Point point1, Point point2) {
}
<commit_msg>Calculating some standard vector and length<commit_after>#include "markertracker.h"
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
MarkerTracker::MarkerTracker() {
thresh = 100;
max_value = 255;
}
void MarkerTracker::find(cv::Mat &img_bgr) {
Mat img_grey, img_thresh;
cv::vector<cv::vector<cv::Point>> contours0;
cv::vector<cv::Vec4i> hierarchy;
vector<vector<Point>> sampledOnLinePoints;
// make the image B/W
cvtColor(img_bgr, img_grey, CV_RGB2GRAY);
blur(img_grey,img_grey, Size(3,3));
threshold(img_grey,img_thresh,this->thresh,this->max_value,cv::THRESH_BINARY);
// Find contours
findContours(img_thresh,
contours0,
hierarchy,
RETR_TREE,
CHAIN_APPROX_SIMPLE,
Point(0,0));
contours.resize(contours0.size());
// we want bounding rectangles now around our stuff - new var here.
vector<Rect> boundRect( contours.size() );
for (size_t i = 0; i < contours0.size(); ++i) {
// Process Polygons here
approxPolyDP(Mat(contours0[i]), contours[i], 3, true);
boundRect[i] = boundingRect( Mat(contours[i]) );
// Filter all the wrong polygons
if (
// the poly should have 4 or 5 borders
contours[i].size() == 4 && contours[i].size() <= 5
// size of rectangle around
&& boundRect[i].width >= 40
&& boundRect[i].height >= 40
)
{
// Debug Text
putText(img_bgr,
std::to_string(contours[i].size()) + "h" + std::to_string(boundRect[i].height) + "w" + std::to_string(boundRect[i].width),
boundRect[i].br(),
FONT_HERSHEY_PLAIN,
1,
cvScalar(200,200,250), 1, CV_AA);
Scalar circlecolor = Scalar(84,223,93);
//circle(img_bgr, contours[i][0], 5, circlecolor, 5);
//circle(img_bgr, contours[i][1], 5, circlecolor, 5);
//circle(img_bgr, contours[i][2], 5, circlecolor, 5);
//circle(img_bgr, contours[i][3], 5, circlecolor, 5);
// Circle in the middle
//sampledOnLinePoints.push_back(getSeventh(7, contours[i][0], contours[i][1]));
//cout << sampledOnLinePoints[0].size() << " - ";
for (int kk = 0; kk < 4; kk++ )
{
Point point1 = contours[i][kk];
Point point2;
if (kk < 3)
point2 = contours[i][kk+1];
else
point2 = contours[i][0];
int distanceX = point2.x - point1.x;
int distanceY = point2.y - point1.y;
//cout << "\n\n" << point1.x << " : " << point1.y << " \n ";
//cout << point2.x << " : " << point2.y << " \n ";
//cout << distanceX << " \n ";
//cout << distanceY << " \n ";
// Trying to get a Matrix from one line here!
Vec2f TheVectorStart(distanceX/7.0+point1.x+distanceY/14.0, distanceY/7.0+point1.y-distanceX/14.0);
Vec2f TheVectorDirection(
- (distanceX/7.0+point1.x+distanceY/14.0)
+ (distanceX/7.0+point1.x-distanceY/14.0)
,
- (distanceY/7.0+point1.y-distanceX/14.0)
+ (distanceY/7.0+point1.y+distanceX/14.0)
);
float TheVectorLength = std::sqrt(std::pow((double)TheVectorDirection[0],2)+std::pow((double)TheVectorDirection[1],2));
cout << TheVectorDirection[0] / TheVectorLength << " : " << TheVectorDirection[1] / TheVectorLength << "\n" ;
line(img_bgr,
Point(TheVectorStart[0],
TheVectorStart[1]),
Point(TheVectorStart[0]+TheVectorDirection[0],
TheVectorStart[1]+TheVectorDirection[1]),
Scalar(0,165,255),
1,
8
);
/*Point(distanceX/7.0*j+point1.x+distanceY/14.0,
distanceY/7.0*j+point1.y-distanceX/14.0);
Point(distanceX/7.0*j+point1.x-distanceY/14.0,
distanceY/7.0*j+point1.y+distanceX/14.0);*/
/*
*
* TODO Draw all lines are uncommented here!
for (int j = 1; j < 7; j++)
{
//circle(img_bgr, Point(distanceX/7*j+point1.x, distanceY/7*j+point1.y), 1, circlecolor, 5);
line(img_bgr,
Point(distanceX/7.0*j+point1.x+distanceY/14.0,
distanceY/7.0*j+point1.y-distanceX/14.0),
Point(distanceX/7.0*j+point1.x-distanceY/14.0,
distanceY/7.0*j+point1.y+distanceX/14.0),
Scalar(0,165,255),
1,
8
);
//cout << "(" << distanceX/7*j+point1.x << ":";
//cout << distanceY/7*j+point1.y << ")";
}*/
}
/*
for (int i = 0; i < sampledOnLinePoints[0].size(); i++)
{
circle(img_bgr, sampledOnLinePoints[0][i], 5, circlecolor, 5);
}
*/
drawContours(img_bgr,contours,i,Scalar(93,239,255),1,8,hierarchy, 0, cv::Point());
// Bounding rectangle
//rectangle( img_bgr, boundRect[i].tl(), boundRect[i].br(), Scalar(100,165,255), 2, 8, 0 );
}
}
}
int sampleSubPix(const cv::Mat &pSrc, const cv::Point2f &p)
{
int x = int(floorf(p.x));
int y = int(floorf(p.y));
if (x < 0 || x >= pSrc.cols - 1 ||
y < 0 || y >= pSrc.rows - 1)
return 127;
int dx = int(256 * (p.x - floorf(p.x)));
int dy = int(256 * (p.y - floorf(p.y)));
unsigned char* i = (unsigned char*)((pSrc.data + y * pSrc.step) + x);
int a = i[0] + ((dx * (i[1] - i[0])) / 256);
i += pSrc.step;
int b = i[0] + ((dx * (i[1] - i[0])) / 256);
return a + ((dy * (b - a)) / 256);
}
/*
What does this code do?
This function solves the following problem: The image is stored as an OpenCV matrix pSrc.
Now, what we are doing is trying to get the intensity at a certain location p in the image.
If p = (x,y) and x,y are natural numbers we can simply access the image pSrc.at<uchar>(y,x).
But since we are interested in non integer locations p, we can use this function.
So what it does is bilinear interpolation (http://en.wikipedia.org/wiki/Bilinear_interpolation)
of the image pSrc at location p.
*/
int getDelta( int value1, int value2)
{
if (value1 > value2)
return value1-value2;
else
return value2-value1;
}
int getMiddle( int value1, int value2){
if (value1 > value2)
return value2 + (value1-value2)/2;
else
return value1 + (value2-value1)/2;
}
cv::vector<Point> getSeventh(int divider, Point point1, Point point2) {
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <master/ConfigDirectoryMaster.h>
#include <stx/io/file.h>
#include <stx/io/fileutil.h>
#include <stx/random.h>
#include <stx/protobuf/msg.h>
#include <stx/logging.h>
#include <stx/inspect.h>
using namespace stx;
namespace cm {
ConfigDirectoryMaster::ConfigDirectoryMaster(
const String& path) :
db_path_(path) {
loadHeads();
}
CustomerConfig ConfigDirectoryMaster::fetchCustomerConfig(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto cpath = FileUtil::joinPaths(db_path_, customer_key);
auto hpath = FileUtil::joinPaths(cpath, "config.HEAD");
if (!FileUtil::exists(hpath)) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
auto head_version = std::stoull(FileUtil::read(hpath).toString());
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("config.$0", head_version));
return msg::decode<CustomerConfig>(FileUtil::read(vpath));
}
void ConfigDirectoryMaster::updateCustomerConfig(CustomerConfig config) {
std::unique_lock<std::mutex> lk(mutex_);
uint64_t head_version = 0;
auto cpath = FileUtil::joinPaths(db_path_, config.customer());
auto hpath = FileUtil::joinPaths(cpath, "config.HEAD");
if (FileUtil::exists(cpath)) {
if (FileUtil::exists(hpath)) {
auto head_version_str = FileUtil::read(hpath);
head_version = std::stoull(head_version_str.toString());
}
} else {
FileUtil::mkdir(cpath);
}
if (config.version() != head_version) {
RAISE(
kRuntimeError,
"VERSION MISMATCH: can't update customer config because the update is" \
" out of date (i.e. it is not based on the latest head version)");
}
config.set_version(++head_version);
auto config_buf = msg::encode(config);
logInfo(
"dxa-master",
"Updating customer config; customer=$0 head=$1",
config.customer(),
head_version);
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("config.$0", head_version));
auto vtmppath = vpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(vtmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(config_buf->data(), config_buf->size());
}
auto htmppath = hpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(htmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(StringUtil::toString(head_version));
}
FileUtil::mv(vtmppath, vpath);
FileUtil::mv(htmppath, hpath);
heads_["customers/" + config.customer()] = head_version;
}
void ConfigDirectoryMaster::updateTableDefinition(const TableDefinition& td) {
std::unique_lock<std::mutex> lk(mutex_);
uint64_t head_version = 0;
auto customer_key = td.customer();
auto cpath = FileUtil::joinPaths(db_path_, customer_key);
auto hpath = FileUtil::joinPaths(cpath, "tables.HEAD");
TableDefinitionList tables;
if (FileUtil::exists(cpath)) {
if (FileUtil::exists(hpath)) {
auto head_version_str = FileUtil::read(hpath);
head_version = std::stoull(head_version_str.toString());
tables = msg::decode<TableDefinitionList>(
FileUtil::read(
FileUtil::joinPaths(
cpath,
StringUtil::format("tables.$0", head_version))));
}
} else {
FileUtil::mkdir(cpath);
}
TableDefinition* head_td = nullptr;
for (auto& tbl : *tables.mutable_tables()) {
if (tbl.table_name() == td.table_name()) {
head_td = &tbl;
}
}
if (head_td == nullptr) {
head_td = tables.add_tables();
}
if (td.version() != head_td->version()) {
RAISE(
kRuntimeError,
"VERSION MISMATCH: can't update table definition because the update is" \
" out of date (i.e. it is not based on the latest head version)");
}
*head_td = td;
head_td->set_version(td.version() + 1);
++head_version;
logInfo(
"dxa-master",
"Updating table config; customer=$0 table=$1 head=$2",
customer_key,
head_td->table_name(),
head_td->version());
auto td_buf = msg::encode(tables);
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("tables.$0", head_version));
auto vtmppath = vpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(vtmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(td_buf->data(), td_buf->size());
}
auto htmppath = hpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(htmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(StringUtil::toString(head_version));
}
FileUtil::mv(vtmppath, vpath);
FileUtil::mv(htmppath, hpath);
heads_["tables/" + customer_key] = head_version;
}
Vector<Pair<String, uint64_t>> ConfigDirectoryMaster::heads() const {
std::unique_lock<std::mutex> lk(mutex_);
Vector<Pair<String, uint64_t>> heads;
for (const auto& h : heads_) {
heads.emplace_back(h);
}
return heads;
}
void ConfigDirectoryMaster::loadHeads() {
FileUtil::ls(db_path_, [this] (const String& customer) -> bool {
{
auto hpath = FileUtil::joinPaths(db_path_, customer + "/config.HEAD");
if (FileUtil::exists(hpath)) {
heads_["customers/" + customer] =
std::stoull(FileUtil::read(hpath).toString());
}
}
{
auto hpath = FileUtil::joinPaths(db_path_, customer + "/tables.HEAD");
if (FileUtil::exists(hpath)) {
heads_["tables/" + customer] =
std::stoull(FileUtil::read(hpath).toString());
}
}
return true;
});
}
} // namespace cm
<commit_msg>ConfigDirectoryMaster::fetchTableDefinition<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <master/ConfigDirectoryMaster.h>
#include <stx/io/file.h>
#include <stx/io/fileutil.h>
#include <stx/random.h>
#include <stx/protobuf/msg.h>
#include <stx/logging.h>
#include <stx/inspect.h>
using namespace stx;
namespace cm {
ConfigDirectoryMaster::ConfigDirectoryMaster(
const String& path) :
db_path_(path) {
loadHeads();
}
CustomerConfig ConfigDirectoryMaster::fetchCustomerConfig(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto cpath = FileUtil::joinPaths(db_path_, customer_key);
auto hpath = FileUtil::joinPaths(cpath, "config.HEAD");
if (!FileUtil::exists(hpath)) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
auto head_version = std::stoull(FileUtil::read(hpath).toString());
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("config.$0", head_version));
return msg::decode<CustomerConfig>(FileUtil::read(vpath));
}
void ConfigDirectoryMaster::updateCustomerConfig(CustomerConfig config) {
std::unique_lock<std::mutex> lk(mutex_);
uint64_t head_version = 0;
auto cpath = FileUtil::joinPaths(db_path_, config.customer());
auto hpath = FileUtil::joinPaths(cpath, "config.HEAD");
if (FileUtil::exists(cpath)) {
if (FileUtil::exists(hpath)) {
auto head_version_str = FileUtil::read(hpath);
head_version = std::stoull(head_version_str.toString());
}
} else {
FileUtil::mkdir(cpath);
}
if (config.version() != head_version) {
RAISE(
kRuntimeError,
"VERSION MISMATCH: can't update customer config because the update is" \
" out of date (i.e. it is not based on the latest head version)");
}
config.set_version(++head_version);
auto config_buf = msg::encode(config);
logInfo(
"dxa-master",
"Updating customer config; customer=$0 head=$1",
config.customer(),
head_version);
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("config.$0", head_version));
auto vtmppath = vpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(vtmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(config_buf->data(), config_buf->size());
}
auto htmppath = hpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(htmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(StringUtil::toString(head_version));
}
FileUtil::mv(vtmppath, vpath);
FileUtil::mv(htmppath, hpath);
heads_["customers/" + config.customer()] = head_version;
}
TableDefinition ConfigDirectoryMaster::fetchTableDefinition(
const String& customer_key,
const String& table_name) {
std::unique_lock<std::mutex> lk(mutex_);
auto cpath = FileUtil::joinPaths(db_path_, customer_key);
auto hpath = FileUtil::joinPaths(cpath, "tables.HEAD");
if (!FileUtil::exists(cpath) || !FileUtil::exists(hpath)) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
auto head_version = FileUtil::read(hpath).toString();
auto tables = msg::decode<TableDefinitionList>(
FileUtil::read(
FileUtil::joinPaths(
cpath,
StringUtil::format("tables.$0", head_version))));
for (auto& tbl : tables.tables()) {
if (tbl.table_name() == table_name) {
return tbl;
}
}
RAISEF(kNotFoundError, "table not found: $0", table_name);
}
void ConfigDirectoryMaster::updateTableDefinition(const TableDefinition& td) {
std::unique_lock<std::mutex> lk(mutex_);
uint64_t head_version = 0;
auto customer_key = td.customer();
auto cpath = FileUtil::joinPaths(db_path_, customer_key);
auto hpath = FileUtil::joinPaths(cpath, "tables.HEAD");
TableDefinitionList tables;
if (FileUtil::exists(cpath)) {
if (FileUtil::exists(hpath)) {
auto head_version_str = FileUtil::read(hpath);
head_version = std::stoull(head_version_str.toString());
tables = msg::decode<TableDefinitionList>(
FileUtil::read(
FileUtil::joinPaths(
cpath,
StringUtil::format("tables.$0", head_version))));
}
} else {
FileUtil::mkdir(cpath);
}
TableDefinition* head_td = nullptr;
for (auto& tbl : *tables.mutable_tables()) {
if (tbl.table_name() == td.table_name()) {
head_td = &tbl;
}
}
if (head_td == nullptr) {
head_td = tables.add_tables();
}
if (td.version() != head_td->version()) {
RAISE(
kRuntimeError,
"VERSION MISMATCH: can't update table definition because the update is" \
" out of date (i.e. it is not based on the latest head version)");
}
*head_td = td;
head_td->set_version(td.version() + 1);
++head_version;
logInfo(
"dxa-master",
"Updating table config; customer=$0 table=$1 head=$2",
customer_key,
head_td->table_name(),
head_td->version());
auto td_buf = msg::encode(tables);
auto vpath = FileUtil::joinPaths(
cpath,
StringUtil::format("tables.$0", head_version));
auto vtmppath = vpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(vtmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(td_buf->data(), td_buf->size());
}
auto htmppath = hpath + "~tmp." + Random::singleton()->hex64();
{
auto tmpfile = File::openFile(htmppath, File::O_CREATE | File::O_WRITE);
tmpfile.write(StringUtil::toString(head_version));
}
FileUtil::mv(vtmppath, vpath);
FileUtil::mv(htmppath, hpath);
heads_["tables/" + customer_key] = head_version;
}
Vector<Pair<String, uint64_t>> ConfigDirectoryMaster::heads() const {
std::unique_lock<std::mutex> lk(mutex_);
Vector<Pair<String, uint64_t>> heads;
for (const auto& h : heads_) {
heads.emplace_back(h);
}
return heads;
}
void ConfigDirectoryMaster::loadHeads() {
FileUtil::ls(db_path_, [this] (const String& customer) -> bool {
{
auto hpath = FileUtil::joinPaths(db_path_, customer + "/config.HEAD");
if (FileUtil::exists(hpath)) {
heads_["customers/" + customer] =
std::stoull(FileUtil::read(hpath).toString());
}
}
{
auto hpath = FileUtil::joinPaths(db_path_, customer + "/tables.HEAD");
if (FileUtil::exists(hpath)) {
heads_["tables/" + customer] =
std::stoull(FileUtil::read(hpath).toString());
}
}
return true;
});
}
} // namespace cm
<|endoftext|> |
<commit_before>/**
* @file nmf_als.hpp
* @author Sumedh Ghaisas
*/
namespace mlpack {
namespace amf {
/**
* Construct the LMF object.
*/
template<typename InitializationRule,
typename UpdateRule>
AMF<InitializationRule, UpdateRule>::AMF(
const size_t maxIterations,
const double tolerance,
const InitializationRule initializeRule,
const UpdateRule update) :
maxIterations(maxIterations),
tolerance(tolerance),
initializeRule(initializeRule),
update(update)
{
if (tolerance < 0.0 || tolerance > 1)
{
Log::Warn << "AMF::AMF(): tolerance must be a positive value in the range (0-1) but value "
<< tolerance << " is given. Setting to the default value of 1e-5.\n";
this->tolerance = 1e-5;
}
}
/**
* Apply Latent Matrix Factorization to the provided matrix.
*
* @param V Input matrix to be factorized
* @param W Basis matrix to be output
* @param H Encoding matrix to output
* @param r Rank r of the factorization
*/
template<typename InitializationRule,
typename UpdateRule>
template<typename MatType>
double AMF<InitializationRule, UpdateRule>::Apply(
const MatType& V,
const size_t r,
arma::mat& W,
arma::mat& H)
{
const size_t n = V.n_rows;
const size_t m = V.n_cols;
// Initialize W and H.
initializeRule.Initialize(V, r, W, H);
Log::Info << "Initialized W and H." << std::endl;
size_t iteration = 1;
const size_t nm = n * m;
double residue = DBL_MIN;
double oldResidue = DBL_MAX;
double normOld = 0;
double norm = 0;
arma::mat WH;
update.Initialize(V, r);
while (((oldResidue - residue) / oldResidue >= tolerance || iteration < 4) && iteration != maxIterations)
{
// Update step.
// Update the value of W and H based on the Update Rules provided
update.WUpdate(V, W, H);
update.HUpdate(V, W, H);
// Calculate norm of WH after each iteration.
WH = W * H;
norm = sqrt(accu(WH % WH) / nm);
if (iteration != 0)
{
oldResidue = residue;
residue = fabs(normOld - norm);
residue /= normOld;
}
normOld = norm;
iteration++;
}
Log::Info << "AMF converged to residue of " << sqrt(residue) << " in "
<< iteration << " iterations." << std::endl;
return residue;
}
}; // namespace nmf
}; // namespace mlpack
<commit_msg>Fix for convergence, because sometimes the residue may increase (especially with ALS update rules).<commit_after>/**
* @file nmf_als.hpp
* @author Sumedh Ghaisas
*/
namespace mlpack {
namespace amf {
/**
* Construct the LMF object.
*/
template<typename InitializationRule,
typename UpdateRule>
AMF<InitializationRule, UpdateRule>::AMF(
const size_t maxIterations,
const double tolerance,
const InitializationRule initializeRule,
const UpdateRule update) :
maxIterations(maxIterations),
tolerance(tolerance),
initializeRule(initializeRule),
update(update)
{
if (tolerance < 0.0 || tolerance > 1)
{
Log::Warn << "AMF::AMF(): tolerance must be a positive value in the range (0-1) but value "
<< tolerance << " is given. Setting to the default value of 1e-5.\n";
this->tolerance = 1e-5;
}
}
/**
* Apply Latent Matrix Factorization to the provided matrix.
*
* @param V Input matrix to be factorized
* @param W Basis matrix to be output
* @param H Encoding matrix to output
* @param r Rank r of the factorization
*/
template<typename InitializationRule,
typename UpdateRule>
template<typename MatType>
double AMF<InitializationRule, UpdateRule>::Apply(
const MatType& V,
const size_t r,
arma::mat& W,
arma::mat& H)
{
const size_t n = V.n_rows;
const size_t m = V.n_cols;
// Initialize W and H.
initializeRule.Initialize(V, r, W, H);
Log::Info << "Initialized W and H." << std::endl;
size_t iteration = 1;
const size_t nm = n * m;
double residue = DBL_MIN;
double oldResidue = DBL_MAX;
double normOld = 0;
double norm = 0;
arma::mat WH;
update.Initialize(V, r);
while ((std::abs(oldResidue - residue) / oldResidue >= tolerance || iteration < 4) && iteration != maxIterations)
{
// Update step.
// Update the value of W and H based on the Update Rules provided
update.WUpdate(V, W, H);
update.HUpdate(V, W, H);
// Calculate norm of WH after each iteration.
WH = W * H;
norm = sqrt(accu(WH % WH) / nm);
if (iteration != 0)
{
oldResidue = residue;
residue = fabs(normOld - norm);
residue /= normOld;
}
normOld = norm;
iteration++;
}
Log::Info << "AMF converged to residue of " << sqrt(residue) << " in "
<< iteration << " iterations." << std::endl;
return residue;
}
}; // namespace nmf
}; // namespace mlpack
<|endoftext|> |
<commit_before>/**
* @file gmm_impl.hpp
* @author Parikshit Ram (pram@cc.gatech.edu)
* @author Ryan Curtin
*
* Implementation of template-based GMM methods.
*/
#ifndef __MLPACK_METHODS_GMM_GMM_IMPL_HPP
#define __MLPACK_METHODS_GMM_GMM_IMPL_HPP
// In case it hasn't already been included.
#include "gmm.hpp"
#include <mlpack/core/util/save_restore_utility.hpp>
namespace mlpack {
namespace gmm {
// Copy constructor.
template<typename FittingType>
template<typename OtherFittingType>
GMM<FittingType>::GMM(const GMM<OtherFittingType>& other) :
gaussians(other.Gaussians()),
dimensionality(other.Dimensionality()),
means(other.Means()),
covariances(other.Covariances()),
weights(other.Weights()),
localFitter(FittingType()),
fitter(localFitter) { /* Nothing to do. */ }
// Copy constructor for when the other GMM uses the same fitting type.
template<typename FittingType>
GMM<FittingType>::GMM(const GMM<FittingType>& other) :
gaussians(other.Gaussians()),
dimensionality(other.Dimensionality()),
means(other.Means()),
covariances(other.Covariances()),
weights(other.Weights()),
localFitter(other.Fitter()),
fitter(localFitter) { /* Nothing to do. */ }
template<typename FittingType>
template<typename OtherFittingType>
GMM<FittingType>& GMM<FittingType>::operator=(
const GMM<OtherFittingType>& other)
{
gaussians = other.Gaussians();
dimensionality = other.Dimensionality();
means = other.Means();
covariances = other.Covariances();
weights = other.Weights();
return *this;
}
template<typename FittingType>
GMM<FittingType>& GMM<FittingType>::operator=(const GMM<FittingType>& other)
{
gaussians = other.Gaussians();
dimensionality = other.Dimensionality();
means = other.Means();
covariances = other.Covariances();
weights = other.Weights();
localFitter = other.Fitter();
return *this;
}
// Load a GMM from file.
template<typename FittingType>
void GMM<FittingType>::Load(const std::string& filename)
{
util::SaveRestoreUtility load;
if (!load.ReadFile(filename))
Log::Fatal << "GMM::Load(): could not read file '" << filename << "'!\n";
load.LoadParameter(gaussians, "gaussians");
load.LoadParameter(dimensionality, "dimensionality");
load.LoadParameter(weights, "weights");
// We need to do a little error checking here.
if (weights.n_elem != gaussians)
{
Log::Fatal << "GMM::Load('" << filename << "'): file reports " << gaussians
<< " gaussians but weights vector only contains " << weights.n_elem
<< " elements!" << std::endl;
}
means.resize(gaussians);
covariances.resize(gaussians);
for (size_t i = 0; i < gaussians; ++i)
{
std::stringstream o;
o << i;
std::string meanName = "mean" + o.str();
std::string covName = "covariance" + o.str();
load.LoadParameter(means[i], meanName);
load.LoadParameter(covariances[i], covName);
}
}
// Save a GMM to a file.
template<typename FittingType>
void GMM<FittingType>::Save(const std::string& filename) const
{
util::SaveRestoreUtility save;
save.SaveParameter(gaussians, "gaussians");
save.SaveParameter(dimensionality, "dimensionality");
save.SaveParameter(weights, "weights");
for (size_t i = 0; i < gaussians; ++i)
{
// Generate names for the XML nodes.
std::stringstream o;
o << i;
std::string meanName = "mean" + o.str();
std::string covName = "covariance" + o.str();
// Now save them.
save.SaveParameter(means[i], meanName);
save.SaveParameter(covariances[i], covName);
}
if (!save.WriteFile(filename))
Log::Warn << "GMM::Save(): error saving to '" << filename << "'.\n";
}
/**
* Return the probability of the given observation being from this GMM.
*/
template<typename FittingType>
double GMM<FittingType>::Probability(const arma::vec& observation) const
{
// Sum the probability for each Gaussian in our mixture (and we have to
// multiply by the prior for each Gaussian too).
double sum = 0;
for (size_t i = 0; i < gaussians; i++)
sum += weights[i] * phi(observation, means[i], covariances[i]);
return sum;
}
/**
* Return the probability of the given observation being from the given
* component in the mixture.
*/
template<typename FittingType>
double GMM<FittingType>::Probability(const arma::vec& observation,
const size_t component) const
{
// We are only considering one Gaussian component -- so we only need to call
// phi() once. We do consider the prior probability!
return weights[component] *
phi(observation, means[component], covariances[component]);
}
/**
* Return a randomly generated observation according to the probability
* distribution defined by this object.
*/
template<typename FittingType>
arma::vec GMM<FittingType>::Random() const
{
// Determine which Gaussian it will be coming from.
double gaussRand = math::Random();
size_t gaussian;
double sumProb = 0;
for (size_t g = 0; g < gaussians; g++)
{
sumProb += weights(g);
if (gaussRand <= sumProb)
{
gaussian = g;
break;
}
}
return trans(chol(covariances[gaussian])) *
arma::randn<arma::vec>(dimensionality) + means[gaussian];
}
/**
* Fit the GMM to the given observations.
*/
template<typename FittingType>
double GMM<FittingType>::Estimate(const arma::mat& observations,
const size_t trials)
{
double bestLikelihood; // This will be reported later.
// We don't need to store temporary models if we are only doing one trial.
if (trials == 1)
{
// Train the model. The user will have been warned earlier if the GMM was
// initialized with no parameters (0 gaussians, dimensionality of 0).
fitter.Estimate(observations, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
}
else
{
if (trials == 0)
return -DBL_MAX; // It's what they asked for...
// We need to keep temporary copies. We'll do the first training into the
// actual model position, so that if it's the best we don't need to copy it.
fitter.Estimate(observations, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial 0 is "
<< bestLikelihood << "." << std::endl;
// Now the temporary model.
std::vector<arma::vec> meansTrial(gaussians, arma::vec(dimensionality));
std::vector<arma::mat> covariancesTrial(gaussians,
arma::mat(dimensionality, dimensionality));
arma::vec weightsTrial(gaussians);
for (size_t trial = 1; trial < trials; ++trial)
{
fitter.Estimate(observations, meansTrial, covariancesTrial, weightsTrial);
// Check to see if the log-likelihood of this one is better.
double newLikelihood = LogLikelihood(observations, meansTrial,
covariancesTrial, weightsTrial);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial " << trial
<< " is " << newLikelihood << "." << std::endl;
if (newLikelihood > bestLikelihood)
{
// Save new likelihood and copy new model.
bestLikelihood = newLikelihood;
means = meansTrial;
covariances = covariancesTrial;
weights = weightsTrial;
}
}
}
// Report final log-likelihood and return it.
Log::Info << "GMM::Estimate(): log-likelihood of trained GMM is "
<< bestLikelihood << "." << std::endl;
return bestLikelihood;
}
/**
* Fit the GMM to the given observations, each of which has a certain
* probability of being from this distribution.
*/
template<typename FittingType>
double GMM<FittingType>::Estimate(const arma::mat& observations,
const arma::vec& probabilities,
const size_t trials)
{
double bestLikelihood; // This will be reported later.
// We don't need to store temporary models if we are only doing one trial.
if (trials == 1)
{
// Train the model. The user will have been warned earlier if the GMM was
// initialized with no parameters (0 gaussians, dimensionality of 0).
fitter.Estimate(observations, probabilities, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
}
else
{
if (trials == 0)
return -DBL_MAX; // It's what they asked for...
// We need to keep temporary copies. We'll do the first training into the
// actual model position, so that if it's the best we don't need to copy it.
fitter.Estimate(observations, probabilities, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial 0 is "
<< bestLikelihood << "." << std::endl;
// Now the temporary model.
std::vector<arma::vec> meansTrial(gaussians, arma::vec(dimensionality));
std::vector<arma::mat> covariancesTrial(gaussians,
arma::mat(dimensionality, dimensionality));
arma::vec weightsTrial(gaussians);
for (size_t trial = 1; trial < trials; ++trial)
{
fitter.Estimate(observations, meansTrial, covariancesTrial, weightsTrial);
// Check to see if the log-likelihood of this one is better.
double newLikelihood = LogLikelihood(observations, meansTrial,
covariancesTrial, weightsTrial);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial " << trial
<< " is " << newLikelihood << "." << std::endl;
if (newLikelihood > bestLikelihood)
{
// Save new likelihood and copy new model.
bestLikelihood = newLikelihood;
means = meansTrial;
covariances = covariancesTrial;
weights = weightsTrial;
}
}
}
// Report final log-likelihood and return it.
Log::Info << "GMM::Estimate(): log-likelihood of trained GMM is "
<< bestLikelihood << "." << std::endl;
return bestLikelihood;
}
/**
* Classify the given observations as being from an individual component in this
* GMM.
*/
template<typename FittingType>
void GMM<FittingType>::Classify(const arma::mat& observations,
arma::Col<size_t>& labels) const
{
// This is not the best way to do this!
// We should not have to fill this with values, because each one should be
// overwritten.
labels.set_size(observations.n_cols);
for (size_t i = 0; i < observations.n_cols; ++i)
{
// Find maximum probability component.
double probability = 0;
for (size_t j = 0; j < gaussians; ++j)
{
double newProb = Probability(observations.unsafe_col(i), j);
if (newProb >= probability)
{
probability = newProb;
labels[i] = j;
}
}
}
}
/**
* Get the log-likelihood of this data's fit to the model.
*/
template<typename FittingType>
double GMM<FittingType>::LogLikelihood(
const arma::mat& data,
const std::vector<arma::vec>& meansL,
const std::vector<arma::mat>& covariancesL,
const arma::vec& weightsL) const
{
double loglikelihood = 0;
arma::vec phis;
arma::mat likelihoods(gaussians, data.n_cols);
for (size_t i = 0; i < gaussians; i++)
{
phi(data, meansL[i], covariancesL[i], phis);
likelihoods.row(i) = weightsL(i) * trans(phis);
}
// Now sum over every point.
for (size_t j = 0; j < data.n_cols; j++)
loglikelihood += log(accu(likelihoods.col(j)));
return loglikelihood;
}
}; // namespace gmm
}; // namespace mlpack
#endif
<commit_msg>This should be informational output which is present even when debugging symbols aren't.<commit_after>/**
* @file gmm_impl.hpp
* @author Parikshit Ram (pram@cc.gatech.edu)
* @author Ryan Curtin
*
* Implementation of template-based GMM methods.
*/
#ifndef __MLPACK_METHODS_GMM_GMM_IMPL_HPP
#define __MLPACK_METHODS_GMM_GMM_IMPL_HPP
// In case it hasn't already been included.
#include "gmm.hpp"
#include <mlpack/core/util/save_restore_utility.hpp>
namespace mlpack {
namespace gmm {
// Copy constructor.
template<typename FittingType>
template<typename OtherFittingType>
GMM<FittingType>::GMM(const GMM<OtherFittingType>& other) :
gaussians(other.Gaussians()),
dimensionality(other.Dimensionality()),
means(other.Means()),
covariances(other.Covariances()),
weights(other.Weights()),
localFitter(FittingType()),
fitter(localFitter) { /* Nothing to do. */ }
// Copy constructor for when the other GMM uses the same fitting type.
template<typename FittingType>
GMM<FittingType>::GMM(const GMM<FittingType>& other) :
gaussians(other.Gaussians()),
dimensionality(other.Dimensionality()),
means(other.Means()),
covariances(other.Covariances()),
weights(other.Weights()),
localFitter(other.Fitter()),
fitter(localFitter) { /* Nothing to do. */ }
template<typename FittingType>
template<typename OtherFittingType>
GMM<FittingType>& GMM<FittingType>::operator=(
const GMM<OtherFittingType>& other)
{
gaussians = other.Gaussians();
dimensionality = other.Dimensionality();
means = other.Means();
covariances = other.Covariances();
weights = other.Weights();
return *this;
}
template<typename FittingType>
GMM<FittingType>& GMM<FittingType>::operator=(const GMM<FittingType>& other)
{
gaussians = other.Gaussians();
dimensionality = other.Dimensionality();
means = other.Means();
covariances = other.Covariances();
weights = other.Weights();
localFitter = other.Fitter();
return *this;
}
// Load a GMM from file.
template<typename FittingType>
void GMM<FittingType>::Load(const std::string& filename)
{
util::SaveRestoreUtility load;
if (!load.ReadFile(filename))
Log::Fatal << "GMM::Load(): could not read file '" << filename << "'!\n";
load.LoadParameter(gaussians, "gaussians");
load.LoadParameter(dimensionality, "dimensionality");
load.LoadParameter(weights, "weights");
// We need to do a little error checking here.
if (weights.n_elem != gaussians)
{
Log::Fatal << "GMM::Load('" << filename << "'): file reports " << gaussians
<< " gaussians but weights vector only contains " << weights.n_elem
<< " elements!" << std::endl;
}
means.resize(gaussians);
covariances.resize(gaussians);
for (size_t i = 0; i < gaussians; ++i)
{
std::stringstream o;
o << i;
std::string meanName = "mean" + o.str();
std::string covName = "covariance" + o.str();
load.LoadParameter(means[i], meanName);
load.LoadParameter(covariances[i], covName);
}
}
// Save a GMM to a file.
template<typename FittingType>
void GMM<FittingType>::Save(const std::string& filename) const
{
util::SaveRestoreUtility save;
save.SaveParameter(gaussians, "gaussians");
save.SaveParameter(dimensionality, "dimensionality");
save.SaveParameter(weights, "weights");
for (size_t i = 0; i < gaussians; ++i)
{
// Generate names for the XML nodes.
std::stringstream o;
o << i;
std::string meanName = "mean" + o.str();
std::string covName = "covariance" + o.str();
// Now save them.
save.SaveParameter(means[i], meanName);
save.SaveParameter(covariances[i], covName);
}
if (!save.WriteFile(filename))
Log::Warn << "GMM::Save(): error saving to '" << filename << "'.\n";
}
/**
* Return the probability of the given observation being from this GMM.
*/
template<typename FittingType>
double GMM<FittingType>::Probability(const arma::vec& observation) const
{
// Sum the probability for each Gaussian in our mixture (and we have to
// multiply by the prior for each Gaussian too).
double sum = 0;
for (size_t i = 0; i < gaussians; i++)
sum += weights[i] * phi(observation, means[i], covariances[i]);
return sum;
}
/**
* Return the probability of the given observation being from the given
* component in the mixture.
*/
template<typename FittingType>
double GMM<FittingType>::Probability(const arma::vec& observation,
const size_t component) const
{
// We are only considering one Gaussian component -- so we only need to call
// phi() once. We do consider the prior probability!
return weights[component] *
phi(observation, means[component], covariances[component]);
}
/**
* Return a randomly generated observation according to the probability
* distribution defined by this object.
*/
template<typename FittingType>
arma::vec GMM<FittingType>::Random() const
{
// Determine which Gaussian it will be coming from.
double gaussRand = math::Random();
size_t gaussian;
double sumProb = 0;
for (size_t g = 0; g < gaussians; g++)
{
sumProb += weights(g);
if (gaussRand <= sumProb)
{
gaussian = g;
break;
}
}
return trans(chol(covariances[gaussian])) *
arma::randn<arma::vec>(dimensionality) + means[gaussian];
}
/**
* Fit the GMM to the given observations.
*/
template<typename FittingType>
double GMM<FittingType>::Estimate(const arma::mat& observations,
const size_t trials)
{
double bestLikelihood; // This will be reported later.
// We don't need to store temporary models if we are only doing one trial.
if (trials == 1)
{
// Train the model. The user will have been warned earlier if the GMM was
// initialized with no parameters (0 gaussians, dimensionality of 0).
fitter.Estimate(observations, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
}
else
{
if (trials == 0)
return -DBL_MAX; // It's what they asked for...
// We need to keep temporary copies. We'll do the first training into the
// actual model position, so that if it's the best we don't need to copy it.
fitter.Estimate(observations, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
Log::Info << "GMM::Estimate(): Log-likelihood of trial 0 is "
<< bestLikelihood << "." << std::endl;
// Now the temporary model.
std::vector<arma::vec> meansTrial(gaussians, arma::vec(dimensionality));
std::vector<arma::mat> covariancesTrial(gaussians,
arma::mat(dimensionality, dimensionality));
arma::vec weightsTrial(gaussians);
for (size_t trial = 1; trial < trials; ++trial)
{
fitter.Estimate(observations, meansTrial, covariancesTrial, weightsTrial);
// Check to see if the log-likelihood of this one is better.
double newLikelihood = LogLikelihood(observations, meansTrial,
covariancesTrial, weightsTrial);
Log::Info << "GMM::Estimate(): Log-likelihood of trial " << trial
<< " is " << newLikelihood << "." << std::endl;
if (newLikelihood > bestLikelihood)
{
// Save new likelihood and copy new model.
bestLikelihood = newLikelihood;
means = meansTrial;
covariances = covariancesTrial;
weights = weightsTrial;
}
}
}
// Report final log-likelihood and return it.
Log::Info << "GMM::Estimate(): log-likelihood of trained GMM is "
<< bestLikelihood << "." << std::endl;
return bestLikelihood;
}
/**
* Fit the GMM to the given observations, each of which has a certain
* probability of being from this distribution.
*/
template<typename FittingType>
double GMM<FittingType>::Estimate(const arma::mat& observations,
const arma::vec& probabilities,
const size_t trials)
{
double bestLikelihood; // This will be reported later.
// We don't need to store temporary models if we are only doing one trial.
if (trials == 1)
{
// Train the model. The user will have been warned earlier if the GMM was
// initialized with no parameters (0 gaussians, dimensionality of 0).
fitter.Estimate(observations, probabilities, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
}
else
{
if (trials == 0)
return -DBL_MAX; // It's what they asked for...
// We need to keep temporary copies. We'll do the first training into the
// actual model position, so that if it's the best we don't need to copy it.
fitter.Estimate(observations, probabilities, means, covariances, weights);
bestLikelihood = LogLikelihood(observations, means, covariances, weights);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial 0 is "
<< bestLikelihood << "." << std::endl;
// Now the temporary model.
std::vector<arma::vec> meansTrial(gaussians, arma::vec(dimensionality));
std::vector<arma::mat> covariancesTrial(gaussians,
arma::mat(dimensionality, dimensionality));
arma::vec weightsTrial(gaussians);
for (size_t trial = 1; trial < trials; ++trial)
{
fitter.Estimate(observations, meansTrial, covariancesTrial, weightsTrial);
// Check to see if the log-likelihood of this one is better.
double newLikelihood = LogLikelihood(observations, meansTrial,
covariancesTrial, weightsTrial);
Log::Debug << "GMM::Estimate(): Log-likelihood of trial " << trial
<< " is " << newLikelihood << "." << std::endl;
if (newLikelihood > bestLikelihood)
{
// Save new likelihood and copy new model.
bestLikelihood = newLikelihood;
means = meansTrial;
covariances = covariancesTrial;
weights = weightsTrial;
}
}
}
// Report final log-likelihood and return it.
Log::Info << "GMM::Estimate(): log-likelihood of trained GMM is "
<< bestLikelihood << "." << std::endl;
return bestLikelihood;
}
/**
* Classify the given observations as being from an individual component in this
* GMM.
*/
template<typename FittingType>
void GMM<FittingType>::Classify(const arma::mat& observations,
arma::Col<size_t>& labels) const
{
// This is not the best way to do this!
// We should not have to fill this with values, because each one should be
// overwritten.
labels.set_size(observations.n_cols);
for (size_t i = 0; i < observations.n_cols; ++i)
{
// Find maximum probability component.
double probability = 0;
for (size_t j = 0; j < gaussians; ++j)
{
double newProb = Probability(observations.unsafe_col(i), j);
if (newProb >= probability)
{
probability = newProb;
labels[i] = j;
}
}
}
}
/**
* Get the log-likelihood of this data's fit to the model.
*/
template<typename FittingType>
double GMM<FittingType>::LogLikelihood(
const arma::mat& data,
const std::vector<arma::vec>& meansL,
const std::vector<arma::mat>& covariancesL,
const arma::vec& weightsL) const
{
double loglikelihood = 0;
arma::vec phis;
arma::mat likelihoods(gaussians, data.n_cols);
for (size_t i = 0; i < gaussians; i++)
{
phi(data, meansL[i], covariancesL[i], phis);
likelihoods.row(i) = weightsL(i) * trans(phis);
}
// Now sum over every point.
for (size_t j = 0; j < data.n_cols; j++)
loglikelihood += log(accu(likelihoods.col(j)));
return loglikelihood;
}
}; // namespace gmm
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#ifndef BASEIO_HPP_
#define BASEIO_HPP_
/*
* Author: jrahm
* created: 2014/11/07
* BaseIO.hpp: <description>
*/
#include <types.h>
#include <cstdio>
namespace io {
/**
* @brief A simple class that can read, write and close.
*
* Basic I/O dascriptor. Can read, write and close.
*/
class BaseIO {
public:
/**
* @brief read data into a byte array
* @param out the buffer to read into
* @param len the lengthe of the buffer
*
* This function should read at most <code>len</code>
* bytes from the input source.
*
* @return the nuber of bytes read
*/
virtual ssize_t read( byte* out, size_t len ) = 0;
/**
* @brief write data to this I/O descriptor.
*
* @param in the data to write
* @param len the length of the data
*
* Write len bytes to the stream
*
* @return the number of bytes written
*/
virtual ssize_t write( const byte* in, size_t len ) = 0;
/**
* @brief close this I/O stream
*/
virtual int close() = 0;
inline virtual ~BaseIO(){}
};
}
#endif /* BASEIO_HPP_ */
<commit_msg>compile BaseIO on mips<commit_after>#ifndef BASEIO_HPP_
#define BASEIO_HPP_
/*
* Author: jrahm
* created: 2014/11/07
* BaseIO.hpp: <description>
*/
#include <Prelude>
#include <cstdio>
namespace io {
/**
* @brief A simple class that can read, write and close.
*
* Basic I/O dascriptor. Can read, write and close.
*/
class BaseIO {
public:
/**
* @brief read data into a byte array
* @param out the buffer to read into
* @param len the lengthe of the buffer
*
* This function should read at most <code>len</code>
* bytes from the input source.
*
* @return the nuber of bytes read
*/
virtual ssize_t read( byte* out, size_t len ) = 0;
/**
* @brief write data to this I/O descriptor.
*
* @param in the data to write
* @param len the length of the data
*
* Write len bytes to the stream
*
* @return the number of bytes written
*/
virtual ssize_t write( const byte* in, size_t len ) = 0;
/**
* @brief close this I/O stream
*/
virtual int close() = 0;
inline virtual ~BaseIO(){}
};
}
#endif /* BASEIO_HPP_ */
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <brick/httpclient/httpclient.h>
#include "account.h"
#include "httpclient/httpclient.h"
#include "include/base/cef_logging.h"
namespace {
const char fake_id = -1;
}
Account::Account() {
id_ = fake_id;
login_ = "";
password_ = "";
domain_ = "";
secure_ = true;
label_ = "";
base_url_ = "";
}
Account::~Account() {
}
bool
Account::IsExisted() {
return id_ != fake_id;
}
bool
Account::IsSecure() {
return secure_;
}
int
Account::GetId() {
return id_;
}
void
Account::SetId(int id) {
id_ = id;
}
std::string
Account::GetLogin() {
return login_;
}
std::string
Account::GetDomain() {
return domain_;
}
std::string
Account::GetPassword() {
/**
* ToDo: Нужно передалать работу с паролем на корню:
* 1. Хранить в памяти пароль как можно меньше времени
* 2. Занулять область памяти где хранился пароль после его использования
* 3. Сделать поддержку GNOME Keyring и KWallet. И только при их отсутствии самому хранить пароль
* 4. При самостоятельном хранении паролей их нужно чемнить зашифровать (libsodium?).
* 5. Ключ для шифрования/дешифрования должен каждый раз читаться из файла и следовать правилу из пунктов 1 и 2
**/
return password_;
}
std::string
Account::GetBaseUrl() {
return base_url_;
}
std::string
Account::GetLabel() {
return label_;
}
bool
Account::CheckBaseUrl(std::string url) {
return (url.find(base_url_) == 0);
}
std::string
Account::GenLabel() {
return (
domain_ + "/" + login_
);
}
void
Account::SetLogin(std::string login) {
login_ = login;
label_ = GenLabel();
}
void
Account::SetPassword(std::string password) {
password_ = password;
}
void
Account::SetDomain(std::string domain) {
domain_ = domain;
label_ = GenLabel();
base_url_ = GenBaseUrl();
}
void
Account::SetSecure(bool is_secure) {
secure_ = is_secure;
base_url_ = GenBaseUrl();
}
void
Account::Set(
bool secure,
std::string domain,
std::string login,
std::string password) {
secure_ = secure;
domain_ = domain;
login_ = login;
password_ = password;
label_ = GenLabel();
base_url_ = GenBaseUrl();
}
std::string
Account::GenBaseUrl() {
return (
(secure_ ? "https://" : "http://" )
+ domain_
+ "/desktop_app/" // ToDo: Need option here?
);
}
Account::AuthResult
Account::Auth(bool renew_password, std::string otp) {
AuthResult result;
HttpClient::form_map form;
// ToDo: use new authentication IM protocol
// form["json"] = "y"; // New versions of IM must return result in json format
if (renew_password) {
// New versions of IM must generate application password
form["renew_password"] = "y";
}
form["action"] = "login";
form["login"] = login_;
form["password"] = password_;
form["otp"] = otp;
form["user_os_mark"] = GetOsMark();
HttpClient::response r = HttpClient::PostForm(
base_url_ + "/login/", &form
);
if (r.code == 200) {
// Auth successful
if (r.body.find("success: true") != std::string::npos) {
// Maybe server returns application password?
std::string new_password = TryParseApplicationPassword(r.body);
if (password_ != new_password) {
LOG_IF(WARNING, !renew_password) << "Unexpected password update";
password_ = new_password;
}
result.success = true;
result.error_code = ERROR_CODE::NONE;
result.cookies = r.cookies;
} else {
// Probably application fatal occurred
result.success = false;
result.error_code = ERROR_CODE::UNKNOWN;
}
} else if (r.code == -1 ) {
// http query failed
LOG(WARNING) << "Auth failed (HTTP error): " << r.error;
result.success = false;
result.error_code = ERROR_CODE::HTTP;
result.http_error = r.error;
} else if (r.code == 401 ) {
// Auth failed
LOG(WARNING) << "Auth failed: " << r.body;
if (r.body.find("needOtp:") != std::string::npos) {
// ToDo: implement OTP authorization
result.error_code = ERROR_CODE::OTP;
} else if (r.body.find("captchaCode:") != std::string::npos) {
result.error_code = ERROR_CODE::CAPTCHA;
} else {
result.error_code = ERROR_CODE::AUTH;
}
result.success = false;
result.cookies = r.cookies;
} else if (r.code == 301 || r.code == 302 || r.code == 307) {
// Some error occurred...
LOG(WARNING) << "Auth failed (redirect occurred to url): " << r.headers["Location"];
result.error_code = ERROR_CODE::INVALID_URL;
result.success = false;
result.cookies = r.cookies;
result.http_error = "Redirect occurred: " + r.headers["Location"];
} else {
// Some error occurred...
LOG(WARNING) << "Auth failed (Application error): " << r.body;
result.error_code = ERROR_CODE::UNKNOWN;
result.success = false;
result.cookies = r.cookies;
}
return result;
}
std::string
Account::TryParseApplicationPassword(std::string body) {
std::string password;
size_t pos = body.find("appPassword: '");
if (pos == std::string::npos)
return password_;
pos += sizeof("appPassword: '");
password = body.substr(
pos - 1,
body.find("'", pos + 1) - pos + 1
);
return password;
}
std::string
Account::GetOsMark() {
// ToDo: use app_token!
char hostname[1024];
gethostname(hostname, 1024);
return std::string(hostname);
}<commit_msg>При ошибке авторизации связанной с редиректом - отдаем только origin, да бы не путать людей<commit_after>#include <unistd.h>
#include <brick/httpclient/httpclient.h>
#include <include/cef_url.h>
#include "account.h"
#include "httpclient/httpclient.h"
#include "include/base/cef_logging.h"
namespace {
const char fake_id = -1;
}
Account::Account() {
id_ = fake_id;
login_ = "";
password_ = "";
domain_ = "";
secure_ = true;
label_ = "";
base_url_ = "";
}
Account::~Account() {
}
bool
Account::IsExisted() {
return id_ != fake_id;
}
bool
Account::IsSecure() {
return secure_;
}
int
Account::GetId() {
return id_;
}
void
Account::SetId(int id) {
id_ = id;
}
std::string
Account::GetLogin() {
return login_;
}
std::string
Account::GetDomain() {
return domain_;
}
std::string
Account::GetPassword() {
/**
* ToDo: Нужно передалать работу с паролем на корню:
* 1. Хранить в памяти пароль как можно меньше времени
* 2. Занулять область памяти где хранился пароль после его использования
* 3. Сделать поддержку GNOME Keyring и KWallet. И только при их отсутствии самому хранить пароль
* 4. При самостоятельном хранении паролей их нужно чемнить зашифровать (libsodium?).
* 5. Ключ для шифрования/дешифрования должен каждый раз читаться из файла и следовать правилу из пунктов 1 и 2
**/
return password_;
}
std::string
Account::GetBaseUrl() {
return base_url_;
}
std::string
Account::GetLabel() {
return label_;
}
bool
Account::CheckBaseUrl(std::string url) {
return (url.find(base_url_) == 0);
}
std::string
Account::GenLabel() {
return (
domain_ + "/" + login_
);
}
void
Account::SetLogin(std::string login) {
login_ = login;
label_ = GenLabel();
}
void
Account::SetPassword(std::string password) {
password_ = password;
}
void
Account::SetDomain(std::string domain) {
domain_ = domain;
label_ = GenLabel();
base_url_ = GenBaseUrl();
}
void
Account::SetSecure(bool is_secure) {
secure_ = is_secure;
base_url_ = GenBaseUrl();
}
void
Account::Set(
bool secure,
std::string domain,
std::string login,
std::string password) {
secure_ = secure;
domain_ = domain;
login_ = login;
password_ = password;
label_ = GenLabel();
base_url_ = GenBaseUrl();
}
std::string
Account::GenBaseUrl() {
return (
(secure_ ? "https://" : "http://" )
+ domain_
+ "/desktop_app/" // ToDo: Need option here?
);
}
Account::AuthResult
Account::Auth(bool renew_password, std::string otp) {
AuthResult result;
HttpClient::form_map form;
// ToDo: use new authentication IM protocol
// form["json"] = "y"; // New versions of IM must return result in json format
if (renew_password) {
// New versions of IM must generate application password
form["renew_password"] = "y";
}
form["action"] = "login";
form["login"] = login_;
form["password"] = password_;
form["otp"] = otp;
form["user_os_mark"] = GetOsMark();
HttpClient::response r = HttpClient::PostForm(
base_url_ + "/login/", &form
);
if (r.code == 200) {
// Auth successful
if (r.body.find("success: true") != std::string::npos) {
// Maybe server returns application password?
std::string new_password = TryParseApplicationPassword(r.body);
if (password_ != new_password) {
LOG_IF(WARNING, !renew_password) << "Unexpected password update";
password_ = new_password;
}
result.success = true;
result.error_code = ERROR_CODE::NONE;
result.cookies = r.cookies;
} else {
// Probably application fatal occurred
result.success = false;
result.error_code = ERROR_CODE::UNKNOWN;
}
} else if (r.code == -1 ) {
// http query failed
LOG(WARNING) << "Auth failed (HTTP error): " << r.error;
result.success = false;
result.error_code = ERROR_CODE::HTTP;
result.http_error = r.error;
} else if (r.code == 401 ) {
// Auth failed
LOG(WARNING) << "Auth failed: " << r.body;
if (r.body.find("needOtp:") != std::string::npos) {
// ToDo: implement OTP authorization
result.error_code = ERROR_CODE::OTP;
} else if (r.body.find("captchaCode:") != std::string::npos) {
result.error_code = ERROR_CODE::CAPTCHA;
} else {
result.error_code = ERROR_CODE::AUTH;
}
result.success = false;
result.cookies = r.cookies;
} else if (r.code == 301 || r.code == 302 || r.code == 307) {
// Some error occurred...
LOG(WARNING) << "Auth failed (redirect occurred to url): " << r.headers["Location"];
result.error_code = ERROR_CODE::INVALID_URL;
result.success = false;
result.cookies = r.cookies;
result.http_error = "Redirect occurred: ";
CefURLParts redirect_parts;
if (CefParseURL(r.headers["Location"], redirect_parts)) {
result.http_error += CefString(&redirect_parts.origin);
}
} else {
// Some error occurred...
LOG(WARNING) << "Auth failed (Application error): " << r.body;
result.error_code = ERROR_CODE::UNKNOWN;
result.success = false;
result.cookies = r.cookies;
}
return result;
}
std::string
Account::TryParseApplicationPassword(std::string body) {
std::string password;
size_t pos = body.find("appPassword: '");
if (pos == std::string::npos)
return password_;
pos += sizeof("appPassword: '");
password = body.substr(
pos - 1,
body.find("'", pos + 1) - pos + 1
);
return password;
}
std::string
Account::GetOsMark() {
// ToDo: use app_token!
char hostname[1024];
gethostname(hostname, 1024);
return std::string(hostname);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 1999-2003 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#ifdef HAVE_CVS_IDENT
#ident "$Id: verireal.cc,v 1.12 2003/03/05 02:36:05 steve Exp $"
#endif
# include "config.h"
# include "verireal.h"
# include "verinum.h"
# include <ctype.h>
# include <iostream>
# include <math.h>
# include <assert.h>
# include <stdio.h>
verireal::verireal()
{
value_ = 0.0;
}
verireal::verireal(const char*txt)
{
char*buf = new char[strlen(txt)+1];
char*cp = buf;
/* filter out Verilog-isms */
for (unsigned i = 0; txt[i]; i += 1) {
if (txt[i] == '_') { continue; }
*cp = txt[i]; cp++;
}
*cp = '\0';
if (sscanf(buf, "%lf", &value_) != 1) {
fprintf(stderr, "PANIC: Unable to sscanf(%s)\n", txt);
assert(0);
}
delete[]buf;
}
verireal::verireal(long val)
{
value_ = (double)val;
}
verireal::~verireal()
{
}
long verireal::as_long(int shift) const
{
double out = value_ * pow(10.0,shift);
double outf;
if (out >= 0.0) {
outf = floor(out);
if (out >= (outf + 0.5))
outf += 1.0;
} else {
outf = ceil(out);
if (out <= (outf - 0.5))
outf -= 1.0;
}
return (long) outf;
}
double verireal::as_double() const
{
return value_;
}
verireal operator* (const verireal&l, const verireal&r)
{
verireal res;
res.value_ = l.value_ * r.value_;
return res;
}
verireal operator/ (const verireal&l, const verireal&r)
{
verireal res;
res.value_ = l.value_ / r.value_;
return res;
}
verireal operator/ (const verireal&l, const verinum&r)
{
verireal res;
res.value_ = l.value_ / (double)r.as_long();
return res;
}
verireal operator% (const verireal&l, const verireal&r)
{
verireal res;
assert(0);
return res;
}
verireal operator% (const verireal&l, const verinum&r)
{
verireal res;
assert(0);
return res;
}
ostream& operator<< (ostream&out, const verireal&v)
{
out << v.value_;
return out;
}
/*
* $Log: verireal.cc,v $
* Revision 1.12 2003/03/05 02:36:05 steve
* Use sscanf to make doubles from strings.
*
* Revision 1.11 2003/02/07 06:13:44 steve
* Store real values as native double.
*
* Revision 1.10 2003/02/07 02:48:43 steve
* NetEBDiv handles real value constant expressions.
*
* Revision 1.9 2003/01/26 21:15:59 steve
* Rework expression parsing and elaboration to
* accommodate real/realtime values and expressions.
*
* Revision 1.8 2002/08/12 01:35:01 steve
* conditional ident string using autoconfig.
*
* Revision 1.7 2002/06/15 02:35:49 steve
* Rounding error.
*
* Revision 1.6 2001/11/06 06:11:55 steve
* Support more real arithmetic in delay constants.
*
* Revision 1.5 2001/07/25 03:10:50 steve
* Create a config.h.in file to hold all the config
* junk, and support gcc 3.0. (Stephan Boettcher)
*
* Revision 1.4 2001/07/07 20:20:10 steve
* Pass parameters to system functions.
*
* Revision 1.3 2000/12/10 22:01:36 steve
* Support decimal constants in behavioral delays.
*
* Revision 1.2 2000/02/23 02:56:56 steve
* Macintosh compilers do not support ident.
*
* Revision 1.1 1999/06/15 02:50:02 steve
* Add lexical support for real numbers.
*
*/
<commit_msg> Restore verireal constructor to match vvp processing of reals.<commit_after>/*
* Copyright (c) 1999 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#ifdef HAVE_CVS_IDENT
#ident "$Id: verireal.cc,v 1.13 2003/03/05 03:45:01 steve Exp $"
#endif
# include "config.h"
# include "verireal.h"
# include "verinum.h"
# include <ctype.h>
# include <iostream>
# include <math.h>
# include <assert.h>
verireal::verireal()
{
value_ = 0.0;
}
verireal::verireal(const char*txt)
{
unsigned long long mant = 0;
bool sign = false;
signed int exp10 = 0;
const char*ptr = txt;
for ( ; *ptr ; ptr += 1) {
if (*ptr == '.') break;
if (*ptr == 'e') break;
if (*ptr == 'E') break;
if (*ptr == '_') continue;
assert(isdigit(*ptr));
mant *= 10;
mant += *ptr - '0';
}
if (*ptr == '.') {
ptr += 1;
for ( ; *ptr ; ptr += 1) {
if (*ptr == 'e') break;
if (*ptr == 'E') break;
if (*ptr == '_') continue;
assert(isdigit(*ptr));
mant *= 10;
mant += *ptr - '0';
exp10 -= 1;
}
}
if ((*ptr == 'e') || (*ptr == 'E')) {
ptr += 1;
long tmp = 0;
bool sflag = false;
if (*ptr == '+') {ptr += 1; sflag = false;}
if (*ptr == '-') {ptr += 1; sflag = true;}
for ( ; *ptr ; ptr += 1) {
if (*ptr == '_') continue;
assert(isdigit(*ptr));
tmp *= 10;
tmp += *ptr - '0';
}
exp10 += sflag? -tmp : +tmp;
}
assert(*ptr == 0);
value_ = pow(10.0,exp10) * mant * (sign? -1.0 : 1.0);
}
verireal::verireal(long val)
{
value_ = (double)val;
}
verireal::~verireal()
{
}
long verireal::as_long(int shift) const
{
double out = value_ * pow(10.0,shift);
double outf;
if (out >= 0.0) {
outf = floor(out);
if (out >= (outf + 0.5))
outf += 1.0;
} else {
outf = ceil(out);
if (out <= (outf - 0.5))
outf -= 1.0;
}
return (long) outf;
}
double verireal::as_double() const
{
return value_;
}
verireal operator* (const verireal&l, const verireal&r)
{
verireal res;
res.value_ = l.value_ * r.value_;
return res;
}
verireal operator/ (const verireal&l, const verireal&r)
{
verireal res;
res.value_ = l.value_ / r.value_;
return res;
}
verireal operator/ (const verireal&l, const verinum&r)
{
verireal res;
res.value_ = l.value_ / (double)r.as_long();
return res;
}
verireal operator% (const verireal&l, const verireal&r)
{
verireal res;
assert(0);
return res;
}
verireal operator% (const verireal&l, const verinum&r)
{
verireal res;
assert(0);
return res;
}
ostream& operator<< (ostream&out, const verireal&v)
{
out << v.value_;
return out;
}
/*
* $Log: verireal.cc,v $
* Revision 1.13 2003/03/05 03:45:01 steve
* Restore verireal constructor to match vvp processing of reals.
*
* Revision 1.11 2003/02/07 06:13:44 steve
* Store real values as native double.
*
* Revision 1.10 2003/02/07 02:48:43 steve
* NetEBDiv handles real value constant expressions.
*
* Revision 1.9 2003/01/26 21:15:59 steve
* Rework expression parsing and elaboration to
* accommodate real/realtime values and expressions.
*
* Revision 1.8 2002/08/12 01:35:01 steve
* conditional ident string using autoconfig.
*
* Revision 1.7 2002/06/15 02:35:49 steve
* Rounding error.
*
* Revision 1.6 2001/11/06 06:11:55 steve
* Support more real arithmetic in delay constants.
*
* Revision 1.5 2001/07/25 03:10:50 steve
* Create a config.h.in file to hold all the config
* junk, and support gcc 3.0. (Stephan Boettcher)
*
* Revision 1.4 2001/07/07 20:20:10 steve
* Pass parameters to system functions.
*
* Revision 1.3 2000/12/10 22:01:36 steve
* Support decimal constants in behavioral delays.
*
* Revision 1.2 2000/02/23 02:56:56 steve
* Macintosh compilers do not support ident.
*
* Revision 1.1 1999/06/15 02:50:02 steve
* Add lexical support for real numbers.
*
*/
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cgo/montecarlo/montecarlo_agent.hpp>
using namespace cgo::base;
using namespace cgo::standardin;
MonteCarloAgent::MonteCarloAgent(Marker marker) :
Agent(marker)
{}
/* virtual */ MonteCarloAgent::~MonteCarloAgent() {}
Move MonteCarloAgent::makeMove(State& state,
const boost::optional< std::tuple< Move, State > >& predecessor) {
Position position(-1, -1);
do {
std::cout << "Enter a move: <row> <col> or (p)ass: ";
std::string move;
do {
std::getline(std::cin, move);
} while (move.size() == 0);
if (move == "p" || move == "pass") {
return Pass();
}
int row, col;
std::stringstream ss(move);
ss >> row >> col;
position = Position(row - 1, col - 1);
} while (!state.isActionValid(Action(this->_marker, position), predecessor));
return Action(this->_marker, position);
}
<commit_msg>updating montecarlo<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cgo/montecarlo/montecarlo_agent.hpp>
using namespace cgo::base;
using namespace cgo::standardin;
MonteCarloAgent::MonteCarloAgent(Marker marker) :
Agent(marker)
{}
/* virtual */ MonteCarloAgent::~MonteCarloAgent() {}
int MonteCarloAgent::CalculateBest(Position position) {
}
Move MonteCarloAgent::makeMove(State& state,
const boost::optional< std::tuple< Move, State > >& predecessor) {
Position position(-1, -1);
// do {
// std::cout << "Enter a move: <row> <col> or (p)ass: ";
// std::string move;
// do {
// std::getline(std::cin, move);
// } while (move.size() == 0);
// if (move == "p" || move == "pass") {
// return Pass();
// }
// int row, col;
// std::stringstream ss(move);
// ss >> row >> col;
// position = Position(row - 1, col - 1);
// } while (!state.isActionValid(Action(this->_marker, position), predecessor));
return Action(this->_marker, position);
}
<|endoftext|> |
<commit_before>#include <d3d11.h>
#include <memory>
#include <ting/Exc.hpp>
#include <ting/Void.hpp>
#include <ting/PoolStored.hpp>
#include <ting/Buffer.hpp>
#include "../Exc.hpp"
#include "../App.hpp"
using namespace morda;
namespace {
struct Direct3DContext : public ting::Void {
IDXGISwapChain *swapchain;
ID3D11Device *dev;
ID3D11DeviceContext *ctx;
ID3D11RenderTargetView *renderTarget;
Direct3DContext(HWND hwnd) {
HRESULT result;
// create a struct to hold information about the swap chain
DXGI_SWAP_CHAIN_DESC scd;
// clear out the struct for use
ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
// fill the swap chain description struct
scd.BufferCount = 1; // one back buffer
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
scd.OutputWindow = hwnd; // the window to be used
scd.SampleDesc.Count = 4; // how many multisamples
scd.Windowed = TRUE; // windowed/full-screen mode
// create a device, device context and swap chain using the information in the scd struct
result = D3D11CreateDeviceAndSwapChain(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&scd,
&this->swapchain,
&this->dev,
NULL,
&this->ctx);
if (FAILED(result)) {
throw morda::Exc("Direct3D init: creating device failed");
}
// get the address of the back buffer
ID3D11Texture2D *pBackBuffer;
result = swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(result)) {
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
throw morda::Exc("Direct3D init: creating device failed");
}
// use the back buffer address to create the render target
result = dev->CreateRenderTargetView(pBackBuffer, NULL, &this->renderTarget);
pBackBuffer->Release();
if (FAILED(result)) {
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
throw morda::Exc("Direct3D init: creating render target failed");
}
// set the render target as the back buffer
this->ctx->OMSetRenderTargets(1, &this->renderTarget, NULL);
}
~Direct3DContext()noexcept {
this->renderTarget->Release();
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
}
morda::Vec4f curClearColor;
} *d3dCtx;
//GLenum modeMap[] = {
// GL_TRIANGLES, //TRIANGLES
// GL_TRIANGLE_FAN, //TRIANGLE_FAN
// GL_LINE_LOOP //LINE_LOOP
//};
}//~namespace
void Render::renderArrays(EMode mode, unsigned numElements) {
//TODO:
}
void Render::renderElements(EMode mode, const ting::Buffer<const std::uint16_t>& i) {
//TODO:
}
void Render::bindShader(ting::Void& p) {
//TODO:
}
std::unique_ptr<ting::Void> Render::compileShader(const char* vertexShaderCode, const char* fragmentShaderCode) {
//TODO:
return nullptr;
}
Render::InputID Render::getAttribute(ting::Void& p, const char* n) {
//TODO:
return InputID(0);
}
Render::InputID Render::getUniform(ting::Void& p, const char* n) {
//TODO:
return InputID(0);
}
void Render::setUniformMatrix4f(InputID id, const Matr4f& m) {
//TODO:
}
void Render::setUniform1i(InputID id, int i) {
//TODO:
}
void Render::setUniform2f(InputID id, Vec2f v) {
//TODO:
}
void Render::setUniform4f(InputID id, float x, float y, float z, float a) {
//TODO:
}
void Render::setUniform4f(InputID id, ting::Buffer<const Vec4f> v) {
//TODO:
}
void Render::setVertexAttribArray(InputID id, const Vec3f* a) {
//TODO:
}
void Render::setVertexAttribArray(InputID id, const Vec2f* a) {
//TODO:
}
void Render::setViewport(Rect2i r){
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = FLOAT(r.p.x);
viewport.TopLeftY = FLOAT(r.p.y);
viewport.Width = FLOAT(r.d.x);
viewport.Height = FLOAT(r.d.y);
d3dCtx->ctx->RSSetViewports(1, &viewport);
}
void Render::setClearColor(Vec4f c){
d3dCtx->curClearColor = c;
}
Render::Render(){
d3dCtx = new Direct3DContext(morda::App::Inst().window.hwnd);
this->pimpl.reset(d3dCtx);
}
Render::~Render()noexcept{
}
void Render::clear(EBuffer b) {
/*
GLbitfield bf = 0;
switch(b){
default:
case EBuffer::COLOR:
bf = GL_COLOR_BUFFER_BIT;
break;
case EBuffer::DEPTH:
bf = GL_DEPTH_BUFFER_BIT;
break;
case EBuffer::ACCUM:
bf = GL_ACCUM_BUFFER_BIT;
break;
case EBuffer::STENCIL:
bf = GL_STENCIL_BUFFER_BIT;
break;
}*/
//TODO: clear depth and other buffers
FLOAT clr[4] = {
d3dCtx->curClearColor.x,
d3dCtx->curClearColor.y,
d3dCtx->curClearColor.z,
d3dCtx->curClearColor.w
};
d3dCtx->ctx->ClearRenderTargetView(d3dCtx->renderTarget, clr);
}
bool Render::isScissorEnabled() {
//TODO:
return false;
}
Rect2i Render::getScissorRect() {
//TODO:
return Rect2i(0);
}
void Render::setScissorEnabled(bool enabled) {
//TODO:
}
void Render::setScissorRect(Rect2i r) {
//TODO:
}
namespace{
/*
GLint texFilterMap[] = {
GL_NEAREST,
GL_LINEAR
};
*/
/*
struct GLTexture2D : public ting::Void, public ting::PoolStored<GLTexture2D, 32>{
GLuint tex;
GLTexture2D(){
glGenTextures(1, &this->tex);
AssertOpenGLNoError();
ASSERT(this->tex != 0)
}
virtual ~GLTexture2D()noexcept{
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(1, &this->tex);
}
void bind(unsigned unitNum){
glActiveTexture(GL_TEXTURE0 + unitNum);
AssertOpenGLNoError();
glBindTexture(GL_TEXTURE_2D, this->tex);
AssertOpenGLNoError();
}
};*/
}//~namespace
std::unique_ptr<ting::Void> Render::create2DTexture(Vec2ui dim, unsigned numChannels, ting::Buffer<const std::uint8_t> data, ETexFilter minFilter, ETexFilter magFilter){
/*
ASSERT(data.size() == 0 || data.size() >= dim.x * dim.y * numChannels)
GLint minFilterGL = texFilterMap[unsigned(minFilter)];
GLint magFilterGL = texFilterMap[unsigned(magFilter)];
std::unique_ptr<GLTexture2D> ret(new GLTexture2D());
ret->bind(0);
GLint internalFormat;
switch(numChannels){
default:
ASSERT(false)
case 1:
internalFormat = GL_LUMINANCE;
break;
case 2:
internalFormat = GL_LUMINANCE_ALPHA;
break;
case 3:
internalFormat = GL_RGB;
break;
case 4:
internalFormat = GL_RGBA;
break;
}
//we will be passing pixels to OpenGL which are 1-byte aligned.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
AssertOpenGLNoError();
glTexImage2D(
GL_TEXTURE_2D,
0,//0th level, no mipmaps
internalFormat, //internal format
dim.x,
dim.y,
0,//border, should be 0!
internalFormat, //format of the texel data
GL_UNSIGNED_BYTE,
&*data.begin()
);
AssertOpenGLNoError();
//NOTE: on OpenGL ES 2 it is necessary to set the filter parameters
// for every texture!!! Otherwise it may not work!
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilterGL);
AssertOpenGLNoError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilterGL);
AssertOpenGLNoError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return std::move(ret);
*/
//TODO:
return nullptr;
}
void Render::bindTexture(ting::Void& tex, unsigned unitNum){
//TODO:
}
void Render::copyColorBufferToTexture(Vec2i dst, Rect2i src){
//TODO:
}
unsigned Render::getMaxTextureSize(){
//TODO:
return 1024;
}
void Render::swapFrameBuffers() {
static_cast<Direct3DContext*>(morda::App::Inst().renderer.pimpl.get())->swapchain->Present(0, 0);
}<commit_msg>stuff<commit_after>#include <d3d11.h>
#include <memory>
#include <ting/Exc.hpp>
#include <ting/Void.hpp>
#include <ting/PoolStored.hpp>
#include <ting/Buffer.hpp>
#include "../Exc.hpp"
#include "../App.hpp"
using namespace morda;
namespace {
struct Direct3DContext : public ting::Void {
IDXGISwapChain *swapchain;
ID3D11Device *dev;
ID3D11DeviceContext *ctx;
ID3D11RenderTargetView *renderTarget;
Direct3DContext(HWND hwnd) {
HRESULT result;
// create a struct to hold information about the swap chain
DXGI_SWAP_CHAIN_DESC scd;
// clear out the struct for use
ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
// fill the swap chain description struct
scd.BufferCount = 1; // one back buffer
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
scd.OutputWindow = hwnd; // the window to be used
scd.SampleDesc.Count = 4; // how many multisamples
scd.Windowed = TRUE; // windowed/full-screen mode
// create a device, device context and swap chain using the information in the scd struct
result = D3D11CreateDeviceAndSwapChain(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&scd,
&this->swapchain,
&this->dev,
NULL,
&this->ctx);
if (FAILED(result)) {
throw morda::Exc("Direct3D init: creating device failed");
}
// get the address of the back buffer
ID3D11Texture2D *pBackBuffer;
result = swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(result)) {
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
throw morda::Exc("Direct3D init: creating device failed");
}
// use the back buffer address to create the render target
result = dev->CreateRenderTargetView(pBackBuffer, NULL, &this->renderTarget);
pBackBuffer->Release();
if (FAILED(result)) {
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
throw morda::Exc("Direct3D init: creating render target failed");
}
// set the render target as the back buffer
this->ctx->OMSetRenderTargets(1, &this->renderTarget, NULL);
}
~Direct3DContext()noexcept {
this->renderTarget->Release();
this->swapchain->Release();
this->dev->Release();
this->ctx->Release();
}
morda::Vec4f curClearColor;
} *d3dCtx;
//GLenum modeMap[] = {
// GL_TRIANGLES, //TRIANGLES
// GL_TRIANGLE_FAN, //TRIANGLE_FAN
// GL_LINE_LOOP //LINE_LOOP
//};
}//~namespace
void Render::renderArrays(EMode mode, unsigned numElements) {
//TODO:
}
void Render::renderElements(EMode mode, const ting::Buffer<const std::uint16_t>& i) {
//TODO:
}
void Render::bindShader(ting::Void& p) {
//TODO:
}
std::unique_ptr<ting::Void> Render::compileShader(const char* vertexShaderCode, const char* fragmentShaderCode) {
//TODO:
return nullptr;
}
Render::InputID Render::getAttribute(ting::Void& p, const char* n) {
//TODO:
return InputID(0);
}
Render::InputID Render::getUniform(ting::Void& p, const char* n) {
//TODO:
return InputID(0);
}
void Render::setUniformMatrix4f(InputID id, const Matr4f& m) {
//TODO:
}
void Render::setUniform1i(InputID id, int i) {
//TODO:
}
void Render::setUniform2f(InputID id, Vec2f v) {
//TODO:
}
void Render::setUniform4f(InputID id, float x, float y, float z, float a) {
//TODO:
}
void Render::setUniform4f(InputID id, ting::Buffer<const Vec4f> v) {
//TODO:
}
void Render::setVertexAttribArray(InputID id, const Vec3f* a) {
//TODO:
}
void Render::setVertexAttribArray(InputID id, const Vec2f* a) {
//TODO:
}
void Render::setViewport(Rect2i r){
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = FLOAT(r.p.x);
viewport.TopLeftY = FLOAT(r.p.y);
viewport.Width = FLOAT(r.d.x);
viewport.Height = FLOAT(r.d.y);
d3dCtx->ctx->RSSetViewports(1, &viewport);
}
void Render::setClearColor(Vec4f c){
d3dCtx->curClearColor = c;
}
Render::Render(){
d3dCtx = new Direct3DContext(morda::App::Inst().window.hwnd);
this->pimpl.reset(d3dCtx);
}
Render::~Render()noexcept{
}
void Render::clear(EBuffer b) {
/*
GLbitfield bf = 0;
switch(b){
default:
case EBuffer::COLOR:
bf = GL_COLOR_BUFFER_BIT;
break;
case EBuffer::DEPTH:
bf = GL_DEPTH_BUFFER_BIT;
break;
case EBuffer::ACCUM:
bf = GL_ACCUM_BUFFER_BIT;
break;
case EBuffer::STENCIL:
bf = GL_STENCIL_BUFFER_BIT;
break;
}*/
//TODO: clear depth and other buffers
FLOAT clr[4] = {
d3dCtx->curClearColor.x,
d3dCtx->curClearColor.y,
d3dCtx->curClearColor.z,
d3dCtx->curClearColor.w
};
d3dCtx->ctx->ClearRenderTargetView(d3dCtx->renderTarget, clr);
}
bool Render::isScissorEnabled() {
//TODO:
return false;
}
Rect2i Render::getScissorRect() {
//TODO:
return Rect2i(0);
}
void Render::setScissorEnabled(bool enabled) {
//TODO:
}
void Render::setScissorRect(Rect2i r) {
//TODO:
}
namespace{
/*
GLint texFilterMap[] = {
GL_NEAREST,
GL_LINEAR
};
*/
/*
struct GLTexture2D : public ting::Void, public ting::PoolStored<GLTexture2D, 32>{
GLuint tex;
GLTexture2D(){
glGenTextures(1, &this->tex);
AssertOpenGLNoError();
ASSERT(this->tex != 0)
}
virtual ~GLTexture2D()noexcept{
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(1, &this->tex);
}
void bind(unsigned unitNum){
glActiveTexture(GL_TEXTURE0 + unitNum);
AssertOpenGLNoError();
glBindTexture(GL_TEXTURE_2D, this->tex);
AssertOpenGLNoError();
}
};*/
}//~namespace
std::unique_ptr<ting::Void> Render::create2DTexture(Vec2ui dim, unsigned numChannels, ting::Buffer<const std::uint8_t> data, ETexFilter minFilter, ETexFilter magFilter){
/*
ASSERT(data.size() == 0 || data.size() >= dim.x * dim.y * numChannels)
GLint minFilterGL = texFilterMap[unsigned(minFilter)];
GLint magFilterGL = texFilterMap[unsigned(magFilter)];
std::unique_ptr<GLTexture2D> ret(new GLTexture2D());
ret->bind(0);
GLint internalFormat;
switch(numChannels){
default:
ASSERT(false)
case 1:
internalFormat = GL_LUMINANCE;
break;
case 2:
internalFormat = GL_LUMINANCE_ALPHA;
break;
case 3:
internalFormat = GL_RGB;
break;
case 4:
internalFormat = GL_RGBA;
break;
}
//we will be passing pixels to OpenGL which are 1-byte aligned.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
AssertOpenGLNoError();
glTexImage2D(
GL_TEXTURE_2D,
0,//0th level, no mipmaps
internalFormat, //internal format
dim.x,
dim.y,
0,//border, should be 0!
internalFormat, //format of the texel data
GL_UNSIGNED_BYTE,
&*data.begin()
);
AssertOpenGLNoError();
//NOTE: on OpenGL ES 2 it is necessary to set the filter parameters
// for every texture!!! Otherwise it may not work!
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilterGL);
AssertOpenGLNoError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilterGL);
AssertOpenGLNoError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return std::move(ret);
*/
//TODO:
return nullptr;
}
void Render::bindTexture(ting::Void& tex, unsigned unitNum){
//TODO:
}
void Render::copyColorBufferToTexture(Vec2i dst, Rect2i src){
//TODO:
}
unsigned Render::getMaxTextureSize(){
//TODO:
return 1024;
}
void Render::swapFrameBuffers() {
static_cast<Direct3DContext*>(morda::App::Inst().renderer.pimpl.get())->swapchain->Present(0, 0);
}<|endoftext|> |
<commit_before>/*
* PixelBufferCarbon.cpp
* OpenSceneGraph
*
* Created by Stephan Huber on 27.06.07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifdef __APPLE__
#include <osg/observer_ptr>
#include <osgViewer/api/Carbon/PixelBufferCarbon>
#include <osgViewer/api/Carbon/GraphicsWindowCarbon>
#include <Carbon/Carbon.h>
#include <OpenGL/OpenGL.h>
using namespace osgViewer;
/** creates a pixelformat from a Trait */
AGLPixelFormat PixelBufferCarbon::createPixelFormat(osg::GraphicsContext::Traits* traits) {
std::vector<GLint> attributes;
attributes.push_back(AGL_NO_RECOVERY);
attributes.push_back(AGL_RGBA);
if (!traits->pbuffer)
attributes.push_back(AGL_COMPLIANT);
else
attributes.push_back(AGL_CLOSEST_POLICY);
if (traits->doubleBuffer) attributes.push_back(AGL_DOUBLEBUFFER);
if (traits->quadBufferStereo) attributes.push_back(AGL_STEREO);
attributes.push_back(AGL_RED_SIZE); attributes.push_back(traits->red);
attributes.push_back(AGL_GREEN_SIZE); attributes.push_back(traits->green);
attributes.push_back(AGL_BLUE_SIZE); attributes.push_back(traits->blue);
attributes.push_back(AGL_DEPTH_SIZE); attributes.push_back(traits->depth);
if (traits->alpha) { attributes.push_back(AGL_ALPHA_SIZE); attributes.push_back(traits->alpha); }
if (traits->stencil) { attributes.push_back(AGL_STENCIL_SIZE); attributes.push_back(traits->stencil); }
// TODO
// missing accumulation-buffer-stuff
#if defined(AGL_SAMPLE_BUFFERS_ARB) && defined (AGL_SAMPLES_ARB)
if (traits->sampleBuffers) { attributes.push_back(AGL_SAMPLE_BUFFERS_ARB); attributes.push_back(traits->sampleBuffers); }
if (traits->sampleBuffers) { attributes.push_back(AGL_SAMPLES_ARB); attributes.push_back(traits->samples); }
#endif
attributes.push_back(AGL_NONE);
return aglChoosePixelFormat(NULL, 0, &(attributes.front()));
}
void PixelBufferCarbon::init()
{
_context = NULL;
_pixelformat = PixelBufferCarbon::createPixelFormat(_traits.get());
if (!_pixelformat)
osg::notify(osg::WARN) << "PixelBufferCarbon::init could not create a valid pixelformat" << std::endl;
_valid = (_pixelformat != NULL);
}
/** This is the class we need to create for pbuffers, note its not a GraphicsWindow as it won't need any of the event handling and window mapping facilities.*/
/** Realise the GraphicsContext implementation,
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::realizeImplementation()
{
if (!_valid) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglChoosePixelFormat failed! " << aglErrorString(aglGetError()) << std::endl;
return false;
}
AGLContext sharedContext = NULL;
// get any shared GLX contexts
GraphicsWindowCarbon* graphicsWindowCarbon = dynamic_cast<GraphicsWindowCarbon*>(_traits->sharedContext);
if (graphicsWindowCarbon)
{
sharedContext = graphicsWindowCarbon->getAGLContext();
}
else
{
PixelBufferCarbon* pixelBufferCarbon = dynamic_cast<PixelBufferCarbon*>(_traits->sharedContext);
if (pixelBufferCarbon)
{
sharedContext = pixelBufferCarbon->getAGLContext();
}
}
_context = aglCreateContext (_pixelformat, sharedContext);
if (!_context) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglCreateContext failed! " << aglErrorString(aglGetError()) << std::endl;
return false;
}
_realized = aglCreatePBuffer (_traits->width, _traits->height, _traits->target, GL_RGBA, _traits->level, &(_pbuffer));
if (!_realized) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglCreatePBuffer failed! " << aglErrorString(aglGetError()) << std::endl;
}
makeCurrentImplementation();
_realized = aglSetPBuffer(_context, _pbuffer, _traits->face, _traits->level, 0);
if (!_realized) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglSetPBuffer failed! " << aglErrorString(aglGetError()) << std::endl;
}
return _realized;
}
void PixelBufferCarbon::closeImplementation()
{
if (_pbuffer) aglDestroyPBuffer(_pbuffer);
if (_context) aglDestroyContext(_context);
if (_pixelformat) aglDestroyPixelFormat(_pixelformat);
_valid = _realized = false;
}
/** Make this graphics context current implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::makeCurrentImplementation()
{
return (_realized) ? (aglSetCurrentContext(_context) == GL_TRUE) : false;
}
/** Make this graphics context current with specified read context implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::makeContextCurrentImplementation(GraphicsContext* /*readContext*/) {
return makeCurrentImplementation();
}
/** Release the graphics context.*/
bool PixelBufferCarbon::releaseContextImplementation()
{
return (aglSetCurrentContext(NULL) == GL_TRUE);
}
/** Pure virtual, Bind the graphics context to associated texture implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
void PixelBufferCarbon::bindPBufferToTextureImplementation( GLenum buffer ){
osg::notify(osg::NOTICE)<<"GraphicsWindow::void bindPBufferToTextureImplementation(..) not implemented."<<std::endl;
}
/** Swap the front and back buffers implementation.
* Pure virtual - must be implemented by Concrate implementations of GraphicsContext. */
void PixelBufferCarbon::swapBuffersImplementation()
{
aglSwapBuffers(_context);
}
PixelBufferCarbon::~PixelBufferCarbon()
{
close(true);
}
#endif<commit_msg>Converted tabs to four spaces<commit_after>/*
* PixelBufferCarbon.cpp
* OpenSceneGraph
*
* Created by Stephan Huber on 27.06.07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifdef __APPLE__
#include <osg/observer_ptr>
#include <osgViewer/api/Carbon/PixelBufferCarbon>
#include <osgViewer/api/Carbon/GraphicsWindowCarbon>
#include <Carbon/Carbon.h>
#include <OpenGL/OpenGL.h>
using namespace osgViewer;
/** creates a pixelformat from a Trait */
AGLPixelFormat PixelBufferCarbon::createPixelFormat(osg::GraphicsContext::Traits* traits) {
std::vector<GLint> attributes;
attributes.push_back(AGL_NO_RECOVERY);
attributes.push_back(AGL_RGBA);
if (!traits->pbuffer)
attributes.push_back(AGL_COMPLIANT);
else
attributes.push_back(AGL_CLOSEST_POLICY);
if (traits->doubleBuffer) attributes.push_back(AGL_DOUBLEBUFFER);
if (traits->quadBufferStereo) attributes.push_back(AGL_STEREO);
attributes.push_back(AGL_RED_SIZE); attributes.push_back(traits->red);
attributes.push_back(AGL_GREEN_SIZE); attributes.push_back(traits->green);
attributes.push_back(AGL_BLUE_SIZE); attributes.push_back(traits->blue);
attributes.push_back(AGL_DEPTH_SIZE); attributes.push_back(traits->depth);
if (traits->alpha) { attributes.push_back(AGL_ALPHA_SIZE); attributes.push_back(traits->alpha); }
if (traits->stencil) { attributes.push_back(AGL_STENCIL_SIZE); attributes.push_back(traits->stencil); }
// TODO
// missing accumulation-buffer-stuff
#if defined(AGL_SAMPLE_BUFFERS_ARB) && defined (AGL_SAMPLES_ARB)
if (traits->sampleBuffers) { attributes.push_back(AGL_SAMPLE_BUFFERS_ARB); attributes.push_back(traits->sampleBuffers); }
if (traits->sampleBuffers) { attributes.push_back(AGL_SAMPLES_ARB); attributes.push_back(traits->samples); }
#endif
attributes.push_back(AGL_NONE);
return aglChoosePixelFormat(NULL, 0, &(attributes.front()));
}
void PixelBufferCarbon::init()
{
_context = NULL;
_pixelformat = PixelBufferCarbon::createPixelFormat(_traits.get());
if (!_pixelformat)
osg::notify(osg::WARN) << "PixelBufferCarbon::init could not create a valid pixelformat" << std::endl;
_valid = (_pixelformat != NULL);
}
/** This is the class we need to create for pbuffers, note its not a GraphicsWindow as it won't need any of the event handling and window mapping facilities.*/
/** Realise the GraphicsContext implementation,
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::realizeImplementation()
{
if (!_valid) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglChoosePixelFormat failed! " << aglErrorString(aglGetError()) << std::endl;
return false;
}
AGLContext sharedContext = NULL;
// get any shared GLX contexts
GraphicsWindowCarbon* graphicsWindowCarbon = dynamic_cast<GraphicsWindowCarbon*>(_traits->sharedContext);
if (graphicsWindowCarbon)
{
sharedContext = graphicsWindowCarbon->getAGLContext();
}
else
{
PixelBufferCarbon* pixelBufferCarbon = dynamic_cast<PixelBufferCarbon*>(_traits->sharedContext);
if (pixelBufferCarbon)
{
sharedContext = pixelBufferCarbon->getAGLContext();
}
}
_context = aglCreateContext (_pixelformat, sharedContext);
if (!_context) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglCreateContext failed! " << aglErrorString(aglGetError()) << std::endl;
return false;
}
_realized = aglCreatePBuffer (_traits->width, _traits->height, _traits->target, GL_RGBA, _traits->level, &(_pbuffer));
if (!_realized) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglCreatePBuffer failed! " << aglErrorString(aglGetError()) << std::endl;
}
makeCurrentImplementation();
_realized = aglSetPBuffer(_context, _pbuffer, _traits->face, _traits->level, 0);
if (!_realized) {
osg::notify(osg::WARN) << "PixelBufferCarbon::realizeImplementation() aglSetPBuffer failed! " << aglErrorString(aglGetError()) << std::endl;
}
return _realized;
}
void PixelBufferCarbon::closeImplementation()
{
if (_pbuffer) aglDestroyPBuffer(_pbuffer);
if (_context) aglDestroyContext(_context);
if (_pixelformat) aglDestroyPixelFormat(_pixelformat);
_valid = _realized = false;
}
/** Make this graphics context current implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::makeCurrentImplementation()
{
return (_realized) ? (aglSetCurrentContext(_context) == GL_TRUE) : false;
}
/** Make this graphics context current with specified read context implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
bool PixelBufferCarbon::makeContextCurrentImplementation(GraphicsContext* /*readContext*/) {
return makeCurrentImplementation();
}
/** Release the graphics context.*/
bool PixelBufferCarbon::releaseContextImplementation()
{
return (aglSetCurrentContext(NULL) == GL_TRUE);
}
/** Pure virtual, Bind the graphics context to associated texture implementation.
* Pure virtual - must be implemented by concrate implementations of GraphicsContext. */
void PixelBufferCarbon::bindPBufferToTextureImplementation( GLenum buffer ){
osg::notify(osg::NOTICE)<<"GraphicsWindow::void bindPBufferToTextureImplementation(..) not implemented."<<std::endl;
}
/** Swap the front and back buffers implementation.
* Pure virtual - must be implemented by Concrate implementations of GraphicsContext. */
void PixelBufferCarbon::swapBuffersImplementation()
{
aglSwapBuffers(_context);
}
PixelBufferCarbon::~PixelBufferCarbon()
{
close(true);
}
#endif<|endoftext|> |
<commit_before>/*
* Glue for using libusb with libev
*
* Copyright (c) 2013 Micah Elizabeth Scott
*
* 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 "libusbev.h"
#include "util.h"
#include <stdlib.h>
#include <poll.h>
void LibUSBEventBridge::cbEvent(struct ev_loop *loop, ev_io *io, int revents)
{
Watcher *w = container_of(io, Watcher, io);
LibUSBEventBridge *self = w->self;
// Handle pending USB events without blocking
struct timeval tvZero = { 0, 0 };
libusb_handle_events_timeout(self->mCtx, &tvZero);
}
void LibUSBEventBridge::cbAdded(int fd, short events, void *user_data)
{
LibUSBEventBridge *self = static_cast<LibUSBEventBridge*>(user_data);
Watcher *w = new Watcher();
w->self = self;
ev_io_init(&w->io, cbEvent, fd,
((events & POLLIN) ? EV_READ : 0) |
((events & POLLOUT) ? EV_WRITE : 0));
self->mWatchers[fd] = w;
ev_io_start(self->mLoop, &w->io);
}
void LibUSBEventBridge::cbRemoved(int fd, void *user_data)
{
LibUSBEventBridge *self = static_cast<LibUSBEventBridge*>(user_data);
Watcher *w = self->mWatchers[fd];
ev_io_stop(self->mLoop, &w->io);
self->mWatchers.erase(fd);
}
void LibUSBEventBridge::init(struct libusb_context *ctx, struct ev_loop *loop)
{
mCtx = ctx;
mLoop = loop;
// Handle FDs that are already registered
const struct libusb_pollfd **fds = libusb_get_pollfds(ctx);
for (const struct libusb_pollfd **i = fds; *i; ++i) {
cbAdded((*i)->fd, (*i)->events, this);
}
free(fds);
// Get notified when future callbacks are added
libusb_set_pollfd_notifiers(ctx, cbAdded, cbRemoved, this);
}
<commit_msg>libusbev: Fix memory leak<commit_after>/*
* Glue for using libusb with libev
*
* Copyright (c) 2013 Micah Elizabeth Scott
*
* 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 "libusbev.h"
#include "util.h"
#include <stdlib.h>
#include <poll.h>
void LibUSBEventBridge::cbEvent(struct ev_loop *loop, ev_io *io, int revents)
{
Watcher *w = container_of(io, Watcher, io);
LibUSBEventBridge *self = w->self;
// Handle pending USB events without blocking
struct timeval tvZero = { 0, 0 };
libusb_handle_events_timeout(self->mCtx, &tvZero);
}
void LibUSBEventBridge::cbAdded(int fd, short events, void *user_data)
{
LibUSBEventBridge *self = static_cast<LibUSBEventBridge*>(user_data);
Watcher *w = new Watcher();
w->self = self;
ev_io_init(&w->io, cbEvent, fd,
((events & POLLIN) ? EV_READ : 0) |
((events & POLLOUT) ? EV_WRITE : 0));
self->mWatchers[fd] = w;
ev_io_start(self->mLoop, &w->io);
}
void LibUSBEventBridge::cbRemoved(int fd, void *user_data)
{
LibUSBEventBridge *self = static_cast<LibUSBEventBridge*>(user_data);
Watcher *w = self->mWatchers[fd];
ev_io_stop(self->mLoop, &w->io);
delete w;
self->mWatchers.erase(fd);
}
void LibUSBEventBridge::init(struct libusb_context *ctx, struct ev_loop *loop)
{
mCtx = ctx;
mLoop = loop;
// Handle FDs that are already registered
const struct libusb_pollfd **fds = libusb_get_pollfds(ctx);
for (const struct libusb_pollfd **i = fds; *i; ++i) {
cbAdded((*i)->fd, (*i)->events, this);
}
free(fds);
// Get notified when future callbacks are added
libusb_set_pollfd_notifiers(ctx, cbAdded, cbRemoved, this);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commitdata.h"
#include "gitclient.h"
#include "gitconstants.h"
#include "gitplugin.h"
#include "gitsubmiteditor.h"
#include "gitsubmiteditorwidget.h"
#include <utils/qtcassert.h>
#include <vcsbase/submitfilemodel.h>
#include <vcsbase/vcsbaseoutputwindow.h>
#include <QDebug>
#include <QStringList>
#include <QTextCodec>
namespace Git {
namespace Internal {
class GitSubmitFileModel : public VcsBase::SubmitFileModel
{
public:
GitSubmitFileModel(QObject *parent = 0) : VcsBase::SubmitFileModel(parent)
{ }
virtual void updateSelections(SubmitFileModel *source)
{
int j = 0;
for (int i = 0; i < rowCount() && j < source->rowCount(); ++i) {
CommitData::StateFilePair stateFile = stateFilePair(i);
for (; j < source->rowCount(); ++j) {
CommitData::StateFilePair sourceStateFile = stateFilePair(j);
if (stateFile == sourceStateFile) {
setChecked(i, source->checked(j));
break;
} else if (stateFile < sourceStateFile) {
break;
}
}
}
}
private:
CommitData::StateFilePair stateFilePair(int row)
{
return CommitData::StateFilePair(static_cast<FileStates>(extraData(row).toInt()), file(row));
}
};
/* The problem with git is that no diff can be obtained to for a random
* multiselection of staged/unstaged files; it requires the --cached
* option for staged files. So, we sort apart the diff file lists
* according to a type flag we add to the model. */
GitSubmitEditor::GitSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters, QWidget *parent) :
VcsBaseSubmitEditor(parameters, new GitSubmitEditorWidget(parent)),
m_model(0),
m_amend(false)
{
connect(this, SIGNAL(diffSelectedFiles(QList<int>)), this, SLOT(slotDiffSelected(QList<int>)));
}
GitSubmitEditorWidget *GitSubmitEditor::submitEditorWidget()
{
return static_cast<GitSubmitEditorWidget *>(widget());
}
void GitSubmitEditor::setCommitData(const CommitData &d)
{
GitSubmitEditorWidget *w = submitEditorWidget();
w->setPanelData(d.panelData);
w->setPanelInfo(d.panelInfo);
w->setHasUnmerged(false);
m_commitEncoding = d.commitEncoding;
m_workingDirectory = d.panelInfo.repository;
m_model = new GitSubmitFileModel(this);
if (!d.files.isEmpty()) {
for (QList<CommitData::StateFilePair>::const_iterator it = d.files.constBegin();
it != d.files.constEnd(); ++it) {
const FileStates state = it->first;
const QString file = it->second;
VcsBase::CheckMode checkMode;
if (state & UnmergedFile) {
checkMode = VcsBase::Uncheckable;
w->setHasUnmerged(true);
} else if (state & StagedFile) {
checkMode = VcsBase::Checked;
} else {
checkMode = VcsBase::Unchecked;
}
m_model->addFile(file, CommitData::stateDisplayName(state), checkMode,
QVariant(static_cast<int>(state)));
}
}
setFileModel(m_model, d.panelInfo.repository);
}
void GitSubmitEditor::setAmend(bool amend)
{
m_amend = amend;
setEmptyFileListEnabled(amend); // Allow for just correcting the message
}
void GitSubmitEditor::slotDiffSelected(const QList<int> &rows)
{
// Sort it apart into unmerged/staged/unstaged files
QStringList unmergedFiles;
QStringList unstagedFiles;
QStringList stagedFiles;
foreach (int row, rows) {
const QString fileName = m_model->file(row);
const FileStates state = static_cast<FileStates>(m_model->extraData(row).toInt());
if (state & UnmergedFile)
unmergedFiles.push_back(fileName);
else if (state & StagedFile)
stagedFiles.push_back(fileName);
else if (state != UntrackedFile)
unstagedFiles.push_back(fileName);
}
if (!unstagedFiles.empty() || !stagedFiles.empty())
emit diff(unstagedFiles, stagedFiles);
if (!unmergedFiles.empty())
emit merge(unmergedFiles);
}
void GitSubmitEditor::updateFileModel()
{
GitClient *client = GitPlugin::instance()->gitClient();
QString errorMessage, commitTemplate;
CommitData data;
if (client->getCommitData(m_workingDirectory, m_amend, &commitTemplate, &data, &errorMessage))
setCommitData(data);
else
VcsBase::VcsBaseOutputWindow::instance()->append(errorMessage);
}
GitSubmitEditorPanelData GitSubmitEditor::panelData() const
{
return const_cast<GitSubmitEditor*>(this)->submitEditorWidget()->panelData();
}
QByteArray GitSubmitEditor::fileContents() const
{
const QString& text = const_cast<GitSubmitEditor*>(this)->submitEditorWidget()->descriptionText();
if (!m_commitEncoding.isEmpty()) {
// Do the encoding convert, When use user-defined encoding
// e.g. git config --global i18n.commitencoding utf-8
QTextCodec *codec = QTextCodec::codecForName(m_commitEncoding.toLocal8Bit());
if (codec)
return codec->fromUnicode(text);
}
// Using utf-8 as the default encoding
return text.toUtf8();
}
} // namespace Internal
} // namespace Git
<commit_msg>Git: Fix reading commit data in wrong working directory on commit<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commitdata.h"
#include "gitclient.h"
#include "gitconstants.h"
#include "gitplugin.h"
#include "gitsubmiteditor.h"
#include "gitsubmiteditorwidget.h"
#include <utils/qtcassert.h>
#include <vcsbase/submitfilemodel.h>
#include <vcsbase/vcsbaseoutputwindow.h>
#include <QDebug>
#include <QStringList>
#include <QTextCodec>
namespace Git {
namespace Internal {
class GitSubmitFileModel : public VcsBase::SubmitFileModel
{
public:
GitSubmitFileModel(QObject *parent = 0) : VcsBase::SubmitFileModel(parent)
{ }
virtual void updateSelections(SubmitFileModel *source)
{
int j = 0;
for (int i = 0; i < rowCount() && j < source->rowCount(); ++i) {
CommitData::StateFilePair stateFile = stateFilePair(i);
for (; j < source->rowCount(); ++j) {
CommitData::StateFilePair sourceStateFile = stateFilePair(j);
if (stateFile == sourceStateFile) {
setChecked(i, source->checked(j));
break;
} else if (stateFile < sourceStateFile) {
break;
}
}
}
}
private:
CommitData::StateFilePair stateFilePair(int row)
{
return CommitData::StateFilePair(static_cast<FileStates>(extraData(row).toInt()), file(row));
}
};
/* The problem with git is that no diff can be obtained to for a random
* multiselection of staged/unstaged files; it requires the --cached
* option for staged files. So, we sort apart the diff file lists
* according to a type flag we add to the model. */
GitSubmitEditor::GitSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters, QWidget *parent) :
VcsBaseSubmitEditor(parameters, new GitSubmitEditorWidget(parent)),
m_model(0),
m_amend(false)
{
connect(this, SIGNAL(diffSelectedFiles(QList<int>)), this, SLOT(slotDiffSelected(QList<int>)));
}
GitSubmitEditorWidget *GitSubmitEditor::submitEditorWidget()
{
return static_cast<GitSubmitEditorWidget *>(widget());
}
void GitSubmitEditor::setCommitData(const CommitData &d)
{
GitSubmitEditorWidget *w = submitEditorWidget();
w->setPanelData(d.panelData);
w->setPanelInfo(d.panelInfo);
w->setHasUnmerged(false);
m_commitEncoding = d.commitEncoding;
m_workingDirectory = d.panelInfo.repository;
m_model = new GitSubmitFileModel(this);
if (!d.files.isEmpty()) {
for (QList<CommitData::StateFilePair>::const_iterator it = d.files.constBegin();
it != d.files.constEnd(); ++it) {
const FileStates state = it->first;
const QString file = it->second;
VcsBase::CheckMode checkMode;
if (state & UnmergedFile) {
checkMode = VcsBase::Uncheckable;
w->setHasUnmerged(true);
} else if (state & StagedFile) {
checkMode = VcsBase::Checked;
} else {
checkMode = VcsBase::Unchecked;
}
m_model->addFile(file, CommitData::stateDisplayName(state), checkMode,
QVariant(static_cast<int>(state)));
}
}
setFileModel(m_model, d.panelInfo.repository);
}
void GitSubmitEditor::setAmend(bool amend)
{
m_amend = amend;
setEmptyFileListEnabled(amend); // Allow for just correcting the message
}
void GitSubmitEditor::slotDiffSelected(const QList<int> &rows)
{
// Sort it apart into unmerged/staged/unstaged files
QStringList unmergedFiles;
QStringList unstagedFiles;
QStringList stagedFiles;
foreach (int row, rows) {
const QString fileName = m_model->file(row);
const FileStates state = static_cast<FileStates>(m_model->extraData(row).toInt());
if (state & UnmergedFile)
unmergedFiles.push_back(fileName);
else if (state & StagedFile)
stagedFiles.push_back(fileName);
else if (state != UntrackedFile)
unstagedFiles.push_back(fileName);
}
if (!unstagedFiles.empty() || !stagedFiles.empty())
emit diff(unstagedFiles, stagedFiles);
if (!unmergedFiles.empty())
emit merge(unmergedFiles);
}
void GitSubmitEditor::updateFileModel()
{
if (m_workingDirectory.isEmpty())
return;
GitClient *client = GitPlugin::instance()->gitClient();
QString errorMessage, commitTemplate;
CommitData data;
if (client->getCommitData(m_workingDirectory, m_amend, &commitTemplate, &data, &errorMessage))
setCommitData(data);
else
VcsBase::VcsBaseOutputWindow::instance()->append(errorMessage);
}
GitSubmitEditorPanelData GitSubmitEditor::panelData() const
{
return const_cast<GitSubmitEditor*>(this)->submitEditorWidget()->panelData();
}
QByteArray GitSubmitEditor::fileContents() const
{
const QString& text = const_cast<GitSubmitEditor*>(this)->submitEditorWidget()->descriptionText();
if (!m_commitEncoding.isEmpty()) {
// Do the encoding convert, When use user-defined encoding
// e.g. git config --global i18n.commitencoding utf-8
QTextCodec *codec = QTextCodec::codecForName(m_commitEncoding.toLocal8Bit());
if (codec)
return codec->fromUnicode(text);
}
// Using utf-8 as the default encoding
return text.toUtf8();
}
} // namespace Internal
} // namespace Git
<|endoftext|> |
<commit_before>//
// BatchEncoder - GetProgress MppDec
// Copyright (C) 2005-2017 Wiesław Šoltés <wieslaw.soltes@gmail.com>
//
// 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; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include "GetProgress.h"
int GetProgress(char *szLineBuff, int nLineLen)
{
int nStart;
int nEnd;
char szPercentage[32];
int j;
int nProgress;
memset(szPercentage, 0x00, sizeof(szPercentage));
nStart = 0;
nEnd = 0;
for (j = 0; j < (int)nLineLen; j++)
{
if (szLineBuff[j] == '(')
{
nStart = j;
}
if (szLineBuff[j] == ')')
{
nEnd = j;
break;
}
}
if (nEnd > 0)
{
// find: 3:45.06 (runtime: 0.98 s speed: 228.48x)
if (szLineBuff[nEnd - 1] == 'x') // done
{
nProgress = 100;
return nProgress;
}
// find: 0:53.07/ 3:45.07 decoded (23.6%)
if (szLineBuff[nEnd - 1] == '%') // progress
{
if (szLineBuff[nEnd - 5] == ' ') // 0 to 9 %
{
szPercentage[0] = szLineBuff[nEnd - 4];
szPercentage[1] = '\0';
nProgress = atoi(szPercentage);
return nProgress;
}
else if (szLineBuff[nEnd - 5] >= '0' && szLineBuff[nEnd - 5] >= '9') // 10 to 99%
{
szPercentage[0] = szLineBuff[nEnd - 5];
szPercentage[1] = szLineBuff[nEnd - 4];
szPercentage[2] = '\0';
nProgress = atoi(szPercentage);
return nProgress;
}
}
}
return -1;
}
<commit_msg>Update GetProgress.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include "GetProgress.h"
int GetProgress(char *szLineBuff, int nLineLen)
{
int nStart;
int nEnd;
char szPercentage[32];
int j;
int nProgress;
memset(szPercentage, 0x00, sizeof(szPercentage));
nStart = 0;
nEnd = 0;
for (j = 0; j < (int)nLineLen; j++)
{
if (szLineBuff[j] == '(')
{
nStart = j;
}
if (szLineBuff[j] == ')')
{
nEnd = j;
break;
}
}
if (nEnd > 0)
{
// find: 3:45.06 (runtime: 0.98 s speed: 228.48x)
if (szLineBuff[nEnd - 1] == 'x') // done
{
nProgress = 100;
return nProgress;
}
// find: 0:53.07/ 3:45.07 decoded (23.6%)
if (szLineBuff[nEnd - 1] == '%') // progress
{
if (szLineBuff[nEnd - 5] == ' ') // 0 to 9 %
{
szPercentage[0] = szLineBuff[nEnd - 4];
szPercentage[1] = '\0';
nProgress = atoi(szPercentage);
return nProgress;
}
else if (szLineBuff[nEnd - 5] >= '0' && szLineBuff[nEnd - 5] >= '9') // 10 to 99%
{
szPercentage[0] = szLineBuff[nEnd - 5];
szPercentage[1] = szLineBuff[nEnd - 4];
szPercentage[2] = '\0';
nProgress = atoi(szPercentage);
return nProgress;
}
}
}
return -1;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2016 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/ports/imageport.h>
#include <inviwo/core/ports/port.h>
#include <inviwo/core/util/document.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/qt/editor/editorgrapicsitem.h>
#include <inviwo/qt/editor/networkeditor.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QToolTip>
#include <QBuffer>
#include <QApplication>
#include <warn/pop>
namespace inviwo {
EditorGraphicsItem::EditorGraphicsItem() : QGraphicsRectItem() {}
EditorGraphicsItem::EditorGraphicsItem(QGraphicsItem* parent) : QGraphicsRectItem(parent) {}
EditorGraphicsItem::~EditorGraphicsItem() = default;
QPoint EditorGraphicsItem::mapPosToSceen(QPointF inPos) const {
if (scene() != nullptr // the focus item belongs to a scene
&& !scene()->views().isEmpty() // that scene is displayed in a view...
&& scene()->views().first() != nullptr // ... which is not null...
&& scene()->views().first()->viewport() != nullptr // ... and has a viewport
) {
QPointF sceneP = mapToScene(inPos);
QGraphicsView* v = scene()->views().first();
QPoint viewP = v->mapFromScene(sceneP);
return v->viewport()->mapToGlobal(viewP);
} else {
return QPoint(0,0);
}
}
const QPainterPath EditorGraphicsItem::makeRoundedBox(QRectF rect, float radius) {
QPainterPath roundRectPath;
roundRectPath.moveTo(rect.left(), rect.top() + radius);
roundRectPath.lineTo(rect.left(), rect.bottom() - radius);
roundRectPath.arcTo(rect.left(), rect.bottom() - (2 * radius), (2 * radius),
(2 * radius), 180.0, 90.0);
roundRectPath.lineTo(rect.right() - radius, rect.bottom());
roundRectPath.arcTo(rect.right() - (2 * radius), rect.bottom() - (2 * radius),
(2 * radius), (2 * radius), 270.0, 90.0);
roundRectPath.lineTo(rect.right(), rect.top() + radius);
roundRectPath.arcTo(rect.right() - (2 * radius), rect.top(), (2 * radius),
(2 * radius), 0.0, 90.0);
roundRectPath.lineTo(rect.left() + radius, rect.top());
roundRectPath.arcTo(rect.left(), rect.top(), (2 * radius), (2 * radius), 90.0,
90.0);
return roundRectPath;
}
void EditorGraphicsItem::showToolTip(QGraphicsSceneHelpEvent* e) {
showToolTipHelper(e, QString("Test"));
}
void EditorGraphicsItem::showToolTipHelper(QGraphicsSceneHelpEvent* e, QString string) const {
QGraphicsView* v = scene()->views().first();
QRectF rect = this->mapRectToScene(this->rect());
QRect viewRect = v->mapFromScene(rect).boundingRect();
QToolTip::showText(e->screenPos(), string, v, viewRect);
}
NetworkEditor* EditorGraphicsItem::getNetworkEditor() const {
return qobject_cast<NetworkEditor*>(scene());
}
void EditorGraphicsItem::showPortInfo(QGraphicsSceneHelpEvent* e, Port* port) const {
SystemSettings* settings = InviwoApplication::getPtr()->getSettingsByType<SystemSettings>();
bool portinfo = settings->enablePortInformation_.get();
bool inspector = settings->enablePortInspectors_.get();
if (!inspector && !portinfo) return;
size_t portInspectorSize = static_cast<size_t>(settings->portInspectorSize_.get());
Document doc;
using P = Document::PathComponent;
using H = utildoc::TableBuilder::Header;
auto t = doc.append("html").append("body").append("table");
if (portinfo) {
auto pi = t.append("tr").append("td");
pi.append("b", port->getClassIdentifier(), {{"style", "color:white;"}});
utildoc::TableBuilder tb(pi, P::end());
if (auto inport = dynamic_cast<const Inport*>(port)) {
if (inport->isOptional()) {
tb(H("Optional Port"));
}
}
tb(H("Identifier"), port->getIdentifier());
}
if (inspector) {
const std::string imageType = "raw";
if (auto outport = dynamic_cast<Outport*>(port)) {
if (auto image = getNetworkEditor()->renderPortInspectorImage(outport)) {
bool isImagePort = (dynamic_cast<ImageOutport*>(port) != nullptr);
std::vector<const Layer *> layers;
if (isImagePort) {
// register all color layers
for (std::size_t i=0; i < image->getNumberOfColorLayers(); ++i) {
layers.push_back(image->getColorLayer(i));
}
// register picking layer
layers.push_back(image->getPickingLayer());
// register depth layer
layers.push_back(image->getDepthLayer());
}
else {
// outport is not an ImageOutport, show only first color layer
layers.push_back(image->getColorLayer(0));
}
// add all layer images into the same row
auto tableCell = t.append("tr").append("td");
for (auto layer : layers) {
auto data = layer->getAsCodedBuffer(imageType);
QByteArray byteArray;
if (imageType == "png") {
// input buffer is already stored as png
byteArray.setRawData(reinterpret_cast<const char*>(&(data->front())),
static_cast<unsigned int>(data->size()));
}
else if (imageType == "raw") {
// do manual conversion from raw to png via QImage
QImage::Format format = QImage::Format_Invalid;
if (data->size() == portInspectorSize * portInspectorSize) {
#if QT_VERSION >= 0x050500
format = QImage::Format_Grayscale8;
#else
format = QImage::Format_RGB888;
// duplicate grayscale data into 3 channels
auto newData = std::make_unique<std::vector<unsigned char>>();
newData->reserve(data->size() * 3);
for (auto value : *data.get()) {
newData->insert(newData->end(), 3, value);
}
data = std::move(newData);
#endif
}
else if (data->size() == portInspectorSize * portInspectorSize * 3) {
format = QImage::Format_RGB888;
}
else if (data->size() == portInspectorSize * portInspectorSize * 4) {
format = QImage::Format_RGBA8888;
}
QImage qImage(reinterpret_cast<const unsigned char*>(&(data->front())),
static_cast<int>(portInspectorSize), static_cast<int>(portInspectorSize), format);
QBuffer buffer(&byteArray);
qImage.save(&buffer, "PNG");
}
else {
throw Exception("Support for image type not yet implemented", IvwContext);
}
tableCell.append(
"img", "",
{ {"width", std::to_string(portInspectorSize)},
{"height", std::to_string(portInspectorSize)},
{"src", "data:image/png;base64," + std::string(byteArray.toBase64().data())} });
}
}
}
}
if (portinfo) {
t.append("tr").append("td", port->getContentInfo());
}
// Need to make sure that we have not pending qt stuff before showing tooltip
// otherwise we might loose focus and the tooltip will go away...
qApp->processEvents();
showToolTipHelper(e, utilqt::toLocalQString(doc));
}
} // namespace
<commit_msg>QtEditor: Fixed crash when no converter was found for layer inspection<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2016 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/ports/imageport.h>
#include <inviwo/core/ports/port.h>
#include <inviwo/core/util/document.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/qt/editor/editorgrapicsitem.h>
#include <inviwo/qt/editor/networkeditor.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QToolTip>
#include <QBuffer>
#include <QApplication>
#include <warn/pop>
namespace inviwo {
EditorGraphicsItem::EditorGraphicsItem() : QGraphicsRectItem() {}
EditorGraphicsItem::EditorGraphicsItem(QGraphicsItem* parent) : QGraphicsRectItem(parent) {}
EditorGraphicsItem::~EditorGraphicsItem() = default;
QPoint EditorGraphicsItem::mapPosToSceen(QPointF inPos) const {
if (scene() != nullptr // the focus item belongs to a scene
&& !scene()->views().isEmpty() // that scene is displayed in a view...
&& scene()->views().first() != nullptr // ... which is not null...
&& scene()->views().first()->viewport() != nullptr // ... and has a viewport
) {
QPointF sceneP = mapToScene(inPos);
QGraphicsView* v = scene()->views().first();
QPoint viewP = v->mapFromScene(sceneP);
return v->viewport()->mapToGlobal(viewP);
} else {
return QPoint(0,0);
}
}
const QPainterPath EditorGraphicsItem::makeRoundedBox(QRectF rect, float radius) {
QPainterPath roundRectPath;
roundRectPath.moveTo(rect.left(), rect.top() + radius);
roundRectPath.lineTo(rect.left(), rect.bottom() - radius);
roundRectPath.arcTo(rect.left(), rect.bottom() - (2 * radius), (2 * radius),
(2 * radius), 180.0, 90.0);
roundRectPath.lineTo(rect.right() - radius, rect.bottom());
roundRectPath.arcTo(rect.right() - (2 * radius), rect.bottom() - (2 * radius),
(2 * radius), (2 * radius), 270.0, 90.0);
roundRectPath.lineTo(rect.right(), rect.top() + radius);
roundRectPath.arcTo(rect.right() - (2 * radius), rect.top(), (2 * radius),
(2 * radius), 0.0, 90.0);
roundRectPath.lineTo(rect.left() + radius, rect.top());
roundRectPath.arcTo(rect.left(), rect.top(), (2 * radius), (2 * radius), 90.0,
90.0);
return roundRectPath;
}
void EditorGraphicsItem::showToolTip(QGraphicsSceneHelpEvent* e) {
showToolTipHelper(e, QString("Test"));
}
void EditorGraphicsItem::showToolTipHelper(QGraphicsSceneHelpEvent* e, QString string) const {
QGraphicsView* v = scene()->views().first();
QRectF rect = this->mapRectToScene(this->rect());
QRect viewRect = v->mapFromScene(rect).boundingRect();
QToolTip::showText(e->screenPos(), string, v, viewRect);
}
NetworkEditor* EditorGraphicsItem::getNetworkEditor() const {
return qobject_cast<NetworkEditor*>(scene());
}
void EditorGraphicsItem::showPortInfo(QGraphicsSceneHelpEvent* e, Port* port) const {
SystemSettings* settings = InviwoApplication::getPtr()->getSettingsByType<SystemSettings>();
bool portinfo = settings->enablePortInformation_.get();
bool inspector = settings->enablePortInspectors_.get();
if (!inspector && !portinfo) return;
size_t portInspectorSize = static_cast<size_t>(settings->portInspectorSize_.get());
Document doc;
using P = Document::PathComponent;
using H = utildoc::TableBuilder::Header;
auto t = doc.append("html").append("body").append("table");
if (portinfo) {
auto pi = t.append("tr").append("td");
pi.append("b", port->getClassIdentifier(), {{"style", "color:white;"}});
utildoc::TableBuilder tb(pi, P::end());
if (auto inport = dynamic_cast<const Inport*>(port)) {
if (inport->isOptional()) {
tb(H("Optional Port"));
}
}
tb(H("Identifier"), port->getIdentifier());
}
if (inspector) {
const std::string imageType = "raw";
if (auto outport = dynamic_cast<Outport*>(port)) {
if (auto image = getNetworkEditor()->renderPortInspectorImage(outport)) {
bool isImagePort = (dynamic_cast<ImageOutport*>(port) != nullptr);
std::vector<const Layer *> layers;
if (isImagePort) {
// register all color layers
for (std::size_t i=0; i < image->getNumberOfColorLayers(); ++i) {
layers.push_back(image->getColorLayer(i));
}
// register picking layer
layers.push_back(image->getPickingLayer());
// register depth layer
layers.push_back(image->getDepthLayer());
}
else {
// outport is not an ImageOutport, show only first color layer
layers.push_back(image->getColorLayer(0));
}
// add all layer images into the same row
auto tableCell = t.append("tr").append("td");
for (auto layer : layers) {
auto data = layer->getAsCodedBuffer(imageType);
if (!data) continue; // no conversion possible
QByteArray byteArray;
if (imageType == "png") {
// input buffer is already stored as png
byteArray.setRawData(reinterpret_cast<const char*>(&(data->front())),
static_cast<unsigned int>(data->size()));
}
else if (imageType == "raw") {
// do manual conversion from raw to png via QImage
QImage::Format format = QImage::Format_Invalid;
if (data->size() == portInspectorSize * portInspectorSize) {
#if QT_VERSION >= 0x050500
format = QImage::Format_Grayscale8;
#else
format = QImage::Format_RGB888;
// duplicate grayscale data into 3 channels
auto newData = std::make_unique<std::vector<unsigned char>>();
newData->reserve(data->size() * 3);
for (auto value : *data.get()) {
newData->insert(newData->end(), 3, value);
}
data = std::move(newData);
#endif
}
else if (data->size() == portInspectorSize * portInspectorSize * 3) {
format = QImage::Format_RGB888;
}
else if (data->size() == portInspectorSize * portInspectorSize * 4) {
format = QImage::Format_RGBA8888;
}
QImage qImage(reinterpret_cast<const unsigned char*>(&(data->front())),
static_cast<int>(portInspectorSize), static_cast<int>(portInspectorSize), format);
QBuffer buffer(&byteArray);
qImage.save(&buffer, "PNG");
}
else {
throw Exception("Support for image type not yet implemented", IvwContext);
}
tableCell.append(
"img", "",
{ {"width", std::to_string(portInspectorSize)},
{"height", std::to_string(portInspectorSize)},
{"src", "data:image/png;base64," + std::string(byteArray.toBase64().data())} });
}
}
}
}
if (portinfo) {
t.append("tr").append("td", port->getContentInfo());
}
// Need to make sure that we have not pending qt stuff before showing tooltip
// otherwise we might loose focus and the tooltip will go away...
qApp->processEvents();
showToolTipHelper(e, utilqt::toLocalQString(doc));
}
} // namespace
<|endoftext|> |
<commit_before>#include "ofdpa_bridge.hpp"
#include "roflibs/netlink/clogging.hpp"
#include <cassert>
#include <map>
#include <cstring>
#include <rofl/common/openflow/cofport.h>
namespace basebox {
ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)
: ingress_vlan_filtered(true), egress_vlan_filtered(false),
fm_driver(fm_driver) {}
ofdpa_bridge::~ofdpa_bridge() {}
void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {
if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {
rofcore::logging::error << __PRETTY_FUNCTION__
<< " not a bridge master: " << rtl << std::endl;
return;
}
this->bridge = rtl;
fm_driver.enable_policy_arp(1, 1);
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
if (not ingress_vlan_filtered) {
// ingress
fm_driver.enable_port_vid_allow_all(rtl.get_devname());
}
if (not egress_vlan_filtered) {
// egress
uint32_t group = fm_driver.enable_port_unfiltered_egress(rtl.get_devname());
l2_domain[0].push_back(group);
}
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = br_vlan->vlan_bitmap[k];
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, a);
if (j > 0) {
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
}
if (egress_vlan_filtered) {
uint32_t group = fm_driver.enable_port_vid_egress(
rtl.get_devname(), vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
}
if (ingress_vlan_filtered) {
if (br_vlan->pvid == vid) {
fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);
} else {
fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);
}
}
// // todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid,
// l2_domain[vid],
// 1 !=
// l2_domain[vid].size());
//
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
i = j;
} else {
done = 1;
}
}
}
}
void ofdpa_bridge::update_vlans(const std::string &devname,
const rtnl_link_bridge_vlan *old_br_vlan,
const rtnl_link_bridge_vlan *new_br_vlan) {
using rofcore::logging;
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t vlan_diff = a ^ b;
uint32_t untagged_diff = c ^ d;
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
if (egress_vlan_filtered) {
try {
uint32_t group = fm_driver.enable_port_vid_egress(
devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress" << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error1:" << e.what() << std::endl;
}
}
if (ingress_vlan_filtered) {
try {
if (new_br_vlan->pvid == vid) {
// todo check for existing pvid?
fm_driver.enable_port_pvid_ingress(devname, vid);
} else {
fm_driver.enable_port_vid_ingress(devname, vid);
}
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error2:" << e.what() << std::endl;
}
}
// todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid,
// l2_domain[vid],
// 1 !=
// l2_domain[vid].size());
// // enable arp flooding as well
// #if DISABLED_TO_TEST
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
// #endif
} else {
// vlan removed
if (ingress_vlan_filtered) {
try {
if (old_br_vlan->pvid == vid) {
fm_driver.disable_port_pvid_ingress(devname, vid);
} else {
fm_driver.disable_port_vid_ingress(devname, vid);
}
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error3:" << e.what() << std::endl;
}
}
if (egress_vlan_filtered) {
try {
// XXX delete all FM pointing to this group first
uint32_t group = fm_driver.disable_port_vid_egress(
devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to remove vid on egress"
<< std::endl;
i = j;
continue;
}
l2_domain[vid].remove(group);
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error4:" << e.what() << std::endl;
}
}
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,
const rofcore::crtlink &newlink) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot update interface without bridge" << std::endl;
return;
}
if (AF_BRIDGE != newlink.get_family()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a bridge interface" << std::endl;
return;
}
// if (AF_BRIDGE != oldlink.get_family()) {
// logging::error << __PRETTY_FUNCTION__ << oldlink << " is
// not a bridge interface" << std::endl;
// return;
// }
if (bridge.get_ifindex() != newlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (bridge.get_ifindex() != oldlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (newlink.get_devname().compare(oldlink.get_devname())) {
logging::info << __PRETTY_FUNCTION__
<< " interface rename currently ignored " << std::endl;
// FIXME this has to be handled differently
return;
}
// handle VLANs
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),
oldlink.get_br_vlan())) {
// vlan updated
update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),
newlink.get_br_vlan());
}
}
void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
if (not ingress_vlan_filtered) {
// ingress
fm_driver.disable_port_vid_allow_all(rtl.get_devname());
}
if (not egress_vlan_filtered) {
// egress
uint32_t group =
fm_driver.disable_port_unfiltered_egress(rtl.get_devname());
l2_domain[0].remove(group);
}
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
struct rtnl_link_bridge_vlan br_vlan_empty;
memset(&br_vlan_empty, 0, sizeof(struct rtnl_link_bridge_vlan));
if (not crtlink::are_br_vlan_equal(br_vlan, &br_vlan_empty)) {
// vlan updated
update_vlans(rtl.get_devname(), br_vlan, &br_vlan_empty);
}
}
void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,
const uint16_t vlan,
const rofl::cmacaddr &mac, bool permanent) {
fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent,
egress_vlan_filtered);
}
void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,
const rofl::cmacaddr &mac) {
fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);
}
} /* namespace basebox */
<commit_msg>wipe bridge table entries for group deletion<commit_after>#include "ofdpa_bridge.hpp"
#include "roflibs/netlink/clogging.hpp"
#include <cassert>
#include <map>
#include <cstring>
#include <rofl/common/openflow/cofport.h>
namespace basebox {
ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)
: ingress_vlan_filtered(true), egress_vlan_filtered(false),
fm_driver(fm_driver) {}
ofdpa_bridge::~ofdpa_bridge() {}
void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {
if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {
rofcore::logging::error << __PRETTY_FUNCTION__
<< " not a bridge master: " << rtl << std::endl;
return;
}
this->bridge = rtl;
fm_driver.enable_policy_arp(1, 1);
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
if (not ingress_vlan_filtered) {
// ingress
fm_driver.enable_port_vid_allow_all(rtl.get_devname());
}
if (not egress_vlan_filtered) {
// egress
uint32_t group = fm_driver.enable_port_unfiltered_egress(rtl.get_devname());
l2_domain[0].push_back(group);
}
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = br_vlan->vlan_bitmap[k];
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, a);
if (j > 0) {
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
}
if (egress_vlan_filtered) {
uint32_t group = fm_driver.enable_port_vid_egress(
rtl.get_devname(), vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
}
if (ingress_vlan_filtered) {
if (br_vlan->pvid == vid) {
fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);
} else {
fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);
}
}
// // todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid,
// l2_domain[vid],
// 1 !=
// l2_domain[vid].size());
//
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
i = j;
} else {
done = 1;
}
}
}
}
void ofdpa_bridge::update_vlans(const std::string &devname,
const rtnl_link_bridge_vlan *old_br_vlan,
const rtnl_link_bridge_vlan *new_br_vlan) {
using rofcore::logging;
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t vlan_diff = a ^ b;
uint32_t untagged_diff = c ^ d;
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
if (egress_vlan_filtered) {
try {
uint32_t group = fm_driver.enable_port_vid_egress(
devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress" << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error1:" << e.what() << std::endl;
}
}
if (ingress_vlan_filtered) {
try {
if (new_br_vlan->pvid == vid) {
// todo check for existing pvid?
fm_driver.enable_port_pvid_ingress(devname, vid);
} else {
fm_driver.enable_port_vid_ingress(devname, vid);
}
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error2:" << e.what() << std::endl;
}
}
// todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid,
// l2_domain[vid],
// 1 !=
// l2_domain[vid].size());
// // enable arp flooding as well
// #if DISABLED_TO_TEST
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
// #endif
} else {
// vlan removed
if (ingress_vlan_filtered) {
try {
if (old_br_vlan->pvid == vid) {
fm_driver.disable_port_pvid_ingress(devname, vid);
} else {
fm_driver.disable_port_vid_ingress(devname, vid);
}
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error3:" << e.what() << std::endl;
}
}
if (egress_vlan_filtered) {
try {
// delete all FM pointing to this group first
fm_driver.remove_bridging_unicast_vlan_all(devname, vid);
// make sure they are deleted
fm_driver.send_barrier();
uint32_t group = fm_driver.disable_port_vid_egress(
devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to remove vid on egress"
<< std::endl;
i = j;
continue;
}
l2_domain[vid].remove(group);
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__
<< " caught error4:" << e.what() << std::endl;
}
}
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,
const rofcore::crtlink &newlink) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot update interface without bridge" << std::endl;
return;
}
if (AF_BRIDGE != newlink.get_family()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a bridge interface" << std::endl;
return;
}
// if (AF_BRIDGE != oldlink.get_family()) {
// logging::error << __PRETTY_FUNCTION__ << oldlink << " is
// not a bridge interface" << std::endl;
// return;
// }
if (bridge.get_ifindex() != newlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (bridge.get_ifindex() != oldlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (newlink.get_devname().compare(oldlink.get_devname())) {
logging::info << __PRETTY_FUNCTION__
<< " interface rename currently ignored " << std::endl;
// FIXME this has to be handled differently
return;
}
// handle VLANs
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),
oldlink.get_br_vlan())) {
// vlan updated
update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),
newlink.get_br_vlan());
}
}
void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
if (not ingress_vlan_filtered) {
// ingress
fm_driver.disable_port_vid_allow_all(rtl.get_devname());
}
if (not egress_vlan_filtered) {
// egress
uint32_t group =
fm_driver.disable_port_unfiltered_egress(rtl.get_devname());
l2_domain[0].remove(group);
}
if (not ingress_vlan_filtered && not egress_vlan_filtered) {
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
struct rtnl_link_bridge_vlan br_vlan_empty;
memset(&br_vlan_empty, 0, sizeof(struct rtnl_link_bridge_vlan));
if (not crtlink::are_br_vlan_equal(br_vlan, &br_vlan_empty)) {
// vlan updated
update_vlans(rtl.get_devname(), br_vlan, &br_vlan_empty);
}
}
void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,
const uint16_t vlan,
const rofl::cmacaddr &mac, bool permanent) {
fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent,
egress_vlan_filtered);
}
void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,
const rofl::cmacaddr &mac) {
fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);
}
} /* namespace basebox */
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qaccelerationsensor.h>
QTM_BEGIN_NAMESPACE
/*!
\class QAccelerationValue
\ingroup sensors
\preliminary
\brief The QAccelerationValue class represents one value from the
acceleration sensor.
The values returned in QAccelerationValue are normalized so that
they are consistent between devices. The axes are arranged as follows.
TODO picture showing axes relative to the monoblock form factor.
The scale of the values is in milli-Gs.
A monoblock device sitting at rest, face up on a desk will experience
the force of gravity as approximately -1000 on the Z axis.
*/
/*!
\internal
*/
QAccelerationValue::QAccelerationValue()
: QSensorValue(QAccelerationSensor::TYPE)
{
}
/*!
\variable QAccelerationValue::Acceleration::x
Holds the acceleration force acting on the X axis.
*/
/*!
\variable QAccelerationValue::Acceleration::y
Holds the acceleration for the Y axis.
*/
/*!
\variable QAccelerationValue::Acceleration::z
Holds the acceleration for the Z axis.
*/
// =====================================================================
/*!
\class QAccelerationSensor
\ingroup sensors
\preliminary
\brief The QAccelerationSensor class reports on linear acceleration
along the X, Y and Z axes.
The values returned by QAccelerationSensor are normalized so that
they are consistent between devices. The axes are arranged as follows.
TODO picture showing axes relative to the monoblock form factor.
The scale of the values is in metres per second per second. A monoblock
device sitting at rest, face up on a desk will experience the force of
gravity as approximately -9.8 on the Z axis.
\sa QAccelerationValue
*/
/*!
\variable QAccelerationSensor::TYPE
*/
const QString QAccelerationSensor::TYPE("qt.Acceleration");
/*!
\fn QAccelerationSensor::type() const
\reimp
*/
/*!
Construct a sensor instance and attach to the sensor indicated by \a id.
The sensor will be deleted when \a parent is deleted.
*/
QAccelerationSensor::QAccelerationSensor(const QSensorID &id, QObject *parent)
: QSensor(parent)
{
connectToBackend(id);
}
/*!
\fn QAccelerationSensor::currentAcceleration() const
Returns the current acceleration values from the sensor.
*/
/*!
\fn QAccelerationSensor::currentXAcceleration() const
Returns the current x acceleration value from the sensor.
*/
/*!
\fn QAccelerationSensor::currentYAcceleration() const
Returns the current y acceleration value from the sensor.
*/
/*!
\fn QAccelerationSensor::currentZAcceleration() const
Returns the current z acceleration value from the sensor.
*/
QTM_END_NAMESPACE
<commit_msg>fix the wording here<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qaccelerationsensor.h>
QTM_BEGIN_NAMESPACE
/*!
\class QAccelerationValue
\ingroup sensors
\preliminary
\brief The QAccelerationValue class represents one value from the
acceleration sensor.
The values returned in QAccelerationValue are scaled so that
they are consistent between devices. The axes are arranged as follows.
TODO picture showing axes relative to the monoblock form factor.
The scale of the values is in milli-Gs.
A monoblock device sitting at rest, face up on a desk will experience
the force of gravity as approximately -1000 on the Z axis.
*/
/*!
\internal
*/
QAccelerationValue::QAccelerationValue()
: QSensorValue(QAccelerationSensor::TYPE)
{
}
/*!
\variable QAccelerationValue::Acceleration::x
Holds the acceleration force acting on the X axis.
*/
/*!
\variable QAccelerationValue::Acceleration::y
Holds the acceleration for the Y axis.
*/
/*!
\variable QAccelerationValue::Acceleration::z
Holds the acceleration for the Z axis.
*/
// =====================================================================
/*!
\class QAccelerationSensor
\ingroup sensors
\preliminary
\brief The QAccelerationSensor class reports on linear acceleration
along the X, Y and Z axes.
The values returned by QAccelerationSensor are scaled so that
they are consistent between devices. The axes are arranged as follows.
TODO picture showing axes relative to the monoblock form factor.
The scale of the values is in milli-Gs.
A monoblock device sitting at rest, face up on a desk will experience
the force of gravity as approximately -1000 on the Z axis.
\sa QAccelerationValue
*/
/*!
\variable QAccelerationSensor::TYPE
*/
const QString QAccelerationSensor::TYPE("qt.Acceleration");
/*!
\fn QAccelerationSensor::type() const
\reimp
*/
/*!
Construct a sensor instance and attach to the sensor indicated by \a id.
The sensor will be deleted when \a parent is deleted.
*/
QAccelerationSensor::QAccelerationSensor(const QSensorID &id, QObject *parent)
: QSensor(parent)
{
connectToBackend(id);
}
/*!
\fn QAccelerationSensor::currentAcceleration() const
Returns the current acceleration values from the sensor.
*/
/*!
\fn QAccelerationSensor::currentXAcceleration() const
Returns the current x acceleration value from the sensor.
*/
/*!
\fn QAccelerationSensor::currentYAcceleration() const
Returns the current y acceleration value from the sensor.
*/
/*!
\fn QAccelerationSensor::currentZAcceleration() const
Returns the current z acceleration value from the sensor.
*/
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>//STL
//Native
#include <windows.h>
#include <psapi.h>
#include <tlhelp32.h>
//Qt
#include <QtCore>
//Project
#include "functions.h"
bool isSubPath(const QString& dir, const QString& path)
{
if (dir.isEmpty())
return false;
QString nativeDir = QDir::toNativeSeparators(dir);
QString nativePath = QDir::toNativeSeparators(path);
if (nativeDir.lastIndexOf(QDir::separator()) != nativeDir.size() - 1) {
nativeDir += QDir::separator();
}
return !nativePath.indexOf(nativeDir, Qt::CaseInsensitive);
}
bool getModulesListFromProcessID(int PID, QList<QString>& modules)
{
auto w2s = [](const wchar_t* str) {
return QString::fromWCharArray( str );
};
MODULEENTRY32 me32;
me32.dwSize = sizeof(MODULEENTRY32);
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID);
if (hSnap != NULL) {
if (Module32First(hSnap, &me32)) {
while (Module32Next(hSnap, &me32)) {
modules.append(w2s(me32.szExePath));
}
CloseHandle(hSnap);
return true;
}
CloseHandle(hSnap);
return false;
}
return false;
}
bool getProcessList(QList<ProcessInfo>& list)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
return false;
if (Process32First(hProcessSnap, &pe32)) {
do {
QString tmpName = QString::fromWCharArray(pe32.szExeFile);
qint32 tmpPID = pe32.th32ProcessID;
list.append({ tmpName, tmpPID });
} while (Process32Next(hProcessSnap, &pe32));
CloseHandle(hProcessSnap);
return true;
}
CloseHandle(hProcessSnap);
return false;
}
QString getFilePathFromPID(int PID)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
if (hProcess == 0)
return QString();
wchar_t bufPath[MAX_PATH + 1]{};
DWORD result = GetModuleFileNameEx(hProcess, NULL, bufPath, MAX_PATH);
CloseHandle(hProcess);
if (result == 0)
return QString();
return QString::fromWCharArray(bufPath);
}
qint64 getPIDFromHWND(qintptr hWnd)
{
DWORD tmpPID{};
GetWindowThreadProcessId(reinterpret_cast<HWND>(hWnd), &tmpPID);
return tmpPID;
}
qintptr getHWindowFromPoint(const QPoint& point)
{
POINT tmpPoint = { point.x(), point.y() };
HWND tmpHWnd = WindowFromPoint(tmpPoint);
return reinterpret_cast<qintptr>(tmpHWnd);
}
QString getWinDir()
{
return QString(qgetenv("WINDIR"));
}
QString findPathQt()
{
//Ищем в параметрах среды
const wchar_t* QT_CORE_FILE = L"Qt5Core.dll";
DWORD nBufferLength = 255;
wchar_t lpBuffer[nBufferLength];
bool findEnv = SearchPath(NULL,
QT_CORE_FILE,
NULL,
nBufferLength,
(LPWSTR)&lpBuffer,
NULL);
if (findEnv) {
QString tmp = QString::fromWCharArray(lpBuffer);
QDir dir(tmp);
dir.cdUp();
dir.cdUp();
return dir.absolutePath();
} else {
}
//Ищем в реестре
QString regKey = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\";
QSettings uninstall(regKey, QSettings::NativeFormat);
QStringList qtKeys = uninstall.childGroups().filter("Qt ");
QString qtPath;
if (!qtKeys.isEmpty()) {
regKey.append(qtKeys.first());
qtPath = QSettings(regKey, QSettings::NativeFormat).value("InstallLocation").toString();
}
//Ищем в директории Qt
const QString QT_LOG_FILE = "InstallationLog.txt";
if (!qtPath.isEmpty()) {
QFile qtLog(qtPath + QDir::separator() + QT_LOG_FILE);
qtLog.open(QFile::ReadOnly);
QString strLog = qtLog.readAll();
QString var1 = "qtenv2.bat";
int qtenv2 = strLog.indexOf(var1);
QString var2 = "arguments: ";
int arguments = strLog.indexOf(var2, qtenv2 - 100);
arguments += var2.size();
QString tmp = strLog.mid(arguments, qtenv2 - arguments);
QDir dir(tmp);
dir.cdUp();
return dir.absolutePath();
}
return QString();
}
<commit_msg>Обновление.<commit_after>//STL
//Native
#include <windows.h>
#include <psapi.h>
#include <tlhelp32.h>
//Qt
#include <QtCore>
//Project
#include "functions.h"
bool isSubPath(const QString& dir, const QString& path)
{
if (dir.isEmpty())
return false;
QString nativeDir = QDir::toNativeSeparators(dir);
QString nativePath = QDir::toNativeSeparators(path);
if (nativeDir.lastIndexOf(QDir::separator()) != nativeDir.size() - 1) {
nativeDir += QDir::separator();
}
return !nativePath.indexOf(nativeDir, Qt::CaseInsensitive);
}
bool getModulesListFromProcessID(int PID, QList<QString>& modules)
{
auto w2s = [](const wchar_t* str) {
return QString::fromWCharArray( str );
};
MODULEENTRY32 me32;
me32.dwSize = sizeof(MODULEENTRY32);
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID);
if (hSnap != NULL) {
if (Module32First(hSnap, &me32)) {
while (Module32Next(hSnap, &me32)) {
modules.append(w2s(me32.szExePath));
}
CloseHandle(hSnap);
return true;
}
CloseHandle(hSnap);
return false;
}
return false;
}
bool getProcessList(QList<ProcessInfo>& list)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
return false;
if (Process32First(hProcessSnap, &pe32)) {
do {
QString tmpName = QString::fromWCharArray(pe32.szExeFile);
qint32 tmpPID = pe32.th32ProcessID;
list.append({ tmpName, tmpPID });
} while (Process32Next(hProcessSnap, &pe32));
CloseHandle(hProcessSnap);
return true;
}
CloseHandle(hProcessSnap);
return false;
}
QString getFilePathFromPID(int PID)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
if (hProcess == 0)
return QString();
wchar_t bufPath[MAX_PATH + 1]{};
DWORD result = GetModuleFileNameEx(hProcess, NULL, bufPath, MAX_PATH);
CloseHandle(hProcess);
if (result == 0)
return QString();
return QString::fromWCharArray(bufPath);
}
qint64 getPIDFromHWND(qintptr hWnd)
{
DWORD tmpPID{};
GetWindowThreadProcessId(reinterpret_cast<HWND>(hWnd), &tmpPID);
return tmpPID;
}
qintptr getHWindowFromPoint(const QPoint& point)
{
POINT tmpPoint = { point.x(), point.y() };
HWND tmpHWnd = WindowFromPoint(tmpPoint);
return reinterpret_cast<qintptr>(tmpHWnd);
}
QString getWinDir()
{
return QString(qgetenv("WINDIR"));
}
QString findPathQt()
{
//Ищем в параметрах среды
const wchar_t* QT_CORE_FILE = L"Qt5Core.dll";
const DWORD nBufferLength = 255;
wchar_t lpBuffer[nBufferLength];
bool findEnv = SearchPath(NULL,
QT_CORE_FILE,
NULL,
nBufferLength,
(LPWSTR)&lpBuffer,
NULL);
if (findEnv) {
QString tmp = QString::fromWCharArray(lpBuffer);
QDir dir(tmp);
dir.cdUp();
dir.cdUp();
return dir.absolutePath();
} else {
}
//Ищем в реестре
QString regKey = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\";
QSettings uninstall(regKey, QSettings::NativeFormat);
QStringList qtKeys = uninstall.childGroups().filter("Qt ");
QString qtPath;
if (!qtKeys.isEmpty()) {
regKey.append(qtKeys.first());
qtPath = QSettings(regKey, QSettings::NativeFormat).value("InstallLocation").toString();
}
//Ищем в директории Qt
const QString QT_LOG_FILE = "InstallationLog.txt";
if (!qtPath.isEmpty()) {
QFile qtLog(qtPath + QDir::separator() + QT_LOG_FILE);
qtLog.open(QFile::ReadOnly);
QString strLog = qtLog.readAll();
QString var1 = "qtenv2.bat";
int qtenv2 = strLog.indexOf(var1);
QString var2 = "arguments: ";
int arguments = strLog.indexOf(var2, qtenv2 - 100);
arguments += var2.size();
QString tmp = strLog.mid(arguments, qtenv2 - arguments);
QDir dir(tmp);
dir.cdUp();
return dir.absolutePath();
}
return QString();
}
<|endoftext|> |
<commit_before>#include "pe.h"
const unsigned char Pe::header_magic[] = { 'M', 'Z' };
size_t Pe::Leanify(size_t size_leanified /*= 0*/)
{
uint32_t pe_header = *(uint32_t *)(fp + 0x3C);
// check PE signature: PE00
if (pe_header < size && *(uint32_t *)(fp + pe_header) != 0x00004550)
{
std::cout << "Not a PE file." << std::endl;
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, size);
}
return size;
}
ImageFileHeader *pimage_file_header = (ImageFileHeader *)(fp + pe_header + 4);
// 0x0001: IMAGE_FILE_RELOCS_STRIPPED
// 0x2000: IMAGE_FILE_DLL
// only remove reloc section when both bit are not set
if (!(pimage_file_header->Characteristics & 0x0001) && !(pimage_file_header->Characteristics & 0x2000))
{
// set IMAGE_FILE_RELOCS_STRIPPED
pimage_file_header->Characteristics |= 0x0001;
char *optional_header = (char *)pimage_file_header + sizeof(ImageFileHeader);
// Data Directories
// PE32: Magic number: 0x10B Offset: 0x60
// PE32+: Magic number: 0x20B Offset: 0x70
char *data_directories = optional_header + (*(uint16_t *)optional_header == 0x10B ? 0x60 : 0x70);
// Base Relocation Table VirtualAddress
uint32_t reloc_virtual_address = *(uint32_t *)(data_directories + 0x28);
*(uint32_t *)(data_directories + 0x28) = 0;
// Base Relocation Table Size
*(uint32_t *)(data_directories + 0x2C) = 0;
// Section Table
ImageSectionHeader *section_table = (ImageSectionHeader *)(optional_header + pimage_file_header->SizeOfOptionalHeader);
uint32_t reloc_raw_offset = 0;
uint32_t reloc_raw_size = 0;
for (int i = 0; i < pimage_file_header->NumberOfSections; i++)
{
if (section_table[i].VirtualAddress == reloc_virtual_address)
{
reloc_raw_offset = section_table[i].PointerToRawData;
reloc_raw_size = section_table[i].SizeOfRawData;
pimage_file_header->NumberOfSections--;
// move sections after reloc forward
memmove(§ion_table[i], §ion_table[i + 1], sizeof(ImageSectionHeader) * (pimage_file_header->NumberOfSections - i));
// fill the last section with 0
memset(§ion_table[pimage_file_header->NumberOfSections], 0, sizeof(ImageSectionHeader));
break;
}
}
// decrease SizeOfImage
*(uint32_t *)(optional_header + 0x38) -= reloc_raw_size;
for (int i = 0; i < pimage_file_header->NumberOfSections; i++)
{
if (section_table[i].PointerToRawData > reloc_raw_offset)
{
section_table[i].PointerToRawData -= reloc_raw_size;
}
}
// move everything before reloc
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, reloc_raw_offset);
}
// move everything after reloc
size -= reloc_raw_size;
memmove(fp + reloc_raw_offset, fp + size_leanified + reloc_raw_offset + reloc_raw_size, size - reloc_raw_offset);
}
else
{
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, size);
}
}
return size;
}
<commit_msg>PE: fix if SizeOfRawData of .reloc is not multiple of SectionAlignment<commit_after>#include "pe.h"
const unsigned char Pe::header_magic[] = { 'M', 'Z' };
size_t Pe::Leanify(size_t size_leanified /*= 0*/)
{
uint32_t pe_header = *(uint32_t *)(fp + 0x3C);
// check PE signature: PE00
if (pe_header < size && *(uint32_t *)(fp + pe_header) != 0x00004550)
{
std::cout << "Not a PE file." << std::endl;
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, size);
}
return size;
}
ImageFileHeader *pimage_file_header = (ImageFileHeader *)(fp + pe_header + 4);
// 0x0001: IMAGE_FILE_RELOCS_STRIPPED
// 0x2000: IMAGE_FILE_DLL
// only remove reloc section when both bit are not set
if (!(pimage_file_header->Characteristics & 0x0001) && !(pimage_file_header->Characteristics & 0x2000))
{
// set IMAGE_FILE_RELOCS_STRIPPED
pimage_file_header->Characteristics |= 0x0001;
char *optional_header = (char *)pimage_file_header + sizeof(ImageFileHeader);
// Data Directories
// PE32: Magic number: 0x10B Offset: 0x60
// PE32+: Magic number: 0x20B Offset: 0x70
char *data_directories = optional_header + (*(uint16_t *)optional_header == 0x10B ? 0x60 : 0x70);
// Base Relocation Table VirtualAddress
uint32_t reloc_virtual_address = *(uint32_t *)(data_directories + 0x28);
*(uint32_t *)(data_directories + 0x28) = 0;
// Base Relocation Table Size
*(uint32_t *)(data_directories + 0x2C) = 0;
// Section Table
ImageSectionHeader *section_table = (ImageSectionHeader *)(optional_header + pimage_file_header->SizeOfOptionalHeader);
uint32_t reloc_raw_offset = 0;
uint32_t reloc_raw_size = 0;
for (int i = 0; i < pimage_file_header->NumberOfSections; i++)
{
if (section_table[i].VirtualAddress == reloc_virtual_address)
{
reloc_raw_offset = section_table[i].PointerToRawData;
reloc_raw_size = section_table[i].SizeOfRawData;
pimage_file_header->NumberOfSections--;
// move sections after reloc forward
memmove(§ion_table[i], §ion_table[i + 1], sizeof(ImageSectionHeader) * (pimage_file_header->NumberOfSections - i));
// fill the last section with 0
memset(§ion_table[pimage_file_header->NumberOfSections], 0, sizeof(ImageSectionHeader));
break;
}
}
// decrease SizeOfImage
*(uint32_t *)(optional_header + 0x38) -= reloc_raw_size;
// make it multiple of SectionAlignment
*(uint32_t *)(optional_header + 0x38) &= ~(*(uint32_t *)(optional_header + 0x20) - 1);
// set ASLR in DllCharacteristics to false
// it seems this isn't necessary
// *(uint16_t *)(optional_header + 0x46) &= ~0x0040;
for (int i = 0; i < pimage_file_header->NumberOfSections; i++)
{
if (section_table[i].PointerToRawData > reloc_raw_offset)
{
section_table[i].PointerToRawData -= reloc_raw_size;
}
}
// move everything before reloc
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, reloc_raw_offset);
}
// move everything after reloc
size -= reloc_raw_size;
memmove(fp + reloc_raw_offset, fp + size_leanified + reloc_raw_offset + reloc_raw_size, size - reloc_raw_offset);
}
else
{
if (size_leanified)
{
fp -= size_leanified;
memmove(fp, fp + size_leanified, size);
}
}
return size;
}
<|endoftext|> |
<commit_before>#ifndef GF2_UTIL_HPP
#define GF2_UTIL_HPP
#include <vector>
#include "Eigen/Dense"
#include "opencv2/core/core.hpp"
namespace GF2 {
namespace util {
template <typename Scalar>
inline ::cv::Point3f
hsv2rgb( ::cv::Point3_<Scalar> const& in )
{
double hh, p, q, t, ff;
long i;
::cv::Point3f out;
if ( in.y <= 0.f ) // < is bogus, just shuts up warnings
{
out.x = in.z;
out.y = in.z;
out.z = in.z;
return out;
}
hh = in.x;
if ( hh >= 360.f ) hh = 0.f;
hh /= 60.f;
i = (long)hh;
ff = hh - i;
p = in.z * (1.f - in.y);
q = in.z * (1.f - (in.y * ff));
t = in.z * (1.f - (in.y * (1.f - ff)));
switch(i) {
case 0:
out.x = in.z;
out.y = t;
out.z = p;
break;
case 1:
out.x = q;
out.y = in.z;
out.z = p;
break;
case 2:
out.x = p;
out.y = in.z;
out.z = t;
break;
case 3:
out.x = p;
out.y = q;
out.z = in.z;
break;
case 4:
out.x = t;
out.y = p;
out.z = in.z;
break;
case 5:
default:
out.x = in.z;
out.y = p;
out.z = q;
break;
}
return out;
}
// generates n different colours
// assumes hue [0, 360), saturation [0, 100), lightness [0, 100)
template <typename Scalar>
inline std::vector< ::cv::Point3f >
nColoursCv(int n, Scalar scale, bool random_shuffle )
{
std::vector< ::cv::Point3f > out;
//srand(time(NULL));
float step = 360. / n;
for ( int i = 0; i < n; ++i )
{
::cv::Point3f c;
c.x = i * step; // hue
c.y = (90.f + rand()/(float)RAND_MAX * 10.f) / 100.f; // saturation
c.z = (50.f + rand()/(float)RAND_MAX * 50.f) / 100.f; // value
// convert and store
out.push_back( hsv2rgb(c) * scale );
}
if ( random_shuffle )
std::random_shuffle( out.begin(), out.end() );
return out;
}
template <typename Scalar>
inline std::vector< ::Eigen::Vector3f >
nColoursEigen( int n, Scalar scale, bool random_shuffle )
{
typedef std::vector< ::cv::Point3f > CvPointsT;
CvPointsT colours = nColoursCv( n, scale, random_shuffle );
std::vector< ::Eigen::Vector3f > colours_eigen;
//for ( CvPointsT::value_type const& colour : colours )
for ( CvPointsT::const_iterator it = colours.begin(); it != colours.end(); ++it )
{
//colours_eigen.push_back( (Eigen::Vector3f() << colour.x, colour.y, colour.z).finished() );
colours_eigen.push_back( (Eigen::Vector3f() << it->x, it->y, it->z).finished() );
}
return colours_eigen;
}
inline std::string timestamp2Str()
{
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time ( &rawtime );
timeinfo = localtime (&rawtime);
strftime ( buffer, 80, "_%Y%m%d_%H%M", timeinfo );
return std::string( buffer );
} //...timestamp2Str()
inline int parseIteration( std::string const& input_prims_path )
{
int iteration = 0;
size_t it_loc = input_prims_path.find("_it");
if ( it_loc == std::string::npos )
iteration = -1;
else
{
iteration = atoi( input_prims_path.substr( it_loc+3,1 ).c_str() );
}
return iteration;
}
} //...namespace util
} //...namespace GF2
#endif // GF2_UTIL_HPP
<commit_msg>util.hpp colour min value and min saturation options added<commit_after>#ifndef GF2_UTIL_HPP
#define GF2_UTIL_HPP
#include <vector>
#include "Eigen/Dense"
#include "opencv2/core/core.hpp"
namespace GF2 {
namespace util {
template <typename Scalar>
inline ::cv::Point3f
hsv2rgb( ::cv::Point3_<Scalar> const& in )
{
double hh, p, q, t, ff;
long i;
::cv::Point3f out;
if ( in.y <= 0.f ) // < is bogus, just shuts up warnings
{
out.x = in.z;
out.y = in.z;
out.z = in.z;
return out;
}
hh = in.x;
if ( hh >= 360.f ) hh = 0.f;
hh /= 60.f;
i = (long)hh;
ff = hh - i;
p = in.z * (1.f - in.y);
q = in.z * (1.f - (in.y * ff));
t = in.z * (1.f - (in.y * (1.f - ff)));
switch(i) {
case 0:
out.x = in.z;
out.y = t;
out.z = p;
break;
case 1:
out.x = q;
out.y = in.z;
out.z = p;
break;
case 2:
out.x = p;
out.y = in.z;
out.z = t;
break;
case 3:
out.x = p;
out.y = q;
out.z = in.z;
break;
case 4:
out.x = t;
out.y = p;
out.z = in.z;
break;
case 5:
default:
out.x = in.z;
out.y = p;
out.z = q;
break;
}
return out;
}
// generates n different colours
// assumes hue [0, 360), saturation [0, 100), lightness [0, 100)
template <typename Scalar>
inline std::vector< ::cv::Point3f >
nColoursCv(int n, Scalar scale, bool random_shuffle, float min_value = 50.f, float min_saturation = 90.f )
{
std::vector< ::cv::Point3f > out;
//srand(time(NULL));
float step = 360. / n;
const float saturation_rest = 100.f - min_saturation;
const float value_rest = 100.f - min_value;
for ( int i = 0; i < n; ++i )
{
::cv::Point3f c;
c.x = i * step; // hue
c.y = (min_saturation + rand()/(float)RAND_MAX * saturation_rest) / 100.f; // saturation
c.z = (min_value + rand()/(float)RAND_MAX * value_rest ) / 100.f; // value
// convert and store
out.push_back( hsv2rgb(c) * scale );
}
if ( random_shuffle )
std::random_shuffle( out.begin(), out.end() );
return out;
}
template <typename Scalar>
inline std::vector< ::Eigen::Vector3f >
nColoursEigen( int n, Scalar scale, bool random_shuffle )
{
typedef std::vector< ::cv::Point3f > CvPointsT;
CvPointsT colours = nColoursCv( n, scale, random_shuffle );
std::vector< ::Eigen::Vector3f > colours_eigen;
//for ( CvPointsT::value_type const& colour : colours )
for ( CvPointsT::const_iterator it = colours.begin(); it != colours.end(); ++it )
{
//colours_eigen.push_back( (Eigen::Vector3f() << colour.x, colour.y, colour.z).finished() );
colours_eigen.push_back( (Eigen::Vector3f() << it->x, it->y, it->z).finished() );
}
return colours_eigen;
}
inline std::string timestamp2Str()
{
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time ( &rawtime );
timeinfo = localtime (&rawtime);
strftime ( buffer, 80, "_%Y%m%d_%H%M", timeinfo );
return std::string( buffer );
} //...timestamp2Str()
inline int parseIteration( std::string const& input_prims_path )
{
int iteration = 0;
size_t it_loc = input_prims_path.find("_it");
if ( it_loc == std::string::npos )
iteration = -1;
else
{
iteration = atoi( input_prims_path.substr( it_loc+3,1 ).c_str() );
}
return iteration;
}
} //...namespace util
} //...namespace GF2
#endif // GF2_UTIL_HPP
<|endoftext|> |
<commit_before>/*
* Main Send File Transfer Window
*
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* 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 "mainwindow.h"
#include "ui_mainwindow.h"
#include <KFileItem>
#include <KFileItemList>
#include <KIO/PreviewJob>
#include <KApplication>
#include <KCmdLineArgs>
#include <KMimeType>
#include <KDebug>
#include <QAbstractItemDelegate>
#include <QPainter>
#include <QRect>
#include <QStyle>
#include <QDebug>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/PendingReady>
#include "accounts-model.h"
#include "flat-model-proxy.h"
#include "account-filter-model.h"
#include "contact-model-item.h"
//FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler.
#define PREFERRED_FILETRANSFER_HANDLER "org.freedesktop.Telepathy.Client.KDE.FileTransfer"
class ContactGridDelegate : public QAbstractItemDelegate {
public:
ContactGridDelegate(QObject *parent);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
ContactGridDelegate::ContactGridDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
}
void ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyle *style = QApplication::style();
int textHeight = option.fontMetrics.height()*2;
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);
QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight);
QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3);
QPixmap avatar = index.data(Qt::DecorationRole).value<QPixmap>();
if (avatar.isNull()) {
avatar = KIcon("im-user-online").pixmap(QSize(70,70));
}
//resize larger avatars
if (avatar.width() > 80 || avatar.height()> 80) {
avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio);
//draw leaving paddings on smaller (or non square) avatars
}
style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar);
QTextOption textOption;
textOption.setAlignment(Qt::AlignCenter);
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
painter->drawText(textRect, index.data().toString(), textOption);
}
QSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
int textHeight = option.fontMetrics.height()*2;
return QSize(80,80+textHeight+3);
}
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWindow),
m_accountsModel(0)
{
Tp::registerTypes();
ui->setupUi(this);
kDebug() << KApplication::arguments();
KUrl filePath (KCmdLineArgs::parsedArgs()->arg(0));
ui->filePreview->showPreview(filePath);
ui->fileNameLabel->setText(filePath.fileName());
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore
<< Tp::Account::FeatureAvatar
<< Tp::Account::FeatureProtocolInfo
<< Tp::Account::FeatureProfile);
Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Connection::FeatureCore
<< Tp::Connection::FeatureRosterGroups
<< Tp::Connection::FeatureRoster
<< Tp::Connection::FeatureSelfContact);
Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias
<< Tp::Contact::FeatureAvatarData
<< Tp::Contact::FeatureSimplePresence
<< Tp::Contact::FeatureCapabilities);
Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());
m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory);
connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));
connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted()));
connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onAccountManagerReady()
{
m_accountsModel = new AccountsModel(m_accountManager, this);
AccountFilterModel *filterModel = new AccountFilterModel(this);
filterModel->setSourceModel(m_accountsModel);
filterModel->filterOfflineUsers(true);
FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel);
ui->listView->setModel(flatProxyModel);
ui->listView->setItemDelegate(new ContactGridDelegate(this));
}
void MainWindow::onDialogAccepted()
{
// don't do anytghing if no contact has been selected
if (!ui->listView->currentIndex().isValid()) {
// show message box?
return;
}
ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value<ContactModelItem*>();
Tp::ContactPtr contact = contactModelItem->contact();
Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem);
if (sendingAccount.isNull()) {
kDebug() << "sending account: NULL";
} else {
kDebug() << "Account is: " << sendingAccount->displayName();
kDebug() << "sending to: " << contact->alias();
}
// start sending file
QString filePath (KCmdLineArgs::parsedArgs()->arg(0));
qDebug() << "FILE TO SEND: " << filePath;
Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name());
Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact,
fileTransferProperties,
QDateTime::currentDateTime(),
PREFERRED_FILETRANSFER_HANDLER);
connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*)));
}
void MainWindow::slotFileTransferFinished(Tp::PendingOperation* op)
{
if (op->isError()) {
//FIXME map to human readable strings.
QString errorMsg(op->errorName() + ": " + op->errorMessage());
kDebug() << "ERROR!: " << errorMsg;
} else {
kDebug() << "Transfer started";
// now I can close the dialog
close();
}
}
<commit_msg>disable buttons after file transfer attempt started<commit_after>/*
* Main Send File Transfer Window
*
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* 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 "mainwindow.h"
#include "ui_mainwindow.h"
#include <KFileItem>
#include <KFileItemList>
#include <KIO/PreviewJob>
#include <KApplication>
#include <KCmdLineArgs>
#include <KMimeType>
#include <KDebug>
#include <KMessageBox>
#include <QAbstractItemDelegate>
#include <QPainter>
#include <QRect>
#include <QStyle>
#include <QDebug>
#include <QAbstractButton>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/PendingReady>
#include "accounts-model.h"
#include "flat-model-proxy.h"
#include "account-filter-model.h"
#include "contact-model-item.h"
//FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler.
#define PREFERRED_FILETRANSFER_HANDLER "org.freedesktop.Telepathy.Client.KDE.FileTransfer"
class ContactGridDelegate : public QAbstractItemDelegate {
public:
ContactGridDelegate(QObject *parent);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
ContactGridDelegate::ContactGridDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
}
void ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyle *style = QApplication::style();
int textHeight = option.fontMetrics.height()*2;
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);
QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight);
QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3);
QPixmap avatar = index.data(Qt::DecorationRole).value<QPixmap>();
if (avatar.isNull()) {
avatar = KIcon("im-user-online").pixmap(QSize(70,70));
}
//resize larger avatars
if (avatar.width() > 80 || avatar.height()> 80) {
avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio);
//draw leaving paddings on smaller (or non square) avatars
}
style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar);
QTextOption textOption;
textOption.setAlignment(Qt::AlignCenter);
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
painter->drawText(textRect, index.data().toString(), textOption);
}
QSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
int textHeight = option.fontMetrics.height()*2;
return QSize(80,80+textHeight+3);
}
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWindow),
m_accountsModel(0)
{
Tp::registerTypes();
ui->setupUi(this);
kDebug() << KApplication::arguments();
KUrl filePath (KCmdLineArgs::parsedArgs()->arg(0));
ui->filePreview->showPreview(filePath);
ui->fileNameLabel->setText(filePath.fileName());
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore
<< Tp::Account::FeatureAvatar
<< Tp::Account::FeatureProtocolInfo
<< Tp::Account::FeatureProfile);
Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Connection::FeatureCore
<< Tp::Connection::FeatureRosterGroups
<< Tp::Connection::FeatureRoster
<< Tp::Connection::FeatureSelfContact);
Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias
<< Tp::Contact::FeatureAvatarData
<< Tp::Contact::FeatureSimplePresence
<< Tp::Contact::FeatureCapabilities);
Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());
m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory);
connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));
connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted()));
connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onAccountManagerReady()
{
m_accountsModel = new AccountsModel(m_accountManager, this);
AccountFilterModel *filterModel = new AccountFilterModel(this);
filterModel->setSourceModel(m_accountsModel);
filterModel->filterOfflineUsers(true);
FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel);
ui->listView->setModel(flatProxyModel);
ui->listView->setItemDelegate(new ContactGridDelegate(this));
}
void MainWindow::onDialogAccepted()
{
// don't do anytghing if no contact has been selected
if (!ui->listView->currentIndex().isValid()) {
// show message box?
return;
}
ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value<ContactModelItem*>();
Tp::ContactPtr contact = contactModelItem->contact();
Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem);
if (sendingAccount.isNull()) {
kDebug() << "sending account: NULL";
} else {
kDebug() << "Account is: " << sendingAccount->displayName();
kDebug() << "sending to: " << contact->alias();
}
// start sending file
QString filePath (KCmdLineArgs::parsedArgs()->arg(0));
qDebug() << "FILE TO SEND: " << filePath;
Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name());
Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact,
fileTransferProperties,
QDateTime::currentDateTime(),
PREFERRED_FILETRANSFER_HANDLER);
connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*)));
//disable the buttons
foreach(QAbstractButton* button, ui->buttonBox->buttons()) {
button->setEnabled(false);
}
}
void MainWindow::slotFileTransferFinished(Tp::PendingOperation* op)
{
if (op->isError()) {
//FIXME map to human readable strings.
QString errorMsg(op->errorName() + ": " + op->errorMessage());
kDebug() << "ERROR!: " << errorMsg;
KMessageBox::error(this, i18n("Failed to send file"), i18n("File Transfer Failed"));
close();
} else {
kDebug() << "Transfer started";
// now I can close the dialog
close();
}
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "listworker.h"
#include <QMessageBox>
#include <QDebug>
#include <string>
#include <QList>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
showComputers();
showConnections();
showScientists();
populateDropdownMenus();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showScientists()
{
ui->table_scientist->clear();
ui->table_scientist->setHorizontalHeaderItem(0,new QTableWidgetItem("Name"));
ui->table_scientist->setHorizontalHeaderItem(1,new QTableWidgetItem("Gender"));
ui->table_scientist->setHorizontalHeaderItem(2,new QTableWidgetItem("Birth"));
ui->table_scientist->setHorizontalHeaderItem(3,new QTableWidgetItem("Death"));
ui->table_scientist->setHorizontalHeaderItem(4,new QTableWidgetItem("Comment"));
ui->table_scientist->setRowCount(list.personsSize());
ui->table_scientist->setColumnCount(5);
for(int i = 0; i < list.personsSize(); i++)
{
int birth = list.getScientistBirth(i);
int death = list.getScientistDeath(i);
QString qname = QString::fromStdString(list.getScientistName(i));
QString qgender = QChar(list.getScientistGender(i));
QString qbirth = QString::number(birth);
QString qdeath = QString::number(death);
QString qcomment = QString::fromStdString(list.getScientistComment(i));
ui->table_scientist->setItem(i,0,new QTableWidgetItem(qname));
ui->table_scientist->setItem(i,1,new QTableWidgetItem(qgender));
ui->table_scientist->setItem(i,2,new QTableWidgetItem(qbirth));
ui->table_scientist->setItem(i,3,new QTableWidgetItem(qdeath));
ui->table_scientist->setItem(i,4,new QTableWidgetItem(qcomment));
}
ui->table_scientist->resizeColumnsToContents();
}
void MainWindow::showComputers()
{
ui->table_computer->clear();
ui->table_computer->setHorizontalHeaderItem(0,new QTableWidgetItem("Name"));
ui->table_computer->setHorizontalHeaderItem(1,new QTableWidgetItem("Type"));
ui->table_computer->setHorizontalHeaderItem(2,new QTableWidgetItem("Date"));
ui->table_computer->setHorizontalHeaderItem(3,new QTableWidgetItem("Wasitbuilt"));
ui->table_computer->setRowCount(list.computerSize());
ui->table_computer->setColumnCount(4);
for(int i = 0; i < list.computerSize(); i++)
{
int date = list.getComputerDate(i);
QString qname = QString::fromStdString(list.getComputerName(i));
QString qtype = QString::fromStdString(list.getComputerType(i));
QString qdate = QString::number(date);
QString qwasitbuilt = QString::fromStdString(list.getComputerWasItBuilt(i));
ui->table_computer->setItem(i,0,new QTableWidgetItem(qname));
ui->table_computer->setItem(i,1,new QTableWidgetItem(qtype));
ui->table_computer->setItem(i,2,new QTableWidgetItem(qdate));
ui->table_computer->setItem(i,3,new QTableWidgetItem(qwasitbuilt));
}
ui->table_computer->resizeColumnsToContents();
}
void MainWindow::showConnections()
{
list.sortConnections("1"); //þegar sort verður lagfært þá verður þetta kannski fært.
ui->table_connections->clear();
ui->table_connections->setHorizontalHeaderItem(0,new QTableWidgetItem("SciName"));
ui->table_connections->setHorizontalHeaderItem(1,new QTableWidgetItem("CompName"));
ui->table_connections->setRowCount(list.getLinkOutputSize());
ui->table_connections->setColumnCount(2);
for(int i = 0; i < list.getLinkOutputSize(); i++)
{
QString qsciname = QString::fromStdString(list.getLinkOutputSciName(i));
QString qcompname = QString::fromStdString(list.getLinkOutputCompName(i));
ui->table_connections->setItem(i,0,new QTableWidgetItem(qsciname));
ui->table_connections->setItem(i,1,new QTableWidgetItem(qcompname));
}
ui->table_connections->resizeColumnsToContents();
}
/*
void MainWindow::on_button_computers_clicked()
{
ui->tableWidget->clear();
ui->tableWidget->setRowCount(list.computerSize());
ui->tableWidget->setColumnCount(4);
ui->listWidget->clear();
for(int i = 0; i < list.computerSize(); i++)
{
int date = listWorker.getComputerDate(i);
QString qname = QString::fromStdString(list.getComputerName(i));
QString qdate = QString::number(date);
QString qtype = QString::fromStdString(list.getComputerType(i));
QString qbuilt = QString::fromStdString(list.getComputerWasItBuilt(i));
ui->listWidget->addItem(QString::fromStdString(list.getScientistName(i)));
ui->tableWidget->setItem(i,0,new QTableWidgetItem(qname));
ui->tableWidget->setItem(i,1,new QTableWidgetItem(qdate));
ui->tableWidget->setItem(i,2,new QTableWidgetItem(qtype));
ui->tableWidget->setItem(i,3,new QTableWidgetItem(qbuilt));
}
ui->tableWidget->resizeColumnsToContents();
}
*/
void MainWindow::on_dropdown_scientist_activated(const QString &arg1)
{
QMessageBox::information(this, "Item Selection",
ui->dropdown_scientist->currentText());
}
void MainWindow::populateDropdownMenus()
{
ui->dropdown_scientist->addItem("Name");
ui->dropdown_scientist->addItem("Gender");
ui->dropdown_scientist->addItem("Birth");
ui->dropdown_scientist->addItem("Death");
ui->dropdown_computer->addItem("Name");
ui->dropdown_computer->addItem("Type");
ui->dropdown_computer->addItem("Year");
ui->dropdown_connections->addItem("Scientist");
ui->dropdown_connections->addItem("Computer");
}
<commit_msg>smá breyting á console glugga<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "listworker.h"
#include <QMessageBox>
#include <QDebug>
#include <string>
#include <QList>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
showComputers();
showConnections();
showScientists();
populateDropdownMenus();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showScientists()
{
ui->table_scientist->clear();
ui->table_scientist->setHorizontalHeaderItem(0,new QTableWidgetItem("Name"));
ui->table_scientist->setHorizontalHeaderItem(1,new QTableWidgetItem("Gender"));
ui->table_scientist->setHorizontalHeaderItem(2,new QTableWidgetItem("Birth"));
ui->table_scientist->setHorizontalHeaderItem(3,new QTableWidgetItem("Death"));
ui->table_scientist->setHorizontalHeaderItem(4,new QTableWidgetItem("Comment"));
ui->table_scientist->setRowCount(list.personsSize());
ui->table_scientist->setColumnCount(5);
for(int i = 0; i < list.personsSize(); i++)
{
int birth = list.getScientistBirth(i);
int death = list.getScientistDeath(i);
QString qname = QString::fromStdString(list.getScientistName(i));
QString qgender = QChar(list.getScientistGender(i));
QString qbirth = QString::number(birth);
QString qdeath = QString::number(death);
QString qcomment = QString::fromStdString(list.getScientistComment(i));
ui->table_scientist->setItem(i,0,new QTableWidgetItem(qname));
ui->table_scientist->setItem(i,1,new QTableWidgetItem(qgender));
ui->table_scientist->setItem(i,2,new QTableWidgetItem(qbirth));
ui->table_scientist->setItem(i,3,new QTableWidgetItem(qdeath));
ui->table_scientist->setItem(i,4,new QTableWidgetItem(qcomment));
}
ui->table_scientist->resizeColumnsToContents();
}
void MainWindow::showComputers()
{
ui->table_computer->clear();
ui->table_computer->setHorizontalHeaderItem(0,new QTableWidgetItem("Name"));
ui->table_computer->setHorizontalHeaderItem(1,new QTableWidgetItem("Type"));
ui->table_computer->setHorizontalHeaderItem(2,new QTableWidgetItem("Date"));
ui->table_computer->setHorizontalHeaderItem(3,new QTableWidgetItem("Was it built"));
ui->table_computer->setRowCount(list.computerSize());
ui->table_computer->setColumnCount(4);
for(int i = 0; i < list.computerSize(); i++)
{
int date = list.getComputerDate(i);
QString qname = QString::fromStdString(list.getComputerName(i));
QString qtype = QString::fromStdString(list.getComputerType(i));
QString qdate = QString::number(date);
QString qwasitbuilt = QString::fromStdString(list.getComputerWasItBuilt(i));
ui->table_computer->setItem(i,0,new QTableWidgetItem(qname));
ui->table_computer->setItem(i,1,new QTableWidgetItem(qtype));
ui->table_computer->setItem(i,2,new QTableWidgetItem(qdate));
ui->table_computer->setItem(i,3,new QTableWidgetItem(qwasitbuilt));
}
ui->table_computer->resizeColumnsToContents();
}
void MainWindow::showConnections()
{
list.sortConnections("1"); //þegar sort verður lagfært þá verður þetta kannski fært.
ui->table_connections->clear();
ui->table_connections->setHorizontalHeaderItem(0,new QTableWidgetItem("SciName"));
ui->table_connections->setHorizontalHeaderItem(1,new QTableWidgetItem("CompName"));
ui->table_connections->setRowCount(list.getLinkOutputSize());
ui->table_connections->setColumnCount(2);
for(int i = 0; i < list.getLinkOutputSize(); i++)
{
QString qsciname = QString::fromStdString(list.getLinkOutputSciName(i));
QString qcompname = QString::fromStdString(list.getLinkOutputCompName(i));
ui->table_connections->setItem(i,0,new QTableWidgetItem(qsciname));
ui->table_connections->setItem(i,1,new QTableWidgetItem(qcompname));
}
ui->table_connections->resizeColumnsToContents();
}
/*
void MainWindow::on_button_computers_clicked()
{
ui->tableWidget->clear();
ui->tableWidget->setRowCount(list.computerSize());
ui->tableWidget->setColumnCount(4);
ui->listWidget->clear();
for(int i = 0; i < list.computerSize(); i++)
{
int date = listWorker.getComputerDate(i);
QString qname = QString::fromStdString(list.getComputerName(i));
QString qdate = QString::number(date);
QString qtype = QString::fromStdString(list.getComputerType(i));
QString qbuilt = QString::fromStdString(list.getComputerWasItBuilt(i));
ui->listWidget->addItem(QString::fromStdString(list.getScientistName(i)));
ui->tableWidget->setItem(i,0,new QTableWidgetItem(qname));
ui->tableWidget->setItem(i,1,new QTableWidgetItem(qdate));
ui->tableWidget->setItem(i,2,new QTableWidgetItem(qtype));
ui->tableWidget->setItem(i,3,new QTableWidgetItem(qbuilt));
}
ui->tableWidget->resizeColumnsToContents();
}
*/
void MainWindow::on_dropdown_scientist_activated(const QString &arg1)
{
QMessageBox::information(this, "Item Selection",
ui->dropdown_scientist->currentText());
}
void MainWindow::populateDropdownMenus()
{
ui->dropdown_scientist->addItem("Name");
ui->dropdown_scientist->addItem("Gender");
ui->dropdown_scientist->addItem("Birth");
ui->dropdown_scientist->addItem("Death");
ui->dropdown_computer->addItem("Name");
ui->dropdown_computer->addItem("Type");
ui->dropdown_computer->addItem("Year");
ui->dropdown_connections->addItem("Scientist");
ui->dropdown_connections->addItem("Computer");
}
<|endoftext|> |
<commit_before>#include <QFileDialog>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include <QTimer>
#include "canvaswidget.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_QuitOnClose);
setWindowState(windowState() | Qt::WindowMaximized);
setWindowTitle(appName());
QActionGroup* modeActionGroup = new QActionGroup(this);
setEtalonAction = new QAction(QIcon(":/pictures/etalon.png"), QString::fromUtf8("Задание эталона"), modeActionGroup);
measureSegmentLengthAction = new QAction(QIcon(":/pictures/segment_length.png"), QString::fromUtf8("Измерение длин отрезков"), modeActionGroup);
measurePolylineLengthAction = new QAction(QIcon(":/pictures/polyline_length.png"), QString::fromUtf8("Измерение длин кривых"), modeActionGroup);
measureClosedPolylineLengthAction = new QAction(QIcon(":/pictures/closed_polyline_length.png"), QString::fromUtf8("Измерение длин замкнутых кривых"), modeActionGroup);
measureRectangleAreaAction = new QAction(QIcon(":/pictures/rectangle_area.png"), QString::fromUtf8("Измерение площадей прямоугольников"), modeActionGroup);
measurePolygonAreaAction = new QAction(QIcon(":/pictures/polygon_area.png"), QString::fromUtf8("Измерение площадей многоугольников"), modeActionGroup);
toggleRulerAction = new QAction(QIcon(":/pictures/toggle_ruler.png"), QString::fromUtf8("Показать/скрыть масштабную линейку"), this);
aboutAction = new QAction(QIcon(":/pictures/about.png"), QString::fromUtf8("О программе"), this);
foreach (QAction* action, modeActionGroup->actions())
action->setCheckable(true);
setEtalonAction->setChecked(true);
toggleRulerAction->setCheckable(true);
toggleRulerAction->setChecked(true);
ui->mainToolBar->addActions(modeActionGroup->actions());
ui->mainToolBar->addAction(toggleRulerAction);
ui->mainToolBar->addAction(aboutAction);
ui->mainToolBar->setIconSize(QSize(32, 32));
ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);
setMeasurementEnabled(false);
QList<QByteArray> supportedFormatsList = QImageReader::supportedImageFormats();
QString supportedFormatsString;
foreach (const QByteArray& format, supportedFormatsList)
supportedFormatsString += "*." + QString(format).toLower() + " ";
QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8("Укажите путь к изображению — ") + appName(),
QString(), QString::fromUtf8("Все изображения (%1)").arg(supportedFormatsString));
if (imageFile.isEmpty()) {
QTimer::singleShot(0, this, SLOT(close()));
return;
}
QPixmap* image = new QPixmap;
if (!image->load(imageFile)) {
QMessageBox::warning(this, appName(), QString::fromUtf8("Не могу открыть изображение \"%1\".").arg(imageFile));
delete image;
QTimer::singleShot(0, this, SLOT(close()));
return;
}
QFont statusBarFont = ui->statusBar->font();
int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; // In contrast to ``labelFont.pointSize()'' it always works
statusBarFont.setPointSize(newSize);
ui->statusBar->setFont(statusBarFont);
QLabel* scaleLabel = new QLabel(this);
QLabel* statusLabel = new QLabel(this);
ui->statusBar->addPermanentWidget(scaleLabel);
ui->statusBar->addWidget(statusLabel);
canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);
ui->containingScrollArea->setBackgroundRole(QPalette::Dark);
ui->containingScrollArea->setWidget(canvasWidget);
connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));
connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));
canvasWidget->toggleRuler(toggleRulerAction->isChecked());
}
MainWindow::~MainWindow()
{
delete ui;
}
QString MainWindow::appName() const
{
return "AreaMeasurement";
}
void MainWindow::setMode(Mode newMode)
{
canvasWidget->setMode(newMode);
}
void MainWindow::setMeasurementEnabled(bool state)
{
measureSegmentLengthAction ->setEnabled(state);
measurePolylineLengthAction ->setEnabled(state);
measureClosedPolylineLengthAction->setEnabled(state);
measureRectangleAreaAction ->setEnabled(state);
measurePolygonAreaAction ->setEnabled(state);
}
void MainWindow::updateMode(QAction* modeAction)
{
if (modeAction == setEtalonAction)
return setMode(SET_ETALON);
if (modeAction == measureSegmentLengthAction)
return setMode(MEASURE_SEGMENT_LENGTH);
if (modeAction == measurePolylineLengthAction)
return setMode(MEASURE_POLYLINE_LENGTH);
if (modeAction == measureClosedPolylineLengthAction)
return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);
if (modeAction == measureRectangleAreaAction)
return setMode(MEASURE_RECTANGLE_AREA);
if (modeAction == measurePolygonAreaAction)
return setMode(MEASURE_POLYGON_AREA);
abort();
}
void MainWindow::showAbout()
{
QString aboutText = QString::fromUtf8("Программа %1 предназначена для измерения длин и площадей объектов на чертежах, картах и пр.\n\n"
"Автор — Матвеякин Андрей.\n\n"
"Программа распространяется свободно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения."
).arg(appName());
QMessageBox::about(this, QString::fromUtf8("О программе %1").arg(appName()), aboutText);
}
<commit_msg>Add toolbar separators<commit_after>#include <QFileDialog>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include <QTimer>
#include "canvaswidget.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_QuitOnClose);
setWindowState(windowState() | Qt::WindowMaximized);
setWindowTitle(appName());
QActionGroup* modeActionGroup = new QActionGroup(this);
setEtalonAction = new QAction(QIcon(":/pictures/etalon.png"), QString::fromUtf8("Задание эталона"), modeActionGroup);
measureSegmentLengthAction = new QAction(QIcon(":/pictures/segment_length.png"), QString::fromUtf8("Измерение длин отрезков"), modeActionGroup);
measurePolylineLengthAction = new QAction(QIcon(":/pictures/polyline_length.png"), QString::fromUtf8("Измерение длин кривых"), modeActionGroup);
measureClosedPolylineLengthAction = new QAction(QIcon(":/pictures/closed_polyline_length.png"), QString::fromUtf8("Измерение длин замкнутых кривых"), modeActionGroup);
measureRectangleAreaAction = new QAction(QIcon(":/pictures/rectangle_area.png"), QString::fromUtf8("Измерение площадей прямоугольников"), modeActionGroup);
measurePolygonAreaAction = new QAction(QIcon(":/pictures/polygon_area.png"), QString::fromUtf8("Измерение площадей многоугольников"), modeActionGroup);
toggleRulerAction = new QAction(QIcon(":/pictures/toggle_ruler.png"), QString::fromUtf8("Показать/скрыть масштабную линейку"), this);
aboutAction = new QAction(QIcon(":/pictures/about.png"), QString::fromUtf8("О программе"), this);
foreach (QAction* action, modeActionGroup->actions())
action->setCheckable(true);
setEtalonAction->setChecked(true);
toggleRulerAction->setCheckable(true);
toggleRulerAction->setChecked(true);
ui->mainToolBar->addActions(modeActionGroup->actions());
ui->mainToolBar->addSeparator();
ui->mainToolBar->addAction(toggleRulerAction);
ui->mainToolBar->addSeparator();
ui->mainToolBar->addAction(aboutAction);
ui->mainToolBar->setIconSize(QSize(32, 32));
ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);
setMeasurementEnabled(false);
QList<QByteArray> supportedFormatsList = QImageReader::supportedImageFormats();
QString supportedFormatsString;
foreach (const QByteArray& format, supportedFormatsList)
supportedFormatsString += "*." + QString(format).toLower() + " ";
QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8("Укажите путь к изображению — ") + appName(),
QString(), QString::fromUtf8("Все изображения (%1)").arg(supportedFormatsString));
if (imageFile.isEmpty()) {
QTimer::singleShot(0, this, SLOT(close()));
return;
}
QPixmap* image = new QPixmap;
if (!image->load(imageFile)) {
QMessageBox::warning(this, appName(), QString::fromUtf8("Не могу открыть изображение \"%1\".").arg(imageFile));
delete image;
QTimer::singleShot(0, this, SLOT(close()));
return;
}
QFont statusBarFont = ui->statusBar->font();
int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; // In contrast to ``labelFont.pointSize()'' it always works
statusBarFont.setPointSize(newSize);
ui->statusBar->setFont(statusBarFont);
QLabel* scaleLabel = new QLabel(this);
QLabel* statusLabel = new QLabel(this);
ui->statusBar->addPermanentWidget(scaleLabel);
ui->statusBar->addWidget(statusLabel);
canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);
ui->containingScrollArea->setBackgroundRole(QPalette::Dark);
ui->containingScrollArea->setWidget(canvasWidget);
connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));
connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));
canvasWidget->toggleRuler(toggleRulerAction->isChecked());
}
MainWindow::~MainWindow()
{
delete ui;
}
QString MainWindow::appName() const
{
return "AreaMeasurement";
}
void MainWindow::setMode(Mode newMode)
{
canvasWidget->setMode(newMode);
}
void MainWindow::setMeasurementEnabled(bool state)
{
measureSegmentLengthAction ->setEnabled(state);
measurePolylineLengthAction ->setEnabled(state);
measureClosedPolylineLengthAction->setEnabled(state);
measureRectangleAreaAction ->setEnabled(state);
measurePolygonAreaAction ->setEnabled(state);
}
void MainWindow::updateMode(QAction* modeAction)
{
if (modeAction == setEtalonAction)
return setMode(SET_ETALON);
if (modeAction == measureSegmentLengthAction)
return setMode(MEASURE_SEGMENT_LENGTH);
if (modeAction == measurePolylineLengthAction)
return setMode(MEASURE_POLYLINE_LENGTH);
if (modeAction == measureClosedPolylineLengthAction)
return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);
if (modeAction == measureRectangleAreaAction)
return setMode(MEASURE_RECTANGLE_AREA);
if (modeAction == measurePolygonAreaAction)
return setMode(MEASURE_POLYGON_AREA);
abort();
}
void MainWindow::showAbout()
{
QString aboutText = QString::fromUtf8("Программа %1 предназначена для измерения длин и площадей объектов на чертежах, картах и пр.\n\n"
"Автор — Матвеякин Андрей.\n\n"
"Программа распространяется свободно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения."
).arg(appName());
QMessageBox::about(this, QString::fromUtf8("О программе %1").arg(appName()), aboutText);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2019 Patrizio Bekerle -- http://www.bekerle.com
*
* 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; version 2 of the License.
*
* 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.
*
* mainwindow.cpp
*
* Example to show the QMarkdownTextEdit widget
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmarkdowntextedit.h"
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QToolBar *toolBar = new QToolBar;
addToolBar(toolBar);
QAction *openAction = new QAction(QIcon::fromTheme("document-open"), tr("Open..."));
openAction->setShortcut(QKeySequence::Open);
connect(openAction, &QAction::triggered, this, &MainWindow::open);
QAction *saveAction = new QAction(QIcon::fromTheme("document-save"), tr("Save"));
saveAction->setShortcut(QKeySequence::Save);
QAction *saveAsAction = new QAction(QIcon::fromTheme("document-save-as"), tr("Save as..."));
saveAsAction->setShortcut(QKeySequence::SaveAs);
QAction *quitAction = new QAction(QIcon::fromTheme("view-close"), tr("Quit"));
quitAction->setShortcut(QKeySequence::Quit);
connect(quitAction, &QAction::triggered, this, &MainWindow::onQuit);
m_loadedContent = ui->textEdit->toPlainText();
toolBar->addActions({openAction, saveAction, saveAsAction, quitAction});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loadFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Failed to open" << filename;
return;
}
m_filename = filename;
m_loadedContent = QString::fromLocal8Bit(file.readAll());
ui->textEdit->setPlainText(m_loadedContent);
}
void MainWindow::saveToFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
qWarning() << "Failed to open" << filename;
return;
}
m_filename = filename;
m_loadedContent = ui->textEdit->toPlainText();
file.write(m_loadedContent.toLocal8Bit());
}
void MainWindow::open()
{
QString filename = QFileDialog::getOpenFileName();
if (filename.isEmpty()) {
return;
}
loadFile(filename);
}
void MainWindow::save()
{
if (!m_filename.isEmpty()) {
saveAs();
return;
}
saveToFile(m_filename);
}
void MainWindow::saveAs()
{
QString filename = QFileDialog::getSaveFileName();
if (filename.isEmpty()) {
return;
}
saveToFile(filename);
}
void MainWindow::onQuit()
{
if (ui->textEdit->toPlainText() != m_loadedContent) {
if (QMessageBox::question(this, tr("Not saved"), tr("Document not saved, sure you want to quit?")) != QMessageBox::Yes) {
return;
}
}
close();
}
<commit_msg>Add missing include<commit_after>/*
* Copyright (c) 2014-2019 Patrizio Bekerle -- http://www.bekerle.com
*
* 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; version 2 of the License.
*
* 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.
*
* mainwindow.cpp
*
* Example to show the QMarkdownTextEdit widget
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmarkdowntextedit.h"
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QAction>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QToolBar *toolBar = new QToolBar;
addToolBar(toolBar);
QAction *openAction = new QAction(QIcon::fromTheme("document-open"), tr("Open..."));
openAction->setShortcut(QKeySequence::Open);
connect(openAction, &QAction::triggered, this, &MainWindow::open);
QAction *saveAction = new QAction(QIcon::fromTheme("document-save"), tr("Save"));
saveAction->setShortcut(QKeySequence::Save);
QAction *saveAsAction = new QAction(QIcon::fromTheme("document-save-as"), tr("Save as..."));
saveAsAction->setShortcut(QKeySequence::SaveAs);
QAction *quitAction = new QAction(QIcon::fromTheme("view-close"), tr("Quit"));
quitAction->setShortcut(QKeySequence::Quit);
connect(quitAction, &QAction::triggered, this, &MainWindow::onQuit);
m_loadedContent = ui->textEdit->toPlainText();
toolBar->addActions({openAction, saveAction, saveAsAction, quitAction});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loadFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Failed to open" << filename;
return;
}
m_filename = filename;
m_loadedContent = QString::fromLocal8Bit(file.readAll());
ui->textEdit->setPlainText(m_loadedContent);
}
void MainWindow::saveToFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
qWarning() << "Failed to open" << filename;
return;
}
m_filename = filename;
m_loadedContent = ui->textEdit->toPlainText();
file.write(m_loadedContent.toLocal8Bit());
}
void MainWindow::open()
{
QString filename = QFileDialog::getOpenFileName();
if (filename.isEmpty()) {
return;
}
loadFile(filename);
}
void MainWindow::save()
{
if (!m_filename.isEmpty()) {
saveAs();
return;
}
saveToFile(m_filename);
}
void MainWindow::saveAs()
{
QString filename = QFileDialog::getSaveFileName();
if (filename.isEmpty()) {
return;
}
saveToFile(filename);
}
void MainWindow::onQuit()
{
if (ui->textEdit->toPlainText() != m_loadedContent) {
if (QMessageBox::question(this, tr("Not saved"), tr("Document not saved, sure you want to quit?")) != QMessageBox::Yes) {
return;
}
}
close();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cgm.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:49:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CGM_HXX_
#define CGM_HXX_
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
// ---------------------------------------------------------------
#undef CGM_USER_BREAKPOINT
#define CGM_IMPORT_CGM 0x00000001
#define CGM_EXPORT_IMPRESS 0x00000100
#define CGM_EXPORT_META 0x00000200
//#define CGM_EXPORT_COMMENT 0x00000400
// ---------------------------------------------------------------
#include <tools/solar.h>
#include <rtl/ustring>
#include <tools/list.hxx>
#include "cgmtypes.hxx"
// ---------------------------------------------------------------
class List;
class Bundle;
class Graphic;
class SvStream;
class CGMChart;
class CGMBitmap;
class CGMOutAct;
class CGMElements;
class BitmapColor;
class GDIMetaFile;
class VirtualDevice;
class CGMBitmapDescriptor;
class CGM
{
friend class CGMChart;
friend class CGMBitmap;
friend class CGMElements;
friend class CGMOutAct;
friend class CGMMetaOutAct;
friend class CGMImpressOutAct;
double mnOutdx; // Ausgabe Groesse in 1/100TH mm
double mnOutdy; // auf das gemappt wird
double mnVDCXadd;
double mnVDCYadd;
double mnVDCXmul;
double mnVDCYmul;
double mnVDCdx;
double mnVDCdy;
double mnXFraction;
double mnYFraction;
sal_Bool mbAngReverse; // AngularDirection
Graphic* mpGraphic; // ifdef CGM_EXPORT_META
SvStream* mpCommentOut; // ifdef CGM_EXPORT_COMMENT
sal_Bool mbStatus;
sal_Bool mbMetaFile;
sal_Bool mbIsFinished;
sal_Bool mbPicture;
sal_Bool mbPictureBody;
sal_Bool mbFigure;
sal_Bool mbFirstOutPut;
sal_uInt32 mnAct4PostReset;
CGMBitmap* mpBitmapInUse;
CGMChart* mpChart; // if sal_True->"SHWSLIDEREC"
// otherwise "BEGINPIC" commands
// controlls page inserting
CGMElements* pElement;
CGMElements* pCopyOfE;
CGMOutAct* mpOutAct;
List maDefRepList;
List maDefRepSizeList;
sal_uInt8* mpSource; // source buffer that is not increased
// ( instead use mnParaCount to index )
sal_uInt32 mnParaSize; // actual parameter size which has been done so far
sal_uInt32 mnActCount; // increased by each action
sal_uInt8* mpBuf; // source stream operation -> then this is allocated for
// the temp input buffer
sal_uInt32 mnMode; // source description
sal_uInt32 mnEscape; //
sal_uInt32 mnElementClass; //
sal_uInt32 mnElementID; //
sal_uInt32 mnElementSize; // full parameter size for the latest action
void ImplCGMInit();
sal_uInt32 ImplGetUI16( sal_uInt32 nAlign = 0 );
sal_uInt8 ImplGetByte( sal_uInt32 nSource, sal_uInt32 nPrecision );
long ImplGetI( sal_uInt32 nPrecision );
sal_uInt32 ImplGetUI( sal_uInt32 nPrecision );
void ImplGetSwitch4( sal_uInt8* pSource, sal_uInt8* pDest );
void ImplGetSwitch8( sal_uInt8* pSource, sal_uInt8* pDest );
double ImplGetFloat( RealPrecision, sal_uInt32 nRealSize );
sal_uInt32 ImplGetBitmapColor( sal_Bool bDirectColor = sal_False );
void ImplSetMapMode();
void ImplMapDouble( double& );
void ImplMapX( double& );
void ImplMapY( double& );
void ImplMapPoint( FloatPoint& );
inline double ImplGetIY();
inline double ImplGetFY();
inline double ImplGetIX();
inline double ImplGetFX();
sal_uInt32 ImplGetPointSize();
void ImplGetPoint( FloatPoint& rFloatPoint, sal_Bool bMap = sal_False );
void ImplGetRectangle( FloatRect&, sal_Bool bMap = sal_False );
void ImplGetRectangleNS( FloatRect& );
void ImplGetVector( double* );
double ImplGetOrientation( FloatPoint& rCenter, FloatPoint& rPoint );
void ImplSwitchStartEndAngle( double& rStartAngle, double& rEndAngle );
sal_Bool ImplGetEllipse( FloatPoint& rCenter, FloatPoint& rRadius, double& rOrientation );
void ImplDefaultReplacement();
void ImplDoClass();
void ImplDoClass0();
void ImplDoClass1();
void ImplDoClass2();
void ImplDoClass3();
void ImplDoClass4();
void ImplDoClass5();
void ImplDoClass6();
void ImplDoClass7();
void ImplDoClass8();
void ImplDoClass9();
void ImplDoClass15();
void ImplDoClass16();
public:
CGM( sal_uInt32 nMode );
~CGM();
CGM( sal_uInt32 nMode, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel );
#ifdef CGM_EXPORT_META
VirtualDevice* mpVirDev;
GDIMetaFile* mpGDIMetaFile;
CGM( sal_uInt32 nMode, Graphic& rGraphic );
#endif
void ImplComment( sal_uInt32, char* );
sal_uInt32 GetBackGroundColor();
sal_Bool IsValid() { return mbStatus; };
sal_Bool IsFinished() { return mbIsFinished; };
sal_Bool Write( sal_uInt8* pSource );
sal_Bool Write( SvStream& rIStm );
friend SvStream& operator>>( SvStream& rOStm, CGM& rCGM );
};
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.4.28); FILE MERGED 2005/11/16 16:42:16 pl 1.4.28.2: #i55991# removed warnings 2005/10/28 09:53:11 sj 1.4.28.1: #i55991# warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cgm.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 21:45:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CGM_HXX_
#define CGM_HXX_
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
// ---------------------------------------------------------------
#undef CGM_USER_BREAKPOINT
#define CGM_IMPORT_CGM 0x00000001
#define CGM_EXPORT_IMPRESS 0x00000100
#define CGM_EXPORT_META 0x00000200
//#define CGM_EXPORT_COMMENT 0x00000400
// ---------------------------------------------------------------
#include <tools/solar.h>
#include <rtl/ustring.hxx>
#include <tools/list.hxx>
#include "cgmtypes.hxx"
// ---------------------------------------------------------------
class List;
class Bundle;
class Graphic;
class SvStream;
class CGMChart;
class CGMBitmap;
class CGMOutAct;
class CGMElements;
class BitmapColor;
class GDIMetaFile;
class VirtualDevice;
class CGMBitmapDescriptor;
class CGM
{
friend class CGMChart;
friend class CGMBitmap;
friend class CGMElements;
friend class CGMOutAct;
friend class CGMMetaOutAct;
friend class CGMImpressOutAct;
double mnOutdx; // Ausgabe Groesse in 1/100TH mm
double mnOutdy; // auf das gemappt wird
double mnVDCXadd;
double mnVDCYadd;
double mnVDCXmul;
double mnVDCYmul;
double mnVDCdx;
double mnVDCdy;
double mnXFraction;
double mnYFraction;
sal_Bool mbAngReverse; // AngularDirection
Graphic* mpGraphic; // ifdef CGM_EXPORT_META
SvStream* mpCommentOut; // ifdef CGM_EXPORT_COMMENT
sal_Bool mbStatus;
sal_Bool mbMetaFile;
sal_Bool mbIsFinished;
sal_Bool mbPicture;
sal_Bool mbPictureBody;
sal_Bool mbFigure;
sal_Bool mbFirstOutPut;
sal_uInt32 mnAct4PostReset;
CGMBitmap* mpBitmapInUse;
CGMChart* mpChart; // if sal_True->"SHWSLIDEREC"
// otherwise "BEGINPIC" commands
// controlls page inserting
CGMElements* pElement;
CGMElements* pCopyOfE;
CGMOutAct* mpOutAct;
List maDefRepList;
List maDefRepSizeList;
sal_uInt8* mpSource; // source buffer that is not increased
// ( instead use mnParaCount to index )
sal_uInt32 mnParaSize; // actual parameter size which has been done so far
sal_uInt32 mnActCount; // increased by each action
sal_uInt8* mpBuf; // source stream operation -> then this is allocated for
// the temp input buffer
sal_uInt32 mnMode; // source description
sal_uInt32 mnEscape; //
sal_uInt32 mnElementClass; //
sal_uInt32 mnElementID; //
sal_uInt32 mnElementSize; // full parameter size for the latest action
void ImplCGMInit();
sal_uInt32 ImplGetUI16( sal_uInt32 nAlign = 0 );
sal_uInt8 ImplGetByte( sal_uInt32 nSource, sal_uInt32 nPrecision );
long ImplGetI( sal_uInt32 nPrecision );
sal_uInt32 ImplGetUI( sal_uInt32 nPrecision );
void ImplGetSwitch4( sal_uInt8* pSource, sal_uInt8* pDest );
void ImplGetSwitch8( sal_uInt8* pSource, sal_uInt8* pDest );
double ImplGetFloat( RealPrecision, sal_uInt32 nRealSize );
sal_uInt32 ImplGetBitmapColor( sal_Bool bDirectColor = sal_False );
void ImplSetMapMode();
void ImplMapDouble( double& );
void ImplMapX( double& );
void ImplMapY( double& );
void ImplMapPoint( FloatPoint& );
inline double ImplGetIY();
inline double ImplGetFY();
inline double ImplGetIX();
inline double ImplGetFX();
sal_uInt32 ImplGetPointSize();
void ImplGetPoint( FloatPoint& rFloatPoint, sal_Bool bMap = sal_False );
void ImplGetRectangle( FloatRect&, sal_Bool bMap = sal_False );
void ImplGetRectangleNS( FloatRect& );
void ImplGetVector( double* );
double ImplGetOrientation( FloatPoint& rCenter, FloatPoint& rPoint );
void ImplSwitchStartEndAngle( double& rStartAngle, double& rEndAngle );
sal_Bool ImplGetEllipse( FloatPoint& rCenter, FloatPoint& rRadius, double& rOrientation );
void ImplDefaultReplacement();
void ImplDoClass();
void ImplDoClass0();
void ImplDoClass1();
void ImplDoClass2();
void ImplDoClass3();
void ImplDoClass4();
void ImplDoClass5();
void ImplDoClass6();
void ImplDoClass7();
void ImplDoClass8();
void ImplDoClass9();
void ImplDoClass15();
void ImplDoClass16();
public:
CGM( sal_uInt32 nMode );
~CGM();
CGM( sal_uInt32 nMode, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel );
#ifdef CGM_EXPORT_META
VirtualDevice* mpVirDev;
GDIMetaFile* mpGDIMetaFile;
CGM( sal_uInt32 nMode, Graphic& rGraphic );
#endif
void ImplComment( sal_uInt32, const char* );
sal_uInt32 GetBackGroundColor();
sal_Bool IsValid() { return mbStatus; };
sal_Bool IsFinished() { return mbIsFinished; };
sal_Bool Write( sal_uInt8* pSource );
sal_Bool Write( SvStream& rIStm );
friend SvStream& operator>>( SvStream& rOStm, CGM& rCGM );
};
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2014, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/lapack-like/Norm/Frobenius.hpp"
#include "elemental/lapack-like/Pseudospectrum.hpp"
#include "elemental/matrices/Grcar.hpp"
#include "elemental/matrices/Lotkin.hpp"
#include "elemental/matrices/Uniform.hpp"
using namespace std;
using namespace elem;
typedef double Real;
typedef Complex<Real> C;
int
main( int argc, char* argv[] )
{
Initialize( argc, argv );
try
{
const Int matType =
Input("--matType","0:uniform,1:Haar,2:Lotkin,3:Grcar",0);
const Int n = Input("--size","height of matrix",100);
const Real realCenter = Input("--realCenter","real center",0.);
const Real imagCenter = Input("--imagCenter","imag center",0.);
Real xWidth = Input("--xWidth","x width of image",0.);
Real yWidth = Input("--yWidth","y width of image",0.);
const Real nx = Input("--nx","num x chunks",2);
const Real ny = Input("--ny","num y chunks",2);
const Int xSize = Input("--xSize","number of x samples",100);
const Int ySize = Input("--ySize","number of y samples",100);
const bool lanczos = Input("--lanczos","use Lanczos?",true);
const bool deflate = Input("--deflate","deflate converged?",true);
const Int maxIts = Input("--maxIts","maximum two-norm iter's",1000);
const Real tol = Input("--tol","tolerance for norm estimates",1e-6);
const bool progress = Input("--progress","print progress?",true);
const bool display = Input("--display","display matrices?",false);
const bool write = Input("--write","write matrices?",false);
const Int formatInt = Input("--format","write format",2);
const Int colorMapInt = Input("--colorMap","color map",0);
ProcessInput();
PrintInputReport();
if( formatInt < 1 || formatInt >= FileFormat_MAX )
LogicError("Invalid file format integer, should be in [1,",
FileFormat_MAX,")");
FileFormat format = static_cast<FileFormat>(formatInt);
ColorMap colorMap = static_cast<ColorMap>(colorMapInt);
SetColorMap( colorMap );
C center(realCenter,imagCenter);
const Grid& g = DefaultGrid();
DistMatrix<C> A(g);
if( matType == 0 )
A = Uniform<C>( g, n, n );
else if( matType == 1 )
A = Haar<C>( g, n );
else if( matType == 2 )
A = Lotkin<C>( g, n );
else
A = Grcar<C>( g, n, 3 );
if( display )
Display( A, "A" );
if( write )
Write( A, "A", format );
// Begin by computing the Schur decomposition
DistMatrix<C> X(g);
DistMatrix<C,VR,STAR> w(g);
schur::SDC( A, w, X );
// Find a window if none is specified
if( xWidth == 0. || yWidth == 0. )
{
const Real radius = MaxNorm( w );
const Real oneNorm = OneNorm( A );
Real width;
if( oneNorm == 0. && radius == 0. )
{
width = 1;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to 1 to handle zero matrix"
<< std::endl;
}
else if( radius >= 0.2*oneNorm )
{
width = 2.5*radius;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to " << width
<< " based on the spectral radius, "
<< radius << std::endl;
}
else
{
width = 0.8*oneNorm;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to " << width
<< " based on the one norm, " << oneNorm
<< std::endl;
}
xWidth = width;
yWidth = width;
}
// Visualize/write the pseudospectrum within each window
DistMatrix<Real> invNormMap(g);
DistMatrix<Int> itCountMap(g);
const Int xBlock = xSize / nx;
const Int yBlock = ySize / ny;
const Int xLeftover = xSize - (nx-1)*xBlock;
const Int yLeftover = ySize - (ny-1)*yBlock;
const Real xStep = xWidth/(xSize-1);
const Real yStep = yWidth/(ySize-1);
const C corner = center - C(xWidth/2,yWidth/2);
for( Int xChunk=0; xChunk<nx; ++xChunk )
{
const Int xChunkSize = ( xChunk==nx-1 ? xLeftover : xBlock );
const Real xChunkWidth = xStep*xChunkSize;
for( Int yChunk=0; yChunk<ny; ++yChunk )
{
const Int yChunkSize = ( yChunk==ny-1 ? yLeftover : yBlock );
const Real yChunkWidth = yStep*yChunkSize;
const C chunkCorner = corner +
C(xStep*xChunk*xBlock,yStep*yChunk*yBlock);
const C chunkCenter = chunkCorner +
0.5*C(xStep*xChunkSize,yStep*yChunkSize);
itCountMap = TriangularPseudospectrum
( A, invNormMap, chunkCenter, xChunkWidth, yChunkWidth,
xChunkSize, yChunkSize, lanczos, deflate, maxIts, tol,
progress );
const Int numIts = MaxNorm( itCountMap );
if( mpi::WorldRank() == 0 )
std::cout << "num iterations=" << numIts << std::endl;
std::ostringstream chunkStream;
chunkStream << "-" << xChunk << "-" << yChunk;
const std::string chunkTag = chunkStream.str();
if( display )
{
Display( invNormMap, "invNormMap"+chunkTag );
Display( itCountMap, "itCountMap"+chunkTag );
}
if( write )
{
Write( invNormMap, "invNormMap"+chunkTag, format );
Write( itCountMap, "itCountMap"+chunkTag, format );
}
// Take the element-wise log
const Int mLocal = invNormMap.LocalHeight();
const Int nLocal = invNormMap.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
invNormMap.SetLocal
( iLoc, jLoc, Log(invNormMap.GetLocal(iLoc,jLoc)) );
if( display )
{
Display( invNormMap, "logInvNormMap"+chunkTag );
if( GetColorMap() != GRAYSCALE_DISCRETE )
{
auto colorMap = GetColorMap();
SetColorMap( GRAYSCALE_DISCRETE );
Display( invNormMap, "discreteLogInvNormMap"+chunkTag );
SetColorMap( colorMap );
}
}
if( write )
{
Write( invNormMap, "logInvNormMap"+chunkTag, format );
if( GetColorMap() != GRAYSCALE_DISCRETE )
{
auto colorMap = GetColorMap();
SetColorMap( GRAYSCALE_DISCRETE );
Write
( invNormMap, "discreteLogInvNormMap"+chunkTag,
format );
SetColorMap( colorMap );
}
}
}
}
}
catch( exception& e ) { ReportException(e); }
Finalize();
return 0;
}
<commit_msg>Updating chunked pseudospectrum computation to support Fox-Li matrices.<commit_after>/*
Copyright (c) 2009-2014, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/lapack-like/Norm/Frobenius.hpp"
#include "elemental/lapack-like/Pseudospectrum.hpp"
#include "elemental/matrices/FoxLi.hpp"
#include "elemental/matrices/Grcar.hpp"
#include "elemental/matrices/Lotkin.hpp"
#include "elemental/matrices/Uniform.hpp"
using namespace std;
using namespace elem;
typedef double Real;
typedef Complex<Real> C;
int
main( int argc, char* argv[] )
{
Initialize( argc, argv );
try
{
const Int matType =
Input("--matType","0:uniform,1:Haar,2:Lotkin,3:Grcar,4:FoxLi",4);
const Int n = Input("--size","height of matrix",100);
const Real realCenter = Input("--realCenter","real center",0.);
const Real imagCenter = Input("--imagCenter","imag center",0.);
Real xWidth = Input("--xWidth","x width of image",0.);
Real yWidth = Input("--yWidth","y width of image",0.);
const Real nx = Input("--nx","num x chunks",2);
const Real ny = Input("--ny","num y chunks",2);
const Int xSize = Input("--xSize","number of x samples",100);
const Int ySize = Input("--ySize","number of y samples",100);
const bool lanczos = Input("--lanczos","use Lanczos?",true);
const bool deflate = Input("--deflate","deflate converged?",true);
const Int maxIts = Input("--maxIts","maximum two-norm iter's",1000);
const Real tol = Input("--tol","tolerance for norm estimates",1e-6);
const Int numBands = Input("--numBands","num bands for Grcar",3);
const Real omega = Input("--omega","frequency for Fox-Li",16*M_PI);
const bool progress = Input("--progress","print progress?",true);
const bool display = Input("--display","display matrices?",false);
const bool write = Input("--write","write matrices?",false);
const Int formatInt = Input("--format","write format",2);
const Int colorMapInt = Input("--colorMap","color map",0);
ProcessInput();
PrintInputReport();
if( formatInt < 1 || formatInt >= FileFormat_MAX )
LogicError("Invalid file format integer, should be in [1,",
FileFormat_MAX,")");
FileFormat format = static_cast<FileFormat>(formatInt);
ColorMap colorMap = static_cast<ColorMap>(colorMapInt);
SetColorMap( colorMap );
C center(realCenter,imagCenter);
DistMatrix<C> A;
switch( matType )
{
case 0: Uniform( A, n, n ); break;
case 1: Haar( A, n ); break;
case 2: Lotkin( A, n ); break;
case 3: Grcar( A, n, numBands ); break;
case 4: FoxLi( A, n, omega ); break;
default: LogicError("Invalid matrix type");
}
if( display )
Display( A, "A" );
if( write )
Write( A, "A", format );
// Begin by computing the Schur decomposition
DistMatrix<C> X;
DistMatrix<C,VR,STAR> w;
schur::SDC( A, w, X );
// Find a window if none is specified
if( xWidth == 0. || yWidth == 0. )
{
const Real radius = MaxNorm( w );
const Real oneNorm = OneNorm( A );
Real width;
if( oneNorm == 0. && radius == 0. )
{
width = 1;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to 1 to handle zero matrix"
<< std::endl;
}
else if( radius >= 0.2*oneNorm )
{
width = 2.5*radius;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to " << width
<< " based on the spectral radius, "
<< radius << std::endl;
}
else
{
width = 0.8*oneNorm;
if( mpi::WorldRank() == 0 )
std::cout << "Setting width to " << width
<< " based on the one norm, " << oneNorm
<< std::endl;
}
xWidth = width;
yWidth = width;
}
// Visualize/write the pseudospectrum within each window
DistMatrix<Real> invNormMap;
DistMatrix<Int> itCountMap;
const Int xBlock = xSize / nx;
const Int yBlock = ySize / ny;
const Int xLeftover = xSize - (nx-1)*xBlock;
const Int yLeftover = ySize - (ny-1)*yBlock;
const Real xStep = xWidth/(xSize-1);
const Real yStep = yWidth/(ySize-1);
const C corner = center - C(xWidth/2,yWidth/2);
for( Int xChunk=0; xChunk<nx; ++xChunk )
{
const Int xChunkSize = ( xChunk==nx-1 ? xLeftover : xBlock );
const Real xChunkWidth = xStep*xChunkSize;
for( Int yChunk=0; yChunk<ny; ++yChunk )
{
const Int yChunkSize = ( yChunk==ny-1 ? yLeftover : yBlock );
const Real yChunkWidth = yStep*yChunkSize;
const C chunkCorner = corner +
C(xStep*xChunk*xBlock,yStep*yChunk*yBlock);
const C chunkCenter = chunkCorner +
0.5*C(xStep*xChunkSize,yStep*yChunkSize);
itCountMap = TriangularPseudospectrum
( A, invNormMap, chunkCenter, xChunkWidth, yChunkWidth,
xChunkSize, yChunkSize, lanczos, deflate, maxIts, tol,
progress );
const Int numIts = MaxNorm( itCountMap );
if( mpi::WorldRank() == 0 )
std::cout << "num iterations=" << numIts << std::endl;
std::ostringstream chunkStream;
chunkStream << "-" << xChunk << "-" << yChunk;
const std::string chunkTag = chunkStream.str();
if( display )
{
Display( invNormMap, "invNormMap"+chunkTag );
Display( itCountMap, "itCountMap"+chunkTag );
}
if( write )
{
Write( invNormMap, "invNormMap"+chunkTag, format );
Write( itCountMap, "itCountMap"+chunkTag, format );
}
// Take the element-wise log
const Int mLocal = invNormMap.LocalHeight();
const Int nLocal = invNormMap.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
invNormMap.SetLocal
( iLoc, jLoc, Log(invNormMap.GetLocal(iLoc,jLoc)) );
if( display )
{
Display( invNormMap, "logInvNormMap"+chunkTag );
if( GetColorMap() != GRAYSCALE_DISCRETE )
{
auto colorMap = GetColorMap();
SetColorMap( GRAYSCALE_DISCRETE );
Display( invNormMap, "discreteLogInvNormMap"+chunkTag );
SetColorMap( colorMap );
}
}
if( write )
{
Write( invNormMap, "logInvNormMap"+chunkTag, format );
if( GetColorMap() != GRAYSCALE_DISCRETE )
{
auto colorMap = GetColorMap();
SetColorMap( GRAYSCALE_DISCRETE );
Write
( invNormMap, "discreteLogInvNormMap"+chunkTag,
format );
SetColorMap( colorMap );
}
}
}
}
}
catch( exception& e ) { ReportException(e); }
Finalize();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "action_header.h"
#include <algorithm>
#include "../../cryptoplugin/ICryptoFactory.h"
#include "../server_settings.h"
extern ICryptoFactory *crypto_fak;
extern std::string server_token;
namespace
{
bool verify_signature(const std::string& exe_extension, const std::string& basename)
{
if(crypto_fak==NULL)
return false;
#ifdef _WIN32
std::string pubkey_fn="urbackup_ecdsa409k1.pub";
#else
std::string pubkey_fn="urbackup/urbackup_ecdsa409k1.pub";
#endif
std::string p_pubkey_fn = Server->getServerParameter("urbackup_public_key");
if(!p_pubkey_fn.empty())
{
pubkey_fn = p_pubkey_fn;
}
return crypto_fak->verifyFile(pubkey_fn, "urbackup/"+basename+"."+ exe_extension, "urbackup/"+ basename+".sig2");
}
std::string constructClientSettings(Helper& helper, int clientid, const std::string& clientname, const std::string& authkey, const std::string& access_keys)
{
ServerSettings settings(helper.getDatabase(), clientid);
SSettings *settingsptr=settings.getSettings();
std::string ret="\r\n";
ret+="internet_mode_enabled="+convert(settingsptr->internet_mode_enabled)+"\r\n";
ret+="internet_server="+settingsptr->internet_server+"\r\n";
ret+="internet_server_port="+convert(settingsptr->internet_server_port)+"\r\n";
ret += "internet_server_proxy=" + settingsptr->internet_server_proxy + "\r\n";
ret+="internet_authkey="+(authkey.empty() ? settingsptr->internet_authkey : authkey ) +"\r\n";
if(!clientname.empty())
{
ret+="computername="+clientname+"\r\n";
}
if (!access_keys.empty())
{
ret += "access_keys=" + access_keys + "\r\n";
}
return ret;
}
std::string constructImageRestoreSettings(Helper& helper, int backupid, const std::string& restore_authkey, const std::string& token)
{
ServerSettings settings(helper.getDatabase());
SSettings* settingsptr = settings.getSettings();
std::string ret = "RESTORE_IMAGE=1\n";
ret += "SERVER_NAME=\"" + settingsptr->internet_server + "\"\n";
ret += "SERVER_PORT=\"" + convert(settingsptr->internet_server_port) + "\"\n";
ret += "SERVER_PROXY=\"" + settingsptr->internet_server_proxy + "\"\n";
ret += "RESTORE_AUTHKEY=\"" + restore_authkey+ "\"\n";
ret += "RESTORE_TOKEN=\"" + token + "\"\n";
return ret;
}
bool replaceToken(const std::string end_token, const std::string& repl, std::string& data, size_t& offset)
{
for(size_t i=offset;i<data.size();++i)
{
if(next(data, i, end_token) )
{
if(i-offset>repl.size())
{
data.replace(data.begin()+offset, data.begin()+offset+repl.size(), repl.begin(), repl.end());
offset=i+end_token.size();
return true;
}
else
{
Server->Log("Cannot replace, because data is too large", LL_ERROR);
return false;
}
}
}
return false;
}
bool replaceStrings(Helper& helper, const std::string& settings, const std::string& restore_vals, std::string& data)
{
const std::string settings_start_token="#48692563-17e4-4ccb-a078-f14372fdbe20";
const std::string settings_end_token="#6e7f6ba0-8478-4946-b70a-f1c7e83d28cc";
const std::string ident_start_token="#17460620-769b-4add-85aa-a764efe84ab7";
const std::string ident_end_token="#569d42d2-1b40-4745-a426-e86a577c7f1a";
const std::string restore_vals_start_token = "#e1128bd07afd40a0a2752818730589ef";
const std::string restore_vals_end_token = "#902761a5525a4007add0b016a35af985";
bool replaced_settings=false;
bool replaced_ident=false;
bool replaced_restore_vals = false;
if (restore_vals.empty())
{
replaced_restore_vals = true;
}
for(size_t i=0;i<data.size();++i)
{
if(!replaced_settings
&& next(data, i, settings_start_token))
{
i+=settings_start_token.size();
if(!replaceToken(settings_end_token, settings, data, i))
{
return false;
}
replaced_settings=true;
}
if(!replaced_ident
&& next(data, i, ident_start_token))
{
i+=ident_start_token.size();
if(!replaceToken(ident_end_token, "\r\n"+helper.getStrippedServerIdentity()+"\r\n", data, i))
{
return false;
}
replaced_ident=true;
}
if (!replaced_restore_vals
&& next(data, i, restore_vals_start_token))
{
i += restore_vals_start_token.size();
if (!replaceToken(restore_vals_end_token, "\n" + restore_vals + "\n", data, i))
{
return false;
}
replaced_restore_vals = true;
}
if( replaced_ident && replaced_settings && replaced_restore_vals)
return true;
}
return false;
}
}
ACTION_IMPL(download_client)
{
Helper helper(tid, &GET, &PARAMS);
SUser *session=helper.getSession();
if(session!=NULL && session->id==SESSION_ID_INVALID) return;
bool all_client_rights;
std::vector<int> clientids = helper.clientRights(RIGHT_SETTINGS, all_client_rights);
bool all_browse_backups;
std::vector<int> browse_backups_rights = helper.clientRights(RIGHT_BROWSE_BACKUPS, all_browse_backups);
std::string authkey = GET["authkey"];
std::string errstr;
if( !authkey.empty()
|| (session!=NULL && (all_client_rights || !clientids.empty()) ) )
{
std::string restore_vals = "RESTORE_IMAGE=0\n";
if (GET.find("restore_image")!=GET.end())
{
int backupid = watoi(GET["backupid"]);
restore_vals = constructImageRestoreSettings(helper, backupid, GET["authkey"], GET["token"]);
}
helper.releaseAll();
session = NULL;
int clientid=watoi(GET["clientid"]);
if(!authkey.empty() || all_client_rights ||
std::find(clientids.begin(), clientids.end(), clientid)!=clientids.end() )
{
std::string os = GET["os"];
std::string exe_extension = "exe";
std::string basename = "UrBackupUpdate";
if (os == "osx" || os=="mac")
{
exe_extension = "sh";
basename = "UrBackupUpdateMac";
}
else if (os == "linux")
{
exe_extension = "sh";
basename = "UrBackupUpdateLinux";
}
Server->Log("Verifying "+ basename +"."+exe_extension+" signature...", LL_INFO);
if(verify_signature(exe_extension, basename))
{
IQuery *q=helper.getDatabase()->Prepare("SELECT name FROM clients WHERE id=?");
q->Bind(clientid);
db_results res=q->Read();
q->Reset();
std::string clientname;
if(!res.empty())
{
clientname=(res[0]["name"]);
}
std::string access_keys;
if ( all_client_rights || std::find(clientids.begin(), clientids.end(), clientid) != clientids.end() )
{
if (all_browse_backups
|| std::find(browse_backups_rights.begin(), browse_backups_rights.end(), clientid) != browse_backups_rights.end() )
{
if (os == "linux" || os == "osx" || os == "mac")
{
//There is only ~4KB available space. Add only root for now
IQuery* q_root_token = helper.getDatabase()->Prepare("SELECT token FROM user_tokens WHERE username='root' AND tgroup IS NULL AND clientid = ? ORDER BY created DESC");
q_root_token->Bind(clientid);
db_results res_root_token = q_root_token->Read();
q_root_token->Reset();
if (!res_root_token.empty())
{
access_keys = "uroot:" + res_root_token[0]["token"];
}
}
ServerSettings settings(helper.getDatabase(), clientid);
std::string client_access_key = settings.getSettings()->client_access_key;
if (!client_access_key.empty())
{
if (!access_keys.empty())
{
access_keys += ";";
}
access_keys += "t" + server_token + ":" + client_access_key;
}
}
}
std::string data=getFile("urbackup/"+basename+"."+ exe_extension);
if( replaceStrings(helper, constructClientSettings(helper, clientid, clientname, authkey, access_keys), restore_vals, data) )
{
Server->setContentType(tid, "application/octet-stream");
Server->addHeader(tid, "Content-Disposition: attachment; filename=\"UrBackup Client ("+clientname+")."+exe_extension+"\"");
Server->addHeader(tid, "Content-Length: "+convert(data.size()) );
Server->WriteRaw(tid, data.c_str(), data.size(), false);
}
else
{
errstr="Replacing data in install file failed";
}
}
else
{
errstr="Signature verification failed";
}
}
else
{
errstr="No right to download client";
}
}
else
{
errstr="No right to download any client";
}
if(!errstr.empty())
{
Server->Log(errstr, LL_ERROR);
helper.Write("ERROR: "+errstr, false);
}
}<commit_msg>Don't try to set restore settings with windows client<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "action_header.h"
#include <algorithm>
#include "../../cryptoplugin/ICryptoFactory.h"
#include "../server_settings.h"
extern ICryptoFactory *crypto_fak;
extern std::string server_token;
namespace
{
bool verify_signature(const std::string& exe_extension, const std::string& basename)
{
if(crypto_fak==NULL)
return false;
#ifdef _WIN32
std::string pubkey_fn="urbackup_ecdsa409k1.pub";
#else
std::string pubkey_fn="urbackup/urbackup_ecdsa409k1.pub";
#endif
std::string p_pubkey_fn = Server->getServerParameter("urbackup_public_key");
if(!p_pubkey_fn.empty())
{
pubkey_fn = p_pubkey_fn;
}
return crypto_fak->verifyFile(pubkey_fn, "urbackup/"+basename+"."+ exe_extension, "urbackup/"+ basename+".sig2");
}
std::string constructClientSettings(Helper& helper, int clientid, const std::string& clientname, const std::string& authkey, const std::string& access_keys)
{
ServerSettings settings(helper.getDatabase(), clientid);
SSettings *settingsptr=settings.getSettings();
std::string ret="\r\n";
ret+="internet_mode_enabled="+convert(settingsptr->internet_mode_enabled)+"\r\n";
ret+="internet_server="+settingsptr->internet_server+"\r\n";
ret+="internet_server_port="+convert(settingsptr->internet_server_port)+"\r\n";
ret += "internet_server_proxy=" + settingsptr->internet_server_proxy + "\r\n";
ret+="internet_authkey="+(authkey.empty() ? settingsptr->internet_authkey : authkey ) +"\r\n";
if(!clientname.empty())
{
ret+="computername="+clientname+"\r\n";
}
if (!access_keys.empty())
{
ret += "access_keys=" + access_keys + "\r\n";
}
return ret;
}
std::string constructImageRestoreSettings(Helper& helper, int backupid, const std::string& restore_authkey, const std::string& token)
{
ServerSettings settings(helper.getDatabase());
SSettings* settingsptr = settings.getSettings();
std::string ret = "RESTORE_IMAGE=1\n";
ret += "SERVER_NAME=\"" + settingsptr->internet_server + "\"\n";
ret += "SERVER_PORT=\"" + convert(settingsptr->internet_server_port) + "\"\n";
ret += "SERVER_PROXY=\"" + settingsptr->internet_server_proxy + "\"\n";
ret += "RESTORE_AUTHKEY=\"" + restore_authkey+ "\"\n";
ret += "RESTORE_TOKEN=\"" + token + "\"\n";
return ret;
}
bool replaceToken(const std::string end_token, const std::string& repl, std::string& data, size_t& offset)
{
for(size_t i=offset;i<data.size();++i)
{
if(next(data, i, end_token) )
{
if(i-offset>repl.size())
{
data.replace(data.begin()+offset, data.begin()+offset+repl.size(), repl.begin(), repl.end());
offset=i+end_token.size();
return true;
}
else
{
Server->Log("Cannot replace, because data is too large", LL_ERROR);
return false;
}
}
}
return false;
}
bool replaceStrings(Helper& helper, const std::string& settings, const std::string& restore_vals, std::string& data)
{
const std::string settings_start_token="#48692563-17e4-4ccb-a078-f14372fdbe20";
const std::string settings_end_token="#6e7f6ba0-8478-4946-b70a-f1c7e83d28cc";
const std::string ident_start_token="#17460620-769b-4add-85aa-a764efe84ab7";
const std::string ident_end_token="#569d42d2-1b40-4745-a426-e86a577c7f1a";
const std::string restore_vals_start_token = "#e1128bd07afd40a0a2752818730589ef";
const std::string restore_vals_end_token = "#902761a5525a4007add0b016a35af985";
bool replaced_settings=false;
bool replaced_ident=false;
bool replaced_restore_vals = false;
if (restore_vals.empty())
{
replaced_restore_vals = true;
}
for(size_t i=0;i<data.size();++i)
{
if(!replaced_settings
&& next(data, i, settings_start_token))
{
i+=settings_start_token.size();
if(!replaceToken(settings_end_token, settings, data, i))
{
return false;
}
replaced_settings=true;
}
if(!replaced_ident
&& next(data, i, ident_start_token))
{
i+=ident_start_token.size();
if(!replaceToken(ident_end_token, "\r\n"+helper.getStrippedServerIdentity()+"\r\n", data, i))
{
return false;
}
replaced_ident=true;
}
if (!replaced_restore_vals
&& next(data, i, restore_vals_start_token))
{
i += restore_vals_start_token.size();
if (!replaceToken(restore_vals_end_token, "\n" + restore_vals + "\n", data, i))
{
return false;
}
replaced_restore_vals = true;
}
if( replaced_ident && replaced_settings && replaced_restore_vals)
return true;
}
return false;
}
}
ACTION_IMPL(download_client)
{
Helper helper(tid, &GET, &PARAMS);
SUser *session=helper.getSession();
if(session!=NULL && session->id==SESSION_ID_INVALID) return;
bool all_client_rights;
std::vector<int> clientids = helper.clientRights(RIGHT_SETTINGS, all_client_rights);
bool all_browse_backups;
std::vector<int> browse_backups_rights = helper.clientRights(RIGHT_BROWSE_BACKUPS, all_browse_backups);
std::string authkey = GET["authkey"];
std::string errstr;
if( !authkey.empty()
|| (session!=NULL && (all_client_rights || !clientids.empty()) ) )
{
std::string restore_vals = "RESTORE_IMAGE=0\n";
if (GET.find("restore_image")!=GET.end())
{
int backupid = watoi(GET["backupid"]);
restore_vals = constructImageRestoreSettings(helper, backupid, GET["authkey"], GET["token"]);
}
helper.releaseAll();
session = NULL;
int clientid=watoi(GET["clientid"]);
if(!authkey.empty() || all_client_rights ||
std::find(clientids.begin(), clientids.end(), clientid)!=clientids.end() )
{
std::string os = GET["os"];
std::string exe_extension = "exe";
std::string basename = "UrBackupUpdate";
if (os == "osx" || os=="mac")
{
exe_extension = "sh";
basename = "UrBackupUpdateMac";
}
else if (os == "linux")
{
exe_extension = "sh";
basename = "UrBackupUpdateLinux";
}
else
{
restore_vals.clear();
}
Server->Log("Verifying "+ basename +"."+exe_extension+" signature...", LL_INFO);
if(verify_signature(exe_extension, basename))
{
IQuery *q=helper.getDatabase()->Prepare("SELECT name FROM clients WHERE id=?");
q->Bind(clientid);
db_results res=q->Read();
q->Reset();
std::string clientname;
if(!res.empty())
{
clientname=(res[0]["name"]);
}
std::string access_keys;
if ( all_client_rights || std::find(clientids.begin(), clientids.end(), clientid) != clientids.end() )
{
if (all_browse_backups
|| std::find(browse_backups_rights.begin(), browse_backups_rights.end(), clientid) != browse_backups_rights.end() )
{
if (os == "linux" || os == "osx" || os == "mac")
{
//There is only ~4KB available space. Add only root for now
IQuery* q_root_token = helper.getDatabase()->Prepare("SELECT token FROM user_tokens WHERE username='root' AND tgroup IS NULL AND clientid = ? ORDER BY created DESC");
q_root_token->Bind(clientid);
db_results res_root_token = q_root_token->Read();
q_root_token->Reset();
if (!res_root_token.empty())
{
access_keys = "uroot:" + res_root_token[0]["token"];
}
}
ServerSettings settings(helper.getDatabase(), clientid);
std::string client_access_key = settings.getSettings()->client_access_key;
if (!client_access_key.empty())
{
if (!access_keys.empty())
{
access_keys += ";";
}
access_keys += "t" + server_token + ":" + client_access_key;
}
}
}
std::string data=getFile("urbackup/"+basename+"."+ exe_extension);
if( replaceStrings(helper, constructClientSettings(helper, clientid, clientname, authkey, access_keys), restore_vals, data) )
{
Server->setContentType(tid, "application/octet-stream");
Server->addHeader(tid, "Content-Disposition: attachment; filename=\"UrBackup Client ("+clientname+")."+exe_extension+"\"");
Server->addHeader(tid, "Content-Length: "+convert(data.size()) );
Server->WriteRaw(tid, data.c_str(), data.size(), false);
}
else
{
errstr="Replacing data in install file failed";
}
}
else
{
errstr="Signature verification failed";
}
}
else
{
errstr="No right to download client";
}
}
else
{
errstr="No right to download any client";
}
if(!errstr.empty())
{
Server->Log(errstr, LL_ERROR);
helper.Write("ERROR: "+errstr, false);
}
}<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2022 Project CHIP 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 "DeviceInstanceInfoProviderImpl.h"
#include <platform/CHIPDeviceConfig.h>
#include <platform/CHIPDeviceError.h>
#include <platform/android/AndroidConfig.h>
#include <platform/internal/GenericDeviceInstanceInfoProvider.ipp>
namespace chip {
namespace DeviceLayer {
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetHardwareVersionString(char * buf, size_t bufSize)
{
CHIP_ERROR err;
size_t hardwareVersionLen = 0; // without counting null-terminator
err = Internal::AndroidConfig::ReadConfigValueStr(Internal::AndroidConfig::kConfigKey_HardwareVersionString, buf, bufSize,
hardwareVersionLen);
if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL);
strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING);
}
return err;
}
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetProductId(uint16_t & productId)
{
productId = static_cast<uint16_t>(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID);
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetProductName(char * buf, size_t bufSize)
{
ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL);
strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME);
return CHIP_NO_ERROR;
}
} // namespace DeviceLayer
} // namespace chip
<commit_msg>[android] Fixed getting product id and product name (#20208)<commit_after>/*
*
* Copyright (c) 2022 Project CHIP 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 "DeviceInstanceInfoProviderImpl.h"
#include <platform/CHIPDeviceConfig.h>
#include <platform/CHIPDeviceError.h>
#include <platform/android/AndroidConfig.h>
#include <platform/internal/GenericDeviceInstanceInfoProvider.ipp>
namespace chip {
namespace DeviceLayer {
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetHardwareVersionString(char * buf, size_t bufSize)
{
CHIP_ERROR err;
size_t hardwareVersionLen = 0; // without counting null-terminator
err = Internal::AndroidConfig::ReadConfigValueStr(Internal::AndroidConfig::kConfigKey_HardwareVersionString, buf, bufSize,
hardwareVersionLen);
if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL);
strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING);
}
return err;
}
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetProductId(uint16_t & productId)
{
CHIP_ERROR err;
uint32_t u32ProductId = 0;
err = Internal::AndroidConfig::ReadConfigValue(Internal::AndroidConfig::kConfigKey_ProductId, u32ProductId);
if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
productId = static_cast<uint16_t>(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID);
}
else
{
productId = static_cast<uint16_t>(u32ProductId);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceInstanceInfoProviderImpl::GetProductName(char * buf, size_t bufSize)
{
CHIP_ERROR err;
size_t productNameSize = 0; // without counting null-terminator
err =
Internal::AndroidConfig::ReadConfigValueStr(Internal::AndroidConfig::kConfigKey_ProductName, buf, bufSize, productNameSize);
if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL);
strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME);
}
return CHIP_NO_ERROR;
}
} // namespace DeviceLayer
} // namespace chip
<|endoftext|> |
<commit_before>// ======================================================================
#include "TemplateFactory.h"
#include <boost/filesystem/operations.hpp>
#include <boost/make_shared.hpp>
#include <spine/Exception.h>
namespace SmartMet
{
namespace Plugin
{
namespace Dali
{
// ----------------------------------------------------------------------
/*!
* \brief Get a thread specific template formatter for given template
*/
// ----------------------------------------------------------------------
SharedFormatter TemplateFactory::get(const boost::filesystem::path& theFilename) const
{
try
{
if (theFilename.empty())
throw Spine::Exception(BCP, "TemplateFactory: Cannot use empty templates");
TemplateMap* tmap = itsTemplates.get();
// tmap is thread specific and hence safe to use without locking
if (tmap == nullptr)
{
tmap = new TemplateMap;
itsTemplates.reset(tmap);
}
// Find out if there is a formatter which is up to date
auto& info = (*tmap)[theFilename];
std::time_t modtime = boost::filesystem::last_write_time(theFilename);
// We assume there are no templates with modtime=0
if (info.modtime == modtime)
return info.formatter;
// Initialize a new formatter and return it
info.modtime = modtime;
info.formatter = boost::make_shared<Fmi::TemplateFormatter>();
info.formatter->load_template(theFilename.c_str());
return info.formatter;
}
catch (...)
{
throw Spine::Exception::Trace(BCP, "Operation failed!");
}
}
} // namespace Dali
} // namespace Plugin
} // namespace SmartMet
<commit_msg>Fixed TemplateFactory to cache the template formatters<commit_after>// ======================================================================
#include "TemplateFactory.h"
#include <boost/filesystem/operations.hpp>
#include <boost/make_shared.hpp>
#include <spine/Exception.h>
namespace SmartMet
{
namespace Plugin
{
namespace Dali
{
// ----------------------------------------------------------------------
/*!
* \brief Get a thread specific template formatter for given template
*/
// ----------------------------------------------------------------------
SharedFormatter TemplateFactory::get(const boost::filesystem::path& theFilename) const
{
try
{
if (theFilename.empty())
throw Spine::Exception(BCP, "TemplateFactory: Cannot use empty templates");
// Make sure thread specific map is initialized
if (itsTemplates.get() == nullptr)
itsTemplates.reset(new TemplateMap);
// Find out if there is a formatter which is up to date
auto& tmap = *itsTemplates;
const auto& tinfo = tmap.find(theFilename);
const std::time_t modtime = boost::filesystem::last_write_time(theFilename);
// Use cached template if it is up to date
if (tinfo != tmap.end())
if (tinfo->second.modtime == modtime)
return tinfo->second.formatter;
// Initialize a new formatter
TemplateInfo newinfo;
newinfo.modtime = modtime;
newinfo.formatter = boost::make_shared<Fmi::TemplateFormatter>();
newinfo.formatter->load_template(theFilename.c_str());
// Cache the new formatter
tmap.insert(std::make_pair(theFilename, newinfo));
return newinfo.formatter;
}
catch (...)
{
throw Spine::Exception::Trace(BCP, "Operation failed!");
}
}
} // namespace Dali
} // namespace Plugin
} // namespace SmartMet
<|endoftext|> |
<commit_before>#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
// include the call which creates the shadowed subgraph.
#include "CreateShadowedScene.h"
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createBase(const osg::Vec3& center,float radius)
{
osg::Geode* geode = new osg::Geode;
// set up the texture of the base.
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
geode->setStateSet( stateset );
osg::Grid* grid = new osg::Grid;
grid->allocateGrid(38,39);
grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
grid->setXInterval(radius*2.0f/(float)(38-1));
grid->setYInterval(radius*2.0f/(float)(39-1));
float minHeight = FLT_MAX;
float maxHeight = -FLT_MAX;
unsigned int r;
for(r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
float h = vertex[r+c*39][2];
if (h>maxHeight) maxHeight=h;
if (h<minHeight) minHeight=h;
}
}
float hieghtScale = radius*0.5f/(maxHeight-minHeight);
float hieghtOffset = -(minHeight+maxHeight)*0.5f;
for(r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
float h = vertex[r+c*39][2];
grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
}
}
geode->addDrawable(new osg::ShapeDrawable(grid));
osg::Group* group = new osg::Group;
group->addChild(geode);
return group;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
positioned->addChild(cessna);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
model->addChild(xform);
}
return model;
}
osg::Node* createModel()
{
osg::Vec3 center(0.0f,0.0f,0.0f);
float radius = 100.0f;
osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
// the shadower model
osg::Node* shadower = createMovingModel(center,radius*0.5f);
// the shadowed model
osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
// combine the models together to create one which has the shadower and the shadowed with the required callback.
osg::Group* root = createShadowedScene(shadower,shadowed,lightPosition,radius/100.0f,1);
return root;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load the nodes from the commandline arguments.
osg::Node* model = createModel();
if (!model)
{
return 1;
}
// comment out optimization over the scene graph right now as it optimizers away the shadow... will look into this..
//osgUtil::Optimizer optimzer;
//optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData( model );
// create the windows and run the threads.
viewer.realize(Producer::CameraGroup::ThreadPerCamera);
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Removed the output of command line usage when no arguments are passed since this example doens't need paramters.<commit_after>#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
// include the call which creates the shadowed subgraph.
#include "CreateShadowedScene.h"
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createBase(const osg::Vec3& center,float radius)
{
osg::Geode* geode = new osg::Geode;
// set up the texture of the base.
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
geode->setStateSet( stateset );
osg::Grid* grid = new osg::Grid;
grid->allocateGrid(38,39);
grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
grid->setXInterval(radius*2.0f/(float)(38-1));
grid->setYInterval(radius*2.0f/(float)(39-1));
float minHeight = FLT_MAX;
float maxHeight = -FLT_MAX;
unsigned int r;
for(r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
float h = vertex[r+c*39][2];
if (h>maxHeight) maxHeight=h;
if (h<minHeight) minHeight=h;
}
}
float hieghtScale = radius*0.5f/(maxHeight-minHeight);
float hieghtOffset = -(minHeight+maxHeight)*0.5f;
for(r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
float h = vertex[r+c*39][2];
grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
}
}
geode->addDrawable(new osg::ShapeDrawable(grid));
osg::Group* group = new osg::Group;
group->addChild(geode);
return group;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
positioned->addChild(cessna);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
model->addChild(xform);
}
return model;
}
osg::Node* createModel()
{
osg::Vec3 center(0.0f,0.0f,0.0f);
float radius = 100.0f;
osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
// the shadower model
osg::Node* shadower = createMovingModel(center,radius*0.5f);
// the shadowed model
osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
// combine the models together to create one which has the shadower and the shadowed with the required callback.
osg::Group* root = createShadowedScene(shadower,shadowed,lightPosition,radius/100.0f,1);
return root;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// load the nodes from the commandline arguments.
osg::Node* model = createModel();
if (!model)
{
return 1;
}
// comment out optimization over the scene graph right now as it optimizers away the shadow... will look into this..
//osgUtil::Optimizer optimzer;
//optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData( model );
// create the windows and run the threads.
viewer.realize(Producer::CameraGroup::ThreadPerCamera);
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: galobj.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:37:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_GALOBJ_HXX_
#define _SVX_GALOBJ_HXX_
#include <tools/urlobj.hxx>
#include <vcl/graph.hxx>
// -----------
// - Defines -
// -----------
#define S_THUMB 80
// -----------------------------------------------------------------------------
#define SGA_FORMAT_NONE 0x00000000L
#define SGA_FORMAT_STRING 0x00000001L
#define SGA_FORMAT_GRAPHIC 0x00000010L
#define SGA_FORMAT_SOUND 0x00000100L
#define SGA_FORMAT_OLE 0x00001000L
#define SGA_FORMAT_SVDRAW 0x00010000L
#define SGA_FORMAT_ALL 0xFFFFFFFFL
// --------------
// - SgaObjKind -
// --------------
enum SgaObjKind
{
SGA_OBJ_NONE = 0, // Abstraktes Objekt
SGA_OBJ_BMP = 1, // Bitmap-Objekt
SGA_OBJ_SOUND = 2, // Sound-Objekt
SGA_OBJ_VIDEO = 3, // Video-Objekt
SGA_OBJ_ANIM = 4, // Animations-Objekt
SGA_OBJ_SVDRAW = 5, // Svdraw-Objekt
SGA_OBJ_INET = 6 // Grafik aus dem Internet
};
// ----------------
// - GalSoundType -
// ----------------
enum GalSoundType
{
SOUND_STANDARD = 0,
SOUND_COMPUTER = 1,
SOUND_MISC = 2,
SOUND_MUSIC = 3,
SOUND_NATURE = 4,
SOUND_SPEECH = 5,
SOUND_TECHNIC = 6,
SOUND_ANIMAL = 7
};
// -------------
// - SgaObject -
// -------------
class SgaObject
{
friend class GalleryTheme;
private:
void ImplUpdateURL( const INetURLObject& rNewURL ) { aURL = rNewURL; }
protected:
Bitmap aThumbBmp;
GDIMetaFile aThumbMtf;
INetURLObject aURL;
String aUserName;
String aTitle;
BOOL bIsValid;
BOOL bIsThumbBmp;
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
BOOL CreateThumb( const Graphic& rGraphic );
public:
SgaObject();
virtual ~SgaObject() {};
virtual SgaObjKind GetObjKind() const = 0;
virtual UINT16 GetVersion() const = 0;
virtual Bitmap GetThumbBmp() const { return aThumbBmp; }
const GDIMetaFile& GetThumbMtf() const { return aThumbMtf; }
const INetURLObject& GetURL() const { return aURL; }
BOOL IsValid() const { return bIsValid; }
BOOL IsThumbBitmap() const { return bIsThumbBmp; }
const String GetTitle() const;
void SetTitle( const String& rTitle );
friend SvStream& operator<<( SvStream& rOut, const SgaObject& rObj );
friend SvStream& operator>>( SvStream& rIn, SgaObject& rObj );
};
// ------------------
// - SgaObjectSound -
// ------------------
class SgaObjectSound : public SgaObject
{
private:
GalSoundType eSoundType;
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 6; }
public:
SgaObjectSound();
SgaObjectSound( const INetURLObject& rURL );
virtual ~SgaObjectSound();
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SOUND; }
virtual Bitmap GetThumbBmp() const;
GalSoundType GetSoundType() const { return eSoundType; }
};
// -------------------
// - SgaObjectSvDraw -
// -------------------
class FmFormModel;
class SgaObjectSvDraw : public SgaObject
{
private:
BOOL CreateThumb( const FmFormModel& rModel );
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 5; }
public:
SgaObjectSvDraw();
SgaObjectSvDraw( const FmFormModel& rModel, const INetURLObject& rURL );
SgaObjectSvDraw( SvStream& rIStm, const INetURLObject& rURL );
virtual ~SgaObjectSvDraw() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SVDRAW; }
public:
static BOOL DrawCentered( OutputDevice* pOut, const FmFormModel& rModel );
};
// ----------------
// - SgaObjectBmp -
// ----------------
class SgaObjectBmp: public SgaObject
{
private:
void Init( const Graphic& rGraphic, const INetURLObject& rURL );
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 5; }
public:
SgaObjectBmp();
SgaObjectBmp( const INetURLObject& rURL );
SgaObjectBmp( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormat );
virtual ~SgaObjectBmp() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_BMP; }
};
// -----------------
// - SgaObjectAnim -
// -----------------
class SgaObjectAnim : public SgaObjectBmp
{
private:
SgaObjectAnim( const INetURLObject& ) {};
public:
SgaObjectAnim();
SgaObjectAnim( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName );
virtual ~SgaObjectAnim() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_ANIM; }
};
// -----------------
// - SgaObjectINet -
// -----------------
class SgaObjectINet : public SgaObjectAnim
{
private:
SgaObjectINet( const INetURLObject& ) {};
public:
SgaObjectINet();
SgaObjectINet( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName );
virtual ~SgaObjectINet() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_INET; }
};
#endif
<commit_msg>INTEGRATION: CWS sb59 (1.5.62); FILE MERGED 2006/08/03 13:47:03 cl 1.5.62.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: galobj.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-10-12 11:44: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
*
************************************************************************/
#ifndef _SVX_GALOBJ_HXX_
#define _SVX_GALOBJ_HXX_
#include <tools/urlobj.hxx>
#include <vcl/graph.hxx>
// -----------
// - Defines -
// -----------
#define S_THUMB 80
// -----------------------------------------------------------------------------
#define SGA_FORMAT_NONE 0x00000000L
#define SGA_FORMAT_STRING 0x00000001L
#define SGA_FORMAT_GRAPHIC 0x00000010L
#define SGA_FORMAT_SOUND 0x00000100L
#define SGA_FORMAT_OLE 0x00001000L
#define SGA_FORMAT_SVDRAW 0x00010000L
#define SGA_FORMAT_ALL 0xFFFFFFFFL
// --------------
// - SgaObjKind -
// --------------
enum SgaObjKind
{
SGA_OBJ_NONE = 0, // Abstraktes Objekt
SGA_OBJ_BMP = 1, // Bitmap-Objekt
SGA_OBJ_SOUND = 2, // Sound-Objekt
SGA_OBJ_VIDEO = 3, // Video-Objekt
SGA_OBJ_ANIM = 4, // Animations-Objekt
SGA_OBJ_SVDRAW = 5, // Svdraw-Objekt
SGA_OBJ_INET = 6 // Grafik aus dem Internet
};
// ----------------
// - GalSoundType -
// ----------------
enum GalSoundType
{
SOUND_STANDARD = 0,
SOUND_COMPUTER = 1,
SOUND_MISC = 2,
SOUND_MUSIC = 3,
SOUND_NATURE = 4,
SOUND_SPEECH = 5,
SOUND_TECHNIC = 6,
SOUND_ANIMAL = 7
};
// -------------
// - SgaObject -
// -------------
class SgaObject
{
friend class GalleryTheme;
private:
void ImplUpdateURL( const INetURLObject& rNewURL ) { aURL = rNewURL; }
protected:
Bitmap aThumbBmp;
GDIMetaFile aThumbMtf;
INetURLObject aURL;
String aUserName;
String aTitle;
BOOL bIsValid;
BOOL bIsThumbBmp;
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
BOOL CreateThumb( const Graphic& rGraphic );
public:
SgaObject();
virtual ~SgaObject() {};
virtual SgaObjKind GetObjKind() const = 0;
virtual UINT16 GetVersion() const = 0;
virtual Bitmap GetThumbBmp() const { return aThumbBmp; }
const GDIMetaFile& GetThumbMtf() const { return aThumbMtf; }
const INetURLObject& GetURL() const { return aURL; }
BOOL IsValid() const { return bIsValid; }
BOOL IsThumbBitmap() const { return bIsThumbBmp; }
const String GetTitle() const;
void SetTitle( const String& rTitle );
friend SvStream& operator<<( SvStream& rOut, const SgaObject& rObj );
friend SvStream& operator>>( SvStream& rIn, SgaObject& rObj );
};
// ------------------
// - SgaObjectSound -
// ------------------
class SgaObjectSound : public SgaObject
{
private:
GalSoundType eSoundType;
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 6; }
public:
SgaObjectSound();
SgaObjectSound( const INetURLObject& rURL );
virtual ~SgaObjectSound();
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SOUND; }
virtual Bitmap GetThumbBmp() const;
GalSoundType GetSoundType() const { return eSoundType; }
};
// -------------------
// - SgaObjectSvDraw -
// -------------------
class FmFormModel;
class SgaObjectSvDraw : public SgaObject
{
using SgaObject::CreateThumb;
private:
BOOL CreateThumb( const FmFormModel& rModel );
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 5; }
public:
SgaObjectSvDraw();
SgaObjectSvDraw( const FmFormModel& rModel, const INetURLObject& rURL );
SgaObjectSvDraw( SvStream& rIStm, const INetURLObject& rURL );
virtual ~SgaObjectSvDraw() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SVDRAW; }
public:
static BOOL DrawCentered( OutputDevice* pOut, const FmFormModel& rModel );
};
// ----------------
// - SgaObjectBmp -
// ----------------
class SgaObjectBmp: public SgaObject
{
private:
void Init( const Graphic& rGraphic, const INetURLObject& rURL );
virtual void WriteData( SvStream& rOut, const String& rDestDir ) const;
virtual void ReadData( SvStream& rIn, UINT16& rReadVersion );
virtual UINT16 GetVersion() const { return 5; }
public:
SgaObjectBmp();
SgaObjectBmp( const INetURLObject& rURL );
SgaObjectBmp( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormat );
virtual ~SgaObjectBmp() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_BMP; }
};
// -----------------
// - SgaObjectAnim -
// -----------------
class SgaObjectAnim : public SgaObjectBmp
{
private:
SgaObjectAnim( const INetURLObject& ) {};
public:
SgaObjectAnim();
SgaObjectAnim( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName );
virtual ~SgaObjectAnim() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_ANIM; }
};
// -----------------
// - SgaObjectINet -
// -----------------
class SgaObjectINet : public SgaObjectAnim
{
private:
SgaObjectINet( const INetURLObject& ) {};
public:
SgaObjectINet();
SgaObjectINet( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName );
virtual ~SgaObjectINet() {};
virtual SgaObjKind GetObjKind() const { return SGA_OBJ_INET; }
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fmtclbl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-07-16 18:04:23 $
*
* 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 _FMTCLBL_HXX
#define _FMTCLBL_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class IntlWrapper;
class SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
: SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT) const;
virtual SvStream& Store(SvStream &, USHORT nItemVersion ) const;
/* virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
*/ virtual USHORT GetVersion( USHORT nFFVer ) const;
};
#if !(defined(MACOSX) && ( __GNUC__ < 3 ))
// GrP moved to gcc_outl.cxx; revisit with gcc3
inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
{ return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }
inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
{ return aSet.GetBalancedColumns( bInP ); }
#endif
#endif
<commit_msg>INTEGRATION: CWS geordi2q14 (1.4.274); FILE MERGED 2004/01/30 14:26:11 hr 1.4.274.1: #111934#: merge CWS ooo111fix2<commit_after>/*************************************************************************
*
* $RCSfile: fmtclbl.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-02-02 17:53:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FMTCLBL_HXX
#define _FMTCLBL_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class IntlWrapper;
class SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
: SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT) const;
virtual SvStream& Store(SvStream &, USHORT nItemVersion ) const;
/* virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
*/ virtual USHORT GetVersion( USHORT nFFVer ) const;
};
inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
{ return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }
inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
{ return aSet.GetBalancedColumns( bInP ); }
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtsrnd.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:53:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FMTSRND_HXX
#define _FMTSRND_HXX
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
class IntlWrapper;
//SwFmtSurround, wie soll sich der ---------------
// Dokumentinhalt unter dem Rahmen verhalten ---
enum SwSurround {
SURROUND_BEGIN,
SURROUND_NONE = SURROUND_BEGIN,
SURROUND_THROUGHT,
SURROUND_PARALLEL,
SURROUND_IDEAL,
SURROUND_LEFT,
SURROUND_RIGHT,
SURROUND_END
};
class SW_DLLPUBLIC SwFmtSurround: public SfxEnumItem
{
BOOL bAnchorOnly :1;
BOOL bContour :1;
BOOL bOutside :1;
public:
SwFmtSurround( SwSurround eNew = SURROUND_PARALLEL );
SwFmtSurround( const SwFmtSurround & );
inline SwFmtSurround &operator=( const SwFmtSurround &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual USHORT GetValueCount() const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwSurround GetSurround()const { return SwSurround( GetValue() ); }
BOOL IsAnchorOnly() const { return bAnchorOnly; }
BOOL IsContour() const { return bContour; }
BOOL IsOutside() const { return bOutside; }
void SetSurround ( SwSurround eNew ){ SfxEnumItem::SetValue( USHORT( eNew ) ); }
void SetAnchorOnly( BOOL bNew ) { bAnchorOnly = bNew; }
void SetContour( BOOL bNew ) { bContour = bNew; }
void SetOutside( BOOL bNew ) { bOutside = bNew; }
};
inline SwFmtSurround &SwFmtSurround::operator=( const SwFmtSurround &rCpy )
{
bAnchorOnly = rCpy.IsAnchorOnly();
bContour = rCpy.IsContour();
bOutside = rCpy.IsOutside();
SfxEnumItem::SetValue( rCpy.GetValue() );
return *this;
}
inline const SwFmtSurround &SwAttrSet::GetSurround(BOOL bInP) const
{ return (const SwFmtSurround&)Get( RES_SURROUND,bInP); }
inline const SwFmtSurround &SwFmt::GetSurround(BOOL bInP) const
{ return aSet.GetSurround(bInP); }
#endif
<commit_msg>INTEGRATION: CWS swqbf81 (1.8.456); FILE MERGED 2006/08/21 07:00:29 od 1.8.456.1: #i68520# - refactoring: new header file for enumeration <SwSurround><commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtsrnd.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-15 11:40:00 $
*
* 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 _FMTSRND_HXX
#define _FMTSRND_HXX
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
// --> OD 2006-08-15 #i68520# - refactoring
// separate enumeration <SwSurround> in own header file
#ifndef _FMTSRNDENUM_HXX
#include <fmtsrndenum.hxx>
#endif
// <--
class IntlWrapper;
//SwFmtSurround, wie soll sich der ---------------
// Dokumentinhalt unter dem Rahmen verhalten ---
class SW_DLLPUBLIC SwFmtSurround: public SfxEnumItem
{
BOOL bAnchorOnly :1;
BOOL bContour :1;
BOOL bOutside :1;
public:
SwFmtSurround( SwSurround eNew = SURROUND_PARALLEL );
SwFmtSurround( const SwFmtSurround & );
inline SwFmtSurround &operator=( const SwFmtSurround &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual USHORT GetValueCount() const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwSurround GetSurround()const { return SwSurround( GetValue() ); }
BOOL IsAnchorOnly() const { return bAnchorOnly; }
BOOL IsContour() const { return bContour; }
BOOL IsOutside() const { return bOutside; }
void SetSurround ( SwSurround eNew ){ SfxEnumItem::SetValue( USHORT( eNew ) ); }
void SetAnchorOnly( BOOL bNew ) { bAnchorOnly = bNew; }
void SetContour( BOOL bNew ) { bContour = bNew; }
void SetOutside( BOOL bNew ) { bOutside = bNew; }
};
inline SwFmtSurround &SwFmtSurround::operator=( const SwFmtSurround &rCpy )
{
bAnchorOnly = rCpy.IsAnchorOnly();
bContour = rCpy.IsContour();
bOutside = rCpy.IsOutside();
SfxEnumItem::SetValue( rCpy.GetValue() );
return *this;
}
inline const SwFmtSurround &SwAttrSet::GetSurround(BOOL bInP) const
{ return (const SwFmtSurround&)Get( RES_SURROUND,bInP); }
inline const SwFmtSurround &SwFmt::GetSurround(BOOL bInP) const
{ return aSet.GetSurround(bInP); }
#endif
<|endoftext|> |
<commit_before>#ifndef slic3r_PresetComboBoxes_hpp_
#define slic3r_PresetComboBoxes_hpp_
#include <wx/bmpcbox.h>
#include <wx/gdicmn.h>
#include "libslic3r/Preset.hpp"
#include "wxExtensions.hpp"
#include "GUI_Utils.hpp"
class wxString;
class wxTextCtrl;
class wxStaticText;
class ScalableButton;
class wxBoxSizer;
class wxComboBox;
class wxStaticBitmap;
namespace Slic3r {
namespace GUI {
class BitmapCache;
// ---------------------------------
// *** PresetComboBox ***
// ---------------------------------
// BitmapComboBox used to presets list on Sidebar and Tabs
class PresetComboBox : public wxBitmapComboBox
{
public:
PresetComboBox(wxWindow* parent, Preset::Type preset_type, const wxSize& size = wxDefaultSize);
~PresetComboBox();
enum LabelItemType {
LABEL_ITEM_PHYSICAL_PRINTER = 0xffffff01,
LABEL_ITEM_DISABLED,
LABEL_ITEM_MARKER,
LABEL_ITEM_PHYSICAL_PRINTERS,
LABEL_ITEM_WIZARD_PRINTERS,
LABEL_ITEM_WIZARD_FILAMENTS,
LABEL_ITEM_WIZARD_MATERIALS,
LABEL_ITEM_MAX,
};
void set_label_marker(int item, LabelItemType label_item_type = LABEL_ITEM_MARKER);
bool set_printer_technology(PrinterTechnology pt);
void set_selection_changed_function(std::function<void(int)> sel_changed) { on_selection_changed = sel_changed; }
bool is_selected_physical_printer();
// Return true, if physical printer was selected
// and next internal selection was accomplished
bool selection_is_changed_according_to_physical_printers();
void update(std::string select_preset);
virtual void update();
virtual void msw_rescale();
protected:
typedef std::size_t Marker;
std::function<void(int)> on_selection_changed { nullptr };
Preset::Type m_type;
std::string m_main_bitmap_name;
PresetBundle* m_preset_bundle {nullptr};
PresetCollection* m_collection {nullptr};
// Caching bitmaps for the all bitmaps, used in preset comboboxes
static BitmapCache& bitmap_cache();
// Indicator, that the preset is compatible with the selected printer.
ScalableBitmap m_bitmapCompatible;
// Indicator, that the preset is NOT compatible with the selected printer.
ScalableBitmap m_bitmapIncompatible;
int m_last_selected;
int m_em_unit;
// parameters for an icon's drawing
int icon_height;
int norm_icon_width;
int thin_icon_width;
int wide_icon_width;
int space_icon_width;
int thin_space_icon_width;
int wide_space_icon_width;
PrinterTechnology printer_technology {ptAny};
void invalidate_selection();
void validate_selection(bool predicate = false);
void update_selection();
#ifdef __linux__
static const char* separator_head() { return "------- "; }
static const char* separator_tail() { return " -------"; }
#else // __linux__
static const char* separator_head() { return "————— "; }
static const char* separator_tail() { return " —————"; }
#endif // __linux__
static wxString separator(const std::string& label);
wxBitmap* get_bmp( std::string bitmap_key, bool wide_icons, const std::string& main_icon_name,
bool is_compatible = true, bool is_system = false, bool is_single_bar = false,
std::string filament_rgb = "", std::string extruder_rgb = "");
wxBitmap* get_bmp( std::string bitmap_key, const std::string& main_icon_name, const std::string& next_icon_name,
bool is_enabled = true, bool is_compatible = true, bool is_system = false);
#ifdef __APPLE__
/* For PresetComboBox we use bitmaps that are created from images that are already scaled appropriately for Retina
* (Contrary to the intuition, the `scale` argument for Bitmap's constructor doesn't mean
* "please scale this to such and such" but rather
* "the wxImage is already sized for backing scale such and such". )
* Unfortunately, the constructor changes the size of wxBitmap too.
* Thus We need to use unscaled size value for bitmaps that we use
* to avoid scaled size of control items.
* For this purpose control drawing methods and
* control size calculation methods (virtual) are overridden.
**/
virtual bool OnAddBitmap(const wxBitmap& bitmap) override;
virtual void OnDrawItem(wxDC& dc, const wxRect& rect, int item, int flags) const override;
#endif
private:
void fill_width_height();
};
// ---------------------------------
// *** PlaterPresetComboBox ***
// ---------------------------------
class PlaterPresetComboBox : public PresetComboBox
{
public:
PlaterPresetComboBox(wxWindow *parent, Preset::Type preset_type);
~PlaterPresetComboBox();
ScalableButton* edit_btn { nullptr };
void set_extruder_idx(const int extr_idx) { m_extruder_idx = extr_idx; }
int get_extruder_idx() const { return m_extruder_idx; }
bool switch_to_tab();
void show_add_menu();
void show_edit_menu();
void update() override;
void msw_rescale() override;
private:
int m_extruder_idx = -1;
};
// ---------------------------------
// *** TabPresetComboBox ***
// ---------------------------------
class TabPresetComboBox : public PresetComboBox
{
bool show_incompatible {false};
bool m_enable_all {false};
public:
TabPresetComboBox(wxWindow *parent, Preset::Type preset_type);
~TabPresetComboBox() {}
void set_show_incompatible_presets(bool show_incompatible_presets) {
show_incompatible = show_incompatible_presets;
}
void update() override;
void update_dirty();
void msw_rescale() override;
void set_enable_all(bool enable=true) { m_enable_all = enable; }
PresetCollection* presets() const { return m_collection; }
Preset::Type type() const { return m_type; }
};
//------------------------------------------------
// SavePresetDialog
//------------------------------------------------
class SavePresetDialog : public DPIDialog
{
enum ActionType
{
ChangePreset,
AddPreset,
Switch,
UndefAction
};
struct Item
{
enum ValidationType
{
Valid,
NoValid,
Warning
};
Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent);
void update_valid_bmp();
void accept();
bool is_valid() const { return m_valid_type != NoValid; }
Preset::Type type() const { return m_type; }
std::string preset_name() const { return m_preset_name; }
private:
Preset::Type m_type;
ValidationType m_valid_type;
std::string m_preset_name;
SavePresetDialog* m_parent {nullptr};
wxStaticBitmap* m_valid_bmp {nullptr};
wxComboBox* m_combo {nullptr};
wxStaticText* m_valid_label {nullptr};
PresetCollection* m_presets {nullptr};
void update();
};
std::vector<Item> m_items;
wxBoxSizer* m_presets_sizer {nullptr};
wxStaticText* m_label {nullptr};
wxRadioBox* m_action_radio_box {nullptr};
wxBoxSizer* m_radio_sizer {nullptr};
ActionType m_action {UndefAction};
std::string m_ph_printer_name;
std::string m_old_preset_name;
public:
SavePresetDialog(Preset::Type type, const std::string& suffix);
~SavePresetDialog() {}
void AddItem(Preset::Type type, const std::string& suffix);
std::string get_name();
std::string get_name(Preset::Type type);
bool enable_ok_btn() const;
void add_info_for_edit_ph_printer(wxBoxSizer *sizer);
void update_info_for_edit_ph_printer(const std::string &preset_name);
void layout();
protected:
void on_dpi_changed(const wxRect& suggested_rect) override;
void on_sys_color_changed() override {}
private:
void update_physical_printers(const std::string& preset_name);
void accept();
};
} // namespace GUI
} // namespace Slic3r
#endif
<commit_msg>Fix build on GCC (missing forward declaration)<commit_after>#ifndef slic3r_PresetComboBoxes_hpp_
#define slic3r_PresetComboBoxes_hpp_
#include <wx/bmpcbox.h>
#include <wx/gdicmn.h>
#include "libslic3r/Preset.hpp"
#include "wxExtensions.hpp"
#include "GUI_Utils.hpp"
class wxString;
class wxTextCtrl;
class wxStaticText;
class ScalableButton;
class wxBoxSizer;
class wxComboBox;
class wxStaticBitmap;
class wxRadioBox;
namespace Slic3r {
namespace GUI {
class BitmapCache;
// ---------------------------------
// *** PresetComboBox ***
// ---------------------------------
// BitmapComboBox used to presets list on Sidebar and Tabs
class PresetComboBox : public wxBitmapComboBox
{
public:
PresetComboBox(wxWindow* parent, Preset::Type preset_type, const wxSize& size = wxDefaultSize);
~PresetComboBox();
enum LabelItemType {
LABEL_ITEM_PHYSICAL_PRINTER = 0xffffff01,
LABEL_ITEM_DISABLED,
LABEL_ITEM_MARKER,
LABEL_ITEM_PHYSICAL_PRINTERS,
LABEL_ITEM_WIZARD_PRINTERS,
LABEL_ITEM_WIZARD_FILAMENTS,
LABEL_ITEM_WIZARD_MATERIALS,
LABEL_ITEM_MAX,
};
void set_label_marker(int item, LabelItemType label_item_type = LABEL_ITEM_MARKER);
bool set_printer_technology(PrinterTechnology pt);
void set_selection_changed_function(std::function<void(int)> sel_changed) { on_selection_changed = sel_changed; }
bool is_selected_physical_printer();
// Return true, if physical printer was selected
// and next internal selection was accomplished
bool selection_is_changed_according_to_physical_printers();
void update(std::string select_preset);
virtual void update();
virtual void msw_rescale();
protected:
typedef std::size_t Marker;
std::function<void(int)> on_selection_changed { nullptr };
Preset::Type m_type;
std::string m_main_bitmap_name;
PresetBundle* m_preset_bundle {nullptr};
PresetCollection* m_collection {nullptr};
// Caching bitmaps for the all bitmaps, used in preset comboboxes
static BitmapCache& bitmap_cache();
// Indicator, that the preset is compatible with the selected printer.
ScalableBitmap m_bitmapCompatible;
// Indicator, that the preset is NOT compatible with the selected printer.
ScalableBitmap m_bitmapIncompatible;
int m_last_selected;
int m_em_unit;
// parameters for an icon's drawing
int icon_height;
int norm_icon_width;
int thin_icon_width;
int wide_icon_width;
int space_icon_width;
int thin_space_icon_width;
int wide_space_icon_width;
PrinterTechnology printer_technology {ptAny};
void invalidate_selection();
void validate_selection(bool predicate = false);
void update_selection();
#ifdef __linux__
static const char* separator_head() { return "------- "; }
static const char* separator_tail() { return " -------"; }
#else // __linux__
static const char* separator_head() { return "————— "; }
static const char* separator_tail() { return " —————"; }
#endif // __linux__
static wxString separator(const std::string& label);
wxBitmap* get_bmp( std::string bitmap_key, bool wide_icons, const std::string& main_icon_name,
bool is_compatible = true, bool is_system = false, bool is_single_bar = false,
std::string filament_rgb = "", std::string extruder_rgb = "");
wxBitmap* get_bmp( std::string bitmap_key, const std::string& main_icon_name, const std::string& next_icon_name,
bool is_enabled = true, bool is_compatible = true, bool is_system = false);
#ifdef __APPLE__
/* For PresetComboBox we use bitmaps that are created from images that are already scaled appropriately for Retina
* (Contrary to the intuition, the `scale` argument for Bitmap's constructor doesn't mean
* "please scale this to such and such" but rather
* "the wxImage is already sized for backing scale such and such". )
* Unfortunately, the constructor changes the size of wxBitmap too.
* Thus We need to use unscaled size value for bitmaps that we use
* to avoid scaled size of control items.
* For this purpose control drawing methods and
* control size calculation methods (virtual) are overridden.
**/
virtual bool OnAddBitmap(const wxBitmap& bitmap) override;
virtual void OnDrawItem(wxDC& dc, const wxRect& rect, int item, int flags) const override;
#endif
private:
void fill_width_height();
};
// ---------------------------------
// *** PlaterPresetComboBox ***
// ---------------------------------
class PlaterPresetComboBox : public PresetComboBox
{
public:
PlaterPresetComboBox(wxWindow *parent, Preset::Type preset_type);
~PlaterPresetComboBox();
ScalableButton* edit_btn { nullptr };
void set_extruder_idx(const int extr_idx) { m_extruder_idx = extr_idx; }
int get_extruder_idx() const { return m_extruder_idx; }
bool switch_to_tab();
void show_add_menu();
void show_edit_menu();
void update() override;
void msw_rescale() override;
private:
int m_extruder_idx = -1;
};
// ---------------------------------
// *** TabPresetComboBox ***
// ---------------------------------
class TabPresetComboBox : public PresetComboBox
{
bool show_incompatible {false};
bool m_enable_all {false};
public:
TabPresetComboBox(wxWindow *parent, Preset::Type preset_type);
~TabPresetComboBox() {}
void set_show_incompatible_presets(bool show_incompatible_presets) {
show_incompatible = show_incompatible_presets;
}
void update() override;
void update_dirty();
void msw_rescale() override;
void set_enable_all(bool enable=true) { m_enable_all = enable; }
PresetCollection* presets() const { return m_collection; }
Preset::Type type() const { return m_type; }
};
//------------------------------------------------
// SavePresetDialog
//------------------------------------------------
class SavePresetDialog : public DPIDialog
{
enum ActionType
{
ChangePreset,
AddPreset,
Switch,
UndefAction
};
struct Item
{
enum ValidationType
{
Valid,
NoValid,
Warning
};
Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent);
void update_valid_bmp();
void accept();
bool is_valid() const { return m_valid_type != NoValid; }
Preset::Type type() const { return m_type; }
std::string preset_name() const { return m_preset_name; }
private:
Preset::Type m_type;
ValidationType m_valid_type;
std::string m_preset_name;
SavePresetDialog* m_parent {nullptr};
wxStaticBitmap* m_valid_bmp {nullptr};
wxComboBox* m_combo {nullptr};
wxStaticText* m_valid_label {nullptr};
PresetCollection* m_presets {nullptr};
void update();
};
std::vector<Item> m_items;
wxBoxSizer* m_presets_sizer {nullptr};
wxStaticText* m_label {nullptr};
wxRadioBox* m_action_radio_box {nullptr};
wxBoxSizer* m_radio_sizer {nullptr};
ActionType m_action {UndefAction};
std::string m_ph_printer_name;
std::string m_old_preset_name;
public:
SavePresetDialog(Preset::Type type, const std::string& suffix);
~SavePresetDialog() {}
void AddItem(Preset::Type type, const std::string& suffix);
std::string get_name();
std::string get_name(Preset::Type type);
bool enable_ok_btn() const;
void add_info_for_edit_ph_printer(wxBoxSizer *sizer);
void update_info_for_edit_ph_printer(const std::string &preset_name);
void layout();
protected:
void on_dpi_changed(const wxRect& suggested_rect) override;
void on_sys_color_changed() override {}
private:
void update_physical_printers(const std::string& preset_name);
void accept();
};
} // namespace GUI
} // namespace Slic3r
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: closedispatcher.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2004-02-25 17:33:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
#define __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRESULTLISTENER_HPP_
#include <com/sun/star/frame/XDispatchResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_
#include <com/sun/star/frame/DispatchResultState.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _VCL_EVNTPOST_HXX
#include <vcl/evntpost.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// exported definitions
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short helper to dispatch the URLs ".uno:CloseDoc" and ".uno:CloseWin" to close a targeted frame/document
@descr These URLs implements a special functionality to close a document or the whole frame ...
and handle the state, it was the last frame or document. Then we create the default backing document
which can be used to open new ones using the file open dialog or some other menu entries.
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class CloseDispatcher : public css::lang::XTypeProvider
, public css::frame::XNotifyingDispatch // => XDispatch
, public css::frame::XStatusListener // => XEventListener
// baseclasses ... order is neccessary for right initialization!
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//_____________________________________________
// types
private:
enum EOperation
{
E_ESTABLISH_BACKINGMODE,
E_CLOSE_TARGET,
E_EXIT_APP
};
//_____________________________________________
// member
private:
/** reference to the uno service manager */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** reference to the target frame */
css::uno::Reference< css::frame::XFrame > m_xTarget;
/** used for asynchronous callbacks within the main thread, to
establish the backing mode or close the target frame. */
::vcl::EventPoster m_aAsyncCallback;
/** used inside asyncronous callback to decide, which operation must be executed. */
EOperation m_eAsyncOperation;
/** for asynchronous operations we must hold us self alive! */
css::uno::Reference< css::uno::XInterface > m_xSelfHold;
/** list of registered status listener */
ListenerHash m_lStatusListener;
/** holded alive for internaly asynchronous operations! */
css::uno::Reference< css::frame::XDispatchResultListener > m_xResultListener;
//_____________________________________________
// native interface
public:
CloseDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xTarget );
virtual ~CloseDispatcher( );
//_____________________________________________
// uno interface
public:
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XNotifyingDispatch
virtual void SAL_CALL dispatchWithNotification( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw(css::uno::RuntimeException);
// XDispatch
virtual void SAL_CALL dispatch ( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments) throw(css::uno::RuntimeException);
virtual void SAL_CALL addStatusListener ( const css::uno::Reference< css::frame::XStatusListener >& xListener ,
const css::util::URL& aURL ) throw(css::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener ,
const css::util::URL& aURL ) throw(css::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& aState ) throw(css::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const css::lang::EventObject& aSource ) throw(css::uno::RuntimeException);
//_____________________________________________
// internal helper
private:
void impl_dispatchCloseDoc ( const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener );
void impl_dispatchCloseWin ( const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener );
void impl_dispatchCloseFrame ( const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener );
sal_Bool impl_closeFrame ( css::uno::Reference< css::frame::XFrame >& xFrame ,
sal_Bool bCallSuspend );
sal_Bool impl_exitApp ( css::uno::Reference< css::frame::XFrame >& xTarget );
void impl_notifyResultListener( const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ,
sal_Int16 nState ,
const css::uno::Any& aResult );
sal_Bool impl_establishBackingMode( );
DECL_LINK( impl_asyncCallback, void* );
}; // class CloseDispatcher
} // namespace framework
#endif // #ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
<commit_msg>INTEGRATION: CWS fwk02ea (1.3.38); FILE MERGED 2004/05/13 08:41:03 as 1.3.38.1: #111074# make frame empty before you check the environment<commit_after>/*************************************************************************
*
* $RCSfile: closedispatcher.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-06-10 13:19:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
#define __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRESULTLISTENER_HPP_
#include <com/sun/star/frame/XDispatchResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_
#include <com/sun/star/frame/DispatchResultState.hpp>
#endif
//_______________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _VCL_EVNTPOST_HXX
#include <vcl/evntpost.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//-----------------------------------------------
/**
@short helper to dispatch the URLs ".uno:CloseDoc"/".uno:CloseWin"/".uno:CloseFrame"
to close a frame/document or the whole application implicitly in case it was the last frame
@descr These URLs implements a special functionality to close a document or the whole frame ...
and handle the state, it was the last frame or document. Then we create the
default backing document which can be used to open new ones using the file open dialog
or some other menu entries. Or we terminate the whole application in case this backing mode shouldnt
be used.
*/
class CloseDispatcher : public css::lang::XTypeProvider
, public css::frame::XNotifyingDispatch // => XDispatch
, public css::frame::XStatusListener // => XEventListener
// baseclasses ... order is neccessary for right initialization!
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//-------------------------------------------
// types
private:
//---------------------------------------
/** @short describe, which request must be done here.
@descr The incoming URLs {.uno:CloseDoc/CloseWin and CloseFrame
can be classified so and checked later performant.}*/
enum EOperation
{
E_CLOSE_DOC,
E_CLOSE_FRAME,
E_CLOSE_WIN
};
//-------------------------------------------
// member
private:
//---------------------------------------
/** @short reference to an uno service manager,
which can be used to create own needed
uno resources. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
//---------------------------------------
/** @short reference to the target frame, which should be
closed by this dispatch. */
css::uno::Reference< css::frame::XFrame > m_xCloseFrame;
//---------------------------------------
/** @short used for asynchronous callbacks within the main thread.
@descr Internaly we work asynchronous. Because our callis
are not aware, that her request can kill its own environment ... */
::vcl::EventPoster m_aAsyncCallback;
//---------------------------------------
/** @short used inside asyncronous callback to decide,
which operation must be executed. */
EOperation m_eOperation;
//---------------------------------------
/** @short for asynchronous operations we must hold us self alive! */
css::uno::Reference< css::uno::XInterface > m_xSelfHold;
//---------------------------------------
/** @short list of registered status listener */
ListenerHash m_lStatusListener;
//---------------------------------------
/** @short holded alive for internaly asynchronous operations! */
css::uno::Reference< css::frame::XDispatchResultListener > m_xResultListener;
//-------------------------------------------
// native interface
public:
//---------------------------------------
/** @short connect a new CloseDispatcher instance to its frame.
@descr One CloseDispatcher instance is bound to onw frame only.
That makes an implementation (e.g. of listener support)
much more easier .-)
@param xSMGR
an un oservice manager, which is needed to create uno resource
internaly.
@param xCloseFrame
the frame, where we must work on.
*/
CloseDispatcher(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xCloseFrame);
//---------------------------------------
/** @short does nothing real. */
virtual ~CloseDispatcher();
//-------------------------------------------
// uno interface
public:
//---------------------------------------
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
//---------------------------------------
// XNotifyingDispatch
virtual void SAL_CALL dispatchWithNotification( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw(css::uno::RuntimeException);
//---------------------------------------
// XDispatch
virtual void SAL_CALL dispatch ( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments) throw(css::uno::RuntimeException);
virtual void SAL_CALL addStatusListener ( const css::uno::Reference< css::frame::XStatusListener >& xListener ,
const css::util::URL& aURL ) throw(css::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener ,
const css::util::URL& aURL ) throw(css::uno::RuntimeException);
//---------------------------------------
// XStatusListener
virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& aState ) throw(css::uno::RuntimeException);
//---------------------------------------
// XEventListener
virtual void SAL_CALL disposing( const css::lang::EventObject& aSource ) throw(css::uno::RuntimeException);
//-------------------------------------------
// internal helper
private:
//---------------------------------------
/** @short a callback for asynchronous started operations.
@descr As already mentione, we make internaly all operations
asynchronous. Otherwhise our callis kill its own environment
during they call us ...
*/
DECL_LINK( impl_asyncCallback, void* );
//---------------------------------------
/** @short close the document view of our m_xCloseFrame.
@descr Thats needed to be shure, that the document cant disagree
later with e.g. an office termination.
The problem: Closing of documents can show UI. If the user
ignores it and open/close other documents, we cant know
which state the office has after closing of this frame.
@param bAllowSuspend
force calling of XController->suspend().
@param bCloseAllOtherViewsToo
if there are other top level frames, which
contains views to the same document then our m_xCloseFrame,
they are forced to be closed too.
We need it to implement the CLOSE_DOC semantic.
@return [boolean]
TRUE if closing was successfully.
*/
sal_Bool implts_closeView(sal_Bool bAllowSuspend ,
sal_Bool bCloseAllOtherViewsToo);
//---------------------------------------
/** @short close the member m_xCloseFrame.
@descr This method does not look for any document
inside this frame. Such views must be cleared
before (e.g. by calling implts_closeView()!
Otherwhise e.g. the XController->suspend()
call isnt made and no UI warn the user about
loosing document changes. Because the
frame is closed ....
@return [bool]
TRUE if closing was successfully.
*/
sal_Bool implts_closeFrame();
//---------------------------------------
/** @short set the special BackingComponent (now StartModule)
as new component of our m_xCloseFrame.
@return [bool]
TRUE if operation was successfully.
*/
sal_Bool implts_establishBackingMode();
//---------------------------------------
/** @short calls XDesktop->terminate().
@descr No office code has to be called
afterwards! Because the process is dieing ...
The only exception is a might be registered
listener at this instance here.
Because he should know, that such things will happen :-)
@return [bool]
TRUE if termination of the application was started ...
*/
sal_Bool implts_terminateApplication();
//---------------------------------------
/** @short notify a DispatchResultListener.
@descr We check the listener reference before we use it.
So this method can be called everytimes!
@parama xListener
the listener, which should be notified.
Can be null!
@param nState
directly used as css::frame::DispatchResultState value.
@param aResult
not used yet realy ...
*/
void implts_notifyResultListener(const css::uno::Reference< css::frame::XDispatchResultListener >& xListener,
sal_Int16 nState ,
const css::uno::Any& aResult );
}; // class CloseDispatcher
} // namespace framework
#endif // #ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
<|endoftext|> |
<commit_before>/*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/logging/LogStreamProcessor.h>
#include <cassert>
#include <folly/experimental/logging/LogStream.h>
namespace folly {
void LogStreamProcessor::operator&(std::ostream& stream) noexcept {
// Note that processMessage() is not noexcept and theoretically may throw.
// However, the only exception that should be possible is std::bad_alloc if
// we fail to allocate memory. We intentionally let our noexcept specifier
// crash in that case, since the program likely won't be able to continue
// anyway.
//
// Any other error here is unexpected and we also want to fail hard
// in that situation too.
auto& logStream = static_cast<LogStream&>(stream);
category_->processMessage(LogMessage{category_,
level_,
filename_,
lineNumber_,
extractMessageString(logStream)});
}
void LogStreamProcessor::operator&(LogStream&& stream) noexcept {
// This version of operator&() is generally only invoked when
// no streaming arguments were supplied to the logging macro.
// Therefore we don't bother calling extractMessageString(stream),
// and just directly use message_.
assert(stream.empty());
category_->processMessage(LogMessage{
category_, level_, filename_, lineNumber_, std::move(message_)});
}
std::string LogStreamProcessor::extractMessageString(
LogStream& stream) noexcept {
if (stream.empty()) {
return std::move(message_);
}
if (message_.empty()) {
return stream.extractString();
}
message_.append(stream.extractString());
return std::move(message_);
}
}
<commit_msg>Fixing opt-asan/ubsan fail for folly contbuild<commit_after>/*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/logging/LogStreamProcessor.h>
#include <cassert>
#include <folly/experimental/logging/LogStream.h>
namespace folly {
void LogStreamProcessor::operator&(std::ostream& stream) noexcept {
// Note that processMessage() is not noexcept and theoretically may throw.
// However, the only exception that should be possible is std::bad_alloc if
// we fail to allocate memory. We intentionally let our noexcept specifier
// crash in that case, since the program likely won't be able to continue
// anyway.
//
// Any other error here is unexpected and we also want to fail hard
// in that situation too.
auto& logStream = static_cast<LogStream&>(stream);
category_->processMessage(LogMessage{category_,
level_,
filename_,
lineNumber_,
extractMessageString(logStream)});
}
void LogStreamProcessor::operator&(LogStream&& stream) noexcept {
// This version of operator&() is generally only invoked when
// no streaming arguments were supplied to the logging macro.
// Therefore we don't bother calling extractMessageString(stream),
// and just directly use message_.
DCHECK(stream.empty());
category_->processMessage(LogMessage{
category_, level_, filename_, lineNumber_, std::move(message_)});
}
std::string LogStreamProcessor::extractMessageString(
LogStream& stream) noexcept {
if (stream.empty()) {
return std::move(message_);
}
if (message_.empty()) {
return stream.extractString();
}
message_.append(stream.extractString());
return std::move(message_);
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray
#include "ospray/volume/DataDistributedBlockedVolume.h"
#include "ospray/common/Core.h"
#include "ospray/transferFunction/TransferFunction.h"
// ispc exports:
#include "DataDistributedBlockedVolume_ispc.h"
namespace ospray {
#if EXP_DATA_PARALLEL
//! Allocate storage and populate the volume, called through the OSPRay API.
void DataDistributedBlockedVolume::commit()
{
// IW: do NOT call parent commit here - this would try to build
// the parent acceleration strucutre, which doesn't make sense on
// blocks that do not exist!!!!
updateEditableParameters();//
StructuredVolume::commit();
for (int i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
block->cppVolume->commit();
}
}
DataDistributedBlockedVolume::DataDistributedBlockedVolume() :
numDDBlocks(0),
ddBlock(NULL)
{
PING;
}
void DataDistributedBlockedVolume::updateEditableParameters()
{
StructuredVolume::updateEditableParameters();
for (int i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
Ref<TransferFunction> transferFunction
= (TransferFunction *)getParamObject("transferFunction", NULL);
auto &cppVolume = block->cppVolume;
cppVolume->findParam("transferFunction",1)->set(transferFunction.ptr);
cppVolume->findParam("samplingRate",1)->set(getParam1f("samplingRate",
1.f));
cppVolume->findParam("gradientShadingEnabled",
1)->set(getParam1i("gradientShadingEnabled", 0));
cppVolume.ptr->updateEditableParameters();
}
}
bool DataDistributedBlockedVolume::isDataDistributed() const
{
return true;
}
void DataDistributedBlockedVolume::buildAccelerator()
{
std::cout << "intentionally SKIP building an accelerator for data parallel "
<< "volume" << std::endl;
}
std::string DataDistributedBlockedVolume::toString() const
{
return("ospray::DataDistributedBlockedVolume<" + voxelType + ">");
}
//! Copy voxels into the volume at the given index (non-zero return value
//! indicates success).
int DataDistributedBlockedVolume::setRegion(
/* points to the first voxel to be copies. The
voxels at 'soruce' MUST have dimensions
'regionSize', must be organized in 3D-array
order, and must have the same voxel type as the
volume.*/
const void *source,
/*! coordinates of the lower,
left, front corner of the target
region.*/
const vec3i ®ionCoords,
/*! size of the region that we're writing to; MUST
be the same as the dimensions of source[][][] */
const vec3i ®ionSize)
{
// Create the equivalent ISPC volume container and allocate memory for voxel
// data.
if (ispcEquivalent == NULL) createEquivalentISPC();
for (int i=0;i<numDDBlocks;i++) {
// that block isn't mine, I shouldn't care ...
if (!ddBlock[i].isMine) continue;
// first, do some culling to make sure we only do setrgion
// calls on blocks that actually map to this block
if (ddBlock[i].domain.lower.x >= regionCoords.x+regionSize.x) continue;
if (ddBlock[i].domain.lower.y >= regionCoords.y+regionSize.y) continue;
if (ddBlock[i].domain.lower.z >= regionCoords.z+regionSize.z) continue;
if (ddBlock[i].domain.upper.x+regionSize.x < regionCoords.x) continue;
if (ddBlock[i].domain.upper.y+regionSize.y < regionCoords.y) continue;
if (ddBlock[i].domain.upper.z+regionSize.z < regionCoords.z) continue;
ddBlock[i].cppVolume->setRegion(source,
regionCoords-ddBlock[i].domain.lower,
regionSize);
ddBlock[i].ispcVolume = ddBlock[i].cppVolume->getIE();
}
return 0;
}
void DataDistributedBlockedVolume::createEquivalentISPC()
{
if (ispcEquivalent != NULL) return;
// Get the voxel type.
voxelType = getParamString("voxelType", "unspecified");
exitOnCondition(getVoxelType() == OSP_UNKNOWN,
"unrecognized voxel type (must be set before calling "
"ospSetRegion())");
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions (must be set before calling "
"ospSetRegion())");
ddBlocks = getParam3i("num_dp_blocks",vec3i(4,4,4));
PRINT(ddBlocks);
blockSize = divRoundUp(dimensions,ddBlocks);
std::cout << "#osp:dp: using data parallel volume of " << ddBlocks
<< " blocks, blockSize is " << blockSize << std::endl;
// Set the grid origin, default to (0,0,0).
this->gridOrigin = getParam3f("gridOrigin", vec3f(0.f));
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions");
// Set the grid spacing, default to (1,1,1).
this->gridSpacing = getParam3f("gridSpacing", vec3f(1.f));
numDDBlocks = embree::reduce_mul(ddBlocks);
ddBlock = new DDBlock[numDDBlocks];
printf("=======================================================\n");
printf("created %ix%ix%i data distributed volume blocks\n",
ddBlocks.x,ddBlocks.y,ddBlocks.z);
printf("=======================================================\n");
if (!ospray::core::isMpiParallel()) {
throw std::runtime_error("data parallel volume, but not in mpi parallel "
"mode...");
}
int64 numWorkers = ospray::core::getWorkerCount();
PRINT(numDDBlocks);
PRINT(numWorkers);
voxelType = getParamString("voxelType", "unspecified");
// if (numDDBlocks >= numWorkers) {
// we have more workers than blocks - use one owner per block,
// meaning we'll end up with multiple blocks per worker
int blockID = 0;
for (int iz=0;iz<ddBlocks.z;iz++)
for (int iy=0;iy<ddBlocks.y;iy++)
for (int ix=0;ix<ddBlocks.x;ix++, blockID++) {
DDBlock *block = &ddBlock[blockID];
if (numDDBlocks >= numWorkers) {
block->firstOwner = blockID % numWorkers;
block->numOwners = 1;
} else {
block->firstOwner = (blockID * numWorkers) / numDDBlocks;
int nextBlockFirstOwner = ((blockID+1)*numWorkers) / numDDBlocks;
block->numOwners = nextBlockFirstOwner - block->firstOwner; // + 1;
// std::cout << "block " << vec3i(ix,iy,iz) << " first=" << block->firstOwner << ", num = " << block->numOwners << std::endl;
}
block->isMine
= (ospray::core::getWorkerRank() >= block->firstOwner)
&& (ospray::core::getWorkerRank() <
(block->firstOwner + block->numOwners));
block->domain.lower = vec3i(ix,iy,iz) * blockSize;
block->domain.upper = min(block->domain.lower+blockSize,dimensions);
block->bounds.lower = gridOrigin +
(gridSpacing * vec3f(block->domain.lower));
block->bounds.upper = gridOrigin +
(gridSpacing * vec3f(block->domain.upper));
// XXX?? 1 overlap?
block->domain.upper = min(block->domain.upper+vec3i(1),dimensions);
if (block->isMine) {
Ref<Volume> volume = new BlockBrickedVolume;
vec3i blockDims = block->domain.upper - block->domain.lower;
volume->findParam("dimensions",1)->set(blockDims);
volume->findParam("gridOrigin",1)->set(block->bounds.lower);
volume->findParam("gridSpacing",1)->set(gridSpacing);
volume->findParam("voxelType",1)->set(voxelType.c_str());
printf("rank %li owns block %i,%i,%i (ID %i), dims %i %i %i\n",
(size_t)core::getWorkerRank(),ix,iy,iz,
blockID,blockDims.x,blockDims.y,blockDims.z);
block->cppVolume = volume;
block->ispcVolume = NULL; //volume->getIE();
} else {
block->ispcVolume = NULL;
block->cppVolume = NULL;
}
}
// } else {
// FATAL("not implemented yet - more workers than blocks ...");//TODO
// }
// Create an ISPC BlockBrickedVolume object and assign type-specific
// function pointers.
ispcEquivalent = ispc::DDBVolume_create(this,
(int)getVoxelType(),
(const ispc::vec3i&)dimensions,
(const ispc::vec3i&)ddBlocks,
(const ispc::vec3i&)blockSize,
ddBlock);
if (!ispcEquivalent) {
throw std::runtime_error("could not create create data distributed "
"volume");
}
}
// A volume type with internal data-distribution. needs a renderer
// that is capable of data-parallel rendering!
OSP_REGISTER_VOLUME(DataDistributedBlockedVolume, data_distributed_volume);
#endif
} // ::ospray
<commit_msg>thrown out all template code for AMR and AMRVolume - it all worked only for floats, anyway, and only complicated the code<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray
#include "ospray/volume/DataDistributedBlockedVolume.h"
#include "ospray/common/Core.h"
#include "ospray/transferFunction/TransferFunction.h"
// ispc exports:
#include "DataDistributedBlockedVolume_ispc.h"
namespace ospray {
#if EXP_DATA_PARALLEL
//! Allocate storage and populate the volume, called through the OSPRay API.
void DataDistributedBlockedVolume::commit()
{
// IW: do NOT call parent commit here - this would try to build
// the parent acceleration strucutre, which doesn't make sense on
// blocks that do not exist!!!!
updateEditableParameters();//
StructuredVolume::commit();
for (int i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
block->cppVolume->commit();
}
}
DataDistributedBlockedVolume::DataDistributedBlockedVolume() :
numDDBlocks(0),
ddBlock(NULL)
{
PING;
}
void DataDistributedBlockedVolume::updateEditableParameters()
{
StructuredVolume::updateEditableParameters();
for (int i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
Ref<TransferFunction> transferFunction
= (TransferFunction *)getParamObject("transferFunction", NULL);
auto &cppVolume = block->cppVolume;
cppVolume->findParam("transferFunction",1)->set(transferFunction.ptr);
cppVolume->findParam("samplingRate",1)->set(getParam1f("samplingRate",
1.f));
cppVolume->findParam("gradientShadingEnabled",
1)->set(getParam1i("gradientShadingEnabled", 0));
cppVolume.ptr->updateEditableParameters();
}
}
bool DataDistributedBlockedVolume::isDataDistributed() const
{
return true;
}
void DataDistributedBlockedVolume::buildAccelerator()
{
std::cout << "intentionally SKIP building an accelerator for data parallel "
<< "volume (this'll be done on the brick level)" << std::endl;
}
std::string DataDistributedBlockedVolume::toString() const
{
return("ospray::DataDistributedBlockedVolume<" + voxelType + ">");
}
//! Copy voxels into the volume at the given index (non-zero return value
//! indicates success).
int DataDistributedBlockedVolume::setRegion(
/* points to the first voxel to be copies. The
voxels at 'soruce' MUST have dimensions
'regionSize', must be organized in 3D-array
order, and must have the same voxel type as the
volume.*/
const void *source,
/*! coordinates of the lower,
left, front corner of the target
region.*/
const vec3i ®ionCoords,
/*! size of the region that we're writing to; MUST
be the same as the dimensions of source[][][] */
const vec3i ®ionSize)
{
// Create the equivalent ISPC volume container and allocate memory for voxel
// data.
if (ispcEquivalent == NULL) createEquivalentISPC();
for (int i=0;i<numDDBlocks;i++) {
// that block isn't mine, I shouldn't care ...
if (!ddBlock[i].isMine) continue;
// first, do some culling to make sure we only do setrgion
// calls on blocks that actually map to this block
if (ddBlock[i].domain.lower.x >= regionCoords.x+regionSize.x) continue;
if (ddBlock[i].domain.lower.y >= regionCoords.y+regionSize.y) continue;
if (ddBlock[i].domain.lower.z >= regionCoords.z+regionSize.z) continue;
if (ddBlock[i].domain.upper.x+regionSize.x < regionCoords.x) continue;
if (ddBlock[i].domain.upper.y+regionSize.y < regionCoords.y) continue;
if (ddBlock[i].domain.upper.z+regionSize.z < regionCoords.z) continue;
ddBlock[i].cppVolume->setRegion(source,
regionCoords-ddBlock[i].domain.lower,
regionSize);
ddBlock[i].ispcVolume = ddBlock[i].cppVolume->getIE();
}
return 0;
}
void DataDistributedBlockedVolume::createEquivalentISPC()
{
if (ispcEquivalent != NULL) return;
// Get the voxel type.
voxelType = getParamString("voxelType", "unspecified");
exitOnCondition(getVoxelType() == OSP_UNKNOWN,
"unrecognized voxel type (must be set before calling "
"ospSetRegion())");
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions (must be set before calling "
"ospSetRegion())");
ddBlocks = getParam3i("num_dp_blocks",vec3i(4,4,4));
blockSize = divRoundUp(dimensions,ddBlocks);
std::cout << "#osp:dp: using data parallel volume of " << ddBlocks
<< " blocks, blockSize is " << blockSize << std::endl;
// Set the grid origin, default to (0,0,0).
this->gridOrigin = getParam3f("gridOrigin", vec3f(0.f));
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions");
// Set the grid spacing, default to (1,1,1).
this->gridSpacing = getParam3f("gridSpacing", vec3f(1.f));
numDDBlocks = embree::reduce_mul(ddBlocks);
ddBlock = new DDBlock[numDDBlocks];
printf("=======================================================\n");
printf("created %ix%ix%i data distributed volume blocks\n",
ddBlocks.x,ddBlocks.y,ddBlocks.z);
printf("=======================================================\n");
if (!ospray::core::isMpiParallel()) {
throw std::runtime_error("data parallel volume, but not in mpi parallel "
"mode...");
}
int64 numWorkers = ospray::core::getWorkerCount();
// PRINT(numDDBlocks);
// PRINT(numWorkers);
voxelType = getParamString("voxelType", "unspecified");
// if (numDDBlocks >= numWorkers) {
// we have more workers than blocks - use one owner per block,
// meaning we'll end up with multiple blocks per worker
int blockID = 0;
for (int iz=0;iz<ddBlocks.z;iz++)
for (int iy=0;iy<ddBlocks.y;iy++)
for (int ix=0;ix<ddBlocks.x;ix++, blockID++) {
DDBlock *block = &ddBlock[blockID];
if (numDDBlocks >= numWorkers) {
block->firstOwner = blockID % numWorkers;
block->numOwners = 1;
} else {
block->firstOwner = (blockID * numWorkers) / numDDBlocks;
int nextBlockFirstOwner = ((blockID+1)*numWorkers) / numDDBlocks;
block->numOwners = nextBlockFirstOwner - block->firstOwner; // + 1;
}
block->isMine
= (ospray::core::getWorkerRank() >= block->firstOwner)
&& (ospray::core::getWorkerRank() <
(block->firstOwner + block->numOwners));
block->domain.lower = vec3i(ix,iy,iz) * blockSize;
block->domain.upper = min(block->domain.lower+blockSize,dimensions);
block->bounds.lower = gridOrigin +
(gridSpacing * vec3f(block->domain.lower));
block->bounds.upper = gridOrigin +
(gridSpacing * vec3f(block->domain.upper));
// iw: add one voxel overlap, so we can properly interpolate
// even across block boundaries (we need the full *cell* on
// the right side, not just the last *voxel*!)
block->domain.upper = min(block->domain.upper+vec3i(1),dimensions);
if (block->isMine) {
Ref<Volume> volume = new BlockBrickedVolume;
vec3i blockDims = block->domain.upper - block->domain.lower;
volume->findParam("dimensions",1)->set(blockDims);
volume->findParam("gridOrigin",1)->set(block->bounds.lower);
volume->findParam("gridSpacing",1)->set(gridSpacing);
volume->findParam("voxelType",1)->set(voxelType.c_str());
printf("rank %li owns block %i,%i,%i (ID %i), dims %i %i %i\n",
(size_t)core::getWorkerRank(),ix,iy,iz,
blockID,blockDims.x,blockDims.y,blockDims.z);
block->cppVolume = volume;
block->ispcVolume = NULL; //volume->getIE();
} else {
block->ispcVolume = NULL;
block->cppVolume = NULL;
}
}
// Create an ISPC BlockBrickedVolume object and assign type-specific
// function pointers.
ispcEquivalent = ispc::DDBVolume_create(this,
(int)getVoxelType(),
(const ispc::vec3i&)dimensions,
(const ispc::vec3i&)ddBlocks,
(const ispc::vec3i&)blockSize,
ddBlock);
if (!ispcEquivalent) {
throw std::runtime_error("could not create create data distributed "
"volume");
}
}
// A volume type with internal data-distribution. needs a renderer
// that is capable of data-parallel rendering!
OSP_REGISTER_VOLUME(DataDistributedBlockedVolume, data_distributed_volume);
#endif
} // ::ospray
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: colorlistener.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-03-23 16:14:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "classes/colorlistener.hxx"
//__________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_INVALIDATESTYLE_HPP_
#include <com/sun/star/awt/InvalidateStyle.hpp>
#endif
//__________________________________________
// other includes
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
DEFINE_XINTERFACE_1( ColorListener ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XEventListener))
//__________________________________________
/** initialize new instance of this class.
It set the window, on which we must apply our detecte color changes.
We start listening for changes and(!) window disposing here too.
@attention Some ressources will be created on demand!
@param xWindow
reference to the window
*/
ColorListener::ColorListener( const css::uno::Reference< css::awt::XWindow >& xWindow )
: ThreadHelpBase(&Application::GetSolarMutex())
, SfxListener ( )
, m_xWindow (xWindow )
, m_bListen (sal_False )
, m_pConfig (NULL )
{
impl_startListening();
impl_applyColor(sal_True);
}
//__________________________________________
/** deinitialize new instance of this class.
Because it's done at different places ... we use an impl method!
see impl_die()
*/
ColorListener::~ColorListener()
{
impl_die();
}
//__________________________________________
/** callback if color config was changed.
@param rBroadcaster
should be our referenced config item (or any helper of it!)
@param rHint
transport an ID, which identify the broadcasted message
*/
void ColorListener::Notify(SfxBroadcaster& rBroadCaster, const SfxHint& rHint)
{
if (((SfxSimpleHint&)rHint).GetId()==SFX_HINT_COLORS_CHANGED)
impl_applyColor(sal_True);
}
//__________________________________________
/** callback if window color was changed by any other!
We own this window .. and we are the only ones, which
define the background color of this window.
*/
IMPL_LINK(ColorListener, impl_SettingsChanged, void*, pVoid)
{
// ignore uninteressting notifications
VclWindowEvent* pEvent = (VclWindowEvent*)pVoid;
if (pEvent->GetId() != VCLEVENT_WINDOW_DATACHANGED)
return 0L;
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow > xWindow = m_xWindow;
long nCurrentColor = m_nColor ;
aReadLock.unlock();
// <- SAFE
if (!xWindow.is())
return 0L;
Window* pWindow = VCLUnoHelper::GetWindow(xWindow);
if (!pWindow)
return 0L;
OutputDevice* pDevice = (OutputDevice*)pWindow;
long nNewColor = (long)(pDevice->GetBackground().GetColor().GetColor());
// Was window background changed?
// NO -> do nothing
// YES -> apply our color!
if (nCurrentColor != nNewColor)
impl_applyColor(sal_False);
return 0L;
}
//__________________________________________
/** set a new background color (retrieved from the configuration)
on the window.
@param bInvalidate
If it's setto TRUE it forces a synchronous update
of the window background.
*/
void ColorListener::impl_applyColor(sal_Bool bInvalidate)
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
if (!m_pConfig)
return;
::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue(::svtools::APPBACKGROUND);
m_nColor = aBackgroundColor.nColor;
css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
aWriteLock.unlock();
// <- SAFE
if (!xPeer.is())
return;
xPeer->setBackground(aBackgroundColor.nColor);
if (bInvalidate)
{
xPeer->invalidate(
css::awt::InvalidateStyle::UPDATE |
css::awt::InvalidateStyle::CHILDREN |
css::awt::InvalidateStyle::NOTRANSPARENT );
}
}
//__________________________________________
/** callback for window destroy.
We must react here automaticly and forget our window reference.
We can die immediatly too. Because there is nothing to do any longer.
@param aEvent
must referr to our window.
@throw ::com::sun::star::uno::RuntimeException
if event source doesn't points to our internal saved window.
*/
void SAL_CALL ColorListener::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
if (aEvent.Source!=m_xWindow)
throw css::uno::RuntimeException(
DECLARE_ASCII(""),
css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
impl_die();
aReadLock.unlock();
/* } SAFE */
}
//__________________________________________
/** starts listening for color changes and window destroy.
We create the needed config singleton on demand here.
*/
void ColorListener::impl_startListening()
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
if (!m_bListen)
{
Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
if (pWindow)
pWindow->AddEventListener(LINK(this, ColorListener, impl_SettingsChanged));
if (!m_pConfig)
m_pConfig = new ::svtools::ColorConfig();
StartListening(*(SfxBroadcaster*)m_pConfig);
css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
if (xDispose.is())
xDispose->addEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
m_bListen = sal_True;
}
aWriteLock.unlock();
/* } SAFE */
}
//__________________________________________
/** stops listening for color changes and window destroy.
*/
void ColorListener::impl_stopListening()
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
if (m_bListen)
{
Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
if (pWindow)
pWindow->RemoveEventListener( LINK( this, ColorListener, impl_SettingsChanged ) );
EndListeningAll();
delete m_pConfig;
m_pConfig = NULL;
css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
if (xDispose.is())
xDispose->removeEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
m_bListen = sal_False;
}
aWriteLock.unlock();
/* } SAFE */
}
//__________________________________________
/** release all used references.
Free all used memory and release any used references.
Of course cancel all existing listener connections, to be
shure never be called again.
*/
void ColorListener::impl_die()
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
// Attention: Deleting of our broadcaster will may force a Notify() call.
// To supress that, we have to disable our listener connection first.
impl_stopListening();
m_xWindow = css::uno::Reference< css::awt::XWindow >();
aReadLock.unlock();
/* } SAFE */
}
} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.100); FILE MERGED 2005/09/05 13:06:03 rt 1.4.100.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: colorlistener.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:08:27 $
*
* 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 "classes/colorlistener.hxx"
//__________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_INVALIDATESTYLE_HPP_
#include <com/sun/star/awt/InvalidateStyle.hpp>
#endif
//__________________________________________
// other includes
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
DEFINE_XINTERFACE_1( ColorListener ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XEventListener))
//__________________________________________
/** initialize new instance of this class.
It set the window, on which we must apply our detecte color changes.
We start listening for changes and(!) window disposing here too.
@attention Some ressources will be created on demand!
@param xWindow
reference to the window
*/
ColorListener::ColorListener( const css::uno::Reference< css::awt::XWindow >& xWindow )
: ThreadHelpBase(&Application::GetSolarMutex())
, SfxListener ( )
, m_xWindow (xWindow )
, m_bListen (sal_False )
, m_pConfig (NULL )
{
impl_startListening();
impl_applyColor(sal_True);
}
//__________________________________________
/** deinitialize new instance of this class.
Because it's done at different places ... we use an impl method!
see impl_die()
*/
ColorListener::~ColorListener()
{
impl_die();
}
//__________________________________________
/** callback if color config was changed.
@param rBroadcaster
should be our referenced config item (or any helper of it!)
@param rHint
transport an ID, which identify the broadcasted message
*/
void ColorListener::Notify(SfxBroadcaster& rBroadCaster, const SfxHint& rHint)
{
if (((SfxSimpleHint&)rHint).GetId()==SFX_HINT_COLORS_CHANGED)
impl_applyColor(sal_True);
}
//__________________________________________
/** callback if window color was changed by any other!
We own this window .. and we are the only ones, which
define the background color of this window.
*/
IMPL_LINK(ColorListener, impl_SettingsChanged, void*, pVoid)
{
// ignore uninteressting notifications
VclWindowEvent* pEvent = (VclWindowEvent*)pVoid;
if (pEvent->GetId() != VCLEVENT_WINDOW_DATACHANGED)
return 0L;
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow > xWindow = m_xWindow;
long nCurrentColor = m_nColor ;
aReadLock.unlock();
// <- SAFE
if (!xWindow.is())
return 0L;
Window* pWindow = VCLUnoHelper::GetWindow(xWindow);
if (!pWindow)
return 0L;
OutputDevice* pDevice = (OutputDevice*)pWindow;
long nNewColor = (long)(pDevice->GetBackground().GetColor().GetColor());
// Was window background changed?
// NO -> do nothing
// YES -> apply our color!
if (nCurrentColor != nNewColor)
impl_applyColor(sal_False);
return 0L;
}
//__________________________________________
/** set a new background color (retrieved from the configuration)
on the window.
@param bInvalidate
If it's setto TRUE it forces a synchronous update
of the window background.
*/
void ColorListener::impl_applyColor(sal_Bool bInvalidate)
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
if (!m_pConfig)
return;
::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue(::svtools::APPBACKGROUND);
m_nColor = aBackgroundColor.nColor;
css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
aWriteLock.unlock();
// <- SAFE
if (!xPeer.is())
return;
xPeer->setBackground(aBackgroundColor.nColor);
if (bInvalidate)
{
xPeer->invalidate(
css::awt::InvalidateStyle::UPDATE |
css::awt::InvalidateStyle::CHILDREN |
css::awt::InvalidateStyle::NOTRANSPARENT );
}
}
//__________________________________________
/** callback for window destroy.
We must react here automaticly and forget our window reference.
We can die immediatly too. Because there is nothing to do any longer.
@param aEvent
must referr to our window.
@throw ::com::sun::star::uno::RuntimeException
if event source doesn't points to our internal saved window.
*/
void SAL_CALL ColorListener::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
if (aEvent.Source!=m_xWindow)
throw css::uno::RuntimeException(
DECLARE_ASCII(""),
css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
impl_die();
aReadLock.unlock();
/* } SAFE */
}
//__________________________________________
/** starts listening for color changes and window destroy.
We create the needed config singleton on demand here.
*/
void ColorListener::impl_startListening()
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
if (!m_bListen)
{
Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
if (pWindow)
pWindow->AddEventListener(LINK(this, ColorListener, impl_SettingsChanged));
if (!m_pConfig)
m_pConfig = new ::svtools::ColorConfig();
StartListening(*(SfxBroadcaster*)m_pConfig);
css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
if (xDispose.is())
xDispose->addEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
m_bListen = sal_True;
}
aWriteLock.unlock();
/* } SAFE */
}
//__________________________________________
/** stops listening for color changes and window destroy.
*/
void ColorListener::impl_stopListening()
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
if (m_bListen)
{
Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
if (pWindow)
pWindow->RemoveEventListener( LINK( this, ColorListener, impl_SettingsChanged ) );
EndListeningAll();
delete m_pConfig;
m_pConfig = NULL;
css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
if (xDispose.is())
xDispose->removeEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );
m_bListen = sal_False;
}
aWriteLock.unlock();
/* } SAFE */
}
//__________________________________________
/** release all used references.
Free all used memory and release any used references.
Of course cancel all existing listener connections, to be
shure never be called again.
*/
void ColorListener::impl_die()
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
// Attention: Deleting of our broadcaster will may force a Notify() call.
// To supress that, we have to disable our listener connection first.
impl_stopListening();
m_xWindow = css::uno::Reference< css::awt::XWindow >();
aReadLock.unlock();
/* } SAFE */
}
} // namespace framework
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2008 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <sqlite3.h>
#include "client/SQLiteKeyValueStore.h"
#include "base/util/StringBuffer.h"
#include "base/util/KeyValuePair.h"
#include "base/Log.h"
BEGIN_NAMESPACE
SQLiteKeyValueStore::SQLiteKeyValueStore(const StringBuffer & table, const StringBuffer & colKey,
const StringBuffer & colValue,
const StringBuffer & thePath)
: SQLKeyValueStore(table,colKey,colValue), enumeration(*this), path(thePath)
{
db = NULL;
statement = NULL;
bool toInit =!checkIfTableExists(table);
if(connect() != SQLITE_OK) {
LOG.error("SQLiteKeyValueStore: cannot connect to database.");
}
if(toInit){
if(init(table,colKey,colValue,thePath) != SQLITE_OK){
LOG.error("SQLiteKeyValueStore: cannot create database.");
}
}
}
SQLiteKeyValueStore::~SQLiteKeyValueStore()
{
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
disconnect();
}
Enumeration& SQLiteKeyValueStore::query(const StringBuffer & sql) const
{
if (!db)
{
throw new StringBuffer /*Exception*/ ("Not connected to database");
}
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
int ret = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &statement, NULL);
if (ret == SQLITE_OK) {
enumeration.reinit(sqlite3_step(statement));
} else {
LOG.error("Unable to prepare sqlite query in query(): %s", sql.c_str());
}
if (ret != SQLITE_OK) {
LOG.error("SQLite execute failed: %s", sqlite3_errmsg(db));
}
return enumeration;
}
int SQLiteKeyValueStore::execute(const StringBuffer & sql)
{
connect();
sqlite3_stmt * stmt;
int ret = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL);
if (ret == SQLITE_OK) {
ret = sqlite3_step(stmt);
} else {
LOG.error("Unable to prepare sqlite query in execute(): %s", sql.c_str());
}
sqlite3_finalize(stmt);
if (ret == SQLITE_DONE)
ret = SQLITE_OK;
if (ret != SQLITE_OK) {
LOG.error("SQLite execute failed: %s", sqlite3_errmsg(db));
}
return ret;
}
/**
* Get all the properties that are currently defined.
*/
Enumeration& SQLiteKeyValueStore::getProperties()
{
StringBuffer sqlQuery = sqlCountAllString();
Enumeration& en = query(sqlQuery);
int rows = 0;
if (en.hasMoreElement())
{
KeyValuePair* kvp = (KeyValuePair*)en.getNextElement();
sscanf(kvp->getValue(), "%d", &rows);
}
if (rows == 0)
return en;
sqlQuery = sqlGetAllString();
SQLiteKeyValueStoreEnumeration& en2 = (SQLiteKeyValueStoreEnumeration&)query(sqlQuery);
en2.setTotalRows(rows);
return en;
}
int SQLiteKeyValueStore::connect()
{
if (db)
return true;
int ret = sqlite3_open(path, &db);
if (ret == SQLITE_OK)
{
return execute("BEGIN TRANSACTION;");
}
return ret;
}
int SQLiteKeyValueStore::disconnect()
{
if (db == NULL)
return true;
execute("ROLLBACK TRANSACTION;");
int ret = sqlite3_close(db);
db = NULL;
return ret;
}
int SQLiteKeyValueStore::close()
{
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
return (
((execute("COMMIT TRANSACTION;") == SQLITE_OK) && (execute("BEGIN TRANSACTION;") == SQLITE_OK))
? 0 : 1);
}
bool SQLiteKeyValueStore::checkIfTableExists(const char* tableName){
/* StringBuffer sql;
sql.sprintf("select count (*) from sqlite_master where type='table' and name='%s';", tableName);
LOG.debug("SQLiteKeyValueStore::checkIfTableExists with sql query %s", sql.c_str());
Enumeration& res = query(sql);
bool ret;
if (res.hasMoreElement())
{
KeyValuePair* kvp = (KeyValuePair*)res.getNextElement();
StringBuffer val = kvp->getValue();
ret = val.icmp("1");
delete kvp;
}*/
FILE* f = fopen(path.c_str(), "r");
if ( !f ) {
return false;
}
return true;
}
int SQLiteKeyValueStore::init(const char* table, const char* colKey, const char* colValue,
const char* path){
StringBuffer sql;
sql.sprintf("CREATE TABLE %s (%s TEXT PRIMARY KEY, %s TEXT)", table, colKey, colValue);
return execute(sql);
}
END_NAMESPACE
<commit_msg>removed transaction mode from default to perform the right mapping storage<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2008 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <sqlite3.h>
#include "client/SQLiteKeyValueStore.h"
#include "base/util/StringBuffer.h"
#include "base/util/KeyValuePair.h"
#include "base/Log.h"
BEGIN_NAMESPACE
SQLiteKeyValueStore::SQLiteKeyValueStore(const StringBuffer & table, const StringBuffer & colKey,
const StringBuffer & colValue,
const StringBuffer & thePath, bool isTransactional)
: SQLKeyValueStore(table,colKey,colValue), enumeration(*this), path(thePath)
{
db = NULL;
statement = NULL;
this->isTransactional = isTransactional;
//bool toInit =!checkIfTableExists(table);
bool toInit = true;
if(connect() != SQLITE_OK) {
LOG.error("SQLiteKeyValueStore: cannot connect to database.");
}
if(toInit){
if(init(table,colKey,colValue,thePath) != SQLITE_OK){
LOG.error("SQLiteKeyValueStore: cannot create database.");
}
}
}
SQLiteKeyValueStore::~SQLiteKeyValueStore()
{
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
disconnect();
}
Enumeration& SQLiteKeyValueStore::query(const StringBuffer & sql) const
{
if (!db)
{
throw new StringBuffer /*Exception*/ ("Not connected to database");
}
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
int ret = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &statement, NULL);
if (ret == SQLITE_OK) {
enumeration.reinit(sqlite3_step(statement));
} else {
LOG.error("Unable to prepare sqlite query in query(): %s", sql.c_str());
}
if (ret != SQLITE_OK) {
LOG.error("SQLite execute failed: %s", sqlite3_errmsg(db));
}
return enumeration;
}
int SQLiteKeyValueStore::execute(const StringBuffer & sql)
{
connect();
sqlite3_stmt * stmt;
int ret = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL);
if (ret == SQLITE_OK) {
ret = sqlite3_step(stmt);
} else {
LOG.error("Unable to prepare sqlite query in execute(): %s", sql.c_str());
}
sqlite3_finalize(stmt);
if (ret == SQLITE_DONE)
ret = SQLITE_OK;
if (ret != SQLITE_OK) {
LOG.error("SQLite execute failed: %s", sqlite3_errmsg(db));
}
return ret;
}
/**
* Get all the properties that are currently defined.
*/
Enumeration& SQLiteKeyValueStore::getProperties()
{
StringBuffer sqlQuery = sqlCountAllString();
Enumeration& en = query(sqlQuery);
int rows = 0;
if (en.hasMoreElement())
{
KeyValuePair* kvp = (KeyValuePair*)en.getNextElement();
sscanf(kvp->getValue(), "%d", &rows);
}
if (rows == 0)
return en;
sqlQuery = sqlGetAllString();
SQLiteKeyValueStoreEnumeration& en2 = (SQLiteKeyValueStoreEnumeration&)query(sqlQuery);
en2.setTotalRows(rows);
return en;
}
int SQLiteKeyValueStore::connect()
{
if (db)
return true;
int ret = sqlite3_open(path, &db);
if (ret == SQLITE_OK )
{
if(isTransactional){
return execute("BEGIN TRANSACTION;");
}
}
return ret;
}
int SQLiteKeyValueStore::disconnect()
{
if (db == NULL)
return true;
if (isTransactional){
execute("ROLLBACK TRANSACTION;");
}
int ret = sqlite3_close(db);
db = NULL;
return ret;
}
int SQLiteKeyValueStore::close()
{
if (statement)
{
sqlite3_finalize(statement);
statement = NULL;
}
if(isTransactional){
return (
((execute("COMMIT TRANSACTION;") == SQLITE_OK) && (execute("BEGIN TRANSACTION;") == SQLITE_OK))
? 0 : 1);
}else{
return 0;
}
return 0;
}
bool SQLiteKeyValueStore::checkIfTableExists(const char* tableName){
/* StringBuffer sql;
sql.sprintf("select count (*) from sqlite_master where type='table' and name='%s';", tableName);
LOG.debug("SQLiteKeyValueStore::checkIfTableExists with sql query %s", sql.c_str());
Enumeration& res = query(sql);
bool ret;
if (res.hasMoreElement())
{
KeyValuePair* kvp = (KeyValuePair*)res.getNextElement();
StringBuffer val = kvp->getValue();
ret = val.icmp("1");
delete kvp;
}*/
FILE* f = fopen(path.c_str(), "r");
if ( !f ) {
return false;
}
return true;
}
int SQLiteKeyValueStore::init(const char* table, const char* colKey, const char* colValue,
const char* path){
StringBuffer sql;
sql.sprintf("CREATE TABLE %s (%s TEXT PRIMARY KEY, %s TEXT)", table, colKey, colValue);
connect();
//execute(sql);
if (db == NULL){
return 1;
}
sqlite3_exec(db,sql.c_str(), NULL, NULL, NULL);
return close();
}
END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* SessionConsoleProcessInfo.cpp
*
* Copyright (C) 2009-17 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionConsoleProcessInfo.hpp>
#include <core/system/Process.hpp>
#include <core/system/System.hpp>
#include <core/text/TermBufferParser.hpp>
#include <session/SessionConsoleProcessPersist.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace console_process {
const int kDefaultMaxOutputLines = 500;
const int kDefaultTerminalMaxOutputLines = 1000; // xterm.js scrollback constant
const int kNoTerminal = 0; // terminal sequence number for a non-terminal
const int kNewTerminal = -1; // new terminal, sequence number yet to be determined
const size_t kOutputBufferSize = 8192;
ConsoleProcessInfo::ConsoleProcessInfo()
: terminalSequence_(kNoTerminal), allowRestart_(false),
interactionMode_(InteractionNever), maxOutputLines_(kDefaultMaxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(false), shellType_(TerminalShell::DefaultShell),
channelMode_(Rpc), cols_(system::kDefaultCols), rows_(system::kDefaultRows),
restarted_(false), autoClose_(DefaultAutoClose), zombie_(false), trackEnv_(false)
{
// When we retrieve from outputBuffer, we only want complete lines. Add a
// dummy \n so we can tell the first line is a complete line.
outputBuffer_.push_back('\n');
}
ConsoleProcessInfo::ConsoleProcessInfo(
const std::string& caption,
const std::string& title,
const std::string& handle,
const int terminalSequence,
TerminalShell::TerminalShellType shellType,
bool altBufferActive,
const core::FilePath& cwd,
int cols, int rows, bool zombie, bool trackEnv)
: caption_(caption), title_(title), handle_(handle),
terminalSequence_(terminalSequence), allowRestart_(true),
interactionMode_(InteractionAlways), maxOutputLines_(kDefaultTerminalMaxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(altBufferActive), shellType_(shellType),
channelMode_(Rpc), cwd_(cwd), cols_(cols), rows_(rows), restarted_(false),
autoClose_(DefaultAutoClose), zombie_(zombie), trackEnv_(trackEnv)
{
}
ConsoleProcessInfo::ConsoleProcessInfo(
const std::string& caption,
InteractionMode mode,
int maxOutputLines)
: caption_(caption), terminalSequence_(kNoTerminal), allowRestart_(false),
interactionMode_(mode), maxOutputLines_(maxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(false), shellType_(TerminalShell::DefaultShell),
channelMode_(Rpc), cols_(system::kDefaultCols), rows_(system::kDefaultRows),
restarted_(false), autoClose_(DefaultAutoClose), zombie_(false), trackEnv_(false)
{
}
void ConsoleProcessInfo::ensureHandle()
{
if (handle_.empty())
handle_ = core::system::generateShortenedUuid();
}
void ConsoleProcessInfo::setExitCode(int exitCode)
{
exitCode_.reset(exitCode);
}
void ConsoleProcessInfo::appendToOutputBuffer(const std::string &str)
{
// For modal console procs, store terminal output directly in the
// ConsoleProcInfo INDEX
if (getTerminalSequence() == kNoTerminal)
{
std::copy(str.begin(), str.end(), std::back_inserter(outputBuffer_));
return;
}
// For terminal tabs, store in a separate file, first removing any
// output targeting the alternate terminal buffer.
std::string mainBufferStr =
core::text::stripSecondaryBuffer(str, &altBufferActive_);
console_persist::appendToOutputBuffer(handle_, mainBufferStr);
}
void ConsoleProcessInfo::appendToOutputBuffer(char ch)
{
outputBuffer_.push_back(ch);
}
std::string ConsoleProcessInfo::getSavedBufferChunk(
int requestedChunk, bool* pMoreAvailable) const
{
// We read the entire buffer into memory to return a given chunk. This is
// ok for our current usage pattern, where the buffer-size is bounded
// to a certain number of lines and is infrequently reloaded (only upon
// browser refresh or reloading a session). If this pattern becomes
// more frequent and/or we support much larger buffers, we'd want to
// reconsider this implementation.
// Read buffer (trims to maxOutputLines_ when chunk zero is requested)
std::string buffer = console_persist::getSavedBuffer(
handle_,
requestedChunk == 0 ? maxOutputLines_ : 0);
*pMoreAvailable = false;
// Common case, entire buffer fits in chunk zero
if (requestedChunk == 0 && (buffer.length() <= kOutputBufferSize))
return buffer;
// Chunk requested past end of buffer?
if (requestedChunk * kOutputBufferSize >= buffer.length())
return std::string();
// Otherwise return substring for the chunk (substr doesn't mind if you ask
// for more characters than are available in the string, as long as the
// starting position is within the string)
std::string chunk = buffer.substr(
requestedChunk * kOutputBufferSize, kOutputBufferSize);
if (requestedChunk * kOutputBufferSize + chunk.length() < buffer.length())
*pMoreAvailable = true;
return chunk;
}
std::string ConsoleProcessInfo::getFullSavedBuffer() const
{
// Read buffer (trims to maxOutputLines_)
return console_persist::getSavedBuffer(handle_, maxOutputLines_);
}
int ConsoleProcessInfo::getBufferLineCount() const
{
return console_persist::getSavedBufferLineCount(handle_, maxOutputLines_);
}
std::string ConsoleProcessInfo::bufferedOutput() const
{
boost::circular_buffer<char>::const_iterator pos =
std::find(outputBuffer_.begin(), outputBuffer_.end(), '\n');
std::string result;
if (pos != outputBuffer_.end())
pos++;
std::copy(pos, outputBuffer_.end(), std::back_inserter(result));
// Will be empty if the buffer was overflowed by a single line
return result;
}
void ConsoleProcessInfo::deleteLogFile(bool lastLineOnly) const
{
console_persist::deleteLogFile(handle_, lastLineOnly);
}
void ConsoleProcessInfo::deleteEnvFile() const
{
console_persist::deleteEnvFile(handle_);
}
core::json::Object ConsoleProcessInfo::toJson() const
{
json::Object result;
result["handle"] = handle_;
result["caption"] = caption_;
result["show_on_output"] = showOnOutput_;
result["interaction_mode"] = static_cast<int>(interactionMode_);
result["max_output_lines"] = maxOutputLines_;
result["buffered_output"] = bufferedOutput();
if (exitCode_)
result["exit_code"] = *exitCode_;
else
result["exit_code"] = json::Value();
// newly added in v1.1
result["terminal_sequence"] = terminalSequence_;
result["allow_restart"] = allowRestart_;
result["title"] = title_;
result["child_procs"] = childProcs_;
result["shell_type"] = static_cast<int>(shellType_);
result["channel_mode"] = static_cast<int>(channelMode_);
result["channel_id"] = channelId_;
result["alt_buffer"] = altBufferActive_;
result["cwd"] = module_context::createAliasedPath(cwd_);
result["cols"] = cols_;
result["rows"] = rows_;
result["restarted"] = restarted_;
result["autoclose"] = static_cast<int>(autoClose_);
result["zombie"] = zombie_;
result["track_env"] = trackEnv_;
return result;
}
boost::shared_ptr<ConsoleProcessInfo> ConsoleProcessInfo::fromJson(core::json::Object& obj)
{
boost::shared_ptr<ConsoleProcessInfo> pProc(new ConsoleProcessInfo());
pProc->handle_ = obj["handle"].get_str();
pProc->caption_ = obj["caption"].get_str();
json::Value showOnOutput = obj["show_on_output"];
if (!showOnOutput.is_null())
pProc->showOnOutput_ = showOnOutput.get_bool();
else
pProc->showOnOutput_ = false;
json::Value mode = obj["interaction_mode"];
if (!mode.is_null())
pProc->interactionMode_ = static_cast<InteractionMode>(mode.get_int());
else
pProc->interactionMode_ = InteractionNever;
json::Value maxLines = obj["max_output_lines"];
if (!maxLines.is_null())
pProc->maxOutputLines_ = maxLines.get_int();
else
pProc->maxOutputLines_ = kDefaultMaxOutputLines;
std::string bufferedOutput = obj["buffered_output"].get_str();
std::copy(bufferedOutput.begin(), bufferedOutput.end(),
std::back_inserter(pProc->outputBuffer_));
json::Value exitCode = obj["exit_code"];
if (exitCode.is_null())
pProc->exitCode_.reset();
else
pProc->exitCode_.reset(exitCode.get_int());
pProc->terminalSequence_ = obj["terminal_sequence"].get_int();
pProc->allowRestart_ = obj["allow_restart"].get_bool();
pProc->title_ = obj["title"].get_str();
pProc->childProcs_ = obj["child_procs"].get_bool();
int shellTypeInt = obj["shell_type"].get_int();
pProc->shellType_ =
static_cast<TerminalShell::TerminalShellType>(shellTypeInt);
int channelModeInt = obj["channel_mode"].get_int();
pProc->channelMode_ = static_cast<ChannelMode>(channelModeInt);
pProc->channelId_ = obj["channel_id"].get_str();
pProc->altBufferActive_ = obj["alt_buffer"].get_bool();
std::string cwd = obj["cwd"].get_str();
if (!cwd.empty())
pProc->cwd_ = module_context::resolveAliasedPath(obj["cwd"].get_str());
pProc->cols_ = obj["cols"].get_int();
pProc->rows_ = obj["rows"].get_int();
pProc->restarted_ = obj["restarted"].get_bool();
int autoCloseInt = obj["autoclose"].get_int();
pProc->autoClose_ = static_cast<AutoCloseMode>(autoCloseInt);
pProc->zombie_ = obj["zombie"].get_bool();
pProc->trackEnv_ = obj["track_env"].get_bool();
return pProc;
}
std::string ConsoleProcessInfo::loadConsoleProcessMetadata()
{
return console_persist::loadConsoleProcessMetadata();
}
void ConsoleProcessInfo::deleteOrphanedLogs(bool (*validHandle)(const std::string&))
{
console_persist::deleteOrphanedLogs(validHandle);
}
void ConsoleProcessInfo::saveConsoleProcesses(const std::string& metadata)
{
console_persist::saveConsoleProcesses(metadata);
}
void ConsoleProcessInfo::saveConsoleEnvironment(const core::system::Options& environment)
{
console_persist::saveConsoleEnvironment(handle_, environment);
}
void ConsoleProcessInfo::loadConsoleEnvironment(const std::string& handle, core::system::Options* pEnv)
{
console_persist::loadConsoleEnvironment(handle, pEnv);
}
} // namespace console_process_info
} // namespace session
} // namespace rstudio
<commit_msg>Guard against null strings<commit_after>/*
* SessionConsoleProcessInfo.cpp
*
* Copyright (C) 2009-17 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionConsoleProcessInfo.hpp>
#include <core/system/Process.hpp>
#include <core/system/System.hpp>
#include <core/text/TermBufferParser.hpp>
#include <session/SessionConsoleProcessPersist.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace console_process {
const int kDefaultMaxOutputLines = 500;
const int kDefaultTerminalMaxOutputLines = 1000; // xterm.js scrollback constant
const int kNoTerminal = 0; // terminal sequence number for a non-terminal
const int kNewTerminal = -1; // new terminal, sequence number yet to be determined
const size_t kOutputBufferSize = 8192;
ConsoleProcessInfo::ConsoleProcessInfo()
: terminalSequence_(kNoTerminal), allowRestart_(false),
interactionMode_(InteractionNever), maxOutputLines_(kDefaultMaxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(false), shellType_(TerminalShell::DefaultShell),
channelMode_(Rpc), cols_(system::kDefaultCols), rows_(system::kDefaultRows),
restarted_(false), autoClose_(DefaultAutoClose), zombie_(false), trackEnv_(false)
{
// When we retrieve from outputBuffer, we only want complete lines. Add a
// dummy \n so we can tell the first line is a complete line.
outputBuffer_.push_back('\n');
}
ConsoleProcessInfo::ConsoleProcessInfo(
const std::string& caption,
const std::string& title,
const std::string& handle,
const int terminalSequence,
TerminalShell::TerminalShellType shellType,
bool altBufferActive,
const core::FilePath& cwd,
int cols, int rows, bool zombie, bool trackEnv)
: caption_(caption), title_(title), handle_(handle),
terminalSequence_(terminalSequence), allowRestart_(true),
interactionMode_(InteractionAlways), maxOutputLines_(kDefaultTerminalMaxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(altBufferActive), shellType_(shellType),
channelMode_(Rpc), cwd_(cwd), cols_(cols), rows_(rows), restarted_(false),
autoClose_(DefaultAutoClose), zombie_(zombie), trackEnv_(trackEnv)
{
}
ConsoleProcessInfo::ConsoleProcessInfo(
const std::string& caption,
InteractionMode mode,
int maxOutputLines)
: caption_(caption), terminalSequence_(kNoTerminal), allowRestart_(false),
interactionMode_(mode), maxOutputLines_(maxOutputLines),
showOnOutput_(false), outputBuffer_(kOutputBufferSize), childProcs_(true),
altBufferActive_(false), shellType_(TerminalShell::DefaultShell),
channelMode_(Rpc), cols_(system::kDefaultCols), rows_(system::kDefaultRows),
restarted_(false), autoClose_(DefaultAutoClose), zombie_(false), trackEnv_(false)
{
}
void ConsoleProcessInfo::ensureHandle()
{
if (handle_.empty())
handle_ = core::system::generateShortenedUuid();
}
void ConsoleProcessInfo::setExitCode(int exitCode)
{
exitCode_.reset(exitCode);
}
void ConsoleProcessInfo::appendToOutputBuffer(const std::string &str)
{
// For modal console procs, store terminal output directly in the
// ConsoleProcInfo INDEX
if (getTerminalSequence() == kNoTerminal)
{
std::copy(str.begin(), str.end(), std::back_inserter(outputBuffer_));
return;
}
// For terminal tabs, store in a separate file, first removing any
// output targeting the alternate terminal buffer.
std::string mainBufferStr =
core::text::stripSecondaryBuffer(str, &altBufferActive_);
console_persist::appendToOutputBuffer(handle_, mainBufferStr);
}
void ConsoleProcessInfo::appendToOutputBuffer(char ch)
{
outputBuffer_.push_back(ch);
}
std::string ConsoleProcessInfo::getSavedBufferChunk(
int requestedChunk, bool* pMoreAvailable) const
{
// We read the entire buffer into memory to return a given chunk. This is
// ok for our current usage pattern, where the buffer-size is bounded
// to a certain number of lines and is infrequently reloaded (only upon
// browser refresh or reloading a session). If this pattern becomes
// more frequent and/or we support much larger buffers, we'd want to
// reconsider this implementation.
// Read buffer (trims to maxOutputLines_ when chunk zero is requested)
std::string buffer = console_persist::getSavedBuffer(
handle_,
requestedChunk == 0 ? maxOutputLines_ : 0);
*pMoreAvailable = false;
// Common case, entire buffer fits in chunk zero
if (requestedChunk == 0 && (buffer.length() <= kOutputBufferSize))
return buffer;
// Chunk requested past end of buffer?
if (requestedChunk * kOutputBufferSize >= buffer.length())
return std::string();
// Otherwise return substring for the chunk (substr doesn't mind if you ask
// for more characters than are available in the string, as long as the
// starting position is within the string)
std::string chunk = buffer.substr(
requestedChunk * kOutputBufferSize, kOutputBufferSize);
if (requestedChunk * kOutputBufferSize + chunk.length() < buffer.length())
*pMoreAvailable = true;
return chunk;
}
std::string ConsoleProcessInfo::getFullSavedBuffer() const
{
// Read buffer (trims to maxOutputLines_)
return console_persist::getSavedBuffer(handle_, maxOutputLines_);
}
int ConsoleProcessInfo::getBufferLineCount() const
{
return console_persist::getSavedBufferLineCount(handle_, maxOutputLines_);
}
std::string ConsoleProcessInfo::bufferedOutput() const
{
boost::circular_buffer<char>::const_iterator pos =
std::find(outputBuffer_.begin(), outputBuffer_.end(), '\n');
std::string result;
if (pos != outputBuffer_.end())
pos++;
std::copy(pos, outputBuffer_.end(), std::back_inserter(result));
// Will be empty if the buffer was overflowed by a single line
return result;
}
void ConsoleProcessInfo::deleteLogFile(bool lastLineOnly) const
{
console_persist::deleteLogFile(handle_, lastLineOnly);
}
void ConsoleProcessInfo::deleteEnvFile() const
{
console_persist::deleteEnvFile(handle_);
}
core::json::Object ConsoleProcessInfo::toJson() const
{
json::Object result;
result["handle"] = handle_;
result["caption"] = caption_;
result["show_on_output"] = showOnOutput_;
result["interaction_mode"] = static_cast<int>(interactionMode_);
result["max_output_lines"] = maxOutputLines_;
result["buffered_output"] = bufferedOutput();
if (exitCode_)
result["exit_code"] = *exitCode_;
else
result["exit_code"] = json::Value();
// newly added in v1.1
result["terminal_sequence"] = terminalSequence_;
result["allow_restart"] = allowRestart_;
result["title"] = title_;
result["child_procs"] = childProcs_;
result["shell_type"] = static_cast<int>(shellType_);
result["channel_mode"] = static_cast<int>(channelMode_);
result["channel_id"] = channelId_;
result["alt_buffer"] = altBufferActive_;
result["cwd"] = module_context::createAliasedPath(cwd_);
result["cols"] = cols_;
result["rows"] = rows_;
result["restarted"] = restarted_;
result["autoclose"] = static_cast<int>(autoClose_);
result["zombie"] = zombie_;
result["track_env"] = trackEnv_;
return result;
}
boost::shared_ptr<ConsoleProcessInfo> ConsoleProcessInfo::fromJson(core::json::Object& obj)
{
boost::shared_ptr<ConsoleProcessInfo> pProc(new ConsoleProcessInfo());
json::Value handle = obj["handle"];
if (!handle.is_null())
pProc->handle_ = handle.get_str();
json::Value caption = obj["caption"];
if (!caption.is_null())
pProc->caption_ = caption.get_str();
json::Value showOnOutput = obj["show_on_output"];
if (!showOnOutput.is_null())
pProc->showOnOutput_ = showOnOutput.get_bool();
else
pProc->showOnOutput_ = false;
json::Value mode = obj["interaction_mode"];
if (!mode.is_null())
pProc->interactionMode_ = static_cast<InteractionMode>(mode.get_int());
else
pProc->interactionMode_ = InteractionNever;
json::Value maxLines = obj["max_output_lines"];
if (!maxLines.is_null())
pProc->maxOutputLines_ = maxLines.get_int();
else
pProc->maxOutputLines_ = kDefaultMaxOutputLines;
json::Value bufferedOutputValue = obj["buffered_output"];
if (!bufferedOutputValue.is_null())
{
std::string bufferedOutput = bufferedOutputValue.get_str();
std::copy(bufferedOutput.begin(), bufferedOutput.end(),
std::back_inserter(pProc->outputBuffer_));
}
json::Value exitCode = obj["exit_code"];
if (exitCode.is_null())
pProc->exitCode_.reset();
else
pProc->exitCode_.reset(exitCode.get_int());
pProc->terminalSequence_ = obj["terminal_sequence"].get_int();
pProc->allowRestart_ = obj["allow_restart"].get_bool();
json::Value title = obj["title"];
if (!title.is_null())
pProc->title_ = title.get_str();
pProc->childProcs_ = obj["child_procs"].get_bool();
int shellTypeInt = obj["shell_type"].get_int();
pProc->shellType_ =
static_cast<TerminalShell::TerminalShellType>(shellTypeInt);
int channelModeInt = obj["channel_mode"].get_int();
pProc->channelMode_ = static_cast<ChannelMode>(channelModeInt);
json::Value channelId = obj["channel_id"];
if (!channelId.is_null())
pProc->channelId_ = channelId.get_str();
pProc->altBufferActive_ = obj["alt_buffer"].get_bool();
json::Value cwdValue = obj["cwd"];
if (!cwdValue.is_null())
{
std::string cwd = cwdValue.get_str();
if (!cwd.empty())
pProc->cwd_ = module_context::resolveAliasedPath(obj["cwd"].get_str());
}
pProc->cols_ = obj["cols"].get_int();
pProc->rows_ = obj["rows"].get_int();
pProc->restarted_ = obj["restarted"].get_bool();
int autoCloseInt = obj["autoclose"].get_int();
pProc->autoClose_ = static_cast<AutoCloseMode>(autoCloseInt);
pProc->zombie_ = obj["zombie"].get_bool();
pProc->trackEnv_ = obj["track_env"].get_bool();
return pProc;
}
std::string ConsoleProcessInfo::loadConsoleProcessMetadata()
{
return console_persist::loadConsoleProcessMetadata();
}
void ConsoleProcessInfo::deleteOrphanedLogs(bool (*validHandle)(const std::string&))
{
console_persist::deleteOrphanedLogs(validHandle);
}
void ConsoleProcessInfo::saveConsoleProcesses(const std::string& metadata)
{
console_persist::saveConsoleProcesses(metadata);
}
void ConsoleProcessInfo::saveConsoleEnvironment(const core::system::Options& environment)
{
console_persist::saveConsoleEnvironment(handle_, environment);
}
void ConsoleProcessInfo::loadConsoleEnvironment(const std::string& handle, core::system::Options* pEnv)
{
console_persist::loadConsoleEnvironment(handle, pEnv);
}
} // namespace console_process_info
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>float rotx, roty, rotz;
class Player{
public:
float x,y,z;
float lookat_x,lookat_y,lookat_z;
};
class Level{
private:
string cur_level_path;
string cur_level;
Model_OBJ *room;
Model_OBJ *player;
int g_rotation;
Player *p;
public:
Level(string &l);
void display();
void keyPress(unsigned char ch, int x, int y);
void specialKeyPress(int key, int x, int y);
};
Level::Level(string &l)
{
cur_level = l;
cur_level_path = "../rooms/" + l +".obj";
player = new Model_OBJ;
room = new Model_OBJ;
player->Load("../models/Tux.obj");
room->Load(&cur_level_path[0]); //&cur_level_path[0] might avoid warning but is it safe?
g_rotation = 0;
p = new Player;
p->x = 0; p->y = -2; p->z = 0;
p->lookat_x = 0; p->lookat_y = 1; p->lookat_z = 0;
}
void Level::display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(roty, 0, 1, 0);
glRotatef(rotx, 1, 0, 0);
glTranslatef(p->x,p->y,p->z);
//gluLookAt( p->x,p->y,p->z - 2, p->lookat_x + p->x,p->lookat_y,p->lookat_z +p->z, 0,1,0);
room->Draw();
glPushMatrix();
player->Draw();
glPopMatrix();
glutSwapBuffers();
glFlush();
}
void Level::keyPress(unsigned char key, int x, int y)
{
cout<<key<<endl;
//normal key press events
if( key == 'w')
{
p->z+=0.3;
}
else if( key == 's')
{
p->z-=0.3;
}
else if(key == 'a')
{
p->x+=0.3;
}
else if(key == 'd')
{
p->x-=0.3;
}
glutPostRedisplay();
}
void Level::specialKeyPress(int key,int x,int y)
{
if ( key == GLUT_KEY_LEFT )
{
roty += 1.0;
if(roty>=360)roty-=360;
}
if ( key == GLUT_KEY_RIGHT )
{
roty -= 1.0;
if(roty<=0)roty+=360;
}
if ( key == GLUT_KEY_UP )
{
rotx += 1.0;
if(rotx>=360)rotx-=360;
}
if ( key == GLUT_KEY_DOWN )
{
rotx -= 1.0;
if(rotx<=0)rotx+=360;
}
glutPostRedisplay();
//Handle arrow, function keys etc
}
<commit_msg>fixed initial position<commit_after>float rotx, roty, rotz;
class Player{
public:
float x,y,z;
float lookat_x,lookat_y,lookat_z;
};
class Level{
private:
string cur_level_path;
string cur_level;
Model_OBJ *room;
Model_OBJ *player;
int g_rotation;
Player *p;
public:
Level(string &l);
void display();
void keyPress(unsigned char ch, int x, int y);
void specialKeyPress(int key, int x, int y);
};
Level::Level(string &l)
{
cur_level = l;
cur_level_path = "../rooms/" + l +".obj";
player = new Model_OBJ;
room = new Model_OBJ;
player->Load("../models/Tux.obj");
room->Load(&cur_level_path[0]); //&cur_level_path[0] might avoid warning but is it safe?
g_rotation = 0;
p = new Player;
p->x = 0; p->y = -1; p->z = -4;
p->lookat_x = 0; p->lookat_y = 1; p->lookat_z = 0;
}
void Level::display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(roty, 0, 1, 0);
glRotatef(rotx, 1, 0, 0);
glTranslatef(p->x,p->y,p->z);
//gluLookAt( p->x,p->y,p->z - 2, p->lookat_x + p->x,p->lookat_y,p->lookat_z +p->z, 0,1,0);
room->Draw();
glPushMatrix();
player->Draw();
glPopMatrix();
glutSwapBuffers();
glFlush();
}
void Level::keyPress(unsigned char key, int x, int y)
{
cout<<key<<endl;
//normal key press events
if( key == 'w')
{
p->z+=0.3;
}
else if( key == 's')
{
p->z-=0.3;
}
else if(key == 'a')
{
p->x+=0.3;
}
else if(key == 'd')
{
p->x-=0.3;
}
glutPostRedisplay();
}
void Level::specialKeyPress(int key,int x,int y)
{
if ( key == GLUT_KEY_LEFT )
{
roty += 1.0;
if(roty>=360)roty-=360;
}
if ( key == GLUT_KEY_RIGHT )
{
roty -= 1.0;
if(roty<=0)roty+=360;
}
if ( key == GLUT_KEY_UP )
{
rotx += 1.0;
if(rotx>=360)rotx-=360;
}
if ( key == GLUT_KEY_DOWN )
{
rotx -= 1.0;
if(rotx<=0)rotx+=360;
}
glutPostRedisplay();
//Handle arrow, function keys etc
}
<|endoftext|> |
<commit_before>#include "version.hpp"
#include "dvwindow.hpp"
#include "dvqmlcommunication.hpp"
#include "dvfolderlisting.hpp"
#include "dvthumbnailprovider.hpp"
#include <QApplication>
#include <QQuickRenderControl>
#include <QQuickWindow>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlContext>
#include <QCommandLineParser>
#include <QMessageBox>
#include <QMimeData>
#include <QOpenGLFramebufferObject>
/* This class is needed for making forwarded keyboard events be recognized by QML. */
class RenderControl : public QQuickRenderControl {
public:
RenderControl(DVWindow* win) : QQuickRenderControl(win), window(win) { }
QWindow* window;
/* Apparently it has something to do with QML making sure the window has focus... */
QWindow* renderWindow(QPoint* offset) {
return window == nullptr ? QQuickRenderControl::renderWindow(offset) : window;
}
};
#ifdef DV_PORTABLE
/* Portable builds store settings in a "DepthView.conf" next to the application executable. */
#define SETTINGS_ARGS QApplication::applicationDirPath() + "/DepthView.conf", QSettings::IniFormat
#else
/* Non-portable builds use an ini file in "%APPDATA%/chipgw" or "~/.config/chipgw". */
#define SETTINGS_ARGS QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()
#endif
DVWindow::DVWindow() : QOpenGLWindow(), settings(SETTINGS_ARGS), renderFBO(nullptr) {
qmlCommunication = new DVQmlCommunication(this, settings);
folderListing = new DVFolderListing(this, settings);
/* Use the class defined above. */
qmlRenderControl = new RenderControl(this);
qmlWindow = new QQuickWindow(qmlRenderControl);
qmlEngine = new QQmlEngine(this);
if (qmlEngine->incubationController() == nullptr)
qmlEngine->setIncubationController(qmlWindow->incubationController());
qmlEngine->rootContext()->setContextProperty("DepthView", qmlCommunication);
qmlEngine->rootContext()->setContextProperty("FolderListing", folderListing);
/* When the Qt.quit() function is called in QML, close this window. */
connect(qmlEngine, &QQmlEngine::quit, this, &DVWindow::close);
qmlEngine->addImageProvider("video", new DVThumbnailProvider);
qmlRegisterUncreatableType<DVDrawMode>(DV_URI_VERSION, "DrawMode", "Only for enum values.");
qmlRegisterUncreatableType<DVSourceMode>(DV_URI_VERSION, "SourceMode", "Only for enum values.");
/* Update QML size whenever draw mode or anamorphic are changed. */
connect(qmlCommunication, &DVQmlCommunication::drawModeChanged, this, &DVWindow::updateQmlSize);
connect(qmlCommunication, &DVQmlCommunication::anamorphicDualViewChanged, this, &DVWindow::updateQmlSize);
/* Update window title whenever file changes. */
connect(folderListing, &DVFolderListing::currentFileChanged, [this](){setTitle(folderListing->currentFile() + " - DepthView");});
connect(this, &DVWindow::frameSwapped, this, &DVWindow::onFrameSwapped);
/* We render a cursor inside QML so it is shown for both eyes. */
setCursor(Qt::BlankCursor);
setMinimumSize(QSize(1000, 500));
setGeometry(0, 0, 1000, 600);
}
DVWindow::~DVWindow() {
unloadPlugins();
delete renderFBO;
if (qmlCommunication->saveWindowState()) {
/* Save the window geometry so that it can be restored next run. */
settings.beginGroup("Window");
settings.setValue("Geometry", geometry());
settings.setValue("State", windowState());
settings.endGroup();
}
}
void DVWindow::updateQmlSize() {
qmlSize = size();
/* If Side-by-Side and not anamorphic we only render QML at half of the window size (horizontally). */
if(qmlCommunication->drawMode() == DVDrawMode::SidebySide && !qmlCommunication->anamorphicDualView())
qmlSize.setWidth(qmlSize.width() / 2);
/* If Top/Bottom and not anamorphic we only render QML at half of the window size (vertically). */
if(qmlCommunication->drawMode() == DVDrawMode::TopBottom && !qmlCommunication->anamorphicDualView())
qmlSize.setHeight(qmlSize.height() / 2);
if (qmlCommunication->drawMode() == DVDrawMode::Plugin)
getPluginSize();
/* Don't recreate fbo unless it's null or its size is wrong. */
if(renderFBO == nullptr || renderFBO->size() != qmlSize)
createFBO();
qmlRoot->setSize(qmlSize);
qmlWindow->setGeometry(QRect(QPoint(), qmlSize));
}
/* Most events need only be passed on to the qmlWindow. */
bool DVWindow::event(QEvent* e) {
switch (e->type()) {
case QEvent::Leave:
/* TODO - This still doesn't always work right, but it's better than using setMouseGrabEnabled()... */
if (holdMouse) {
QPoint pos = mapFromGlobal(QCursor::pos());
/* Generate a new coordinate on screen. */
pos.setX(qBound(1, pos.x(), width()-1));
pos.setY(qBound(1, pos.y(), height()-1));
/* Will generate a new event. */
QCursor::setPos(mapToGlobal(pos));
}
break;
case QEvent::MouseMove:
/* We also emit a special signal for this one so that the fake cursor
* can be set to the right position without having a MouseArea that absorbs events. */
emit qmlCommunication->mouseMoved(static_cast<QMouseEvent*>(e)->localPos());
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::Wheel:
QCoreApplication::sendEvent(qmlWindow, e);
setCursor(Qt::BlankCursor);
return true;
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
case QEvent::TouchCancel:
/* TODO - Remap touch location into the modified screen coordinates,
* in particular for Side by Side & Top/Bottom modes. */
QCoreApplication::sendEvent(qmlWindow, e);
emit qmlCommunication->touchEvent();
return true;
case QEvent::KeyPress:
case QEvent::KeyRelease:
QCoreApplication::sendEvent(qmlWindow, e);
return true;
case QEvent::DragEnter: {
QDragEnterEvent* drag = static_cast<QDragEnterEvent*>(e);
if (drag->mimeData()->hasUrls()) {
for (const QUrl& url : drag->mimeData()->urls()) {
QFileInfo info(url.toLocalFile());
/* If there are any local URLs that exist and match either the video or image filters, accept the drop. */
if (info.exists() && (folderListing->isFileImage(info) || folderListing->isFileVideo(info))) {
drag->acceptProposedAction();
return true;
}
}
}
/* Don't relay the event to QOpenGLWindow. */
return true;
}
case QEvent::Drop: {
QDropEvent* drop = static_cast<QDropEvent*>(e);
if (drop->mimeData()->hasUrls()) {
for (const QUrl& url : drop->mimeData()->urls()) {
/* If the file opened properly, accept the drop. */
if (folderListing->openFile(url)) {
drop->acceptProposedAction();
return true;
}
}
}
/* Don't relay the event to QOpenGLWindow. */
return true;
}
default:
break;
}
return QOpenGLWindow::event(e);
}
void DVWindow::doCommandLine(QCommandLineParser& parser) {
/* We use one string to hold all warning messages, so we only have to show one dialog. */
QString warning;
if(parser.isSet("f"))
setWindowState(Qt::WindowFullScreen);
if(parser.isSet("d") && !folderListing->initDir(parser.value("d")))
warning += tr("<p>Invalid directory \"%1\" passed to \"--startdir\" argument!</p>").arg(parser.value("d"));
if(parser.isSet("r")){
const QString& renderer = parser.value("r");
int mode = qmlCommunication->getModes().indexOf(renderer);
if(mode == -1)
warning += tr("<p>Invalid renderer \"%1\" passed to \"--renderer\" argument!</p>").arg(renderer);
if (mode >= DVDrawMode::Plugin) {
qmlCommunication->setPluginMode(renderer);
qmlCommunication->initDrawMode(DVDrawMode::Plugin);
} else {
qmlCommunication->initDrawMode(DVDrawMode::Type(mode));
}
}
for (const QString& arg : parser.positionalArguments()) {
QFileInfo file(arg);
/* The file extension is checked by openFile(). */
if (file.exists() && folderListing->openFile(file))
break;
}
/* If there weren't any warnings we don't show the dialog. */
if(!warning.isEmpty())
QMessageBox::warning(nullptr, tr("Invalid Command Line!"), warning);
}
<commit_msg>Locking mouse now keeps the cursor inside qmlSize.<commit_after>#include "version.hpp"
#include "dvwindow.hpp"
#include "dvqmlcommunication.hpp"
#include "dvfolderlisting.hpp"
#include "dvthumbnailprovider.hpp"
#include <QApplication>
#include <QQuickRenderControl>
#include <QQuickWindow>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlContext>
#include <QCommandLineParser>
#include <QMessageBox>
#include <QMimeData>
#include <QOpenGLFramebufferObject>
/* This class is needed for making forwarded keyboard events be recognized by QML. */
class RenderControl : public QQuickRenderControl {
public:
RenderControl(DVWindow* win) : QQuickRenderControl(win), window(win) { }
QWindow* window;
/* Apparently it has something to do with QML making sure the window has focus... */
QWindow* renderWindow(QPoint* offset) {
return window == nullptr ? QQuickRenderControl::renderWindow(offset) : window;
}
};
#ifdef DV_PORTABLE
/* Portable builds store settings in a "DepthView.conf" next to the application executable. */
#define SETTINGS_ARGS QApplication::applicationDirPath() + "/DepthView.conf", QSettings::IniFormat
#else
/* Non-portable builds use an ini file in "%APPDATA%/chipgw" or "~/.config/chipgw". */
#define SETTINGS_ARGS QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()
#endif
DVWindow::DVWindow() : QOpenGLWindow(), settings(SETTINGS_ARGS), renderFBO(nullptr) {
qmlCommunication = new DVQmlCommunication(this, settings);
folderListing = new DVFolderListing(this, settings);
/* Use the class defined above. */
qmlRenderControl = new RenderControl(this);
qmlWindow = new QQuickWindow(qmlRenderControl);
qmlEngine = new QQmlEngine(this);
if (qmlEngine->incubationController() == nullptr)
qmlEngine->setIncubationController(qmlWindow->incubationController());
qmlEngine->rootContext()->setContextProperty("DepthView", qmlCommunication);
qmlEngine->rootContext()->setContextProperty("FolderListing", folderListing);
/* When the Qt.quit() function is called in QML, close this window. */
connect(qmlEngine, &QQmlEngine::quit, this, &DVWindow::close);
qmlEngine->addImageProvider("video", new DVThumbnailProvider);
qmlRegisterUncreatableType<DVDrawMode>(DV_URI_VERSION, "DrawMode", "Only for enum values.");
qmlRegisterUncreatableType<DVSourceMode>(DV_URI_VERSION, "SourceMode", "Only for enum values.");
/* Update QML size whenever draw mode or anamorphic are changed. */
connect(qmlCommunication, &DVQmlCommunication::drawModeChanged, this, &DVWindow::updateQmlSize);
connect(qmlCommunication, &DVQmlCommunication::anamorphicDualViewChanged, this, &DVWindow::updateQmlSize);
/* Update window title whenever file changes. */
connect(folderListing, &DVFolderListing::currentFileChanged, [this](){setTitle(folderListing->currentFile() + " - DepthView");});
connect(this, &DVWindow::frameSwapped, this, &DVWindow::onFrameSwapped);
/* We render a cursor inside QML so it is shown for both eyes. */
setCursor(Qt::BlankCursor);
setMinimumSize(QSize(1000, 500));
setGeometry(0, 0, 1000, 600);
}
DVWindow::~DVWindow() {
unloadPlugins();
delete renderFBO;
if (qmlCommunication->saveWindowState()) {
/* Save the window geometry so that it can be restored next run. */
settings.beginGroup("Window");
settings.setValue("Geometry", geometry());
settings.setValue("State", windowState());
settings.endGroup();
}
}
void DVWindow::updateQmlSize() {
qmlSize = size();
/* If Side-by-Side and not anamorphic we only render QML at half of the window size (horizontally). */
if(qmlCommunication->drawMode() == DVDrawMode::SidebySide && !qmlCommunication->anamorphicDualView())
qmlSize.setWidth(qmlSize.width() / 2);
/* If Top/Bottom and not anamorphic we only render QML at half of the window size (vertically). */
if(qmlCommunication->drawMode() == DVDrawMode::TopBottom && !qmlCommunication->anamorphicDualView())
qmlSize.setHeight(qmlSize.height() / 2);
if (qmlCommunication->drawMode() == DVDrawMode::Plugin)
getPluginSize();
/* Don't recreate fbo unless it's null or its size is wrong. */
if(renderFBO == nullptr || renderFBO->size() != qmlSize)
createFBO();
qmlRoot->setSize(qmlSize);
qmlWindow->setGeometry(QRect(QPoint(), qmlSize));
}
/* Most events need only be passed on to the qmlWindow. */
bool DVWindow::event(QEvent* e) {
switch (e->type()) {
case QEvent::Leave:
/* TODO - This still doesn't always work right, but it's better than using setMouseGrabEnabled()... */
if (holdMouse) {
QPoint pos = mapFromGlobal(QCursor::pos());
/* Generate a new coordinate on screen. */
pos.setX(qBound(1, pos.x(), qmlSize.width()-1));
pos.setY(qBound(1, pos.y(), qmlSize.height()-1));
/* Will generate a new event. */
QCursor::setPos(mapToGlobal(pos));
}
break;
case QEvent::MouseMove:
/* If holding the mouse, make sure it's inside the QML render area. */
if (holdMouse && !QRect(QPoint(), qmlSize).contains(mapFromGlobal(QCursor::pos()), true)) {
QPoint pos = mapFromGlobal(QCursor::pos());
/* Generate a new coordinate on screen. */
pos.setX(qBound(1, pos.x(), qmlSize.width()-1));
pos.setY(qBound(1, pos.y(), qmlSize.height()-1));
/* Will generate a new event. */
QCursor::setPos(mapToGlobal(pos));
break;
}
/* We also emit a special signal for this one so that the fake cursor
* can be set to the right position without having a MouseArea that absorbs events. */
emit qmlCommunication->mouseMoved(static_cast<QMouseEvent*>(e)->localPos());
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::Wheel:
QCoreApplication::sendEvent(qmlWindow, e);
setCursor(Qt::BlankCursor);
return true;
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
case QEvent::TouchCancel:
/* TODO - Remap touch location into the modified screen coordinates,
* in particular for Side by Side & Top/Bottom modes. */
QCoreApplication::sendEvent(qmlWindow, e);
emit qmlCommunication->touchEvent();
return true;
case QEvent::KeyPress:
case QEvent::KeyRelease:
QCoreApplication::sendEvent(qmlWindow, e);
return true;
case QEvent::DragEnter: {
QDragEnterEvent* drag = static_cast<QDragEnterEvent*>(e);
if (drag->mimeData()->hasUrls()) {
for (const QUrl& url : drag->mimeData()->urls()) {
QFileInfo info(url.toLocalFile());
/* If there are any local URLs that exist and match either the video or image filters, accept the drop. */
if (info.exists() && (folderListing->isFileImage(info) || folderListing->isFileVideo(info))) {
drag->acceptProposedAction();
return true;
}
}
}
/* Don't relay the event to QOpenGLWindow. */
return true;
}
case QEvent::Drop: {
QDropEvent* drop = static_cast<QDropEvent*>(e);
if (drop->mimeData()->hasUrls()) {
for (const QUrl& url : drop->mimeData()->urls()) {
/* If the file opened properly, accept the drop. */
if (folderListing->openFile(url)) {
drop->acceptProposedAction();
return true;
}
}
}
/* Don't relay the event to QOpenGLWindow. */
return true;
}
default:
break;
}
return QOpenGLWindow::event(e);
}
void DVWindow::doCommandLine(QCommandLineParser& parser) {
/* We use one string to hold all warning messages, so we only have to show one dialog. */
QString warning;
if(parser.isSet("f"))
setWindowState(Qt::WindowFullScreen);
if(parser.isSet("d") && !folderListing->initDir(parser.value("d")))
warning += tr("<p>Invalid directory \"%1\" passed to \"--startdir\" argument!</p>").arg(parser.value("d"));
if(parser.isSet("r")){
const QString& renderer = parser.value("r");
int mode = qmlCommunication->getModes().indexOf(renderer);
if(mode == -1)
warning += tr("<p>Invalid renderer \"%1\" passed to \"--renderer\" argument!</p>").arg(renderer);
if (mode >= DVDrawMode::Plugin) {
qmlCommunication->setPluginMode(renderer);
qmlCommunication->initDrawMode(DVDrawMode::Plugin);
} else {
qmlCommunication->initDrawMode(DVDrawMode::Type(mode));
}
}
for (const QString& arg : parser.positionalArguments()) {
QFileInfo file(arg);
/* The file extension is checked by openFile(). */
if (file.exists() && folderListing->openFile(file))
break;
}
/* If there weren't any warnings we don't show the dialog. */
if(!warning.isEmpty())
QMessageBox::warning(nullptr, tr("Invalid Command Line!"), warning);
}
<|endoftext|> |
<commit_before>#include "game.hpp"
int Game::startGame() {
std::string str;
while(true) {
std::getline(std::cin, str);
if(!uciHandler(str)) {
return 0;
};
}
}
int64_t Game::mtdf(int64_t f, int depth) {
int64_t bound[2] = {-WHITE_WIN, +WHITE_WIN};
do {
double beta = f + (f == bound[0]);
f = negamax(game_board, beta - 1, beta, depth, 0, FIXED_DEPTH, false, true);
bound[f < beta] = f;
} while (bound[0] < bound[1]);
return f;
}
void Game::goFixedDepth() {
clearCash();
++hashAge;
stopped = false;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
int max_depth_global = max_depth;
max_depth = 1;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
hasBestMove = true;
bestScore = 0;
int64_t f = 0;
int64_t current_alpha = -WHITE_WIN, current_beta = WHITE_WIN, win_size = 50;
for(; max_depth <= max_depth_global; ++max_depth) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
//negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
if(max_depth > 1) {
current_alpha = bestScore - 30;
current_beta = bestScore + 30;
}
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*std::cout << "!";
if(bestScore <= current_alpha) {
std::cout << "!";
negamax(game_board, -WHITE_WIN, current_beta, max_depth, 0, FIXED_DEPTH, false, true);
} else if(bestScore >= current_beta) {
std::cout << "!";
negamax(game_board, current_alpha, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
}*/
//f = mtdf(f, max_depth);
hasBestMove = true;
if((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {
break;
}
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goFixedTime(int tm) {
stopped = false;
if(tm >= 200) {
tm -= 100;
}
time = tm;
timer.start();
clearCash();
++hashAge;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
bestScore = 0;
hasBestMove = true;
max_depth = 1;
std::vector<BitMove> bestPV;
for(; timer.getTime() < time; ) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);
if(abs(bestScore) >= (WHITE_WIN - 100) || stopped) {
break;
}
hasBestMove = true;
++max_depth;
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goTournament() {
double tm, inc;
if(game_board.whiteMove) {
tm = wtime;
inc = winc;
} else {
tm = btime;
inc = binc;
}
double k = 50;
if(movestogoEnable) {
k = movestogo;
goFixedTime(tm / k + inc);
} else {
goFixedTime(tm / k + inc - 100);
}
}
bool Game::move(std::string mv) {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves);
for(unsigned int i = 0; i < moves.count; ++i) {
if(moves.moveArray[i].getMoveString() == mv) {
game_board.move(moves.moveArray[i]);
uint8_t color;
if(game_board.whiteMove) {
color = BLACK;
} else {
color = WHITE;
}
if(game_board.inCheck(color)) {
game_board.goBack();
continue;
}
++hash_decrement;
return true;
}
}
return false;
}
<commit_msg>улучшение контроля времени<commit_after>#include "game.hpp"
int Game::startGame() {
std::string str;
while(true) {
std::getline(std::cin, str);
if(!uciHandler(str)) {
return 0;
};
}
}
int64_t Game::mtdf(int64_t f, int depth) {
int64_t bound[2] = {-WHITE_WIN, +WHITE_WIN};
do {
double beta = f + (f == bound[0]);
f = negamax(game_board, beta - 1, beta, depth, 0, FIXED_DEPTH, false, true);
bound[f < beta] = f;
} while (bound[0] < bound[1]);
return f;
}
void Game::goFixedDepth() {
clearCash();
++hashAge;
stopped = false;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
int max_depth_global = max_depth;
max_depth = 1;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
hasBestMove = true;
bestScore = 0;
int64_t f = 0;
int64_t current_alpha = -WHITE_WIN, current_beta = WHITE_WIN, win_size = 50;
for(; max_depth <= max_depth_global; ++max_depth) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
//negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
if(max_depth > 1) {
current_alpha = bestScore - 30;
current_beta = bestScore + 30;
}
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*std::cout << "!";
if(bestScore <= current_alpha) {
std::cout << "!";
negamax(game_board, -WHITE_WIN, current_beta, max_depth, 0, FIXED_DEPTH, false, true);
} else if(bestScore >= current_beta) {
std::cout << "!";
negamax(game_board, current_alpha, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
}*/
//f = mtdf(f, max_depth);
hasBestMove = true;
if((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {
break;
}
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goFixedTime(int tm) {
stopped = false;
/*if(tm >= 200) {
tm -= 100;
}*/
time = tm;
timer.start();
clearCash();
++hashAge;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
bestScore = 0;
hasBestMove = true;
max_depth = 1;
std::vector<BitMove> bestPV;
for(; timer.getTime() < time; ) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);
if(abs(bestScore) >= (WHITE_WIN - 100) || stopped) {
break;
}
hasBestMove = true;
++max_depth;
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goTournament() {
double tm, inc;
if(game_board.whiteMove) {
tm = wtime;
inc = winc;
} else {
tm = btime;
inc = binc;
}
double k = 50;
if(movestogoEnable) {
k = movestogo;
goFixedTime(tm / k + inc);
} else {
goFixedTime(tm / k + inc - 100);
}
}
bool Game::move(std::string mv) {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves);
for(unsigned int i = 0; i < moves.count; ++i) {
if(moves.moveArray[i].getMoveString() == mv) {
game_board.move(moves.moveArray[i]);
uint8_t color;
if(game_board.whiteMove) {
color = BLACK;
} else {
color = WHITE;
}
if(game_board.inCheck(color)) {
game_board.goBack();
continue;
}
++hash_decrement;
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////////
// Name: ghistogram.cpp
// Purpose:
// Author: Eloy Martinez
// Modified by:
// Created: Mon 23 Jun 2008 11:40:03 CEST
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <sstream>
#include "ghistogram.h"
#include "histogram.h"
#include "labelconstructor.h"
#include "histogramtotals.h"
////@begin XPM images
////@end XPM images
/*!
* gHistogram type definition
*/
IMPLEMENT_CLASS( gHistogram, wxFrame )
/*!
* gHistogram event table definition
*/
BEGIN_EVENT_TABLE( gHistogram, wxFrame )
////@begin gHistogram event table entries
////@end gHistogram event table entries
END_EVENT_TABLE()
/*!
* gHistogram constructors
*/
gHistogram::gHistogram()
{
Init();
}
gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create( parent, id, caption, pos, size, style );
}
/*!
* gHistogram creator
*/
bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin gHistogram creation
wxFrame::Create( parent, id, caption, pos, size, style );
CreateControls();
////@end gHistogram creation
return true;
}
/*!
* gHistogram destructor
*/
gHistogram::~gHistogram()
{
////@begin gHistogram destruction
////@end gHistogram destruction
}
/*!
* Member initialisation
*/
void gHistogram::Init()
{
////@begin gHistogram member initialisation
myHistogram = NULL;
gridHisto = NULL;
////@end gHistogram member initialisation
}
/*!
* Control creation for gHistogram
*/
void gHistogram::CreateControls()
{
////@begin gHistogram content construction
gHistogram* itemFrame1 = this;
gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, itemFrame1->ConvertDialogToPixels(wxSize(200, 150)), wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB );
gridHisto->SetDefaultColSize(50);
gridHisto->SetDefaultRowSize(25);
gridHisto->SetColLabelSize(25);
gridHisto->SetRowLabelSize(50);
gridHisto->CreateGrid(5, 5, wxGrid::wxGridSelectCells);
////@end gHistogram content construction
}
void gHistogram::execute()
{
if( myHistogram == NULL )
return;
myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() );
fillGrid();
}
void gHistogram::fillGrid()
{
int rowLabelWidth = 0;
wxFont labelFont = gridHisto->GetLabelFont();
bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() );
UINT16 idStat;
THistogramColumn curPlane;
if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) )
throw( exception() );
if( commStat )
curPlane = myHistogram->getCommSelectedPlane();
else
curPlane = myHistogram->getSelectedPlane();
gridHisto->BeginBatch();
gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() );
gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() );
gridHisto->AppendCols( myHistogram->getNumColumns() );
gridHisto->AppendRows( myHistogram->getNumRows() + NUMTOTALS );
for( THistogramColumn iCol = 0; iCol < myHistogram->getNumColumns(); iCol++ )
{
if( commStat )
{
gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) );
myHistogram->setCommFirstCell( iCol, curPlane );
}
else
{
gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) );
myHistogram->setFirstCell( iCol, curPlane );
}
for( TObjectOrder iRow = 0; iRow < myHistogram->getNumRows(); iRow++ )
{
int w, h;
gridHisto->GetTextExtent( myHistogram->getRowLabel( iCol ), &w, &h, NULL, NULL, &labelFont );
if( rowLabelWidth == 0 || rowLabelWidth < w )
rowLabelWidth = w;
gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) );
if( commStat && myHistogram->endCommCell( iCol, curPlane ) ||
!commStat && myHistogram->endCell( iCol, curPlane ) )
gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
else
{
if( commStat )
{
if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram,
myHistogram->getCommCurrentValue( iCol, idStat, curPlane ) );
gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) );
myHistogram->setCommNextCell( iCol, curPlane );
}
else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
}
else
{
if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram,
myHistogram->getCurrentValue( iCol, idStat, curPlane ) );
gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) );
myHistogram->setNextCell( iCol, curPlane );
}
else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
}
}
}
HistogramTotals *histoTotals = myHistogram->getTotals( myHistogram->getCurrentStat() );
vector<TSemanticValue> totals;
histoTotals->getAll( totals, idStat, iCol, curPlane );
for( int i = 0; i < NUMTOTALS; i++ )
{
gridHisto->SetRowLabelValue( myHistogram->getNumRows() + i,
LabelConstructor::histoTotalLabel( (THistoTotals) i ) );
if( totals[ 0 ] > 0.0 )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram, totals[ i ] );
gridHisto->SetCellValue( myHistogram->getNumRows() + i, iCol, wxString( tmpStr ) );
}
else gridHisto->SetCellValue( myHistogram->getNumRows() + i, iCol, wxString( "-" ) );
}
}
gridHisto->SetRowLabelSize( rowLabelWidth );
gridHisto->Fit();
gridHisto->AutoSize();
gridHisto->EndBatch();
}
/*!
* Should we show tooltips?
*/
bool gHistogram::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap gHistogram::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin gHistogram bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end gHistogram bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon gHistogram::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin gHistogram icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end gHistogram icon retrieval
}
<commit_msg>*** empty log message ***<commit_after>/////////////////////////////////////////////////////////////////////////////
// Name: ghistogram.cpp
// Purpose:
// Author: Eloy Martinez
// Modified by:
// Created: Mon 23 Jun 2008 11:40:03 CEST
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <sstream>
#include "ghistogram.h"
#include "histogram.h"
#include "labelconstructor.h"
#include "histogramtotals.h"
////@begin XPM images
////@end XPM images
/*!
* gHistogram type definition
*/
IMPLEMENT_CLASS( gHistogram, wxFrame )
/*!
* gHistogram event table definition
*/
BEGIN_EVENT_TABLE( gHistogram, wxFrame )
////@begin gHistogram event table entries
////@end gHistogram event table entries
END_EVENT_TABLE()
/*!
* gHistogram constructors
*/
gHistogram::gHistogram()
{
Init();
}
gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create( parent, id, caption, pos, size, style );
}
/*!
* gHistogram creator
*/
bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin gHistogram creation
wxFrame::Create( parent, id, caption, pos, size, style );
CreateControls();
////@end gHistogram creation
return true;
}
/*!
* gHistogram destructor
*/
gHistogram::~gHistogram()
{
////@begin gHistogram destruction
////@end gHistogram destruction
}
/*!
* Member initialisation
*/
void gHistogram::Init()
{
////@begin gHistogram member initialisation
myHistogram = NULL;
gridHisto = NULL;
////@end gHistogram member initialisation
}
/*!
* Control creation for gHistogram
*/
void gHistogram::CreateControls()
{
////@begin gHistogram content construction
gHistogram* itemFrame1 = this;
gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, itemFrame1->ConvertDialogToPixels(wxSize(200, 150)), wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB );
gridHisto->SetDefaultColSize(50);
gridHisto->SetDefaultRowSize(25);
gridHisto->SetColLabelSize(25);
gridHisto->SetRowLabelSize(50);
gridHisto->CreateGrid(5, 5, wxGrid::wxGridSelectCells);
////@end gHistogram content construction
gridHisto->EnableEditing( false );
gridHisto->SetDefaultCellAlignment( wxALIGN_RIGHT, wxALIGN_CENTRE );
}
void gHistogram::execute()
{
if( myHistogram == NULL )
return;
myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() );
fillGrid();
}
void gHistogram::fillGrid()
{
int rowLabelWidth = 0;
wxFont labelFont = gridHisto->GetLabelFont();
bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() );
UINT16 idStat;
THistogramColumn curPlane;
if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) )
throw( exception() );
if( commStat )
curPlane = myHistogram->getCommSelectedPlane();
else
curPlane = myHistogram->getSelectedPlane();
gridHisto->BeginBatch();
if( (THistogramColumn)gridHisto->GetNumberCols() != myHistogram->getNumColumns( myHistogram->getCurrentStat() ) )
{
gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() );
gridHisto->AppendCols( myHistogram->getNumColumns( myHistogram->getCurrentStat() ) );
}
if( gridHisto->GetNumberRows() != myHistogram->getNumRows() + NUMTOTALS + 1 )
{
gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() );
gridHisto->AppendRows( myHistogram->getNumRows() + NUMTOTALS + 1 );
}
for( THistogramColumn iCol = 0; iCol < myHistogram->getNumColumns(); iCol++ )
{
if( commStat )
{
gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) );
myHistogram->setCommFirstCell( iCol, curPlane );
}
else
{
gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) );
myHistogram->setFirstCell( iCol, curPlane );
}
for( TObjectOrder iRow = 0; iRow < myHistogram->getNumRows(); iRow++ )
{
int w, h;
gridHisto->GetTextExtent( myHistogram->getRowLabel( iCol ), &w, &h, NULL, NULL, &labelFont );
if( rowLabelWidth == 0 || rowLabelWidth < w )
rowLabelWidth = w;
gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) );
if( commStat && myHistogram->endCommCell( iCol, curPlane ) ||
!commStat && myHistogram->endCell( iCol, curPlane ) )
gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
else
{
if( commStat )
{
if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram,
myHistogram->getCommCurrentValue( iCol, idStat, curPlane ) );
gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) );
myHistogram->setCommNextCell( iCol, curPlane );
}
else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
}
else
{
if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram,
myHistogram->getCurrentValue( iCol, idStat, curPlane ) );
gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) );
myHistogram->setNextCell( iCol, curPlane );
}
else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) );
}
}
}
HistogramTotals *histoTotals = myHistogram->getTotals( myHistogram->getCurrentStat() );
vector<TSemanticValue> totals;
histoTotals->getAll( totals, idStat, iCol, curPlane );
gridHisto->SetRowLabelValue( myHistogram->getNumRows(), "" );
for( int i = 0; i < NUMTOTALS; i++ )
{
gridHisto->SetRowLabelValue( myHistogram->getNumRows() + i + 1,
LabelConstructor::histoTotalLabel( (THistoTotals) i ) );
if( totals[ 0 ] > 0.0 )
{
string tmpStr;
tmpStr = LabelConstructor::histoCellLabel( myHistogram, totals[ i ] );
gridHisto->SetCellValue( myHistogram->getNumRows() + i + 1, iCol, wxString( tmpStr ) );
}
else gridHisto->SetCellValue( myHistogram->getNumRows() + i + 1, iCol, wxString( "-" ) );
}
}
gridHisto->SetRowLabelSize( rowLabelWidth );
gridHisto->Fit();
gridHisto->AutoSize();
gridHisto->EndBatch();
}
/*!
* Should we show tooltips?
*/
bool gHistogram::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap gHistogram::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin gHistogram bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end gHistogram bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon gHistogram::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin gHistogram icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end gHistogram icon retrieval
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013, Mozilla Foundation and 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 "stdafx.h"
#ifdef TEST_DECODING
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "wmcodecdspuuid")
#pragma comment(lib, "mfplat.lib")
#endif
static GMPPlatformAPI* sPlatformAPI = nullptr;
GMPErr
GMPCreateThread(GMPThread** aThread)
{
assert(sPlatformAPI);
return sPlatformAPI->createthread(aThread);
}
GMPErr
GMPRunOnMainThread(GMPTask* aTask)
{
assert(sPlatformAPI);
return sPlatformAPI->runonmainthread(aTask);
}
GMPErr
GMPSyncRunOnMainThread(GMPTask* aTask)
{
assert(sPlatformAPI);
return sPlatformAPI->syncrunonmainthread(aTask);
}
GMPErr
GMPCreateMutex(GMPMutex** aMutex)
{
assert(sPlatformAPI);
return sPlatformAPI->createmutex(aMutex);
}
#ifdef TEST_GMP_STORAGE
GMPErr
GMPOpenRecord(const char* aName,
uint32_t aNameLength,
GMPRecord** aOutRecord,
GMPRecordClient* aClient)
{
return sPlatformAPI->createrecord(aName, aNameLength, aOutRecord, aClient);
}
#endif
#ifdef TEST_GMP_TIMER
GMPErr
GMPSetTimer(GMPTask* aTask, int64_t aTimeoutMS)
{
return sPlatformAPI->settimer(aTask, aTimeoutMS);
}
#endif
GMPErr
GMPGetCurrentTime(GMPTimestamp* aOutTime)
{
return sPlatformAPI->getcurrenttime(aOutTime);
}
#ifdef TEST_NODE_ID
static std::string sNodeId;
const std::string& GetNodeId() {
return sNodeId;
}
#endif // TEST_NODE_ID
extern "C" {
HMODULE h264DecoderModule = 0;
GMP_EXPORT GMPErr
GMPInit(GMPPlatformAPI* aPlatformAPI)
{
assert(aPlatformAPI);
assert(aPlatformAPI->createthread);
assert(aPlatformAPI->runonmainthread);
assert(aPlatformAPI->syncrunonmainthread);
assert(aPlatformAPI->createmutex);
sPlatformAPI = aPlatformAPI;
#ifdef TEST_DECODING
// TODO: This is unlikely to succeed once the sandbox is enabled....
SUCCEEDED(CoInitializeEx(0, COINIT_MULTITHREADED));
const int MF_WIN7_VERSION = (0x0002 << 16 | MF_API_VERSION);
MFStartup(MF_WIN7_VERSION, MFSTARTUP_FULL);
h264DecoderModule = LoadLibraryA("msmpeg2vdec.dll");
#endif
return GMPNoErr;
}
GMP_EXPORT GMPErr
GMPGetAPI(const char* aApiName, void* aHostAPI, void** aPluginApi)
{
if (!strcmp(aApiName, "eme-decrypt")) {
*aPluginApi = new Decryptor(reinterpret_cast<GMPDecryptorHost*>(aHostAPI));
return GMPNoErr;
}
#ifdef TEST_DECODING
if (!strcmp(aApiName, "decode-video")) {
*aPluginApi = new VideoDecoder(reinterpret_cast<GMPVideoHost*>(aHostAPI));
return GMPNoErr;
}
if (!strcmp(aApiName, "decode-audio")) {
*aPluginApi = new AudioDecoder(reinterpret_cast<GMPAudioHost*>(aHostAPI));
return GMPNoErr;
}
#endif
#ifdef TEST_GMP_ASYNC_SHUTDOWN
if (!strcmp(aApiName, "async-shutdown")) {
*aPluginApi = new AsyncShutdown(reinterpret_cast<GMPAsyncShutdownHost*>(aHostAPI));
return GMPNoErr;
}
#endif
return GMPGenericErr;
}
GMP_EXPORT void
GMPShutdown(void)
{
#ifdef TEST_DECODING
FreeLibrary(h264DecoderModule);
MFShutdown();
CoUninitialize();
#endif
sPlatformAPI = nullptr;
}
#ifdef TEST_NODE_ID
GMP_EXPORT void
GMPSetNodeId(const char* aNodeId, uint32_t aLength)
{
sNodeId = std::string(aNodeId, aNodeId + aLength);
}
#endif // TEST_NODE_ID
} // extern "C"
<commit_msg>Use GMP_API_* macros to instantiate API objects, so that when the API version changes, we automatically fail to instantiate them.<commit_after>/*
* Copyright 2013, Mozilla Foundation and 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 "stdafx.h"
#ifdef TEST_DECODING
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "wmcodecdspuuid")
#pragma comment(lib, "mfplat.lib")
#endif
static GMPPlatformAPI* sPlatformAPI = nullptr;
GMPErr
GMPCreateThread(GMPThread** aThread)
{
assert(sPlatformAPI);
return sPlatformAPI->createthread(aThread);
}
GMPErr
GMPRunOnMainThread(GMPTask* aTask)
{
assert(sPlatformAPI);
return sPlatformAPI->runonmainthread(aTask);
}
GMPErr
GMPSyncRunOnMainThread(GMPTask* aTask)
{
assert(sPlatformAPI);
return sPlatformAPI->syncrunonmainthread(aTask);
}
GMPErr
GMPCreateMutex(GMPMutex** aMutex)
{
assert(sPlatformAPI);
return sPlatformAPI->createmutex(aMutex);
}
#ifdef TEST_GMP_STORAGE
GMPErr
GMPOpenRecord(const char* aName,
uint32_t aNameLength,
GMPRecord** aOutRecord,
GMPRecordClient* aClient)
{
return sPlatformAPI->createrecord(aName, aNameLength, aOutRecord, aClient);
}
#endif
#ifdef TEST_GMP_TIMER
GMPErr
GMPSetTimer(GMPTask* aTask, int64_t aTimeoutMS)
{
return sPlatformAPI->settimer(aTask, aTimeoutMS);
}
#endif
GMPErr
GMPGetCurrentTime(GMPTimestamp* aOutTime)
{
return sPlatformAPI->getcurrenttime(aOutTime);
}
#ifdef TEST_NODE_ID
static std::string sNodeId;
const std::string& GetNodeId() {
return sNodeId;
}
#endif // TEST_NODE_ID
extern "C" {
HMODULE h264DecoderModule = 0;
GMP_EXPORT GMPErr
GMPInit(GMPPlatformAPI* aPlatformAPI)
{
assert(aPlatformAPI);
assert(aPlatformAPI->createthread);
assert(aPlatformAPI->runonmainthread);
assert(aPlatformAPI->syncrunonmainthread);
assert(aPlatformAPI->createmutex);
sPlatformAPI = aPlatformAPI;
#ifdef TEST_DECODING
// TODO: This is unlikely to succeed once the sandbox is enabled....
SUCCEEDED(CoInitializeEx(0, COINIT_MULTITHREADED));
const int MF_WIN7_VERSION = (0x0002 << 16 | MF_API_VERSION);
MFStartup(MF_WIN7_VERSION, MFSTARTUP_FULL);
h264DecoderModule = LoadLibraryA("msmpeg2vdec.dll");
#endif
return GMPNoErr;
}
GMP_EXPORT GMPErr
GMPGetAPI(const char* aApiName, void* aHostAPI, void** aPluginApi)
{
if (!strcmp(aApiName, GMP_API_DECRYPTOR)) {
*aPluginApi = new Decryptor(reinterpret_cast<GMPDecryptorHost*>(aHostAPI));
return GMPNoErr;
}
#ifdef TEST_DECODING
if (!strcmp(aApiName, GMP_API_VIDEO_DECODER)) {
*aPluginApi = new VideoDecoder(reinterpret_cast<GMPVideoHost*>(aHostAPI));
return GMPNoErr;
}
if (!strcmp(aApiName, GMP_API_AUDIO_DECODER)) {
*aPluginApi = new AudioDecoder(reinterpret_cast<GMPAudioHost*>(aHostAPI));
return GMPNoErr;
}
#endif
#ifdef TEST_GMP_ASYNC_SHUTDOWN
if (!strcmp(aApiName, GMP_API_ASYNC_SHUTDOWN)) {
*aPluginApi = new AsyncShutdown(reinterpret_cast<GMPAsyncShutdownHost*>(aHostAPI));
return GMPNoErr;
}
#endif
return GMPGenericErr;
}
GMP_EXPORT void
GMPShutdown(void)
{
#ifdef TEST_DECODING
FreeLibrary(h264DecoderModule);
MFShutdown();
CoUninitialize();
#endif
sPlatformAPI = nullptr;
}
#ifdef TEST_NODE_ID
GMP_EXPORT void
GMPSetNodeId(const char* aNodeId, uint32_t aLength)
{
sNodeId = std::string(aNodeId, aNodeId + aLength);
}
#endif // TEST_NODE_ID
} // extern "C"
<|endoftext|> |
<commit_before>/*!
* FrameReceiverZMQRxThread.cpp
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include "FrameReceiverZMQRxThread.h"
#include <unistd.h>
using namespace FrameReceiver;
FrameReceiverZMQRxThread::FrameReceiverZMQRxThread(FrameReceiverConfig& config, LoggerPtr& logger,
SharedBufferManagerPtr buffer_manager, FrameDecoderPtr frame_decoder, unsigned int tick_period_ms) :
FrameReceiverRxThread(config, logger, buffer_manager, frame_decoder, tick_period_ms),
logger_(logger),
skt_channel_(ZMQ_PULL)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "FrameReceiverZMQRxThread constructor entered....");
// Store the frame decoder as a UDP type frame decoder
frame_decoder_ = boost::dynamic_pointer_cast<FrameDecoderZMQ>(frame_decoder);
}
FrameReceiverZMQRxThread::~FrameReceiverZMQRxThread()
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Destroying FrameReceiverZMQRxThread....");
}
void FrameReceiverZMQRxThread::run_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Running ZMQ RX thread service");
for (std::vector<uint16_t>::iterator rx_port_itr = config_.rx_ports_.begin(); rx_port_itr != config_.rx_ports_.end(); rx_port_itr++)
{
uint16_t rx_port = *rx_port_itr;
std::stringstream ss;
ss << "tcp://" << config_.rx_address_ << ":" << rx_port;
skt_channel_.connect(ss.str().c_str());
// Register the IPC channel with the reactor
reactor_.register_channel(skt_channel_, boost::bind(&FrameReceiverZMQRxThread::handle_receive_socket, this));
}
}
void FrameReceiverZMQRxThread::cleanup_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Cleaning up ZMQ RX thread service");
// Remove the IPC channel from the reactor
reactor_.remove_channel(skt_channel_);
skt_channel_.close();
}
void FrameReceiverZMQRxThread::handle_receive_socket()
{
// Receive a message from the main thread channel and place it directly into the
// provided memory buffer
size_t msg_len = skt_channel_.recv_raw(frame_decoder_->get_next_message_buffer());
LOG4CXX_DEBUG_LEVEL(3, logger_, "RX thread received " << msg_len << " bytes on IPC channel, payload buffer address "
<< frame_decoder_->get_next_message_buffer());
FrameDecoder::FrameReceiveState frame_receive_state = frame_decoder_->process_message(msg_len);
// Now check for end of messsage
if (skt_channel_.eom()){
// Message complete, notify the decoder
frame_decoder_->frame_meta_data(1);
}
}
<commit_msg>Prevented get_next_message_buffer from being called twice<commit_after>/*!
* FrameReceiverZMQRxThread.cpp
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include "FrameReceiverZMQRxThread.h"
#include <unistd.h>
using namespace FrameReceiver;
FrameReceiverZMQRxThread::FrameReceiverZMQRxThread(FrameReceiverConfig& config, LoggerPtr& logger,
SharedBufferManagerPtr buffer_manager, FrameDecoderPtr frame_decoder, unsigned int tick_period_ms) :
FrameReceiverRxThread(config, logger, buffer_manager, frame_decoder, tick_period_ms),
logger_(logger),
skt_channel_(ZMQ_PULL)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "FrameReceiverZMQRxThread constructor entered....");
// Store the frame decoder as a UDP type frame decoder
frame_decoder_ = boost::dynamic_pointer_cast<FrameDecoderZMQ>(frame_decoder);
}
FrameReceiverZMQRxThread::~FrameReceiverZMQRxThread()
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Destroying FrameReceiverZMQRxThread....");
}
void FrameReceiverZMQRxThread::run_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Running ZMQ RX thread service");
for (std::vector<uint16_t>::iterator rx_port_itr = config_.rx_ports_.begin(); rx_port_itr != config_.rx_ports_.end(); rx_port_itr++)
{
uint16_t rx_port = *rx_port_itr;
std::stringstream ss;
ss << "tcp://" << config_.rx_address_ << ":" << rx_port;
skt_channel_.connect(ss.str().c_str());
// Register the IPC channel with the reactor
reactor_.register_channel(skt_channel_, boost::bind(&FrameReceiverZMQRxThread::handle_receive_socket, this));
}
}
void FrameReceiverZMQRxThread::cleanup_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Cleaning up ZMQ RX thread service");
// Remove the IPC channel from the reactor
reactor_.remove_channel(skt_channel_);
skt_channel_.close();
}
void FrameReceiverZMQRxThread::handle_receive_socket()
{
// Receive a message from the main thread channel and place it directly into the
// provided memory buffer
void* nextMessageBuffer = frame_decoder_->get_next_message_buffer();
size_t msg_len = skt_channel_.recv_raw(nextMessageBuffer);
LOG4CXX_DEBUG_LEVEL(3, logger_, "RX thread received " << msg_len << " bytes on IPC channel, payload buffer address "
<< nextMessageBuffer);
FrameDecoder::FrameReceiveState frame_receive_state = frame_decoder_->process_message(msg_len);
// Now check for end of messsage
if (skt_channel_.eom()){
// Message complete, notify the decoder
frame_decoder_->frame_meta_data(1);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: registerservices.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2003-03-25 18:21:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_PLUGINFRAME_HXX_
#include <services/pluginframe.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::PlugInFrame )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::DocumentProperties )
COMPONENTINFO( ::framework::SoundHandler )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::PlugInFrame ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::DocumentProperties ) else
IFFACTORY( ::framework::SoundHandler ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper )
)
<commit_msg>INTEGRATION: CWS filtercfg (1.17.50); FILE MERGED 2003/08/04 05:45:33 as 1.17.50.1: #102620# first step: remove filter/type cfg related services; remove obsolete plugin classes<commit_after>/*************************************************************************
*
* $RCSfile: registerservices.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2004-01-28 14:38:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::DocumentProperties )
COMPONENTINFO( ::framework::SoundHandler )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::DocumentProperties ) else
IFFACTORY( ::framework::SoundHandler ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper )
)
<|endoftext|> |
<commit_before>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static const char* kMimeTypes[][2] = {
{"image/jpeg", ".jpg"},
{"image/jpeg", ".jpeg"},
{"image/png", ".png"},
};
void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
const cgltf_material& material = data->materials[i];
if (material.has_pbr_metallic_roughness)
{
const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
images[pbr.base_color_texture.texture->image - data->images].srgb = true;
}
if (material.has_pbr_specular_glossiness)
{
const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
}
if (material.emissive_texture.texture && material.emissive_texture.texture->image)
images[material.emissive_texture.texture->image - data->images].srgb = true;
if (material.normal_texture.texture && material.normal_texture.texture->image)
images[material.normal_texture.texture->image - data->images].normal_map = true;
}
}
const char* inferMimeType(const char* path)
{
const char* ext = strrchr(path, '.');
if (!ext)
return "";
std::string extl = ext;
for (size_t i = 0; i < extl.length(); ++i)
extl[i] = char(tolower(extl[i]));
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (extl == kMimeTypes[i][1])
return kMimeTypes[i][0];
return "";
}
static const char* mimeExtension(const char* mime_type)
{
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (strcmp(kMimeTypes[i][0], mime_type) == 0)
return kMimeTypes[i][1];
return ".raw";
}
#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
var cp = require('child_process');
var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
return ret.status == null ? 256 : ret.status;
});
EM_JS(const char*, readenv, (const char* name), {
var val = process.env[UTF8ToString(name)];
if (!val) return 0;
var ret = _malloc(lengthBytesUTF8(val) + 1);
stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
std::string ignore = "nul";
#else
std::string ignore = "/dev/null";
#endif
std::string cmd = cmd_;
if (ignore_stdout)
(cmd += " >") += ignore;
if (ignore_stderr)
(cmd += " 2>") += ignore;
return system(cmd.c_str());
}
static const char* readenv(const char* name)
{
return getenv(name);
}
#endif
bool checkBasis(bool verbose)
{
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
cmd += " -version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
(void)scale;
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".basis");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " -q ";
cmd += ql;
cmd += " -mipmap";
if (normal_map)
{
cmd += " -normal_map";
// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
}
else if (!srgb)
{
cmd += " -linear";
}
if (uastc)
{
cmd += " -uastc";
}
cmd += " -file ";
cmd += temp_input.path;
cmd += " -output_file ";
cmd += temp_output.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
bool checkKtx(bool verbose)
{
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".ktx2");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --2d";
cmd += " --t2";
cmd += " --automipmap";
if (scale < 1)
{
char sl[128];
sprintf(sl, "%g", scale);
cmd += " --scale ";
cmd += sl;
}
if (uastc)
{
cmd += " --uastc 2";
}
else
{
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " --bcmp";
cmd += " --qlevel ";
cmd += ql;
// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
if (normal_map)
cmd += " --normal_map";
}
if (srgb)
cmd += " --srgb";
else
cmd += " --linear";
cmd += " ";
cmd += temp_output.path;
cmd += " ";
cmd += temp_input.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<commit_msg>gltfpack: Always use zstd compression with UASTC<commit_after>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static const char* kMimeTypes[][2] = {
{"image/jpeg", ".jpg"},
{"image/jpeg", ".jpeg"},
{"image/png", ".png"},
};
void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
const cgltf_material& material = data->materials[i];
if (material.has_pbr_metallic_roughness)
{
const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
images[pbr.base_color_texture.texture->image - data->images].srgb = true;
}
if (material.has_pbr_specular_glossiness)
{
const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
}
if (material.emissive_texture.texture && material.emissive_texture.texture->image)
images[material.emissive_texture.texture->image - data->images].srgb = true;
if (material.normal_texture.texture && material.normal_texture.texture->image)
images[material.normal_texture.texture->image - data->images].normal_map = true;
}
}
const char* inferMimeType(const char* path)
{
const char* ext = strrchr(path, '.');
if (!ext)
return "";
std::string extl = ext;
for (size_t i = 0; i < extl.length(); ++i)
extl[i] = char(tolower(extl[i]));
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (extl == kMimeTypes[i][1])
return kMimeTypes[i][0];
return "";
}
static const char* mimeExtension(const char* mime_type)
{
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (strcmp(kMimeTypes[i][0], mime_type) == 0)
return kMimeTypes[i][1];
return ".raw";
}
#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
var cp = require('child_process');
var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
return ret.status == null ? 256 : ret.status;
});
EM_JS(const char*, readenv, (const char* name), {
var val = process.env[UTF8ToString(name)];
if (!val) return 0;
var ret = _malloc(lengthBytesUTF8(val) + 1);
stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
std::string ignore = "nul";
#else
std::string ignore = "/dev/null";
#endif
std::string cmd = cmd_;
if (ignore_stdout)
(cmd += " >") += ignore;
if (ignore_stderr)
(cmd += " 2>") += ignore;
return system(cmd.c_str());
}
static const char* readenv(const char* name)
{
return getenv(name);
}
#endif
bool checkBasis(bool verbose)
{
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
cmd += " -version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
(void)scale;
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".basis");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " -q ";
cmd += ql;
cmd += " -mipmap";
if (normal_map)
{
cmd += " -normal_map";
// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
}
else if (!srgb)
{
cmd += " -linear";
}
if (uastc)
{
cmd += " -uastc";
}
cmd += " -file ";
cmd += temp_input.path;
cmd += " -output_file ";
cmd += temp_output.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
bool checkKtx(bool verbose)
{
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".ktx2");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --2d";
cmd += " --t2";
cmd += " --automipmap";
if (scale < 1)
{
char sl[128];
sprintf(sl, "%g", scale);
cmd += " --scale ";
cmd += sl;
}
if (uastc)
{
cmd += " --uastc 2";
cmd += " --zcmp 9";
}
else
{
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " --bcmp";
cmd += " --qlevel ";
cmd += ql;
// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
if (normal_map)
cmd += " --normal_map";
}
if (srgb)
cmd += " --srgb";
else
cmd += " --linear";
cmd += " ";
cmd += temp_output.path;
cmd += " ";
cmd += temp_input.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google, Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
/*
* Draw 50 semi-transparent circles with pseudo-random positions, radii, and
* colors, using the default blend mode (SRC OVER). Use of SkRandom with
* default seed means results SHOULD be identical across multiple platforms.
*/
DEF_SIMPLE_GM(bubbles, canvas, 512, 512) {
canvas->clear(SK_ColorWHITE);
SkPaint p;
p.setAntiAlias(true);
SkRandom rand;
auto pos_min = SkIntToScalar(0);
auto pos_max = SkIntToScalar(511);
auto radius_min = SkIntToScalar(0);
auto radius_max = SkIntToScalar(128);
auto color_min = SkIntToScalar(0);
auto color_max = SkIntToScalar(255);
const int NUM_BUBBLES = 50;
for (int i = 0; i < NUM_BUBBLES; i++) {
auto cx = rand.nextRangeScalar(pos_min, pos_max);
auto cy = rand.nextRangeScalar(pos_min, pos_max);
auto radius = rand.nextRangeScalar(radius_min, radius_max);
auto a = (U8CPU)128;
auto r = (U8CPU)rand.nextRangeScalar(color_min, color_max);
auto g = (U8CPU)rand.nextRangeScalar(color_min, color_max);
auto b = (U8CPU)rand.nextRangeScalar(color_min, color_max);
p.setColor(SkColorSetARGB(a, r, g, b));
canvas->drawCircle(cx, cy, radius, p);
}
}
<commit_msg>Remove bubbles GM<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.