text
stringlengths 54
60.6k
|
---|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#include <string>
#include <vector>
#include <memory>
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif
#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/exceptions.hh>
#include "problems/interfaces.hh"
#include "problems/default.hh"
#include "problems/ESV2007.hh"
#include "../playground/linearelliptic/problems/mixed-boundaries.hh"
#include "../playground/linearelliptic/problems/thermalblock.hh"
namespace Dune {
namespace HDD {
namespace internal {
void lib_exists();
} // namespace internal
namespace LinearElliptic {
namespace internal {
template< class E, class D, int d, class R, int r = 1 >
class ProblemProviderBase
{
public:
typedef ProblemInterface< E, D, d, R, r > InterfaceType;
protected:
template< class ProblemType >
static std::unique_ptr< ProblemType > call_create(const Stuff::Common::ConfigTree& config)
{
if (config.empty())
return ProblemType::create();
else
return ProblemType::create(config);
} // ... call_create(...)
public:
static std::vector< std::string > available()
{
return {
Problems::Default< E, D, d, R, r >::static_id()
, Problems::MixedBoundaries< E, D, d, R, r >::static_id()
, Problems::Thermalblock< E, D, d, R, r >::static_id()
};
} // ... available(...)
static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
const std::string sub_name = "")
{
if (type == Problems::Default< E, D, d, R, r >::static_id())
return Problems::Default< E, D, d, R, r >::default_config(sub_name);
else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
return Problems::MixedBoundaries< E, D, d, R, r >::default_config(sub_name);
else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
return Problems::Thermalblock< E, D, d, R, r >::default_config(sub_name);
else
DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
"'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
} // ... default_config(...)
static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
const Stuff::Common::ConfigTree config = default_config(available()[0]))
{
if (type == Problems::Default< E, D, d, R, r >::static_id())
return call_create< Problems::Default< E, D, d, R, r > >(config);
else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
return call_create< Problems::MixedBoundaries< E, D, d, R, r > >(config);
else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
return call_create< Problems::Thermalblock< E, D, d, R, r > >(config);
else
DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
"'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
} // ... create(...)
}; // clas ProblemProviderBase
} // namespace internal
template< class E, class D, int d, class R, int r = 1 >
class ProblemProvider
: public internal::ProblemProviderBase< E, D, d, R, r >
{};
template< class E, class D, class R >
class ProblemProvider< E, D, 2, R, 1 >
: public internal::ProblemProviderBase< E, D, 2, R, 1 >
{
static const unsigned int d = 2;
static const unsigned int r = 1;
typedef internal::ProblemProviderBase< E, D, d, R, r > BaseType;
public:
using typename BaseType::InterfaceType;
static std::vector< std::string > available()
{
auto base = BaseType::available();
base.push_back(Problems::ESV2007< E, D, d, R, r >::static_id());
return base;
} // ... available(...)
static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
const std::string sub_name = "")
{
if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
return Problems::ESV2007< E, D, d, R, r >::default_config(sub_name);
else
return BaseType::default_config(type, sub_name);
} // ... default_config(...)
static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
const Stuff::Common::ConfigTree config = Stuff::Common::ConfigTree())
{
if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
return BaseType::template call_create< Problems::ESV2007< E, D, d, R, r > >(config);
else
return BaseType::create(type, config);
} // ... create(...)
}; // clas ProblemProvider< ..., 2, ... 1 >
#if HAVE_ALUGRID
extern template class ProblemProvider< typename ALUConformGrid< 2, 2 >::template Codim< 0 >::Entity,
double, 2, double, 1 >;
#endif // HAVE_ALUGRID
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
<commit_msg>[linearelliptic.problems] added OS2014<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#include <string>
#include <vector>
#include <memory>
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif
#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/exceptions.hh>
#include "problems/interfaces.hh"
#include "problems/default.hh"
#include "problems/ESV2007.hh"
#include "../playground/linearelliptic/problems/mixed-boundaries.hh"
#include "../playground/linearelliptic/problems/thermalblock.hh"
#include "../playground/linearelliptic/problems/OS2014.hh"
namespace Dune {
namespace HDD {
namespace internal {
void lib_exists();
} // namespace internal
namespace LinearElliptic {
namespace internal {
template< class E, class D, int d, class R, int r = 1 >
class ProblemProviderBase
{
public:
typedef ProblemInterface< E, D, d, R, r > InterfaceType;
protected:
template< class ProblemType >
static std::unique_ptr< ProblemType > call_create(const Stuff::Common::ConfigTree& config)
{
if (config.empty())
return ProblemType::create();
else
return ProblemType::create(config);
} // ... call_create(...)
public:
static std::vector< std::string > available()
{
return {
Problems::Default< E, D, d, R, r >::static_id()
, Problems::MixedBoundaries< E, D, d, R, r >::static_id()
, Problems::Thermalblock< E, D, d, R, r >::static_id()
};
} // ... available(...)
static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
const std::string sub_name = "")
{
if (type == Problems::Default< E, D, d, R, r >::static_id())
return Problems::Default< E, D, d, R, r >::default_config(sub_name);
else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
return Problems::MixedBoundaries< E, D, d, R, r >::default_config(sub_name);
else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
return Problems::Thermalblock< E, D, d, R, r >::default_config(sub_name);
else
DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
"'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
} // ... default_config(...)
static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
const Stuff::Common::ConfigTree config = default_config(available()[0]))
{
if (type == Problems::Default< E, D, d, R, r >::static_id())
return call_create< Problems::Default< E, D, d, R, r > >(config);
else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
return call_create< Problems::MixedBoundaries< E, D, d, R, r > >(config);
else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
return call_create< Problems::Thermalblock< E, D, d, R, r > >(config);
else
DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
"'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
} // ... create(...)
}; // clas ProblemProviderBase
} // namespace internal
template< class E, class D, int d, class R, int r = 1 >
class ProblemProvider
: public internal::ProblemProviderBase< E, D, d, R, r >
{};
template< class E, class D, class R >
class ProblemProvider< E, D, 2, R, 1 >
: public internal::ProblemProviderBase< E, D, 2, R, 1 >
{
static const unsigned int d = 2;
static const unsigned int r = 1;
typedef internal::ProblemProviderBase< E, D, d, R, r > BaseType;
public:
using typename BaseType::InterfaceType;
static std::vector< std::string > available()
{
auto base = BaseType::available();
base.push_back(Problems::ESV2007< E, D, d, R, r >::static_id());
base.push_back(Problems::OS2014< E, D, d, R, r >::static_id());
return base;
} // ... available(...)
static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
const std::string sub_name = "")
{
if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
return Problems::ESV2007< E, D, d, R, r >::default_config(sub_name);
else if (type == Problems::OS2014< E, D, d, R, r >::static_id())
return Problems::OS2014< E, D, d, R, r >::default_config(sub_name);
else
return BaseType::default_config(type, sub_name);
} // ... default_config(...)
static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
const Stuff::Common::ConfigTree config = Stuff::Common::ConfigTree())
{
if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
return BaseType::template call_create< Problems::ESV2007< E, D, d, R, r > >(config);
else if (type == Problems::OS2014< E, D, d, R, r >::static_id())
return BaseType::template call_create< Problems::OS2014< E, D, d, R, r > >(config);
else
return BaseType::create(type, config);
} // ... create(...)
}; // clas ProblemProvider< ..., 2, ... 1 >
#if HAVE_ALUGRID
extern template class ProblemProvider< typename ALUConformGrid< 2, 2 >::template Codim< 0 >::Entity,
double, 2, double, 1 >;
#endif // HAVE_ALUGRID
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
<|endoftext|> |
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#define IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#include "iceoryx_posh/internal/popo/building_blocks/event_variable_data.hpp"
#include <cstdint>
namespace iox
{
namespace popo
{
class EventNotifier
{
public:
EventNotifier(EventVariableData& dataRef, const uint64_t index) noexcept
{
}
void notify()
{
}
};
} // namespace popo
} // namespace iox
#endif
<commit_msg>iox-#350 implemented event notifier<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#define IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#include "iceoryx_posh/internal/popo/building_blocks/event_variable_data.hpp"
#include <cstdint>
namespace iox
{
namespace popo
{
class EventNotifier
{
public:
EventNotifier(EventVariableData& dataRef, const uint64_t index) noexcept
: m_pointerToEventVariableData(&dataRef)
, m_notificationIndex(index)
{
}
void notify()
{
m_pointerToEventVariableData->m_activeNotifications[m_notificationIndex] = true;
m_pointerToEventVariableData->m_semaphore.post();
}
private:
EventVariableData* m_pointerToEventVariableData{nullptr};
uint64_t m_notificationIndex{0U};
};
} // namespace popo
} // namespace iox
#endif
<|endoftext|> |
<commit_before>// Author: Akira Okumura 2012/11/26
// Examples for simple optical systems which use products by Edmund Optics.
// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t m = AOpticsManager::m();
void NT49665()
{
// Aspherized achromatic lens.
// http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953
// ZEMAX data is available at
// http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx
AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665");
// Make the world
TGeoBBox* box = new TGeoBBox("box", 10*cm, 10*cm, 10*cm);
AOpticalComponent *top = new AOpticalComponent("top", box);
manager->SetTopVolume(top);
Double_t rmax = 12.5*mm;
Double_t rmin = 0.*mm;
Double_t d1 = 9.0*mm;
Double_t d2 = 2.5*mm;
Double_t d3 = 8e-2*mm;
Double_t d4 = 4.40605264801e1*mm;
Double_t z1 = 0*mm;
Double_t z2 = z1 + d1;
Double_t z3 = z2 + d2;
Double_t z4 = z3 + d3;
Double_t z5 = z4 + d4;
Double_t curv1 = 1./(28.5*mm);
Double_t curv2 = 1./(-31.0*mm);
Double_t curv3 = 1./(-66.0*mm);
Double_t curv4 = 1./(-63.0*mm);
AGeoAsphericDisk* disk1
= new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin);
AGeoAsphericDisk* disk2
= new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin);
AGeoAsphericDisk* disk3
= new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin);
Double_t coefficients[3] = {0, 4.66252900195e-6/(mm*mm*mm), -8.02842124899e-9/(mm*mm*mm*mm*mm)};
//Double_t coefficients[3] = {4.66252900195e-6/(mm*mm), -8.02842124899e-9/(mm*mm*mm*mm), 0};
disk3->SetPolynomials(0, 0, 3, coefficients);
// Ohara S-FSL5
// http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf
ASellmeierFormula* FSL5
= new ASellmeierFormula(1.17447043e0, 1.40056154e-2, 1.19272435e0,
8.41855181e-3, -5.81790767e-2, 1.29599726e2);
// should be 1.48749
std::cout << FSL5->GetIndex(0.58756*um) << std::endl;
// S-TIH13
// http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf
ASellmeierFormula* TIH13
= new ASellmeierFormula(1.62224674e0, 2.93844589e-1, 1.99225164e0,
1.18368386e-2,5.90208025e-2, 1.71959976e2);
// should be 1.74077
std::cout << TIH13->GetIndex(0.58756*um) << std::endl;
ALens* lens1 = new ALens("lens1", disk1);
lens1->SetRefractiveIndex(FSL5);
ALens* lens2 = new ALens("lens2", disk2);
lens2->SetRefractiveIndex(TIH13);
ALens* lens3 = new ALens("lens3", disk3);
lens3->SetConstantRefractiveIndex(1.517);
top->AddNode(lens1, 1);
top->AddNode(lens2, 1);
top->AddNode(lens3, 1);
Double_t origin[3] = {0, 0, z5 + 1*um};
TGeoBBox* box2 = new TGeoBBox("box2", 1*mm, 1*mm, 1*um, origin);
AFocalSurface* screen = new AFocalSurface("screen", box2);
top->AddNode(screen, 1);
manager->CloseGeometry();
top->Draw("ogl");
TGeoRotation* rot = new TGeoRotation;
rot->SetAngles(180., 0., 0.);
TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15*mm);
const Int_t nColor = 3;
Double_t wavelength[nColor] = {486.1*nm, 587.6*nm, 656.3*nm}; // n_F, n_d, n_C
TH2D* spot[nColor];
for(Int_t j = 0; j < nColor; j++){
ARayArray* array = ARayShooter::Circle(wavelength[j], rmax*1.1, 50, 4, rot, tr);
manager->TraceNonSequential(*array);
spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X (#it{#mu}m);Y (#it{#mu}m)", wavelength[j]/nm), 500, -25, 25, 500, -25, 25);
TObjArray* focused = array->GetFocused();
for(Int_t i = 0; i <= focused->GetLast(); i++){
ARay* ray = (ARay*)(*focused)[i];
if(j == 1 && i%10 == 0){
ray->MakePolyLine3D()->Draw();
} // if
Double_t p[4];
ray->GetLastPoint(p);
spot[j]->Fill(p[0]/um, p[1]/um);
} // i
delete array;
} // j
TCanvas* can = new TCanvas("can", "can", 1200, 400);
can->Divide(3, 1, 1e-10, 1e-10);
for(Int_t j = 0; j < nColor; j++){
can->cd(j + 1);
spot[j]->Draw("colz");
} // j
}
<commit_msg>Change the function name<commit_after>// Author: Akira Okumura 2012/11/26
// Examples for simple optical systems which use products by Edmund Optics.
// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t m = AOpticsManager::m();
void EdmundOptics()
{
// Aspherized achromatic lens.
// http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953
// ZEMAX data is available at
// http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx
AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665");
// Make the world
TGeoBBox* box = new TGeoBBox("box", 10*cm, 10*cm, 10*cm);
AOpticalComponent *top = new AOpticalComponent("top", box);
manager->SetTopVolume(top);
Double_t rmax = 12.5*mm;
Double_t rmin = 0.*mm;
Double_t d1 = 9.0*mm;
Double_t d2 = 2.5*mm;
Double_t d3 = 8e-2*mm;
Double_t d4 = 4.40605264801e1*mm;
Double_t z1 = 0*mm;
Double_t z2 = z1 + d1;
Double_t z3 = z2 + d2;
Double_t z4 = z3 + d3;
Double_t z5 = z4 + d4;
Double_t curv1 = 1./(28.5*mm);
Double_t curv2 = 1./(-31.0*mm);
Double_t curv3 = 1./(-66.0*mm);
Double_t curv4 = 1./(-63.0*mm);
AGeoAsphericDisk* disk1
= new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin);
AGeoAsphericDisk* disk2
= new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin);
AGeoAsphericDisk* disk3
= new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin);
Double_t coefficients[3] = {0, 4.66252900195e-6/(mm*mm*mm), -8.02842124899e-9/(mm*mm*mm*mm*mm)};
disk3->SetPolynomials(0, 0, 3, coefficients);
// Ohara S-FSL5
// http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf
ASellmeierFormula* FSL5
= new ASellmeierFormula(1.17447043e0, 1.40056154e-2, 1.19272435e0,
8.41855181e-3, -5.81790767e-2, 1.29599726e2);
// should be 1.48749
std::cout << FSL5->GetIndex(0.58756*um) << std::endl;
// S-TIH13
// http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf
ASellmeierFormula* TIH13
= new ASellmeierFormula(1.62224674e0, 2.93844589e-1, 1.99225164e0,
1.18368386e-2,5.90208025e-2, 1.71959976e2);
// should be 1.74077
std::cout << TIH13->GetIndex(0.58756*um) << std::endl;
ALens* lens1 = new ALens("lens1", disk1);
lens1->SetRefractiveIndex(FSL5);
ALens* lens2 = new ALens("lens2", disk2);
lens2->SetRefractiveIndex(TIH13);
ALens* lens3 = new ALens("lens3", disk3);
lens3->SetConstantRefractiveIndex(1.517);
top->AddNode(lens1, 1);
top->AddNode(lens2, 1);
top->AddNode(lens3, 1);
Double_t origin[3] = {0, 0, z5 + 1*um};
TGeoBBox* box2 = new TGeoBBox("box2", 1*mm, 1*mm, 1*um, origin);
AFocalSurface* screen = new AFocalSurface("screen", box2);
top->AddNode(screen, 1);
manager->CloseGeometry();
top->Draw("ogl");
TGeoRotation* rot = new TGeoRotation;
rot->SetAngles(180., 0., 0.);
TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15*mm);
const Int_t nColor = 3;
Double_t wavelength[nColor] = {486.1*nm, 587.6*nm, 656.3*nm}; // n_F, n_d, n_C
TH2D* spot[nColor];
for(Int_t j = 0; j < nColor; j++){
ARayArray* array = ARayShooter::Circle(wavelength[j], rmax*1.1, 50, 4, rot, tr);
manager->TraceNonSequential(*array);
spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X (#it{#mu}m);Y (#it{#mu}m)", wavelength[j]/nm), 500, -25, 25, 500, -25, 25);
TObjArray* focused = array->GetFocused();
for(Int_t i = 0; i <= focused->GetLast(); i++){
ARay* ray = (ARay*)(*focused)[i];
if(j == 1 && i%10 == 0){
ray->MakePolyLine3D()->Draw();
} // if
Double_t p[4];
ray->GetLastPoint(p);
spot[j]->Fill(p[0]/um, p[1]/um);
} // i
delete array;
} // j
TCanvas* can = new TCanvas("can", "can", 1200, 400);
can->Divide(3, 1, 1e-10, 1e-10);
for(int i = 0; i < nColor; i++){
can->cd(i + 1);
spot[i]->Draw("colz");
} // i
}
<|endoftext|> |
<commit_before><commit_msg>android: An attempt to handle mouse events.<commit_after><|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// template <class T>
// struct hash
// : public unary_function<T, size_t>
// {
// size_t operator()(T val) const;
// };
// Not very portable
#include <functional>
#include <cassert>
#include <type_traits>
#include <cstddef>
#include <limits>
template <class T>
void
test()
{
typedef std::hash<T> H;
static_assert((std::is_same<typename H::argument_type, T>::value), "" );
static_assert((std::is_same<typename H::result_type, std::size_t>::value), "" );
H h;
for (int i = 0; i <= 5; ++i)
{
T t(i);
if (sizeof(T) <= sizeof(std::size_t))
assert(h(t) == t);
}
}
int main()
{
test<bool>();
test<char>();
test<signed char>();
test<unsigned char>();
test<char16_t>();
test<char32_t>();
test<wchar_t>();
test<short>();
test<unsigned short>();
test<int>();
test<unsigned int>();
test<long>();
test<unsigned long>();
test<long long>();
test<unsigned long long>();
// LWG #2119
test<std::ptrdiff_t>();
test<size_t>();
test<int8_t>();
test<int16_t>();
test<int32_t>();
test<int64_t>();
test<int_fast8_t>();
test<int_fast16_t>();
test<int_fast32_t>();
test<int_fast64_t>();
test<int_least8_t>();
test<int_least16_t>();
test<int_least32_t>();
test<int_least64_t>();
test<intmax_t>();
test<intptr_t>();
test<uint8_t>();
test<uint16_t>();
test<uint32_t>();
test<uint64_t>();
test<uint_fast8_t>();
test<uint_fast16_t>();
test<uint_fast32_t>();
test<uint_fast64_t>();
test<uint_least8_t>();
test<uint_least16_t>();
test<uint_least32_t>();
test<uint_least64_t>();
test<uintmax_t>();
test<uintptr_t>();
#ifndef _LIBCPP_HAS_NO_INT128
test<__int128_t>();
test<__uint128_t>();
#endif
}
<commit_msg>Guard libc++ assumption about identity hashing in test. Patch from [email protected]<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// template <class T>
// struct hash
// : public unary_function<T, size_t>
// {
// size_t operator()(T val) const;
// };
#include <functional>
#include <cassert>
#include <type_traits>
#include <cstddef>
#include <limits>
#include "test_macros.h"
template <class T>
void
test()
{
typedef std::hash<T> H;
static_assert((std::is_same<typename H::argument_type, T>::value), "" );
static_assert((std::is_same<typename H::result_type, std::size_t>::value), "" );
H h;
for (int i = 0; i <= 5; ++i)
{
T t(i);
if (sizeof(T) <= sizeof(std::size_t))
{
const std::size_t result = h(t);
LIBCPP_ASSERT(result == t);
((void)result); // Prevent unused warning
}
}
}
int main()
{
test<bool>();
test<char>();
test<signed char>();
test<unsigned char>();
test<char16_t>();
test<char32_t>();
test<wchar_t>();
test<short>();
test<unsigned short>();
test<int>();
test<unsigned int>();
test<long>();
test<unsigned long>();
test<long long>();
test<unsigned long long>();
// LWG #2119
test<std::ptrdiff_t>();
test<size_t>();
test<int8_t>();
test<int16_t>();
test<int32_t>();
test<int64_t>();
test<int_fast8_t>();
test<int_fast16_t>();
test<int_fast32_t>();
test<int_fast64_t>();
test<int_least8_t>();
test<int_least16_t>();
test<int_least32_t>();
test<int_least64_t>();
test<intmax_t>();
test<intptr_t>();
test<uint8_t>();
test<uint16_t>();
test<uint32_t>();
test<uint64_t>();
test<uint_fast8_t>();
test<uint_fast16_t>();
test<uint_fast32_t>();
test<uint_fast64_t>();
test<uint_least8_t>();
test<uint_least16_t>();
test<uint_least32_t>();
test<uint_least64_t>();
test<uintmax_t>();
test<uintptr_t>();
#ifndef _LIBCPP_HAS_NO_INT128
test<__int128_t>();
test<__uint128_t>();
#endif
}
<|endoftext|> |
<commit_before><commit_msg>coverity#1027396 : Logically dead code<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2011 Mads R. B. Kristensen <[email protected]>
*
* This file is part of cphVB.
*
* cphVB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>
#include "cphvb_vem_node.h"
#include "ArrayManager.hpp"
//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;
//The VE components
static cphvb_component **vem_node_components;
//Our self
static cphvb_component *vem_node_myself;
//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;
#define PLAININST (1)
#define REDUCEINST (2)
ArrayManager* arrayManager;
/* Initialize the VEM
*
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
cphvb_intp children_count;
cphvb_error err;
vem_node_myself = self;
err = cphvb_component_children(self, &children_count, &vem_node_components);
if (children_count != 1)
{
std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
return CPHVB_ERROR;
}
if (err != CPHVB_SUCCESS)
return err;
ve_init = vem_node_components[0]->init;
ve_execute = vem_node_components[0]->execute;
ve_shutdown = vem_node_components[0]->shutdown;
ve_reg_func = vem_node_components[0]->reg_func;
//Let us initiate the simple VE and register what it supports.
err = ve_init(vem_node_components[0]);
if(err)
return err;
try
{
arrayManager = new ArrayManager();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return CPHVB_ERROR;
}
return CPHVB_SUCCESS;
}
/* Shutdown the VEM, which include a instruction flush
*
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_shutdown(void)
{
cphvb_error err;
err = ve_shutdown();
cphvb_component_free(vem_node_components[0]);//Only got one child.
ve_init = NULL;
ve_execute = NULL;
ve_shutdown = NULL;
ve_reg_func= NULL;
cphvb_component_free_ptr(vem_node_components);
vem_node_components = NULL;
delete arrayManager;
arrayManager = NULL;
return err;
}
/* Create an array, which are handled by the VEM.
*
* @base Pointer to the base array. If NULL this is a base array
* @type The type of data in the array
* @ndim Number of dimensions
* @start Index of the start element (always 0 for base-array)
* @shape[CPHVB_MAXDIM] Number of elements in each dimention
* @stride[CPHVB_MAXDIM] The stride for each dimention
* @new_array The handler for the newly created array
* @return Error code (CPHVB_SUCCESS, CPHVB_OUT_OF_MEMORY)
*/
cphvb_error cphvb_vem_node_create_array(cphvb_array* base,
cphvb_type type,
cphvb_intp ndim,
cphvb_index start,
cphvb_index shape[CPHVB_MAXDIM],
cphvb_index stride[CPHVB_MAXDIM],
cphvb_array** new_array)
{
try
{
*new_array = arrayManager->create(base, type, ndim, start, shape, stride);
}
catch(std::exception& e)
{
return CPHVB_OUT_OF_MEMORY;
}
#ifdef CPHVB_TRACE
cphvb_component_trace_array(vem_node_myself, *new_array);
#endif
return CPHVB_SUCCESS;
}
/* Register a new user-defined function.
*
* @lib Name of the shared library e.g. libmyfunc.so
* When NULL the default library is used.
* @fun Name of the function e.g. myfunc
* @id Identifier for the new function. The bridge should set the
* initial value to Zero. (in/out-put)
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
cphvb_error e;
cphvb_intp tmpid;
if(*id == 0)//Only if parent didn't set the ID.
tmpid = vem_userfunc_count + 1;
e = ve_reg_func(fun, &tmpid);
//If the call succeeded, register the id as taken and return it
if (e == CPHVB_SUCCESS)
{
if (tmpid > vem_userfunc_count)
vem_userfunc_count = tmpid;
*id = tmpid;
}
return e;
}
/* Execute a list of instructions (blocking, for the time being).
* It is required that the VEM supports all instructions in the list.
*
* @instruction A list of instructions to execute
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
cphvb_instruction inst_list[])
{
cphvb_intp i;
if (count <= 0)
return CPHVB_SUCCESS;
for(i=0; i<count; ++i)
{
cphvb_instruction* inst = &inst_list[i];
#ifdef CPHVB_TRACE
cphvb_component_trace_inst(vem_node_myself, inst);
#endif
switch(inst->opcode)
{
//Special handling
case CPHVB_FREE:
case CPHVB_SYNC:
case CPHVB_DISCARD:
{
switch(inst->opcode)
{
case CPHVB_FREE:
assert(inst->operand[0]->base == NULL);
arrayManager->freePending(inst);
break;
case CPHVB_DISCARD:
arrayManager->erasePending(inst);
break;
case CPHVB_SYNC:
arrayManager->changeOwnerPending(inst, cphvb_base_array(inst->operand[0]), CPHVB_SELF);
break;
default:
assert(false);
}
break;
}
case CPHVB_USERFUNC:
{
cphvb_userfunc *uf = inst->userfunc;
//The children should own the output arrays.
for(int j = 0; j < uf->nout; ++j)
{
cphvb_array* base = cphvb_base_array(uf->operand[j]);
base->owner = CPHVB_CHILD;
}
//We should own the input arrays.
for(int j = uf->nout; j < uf->nout + uf->nin; ++j)
{
cphvb_array* base = cphvb_base_array(uf->operand[j]);
if(base->owner == CPHVB_PARENT)
{
base->owner = CPHVB_SELF;
}
}
break;
}
default:
{
cphvb_array* base = cphvb_base_array(inst->operand[0]);
// "Regular" operation: set ownership and send down stream
base->owner = CPHVB_CHILD;//The child owns the output ary.
for (int j = 1; j < cphvb_operands(inst->opcode); ++j)
{
if(!cphvb_is_constant(inst->operand[j]) &&
cphvb_base_array(inst->operand[j])->owner == CPHVB_PARENT)
{
cphvb_base_array(inst->operand[j])->owner = CPHVB_SELF;
}
}
}
}
}
cphvb_error e1 = ve_execute(count, inst_list);
cphvb_error e2 = arrayManager->flush();
if (e1 != CPHVB_SUCCESS)
return e1;
else if (e2 != CPHVB_SUCCESS)
return e2;
else
return CPHVB_SUCCESS;
}
<commit_msg>Minor cleanup in the VEM-NODE<commit_after>/*
* Copyright 2011 Mads R. B. Kristensen <[email protected]>
*
* This file is part of cphVB.
*
* cphVB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>
#include "cphvb_vem_node.h"
#include "ArrayManager.hpp"
//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;
//The VE components
static cphvb_component **vem_node_components;
//Our self
static cphvb_component *vem_node_myself;
//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;
ArrayManager* arrayManager;
/* Initialize the VEM
*
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
cphvb_intp children_count;
cphvb_error err;
vem_node_myself = self;
err = cphvb_component_children(self, &children_count, &vem_node_components);
if (children_count != 1)
{
std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
return CPHVB_ERROR;
}
if (err != CPHVB_SUCCESS)
return err;
ve_init = vem_node_components[0]->init;
ve_execute = vem_node_components[0]->execute;
ve_shutdown = vem_node_components[0]->shutdown;
ve_reg_func = vem_node_components[0]->reg_func;
//Let us initiate the simple VE and register what it supports.
if((err = ve_init(vem_node_components[0])) != 0)
return err;
try
{
arrayManager = new ArrayManager();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return CPHVB_ERROR;
}
return CPHVB_SUCCESS;
}
/* Shutdown the VEM, which include a instruction flush
*
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_shutdown(void)
{
cphvb_error err;
err = ve_shutdown();
cphvb_component_free(vem_node_components[0]);//Only got one child.
ve_init = NULL;
ve_execute = NULL;
ve_shutdown = NULL;
ve_reg_func = NULL;
cphvb_component_free_ptr(vem_node_components);
vem_node_components = NULL;
delete arrayManager;
arrayManager = NULL;
return err;
}
/* Create an array, which are handled by the VEM.
*
* @base Pointer to the base array. If NULL this is a base array
* @type The type of data in the array
* @ndim Number of dimensions
* @start Index of the start element (always 0 for base-array)
* @shape[CPHVB_MAXDIM] Number of elements in each dimention
* @stride[CPHVB_MAXDIM] The stride for each dimention
* @new_array The handler for the newly created array
* @return Error code (CPHVB_SUCCESS, CPHVB_OUT_OF_MEMORY)
*/
cphvb_error cphvb_vem_node_create_array(cphvb_array* base,
cphvb_type type,
cphvb_intp ndim,
cphvb_index start,
cphvb_index shape[CPHVB_MAXDIM],
cphvb_index stride[CPHVB_MAXDIM],
cphvb_array** new_array)
{
try
{
*new_array = arrayManager->create(base, type, ndim, start, shape, stride);
}
catch(std::exception& e)
{
return CPHVB_OUT_OF_MEMORY;
}
#ifdef CPHVB_TRACE
cphvb_component_trace_array(vem_node_myself, *new_array);
#endif
return CPHVB_SUCCESS;
}
/* Register a new user-defined function.
*
* @lib Name of the shared library e.g. libmyfunc.so
* When NULL the default library is used.
* @fun Name of the function e.g. myfunc
* @id Identifier for the new function. The bridge should set the
* initial value to Zero. (in/out-put)
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
cphvb_error e;
cphvb_intp tmpid;
if(*id == 0)//Only if parent didn't set the ID.
tmpid = vem_userfunc_count + 1;
e = ve_reg_func(fun, &tmpid);
//If the call succeeded, register the id as taken and return it
if (e == CPHVB_SUCCESS)
{
if (tmpid > vem_userfunc_count)
vem_userfunc_count = tmpid;
*id = tmpid;
}
return e;
}
/* Execute a list of instructions (blocking, for the time being).
* It is required that the VEM supports all instructions in the list.
*
* @instruction A list of instructions to execute
* @return Error codes (CPHVB_SUCCESS)
*/
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
cphvb_instruction inst_list[])
{
cphvb_intp i;
if (count <= 0)
return CPHVB_SUCCESS;
for(i=0; i<count; ++i)
{
cphvb_instruction* inst = &inst_list[i];
#ifdef CPHVB_TRACE
cphvb_component_trace_inst(vem_node_myself, inst);
#endif
switch(inst->opcode)
{
//Special handling
case CPHVB_FREE:
case CPHVB_SYNC:
case CPHVB_DISCARD:
{
switch(inst->opcode)
{
case CPHVB_FREE:
assert(inst->operand[0]->base == NULL);
arrayManager->freePending(inst);
break;
case CPHVB_DISCARD:
arrayManager->erasePending(inst);
break;
case CPHVB_SYNC:
arrayManager->changeOwnerPending(inst, cphvb_base_array(inst->operand[0]), CPHVB_SELF);
break;
default:
assert(false);
}
break;
}
case CPHVB_USERFUNC:
{
cphvb_userfunc *uf = inst->userfunc;
//The children should own the output arrays.
for(int j = 0; j < uf->nout; ++j)
{
cphvb_array* base = cphvb_base_array(uf->operand[j]);
base->owner = CPHVB_CHILD;
}
//We should own the input arrays.
for(int j = uf->nout; j < uf->nout + uf->nin; ++j)
{
cphvb_array* base = cphvb_base_array(uf->operand[j]);
if(base->owner == CPHVB_PARENT)
{
base->owner = CPHVB_SELF;
}
}
break;
}
default:
{
cphvb_array* base = cphvb_base_array(inst->operand[0]);
// "Regular" operation: set ownership and send down stream
base->owner = CPHVB_CHILD;//The child owns the output ary.
for (int j = 1; j < cphvb_operands(inst->opcode); ++j)
{
if(!cphvb_is_constant(inst->operand[j]) &&
cphvb_base_array(inst->operand[j])->owner == CPHVB_PARENT)
{
cphvb_base_array(inst->operand[j])->owner = CPHVB_SELF;
}
}
}
}
}
cphvb_error e1 = ve_execute(count, inst_list);
cphvb_error e2 = arrayManager->flush();
if (e1 != CPHVB_SUCCESS)
return e1;
else if (e2 != CPHVB_SUCCESS)
return e2;
else
return CPHVB_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <catch2/catch.hpp>
#include "pressed_keys_manager.hpp"
TEST_CASE("pressed_keys_manager") {
// empty
{
krbn::pressed_keys_manager manager;
REQUIRE(manager.empty());
}
// key_code
{
krbn::pressed_keys_manager manager;
REQUIRE(!manager.exists(krbn::key_code::a));
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
REQUIRE(manager.exists(krbn::key_code::a));
manager.erase(krbn::key_code::a);
REQUIRE(manager.empty());
REQUIRE(!manager.exists(krbn::key_code::a));
}
// Duplicated key_code
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::key_code::a);
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.erase(krbn::key_code::a);
REQUIRE(manager.empty());
}
// consumer_key_code
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.erase(krbn::consumer_key_code::mute);
REQUIRE(manager.empty());
}
// pointing_button
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::pointing_button::button1);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button1);
REQUIRE(manager.empty());
}
// combination
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.insert(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.insert(krbn::pointing_button::button1);
REQUIRE(!manager.empty());
manager.erase(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.erase(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button10);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button1);
REQUIRE(manager.empty());
}
}
<commit_msg>fix tests<commit_after>#include <catch2/catch.hpp>
#include "pressed_keys_manager.hpp"
TEST_CASE("pressed_keys_manager") {
// empty
{
krbn::pressed_keys_manager manager;
REQUIRE(manager.empty());
}
// key_code
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.erase(krbn::key_code::a);
REQUIRE(manager.empty());
}
// Duplicated key_code
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::key_code::a);
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.erase(krbn::key_code::a);
REQUIRE(manager.empty());
}
// consumer_key_code
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.erase(krbn::consumer_key_code::mute);
REQUIRE(manager.empty());
}
// pointing_button
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::pointing_button::button1);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button1);
REQUIRE(manager.empty());
}
// combination
{
krbn::pressed_keys_manager manager;
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.insert(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.insert(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.insert(krbn::pointing_button::button1);
REQUIRE(!manager.empty());
manager.erase(krbn::key_code::a);
REQUIRE(!manager.empty());
manager.erase(krbn::consumer_key_code::mute);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button10);
REQUIRE(!manager.empty());
manager.erase(krbn::pointing_button::button1);
REQUIRE(manager.empty());
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: colorlistener.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-03-25 18:21:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#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 _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.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();
}
//__________________________________________
/** 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 for color changes.
@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();
}
void ColorListener::impl_applyColor()
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
if (m_pConfig)
{
css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue( ::svtools::APPBACKGROUND );
if (xPeer.is())
{
xPeer->setBackground(aBackgroundColor.nColor);
xPeer->invalidate(
css::awt::InvalidateStyle::UPDATE | css::awt::InvalidateStyle::CHILDREN | css::awt::InvalidateStyle::NOTRANSPARENT );
}
}
aReadLock.unlock();
/* } SAFE */
}
//__________________________________________
/** 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)
{
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)
{
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 mav4 (1.2.10); FILE MERGED 2003/04/23 13:17:52 as 1.2.10.1: #109052# HACK: refresh background color if it was changed by 3rdparty!<commit_after>/*************************************************************************
*
* $RCSfile: colorlistener.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-04-24 13:33:02 $
*
* 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 for color changes.
@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);
}
void ColorListener::impl_applyColor( sal_Bool bInvalidate )
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
if (m_pConfig)
{
css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue( ::svtools::APPBACKGROUND );
if (xPeer.is())
{
m_nColor = aBackgroundColor.nColor;
xPeer->setBackground(m_nColor);
if (bInvalidate)
{
xPeer->invalidate(
css::awt::InvalidateStyle::UPDATE | css::awt::InvalidateStyle::CHILDREN | css::awt::InvalidateStyle::NOTRANSPARENT );
}
}
}
aWriteLock.unlock();
/* } SAFE */
}
//__________________________________________
/** 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 */
}
IMPL_LINK( ColorListener, impl_SettingsChanged, void*, pVoid )
{
VclWindowEvent* pEvent = (VclWindowEvent*)pVoid;
if (pEvent->GetId() != VCLEVENT_APPLICATION_DATACHANGED)
return 0L;
/* SAFE { */
ReadGuard aReadLock(m_aLock);
Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
if (!pWindow)
return 0L;
OutputDevice* pDevice = (OutputDevice*)pWindow;
long nNewColor = (long)(pDevice->GetBackground().GetColor().GetColor());
if (m_nColor != nNewColor)
impl_applyColor(sal_False);
aReadLock.unlock();
/* } SAFE */
return 0L;
}
//__________________________________________
/** 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)
{
Application::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)
{
Application::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>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: registertemp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:07:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// 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_MEDIATYPEDETECTIONHELPER_HXX_
#include <services/mediatypedetectionhelper.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_SUBSTPATHVARS_HXX_
#include <services/substitutepathvars.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_PATHSETTINGS_HXX_
#include <services/pathsettings.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::MediaTypeDetectionHelper )
COMPONENTINFO( ::framework::SubstitutePathVariables )
COMPONENTINFO( ::framework::PathSettings )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::MediaTypeDetectionHelper ) else
IFFACTORY( ::framework::SubstitutePathVariables ) else
IFFACTORY( ::framework::PathSettings )
)
<commit_msg>INTEGRATION: CWS changefileheader (1.11.262); FILE MERGED 2008/04/01 10:58:11 thb 1.11.262.2: #i85898# Stripping all external header guards 2008/03/28 15:35:25 rt 1.11.262.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: registertemp.cxx,v $
* $Revision: 1.12 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#include <macros/registration.hxx>
/*=================================================================================================================
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 )
)
=================================================================================================================*/
#include <services/mediatypedetectionhelper.hxx>
#include <services/substitutepathvars.hxx>
#include <services/pathsettings.hxx>
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::MediaTypeDetectionHelper )
COMPONENTINFO( ::framework::SubstitutePathVariables )
COMPONENTINFO( ::framework::PathSettings )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::MediaTypeDetectionHelper ) else
IFFACTORY( ::framework::SubstitutePathVariables ) else
IFFACTORY( ::framework::PathSettings )
)
<|endoftext|> |
<commit_before>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>
#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"
#define RJ_WATCHDOG_TIMER_VALUE 2 // seconds
using namespace std;
// USBHID interface. The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
RJ_BASE2015_RELEASE);
bool initRadio() {
// setup SPI bus
shared_ptr<SharedSPI> sharedSPI =
make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
sharedSPI->format(8, 0); // 8 bits per transfer
// RX/TX leds
auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);
// Startup the CommModule interface
CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
shared_ptr<CommModule> commModule = CommModule::Instance;
// Create a new physical hardware communication link
global_radio =
new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
sizeof(preferredSettings) / sizeof(registerSetting_t));
return global_radio->isConnected();
}
void radioRxHandler(rtp::packet* pkt) {
// write packet content out to endpoint 1
vector<uint8_t> buffer;
pkt->pack(&buffer);
bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
MAX_PACKET_SIZE_EPBULK);
if (!success) {
LOG(WARN, "Failed to transfer received packet over usb");
}
}
int main() {
// set baud rate to higher value than the default for faster terminal
Serial s(RJ_SERIAL_RXTX);
s.baud(57600);
// Set the default logging configurations
isLogging = RJ_LOGGING_EN;
rjLogLevel = INIT;
LOG(INIT, "Base station starting...");
if (initRadio()) {
LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());
// register handlers for any ports we might use
for (rtp::port port :
{rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
CommModule::Instance->setRxHandler(&radioRxHandler, port);
CommModule::Instance->setTxHandler((CommLink*)global_radio,
&CommLink::sendPacket, port);
}
} else {
LOG(FATAL, "No radio interface found!");
}
DigitalOut radioStatusLed(LED4, global_radio->isConnected());
// set callbacks for usb control transfers
usbLink.writeRegisterCallback = [](uint8_t reg, uint8_t val) {
global_radio->writeReg(reg, val);
};
usbLink.readRegisterCallback = [](uint8_t reg) {
return global_radio->readReg(reg);
};
usbLink.strobeCallback = [](uint8_t strobe) {
global_radio->strobe(strobe);
};
LOG(INIT, "Initializing USB interface...");
usbLink.connect(); // note: this blocks until the link is connected
LOG(INIT, "Initialized USB interface!");
// Set the watdog timer's initial config
Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);
LOG(INIT, "Listening for commands over USB");
uint8_t buf[MAX_PACKET_SIZE_EPBULK];
uint32_t bufSize;
while (true) {
// make sure we can always reach back to main by renewing the watchdog
// timer periodically
Watchdog::Renew();
// attempt to read data from endpoint 2
// if data is available, write it into @pkt and send it
if (usbLink.readEP_NB(2, buf, &bufSize, sizeof(buf))) {
// construct packet from buffer received over USB
rtp::packet pkt;
pkt.recv(buf, bufSize);
// transmit!
CommModule::Instance->send(pkt);
}
}
}
<commit_msg>checkstyle patch<commit_after>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>
#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"
#define RJ_WATCHDOG_TIMER_VALUE 2 // seconds
using namespace std;
// USBHID interface. The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
RJ_BASE2015_RELEASE);
bool initRadio() {
// setup SPI bus
shared_ptr<SharedSPI> sharedSPI =
make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
sharedSPI->format(8, 0); // 8 bits per transfer
// RX/TX leds
auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);
// Startup the CommModule interface
CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
shared_ptr<CommModule> commModule = CommModule::Instance;
// Create a new physical hardware communication link
global_radio =
new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
sizeof(preferredSettings) / sizeof(registerSetting_t));
return global_radio->isConnected();
}
void radioRxHandler(rtp::packet* pkt) {
// write packet content out to endpoint 1
vector<uint8_t> buffer;
pkt->pack(&buffer);
bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
MAX_PACKET_SIZE_EPBULK);
if (!success) {
LOG(WARN, "Failed to transfer received packet over usb");
}
}
int main() {
// set baud rate to higher value than the default for faster terminal
Serial s(RJ_SERIAL_RXTX);
s.baud(57600);
// Set the default logging configurations
isLogging = RJ_LOGGING_EN;
rjLogLevel = INIT;
LOG(INIT, "Base station starting...");
if (initRadio()) {
LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());
// register handlers for any ports we might use
for (rtp::port port :
{rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
CommModule::Instance->setRxHandler(&radioRxHandler, port);
CommModule::Instance->setTxHandler((CommLink*)global_radio,
&CommLink::sendPacket, port);
}
} else {
LOG(FATAL, "No radio interface found!");
}
DigitalOut radioStatusLed(LED4, global_radio->isConnected());
// set callbacks for usb control transfers
usbLink.writeRegisterCallback =
[](uint8_t reg, uint8_t val) { global_radio->writeReg(reg, val); };
usbLink.readRegisterCallback =
[](uint8_t reg) { return global_radio->readReg(reg); };
usbLink.strobeCallback =
[](uint8_t strobe) { global_radio->strobe(strobe); };
LOG(INIT, "Initializing USB interface...");
usbLink.connect(); // note: this blocks until the link is connected
LOG(INIT, "Initialized USB interface!");
// Set the watdog timer's initial config
Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);
LOG(INIT, "Listening for commands over USB");
uint8_t buf[MAX_PACKET_SIZE_EPBULK];
uint32_t bufSize;
while (true) {
// make sure we can always reach back to main by renewing the watchdog
// timer periodically
Watchdog::Renew();
// attempt to read data from endpoint 2
// if data is available, write it into @pkt and send it
if (usbLink.readEP_NB(2, buf, &bufSize, sizeof(buf))) {
// construct packet from buffer received over USB
rtp::packet pkt;
pkt.recv(buf, bufSize);
// transmit!
CommModule::Instance->send(pkt);
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#include "filterexpression.h"
#include "parser.h"
#include "grantlee.h"
#include "filter.h"
#include "util_p.h"
using namespace Grantlee;
namespace Grantlee
{
class FilterExpressionPrivate
{
FilterExpressionPrivate(FilterExpression *fe, int error)
: q_ptr(fe), m_error(error)
{
}
Variable m_variable;
QList<ArgFilter> m_filters;
int m_error;
Q_DECLARE_PUBLIC(FilterExpression)
FilterExpression *q_ptr;
};
}
static const char * FILTER_SEPARATOR = "|";
static const char * FILTER_ARGUMENT_SEPARATOR = ":";
static const char * VARIABLE_ATTRIBUTE_SEPARATOR = ".";
static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\.";
static const char * varChars = "\\w\\." ;
static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*";
static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) );
static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) );
static const QString i18nOpen( QRegExp::escape( "_(" ) );
static const QString i18nClose( QRegExp::escape( ")" ) );
static const QString constantString = QString(
"(?:%3%1%4|"
"%3%2%4|"
"%1|"
"%2)"
)
.arg("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"")
.arg("\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'")
.arg(i18nOpen)
.arg(i18nClose)
;
static const QString filterRawString = QString(
"^%1|" /* Match "strings" and 'strings' incl i18n */
"^[%2]+|" /* Match variables */
"%3|" /* Match numbers */
"%4\\w+|" /* Match filters */
"%5(?:%1|[%2]+|%3|%4\\w+)" /* Match arguments to filters, which may be strings, */
) /* variables, numbers or another filter in the chain */
/* 1 */ .arg(constantString)
/* 2 */ .arg(varChars)
/* 3 */ .arg(numChars)
/* 4 */ .arg(filterSep)
/* 5 */ .arg(argSep);
static const QRegExp sFilterRe(filterRawString);
FilterExpression::FilterExpression(const QString &varString, Parser *parser)
: d_ptr(new FilterExpressionPrivate(this, NoError))
{
Q_D(FilterExpression);
int pos = 0;
int lastPos = 0;
int len;
QString subString;
if (varString.contains("\n"))
{
// error.
}
QString vs = varString.trimmed();
while ((pos = sFilterRe.indexIn(vs, pos)) != -1) {
len = sFilterRe.matchedLength();
subString = vs.mid(pos, len);
int ssSize = subString.size();
if (subString.startsWith(FILTER_SEPARATOR))
{
subString = subString.right(ssSize - 1);
Filter *f = parser->getFilter(subString);
if (f)
d->m_filters << qMakePair<Filter*, Variable>(f, Variable());
else
{
d->m_error = TagSyntaxError;
return;
}
}
else if (subString.startsWith(FILTER_ARGUMENT_SEPARATOR))
{
subString = subString.right(ssSize - 1);
int lastFilter = d->m_filters.size();
d->m_filters[lastFilter -1].second = Variable(subString);
} else
{
// Token is _("translated"), or "constant", or a variable;
d->m_variable = Variable(subString);
}
pos += len;
lastPos = pos;
}
QString remainder = vs.right( vs.size() - lastPos);
if (remainder.size() > 0)
{
d->m_error = TagSyntaxError;
}
}
int FilterExpression::error() const
{
Q_D(const FilterExpression);
return d->m_error;
}
FilterExpression::FilterExpression(const FilterExpression &other)
: d_ptr(new FilterExpressionPrivate(this, other.d_ptr->m_error))
{
d_ptr->m_variable = other.d_ptr->m_variable;
d_ptr->m_filters = other.d_ptr->m_filters;
}
FilterExpression::FilterExpression()
: d_ptr(new FilterExpressionPrivate(this, NoError))
{
Q_D(FilterExpression);
}
FilterExpression::~FilterExpression()
{
delete d_ptr;
}
Variable FilterExpression::variable() const
{
Q_D(const FilterExpression);
return d->m_variable;
}
FilterExpression &FilterExpression::operator=(const FilterExpression &other)
{
d_ptr->m_variable = other.d_ptr->m_variable;
d_ptr->m_filters = other.d_ptr->m_filters;
d_ptr->m_error = other.d_ptr->m_error;
return *this;
}
QVariant FilterExpression::resolve(Context *c) const
{
Q_D(const FilterExpression);
QVariant var = d->m_variable.resolve(c);
foreach(ArgFilter argfilter, d->m_filters)
{
var = argfilter.first->doFilter(var, argfilter.second.resolve(c).toString());
}
return var;
}
// void FilterExpression::begin(Context *c, int reversed)
// {
// m_position = 0;
// QVariant var = resolve(c);
// if (!var.isValid())
// return;
//
// if (var.type() == QVariant::String)
// {
//
// } else if (var.userType() > 0)
// {
// // A registered user type. Signal error.
// // void *obj = QMetaType::construct(var.userType(), (void *)var );
//
// // Instead of all this messing, I can simply require that an object can't be iterated over.
// // Iterate over a property instead.
// // Or I can allow iterating over an objects children(), which is a QList<QObject>
//
// // QMetaType::destroy(var.userType(), obj);
// // TODO: see if I can use QMetaType::construct for user defined types.
// }
// else
// {
// m_variantList.append(var);
// }
// }
QVariantList FilterExpression::toList(Context *c) const
{
QVariant var = resolve(c);
if (!var.isValid())
return QVariantList();
if (var.type() == QVariant::List)
{
return var.toList();
}
if (var.type() == QVariant::String)
{
QString s = var.toString();
QString::iterator i;
QVariantList list;
for (i = s.begin(); i != s.end(); ++i)
{
list << *i;
}
return list;
} else if (var.userType() == QMetaType::QObjectStar)
{
// A registered user type. Signal error.
// void *obj = QMetaType::construct(var.userType(), (void *)var );
// Instead of all this messing, I can simply require that an object can't be iterated over.
// Iterate over a property instead.
// Or I can allow iterating over an objects children(), which is a QList<QObject *>
// QMetaType::destroy(var.userType(), obj);
// TODO: see if I can use QMetaType::construct for user defined types.
}
else
{
// QVariantList list;
// list << var;
// return list;
return QVariantList() << var;
// m_variantList.append(var);
}
}
bool FilterExpression::isTrue(Context *c) const
{
return Util::variantIsTrue(resolve(c));
}
// QVariant FilterExpression::next()
// {
// return m_variantList[m_position++];
//
// // if (!var.isValid())
// // return QVariant();
// //
// // m_iterVariant = var;
// }
<commit_msg>No need to trim this.<commit_after>/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#include "filterexpression.h"
#include "parser.h"
#include "grantlee.h"
#include "filter.h"
#include "util_p.h"
using namespace Grantlee;
namespace Grantlee
{
class FilterExpressionPrivate
{
FilterExpressionPrivate(FilterExpression *fe, int error)
: q_ptr(fe), m_error(error)
{
}
Variable m_variable;
QList<ArgFilter> m_filters;
int m_error;
Q_DECLARE_PUBLIC(FilterExpression)
FilterExpression *q_ptr;
};
}
static const char * FILTER_SEPARATOR = "|";
static const char * FILTER_ARGUMENT_SEPARATOR = ":";
static const char * VARIABLE_ATTRIBUTE_SEPARATOR = ".";
static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\.";
static const char * varChars = "\\w\\." ;
static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*";
static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) );
static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) );
static const QString i18nOpen( QRegExp::escape( "_(" ) );
static const QString i18nClose( QRegExp::escape( ")" ) );
static const QString constantString = QString(
"(?:%3%1%4|"
"%3%2%4|"
"%1|"
"%2)"
)
.arg("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"")
.arg("\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'")
.arg(i18nOpen)
.arg(i18nClose)
;
static const QString filterRawString = QString(
"^%1|" /* Match "strings" and 'strings' incl i18n */
"^[%2]+|" /* Match variables */
"%3|" /* Match numbers */
"%4\\w+|" /* Match filters */
"%5(?:%1|[%2]+|%3|%4\\w+)" /* Match arguments to filters, which may be strings, */
) /* variables, numbers or another filter in the chain */
/* 1 */ .arg(constantString)
/* 2 */ .arg(varChars)
/* 3 */ .arg(numChars)
/* 4 */ .arg(filterSep)
/* 5 */ .arg(argSep);
static const QRegExp sFilterRe(filterRawString);
FilterExpression::FilterExpression(const QString &varString, Parser *parser)
: d_ptr(new FilterExpressionPrivate(this, NoError))
{
Q_D(FilterExpression);
int pos = 0;
int lastPos = 0;
int len;
QString subString;
if (varString.contains("\n"))
{
// error.
}
QString vs = varString; //.trimmed();
while ((pos = sFilterRe.indexIn(vs, pos)) != -1) {
len = sFilterRe.matchedLength();
subString = vs.mid(pos, len);
int ssSize = subString.size();
if (subString.startsWith(FILTER_SEPARATOR))
{
subString = subString.right(ssSize - 1);
Filter *f = parser->getFilter(subString);
if (f)
d->m_filters << qMakePair<Filter*, Variable>(f, Variable());
else
{
d->m_error = TagSyntaxError;
return;
}
}
else if (subString.startsWith(FILTER_ARGUMENT_SEPARATOR))
{
subString = subString.right(ssSize - 1);
int lastFilter = d->m_filters.size();
d->m_filters[lastFilter -1].second = Variable(subString);
} else
{
// Token is _("translated"), or "constant", or a variable;
d->m_variable = Variable(subString);
}
pos += len;
lastPos = pos;
}
QString remainder = vs.right( vs.size() - lastPos);
if (remainder.size() > 0)
{
d->m_error = TagSyntaxError;
}
}
int FilterExpression::error() const
{
Q_D(const FilterExpression);
return d->m_error;
}
FilterExpression::FilterExpression(const FilterExpression &other)
: d_ptr(new FilterExpressionPrivate(this, other.d_ptr->m_error))
{
d_ptr->m_variable = other.d_ptr->m_variable;
d_ptr->m_filters = other.d_ptr->m_filters;
}
FilterExpression::FilterExpression()
: d_ptr(new FilterExpressionPrivate(this, NoError))
{
Q_D(FilterExpression);
}
FilterExpression::~FilterExpression()
{
delete d_ptr;
}
Variable FilterExpression::variable() const
{
Q_D(const FilterExpression);
return d->m_variable;
}
FilterExpression &FilterExpression::operator=(const FilterExpression &other)
{
d_ptr->m_variable = other.d_ptr->m_variable;
d_ptr->m_filters = other.d_ptr->m_filters;
d_ptr->m_error = other.d_ptr->m_error;
return *this;
}
QVariant FilterExpression::resolve(Context *c) const
{
Q_D(const FilterExpression);
QVariant var = d->m_variable.resolve(c);
foreach(ArgFilter argfilter, d->m_filters)
{
var = argfilter.first->doFilter(var, argfilter.second.resolve(c).toString());
}
return var;
}
// void FilterExpression::begin(Context *c, int reversed)
// {
// m_position = 0;
// QVariant var = resolve(c);
// if (!var.isValid())
// return;
//
// if (var.type() == QVariant::String)
// {
//
// } else if (var.userType() > 0)
// {
// // A registered user type. Signal error.
// // void *obj = QMetaType::construct(var.userType(), (void *)var );
//
// // Instead of all this messing, I can simply require that an object can't be iterated over.
// // Iterate over a property instead.
// // Or I can allow iterating over an objects children(), which is a QList<QObject>
//
// // QMetaType::destroy(var.userType(), obj);
// // TODO: see if I can use QMetaType::construct for user defined types.
// }
// else
// {
// m_variantList.append(var);
// }
// }
QVariantList FilterExpression::toList(Context *c) const
{
QVariant var = resolve(c);
if (!var.isValid())
return QVariantList();
if (var.type() == QVariant::List)
{
return var.toList();
}
if (var.type() == QVariant::String)
{
QString s = var.toString();
QString::iterator i;
QVariantList list;
for (i = s.begin(); i != s.end(); ++i)
{
list << *i;
}
return list;
} else if (var.userType() == QMetaType::QObjectStar)
{
// A registered user type. Signal error.
// void *obj = QMetaType::construct(var.userType(), (void *)var );
// Instead of all this messing, I can simply require that an object can't be iterated over.
// Iterate over a property instead.
// Or I can allow iterating over an objects children(), which is a QList<QObject *>
// QMetaType::destroy(var.userType(), obj);
// TODO: see if I can use QMetaType::construct for user defined types.
}
else
{
// QVariantList list;
// list << var;
// return list;
return QVariantList() << var;
// m_variantList.append(var);
}
}
bool FilterExpression::isTrue(Context *c) const
{
return Util::variantIsTrue(resolve(c));
}
// QVariant FilterExpression::next()
// {
// return m_variantList[m_position++];
//
// // if (!var.isValid())
// // return QVariant();
// //
// // m_iterVariant = var;
// }
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"
enum P9_MEM_STARTCLOCKS_Private_Constants
{
CLOCK_CMD = 0x1,
STARTSLAVE = 0x1,
STARTMASTER = 0x1,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
CLOCK_TYPES = 0x7,
DONT_STARTMASTER = 0x0,
DONT_STARTSLAVE = 0x0
};
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector);
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg);
fapi2::ReturnCode p9_mem_startclocks(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
uint8_t l_sync_mode = 0;
fapi2::buffer<uint64_t> l_pg_vector;
fapi2::buffer<uint64_t> l_clock_regions;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
"Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");
FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);
if (!l_sync_mode)
{
for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));
FAPI_INF("Call module align chiplets for Mc chiplets");
FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));
FAPI_TRY(p9_mem_startclocks_regions_setup(l_trgt_chplt,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL, l_clock_regions));
FAPI_INF("Call module clock start stop for MC01, MC23.");
FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
DONT_STARTSLAVE, DONT_STARTMASTER, l_clock_regions,
CLOCK_TYPES));
FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));
FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));
FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop chiplet fence
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector)
{
uint8_t l_read_attrunitpos = 0;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
l_read_attrunitpos));
if ( l_read_attrunitpos == 0x07 )
{
if ( i_pg_vector.getBit<5>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
if ( l_read_attrunitpos == 0x08 )
{
if ( i_pg_vector.getBit<3>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
// Local variable and constant definition
fapi2::buffer <uint16_t> l_attr_pg;
fapi2::buffer <uint16_t> l_cplt_ctrl_init;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));
l_attr_pg.invert();
l_attr_pg.extractToRight<4, 11>(l_cplt_ctrl_init);
FAPI_DBG("Drop partial good fences");
//Setting CPLT_CTRL1 register value
l_data64.flush<0>();
l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
//CPLT_CTRL1.TC_ALL_REGIONS_FENCE = l_cplt_ctrl_init
l_data64.insertFromRight<4, 11>(l_cplt_ctrl_init);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));
FAPI_DBG("reset abistclk_muxsel and syncclk_muxsel");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
//CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief will force all chiplets out of flush
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_DBG("Clear flush_inhibit to go in to flush mode");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Region value settings : The anding of REGIONS_ALL_EXCEPT_VITAL_NESTPLL, ATTR_PG
// disables PLL region and retains enabled regions info from chiplet pg attribute.
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @param[in] i_regions_except_vital_pll regions except vital and pll
/// @param[out] o_regions_enabled_after_pg enabled regions value after anding with ATTR_PG
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(const
fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg)
{
fapi2::buffer<uint16_t> l_read_attr = 0;
fapi2::buffer<uint16_t> l_read_attr_invert = 0;
fapi2::buffer<uint16_t> l_read_attr_shift1_right = 0;
FAPI_DBG("p9_mem_startclocks_regions_setup: Entering ...");
FAPI_DBG("Reading ATTR_PG");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_read_attr));
if ( l_read_attr == 0x0 )
{
o_regions_enabled_after_pg = static_cast<uint64_t>(i_regions_except_vital_pll) ;
}
else
{
l_read_attr_invert = l_read_attr.invert();
l_read_attr_shift1_right = (l_read_attr_invert >> 1);
o_regions_enabled_after_pg = (i_regions_except_vital_pll & l_read_attr_shift1_right);
}
FAPI_DBG("p9_mem_startclocks_regions_setup : Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>p9_mem_startclocks -- restore fabric group/node ID in async mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"
enum P9_MEM_STARTCLOCKS_Private_Constants
{
CLOCK_CMD = 0x1,
STARTSLAVE = 0x1,
STARTMASTER = 0x1,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
CLOCK_TYPES = 0x7,
DONT_STARTMASTER = 0x0,
DONT_STARTSLAVE = 0x0
};
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector);
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg);
fapi2::ReturnCode p9_mem_startclocks(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
uint8_t l_sync_mode = 0;
fapi2::buffer<uint64_t> l_pg_vector;
fapi2::buffer<uint64_t> l_clock_regions;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
"Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");
FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);
if (!l_sync_mode)
{
uint32_t l_fbc_system_id;
uint8_t l_fbc_group_id;
uint8_t l_fbc_chip_id;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_SYSTEM_ID, i_target_chip, l_fbc_system_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_SYSTEM_ID)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_GROUP_ID, i_target_chip, l_fbc_group_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_GROUP_ID)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_CHIP_ID, i_target_chip, l_fbc_chip_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_CHIP_ID)");
for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));
FAPI_INF("Call module align chiplets for Mc chiplets");
FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));
FAPI_TRY(p9_mem_startclocks_regions_setup(l_trgt_chplt,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL, l_clock_regions));
FAPI_INF("Call module clock start stop for MC01, MC23.");
FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
DONT_STARTSLAVE, DONT_STARTMASTER, l_clock_regions,
CLOCK_TYPES));
FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));
FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));
FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));
FAPI_INF("Reset FBC chiplet configuration");
fapi2::buffer<uint64_t> l_cplt_conf0;
FAPI_TRY(fapi2::getScom(l_trgt_chplt, PERV_CPLT_CONF0, l_cplt_conf0),
"Error from getScom (PERV_CPLT_CONF0)");
l_cplt_conf0.insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_SYS_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_SYS_ID_DC_LEN>
(l_fbc_system_id)
.insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_GROUP_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_GROUP_ID_DC_LEN>(l_fbc_group_id)
.insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_CHIP_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_CHIP_ID_DC_LEN>(l_fbc_chip_id);
FAPI_TRY(fapi2::putScom(l_trgt_chplt, PERV_CPLT_CONF0, l_cplt_conf0),
"Error from putScom (PERV_CPLT_CONF0)");
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop chiplet fence
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector)
{
uint8_t l_read_attrunitpos = 0;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
l_read_attrunitpos));
if ( l_read_attrunitpos == 0x07 )
{
if ( i_pg_vector.getBit<5>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
if ( l_read_attrunitpos == 0x08 )
{
if ( i_pg_vector.getBit<3>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
// Local variable and constant definition
fapi2::buffer <uint16_t> l_attr_pg;
fapi2::buffer <uint16_t> l_cplt_ctrl_init;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));
l_attr_pg.invert();
l_attr_pg.extractToRight<4, 11>(l_cplt_ctrl_init);
FAPI_DBG("Drop partial good fences");
//Setting CPLT_CTRL1 register value
l_data64.flush<0>();
l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
//CPLT_CTRL1.TC_ALL_REGIONS_FENCE = l_cplt_ctrl_init
l_data64.insertFromRight<4, 11>(l_cplt_ctrl_init);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));
FAPI_DBG("reset abistclk_muxsel and syncclk_muxsel");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
//CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief will force all chiplets out of flush
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_DBG("Clear flush_inhibit to go in to flush mode");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Region value settings : The anding of REGIONS_ALL_EXCEPT_VITAL_NESTPLL, ATTR_PG
// disables PLL region and retains enabled regions info from chiplet pg attribute.
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @param[in] i_regions_except_vital_pll regions except vital and pll
/// @param[out] o_regions_enabled_after_pg enabled regions value after anding with ATTR_PG
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(const
fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg)
{
fapi2::buffer<uint16_t> l_read_attr = 0;
fapi2::buffer<uint16_t> l_read_attr_invert = 0;
fapi2::buffer<uint16_t> l_read_attr_shift1_right = 0;
FAPI_DBG("p9_mem_startclocks_regions_setup: Entering ...");
FAPI_DBG("Reading ATTR_PG");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_read_attr));
if ( l_read_attr == 0x0 )
{
o_regions_enabled_after_pg = static_cast<uint64_t>(i_regions_except_vital_pll) ;
}
else
{
l_read_attr_invert = l_read_attr.invert();
l_read_attr_shift1_right = (l_read_attr_invert >> 1);
o_regions_enabled_after_pg = (i_regions_except_vital_pll & l_read_attr_shift1_right);
}
FAPI_DBG("p9_mem_startclocks_regions_setup : Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#pragma once
#include "atlas/mesh.h"
#include <cassert>
namespace utility {
namespace impl_ {
template <typename Integer>
class irange_ {
public:
class iterator {
public:
Integer operator*() const { return i_; }
const iterator& operator++() {
++i_;
return *this;
}
iterator operator++(int) {
iterator copy(*this);
++i_;
return copy;
}
bool operator==(const iterator& other) const { return i_ == other.i_; }
bool operator!=(const iterator& other) const { return i_ != other.i_; }
iterator(Integer start) : i_(start) {}
private:
Integer i_;
};
iterator begin() const { return begin_; }
iterator end() const { return end_; }
irange_(Integer begin, Integer end) : begin_(begin), end_(end) {}
private:
iterator begin_;
iterator end_;
};
} // namespace impl_
template <typename Integer>
impl_::irange_<Integer> irange(Integer from, Integer to) {
return {from, to};
}
} // namespace utility
namespace atlasInterface {
struct atlasTag {};
template <typename T>
class Field {
public:
T const& operator()(int f) const { return atlas_field_(f, 0); }
T& operator()(int f) { return atlas_field_(f, 0); }
Field(atlas::array::ArrayView<T, 2> const& atlas_field) : atlas_field_(atlas_field) {}
private:
atlas::array::ArrayView<T, 2> atlas_field_;
};
template <typename T>
Field<T> cellFieldType(atlasTag);
template <typename T>
Field<T> edgeFieldType(atlasTag);
template <typename T>
Field<T> vertexFieldType(atlasTag);
atlas::Mesh meshType(atlasTag);
auto getCells(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.cells().size()); }
auto getEdges(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.edges().size()); }
auto getVertices(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.nodes().size()); }
std::vector<int> const& cellNeighboursOfCell(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
const auto& conn = m.cells().edge_connectivity();
neighs[idx] = std::vector<int>{};
for(int n = 0; n < conn.cols(idx); ++n) {
int initialEdge = conn(idx, n);
for(int c1 = 0; c1 < m.cells().size(); ++c1) {
for(int n1 = 0; n1 < conn.cols(c1); ++n1) {
int compareEdge = conn(c1, n1);
if(initialEdge == compareEdge && c1 != idx) {
neighs[idx].emplace_back(c1);
}
}
}
}
}
return neighs[idx];
}
std::vector<int> const& edgeNeighboursOfCell(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
const auto& conn = m.cells().edge_connectivity();
neighs[idx] = std::vector<int>{};
for(int n = 0; n < conn.cols(idx); ++n) {
neighs[idx].emplace_back(conn(idx, n));
}
}
return neighs[idx];
}
template <typename Init, typename Op>
auto reduceCellToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : cellNeighboursOfCell(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceEdgeToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : edgeNeighboursOfCell(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceVertexToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
template <typename Init, typename Op>
auto reduceCellToEdge(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
template <typename Init, typename Op>
auto reduceVertexToEdge(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
template <typename Init, typename Op>
auto reduceCellToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
template <typename Init, typename Op>
auto reduceEdgeToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
template <typename Init, typename Op>
auto reduceVertexToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
assert(false && "function not implemented in the atlas back end");
return 1;
}
} // namespace atlasInterface
<commit_msg>extended atlas interface to include all possible reductions (#440)<commit_after>#pragma once
#include "atlas/mesh.h"
#include <cassert>
namespace utility {
namespace impl_ {
template <typename Integer>
class irange_ {
public:
class iterator {
public:
Integer operator*() const { return i_; }
const iterator& operator++() {
++i_;
return *this;
}
iterator operator++(int) {
iterator copy(*this);
++i_;
return copy;
}
bool operator==(const iterator& other) const { return i_ == other.i_; }
bool operator!=(const iterator& other) const { return i_ != other.i_; }
iterator(Integer start) : i_(start) {}
private:
Integer i_;
};
iterator begin() const { return begin_; }
iterator end() const { return end_; }
irange_(Integer begin, Integer end) : begin_(begin), end_(end) {}
private:
iterator begin_;
iterator end_;
};
} // namespace impl_
template <typename Integer>
impl_::irange_<Integer> irange(Integer from, Integer to) {
return {from, to};
}
} // namespace utility
namespace atlasInterface {
struct atlasTag {};
template <typename T>
class Field {
public:
T const& operator()(int f) const { return atlas_field_(f, 0); }
T& operator()(int f) { return atlas_field_(f, 0); }
Field(atlas::array::ArrayView<T, 2> const& atlas_field) : atlas_field_(atlas_field) {}
private:
atlas::array::ArrayView<T, 2> atlas_field_;
};
template <typename T>
Field<T> cellFieldType(atlasTag);
template <typename T>
Field<T> edgeFieldType(atlasTag);
template <typename T>
Field<T> vertexFieldType(atlasTag);
atlas::Mesh meshType(atlasTag);
auto getCells(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.cells().size()); }
auto getEdges(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.edges().size()); }
auto getVertices(atlasTag, atlas::Mesh const& m) { return utility::irange(0, m.nodes().size()); }
std::vector<int> getNeighs(const atlas::Mesh::HybridElements::Connectivity& conn, int idx) {
std::vector<int> neighs;
for(int n = 0; n < conn.cols(idx); ++n) {
neighs.emplace_back(conn(idx, n));
}
return neighs;
}
std::vector<int> const& cellNeighboursOfCell(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
const auto& conn = m.cells().edge_connectivity();
neighs[idx] = std::vector<int>{};
for(int n = 0; n < conn.cols(idx); ++n) {
int initialEdge = conn(idx, n);
for(int c1 = 0; c1 < m.cells().size(); ++c1) {
for(int n1 = 0; n1 < conn.cols(c1); ++n1) {
int compareEdge = conn(c1, n1);
if(initialEdge == compareEdge && c1 != idx) {
neighs[idx].emplace_back(c1);
}
}
}
}
}
return neighs[idx];
}
std::vector<int> const& edgeNeighboursOfCell(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().edge_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> const& nodeNeighboursOfCell(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().node_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> cellNeighboursOfEdge(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().cell_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> nodeNeighboursOfEdge(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().node_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> cellNeighboursOfNode(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().cell_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> edgeNeighboursOfNode(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
neighs[idx] = getNeighs(m.cells().edge_connectivity(), idx);
}
return neighs[idx];
}
std::vector<int> nodeNeighboursOfNode(atlas::Mesh const& m, int const& idx) {
// note this is only a workaround and does only work as long as we have only one mesh
static std::map<int, std::vector<int>> neighs;
if(neighs.count(idx) == 0) {
const auto& conn_nodes_to_edge = m.nodes().edge_connectivity();
neighs[idx] = std::vector<int>{};
for(int ne = 0; ne < conn_nodes_to_edge.cols(idx); ++ne) {
int nbh_edge_idx = conn_nodes_to_edge(idx, ne);
const auto& conn_edge_to_nodes = m.edges().node_connectivity();
for(int nn = 0; nn < conn_edge_to_nodes.cols(nbh_edge_idx); ++nn) {
int nbhNode = conn_edge_to_nodes(idx, nn);
if(nbhNode != idx) {
neighs[idx].emplace_back();
}
}
}
}
return neighs[idx];
}
template <typename Init, typename Op>
auto reduceCellToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : cellNeighboursOfCell(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceEdgeToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : edgeNeighboursOfCell(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceVertexToCell(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : nodeNeighboursOfCell(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceCellToEdge(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : cellNeighboursOfEdge(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceVertexToEdge(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : nodeNeighboursOfEdge(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceCellToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : cellNeighboursOfNode(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceEdgeToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : edgeNeighboursOfNode(m, idx))
op(init, obj);
return init;
}
template <typename Init, typename Op>
auto reduceVertexToVertex(atlasTag, atlas::Mesh const& m, int idx, Init init, Op&& op) {
for(auto&& obj : nodeNeighboursOfNode(m, idx))
op(init, obj);
return init;
}
} // namespace atlasInterface
<|endoftext|> |
<commit_before>#include <iostream>
#include "headers/uhdm.h"
#include "headers/vpi_visitor.h"
using namespace UHDM;
#include "vpi_visitor.h"
std::vector<vpiHandle> build_designs (Serializer& s) {
std::vector<vpiHandle> designs;
// Design building
design* d = s.MakeDesign();
d->VpiName("designTF");
module* m1 = s.MakeModule();
m1->VpiTopModule(true);
m1->VpiDefName("M1");
m1->VpiParent(d);
m1->VpiFile("fake1.sv");
m1->VpiLineNo(10);
initial* init = s.MakeInitial();
VectorOfprocess* processes = s.MakeProcessVec();
processes->push_back(init);
begin* begin_block = s.MakeBegin();
init->Stmt(begin_block);
VectorOfany* statements = s.MakeAnyVec();
sys_func_call* display = s.MakeSys_func_call();
display->VpiName("display");
VectorOfany *arguments = s.MakeAnyVec();
constant* cA = s.MakeConstant();
cA->VpiValue("INT:0");
arguments->push_back(cA);
constant* cA1 = s.MakeConstant();
cA1->VpiValue("INT:8");
arguments->push_back(cA1);
display->Tf_call_args(arguments);
statements->push_back(display);
func_call* my_func_call = s.MakeFunc_call();
function* my_func = s.MakeFunction();
my_func->VpiName("a_func");
my_func_call->Function(my_func);
VectorOfany *arguments2 = s.MakeAnyVec();
constant* cA2 = s.MakeConstant();
cA2->VpiValue("INT:1");
arguments2->push_back(cA2);
constant* cA3 = s.MakeConstant();
cA3->VpiValue("INT:2");
arguments2->push_back(cA3);
my_func_call->Tf_call_args(arguments2);
statements->push_back(my_func_call);
begin_block->Stmts(statements);
m1->Process(processes);
VectorOfmodule* v1 = s.MakeModuleVec();
v1->push_back(m1);
d->AllModules(v1);
package* p1 = s.MakePackage();
p1->VpiDefName("P0");
VectorOfpackage* v3 = s.MakePackageVec();
v3->push_back(p1);
d->AllPackages(v3);
designs.push_back(s.MakeUhdmHandle(uhdmdesign, d));
return designs;
}
int main (int argc, char** argv) {
std::cout << "Make design" << std::endl;
Serializer serializer;
std::string orig = visit_designs(build_designs(serializer));
std::cout << orig;
std::cout << "\nSave design" << std::endl;
serializer.Save("surelog3.uhdm");
std::cout << "Restore design" << std::endl;
std::vector<vpiHandle> restoredDesigns = serializer.Restore("surelog3.uhdm");
std::string restored = visit_designs(restoredDesigns);
std::cout << restored;
return (orig != restored);
}
<commit_msg>Change file name in test_tf_call<commit_after>#include <iostream>
#include "headers/uhdm.h"
#include "headers/vpi_visitor.h"
using namespace UHDM;
#include "vpi_visitor.h"
std::vector<vpiHandle> build_designs (Serializer& s) {
std::vector<vpiHandle> designs;
// Design building
design* d = s.MakeDesign();
d->VpiName("designTF");
module* m1 = s.MakeModule();
m1->VpiTopModule(true);
m1->VpiDefName("M1");
m1->VpiParent(d);
m1->VpiFile("fake1.sv");
m1->VpiLineNo(10);
initial* init = s.MakeInitial();
VectorOfprocess* processes = s.MakeProcessVec();
processes->push_back(init);
begin* begin_block = s.MakeBegin();
init->Stmt(begin_block);
VectorOfany* statements = s.MakeAnyVec();
sys_func_call* display = s.MakeSys_func_call();
display->VpiName("display");
VectorOfany *arguments = s.MakeAnyVec();
constant* cA = s.MakeConstant();
cA->VpiValue("INT:0");
arguments->push_back(cA);
constant* cA1 = s.MakeConstant();
cA1->VpiValue("INT:8");
arguments->push_back(cA1);
display->Tf_call_args(arguments);
statements->push_back(display);
func_call* my_func_call = s.MakeFunc_call();
function* my_func = s.MakeFunction();
my_func->VpiName("a_func");
my_func_call->Function(my_func);
VectorOfany *arguments2 = s.MakeAnyVec();
constant* cA2 = s.MakeConstant();
cA2->VpiValue("INT:1");
arguments2->push_back(cA2);
constant* cA3 = s.MakeConstant();
cA3->VpiValue("INT:2");
arguments2->push_back(cA3);
my_func_call->Tf_call_args(arguments2);
statements->push_back(my_func_call);
begin_block->Stmts(statements);
m1->Process(processes);
VectorOfmodule* v1 = s.MakeModuleVec();
v1->push_back(m1);
d->AllModules(v1);
package* p1 = s.MakePackage();
p1->VpiDefName("P0");
VectorOfpackage* v3 = s.MakePackageVec();
v3->push_back(p1);
d->AllPackages(v3);
designs.push_back(s.MakeUhdmHandle(uhdmdesign, d));
return designs;
}
int main (int argc, char** argv) {
std::cout << "Make design" << std::endl;
Serializer serializer;
std::string orig = visit_designs(build_designs(serializer));
std::cout << orig;
std::cout << "\nSave design" << std::endl;
serializer.Save("surelog_tf_call.uhdm");
std::cout << "Restore design" << std::endl;
std::vector<vpiHandle> restoredDesigns = serializer.Restore("surelog_tf_call.uhdm");
std::string restored = visit_designs(restoredDesigns);
std::cout << restored;
return (orig != restored);
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "Message.h"
#include "FakeMessenger.h"
#include "mds/MDS.h"
#include "common/Timer.h"
#include "common/LogType.h"
#include "common/Logger.h"
#include "config.h"
#undef dout
#define dout(x) if ((x) <= g_conf.debug_ms) cout << g_clock.now() << " "
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <cassert>
#include <iostream>
using namespace std;
#include <ext/hash_map>
using namespace __gnu_cxx;
#include "common/Cond.h"
#include "common/Mutex.h"
#include <pthread.h>
// global queue.
int nranks = 0; // this identify each entity_inst_t
map<entity_addr_t, FakeMessenger*> directory;
hash_map<int, Logger*> loggers;
LogType fakemsg_logtype;
set<entity_addr_t> shutdown_set;
Mutex lock;
Cond cond;
bool awake = false;
bool fm_shutdown = false;
pthread_t thread_id;
extern std::map<entity_name_t,float> g_fake_kill_after; // in config.cc
utime_t start_time;
map<utime_t,entity_name_t> fail_queue;
list<Message*> sent_to_failed_queue;
void *fakemessenger_thread(void *ptr)
{
start_time = g_clock.now();
lock.Lock();
while (1) {
if (fm_shutdown) break;
fakemessenger_do_loop_2();
if (directory.empty() && nranks > 0) break;
dout(20) << "thread waiting" << endl;
if (fm_shutdown) break;
awake = false;
cond.Wait(lock);
awake = true;
dout(20) << "thread woke up" << endl;
}
lock.Unlock();
dout(1) << "thread finish (i woke up but no messages, bye)" << endl;
return 0;
}
void fakemessenger_startthread() {
pthread_create(&thread_id, NULL, fakemessenger_thread, 0);
}
void fakemessenger_stopthread() {
cout << "fakemessenger_stopthread setting stop flag" << endl;
lock.Lock();
fm_shutdown = true;
lock.Unlock();
cond.Signal();
fakemessenger_wait();
}
void fakemessenger_wait()
{
cout << "fakemessenger_wait waiting" << endl;
void *ptr;
pthread_join(thread_id, &ptr);
}
// fake failure
// lame main looper
int fakemessenger_do_loop()
{
lock.Lock();
fakemessenger_do_loop_2();
lock.Unlock();
g_timer.shutdown();
return 0;
}
int fakemessenger_do_loop_2()
{
//lock.Lock();
dout(18) << "do_loop begin." << endl;
while (1) {
bool didone = false;
dout(18) << "do_loop top" << endl;
// fail_queue
while (!fail_queue.empty() &&
fail_queue.begin()->first < g_clock.now()) {
entity_name_t nm = fail_queue.begin()->second;
fail_queue.erase(fail_queue.begin());
dout(0) << "MUST FAKE KILL " << nm << endl;
for (map<entity_addr_t, FakeMessenger*>::iterator p = directory.begin();
p != directory.end();
++p) {
if (p->second->get_myname() == nm) {
dout(0) << "FAKING FAILURE of " << nm << " at " << p->first << endl;
directory.erase(p);
p->second->failed = true;
break;
}
}
}
list<Message*> ls;
ls.swap(sent_to_failed_queue);
for (list<Message*>::iterator p = ls.begin();
p != ls.end();
++p) {
Message *m = *p;
FakeMessenger *mgr = directory[m->get_source_addr()];
Dispatcher *dis = 0;
if (mgr) dis = mgr->get_dispatcher();
if (dis) {
dout(1) << "fail on " << *m
<< " to " << m->get_dest() << " from " << m->get_source()
<< ", passing back to sender." << endl;
dis->ms_handle_failure(m, m->get_dest_inst());
} else {
dout(1) << "fail on " << *m
<< " to " << m->get_dest() << " from " << m->get_source()
<< ", sender gone, dropping." << endl;
delete m;
}
}
// messages
map<entity_addr_t, FakeMessenger*>::iterator it = directory.begin();
while (it != directory.end()) {
FakeMessenger *mgr = it->second;
dout(18) << "messenger " << mgr << " at " << mgr->get_myname() << " has " << mgr->num_incoming() << " queued" << endl;
if (!mgr->is_ready()) {
dout(18) << "messenger " << mgr << " at " << mgr->get_myname() << " has no dispatcher, skipping" << endl;
it++;
continue;
}
Message *m = mgr->get_message();
it++;
if (m) {
//dout(18) << "got " << m << endl;
dout(1) << "==== " << m->get_dest()
<< " <- " << m->get_source()
<< " ==== " << *m
<< " ---- " << m
<< endl;
if (g_conf.fakemessenger_serialize) {
// encode
if (m->empty_payload())
m->encode_payload();
msg_envelope_t env = m->get_envelope();
bufferlist bl;
bl.claim( m->get_payload() );
//bl.c_str(); // condense into 1 buffer
delete m;
// decode
m = decode_message(env, bl);
assert(m);
}
didone = true;
lock.Unlock();
mgr->dispatch(m);
lock.Lock();
}
}
// deal with shutdowns.. delayed to avoid concurrent directory modification
if (!shutdown_set.empty()) {
for (set<entity_addr_t>::iterator it = shutdown_set.begin();
it != shutdown_set.end();
it++) {
dout(7) << "fakemessenger: removing " << *it << " from directory" << endl;
assert(directory.count(*it));
directory.erase(*it);
if (directory.empty()) {
dout(1) << "fakemessenger: last shutdown" << endl;
::fm_shutdown = true;
}
}
shutdown_set.clear();
}
if (!didone)
break;
}
dout(18) << "do_loop end (no more messages)." << endl;
//lock.Unlock();
return 0;
}
FakeMessenger::FakeMessenger(entity_name_t me) : Messenger(me)
{
failed = false;
lock.Lock();
{
// assign rank
_myinst.name = me;
_myinst.addr.port = nranks++;
//if (!me.is_mon())
_myinst.addr.nonce = getpid();
// add to directory
directory[ _myinst.addr ] = this;
// put myself in the fail queue?
if (g_fake_kill_after.count(me)) {
utime_t w = start_time;
w += g_fake_kill_after[me];
dout(0) << "will fake failure of " << me << " at " << w << endl;
fail_queue[w] = me;
}
}
lock.Unlock();
cout << "fakemessenger " << get_myname() << " messenger is " << this << " at " << _myinst << endl;
qlen = 0;
/*
string name;
name = "m.";
name += MSG_ADDR_TYPE(myaddr);
int w = MSG_ADDR_NUM(myaddr);
if (w >= 1000) name += ('0' + ((w/1000)%10));
if (w >= 100) name += ('0' + ((w/100)%10));
if (w >= 10) name += ('0' + ((w/10)%10));
name += ('0' + ((w/1)%10));
loggers[ myaddr ] = new Logger(name, (LogType*)&fakemsg_logtype);
*/
}
FakeMessenger::~FakeMessenger()
{
// hose any undelivered messages
for (list<Message*>::iterator p = incoming.begin();
p != incoming.end();
++p)
delete *p;
}
int FakeMessenger::shutdown()
{
//cout << "shutdown on messenger " << this << " has " << num_incoming() << " queued" << endl;
lock.Lock();
assert(directory.count(_myinst.addr) == 1);
shutdown_set.insert(_myinst.addr);
/*
if (loggers[myaddr]) {
delete loggers[myaddr];
loggers.erase(myaddr);
}
*/
lock.Unlock();
return 0;
}
void FakeMessenger::reset_myname(entity_name_t m)
{
dout(1) << "reset_myname from " << get_myname() << " to " << m << endl;
_set_myname(m);
directory.erase(_myinst.addr);
_myinst.name = m;
directory[_myinst.addr] = this;
// put myself in the fail queue?
if (g_fake_kill_after.count(m)) {
utime_t w = start_time;
w += g_fake_kill_after[m];
dout(0) << "will fake failure of " << m << " at " << w << endl;
fail_queue[w] = m;
}
}
int FakeMessenger::send_message(Message *m, entity_inst_t inst, int port, int fromport)
{
entity_name_t dest = inst.name;
m->set_source(get_myname(), fromport);
m->set_source_addr(get_myaddr());
m->set_dest_inst(inst);
m->set_dest_port(port);
lock.Lock();
#ifdef LOG_MESSAGES
// stats
loggers[get_myaddr()]->inc("+send",1);
loggers[dest]->inc("-recv",1);
char s[20];
sprintf(s,"+%s", m->get_type_name());
loggers[get_myaddr()]->inc(s);
sprintf(s,"-%s", m->get_type_name());
loggers[dest]->inc(s);
#endif
// queue
if (directory.count(inst.addr) &&
shutdown_set.count(inst.addr) == 0) {
dout(1) << "--> " << get_myname() << " -> " << inst.name << " --- " << *m << " -- " << m
<< endl;
directory[inst.addr]->queue_incoming(m);
} else {
dout(0) << "--> " << get_myname() << " -> " << inst.name << " " << *m << " -- " << m
<< " *** destination " << inst.addr << " DNE ***"
<< endl;
for (map<entity_addr_t, FakeMessenger*>::iterator p = directory.begin();
p != directory.end();
++p) {
dout(20) << "** have " << p->first << " to " << p->second << endl;
}
// do the failure callback
sent_to_failed_queue.push_back(m);
}
// wake up loop?
if (!awake) {
dout(10) << "waking up fakemessenger thread" << endl;
cond.Signal();
lock.Unlock();
} else
lock.Unlock();
return 0;
}
<commit_msg>locked debug output<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "Message.h"
#include "FakeMessenger.h"
#include "mds/MDS.h"
#include "common/Timer.h"
#include "common/LogType.h"
#include "common/Logger.h"
#include "config.h"
#include "debug.h"
#undef dout
#define dout(x) if ((x) <= g_conf.debug_ms) cout << dbeginl << g_clock.now() << " "
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <cassert>
#include <iostream>
using namespace std;
#include <ext/hash_map>
using namespace __gnu_cxx;
#include "common/Cond.h"
#include "common/Mutex.h"
#include <pthread.h>
// global queue.
int nranks = 0; // this identify each entity_inst_t
map<entity_addr_t, FakeMessenger*> directory;
hash_map<int, Logger*> loggers;
LogType fakemsg_logtype;
set<entity_addr_t> shutdown_set;
Mutex lock;
Cond cond;
bool awake = false;
bool fm_shutdown = false;
pthread_t thread_id;
extern std::map<entity_name_t,float> g_fake_kill_after; // in config.cc
utime_t start_time;
map<utime_t,entity_name_t> fail_queue;
list<Message*> sent_to_failed_queue;
void *fakemessenger_thread(void *ptr)
{
start_time = g_clock.now();
lock.Lock();
while (1) {
if (fm_shutdown) break;
fakemessenger_do_loop_2();
if (directory.empty() && nranks > 0) break;
dout(20) << "thread waiting" << dendl;
if (fm_shutdown) break;
awake = false;
cond.Wait(lock);
awake = true;
dout(20) << "thread woke up" << dendl;
}
lock.Unlock();
dout(1) << "thread finish (i woke up but no messages, bye)" << dendl;
return 0;
}
void fakemessenger_startthread() {
pthread_create(&thread_id, NULL, fakemessenger_thread, 0);
}
void fakemessenger_stopthread() {
dout(0) << "fakemessenger_stopthread setting stop flag" << dendl;
lock.Lock();
fm_shutdown = true;
lock.Unlock();
cond.Signal();
fakemessenger_wait();
}
void fakemessenger_wait()
{
dout(0) << "fakemessenger_wait waiting" << dendl;
void *ptr;
pthread_join(thread_id, &ptr);
}
// fake failure
// lame main looper
int fakemessenger_do_loop()
{
lock.Lock();
fakemessenger_do_loop_2();
lock.Unlock();
g_timer.shutdown();
return 0;
}
int fakemessenger_do_loop_2()
{
//lock.Lock();
dout(18) << "do_loop begin." << dendl;
while (1) {
bool didone = false;
dout(18) << "do_loop top" << dendl;
// fail_queue
while (!fail_queue.empty() &&
fail_queue.begin()->first < g_clock.now()) {
entity_name_t nm = fail_queue.begin()->second;
fail_queue.erase(fail_queue.begin());
dout(0) << "MUST FAKE KILL " << nm << dendl;
for (map<entity_addr_t, FakeMessenger*>::iterator p = directory.begin();
p != directory.end();
++p) {
if (p->second->get_myname() == nm) {
dout(0) << "FAKING FAILURE of " << nm << " at " << p->first << dendl;
directory.erase(p);
p->second->failed = true;
break;
}
}
}
list<Message*> ls;
ls.swap(sent_to_failed_queue);
for (list<Message*>::iterator p = ls.begin();
p != ls.end();
++p) {
Message *m = *p;
FakeMessenger *mgr = directory[m->get_source_addr()];
Dispatcher *dis = 0;
if (mgr) dis = mgr->get_dispatcher();
if (dis) {
dout(1) << "fail on " << *m
<< " to " << m->get_dest() << " from " << m->get_source()
<< ", passing back to sender." << dendl;
dis->ms_handle_failure(m, m->get_dest_inst());
} else {
dout(1) << "fail on " << *m
<< " to " << m->get_dest() << " from " << m->get_source()
<< ", sender gone, dropping." << dendl;
delete m;
}
}
// messages
map<entity_addr_t, FakeMessenger*>::iterator it = directory.begin();
while (it != directory.end()) {
FakeMessenger *mgr = it->second;
dout(18) << "messenger " << mgr << " at " << mgr->get_myname() << " has " << mgr->num_incoming() << " queued" << dendl;
if (!mgr->is_ready()) {
dout(18) << "messenger " << mgr << " at " << mgr->get_myname() << " has no dispatcher, skipping" << dendl;
it++;
continue;
}
Message *m = mgr->get_message();
it++;
if (m) {
//dout(18) << "got " << m << dendl;
dout(1) << "==== " << m->get_dest()
<< " <- " << m->get_source()
<< " ==== " << *m
<< " ---- " << m
<< dendl;
if (g_conf.fakemessenger_serialize) {
// encode
if (m->empty_payload())
m->encode_payload();
msg_envelope_t env = m->get_envelope();
bufferlist bl;
bl.claim( m->get_payload() );
//bl.c_str(); // condense into 1 buffer
delete m;
// decode
m = decode_message(env, bl);
assert(m);
}
didone = true;
lock.Unlock();
mgr->dispatch(m);
lock.Lock();
}
}
// deal with shutdowns.. delayed to avoid concurrent directory modification
if (!shutdown_set.empty()) {
for (set<entity_addr_t>::iterator it = shutdown_set.begin();
it != shutdown_set.end();
it++) {
dout(7) << "fakemessenger: removing " << *it << " from directory" << dendl;
assert(directory.count(*it));
directory.erase(*it);
if (directory.empty()) {
dout(1) << "fakemessenger: last shutdown" << dendl;
::fm_shutdown = true;
}
}
shutdown_set.clear();
}
if (!didone)
break;
}
dout(18) << "do_loop end (no more messages)." << dendl;
//lock.Unlock();
return 0;
}
FakeMessenger::FakeMessenger(entity_name_t me) : Messenger(me)
{
failed = false;
lock.Lock();
{
// assign rank
_myinst.name = me;
_myinst.addr.port = nranks++;
//if (!me.is_mon())
_myinst.addr.nonce = getpid();
// add to directory
directory[ _myinst.addr ] = this;
// put myself in the fail queue?
if (g_fake_kill_after.count(me)) {
utime_t w = start_time;
w += g_fake_kill_after[me];
dout(0) << "will fake failure of " << me << " at " << w << dendl;
fail_queue[w] = me;
}
}
lock.Unlock();
dout(0) << "fakemessenger " << get_myname() << " messenger is " << this << " at " << _myinst << dendl;
qlen = 0;
/*
string name;
name = "m.";
name += MSG_ADDR_TYPE(myaddr);
int w = MSG_ADDR_NUM(myaddr);
if (w >= 1000) name += ('0' + ((w/1000)%10));
if (w >= 100) name += ('0' + ((w/100)%10));
if (w >= 10) name += ('0' + ((w/10)%10));
name += ('0' + ((w/1)%10));
loggers[ myaddr ] = new Logger(name, (LogType*)&fakemsg_logtype);
*/
}
FakeMessenger::~FakeMessenger()
{
// hose any undelivered messages
for (list<Message*>::iterator p = incoming.begin();
p != incoming.end();
++p)
delete *p;
}
int FakeMessenger::shutdown()
{
//dout(0) << "shutdown on messenger " << this << " has " << num_incoming() << " queued" << dendl;
lock.Lock();
assert(directory.count(_myinst.addr) == 1);
shutdown_set.insert(_myinst.addr);
/*
if (loggers[myaddr]) {
delete loggers[myaddr];
loggers.erase(myaddr);
}
*/
lock.Unlock();
return 0;
}
void FakeMessenger::reset_myname(entity_name_t m)
{
dout(1) << "reset_myname from " << get_myname() << " to " << m << dendl;
_set_myname(m);
directory.erase(_myinst.addr);
_myinst.name = m;
directory[_myinst.addr] = this;
// put myself in the fail queue?
if (g_fake_kill_after.count(m)) {
utime_t w = start_time;
w += g_fake_kill_after[m];
dout(0) << "will fake failure of " << m << " at " << w << dendl;
fail_queue[w] = m;
}
}
int FakeMessenger::send_message(Message *m, entity_inst_t inst, int port, int fromport)
{
entity_name_t dest = inst.name;
m->set_source(get_myname(), fromport);
m->set_source_addr(get_myaddr());
m->set_dest_inst(inst);
m->set_dest_port(port);
lock.Lock();
#ifdef LOG_MESSAGES
// stats
loggers[get_myaddr()]->inc("+send",1);
loggers[dest]->inc("-recv",1);
char s[20];
sprintf(s,"+%s", m->get_type_name());
loggers[get_myaddr()]->inc(s);
sprintf(s,"-%s", m->get_type_name());
loggers[dest]->inc(s);
#endif
// queue
if (directory.count(inst.addr) &&
shutdown_set.count(inst.addr) == 0) {
dout(1) << "--> " << get_myname() << " -> " << inst.name << " --- " << *m << " -- " << m
<< dendl;
directory[inst.addr]->queue_incoming(m);
} else {
dout(0) << "--> " << get_myname() << " -> " << inst.name << " " << *m << " -- " << m
<< " *** destination " << inst.addr << " DNE ***"
<< dendl;
for (map<entity_addr_t, FakeMessenger*>::iterator p = directory.begin();
p != directory.end();
++p) {
dout(20) << "** have " << p->first << " to " << p->second << dendl;
}
// do the failure callback
sent_to_failed_queue.push_back(m);
}
// wake up loop?
if (!awake) {
dout(10) << "waking up fakemessenger thread" << dendl;
cond.Signal();
lock.Unlock();
} else
lock.Unlock();
return 0;
}
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <event/timeout.h>
#include <network/network_interface.h>
static void usage(void);
int
main(int argc, char *argv[])
{
const char *ifname;
int ch;
ifname = NULL;
while ((ch = getopt(argc, argv, "i:")) != -1) {
switch (ch) {
case 'i':
if (ifname != NULL)
usage();
ifname = optarg;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (ifname == NULL)
usage();
if (argc != 0)
usage();
NetworkInterface *interface = NetworkInterface::open(ifname);
if (interface == NULL) {
ERROR("/main") << "Unable to open interface.";
return (1);
}
EventSystem::instance()->start();
delete interface;
}
static void
usage(void)
{
ERROR("/main") << "usage: network-packet-receive-hexdump1 -i ifname";
exit(1);
}
<commit_msg>Trivial dump implementation.<commit_after>#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <event/timeout.h>
#include <network/network_interface.h>
class PacketDumper {
NetworkInterface *interface_;
Action *receive_action_;
public:
PacketDumper(NetworkInterface *interface)
: interface_(interface),
receive_action_(NULL)
{
EventCallback *cb = callback(this, &PacketDumper::receive_complete);
receive_action_ = interface_->receive(cb);
}
~PacketDumper()
{
if (receive_action_ != NULL) {
receive_action_->cancel();
receive_action_ = NULL;
}
}
private:
void receive_complete(Event e)
{
receive_action_->cancel();
receive_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
HALT("/packet/dumper") << "Unexpected event: " << e;
return;
}
INFO("/packet/dumper") << e.buffer_.length() << " byte packet: " << std::endl << e.buffer_.hexdump();
EventCallback *cb = callback(this, &PacketDumper::receive_complete);
receive_action_ = interface_->receive(cb);
}
};
static void usage(void);
int
main(int argc, char *argv[])
{
const char *ifname;
int ch;
ifname = NULL;
while ((ch = getopt(argc, argv, "i:")) != -1) {
switch (ch) {
case 'i':
if (ifname != NULL)
usage();
ifname = optarg;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (ifname == NULL)
usage();
if (argc != 0)
usage();
NetworkInterface *interface = NetworkInterface::open(ifname);
if (interface == NULL) {
ERROR("/main") << "Unable to open interface.";
return (1);
}
PacketDumper dumper(interface);
EventSystem::instance()->start();
delete interface;
}
static void
usage(void)
{
ERROR("/main") << "usage: network-packet-receive-hexdump1 -i ifname";
exit(1);
}
<|endoftext|> |
<commit_before>#include "import-stdcore.h"
#include "details/intrinsic/intrinsic-table.h"
#include <yuni/yuni.h>
#include <yuni/core/string.h>
using namespace Yuni;
namespace Nany
{
namespace Builtin
{
static void* yn_string_new(nytctx_t* tctx)
{
void* p = tctx->context->memory.allocate(tctx->context, sizeof(String));
return new (p) String{};
}
static void yn_string_delete(nytctx_t* tctx, void* string)
{
(reinterpret_cast<String*>(string))->~String();
tctx->context->memory.release(tctx->context, string, sizeof(String));
}
static uint64_t yn_string_size(nytctx_t*, void* string)
{
return (reinterpret_cast<String*>(string))->size();
}
static void yn_string_append_str(nytctx_t*, void* string, void* rhs)
{
auto& other = *(reinterpret_cast<String*>(rhs));
reinterpret_cast<String*>(string)->append(other);
}
static void yn_string_append_cstring(nytctx_t*, void* string, void* ptr, uint64_t size)
{
const char* const text = reinterpret_cast<const char* const>(ptr);
reinterpret_cast<String*>(string)->append(text, static_cast<uint32_t>(size));
}
static void yn_string_clear(nytctx_t*, void* string)
{
reinterpret_cast<String*>(string)->clear();
}
static void yn_string_cout(nytctx_t* tctx, void* string)
{
auto& str = *(reinterpret_cast<String*>(string));
tctx->context->console.write_stdout(tctx->context, str.c_str(), str.size());
}
template<class T> struct IntCast { typedef T value; };
template<> struct IntCast<int8_t> { typedef int32_t value; };
template<> struct IntCast<uint8_t> { typedef uint32_t value; };
template<> struct IntCast<int16_t> { typedef int32_t value; };
template<> struct IntCast<uint16_t> { typedef uint32_t value; };
template<class T> static void yn_string_append(nytctx_t*, void* string, T value)
{
reinterpret_cast<String*>(string)->append(static_cast<typename IntCast<T>::value>(value));
}
} // namespace Builtin
} // namespace Nany
namespace Nany
{
void importNSLCoreString(IntrinsicTable& intrinsics)
{
intrinsics.add("yuni.string.new", Builtin::yn_string_new);
intrinsics.add("yuni.string.delete", Builtin::yn_string_delete);
intrinsics.add("yuni.string.clear", Builtin::yn_string_clear);
intrinsics.add("yuni.string.size", Builtin::yn_string_size);
intrinsics.add("yuni.string.append", Builtin::yn_string_append_str);
intrinsics.add("yuni.string.append.cstring", Builtin::yn_string_append_cstring);
intrinsics.add("yuni.string.append.u8", Builtin::yn_string_append<uint8_t>);
intrinsics.add("yuni.string.append.u16", Builtin::yn_string_append<uint16_t>);
intrinsics.add("yuni.string.append.u32", Builtin::yn_string_append<uint32_t>);
intrinsics.add("yuni.string.append.u64", Builtin::yn_string_append<uint64_t>);
intrinsics.add("yuni.string.append.i8", Builtin::yn_string_append<int8_t>);
intrinsics.add("yuni.string.append.i16", Builtin::yn_string_append<int16_t>);
intrinsics.add("yuni.string.append.i32", Builtin::yn_string_append<int32_t>);
intrinsics.add("yuni.string.append.i64", Builtin::yn_string_append<int64_t>);
intrinsics.add("yuni.string.cout", Builtin::yn_string_cout);
}
} // namespace Nany
<commit_msg>fixed intrinsic name for appending a string to another string<commit_after>#include "import-stdcore.h"
#include "details/intrinsic/intrinsic-table.h"
#include <yuni/yuni.h>
#include <yuni/core/string.h>
using namespace Yuni;
namespace Nany
{
namespace Builtin
{
static void* yn_string_new(nytctx_t* tctx)
{
void* p = tctx->context->memory.allocate(tctx->context, sizeof(String));
return new (p) String{};
}
static void yn_string_delete(nytctx_t* tctx, void* string)
{
(reinterpret_cast<String*>(string))->~String();
tctx->context->memory.release(tctx->context, string, sizeof(String));
}
static uint64_t yn_string_size(nytctx_t*, void* string)
{
return (reinterpret_cast<String*>(string))->size();
}
static void yn_string_append_str(nytctx_t*, void* string, void* rhs)
{
auto& other = *(reinterpret_cast<String*>(rhs));
reinterpret_cast<String*>(string)->append(other);
}
static void yn_string_append_cstring(nytctx_t*, void* string, void* ptr, uint64_t size)
{
const char* const text = reinterpret_cast<const char* const>(ptr);
reinterpret_cast<String*>(string)->append(text, static_cast<uint32_t>(size));
}
static void yn_string_clear(nytctx_t*, void* string)
{
reinterpret_cast<String*>(string)->clear();
}
static void yn_string_cout(nytctx_t* tctx, void* string)
{
auto& str = *(reinterpret_cast<String*>(string));
tctx->context->console.write_stdout(tctx->context, str.c_str(), str.size());
}
template<class T> struct IntCast { typedef T value; };
template<> struct IntCast<int8_t> { typedef int32_t value; };
template<> struct IntCast<uint8_t> { typedef uint32_t value; };
template<> struct IntCast<int16_t> { typedef int32_t value; };
template<> struct IntCast<uint16_t> { typedef uint32_t value; };
template<class T> static void yn_string_append(nytctx_t*, void* string, T value)
{
reinterpret_cast<String*>(string)->append(static_cast<typename IntCast<T>::value>(value));
}
} // namespace Builtin
} // namespace Nany
namespace Nany
{
void importNSLCoreString(IntrinsicTable& intrinsics)
{
intrinsics.add("yuni.string.new", Builtin::yn_string_new);
intrinsics.add("yuni.string.delete", Builtin::yn_string_delete);
intrinsics.add("yuni.string.clear", Builtin::yn_string_clear);
intrinsics.add("yuni.string.size", Builtin::yn_string_size);
intrinsics.add("yuni.string.append.string", Builtin::yn_string_append_str);
intrinsics.add("yuni.string.append.cstring", Builtin::yn_string_append_cstring);
intrinsics.add("yuni.string.append.u8", Builtin::yn_string_append<uint8_t>);
intrinsics.add("yuni.string.append.u16", Builtin::yn_string_append<uint16_t>);
intrinsics.add("yuni.string.append.u32", Builtin::yn_string_append<uint32_t>);
intrinsics.add("yuni.string.append.u64", Builtin::yn_string_append<uint64_t>);
intrinsics.add("yuni.string.append.i8", Builtin::yn_string_append<int8_t>);
intrinsics.add("yuni.string.append.i16", Builtin::yn_string_append<int16_t>);
intrinsics.add("yuni.string.append.i32", Builtin::yn_string_append<int32_t>);
intrinsics.add("yuni.string.append.i64", Builtin::yn_string_append<int64_t>);
intrinsics.add("yuni.string.cout", Builtin::yn_string_cout);
}
} // namespace Nany
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>
#include <mitkGIFFirstOrderHistogramStatistics.h>
class mitkGIFFirstOrderHistogramStatisticsTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkGIFFirstOrderHistogramStatisticsTestSuite);
MITK_TEST(ImageDescription_PhantomTest);
CPPUNIT_TEST_SUITE_END();
private:
mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;
public:
void setUp(void) override
{
m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
}
void ImageDescription_PhantomTest()
{
mitk::GIFFirstOrderHistogramStatistics::Pointer featureCalculator = mitk::GIFFirstOrderHistogramStatistics::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 46 features.", std::size_t(46), featureList.size());
// These values are taken from the IBSI Initiative to ensure compatibility
// The values are given with an accuracy of 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Index should be 2.15 with Large IBSI Phantom Image", 2.15, results["First Order Histogram::Mean Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Variance Index should be 3.05 with Large IBSI Phantom Image", 3.05, results["First Order Histogram::Variance Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Skewness Index should be 1.08 with Large IBSI Phantom Image", 1.08, results["First Order Histogram::Skewness Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Excess Kurtosis Index should be -0.355 with Large IBSI Phantom Image", -0.355, results["First Order Histogram::Excess Kurtosis Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Median Index should be 1 with Large IBSI Phantom Image", 1.0, results["First Order Histogram::Median Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Minimum Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Minimum Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Percentile 10 Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Percentile 10 Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Percentile 90 Index should be 2.15 with Large IBSI Phantom Image", 4, results["First Order Histogram::Percentile 90 Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Maximum Index should be 6 with Large IBSI Phantom Image", 6, results["First Order Histogram::Maximum Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mode Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Mode Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Interquantile Range Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Range Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Absolute DeviationIndex should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
/*CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Image Dimension X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Z"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing X"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Y"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Z"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Mean intensity should be 0.6865 with Large IBSI Phantom Image", 0.686508, results["Diagnostic::Image Mean intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Minimum intensity should be 0 with Large IBSI Phantom Image", 0, results["Diagnostic::Image Minimum intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Maximum intensity should be 9 with Large IBSI Phantom Image", 9, results["Diagnostic::Image Maximum intensity"], 0.0001);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Mask Dimension X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Z"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box X should be 5 with Large IBSI Phantom Image", int(5), int(results["Diagnostic::Mask bounding box X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Y should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Z should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Z"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing X"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Y"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Z"], 0.0001);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Voxel Count should be 74 with Large IBSI Phantom Image", int(74), int(results["Diagnostic::Mask Voxel Count"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Mean intensity should be 2.14865 with Large IBSI Phantom Image", 2.14865, results["Diagnostic::Mask Mean intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Minimum intensity should be 1 with Large IBSI Phantom Image", 1, results["Diagnostic::Mask Minimum intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Maximum intensity should be 6 with Large IBSI Phantom Image", 6, results["Diagnostic::Mask Maximum intensity"], 0.0001);*/
}
};
MITK_TEST_SUITE_REGISTRATION(mitkGIFFirstOrderHistogramStatistics )<commit_msg>Tests more values, Quantile coefficient of Dispersion is wrong<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>
#include <mitkGIFFirstOrderHistogramStatistics.h>
class mitkGIFFirstOrderHistogramStatisticsTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkGIFFirstOrderHistogramStatisticsTestSuite);
MITK_TEST(ImageDescription_PhantomTest);
CPPUNIT_TEST_SUITE_END();
private:
mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;
public:
void setUp(void) override
{
m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
}
void ImageDescription_PhantomTest()
{
mitk::GIFFirstOrderHistogramStatistics::Pointer featureCalculator = mitk::GIFFirstOrderHistogramStatistics::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 46 features.", std::size_t(46), featureList.size());
// These values are taken from the IBSI Initiative to ensure compatibility
// The values are given with an accuracy of 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Index should be 2.15 with Large IBSI Phantom Image", 2.15, results["First Order Histogram::Mean Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Variance Index should be 3.05 with Large IBSI Phantom Image", 3.05, results["First Order Histogram::Variance Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Skewness Index should be 1.08 with Large IBSI Phantom Image", 1.08, results["First Order Histogram::Skewness Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Excess Kurtosis Index should be -0.355 with Large IBSI Phantom Image", -0.355, results["First Order Histogram::Excess Kurtosis Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Median Index should be 1 with Large IBSI Phantom Image", 1.0, results["First Order Histogram::Median Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Minimum Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Minimum Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Percentile 10 Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Percentile 10 Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Percentile 90 Index should be 2.15 with Large IBSI Phantom Image", 4, results["First Order Histogram::Percentile 90 Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Maximum Index should be 6 with Large IBSI Phantom Image", 6, results["First Order Histogram::Maximum Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mode Index should be 1 with Large IBSI Phantom Image", 1, results["First Order Histogram::Mode Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Interquantile Range Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Range Index should be 5 with Large IBSI Phantom Image", 5, results["First Order Histogram::Range Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Absolute Deviation Index should be 3 with Large IBSI Phantom Image", 1.55, results["First Order Histogram::Mean Absolute Deviation Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Robust Mean Absolute Deviation Index should be 1.11 with Large IBSI Phantom Image", 1.11, results["First Order Histogram::Robust Mean Absolute Deviation Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Median Absolute Deviation Index should be 1.14 with Large IBSI Phantom Image", 1.14, results["First Order Histogram::Median Absolute Deviation Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Coefficient of Variation Index should be 0.812 with Large IBSI Phantom Image", 0.812, results["First Order Histogram::Coefficient of Variation Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Quantile coefficient of Dispersion Index should be 0.6 with Large IBSI Phantom Image", 0.6, results["First Order Histogram::Quantile coefficient of Dispersion Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Entropy Index should be 1.27 with Large IBSI Phantom Image", 1.27, results["First Order Histogram::Quantile coefficient of Dispersion Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Uniformity Index should be 0.512 with Large IBSI Phantom Image", 0.512, results["First Order Histogram::Uniformity Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Maximum Gradient should be 8 with Large IBSI Phantom Image", 8, results["First Order Histogram::Maximum Gradient"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Maximum Gradient Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Maximum Gradient Index"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Minimum Gradient should be -50 with Large IBSI Phantom Image", -50, results["First Order Histogram::Minimum Gradient"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Minimum Gradient Index should be 3 with Large IBSI Phantom Image", 1, results["First Order Histogram::Minimum Gradient Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Robust Mean Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram:: Index should be 3 with Large IBSI Phantom Image", 3, results["First Order Histogram::Interquantile Range Index"], 0.01);
/*CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Image Dimension X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Z"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing X"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Y"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Z"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Mean intensity should be 0.6865 with Large IBSI Phantom Image", 0.686508, results["Diagnostic::Image Mean intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Minimum intensity should be 0 with Large IBSI Phantom Image", 0, results["Diagnostic::Image Minimum intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Maximum intensity should be 9 with Large IBSI Phantom Image", 9, results["Diagnostic::Image Maximum intensity"], 0.0001);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Mask Dimension X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Z"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box X should be 5 with Large IBSI Phantom Image", int(5), int(results["Diagnostic::Mask bounding box X"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Y should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Y"]));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Z should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Z"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing X"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Y"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Z"], 0.0001);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Voxel Count should be 74 with Large IBSI Phantom Image", int(74), int(results["Diagnostic::Mask Voxel Count"]));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Mean intensity should be 2.14865 with Large IBSI Phantom Image", 2.14865, results["Diagnostic::Mask Mean intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Minimum intensity should be 1 with Large IBSI Phantom Image", 1, results["Diagnostic::Mask Minimum intensity"], 0.0001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Maximum intensity should be 6 with Large IBSI Phantom Image", 6, results["Diagnostic::Mask Maximum intensity"], 0.0001);*/
}
};
MITK_TEST_SUITE_REGISTRATION(mitkGIFFirstOrderHistogramStatistics )<|endoftext|> |
<commit_before>/*
* gVirtuS -- A GPGPU transparent virtualization component.
*
* Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples.
*
* This file is part of gVirtuS.
*
* gVirtuS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* gVirtuS 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 General Public License
* along with gVirtuS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by: Flora Giannone <[email protected]>,
* Department of Applied Science
*/
#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>
#include <stdio.h>
using namespace std;
/*Create a CUDA context*/
extern CUresult cuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddVariableForArguments(flags);
CudaDrFrontend::AddVariableForArguments(dev);
CudaDrFrontend::Execute("cuCtxCreate");
if (CudaDrFrontend::Success()){
*pctx = (CUcontext) (CudaDrFrontend::GetOutputDevicePointer());
}
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/*Increment a context's usage-count*/
extern CUresult cuCtxAttach(CUcontext *pctx, unsigned int flags) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddVariableForArguments(flags);
CudaDrFrontend::AddHostPointerForArguments(pctx);
CudaDrFrontend::Execute("cuCtxAttach");
if (CudaDrFrontend::Success())
*pctx = (CUcontext) CudaDrFrontend::GetOutputDevicePointer();
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/*Destroy the current context or a floating CUDA context*/
extern CUresult cuCtxDestroy(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxDestroy");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Decrement a context's usage-count. */
extern CUresult cuCtxDetach(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxDetach");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Returns the device ID for the current context.*/
extern CUresult cuCtxGetDevice(CUdevice *device) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddHostPointerForArguments(device);
CudaDrFrontend::Execute("cuCtxGetDevice");
if (CudaDrFrontend::Success()) {
*device = *(CudaDrFrontend::GetOutputHostPointer<CUdevice > ());
}
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Pops the current CUDA context from the current CPU thread.*/
extern CUresult cuCtxPopCurrent(CUcontext *pctx) {
CudaDrFrontend::Prepare();
CUcontext ctx;
pctx = &ctx;
CudaDrFrontend::Execute("cuCtxPopCurrent");
if (CudaDrFrontend::Success())
*pctx = (CUcontext) (CudaDrFrontend::GetOutputDevicePointer());
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Pushes a floating context on the current CPU thread. */
extern CUresult cuCtxPushCurrent(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxPushCurrent");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Block for a context's tasks to complete.*/
extern CUresult cuCtxSynchronize(void) {
CudaDrFrontend::Prepare();
CudaDrFrontend::Execute("cuCtxSynchronize");
return (CUresult) CudaDrFrontend::GetExitCode();
}
<commit_msg>Added cuCtxSynchronize, cuCtxDisablePeerAccess, cuCtxEnablePeerAccess, cuDeviceCanAccessPeer<commit_after>/*
* gVirtuS -- A GPGPU transparent virtualization component.
*
* Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples.
*
* This file is part of gVirtuS.
*
* gVirtuS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* gVirtuS 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 General Public License
* along with gVirtuS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by: Flora Giannone <[email protected]>,
* Department of Applied Science
*/
#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>
#include <stdio.h>
using namespace std;
/*Create a CUDA context*/
extern CUresult cuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddVariableForArguments(flags);
CudaDrFrontend::AddVariableForArguments(dev);
CudaDrFrontend::Execute("cuCtxCreate");
if (CudaDrFrontend::Success()){
*pctx = (CUcontext) (CudaDrFrontend::GetOutputDevicePointer());
}
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/*Increment a context's usage-count*/
extern CUresult cuCtxAttach(CUcontext *pctx, unsigned int flags) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddVariableForArguments(flags);
CudaDrFrontend::AddHostPointerForArguments(pctx);
CudaDrFrontend::Execute("cuCtxAttach");
if (CudaDrFrontend::Success())
*pctx = (CUcontext) CudaDrFrontend::GetOutputDevicePointer();
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/*Destroy the current context or a floating CUDA context*/
extern CUresult cuCtxDestroy(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxDestroy");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Decrement a context's usage-count. */
extern CUresult cuCtxDetach(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxDetach");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Returns the device ID for the current context.*/
extern CUresult cuCtxGetDevice(CUdevice *device) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddHostPointerForArguments(device);
CudaDrFrontend::Execute("cuCtxGetDevice");
if (CudaDrFrontend::Success()) {
*device = *(CudaDrFrontend::GetOutputHostPointer<CUdevice > ());
}
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Pops the current CUDA context from the current CPU thread.*/
extern CUresult cuCtxPopCurrent(CUcontext *pctx) {
CudaDrFrontend::Prepare();
CUcontext ctx;
pctx = &ctx;
CudaDrFrontend::Execute("cuCtxPopCurrent");
if (CudaDrFrontend::Success())
*pctx = (CUcontext) (CudaDrFrontend::GetOutputDevicePointer());
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Pushes a floating context on the current CPU thread. */
extern CUresult cuCtxPushCurrent(CUcontext ctx) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) ctx);
CudaDrFrontend::Execute("cuCtxPushCurrent");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/*Block for a context's tasks to complete.*/
extern CUresult cuCtxSynchronize(void) {
CudaDrFrontend::Prepare();
CudaDrFrontend::Execute("cuCtxSynchronize");
return (CUresult) CudaDrFrontend::GetExitCode();
}
/* Disable peer access */
extern CUresult cuCtxDisablePeerAccess(CUcontext peerContext) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) peerContext);
CudaDrFrontend::Execute("cuCtxDisablePeerAccess");
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/* Enable peer access */
extern CUresult cuCtxEnablePeerAccess(CUcontext peerContext, unsigned int flags) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddDevicePointerForArguments((void*) peerContext);
CudaDrFrontend::AddVariableForArguments(flags);
CudaDrFrontend::Execute("cuCtxEnablePeerAccess");
return (CUresult) (CudaDrFrontend::GetExitCode());
}
/* Check if two devices could be connected using peer to peer */
extern CUresult cuDeviceCanAccessPeer(int *canAccessPeer, CUdevice dev, CUdevice peerDev) {
CudaDrFrontend::Prepare();
CudaDrFrontend::AddHostPointerForArguments(canAccessPeer);
CudaDrFrontend::AddVariableForArguments(dev);
CudaDrFrontend::AddVariableForArguments(peerDev);
CudaDrFrontend::Execute("cuDeviceCanAccessPeer");
if (CudaDrFrontend::Success())
*canAccessPeer = *(CudaDrFrontend::GetOutputHostPointer<int>());
return (CUresult) (CudaDrFrontend::GetExitCode());
}
<|endoftext|> |
<commit_before>//
// chip.cpp
// chip
//
// Created by lex on 22/08/2017.
// Copyright © 2017 lex. All rights reserved.
//
#include "chip.hpp"
bool Chip::ReadRom(const std::string& file) {
std::ifstream is(file, std::ios::binary | std::ios::ate);
if (!is.is_open()) {
std::cout << "couldn't open file " << file << std::endl;
return false;
}
const size_t size = is.tellg();
std::cout << "rom size: " << size << " bytes" << std::endl;
if (size > MAXIMUM_GAME_SIZE) {
std::cout << "rom too large: " << size << " bytes" << std::endl;
is.close();
return false;
}
is.seekg(0);
is.read(reinterpret_cast<char*>(&memory.at(PROGRAM_START_ADDRESS)), size);
is.close();
return true;
}
void Chip::Initialize() {
PC = PROGRAM_START_ADDRESS;
I = 0;
SP = 0;
delayTimer = 0;
soundTimer = 0;
ClearScreen();
std::copy_n(FONTSET.begin(), FONTSET_SIZE, memory.begin());
}
void Chip::ClearScreen() {
for (auto& row : videoMemory) {
std::fill(row.begin(), row.end(), 0);
}
if (debugging) {
std::cout << "Screen cleared" << std::endl;
}
}
const VideoMemory& Chip::GetVideoMemory() const {
return videoMemory;
}
void Chip::DrawSprite(const uint8_t &x, const uint8_t &y, const uint8_t &height) {
for (int byteIndex = 0; byteIndex < height; ++byteIndex) {
const uint8_t byte = memory[I + byteIndex];
for (int bitIndex = 0; bitIndex < 8; ++bitIndex) {
const uint8_t bit = (byte >> bitIndex) & 0x1;
const size_t memoryX = (x + (7 - bitIndex)) % VIDEO_MEMORY_COLUMNS;
const size_t memoryY = (y + byteIndex) % VIDEO_MEMORY_ROWS;
const uint8_t oldBit = videoMemory.at(memoryY).at(memoryX);
// Sprite pixels that are set flip the color of the corresponding screen pixel, while unset sprite pixels do nothing.
videoMemory.at(memoryY).at(memoryX) = oldBit ^ bit;
// The carry flag (VF) is set to 1 if any screen pixels are flipped from set to unset when a sprite is drawn and set to 0 otherwise.
V[F] = (oldBit == 1 && bit == 1 ? 1 : 0);
}
}
}
void Chip::Step() {
const uint16_t opcode = memory[PC] << 8 | memory[PC + 1];
// https://en.wikipedia.org/wiki/CHIP-8#Opcode_table
// NNN: address
// NN: 8-bit constant
// N: 4-bit constant
// X and Y: 4-bit register identifier
const uint16_t NNN = opcode & 0x0FFF;
const uint8_t NN = opcode & 0x00FF;
const uint8_t N = opcode & 0x00F;
const uint8_t X = (opcode >> 8) & 0x000F;
const uint8_t Y = (opcode >> 4) & 0x000F;
if (debugging) {
std::cout << "PC: " << PC << " Opcode: ";
std::cout << std::hex << std::uppercase << static_cast<int>(opcode) << std::endl;
std::cout << std::dec << std::nouppercase << std::endl;
}
switch (opcode & 0xF000) {
case 0x0000:
switch (NN) {
case 0x00E0:
// Clears the screen.
ClearScreen();
PC += 2;
break;
case 0x00EE:
// Returns from a subroutine.
PC = stack.at(--SP);
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0x1000:
// Jumps to address NNN.
PC = NNN;
break;
case 0x2000:
// Calls subroutine at NNN.
stack.at(SP) = PC + 2;
++SP;
PC = NNN;
break;
case 0x3000:
// Skips the next instruction if VX equals NN.
PC += (V[X] == NN ? 4 : 2);
break;
case 0x4000:
// Skips the next instruction if VX doesn't equal NN.
PC += (V[X] != NN ? 4 : 2);
break;
case 0x5000:
// Skips the next instruction if VX equals VY.
PC += (V[X] == V[Y] ? 4 : 2);
break;
case 0x6000:
// Sets VX to NN.
V[X] = NN;
PC += 2;
break;
case 0x7000:
// Adds NN to VX.
V[X] += NN;
PC += 2;
break;
case 0x8000:
switch (N) {
case 0x0:
// Sets VX to the value of VY.
V[X] = V[Y];
PC += 2;
break;
case 0x1:
// Sets VX to VX or VY.
V[X] = V[X] | V[Y];
PC += 2;
break;
case 0x2:
// Sets VX to VX and VY.
V[X] = V[X] & V[Y];
PC += 2;
break;
case 0x3:
// Sets VX to VX xor VY.
V[X] = V[X] ^ V[Y];
PC += 2;
break;
case 0x4:
// Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't.
V[F] = (static_cast<int>(V[X]) + static_cast<int>(V[Y]) > 255 ? 1 : 0);
V[X] += V[Y];
PC += 2;
break;
case 0x5:
// VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
V[F] = (V[X] > V[Y] ? 1 : 0);
V[X] -= V[Y];
PC += 2;
break;
case 0x6:
// Shifts VX right by one. VF is set to the value of the least significant bit of VX before the shift.
V[F] = V[X] & 0x1;
V[X] = V[X] >> 1;
PC += 2;
break;
case 0x7:
// Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
V[F] = (V[X] < V[Y] ? 1 : 0);
V[X] = V[Y] - V[X];
PC += 2;
break;
case 0xE:
// Shifts VX left by one. VF is set to the value of the most significant bit of VX before the shift.
V[F] = (V[X] >> 7) & 0x1;
V[X] = V[X] << 1;
PC += 2;
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0x9000:
switch (N) {
case 0:
// Skips the next instruction if VX doesn't equal VY.
PC += (V[X] != V[Y] ? 4 : 2);
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0xA000:
// Sets I to the address NNN.
I = NNN;
PC += 2;
break;
case 0xB000:
// Jumps to the address NNN plus V0.
PC = NNN + V[0x0];
break;
case 0xC000:
// Sets VX to the result of a bitwise and operation on a random number (Typically: 0 to 255) and NN.
V[X] = (std::rand() % 256) & NN;
PC += 2;
break;
case 0xD000:
// Draws a sprite at coordinate (VX, VY)
DrawSprite(V[X], V[Y], N);
PC += 2;
break;
case 0xE000:
switch (NN) {
case 0x9E:
// Skips the next instruction if the key stored in VX is pressed.
UnimplementedOpcode(opcode);
PC += 2;
break;
case 0xA1:
// Skips the next instruction if the key stored in VX isn't pressed.
UnimplementedOpcode(opcode);
PC += 4;
break;
}
break;
case 0xF000:
switch (NN) {
case 0x07:
// Sets VX to the value of the delay timer.
V[X] = delayTimer;
PC += 2;
break;
case 0x0A:
// A key press is awaited, and then stored in VX. (Blocking Operation. All instruction halted until next key event)
UnimplementedOpcode(opcode);
PC += 2;
break;
case 0x15:
// Sets the delay timer to VX.
delayTimer = V[X];
PC += 2;
break;
case 0x18:
// Sets the sound timer to VX.
soundTimer = V[X];
PC += 2;
break;
case 0x1E:
// Adds VX to I.
I += V[X];
PC += 2;
break;
case 0x29:
// Sets I to the location of the sprite for the character in VX.
I = FONTSET_CHARACTER_SIZE * V[X];
PC += 2;
break;
case 0x33:
// Stores the binary-coded decimal representation of VX
memory[I] = (V[X] % 1000) / 100;
memory[I + 1] = (V[X] % 100) / 10;
memory[I + 2] = (V[X] % 10);
PC += 2;
break;
case 0x55:
// Stores V0 to VX (including VX) in memory starting at address I.
for (int i = 0; i < X; ++i) {
memory.at(I + i) = V[i];
}
I += X + 1;
PC += 2;
break;
case 0x65:
// Fills V0 to VX (including VX) with values from memory starting at address I.
for (int i = 0; i < X; ++i) {
V[i] = memory.at(I + i);
}
I += X + 1;
PC += 2;
break;
}
break;
default:
UnknownOpcode(opcode);
break;
}
if (delayTimer > 0) {
--delayTimer;
}
if (soundTimer > 0) {
--soundTimer;
}
}
void Chip::UnimplementedOpcode(const uint16_t& opcode) const {
std::cout << "Unimplemented opcode: "
<< std::hex << std::uppercase << static_cast<int>(opcode)
<< std::dec << std::nouppercase << std::endl;
}
void Chip::UnknownOpcode(const uint16_t& opcode) const {
std::cout << "Unknown opcode: "
<< std::hex << std::uppercase << static_cast<int>(opcode)
<< std::dec << std::nouppercase << std::endl;
}
<commit_msg>fix collision detection<commit_after>//
// chip.cpp
// chip
//
// Created by lex on 22/08/2017.
// Copyright © 2017 lex. All rights reserved.
//
#include "chip.hpp"
bool Chip::ReadRom(const std::string& file) {
std::ifstream is(file, std::ios::binary | std::ios::ate);
if (!is.is_open()) {
std::cout << "couldn't open file " << file << std::endl;
return false;
}
const size_t size = is.tellg();
std::cout << "rom size: " << size << " bytes" << std::endl;
if (size > MAXIMUM_GAME_SIZE) {
std::cout << "rom too large: " << size << " bytes" << std::endl;
is.close();
return false;
}
is.seekg(0);
is.read(reinterpret_cast<char*>(&memory.at(PROGRAM_START_ADDRESS)), size);
is.close();
return true;
}
void Chip::Initialize() {
PC = PROGRAM_START_ADDRESS;
I = 0;
SP = 0;
delayTimer = 0;
soundTimer = 0;
ClearScreen();
std::copy_n(FONTSET.begin(), FONTSET_SIZE, memory.begin());
}
void Chip::ClearScreen() {
for (auto& row : videoMemory) {
std::fill(row.begin(), row.end(), 0);
}
if (debugging) {
std::cout << "Screen cleared" << std::endl;
}
}
const VideoMemory& Chip::GetVideoMemory() const {
return videoMemory;
}
void Chip::DrawSprite(const uint8_t &x, const uint8_t &y, const uint8_t &height) {
V[F] = 0;
for (int byteIndex = 0; byteIndex < height; ++byteIndex) {
const uint8_t byte = memory[I + byteIndex];
for (int bitIndex = 0; bitIndex < 8; ++bitIndex) {
const uint8_t bit = (byte >> bitIndex) & 0x1;
const size_t memoryX = (x + (7 - bitIndex)) % VIDEO_MEMORY_COLUMNS;
const size_t memoryY = (y + byteIndex) % VIDEO_MEMORY_ROWS;
const uint8_t oldBit = videoMemory.at(memoryY).at(memoryX);
// Sprite pixels that are set flip the color of the corresponding screen pixel, while unset sprite pixels do nothing.
videoMemory.at(memoryY).at(memoryX) = oldBit ^ bit;
// The carry flag (VF) is set to 1 if any screen pixels are flipped from set to unset when a sprite is drawn and set to 0 otherwise.
if (oldBit == 1 && bit == 1) {
V[F] = 1;
}
if (debugging && V[F] == 1) {
std::cout << "Collision detected at (" << memoryX << ", " << memoryY << ")" << std::endl;
}
}
}
}
void Chip::Step() {
const uint16_t opcode = memory[PC] << 8 | memory[PC + 1];
// https://en.wikipedia.org/wiki/CHIP-8#Opcode_table
// NNN: address
// NN: 8-bit constant
// N: 4-bit constant
// X and Y: 4-bit register identifier
const uint16_t NNN = opcode & 0x0FFF;
const uint8_t NN = opcode & 0x00FF;
const uint8_t N = opcode & 0x00F;
const uint8_t X = (opcode >> 8) & 0x000F;
const uint8_t Y = (opcode >> 4) & 0x000F;
if (debugging) {
std::cout << "PC: " << PC << " Opcode: ";
std::cout << std::hex << std::uppercase << static_cast<int>(opcode) << std::endl;
std::cout << std::dec << std::nouppercase << std::endl;
}
switch (opcode & 0xF000) {
case 0x0000:
switch (NN) {
case 0x00E0:
// Clears the screen.
ClearScreen();
PC += 2;
break;
case 0x00EE:
// Returns from a subroutine.
PC = stack.at(--SP);
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0x1000:
// Jumps to address NNN.
PC = NNN;
break;
case 0x2000:
// Calls subroutine at NNN.
stack.at(SP) = PC + 2;
++SP;
PC = NNN;
break;
case 0x3000:
// Skips the next instruction if VX equals NN.
PC += (V[X] == NN ? 4 : 2);
break;
case 0x4000:
// Skips the next instruction if VX doesn't equal NN.
PC += (V[X] != NN ? 4 : 2);
break;
case 0x5000:
// Skips the next instruction if VX equals VY.
PC += (V[X] == V[Y] ? 4 : 2);
break;
case 0x6000:
// Sets VX to NN.
V[X] = NN;
PC += 2;
break;
case 0x7000:
// Adds NN to VX.
V[X] += NN;
PC += 2;
break;
case 0x8000:
switch (N) {
case 0x0:
// Sets VX to the value of VY.
V[X] = V[Y];
PC += 2;
break;
case 0x1:
// Sets VX to VX or VY.
V[X] = V[X] | V[Y];
PC += 2;
break;
case 0x2:
// Sets VX to VX and VY.
V[X] = V[X] & V[Y];
PC += 2;
break;
case 0x3:
// Sets VX to VX xor VY.
V[X] = V[X] ^ V[Y];
PC += 2;
break;
case 0x4:
// Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't.
V[F] = (static_cast<int>(V[X]) + static_cast<int>(V[Y]) > 255 ? 1 : 0);
V[X] += V[Y];
PC += 2;
break;
case 0x5:
// VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
V[F] = (V[X] > V[Y] ? 1 : 0);
V[X] -= V[Y];
PC += 2;
break;
case 0x6:
// Shifts VX right by one. VF is set to the value of the least significant bit of VX before the shift.
V[F] = V[X] & 0x1;
V[X] = V[X] >> 1;
PC += 2;
break;
case 0x7:
// Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
V[F] = (V[X] < V[Y] ? 1 : 0);
V[X] = V[Y] - V[X];
PC += 2;
break;
case 0xE:
// Shifts VX left by one. VF is set to the value of the most significant bit of VX before the shift.
V[F] = (V[X] >> 7) & 0x1;
V[X] = V[X] << 1;
PC += 2;
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0x9000:
switch (N) {
case 0:
// Skips the next instruction if VX doesn't equal VY.
PC += (V[X] != V[Y] ? 4 : 2);
break;
default:
UnknownOpcode(opcode);
break;
}
break;
case 0xA000:
// Sets I to the address NNN.
I = NNN;
PC += 2;
break;
case 0xB000:
// Jumps to the address NNN plus V0.
PC = NNN + V[0x0];
break;
case 0xC000:
// Sets VX to the result of a bitwise and operation on a random number (Typically: 0 to 255) and NN.
V[X] = (std::rand() % 256) & NN;
PC += 2;
break;
case 0xD000:
// Draws a sprite at coordinate (VX, VY)
DrawSprite(V[X], V[Y], N);
PC += 2;
break;
case 0xE000:
switch (NN) {
case 0x9E:
// Skips the next instruction if the key stored in VX is pressed.
UnimplementedOpcode(opcode);
PC += 2;
break;
case 0xA1:
// Skips the next instruction if the key stored in VX isn't pressed.
UnimplementedOpcode(opcode);
PC += 4;
break;
}
break;
case 0xF000:
switch (NN) {
case 0x07:
// Sets VX to the value of the delay timer.
V[X] = delayTimer;
PC += 2;
break;
case 0x0A:
// A key press is awaited, and then stored in VX. (Blocking Operation. All instruction halted until next key event)
UnimplementedOpcode(opcode);
PC += 2;
break;
case 0x15:
// Sets the delay timer to VX.
delayTimer = V[X];
PC += 2;
break;
case 0x18:
// Sets the sound timer to VX.
soundTimer = V[X];
PC += 2;
break;
case 0x1E:
// Adds VX to I.
I += V[X];
PC += 2;
break;
case 0x29:
// Sets I to the location of the sprite for the character in VX.
I = FONTSET_CHARACTER_SIZE * V[X];
PC += 2;
break;
case 0x33:
// Stores the binary-coded decimal representation of VX
memory[I] = (V[X] % 1000) / 100;
memory[I + 1] = (V[X] % 100) / 10;
memory[I + 2] = (V[X] % 10);
PC += 2;
break;
case 0x55:
// Stores V0 to VX (including VX) in memory starting at address I.
for (int i = 0; i < X; ++i) {
memory.at(I + i) = V[i];
}
I += X + 1;
PC += 2;
break;
case 0x65:
// Fills V0 to VX (including VX) with values from memory starting at address I.
for (int i = 0; i < X; ++i) {
V[i] = memory.at(I + i);
}
I += X + 1;
PC += 2;
break;
}
break;
default:
UnknownOpcode(opcode);
break;
}
if (delayTimer > 0) {
--delayTimer;
}
if (soundTimer > 0) {
--soundTimer;
}
}
void Chip::UnimplementedOpcode(const uint16_t& opcode) const {
std::cout << "Unimplemented opcode: "
<< std::hex << std::uppercase << static_cast<int>(opcode)
<< std::dec << std::nouppercase << std::endl;
}
void Chip::UnknownOpcode(const uint16_t& opcode) const {
std::cout << "Unknown opcode: "
<< std::hex << std::uppercase << static_cast<int>(opcode)
<< std::dec << std::nouppercase << std::endl;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef CONCURRENT_HPP_
#define CONCURRENT_HPP_
#include "top.hpp"
#include "thread/atomic.hpp"
#include "os/alloc.hpp"
#include <new>
//! \addtogroup Utils
namespace amd {/*@{*/
namespace details {
template <typename T, int N>
struct TaggedPointerHelper
{
static const uintptr_t TagMask = (1u << N) - 1;
private:
TaggedPointerHelper(); // Cannot instantiate
void* operator new(size_t); // allocate or
void operator delete(void*); // delete a TaggedPointerHelper.
public:
//! Create a tagged pointer.
static TaggedPointerHelper* make(T* ptr, size_t tag)
{
return reinterpret_cast<TaggedPointerHelper*>(
(reinterpret_cast<uintptr_t>(ptr) & ~TagMask) | (tag & TagMask));
}
//! Return the pointer value.
T* ptr()
{
return reinterpret_cast<T*>(
reinterpret_cast<uintptr_t>(this) & ~TagMask);
}
//! Return the tag value.
size_t tag() const
{
return reinterpret_cast<uintptr_t>(this) & TagMask;
}
};
} // namespace details
/*! \brief An unbounded thread-safe queue.
*
* This queue orders elements first-in-first-out. It is based on the algorithm
* "Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue
* Algorithms by Maged M. Michael and Michael L. Scott.".
*
* FIXME_lmoriche: Implement the new/delete operators for SimplyLinkedNode
* using thread-local allocation buffers.
*/
template <typename T, int N = 5>
class ConcurrentLinkedQueue : public HeapObject
{
//! A simply-linked node
struct Node
{
typedef details::TaggedPointerHelper<Node,N> TaggedPointerHelper;
typedef TaggedPointerHelper* Ptr;
T value_; //!< The value stored in that node.
Atomic<Ptr> next_; //!< Pointer to the next node
//! Create a Node::Ptr
static inline Ptr ptr(Node* ptr, size_t counter = 0)
{
return TaggedPointerHelper::make(ptr, counter);
}
};
private:
Atomic<typename Node::Ptr> head_; //! Pointer to the oldest element.
Atomic<typename Node::Ptr> tail_; //! Pointer to the most recent element.
private:
//! \brief Allocate a free node.
static inline Node* allocNode()
{
return new(AlignedMemory::allocate(sizeof(Node), 1 << N)) Node();
}
//! \brief Return a node to the free list.
static inline void reclaimNode(Node* node)
{
AlignedMemory::deallocate(node);
}
public:
//! \brief Initialize a new concurrent linked queue.
ConcurrentLinkedQueue();
//! \brief Destroy this concurrent linked queue.
~ConcurrentLinkedQueue();
//! \brief Enqueue an element to this queue.
inline void enqueue(T elem);
//! \brief Dequeue an element from this queue.
inline T dequeue();
};
/*@}*/
template <typename T, int N>
inline
ConcurrentLinkedQueue<T,N>::ConcurrentLinkedQueue()
{
// Create the first "dummy" node.
Node* dummy = allocNode();
dummy->next_ = NULL;
DEBUG_ONLY(dummy->value_ = NULL);
// Head and tail should now point to it (empty list).
head_ = tail_ = Node::ptr(dummy);
// Make sure the instance is fully initialized before it becomes
// globally visible.
MemoryOrder::sfence();
}
template <typename T, int N>
inline
ConcurrentLinkedQueue<T,N>::~ConcurrentLinkedQueue()
{
typename Node::Ptr head = head_;
typename Node::Ptr tail = tail_;
while (head->ptr() != tail->ptr()) {
Node* node = head->ptr();
head = head->ptr()->next_;
reclaimNode(node);
}
reclaimNode(head->ptr());
}
template <typename T, int N>
inline void
ConcurrentLinkedQueue<T,N>::enqueue(T elem)
{
Node* node = allocNode();
node->value_ = elem;
node->next_ = NULL;
while (true) {
typename Node::Ptr tail = tail_;
typename Node::Ptr next = tail->ptr()->next_;
MemoryOrder::lfence();
if (tail == tail_) {
if (next->ptr() == NULL) {
if (tail->ptr()->next_.compareAndSet(
next, Node::ptr(node, next->tag()+1))) {
tail_.compareAndSet(tail, Node::ptr(node, tail->tag()+1));
return;
}
}
else {
tail_.compareAndSet(
tail, Node::ptr(next->ptr(), tail->tag()+1));
}
}
}
}
template <typename T, int N>
inline T
ConcurrentLinkedQueue<T,N>::dequeue()
{
while (true) {
typename Node::Ptr head = head_;
typename Node::Ptr tail = tail_;
typename Node::Ptr next = head->ptr()->next_;
MemoryOrder::lfence();
if (head == head_) {
if (head->ptr() == tail->ptr()) {
if (next->ptr() == NULL) {
return NULL;
}
tail_.compareAndSet(
tail, Node::ptr(next->ptr(), tail->tag()+1));
}
else {
T value = next->ptr()->value_;
if (head_.compareAndSet(
head, Node::ptr(next->ptr(), head->tag()+1))) {
// we can reclaim head now
reclaimNode(head->ptr());
return value;
}
}
}
}
}
} // namespace amd
#endif /*CONCURRENT_HPP_*/
<commit_msg>P4 to Git Change 1081826 by lmoriche@lmoriche_opencl_dev on 2014/09/26 18:40:37<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef CONCURRENT_HPP_
#define CONCURRENT_HPP_
#include "top.hpp"
#include "os/alloc.hpp"
#include <atomic>
#include <new>
//! \addtogroup Utils
namespace amd {/*@{*/
namespace details {
template <typename T, int N>
struct TaggedPointerHelper
{
static const uintptr_t TagMask = (1u << N) - 1;
private:
TaggedPointerHelper(); // Cannot instantiate
void* operator new(size_t); // allocate or
void operator delete(void*); // delete a TaggedPointerHelper.
public:
//! Create a tagged pointer.
static TaggedPointerHelper* make(T* ptr, size_t tag)
{
return reinterpret_cast<TaggedPointerHelper*>(
(reinterpret_cast<uintptr_t>(ptr) & ~TagMask) | (tag & TagMask));
}
//! Return the pointer value.
T* ptr()
{
return reinterpret_cast<T*>(
reinterpret_cast<uintptr_t>(this) & ~TagMask);
}
//! Return the tag value.
size_t tag() const
{
return reinterpret_cast<uintptr_t>(this) & TagMask;
}
};
} // namespace details
/*! \brief An unbounded thread-safe queue.
*
* This queue orders elements first-in-first-out. It is based on the algorithm
* "Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue
* Algorithms by Maged M. Michael and Michael L. Scott.".
*
* FIXME_lmoriche: Implement the new/delete operators for SimplyLinkedNode
* using thread-local allocation buffers.
*/
template <typename T, int N = 5>
class ConcurrentLinkedQueue : public HeapObject
{
//! A simply-linked node
struct Node
{
typedef details::TaggedPointerHelper<Node,N> TaggedPointerHelper;
typedef TaggedPointerHelper* Ptr;
T value_; //!< The value stored in that node.
std::atomic<Ptr> next_; //!< Pointer to the next node
//! Create a Node::Ptr
static inline Ptr ptr(Node* ptr, size_t counter = 0)
{
return TaggedPointerHelper::make(ptr, counter);
}
};
private:
std::atomic<typename Node::Ptr> head_; //! Pointer to the oldest element.
std::atomic<typename Node::Ptr> tail_; //! Pointer to the most recent element.
private:
//! \brief Allocate a free node.
static inline Node* allocNode()
{
return new(AlignedMemory::allocate(sizeof(Node), 1 << N)) Node();
}
//! \brief Return a node to the free list.
static inline void reclaimNode(Node* node)
{
AlignedMemory::deallocate(node);
}
public:
//! \brief Initialize a new concurrent linked queue.
ConcurrentLinkedQueue();
//! \brief Destroy this concurrent linked queue.
~ConcurrentLinkedQueue();
//! \brief Enqueue an element to this queue.
inline void enqueue(T elem);
//! \brief Dequeue an element from this queue.
inline T dequeue();
};
/*@}*/
template <typename T, int N>
inline
ConcurrentLinkedQueue<T,N>::ConcurrentLinkedQueue()
{
// Create the first "dummy" node.
Node* dummy = allocNode();
dummy->next_ = NULL;
DEBUG_ONLY(dummy->value_ = NULL);
// Head and tail should now point to it (empty list).
head_ = tail_ = Node::ptr(dummy);
// Make sure the instance is fully initialized before it becomes
// globally visible.
MemoryOrder::sfence();
}
template <typename T, int N>
inline
ConcurrentLinkedQueue<T,N>::~ConcurrentLinkedQueue()
{
typename Node::Ptr head = head_;
typename Node::Ptr tail = tail_;
while (head->ptr() != tail->ptr()) {
Node* node = head->ptr();
head = head->ptr()->next_;
reclaimNode(node);
}
reclaimNode(head->ptr());
}
template <typename T, int N>
inline void
ConcurrentLinkedQueue<T,N>::enqueue(T elem)
{
Node* node = allocNode();
node->value_ = elem;
node->next_ = NULL;
while (true) {
typename Node::Ptr tail = tail_.load(std::memory_order_acquire);
typename Node::Ptr next =
tail->ptr()->next_.load(std::memory_order_acquire);
if (tail == tail_.load(std::memory_order_acquire)) {
if (next->ptr() == NULL) {
if (tail->ptr()->next_.compare_exchange_weak(
next, Node::ptr(node, next->tag()+1),
std::memory_order_acq_rel, std::memory_order_acquire)) {
tail_.compare_exchange_strong(
tail, Node::ptr(node, tail->tag()+1),
std::memory_order_acq_rel, std::memory_order_acquire);
return;
}
}
else {
tail_.compare_exchange_strong(
tail, Node::ptr(next->ptr(), tail->tag()+1),
std::memory_order_acq_rel, std::memory_order_acquire);
}
}
}
}
template <typename T, int N>
inline T
ConcurrentLinkedQueue<T,N>::dequeue()
{
while (true) {
typename Node::Ptr head = head_.load(std::memory_order_acquire);
typename Node::Ptr tail = tail_.load(std::memory_order_acquire);
typename Node::Ptr next =
head->ptr()->next_.load(std::memory_order_acquire);
if (head == head_.load(std::memory_order_acquire)) {
if (head->ptr() == tail->ptr()) {
if (next->ptr() == NULL) {
return NULL;
}
tail_.compare_exchange_strong(
tail, Node::ptr(next->ptr(), tail->tag()+1),
std::memory_order_acq_rel, std::memory_order_acquire);
}
else {
T value = next->ptr()->value_;
if (head_.compare_exchange_weak(
head, Node::ptr(next->ptr(), head->tag()+1),
std::memory_order_acq_rel, std::memory_order_acquire)) {
// we can reclaim head now
reclaimNode(head->ptr());
return value;
}
}
}
}
}
} // namespace amd
#endif /*CONCURRENT_HPP_*/
<|endoftext|> |
<commit_before>#include "CCHandler.h"
#include "Midi.h"
CCHandler *activeCCHandler = NULL;
void CCHandlerOnCCCallback(uint8_t *msg) {
if (activeCCHandler != NULL) {
activeCCHandler->onCCCallback(msg);
}
}
void onOutgoingCCCallback(uint8_t *msg) {
if (activeCCHandler != NULL) {
activeCCHandler->onOutgoingCC(MIDI_VOICE_CHANNEL(msg[0]), msg[1], msg[2]);
}
}
void CCHandler::setup() {
activeCCHandler = this;
Midi.addOnControlChangeCallback(CCHandlerOnCCCallback);
MidiUart.addOnControlChangeCallback(onOutgoingCCCallback);
}
void CCHandler::destroy() {
Midi.removeOnControlChangeCallback(CCHandlerOnCCCallback);
MidiUart.removeOnControlChangeCallback(onOutgoingCCCallback);
}
void CCHandler::onCCCallback(uint8_t *msg) {
incoming_cc_t cc;
cc.channel = MIDI_VOICE_CHANNEL(msg[0]);
cc.cc = msg[1];
cc.value = msg[2];
bool found = false;
for (int i = 0; i < incomingCCs.size(); i++) {
incoming_cc_t *cc2 = incomingCCs.getp(i);
if (cc2->channel == cc.channel && cc2->cc == cc.cc) {
cc2->value = cc.value;
found = true;
break;
}
}
if (!found)
incomingCCs.putp(&cc);
if (midiLearnEnc != NULL) {
midiLearnEnc->initCCEncoder(cc.channel, cc.cc);
midiLearnEnc->setValue(cc.value);
if (callback != NULL)
callback(midiLearnEnc);
midiLearnEnc = NULL;
}
for (int i = 0; i < encoders.size; i++) {
if (encoders.arr[i] != NULL) {
if (encoders.arr[i]->getChannel() == cc.channel &&
encoders.arr[i]->getCC() == cc.cc) {
encoders.arr[i]->setValue(cc.value);
}
}
}
}
void CCHandler::onOutgoingCC(uint8_t channel, uint8_t cc, uint8_t value) {
for (int i = 0; i < encoders.size; i++) {
if (encoders.arr[i] != NULL) {
if (encoders.arr[i]->getChannel() == channel &&
encoders.arr[i]->getCC() == cc) {
encoders.arr[i]->setValue(value);
}
}
}
}
<commit_msg>add correct recognition and shifting (ahem) of incoming ccs<commit_after>#include "CCHandler.h"
#include "Midi.h"
CCHandler *activeCCHandler = NULL;
void CCHandlerOnCCCallback(uint8_t *msg) {
if (activeCCHandler != NULL) {
activeCCHandler->onCCCallback(msg);
}
}
void onOutgoingCCCallback(uint8_t *msg) {
if (activeCCHandler != NULL) {
activeCCHandler->onOutgoingCC(MIDI_VOICE_CHANNEL(msg[0]), msg[1], msg[2]);
}
}
void CCHandler::setup() {
activeCCHandler = this;
Midi.addOnControlChangeCallback(CCHandlerOnCCCallback);
MidiUart.addOnControlChangeCallback(onOutgoingCCCallback);
}
void CCHandler::destroy() {
Midi.removeOnControlChangeCallback(CCHandlerOnCCCallback);
MidiUart.removeOnControlChangeCallback(onOutgoingCCCallback);
}
void CCHandler::onCCCallback(uint8_t *msg) {
incoming_cc_t cc;
cc.channel = MIDI_VOICE_CHANNEL(msg[0]);
cc.cc = msg[1];
cc.value = msg[2];
bool found = false;
for (int i = 0; i < incomingCCs.size(); i++) {
incoming_cc_t *cc2 = incomingCCs.getp(i);
if (cc2->channel == cc.channel && cc2->cc == cc.cc) {
// cc2->value = cc.value;
found = true;
/* swap to top */
// incoming_cc_t *topcc = incomingCCs.getp(incomingCCs.size() - 1);
for (int j = i; j < incomingCCs.size() - 1; j++) {
incoming_cc_t *botcc = incomingCCs.getp(j);
incoming_cc_t *topcc = incomingCCs.getp(j+1);
botcc->value = topcc->value;
botcc->channel = topcc->channel;
botcc->cc = topcc->cc;
topcc->value = cc.value;
topcc->cc = cc.cc;
topcc->channel = cc.channel;
}
break;
}
}
if (!found)
incomingCCs.putp(&cc);
if (midiLearnEnc != NULL) {
midiLearnEnc->initCCEncoder(cc.channel, cc.cc);
midiLearnEnc->setValue(cc.value);
if (callback != NULL)
callback(midiLearnEnc);
midiLearnEnc = NULL;
}
for (int i = 0; i < encoders.size; i++) {
if (encoders.arr[i] != NULL) {
if (encoders.arr[i]->getChannel() == cc.channel &&
encoders.arr[i]->getCC() == cc.cc) {
encoders.arr[i]->setValue(cc.value);
}
}
}
}
void CCHandler::onOutgoingCC(uint8_t channel, uint8_t cc, uint8_t value) {
for (int i = 0; i < encoders.size; i++) {
if (encoders.arr[i] != NULL) {
if (encoders.arr[i]->getChannel() == channel &&
encoders.arr[i]->getCC() == cc) {
encoders.arr[i]->setValue(value);
}
}
}
}
<|endoftext|> |
<commit_before>#include "pixelboost/file/fileHelpers.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/device/indexBuffer.h"
#include "pixelboost/graphics/device/texture.h"
#include "pixelboost/graphics/device/vertexBuffer.h"
#include "pixelboost/graphics/helper/screenHelpers.h"
#include "pixelboost/graphics/render/font/fontRenderer.h"
using namespace pixelboost;
FontRenderer::FontRenderer(int maxCharacters)
: _MaxCharacters(maxCharacters)
{
_IndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, _MaxCharacters*6);
_VertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ_UV, _MaxCharacters*4);
_IndexBuffer->Lock();
unsigned short* indices = _IndexBuffer->GetData();
for (int i=0; i<_MaxCharacters; i++)
{
indices[0] = (i*4);
indices[1] = (i*4)+1;
indices[2] = (i*4)+2;
indices[3] = (i*4);
indices[4] = (i*4)+2;
indices[5] = (i*4)+3;
indices += 6;
}
_IndexBuffer->Unlock();
}
FontRenderer::~FontRenderer()
{
GraphicsDevice::Instance()->DestroyIndexBuffer(_IndexBuffer);
GraphicsDevice::Instance()->DestroyVertexBuffer(_VertexBuffer);
for (FontMap::iterator it = _Fonts.begin(); it != _Fonts.end(); ++it)
{
delete it->second;
}
}
void FontRenderer::AddCharacter(Vertex_PXYZ_UV* buffer, const Font::Character& character, float offset, float baseline)
{
float xOffset = character.xOffset;
float yOffset = -character.yOffset + baseline;
buffer[0].position[0] = offset + xOffset;
buffer[0].position[1] = yOffset - character.height;
buffer[0].uv[0] = character.uvx;
buffer[0].uv[1] = character.uvy + character.uvv;
buffer[1].position[0] = offset + xOffset;
buffer[1].position[1] = yOffset;
buffer[1].uv[0] = character.uvx;
buffer[1].uv[1] = character.uvy;
buffer[2].position[0] = offset + character.width + xOffset;
buffer[2].position[1] = yOffset;
buffer[2].uv[0] = character.uvx + character.uvu;
buffer[2].uv[1] = character.uvy;
buffer[3].position[0] = offset + character.width + xOffset;
buffer[3].position[1] = yOffset - character.height;
buffer[3].uv[0] = character.uvx + character.uvu;
buffer[3].uv[1] = character.uvy + character.uvv;
}
void FontRenderer::LoadFont(const std::string& name)
{
if (_Fonts.find(name) != _Fonts.end())
return;
Font* font = new Font();
std::string fileRoot = FileHelpers::GetRootPath();
std::string fntFilename = fileRoot + "/data/fonts/" + name + (ScreenHelpers::IsHighResolution() ? "-hd" : "") + ".fnt";
std::string fontContents = FileHelpers::FileToString(fntFilename);
std::vector<std::string> lines;
SplitString(fontContents, '\n', lines);
for (std::vector<std::string>::iterator line = lines.begin(); line != lines.end(); ++line)
{
std::vector<std::string> elements;
SplitString(*line, ' ', elements);
if (elements.size() < 1 )
continue;
std::map<std::string, std::string> data;
for (std::vector<std::string>::iterator element = elements.begin(); element != elements.end(); ++element)
{
data[element->substr(0, element->find('='))] = element->substr(element->find('=')+1);
}
std::string elementType = elements[0];
Vec2 texSize;
if (elementType == "info")
{
int size = (int)atoi(data["size"].c_str());
font->size = size;
} else if (elementType == "common")
{
int lineHeight = (int)atoi(data["lineHeight"].c_str());
int base = (int)atoi(data["base"].c_str());
int scaleW = (int)atoi(data["scaleW"].c_str());
int scaleH = (int)atoi(data["scaleH"].c_str());
font->base = (float)base/(float)font->size;
font->lineHeight = (float)lineHeight / (float)scaleH;
texSize = Vec2(scaleW, scaleH);
} else if (elementType == "page")
{
std::string texFilename = fileRoot + "/data/fonts/" + data["file"].substr(1, data["file"].find('"', 1)-1);
font->texture = GraphicsDevice::Instance()->CreateTexture();
font->texture->Load(texFilename, true);
} else if (elementType == "char")
{
Font::Character character;
char charCode = (char)atoi(data["id"].c_str());
int x = (int)atoi(data["x"].c_str());
int y = (int)atoi(data["y"].c_str());
int width = (int)atoi(data["width"].c_str());
int height = (int)atoi(data["height"].c_str());
int xoffset = (int)atoi(data["xoffset"].c_str());
int yoffset = (int)atoi(data["yoffset"].c_str());
int xadvance = (int)atoi(data["xadvance"].c_str());
character.width = width/(float)font->size;
character.height = height/(float)font->size;
character.uvx = x/texSize[0];
character.uvy = y/texSize[1];
character.uvu = width/texSize[0];
character.uvv = height/texSize[1];
character.xOffset = xoffset/(float)font->size;
character.yOffset = yoffset/(float)font->size;
character.xAdvance = xadvance/(float)font->size;
font->chars[charCode] = character;
} else if (elementType == "kerning")
{
char charOne = (char)atoi(data["first"].c_str());
char charTwo = (char)atoi(data["second"].c_str());
int amount = (int)atoi(data["amount"].c_str());
font->kerning[std::pair<char, char>(charOne, charTwo)] = amount/texSize[0];
}
}
_Fonts[name] = font;
}
void FontRenderer::Update(float time)
{
_Instances.clear();
}
void FontRenderer::Render(RenderLayer* layer)
{
InstanceList& instances = _Instances[layer];
if (instances.size() == 0)
return;
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
#ifndef PIXELBOOST_GRAPHICS_PREMULTIPLIED_ALPHA
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#else
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
#endif
glDisableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
_IndexBuffer->Bind();
for (InstanceList::iterator it = instances.begin(); it != instances.end(); ++it)
{
Font* font;
FontMap::iterator fontIt = _Fonts.find(it->_Font);
if (fontIt == _Fonts.end())
continue;
font = fontIt->second;
_VertexBuffer->Lock();
Vertex_PXYZ_UV* vertexBuffer = static_cast<Vertex_PXYZ_UV*>(_VertexBuffer->GetData());
float offset = 0.f;
for (int i=0; i<it->_String.length(); i++)
{
std::map<char, Font::Character>::iterator charIt = font->chars.find(it->_String[i]);
if (charIt == font->chars.end())
continue;
AddCharacter(vertexBuffer, charIt->second, offset, font->base);
vertexBuffer += 4;
offset += charIt->second.xAdvance;
if (i<it->_String.length()-1)
{
std::map<std::pair<char, char>, float>::iterator kerningIt = font->kerning.find(std::pair<char, char>(it->_String[i], it->_String[i+1]));
if (kerningIt != font->kerning.end())
offset += kerningIt->second;
}
}
_VertexBuffer->Unlock(it->_String.length()*4);
_VertexBuffer->Bind();
font->texture->Bind(0);
glPushMatrix();
glTranslatef(it->_Position[0], it->_Position[1], 0.f);
glRotatef(it->_Rotation, 0, 0, 1);
glScalef(it->_Size, it->_Size, 1.f);
switch (it->_Alignment) {
case kFontAlignLeft:
break;
case kFontAlignCenter:
glTranslatef(-offset/2.f, 0, 0);
break;
case kFontAlignRight:
glTranslatef(-offset, 0, 0);
break;
}
GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, it->_String.length()*6);
glPopMatrix();
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
GraphicsDevice::Instance()->BindIndexBuffer(0);
GraphicsDevice::Instance()->BindVertexBuffer(0);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
}
bool FontRenderer::AttachToRenderer(RenderLayer* layer, const std::string& fontName, const std::string& string, Vec2 position, FontAlign alignment, float size, float rotation, Vec4 color)
{
FontInstance instance;
instance._Font = fontName;
instance._String = string;
instance._Position = position;
instance._Alignment = alignment;
instance._Rotation = rotation;
instance._Size = size;
instance._Color = color;
_Instances[layer].push_back(instance);
return true;
}
void FontRenderer::SplitString(const std::string& string, char seperator, std::vector<std::string>& output)
{
std::string item;
for (int i=0; i<string.length(); i++)
{
char ch=string[i];
if (ch == seperator)
{
if (!item.empty())
{
output.push_back(item);
}
item = "";
}
else
{
item += ch;
}
}
if (!item.empty())
{
output.push_back(item);
}
}
<commit_msg>Add temp color implementation to font renderer<commit_after>#include "pixelboost/file/fileHelpers.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/device/indexBuffer.h"
#include "pixelboost/graphics/device/texture.h"
#include "pixelboost/graphics/device/vertexBuffer.h"
#include "pixelboost/graphics/helper/screenHelpers.h"
#include "pixelboost/graphics/render/font/fontRenderer.h"
using namespace pixelboost;
FontRenderer::FontRenderer(int maxCharacters)
: _MaxCharacters(maxCharacters)
{
_IndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, _MaxCharacters*6);
_VertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ_UV, _MaxCharacters*4);
_IndexBuffer->Lock();
unsigned short* indices = _IndexBuffer->GetData();
for (int i=0; i<_MaxCharacters; i++)
{
indices[0] = (i*4);
indices[1] = (i*4)+1;
indices[2] = (i*4)+2;
indices[3] = (i*4);
indices[4] = (i*4)+2;
indices[5] = (i*4)+3;
indices += 6;
}
_IndexBuffer->Unlock();
}
FontRenderer::~FontRenderer()
{
GraphicsDevice::Instance()->DestroyIndexBuffer(_IndexBuffer);
GraphicsDevice::Instance()->DestroyVertexBuffer(_VertexBuffer);
for (FontMap::iterator it = _Fonts.begin(); it != _Fonts.end(); ++it)
{
delete it->second;
}
}
void FontRenderer::AddCharacter(Vertex_PXYZ_UV* buffer, const Font::Character& character, float offset, float baseline)
{
float xOffset = character.xOffset;
float yOffset = -character.yOffset + baseline;
buffer[0].position[0] = offset + xOffset;
buffer[0].position[1] = yOffset - character.height;
buffer[0].uv[0] = character.uvx;
buffer[0].uv[1] = character.uvy + character.uvv;
buffer[1].position[0] = offset + xOffset;
buffer[1].position[1] = yOffset;
buffer[1].uv[0] = character.uvx;
buffer[1].uv[1] = character.uvy;
buffer[2].position[0] = offset + character.width + xOffset;
buffer[2].position[1] = yOffset;
buffer[2].uv[0] = character.uvx + character.uvu;
buffer[2].uv[1] = character.uvy;
buffer[3].position[0] = offset + character.width + xOffset;
buffer[3].position[1] = yOffset - character.height;
buffer[3].uv[0] = character.uvx + character.uvu;
buffer[3].uv[1] = character.uvy + character.uvv;
}
void FontRenderer::LoadFont(const std::string& name)
{
if (_Fonts.find(name) != _Fonts.end())
return;
Font* font = new Font();
std::string fileRoot = FileHelpers::GetRootPath();
std::string fntFilename = fileRoot + "/data/fonts/" + name + (ScreenHelpers::IsHighResolution() ? "-hd" : "") + ".fnt";
std::string fontContents = FileHelpers::FileToString(fntFilename);
std::vector<std::string> lines;
SplitString(fontContents, '\n', lines);
for (std::vector<std::string>::iterator line = lines.begin(); line != lines.end(); ++line)
{
std::vector<std::string> elements;
SplitString(*line, ' ', elements);
if (elements.size() < 1 )
continue;
std::map<std::string, std::string> data;
for (std::vector<std::string>::iterator element = elements.begin(); element != elements.end(); ++element)
{
data[element->substr(0, element->find('='))] = element->substr(element->find('=')+1);
}
std::string elementType = elements[0];
Vec2 texSize;
if (elementType == "info")
{
int size = (int)atoi(data["size"].c_str());
font->size = size;
} else if (elementType == "common")
{
int lineHeight = (int)atoi(data["lineHeight"].c_str());
int base = (int)atoi(data["base"].c_str());
int scaleW = (int)atoi(data["scaleW"].c_str());
int scaleH = (int)atoi(data["scaleH"].c_str());
font->base = (float)base/(float)font->size;
font->lineHeight = (float)lineHeight / (float)scaleH;
texSize = Vec2(scaleW, scaleH);
} else if (elementType == "page")
{
std::string texFilename = fileRoot + "/data/fonts/" + data["file"].substr(1, data["file"].find('"', 1)-1);
font->texture = GraphicsDevice::Instance()->CreateTexture();
font->texture->Load(texFilename, true);
} else if (elementType == "char")
{
Font::Character character;
char charCode = (char)atoi(data["id"].c_str());
int x = (int)atoi(data["x"].c_str());
int y = (int)atoi(data["y"].c_str());
int width = (int)atoi(data["width"].c_str());
int height = (int)atoi(data["height"].c_str());
int xoffset = (int)atoi(data["xoffset"].c_str());
int yoffset = (int)atoi(data["yoffset"].c_str());
int xadvance = (int)atoi(data["xadvance"].c_str());
character.width = width/(float)font->size;
character.height = height/(float)font->size;
character.uvx = x/texSize[0];
character.uvy = y/texSize[1];
character.uvu = width/texSize[0];
character.uvv = height/texSize[1];
character.xOffset = xoffset/(float)font->size;
character.yOffset = yoffset/(float)font->size;
character.xAdvance = xadvance/(float)font->size;
font->chars[charCode] = character;
} else if (elementType == "kerning")
{
char charOne = (char)atoi(data["first"].c_str());
char charTwo = (char)atoi(data["second"].c_str());
int amount = (int)atoi(data["amount"].c_str());
font->kerning[std::pair<char, char>(charOne, charTwo)] = amount/texSize[0];
}
}
_Fonts[name] = font;
}
void FontRenderer::Update(float time)
{
_Instances.clear();
}
void FontRenderer::Render(RenderLayer* layer)
{
InstanceList& instances = _Instances[layer];
if (instances.size() == 0)
return;
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
#ifndef PIXELBOOST_GRAPHICS_PREMULTIPLIED_ALPHA
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#else
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
#endif
glDisableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
_IndexBuffer->Bind();
for (InstanceList::iterator it = instances.begin(); it != instances.end(); ++it)
{
Font* font;
FontMap::iterator fontIt = _Fonts.find(it->_Font);
if (fontIt == _Fonts.end())
continue;
font = fontIt->second;
_VertexBuffer->Lock();
Vertex_PXYZ_UV* vertexBuffer = static_cast<Vertex_PXYZ_UV*>(_VertexBuffer->GetData());
float offset = 0.f;
for (int i=0; i<it->_String.length(); i++)
{
std::map<char, Font::Character>::iterator charIt = font->chars.find(it->_String[i]);
if (charIt == font->chars.end())
continue;
AddCharacter(vertexBuffer, charIt->second, offset, font->base);
vertexBuffer += 4;
offset += charIt->second.xAdvance;
if (i<it->_String.length()-1)
{
std::map<std::pair<char, char>, float>::iterator kerningIt = font->kerning.find(std::pair<char, char>(it->_String[i], it->_String[i+1]));
if (kerningIt != font->kerning.end())
offset += kerningIt->second;
}
}
_VertexBuffer->Unlock(it->_String.length()*4);
_VertexBuffer->Bind();
font->texture->Bind(0);
glPushMatrix();
glTranslatef(it->_Position[0], it->_Position[1], 0.f);
glRotatef(it->_Rotation, 0, 0, 1);
glScalef(it->_Size, it->_Size, 1.f);
switch (it->_Alignment) {
case kFontAlignLeft:
break;
case kFontAlignCenter:
glTranslatef(-offset/2.f, 0, 0);
break;
case kFontAlignRight:
glTranslatef(-offset, 0, 0);
break;
}
glColor4f(it->_Color[0], it->_Color[1], it->_Color[2], it->_Color[3]);
GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, it->_String.length()*6);
glColor4f(1, 1, 1, 1);
glPopMatrix();
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
GraphicsDevice::Instance()->BindIndexBuffer(0);
GraphicsDevice::Instance()->BindVertexBuffer(0);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
}
bool FontRenderer::AttachToRenderer(RenderLayer* layer, const std::string& fontName, const std::string& string, Vec2 position, FontAlign alignment, float size, float rotation, Vec4 color)
{
FontInstance instance;
instance._Font = fontName;
instance._String = string;
instance._Position = position;
instance._Alignment = alignment;
instance._Rotation = rotation;
instance._Size = size;
instance._Color = color;
_Instances[layer].push_back(instance);
return true;
}
void FontRenderer::SplitString(const std::string& string, char seperator, std::vector<std::string>& output)
{
std::string item;
for (int i=0; i<string.length(); i++)
{
char ch=string[i];
if (ch == seperator)
{
if (!item.empty())
{
output.push_back(item);
}
item = "";
}
else
{
item += ch;
}
}
if (!item.empty())
{
output.push_back(item);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxextension
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/busyinfo.h>
#include <wx/numdlg.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h>
#include <wx/extension/renderer.h>
#include "appl.h"
#include "appl.xpm"
enum
{
ID_FIRST = 15000,
ID_CONFIG_DLG,
ID_CONFIG_DLG_READONLY,
ID_PRINT_SPECIAL,
ID_LOCALE_SHOW_DIR,
ID_STATISTICS_CLEAR,
ID_STATISTICS_SHOW,
ID_STC_CONFIG_DLG,
ID_STC_FLAGS,
ID_STC_GOTO,
ID_STC_SPLIT,
ID_STC_LEXER,
ID_LAST,
};
BEGIN_EVENT_TABLE(exSampleFrame, exFrame)
EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, exSampleFrame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, exSampleFrame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, exSampleFrame::OnCommand)
END_EVENT_TABLE()
IMPLEMENT_APP(exSampleApp)
bool exSampleApp::OnInit()
{
SetAppName("exSample");
SetLogging();
exApp::OnInit();
exSampleFrame *frame = new exSampleFrame("exSample");
frame->Show(true);
SetTopWindow(frame);
return true;
}
#if wxUSE_GRID
exSampleDir::exSampleDir(const wxString& fullpath, const wxString& findfiles, exGrid* grid)
: exDir(fullpath, findfiles)
, m_Grid(grid)
{
}
void exSampleDir::OnFile(const wxString& file)
{
m_Grid->AppendRows(1);
const int no = m_Grid->GetNumberRows() - 1;
m_Grid->SetCellValue(no, 0, wxString::Format("cell%d", no));
m_Grid->SetCellValue(no, 1, file);
exRenderer* renderer = new exRenderer(exRenderer::CELL_CROSS, *wxGREEN_PEN, *wxRED_PEN);
m_Grid->SetCellRenderer(no, 0, renderer);
// Let's make these cells readonly and colour them, so we can test
// things like cutting and dropping is forbidden.
m_Grid->SetReadOnly(no, 1);
m_Grid->SetCellBackgroundColour(no, 1, *wxLIGHT_GREY);
}
#endif
exSampleFrame::exSampleFrame(const wxString& title)
: exManagedFrame(NULL, wxID_ANY, title)
, m_FlagsSTC(0)
{
SetIcon(appl_xpm);
exMenu* menuFile = new exMenu;
menuFile->Append(wxID_OPEN);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(ID_PRINT_SPECIAL, _("Print Test")); // test to print without a window
menuFile->AppendSeparator();
menuFile->Append(ID_LOCALE_SHOW_DIR, _("Show Locale Dir"));
menuFile->AppendSeparator();
menuFile->Append(ID_STATISTICS_SHOW, _("Show Statistics"));
menuFile->Append(ID_STATISTICS_CLEAR, _("Clear Statistics"));
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
exMenu* menuConfig = new exMenu;
menuConfig->Append(ID_CONFIG_DLG, exEllipsed(_("Config Dialog")));
menuConfig->Append(ID_CONFIG_DLG_READONLY, exEllipsed(_("Config Dialog Readonly")));
menuConfig->AppendSeparator();
exMenu* menuSTC = new exMenu;
menuSTC->Append(ID_STC_FLAGS, exEllipsed(_("Open Flag")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_CONFIG_DLG, exEllipsed(_("Config Dialog")));
menuSTC->Append(ID_STC_GOTO, exEllipsed(_("Goto Dialog")));
menuSTC->Append(ID_STC_LEXER, exEllipsed(_("Lexer Dialog")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_SPLIT, _("Split"));
menuSTC->AppendSeparator();
menuSTC->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuSTC->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuSTC->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback"));
exMenu* menuHelp = new exMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuSTC, _("&STC"));
menubar->Append(menuConfig, _("&Config"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
m_Notebook = new exNotebook(this, NULL);
#if wxUSE_GRID
m_Grid = new exGrid(m_Notebook);
#endif
m_ListView = new exListView(m_Notebook);
m_STC = new exSTC(this);
m_STCShell = new exSTCShell(this, ">", wxTextFile::GetEOL(), true, 10);
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true).Name("exSTC"));
GetManager().AddPane(m_STCShell, wxAuiPaneInfo().Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_Notebook, wxAuiPaneInfo().Left().MinSize(wxSize(250, 250)));
GetManager().Update();
assert(exApp::GetLexers());
exSTC* st = new exSTC(this, exApp::GetLexers()->GetFileName().GetFullPath());
m_Notebook->AddPage(st, exApp::GetLexers()->GetFileName().GetFullName());
m_Notebook->AddPage(m_ListView, "exListView");
#if wxUSE_GRID
m_Notebook->AddPage(m_Grid, "exGrid");
m_Grid->CreateGrid(0, 0);
m_Grid->AppendCols(2);
exSampleDir dir(wxGetCwd(), "appl.*", m_Grid);
dir.FindFiles();
m_Grid->AutoSizeColumns();
#endif
m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON);
m_ListView->InsertColumn("String", exColumn::COL_STRING);
m_ListView->InsertColumn("Number", exColumn::COL_INT);
m_ListView->InsertColumn("Float", exColumn::COL_FLOAT);
m_ListView->InsertColumn("Date", exColumn::COL_DATE);
const int items = 50;
for (int i = 0; i < items; i++)
{
exListItem item(m_ListView, wxString::Format("item%d", i));
item.Insert();
item.SetColumnText(1, wxString::Format("%d", i));
item.SetColumnText(2, wxString::Format("%f", (float)i / 2.0));
item.SetColumnText(3, wxDateTime::Now().Format());
// Set some images.
if (i == 0) item.SetImage(wxART_CDROM);
else if (i == 1) item.SetImage(wxART_REMOVABLE);
else if (i == 2) item.SetImage(wxART_FOLDER);
else if (i == 3) item.SetImage(wxART_FOLDER_OPEN);
else if (i == 4) item.SetImage(wxART_GO_DIR_UP);
else if (i == 5) item.SetImage(wxART_EXECUTABLE_FILE);
else if (i == 6) item.SetImage(wxART_NORMAL_FILE);
else item.SetImage(wxART_TICK_MARK);
}
std::vector<exPane> panes;
panes.push_back(exPane("PaneText", -3));
panes.push_back(exPane("PaneFileType", 50, _("File type")));
panes.push_back(exPane("PaneCells", 60, _("Cells")));
panes.push_back(exPane("PaneItems", 60, _("Items")));
panes.push_back(exPane("PaneLines", 100, _("Lines")));
panes.push_back(exPane("PaneLexer", 60, _("Lexer")));
SetupStatusBar(panes);
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddTool(wxID_EXIT);
m_ToolBar->Realize();
}
void exSampleFrame::ConfigDialogApplied(wxWindowID id)
{
m_STC->ConfigGet();
m_STCShell->ConfigGet();
}
void exSampleFrame::OnCommand(wxCommandEvent& event)
{
m_Statistics.Inc(wxString::Format("%d", event.GetId()));
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(EX_LIB_VERSION);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
{
wxFileDialog dlg(this,
_("Select File"),
wxEmptyString,
wxEmptyString,
wxFileSelectorDefaultWildcardStr,
wxFD_OPEN | wxFD_CHANGE_DIR);
if (m_STC->AskFileOpen(dlg) == wxID_CANCEL) return;
wxStopWatch sw;
m_STC->Open(dlg.GetPath(), 0, wxEmptyString, m_FlagsSTC);
const long stop = sw.Time();
StatusText(wxString::Format("exSTC::Open:%ld milliseconds, %d bytes", stop, m_STC->GetTextLength()));
}
break;
case wxID_PREVIEW: m_ListView->PrintPreview(); break;
case wxID_PRINT: m_ListView->Print(); break;
case wxID_PRINT_SETUP: exApp::GetPrinter()->PageSetup(); break;
case wxID_SAVE:
m_STC->FileSave();
if (m_STC->GetFileName().GetFullPath() == exApp::GetLexers()->GetFileName().GetFullPath())
{
if (exApp::GetLexers()->Read())
{
wxLogMessage("file contains: %d lexers", exApp::GetLexers()->Get().size());
m_STC->SetLexer();
// As the lexer might have changed, update status bar field as well.
m_STC->UpdateStatusBar("PaneLexer");
}
}
break;
case ID_CONFIG_DLG:
{
std::vector<exConfigItem> v;
for (size_t h = 1; h <= 25; h++)
{
v.push_back(exConfigItem(wxString::Format(_("check%d"), h), CONFIG_CHECKBOX, "Checkboxes"));
}
for (size_t i = 1; i <= 25; i++)
{
v.push_back(exConfigItem(wxString::Format(_("colour%d"), i), CONFIG_COLOUR, "Colours"));
}
for (size_t j = 1; j <= 10; j++)
{
v.push_back(exConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT, "Integers", true));
}
for (size_t k = 1; k <= 10; k++)
{
v.push_back(exConfigItem(wxString::Format(_("spin%d"), k), 1, k, wxString("Spin controls")));
}
for (size_t l = 1; l <= 10; l++)
{
v.push_back(exConfigItem(wxString::Format(_("string%d"), l), CONFIG_STRING, "Strings"));
}
for (size_t m = 1; m <= 10; m++)
{
v.push_back(exConfigItem(wxString::Format(_("combobox%d"), m), CONFIG_COMBOBOX, "Comboboxes"));
}
v.push_back(exConfigItem(_("dirpicker"), CONFIG_DIRPICKERCTRL, "Pickers"));
v.push_back(exConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL, "Pickers"));
exConfigDialog* dlg = new exConfigDialog(
this,
v,
_("Config Dialog"),
wxEmptyString,
5,
6,
wxAPPLY | wxCANCEL,
wxID_ANY,
wxDefaultPosition,
wxSize(400,300));
dlg->Show();
// Dialog is not placed nicely.
//GetManager().GetPane("NOTEBOOK"));
//GetManager().Update();
}
break;
case ID_CONFIG_DLG_READONLY:
{
std::vector<exConfigItem> v;
v.push_back(exConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL));
for (size_t j = 1; j <= 10; j++)
{
v.push_back(exConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT));
}
exConfigDialog* dlg = new exConfigDialog(
this,
v,
_("Config Dialog Readonly"),
wxEmptyString,
2,
2,
wxCANCEL);
dlg->Show();
}
break;
case ID_PRINT_SPECIAL:
{
wxHtmlEasyPrinting* print = exApp::GetPrinter();
wxPrintDialogData printDialogData(*print->GetPrintData());
wxPrinter printer(&printDialogData);
wxHtmlPrintout printout;
printout.SetHtmlFile("appl.xpm");
printer.Print(this, &printout, false);
/*
// This is the simplest, but
// asks for printing always (in lib source).
print->PrintFile("mondrian.xpm");
*/
/*
// This could be made better, immediately hide etc.
exSTC* stc = new exSTC(this, "mondrian.xpm");
stc->Hide();
stc->Print(false);// however stc->Print(false) does not print
delete stc;
*/
}
break;
case ID_LOCALE_SHOW_DIR:
wxLogMessage(exApp::GetCatalogDir());
break;
case ID_SHELL_COMMAND:
m_STCShell->AppendText("\nHello '" + event.GetString() + "' from the shell"),
m_STCShell->Prompt();
break;
case ID_STATISTICS_SHOW:
m_Notebook->AddPage(m_Statistics.Show(m_Notebook), "Statistics");
break;
case ID_STATISTICS_CLEAR:
m_Statistics.Clear();
break;
case ID_STC_CONFIG_DLG:
exSTC::ConfigDialog(
_("Editor Options"),
exSTC::STC_CONFIG_MODELESS | exSTC::STC_CONFIG_WITH_APPLY);
break;
case ID_STC_FLAGS:
{
long value = wxGetNumberFromUser(
"Input:",
wxEmptyString,
"STC Open Flag",
m_FlagsSTC,
0,
2 * exSTC::STC_OPEN_FROM_URL);
if (value != -1)
{
m_FlagsSTC = value;
}
}
break;
case ID_STC_GOTO: m_STC->GotoDialog(); break;
case ID_STC_LEXER: m_STC->LexerDialog(); break;
case ID_STC_SPLIT:
{
exSTC* stc = new exSTC(*m_STC);
m_Notebook->AddPage(
stc,
wxString::Format("stc%d", stc->GetId()),
m_STC->GetFileName().GetFullName());
stc->SetDocPointer(m_STC->GetDocPointer());
}
break;
}
}
<commit_msg>removed unnecessary separator<commit_after>/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxextension
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/busyinfo.h>
#include <wx/numdlg.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h>
#include <wx/extension/renderer.h>
#include "appl.h"
#include "appl.xpm"
enum
{
ID_FIRST = 15000,
ID_CONFIG_DLG,
ID_CONFIG_DLG_READONLY,
ID_PRINT_SPECIAL,
ID_LOCALE_SHOW_DIR,
ID_STATISTICS_CLEAR,
ID_STATISTICS_SHOW,
ID_STC_CONFIG_DLG,
ID_STC_FLAGS,
ID_STC_GOTO,
ID_STC_SPLIT,
ID_STC_LEXER,
ID_LAST,
};
BEGIN_EVENT_TABLE(exSampleFrame, exFrame)
EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, exSampleFrame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, exSampleFrame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, exSampleFrame::OnCommand)
END_EVENT_TABLE()
IMPLEMENT_APP(exSampleApp)
bool exSampleApp::OnInit()
{
SetAppName("exSample");
SetLogging();
exApp::OnInit();
exSampleFrame *frame = new exSampleFrame("exSample");
frame->Show(true);
SetTopWindow(frame);
return true;
}
#if wxUSE_GRID
exSampleDir::exSampleDir(const wxString& fullpath, const wxString& findfiles, exGrid* grid)
: exDir(fullpath, findfiles)
, m_Grid(grid)
{
}
void exSampleDir::OnFile(const wxString& file)
{
m_Grid->AppendRows(1);
const int no = m_Grid->GetNumberRows() - 1;
m_Grid->SetCellValue(no, 0, wxString::Format("cell%d", no));
m_Grid->SetCellValue(no, 1, file);
exRenderer* renderer = new exRenderer(exRenderer::CELL_CROSS, *wxGREEN_PEN, *wxRED_PEN);
m_Grid->SetCellRenderer(no, 0, renderer);
// Let's make these cells readonly and colour them, so we can test
// things like cutting and dropping is forbidden.
m_Grid->SetReadOnly(no, 1);
m_Grid->SetCellBackgroundColour(no, 1, *wxLIGHT_GREY);
}
#endif
exSampleFrame::exSampleFrame(const wxString& title)
: exManagedFrame(NULL, wxID_ANY, title)
, m_FlagsSTC(0)
{
SetIcon(appl_xpm);
exMenu* menuFile = new exMenu;
menuFile->Append(wxID_OPEN);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(ID_PRINT_SPECIAL, _("Print Test")); // test to print without a window
menuFile->AppendSeparator();
menuFile->Append(ID_LOCALE_SHOW_DIR, _("Show Locale Dir"));
menuFile->AppendSeparator();
menuFile->Append(ID_STATISTICS_SHOW, _("Show Statistics"));
menuFile->Append(ID_STATISTICS_CLEAR, _("Clear Statistics"));
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
exMenu* menuConfig = new exMenu;
menuConfig->Append(ID_CONFIG_DLG, exEllipsed(_("Config Dialog")));
menuConfig->Append(ID_CONFIG_DLG_READONLY, exEllipsed(_("Config Dialog Readonly")));
exMenu* menuSTC = new exMenu;
menuSTC->Append(ID_STC_FLAGS, exEllipsed(_("Open Flag")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_CONFIG_DLG, exEllipsed(_("Config Dialog")));
menuSTC->Append(ID_STC_GOTO, exEllipsed(_("Goto Dialog")));
menuSTC->Append(ID_STC_LEXER, exEllipsed(_("Lexer Dialog")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_SPLIT, _("Split"));
menuSTC->AppendSeparator();
menuSTC->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuSTC->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuSTC->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback"));
exMenu* menuHelp = new exMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuSTC, _("&STC"));
menubar->Append(menuConfig, _("&Config"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
m_Notebook = new exNotebook(this, NULL);
#if wxUSE_GRID
m_Grid = new exGrid(m_Notebook);
#endif
m_ListView = new exListView(m_Notebook);
m_STC = new exSTC(this);
m_STCShell = new exSTCShell(this, ">", wxTextFile::GetEOL(), true, 10);
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true).Name("exSTC"));
GetManager().AddPane(m_STCShell, wxAuiPaneInfo().Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_Notebook, wxAuiPaneInfo().Left().MinSize(wxSize(250, 250)));
GetManager().Update();
assert(exApp::GetLexers());
exSTC* st = new exSTC(this, exApp::GetLexers()->GetFileName().GetFullPath());
m_Notebook->AddPage(st, exApp::GetLexers()->GetFileName().GetFullName());
m_Notebook->AddPage(m_ListView, "exListView");
#if wxUSE_GRID
m_Notebook->AddPage(m_Grid, "exGrid");
m_Grid->CreateGrid(0, 0);
m_Grid->AppendCols(2);
exSampleDir dir(wxGetCwd(), "appl.*", m_Grid);
dir.FindFiles();
m_Grid->AutoSizeColumns();
#endif
m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON);
m_ListView->InsertColumn("String", exColumn::COL_STRING);
m_ListView->InsertColumn("Number", exColumn::COL_INT);
m_ListView->InsertColumn("Float", exColumn::COL_FLOAT);
m_ListView->InsertColumn("Date", exColumn::COL_DATE);
const int items = 50;
for (int i = 0; i < items; i++)
{
exListItem item(m_ListView, wxString::Format("item%d", i));
item.Insert();
item.SetColumnText(1, wxString::Format("%d", i));
item.SetColumnText(2, wxString::Format("%f", (float)i / 2.0));
item.SetColumnText(3, wxDateTime::Now().Format());
// Set some images.
if (i == 0) item.SetImage(wxART_CDROM);
else if (i == 1) item.SetImage(wxART_REMOVABLE);
else if (i == 2) item.SetImage(wxART_FOLDER);
else if (i == 3) item.SetImage(wxART_FOLDER_OPEN);
else if (i == 4) item.SetImage(wxART_GO_DIR_UP);
else if (i == 5) item.SetImage(wxART_EXECUTABLE_FILE);
else if (i == 6) item.SetImage(wxART_NORMAL_FILE);
else item.SetImage(wxART_TICK_MARK);
}
std::vector<exPane> panes;
panes.push_back(exPane("PaneText", -3));
panes.push_back(exPane("PaneFileType", 50, _("File type")));
panes.push_back(exPane("PaneCells", 60, _("Cells")));
panes.push_back(exPane("PaneItems", 60, _("Items")));
panes.push_back(exPane("PaneLines", 100, _("Lines")));
panes.push_back(exPane("PaneLexer", 60, _("Lexer")));
SetupStatusBar(panes);
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddTool(wxID_EXIT);
m_ToolBar->Realize();
}
void exSampleFrame::ConfigDialogApplied(wxWindowID id)
{
m_STC->ConfigGet();
m_STCShell->ConfigGet();
}
void exSampleFrame::OnCommand(wxCommandEvent& event)
{
m_Statistics.Inc(wxString::Format("%d", event.GetId()));
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(EX_LIB_VERSION);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
{
wxFileDialog dlg(this,
_("Select File"),
wxEmptyString,
wxEmptyString,
wxFileSelectorDefaultWildcardStr,
wxFD_OPEN | wxFD_CHANGE_DIR);
if (m_STC->AskFileOpen(dlg) == wxID_CANCEL) return;
wxStopWatch sw;
m_STC->Open(dlg.GetPath(), 0, wxEmptyString, m_FlagsSTC);
const long stop = sw.Time();
StatusText(wxString::Format("exSTC::Open:%ld milliseconds, %d bytes", stop, m_STC->GetTextLength()));
}
break;
case wxID_PREVIEW: m_ListView->PrintPreview(); break;
case wxID_PRINT: m_ListView->Print(); break;
case wxID_PRINT_SETUP: exApp::GetPrinter()->PageSetup(); break;
case wxID_SAVE:
m_STC->FileSave();
if (m_STC->GetFileName().GetFullPath() == exApp::GetLexers()->GetFileName().GetFullPath())
{
if (exApp::GetLexers()->Read())
{
wxLogMessage("file contains: %d lexers", exApp::GetLexers()->Get().size());
m_STC->SetLexer();
// As the lexer might have changed, update status bar field as well.
m_STC->UpdateStatusBar("PaneLexer");
}
}
break;
case ID_CONFIG_DLG:
{
std::vector<exConfigItem> v;
for (size_t h = 1; h <= 25; h++)
{
v.push_back(exConfigItem(wxString::Format(_("check%d"), h), CONFIG_CHECKBOX, "Checkboxes"));
}
for (size_t i = 1; i <= 25; i++)
{
v.push_back(exConfigItem(wxString::Format(_("colour%d"), i), CONFIG_COLOUR, "Colours"));
}
for (size_t j = 1; j <= 10; j++)
{
v.push_back(exConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT, "Integers", true));
}
for (size_t k = 1; k <= 10; k++)
{
v.push_back(exConfigItem(wxString::Format(_("spin%d"), k), 1, k, wxString("Spin controls")));
}
for (size_t l = 1; l <= 10; l++)
{
v.push_back(exConfigItem(wxString::Format(_("string%d"), l), CONFIG_STRING, "Strings"));
}
for (size_t m = 1; m <= 10; m++)
{
v.push_back(exConfigItem(wxString::Format(_("combobox%d"), m), CONFIG_COMBOBOX, "Comboboxes"));
}
v.push_back(exConfigItem(_("dirpicker"), CONFIG_DIRPICKERCTRL, "Pickers"));
v.push_back(exConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL, "Pickers"));
exConfigDialog* dlg = new exConfigDialog(
this,
v,
_("Config Dialog"),
wxEmptyString,
5,
6,
wxAPPLY | wxCANCEL,
wxID_ANY,
wxDefaultPosition,
wxSize(400,300));
dlg->Show();
// Dialog is not placed nicely.
//GetManager().GetPane("NOTEBOOK"));
//GetManager().Update();
}
break;
case ID_CONFIG_DLG_READONLY:
{
std::vector<exConfigItem> v;
v.push_back(exConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL));
for (size_t j = 1; j <= 10; j++)
{
v.push_back(exConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT));
}
exConfigDialog* dlg = new exConfigDialog(
this,
v,
_("Config Dialog Readonly"),
wxEmptyString,
2,
2,
wxCANCEL);
dlg->Show();
}
break;
case ID_PRINT_SPECIAL:
{
wxHtmlEasyPrinting* print = exApp::GetPrinter();
wxPrintDialogData printDialogData(*print->GetPrintData());
wxPrinter printer(&printDialogData);
wxHtmlPrintout printout;
printout.SetHtmlFile("appl.xpm");
printer.Print(this, &printout, false);
/*
// This is the simplest, but
// asks for printing always (in lib source).
print->PrintFile("mondrian.xpm");
*/
/*
// This could be made better, immediately hide etc.
exSTC* stc = new exSTC(this, "mondrian.xpm");
stc->Hide();
stc->Print(false);// however stc->Print(false) does not print
delete stc;
*/
}
break;
case ID_LOCALE_SHOW_DIR:
wxLogMessage(exApp::GetCatalogDir());
break;
case ID_SHELL_COMMAND:
m_STCShell->AppendText("\nHello '" + event.GetString() + "' from the shell"),
m_STCShell->Prompt();
break;
case ID_STATISTICS_SHOW:
m_Notebook->AddPage(m_Statistics.Show(m_Notebook), "Statistics");
break;
case ID_STATISTICS_CLEAR:
m_Statistics.Clear();
break;
case ID_STC_CONFIG_DLG:
exSTC::ConfigDialog(
_("Editor Options"),
exSTC::STC_CONFIG_MODELESS | exSTC::STC_CONFIG_WITH_APPLY);
break;
case ID_STC_FLAGS:
{
long value = wxGetNumberFromUser(
"Input:",
wxEmptyString,
"STC Open Flag",
m_FlagsSTC,
0,
2 * exSTC::STC_OPEN_FROM_URL);
if (value != -1)
{
m_FlagsSTC = value;
}
}
break;
case ID_STC_GOTO: m_STC->GotoDialog(); break;
case ID_STC_LEXER: m_STC->LexerDialog(); break;
case ID_STC_SPLIT:
{
exSTC* stc = new exSTC(*m_STC);
m_Notebook->AddPage(
stc,
wxString::Format("stc%d", stc->GetId()),
m_STC->GetFileName().GetFullName());
stc->SetDocPointer(m_STC->GetDocPointer());
}
break;
}
}
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/javanano/javanano_params.h>
#include <google/protobuf/compiler/javanano/javanano_generator.h>
#include <google/protobuf/compiler/javanano/javanano_file.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
namespace {
string TrimString(const string& s) {
string::size_type start = s.find_first_not_of(" \n\r\t");
if (start == string::npos) {
return "";
}
string::size_type end = s.find_last_not_of(" \n\r\t") + 1;
return s.substr(start, end - start);
}
} // namespace
void UpdateParamsRecursively(Params& params,
const FileDescriptor* file) {
// Add any parameters for this file
if (file->options().has_java_outer_classname()) {
params.set_java_outer_classname(
file->name(), file->options().java_outer_classname());
}
if (file->options().has_java_package()) {
params.set_java_package(
file->name(), file->options().java_package());
}
if (file->options().has_java_multiple_files()) {
params.set_java_multiple_files(
file->name(), file->options().java_multiple_files());
}
// Loop through all dependent files recursively
// adding dep
for (int i = 0; i < file->dependency_count(); i++) {
UpdateParamsRecursively(params, file->dependency(i));
}
}
JavaNanoGenerator::JavaNanoGenerator() {}
JavaNanoGenerator::~JavaNanoGenerator() {}
bool JavaNanoGenerator::Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* output_directory,
string* error) const {
vector<pair<string, string> > options;
ParseGeneratorParameter(parameter, &options);
// -----------------------------------------------------------------
// parse generator options
// Name a file where we will write a list of generated file names, one
// per line.
string output_list_file;
Params params(file->name());
// Update per file params
UpdateParamsRecursively(params, file);
// Replace any existing options with ones from command line
for (int i = 0; i < options.size(); i++) {
string option_name = TrimString(options[i].first);
string option_value = TrimString(options[i].second);
if (option_name == "output_list_file") {
output_list_file = option_value;
} else if (option_name == "java_package") {
vector<string> parts;
SplitStringUsing(option_value, "|", &parts);
if (parts.size() != 2) {
*error = "Bad java_package, expecting filename|PackageName found '"
+ option_value + "'";
return false;
}
params.set_java_package(parts[0], parts[1]);
} else if (option_name == "java_outer_classname") {
vector<string> parts;
SplitStringUsing(option_value, "|", &parts);
if (parts.size() != 2) {
*error = "Bad java_outer_classname, "
"expecting filename|ClassName found '"
+ option_value + "'";
return false;
}
params.set_java_outer_classname(parts[0], parts[1]);
} else if (option_name == "store_unknown_fields") {
params.set_store_unknown_fields(option_value == "true");
} else if (option_name == "java_multiple_files") {
params.set_override_java_multiple_files(option_value == "true");
} else if (option_name == "java_nano_generate_has") {
params.set_generate_has(option_value == "true");
} else if (option_name == "enum_style") {
params.set_java_enum_style(option_value == "java");
} else if (option_name == "optional_field_style") {
params.set_optional_field_accessors(option_value == "accessors");
params.set_use_reference_types_for_primitives(option_value == "reftypes"
|| option_value == "reftypes_compat_mode");
params.set_reftypes_primitive_enums(
option_value == "reftypes_compat_mode");
if (option_value == "reftypes_compat_mode") {
params.set_generate_clear(false);
}
} else if (option_name == "generate_equals") {
params.set_generate_equals(option_value == "true");
} else if (option_name == "ignore_services") {
params.set_ignore_services(option_value == "true");
} else if (option_name == "parcelable_messages") {
params.set_parcelable_messages(option_value == "true");
} else if (option_name == "generate_clone") {
params.set_generate_clone(option_value == "true");
} else if (option_name == "generate_intdefs") {
params.set_generate_intdefs(option_value == "true");
} else {
*error = "Ignore unknown javanano generator option: " + option_name;
}
}
// Check illegal parameter combinations
// Note: the enum-like optional_field_style generator param ensures
// that we can never have illegal combinations of field styles
// (e.g. reftypes and accessors can't be on at the same time).
if (params.generate_has()
&& (params.optional_field_accessors()
|| params.use_reference_types_for_primitives())) {
error->assign("java_nano_generate_has=true cannot be used in conjunction"
" with optional_field_style=accessors or optional_field_style=reftypes");
return false;
}
// -----------------------------------------------------------------
FileGenerator file_generator(file, params);
if (!file_generator.Validate(error)) {
return false;
}
string package_dir =
StringReplace(file_generator.java_package(), ".", "/", true);
if (!package_dir.empty()) package_dir += "/";
vector<string> all_files;
if (IsOuterClassNeeded(params, file)) {
string java_filename = package_dir;
java_filename += file_generator.classname();
java_filename += ".java";
all_files.push_back(java_filename);
// Generate main java file.
scoped_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(java_filename));
io::Printer printer(output.get(), '$');
file_generator.Generate(&printer);
}
// Generate sibling files.
file_generator.GenerateSiblings(package_dir, output_directory, &all_files);
// Generate output list if requested.
if (!output_list_file.empty()) {
// Generate output list. This is just a simple text file placed in a
// deterministic location which lists the .java files being generated.
scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
output_directory->Open(output_list_file));
io::Printer srclist_printer(srclist_raw_output.get(), '$');
for (int i = 0; i < all_files.size(); i++) {
srclist_printer.Print("$filename$\n", "filename", all_files[i]);
}
}
return true;
}
} // namespace java
} // namespace compiler
} // namespace protobuf
} // namespace google
<commit_msg>Expose generate_clear as an option.<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/javanano/javanano_params.h>
#include <google/protobuf/compiler/javanano/javanano_generator.h>
#include <google/protobuf/compiler/javanano/javanano_file.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
namespace {
string TrimString(const string& s) {
string::size_type start = s.find_first_not_of(" \n\r\t");
if (start == string::npos) {
return "";
}
string::size_type end = s.find_last_not_of(" \n\r\t") + 1;
return s.substr(start, end - start);
}
} // namespace
void UpdateParamsRecursively(Params& params,
const FileDescriptor* file) {
// Add any parameters for this file
if (file->options().has_java_outer_classname()) {
params.set_java_outer_classname(
file->name(), file->options().java_outer_classname());
}
if (file->options().has_java_package()) {
params.set_java_package(
file->name(), file->options().java_package());
}
if (file->options().has_java_multiple_files()) {
params.set_java_multiple_files(
file->name(), file->options().java_multiple_files());
}
// Loop through all dependent files recursively
// adding dep
for (int i = 0; i < file->dependency_count(); i++) {
UpdateParamsRecursively(params, file->dependency(i));
}
}
JavaNanoGenerator::JavaNanoGenerator() {}
JavaNanoGenerator::~JavaNanoGenerator() {}
bool JavaNanoGenerator::Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* output_directory,
string* error) const {
vector<pair<string, string> > options;
ParseGeneratorParameter(parameter, &options);
// -----------------------------------------------------------------
// parse generator options
// Name a file where we will write a list of generated file names, one
// per line.
string output_list_file;
Params params(file->name());
// Update per file params
UpdateParamsRecursively(params, file);
// Replace any existing options with ones from command line
for (int i = 0; i < options.size(); i++) {
string option_name = TrimString(options[i].first);
string option_value = TrimString(options[i].second);
if (option_name == "output_list_file") {
output_list_file = option_value;
} else if (option_name == "java_package") {
vector<string> parts;
SplitStringUsing(option_value, "|", &parts);
if (parts.size() != 2) {
*error = "Bad java_package, expecting filename|PackageName found '"
+ option_value + "'";
return false;
}
params.set_java_package(parts[0], parts[1]);
} else if (option_name == "java_outer_classname") {
vector<string> parts;
SplitStringUsing(option_value, "|", &parts);
if (parts.size() != 2) {
*error = "Bad java_outer_classname, "
"expecting filename|ClassName found '"
+ option_value + "'";
return false;
}
params.set_java_outer_classname(parts[0], parts[1]);
} else if (option_name == "store_unknown_fields") {
params.set_store_unknown_fields(option_value == "true");
} else if (option_name == "java_multiple_files") {
params.set_override_java_multiple_files(option_value == "true");
} else if (option_name == "java_nano_generate_has") {
params.set_generate_has(option_value == "true");
} else if (option_name == "enum_style") {
params.set_java_enum_style(option_value == "java");
} else if (option_name == "optional_field_style") {
params.set_optional_field_accessors(option_value == "accessors");
params.set_use_reference_types_for_primitives(option_value == "reftypes"
|| option_value == "reftypes_compat_mode");
params.set_reftypes_primitive_enums(
option_value == "reftypes_compat_mode");
if (option_value == "reftypes_compat_mode") {
params.set_generate_clear(false);
}
} else if (option_name == "generate_equals") {
params.set_generate_equals(option_value == "true");
} else if (option_name == "ignore_services") {
params.set_ignore_services(option_value == "true");
} else if (option_name == "parcelable_messages") {
params.set_parcelable_messages(option_value == "true");
} else if (option_name == "generate_clone") {
params.set_generate_clone(option_value == "true");
} else if (option_name == "generate_intdefs") {
params.set_generate_intdefs(option_value == "true");
} else if (option_name == "generate_clear") {
params.set_generate_clear(option_value == "true");
} else {
*error = "Ignore unknown javanano generator option: " + option_name;
}
}
// Check illegal parameter combinations
// Note: the enum-like optional_field_style generator param ensures
// that we can never have illegal combinations of field styles
// (e.g. reftypes and accessors can't be on at the same time).
if (params.generate_has()
&& (params.optional_field_accessors()
|| params.use_reference_types_for_primitives())) {
error->assign("java_nano_generate_has=true cannot be used in conjunction"
" with optional_field_style=accessors or optional_field_style=reftypes");
return false;
}
// -----------------------------------------------------------------
FileGenerator file_generator(file, params);
if (!file_generator.Validate(error)) {
return false;
}
string package_dir =
StringReplace(file_generator.java_package(), ".", "/", true);
if (!package_dir.empty()) package_dir += "/";
vector<string> all_files;
if (IsOuterClassNeeded(params, file)) {
string java_filename = package_dir;
java_filename += file_generator.classname();
java_filename += ".java";
all_files.push_back(java_filename);
// Generate main java file.
scoped_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(java_filename));
io::Printer printer(output.get(), '$');
file_generator.Generate(&printer);
}
// Generate sibling files.
file_generator.GenerateSiblings(package_dir, output_directory, &all_files);
// Generate output list if requested.
if (!output_list_file.empty()) {
// Generate output list. This is just a simple text file placed in a
// deterministic location which lists the .java files being generated.
scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
output_directory->Open(output_list_file));
io::Printer srclist_printer(srclist_raw_output.get(), '$');
for (int i = 0; i < all_files.size(); i++) {
srclist_printer.Print("$filename$\n", "filename", all_files[i]);
}
}
return true;
}
} // namespace java
} // namespace compiler
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>/// \file
/// \ingroup graphics
/// Show how to shade an area between two graphs
///
/// \macro_image
/// \macro_code
///
/// \author Rene Brun
void graphShade() {
TCanvas *c1 = new TCanvas("c1",
"A Simple Graph Example",200,10,700,500);
c1->SetGrid();
c1->DrawFrame(0,0,2.2,12);
const Int_t n = 20;
Double_t x[n], y[n],ymin[n], ymax[n];
Int_t i;
for (i=0;i<n;i++) {
x[i] = 0.1+i*0.1;
ymax[i] = 10*sin(x[i]+0.2);
ymin[i] = 8*sin(x[i]+0.1);
y[i] = 9*sin(x[i]+0.15);
}
TGraph *grmin = new TGraph(n,x,ymin);
TGraph *grmax = new TGraph(n,x,ymax);
TGraph *gr = new TGraph(n,x,y);
TGraph *grshade = new TGraph(2*n);
for (i=0;i<n;i++) {
grshade->SetPoint(i,x[i],ymax[i]);
grshade->SetPoint(n+i,x[n-i-1],ymin[n-i-1]);
}
grshade->SetFillStyle(3013);
grshade->SetFillColor(16);
grshade->Draw("f");
grmin->Draw("l");
grmax->Draw("l");
gr->SetLineWidth(4);
gr->SetMarkerColor(4);
gr->SetMarkerStyle(21);
gr->Draw("CP");
}
<commit_msg>Move this Macro to "graphs"<commit_after><|endoftext|> |
<commit_before>// Author: Enric Tejedor CERN 10/2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// clang-format off
/** \class ROOT::RDF::RCsvDS
\ingroup dataframe
\brief RDataFrame data source class for reading CSV files.
The RCsvDS class implements a CSV file reader for RDataFrame.
A RDataFrame that reads from a CSV file can be constructed using the factory method
ROOT::RDF::MakeCsvDataFrame, which accepts three parameters:
1. Path to the CSV file.
2. Boolean that specifies whether the first row of the CSV file contains headers or
not (optional, default `true`). If `false`, header names will be automatically generated as Col0, Col1, ..., ColN.
3. Delimiter (optional, default ',').
The types of the columns in the CSV file are automatically inferred. The supported
types are:
- Integer: stored as a 64-bit long long int.
- Floating point number: stored with double precision.
- Boolean: matches the literals `true` and `false`.
- String: stored as an std::string, matches anything that does not fall into any of the
previous types.
These are some formatting rules expected by the RCsvDS implementation:
- All records must have the same number of fields, in the same order.
- Any field may be quoted.
~~~
"1997","Ford","E350"
~~~
- Fields with embedded delimiters (e.g. comma) must be quoted.
~~~
1997,Ford,E350,"Super, luxurious truck"
~~~
- Fields with double-quote characters must be quoted, and each of the embedded
double-quote characters must be represented by a pair of double-quote characters.
~~~
1997,Ford,E350,"Super, ""luxurious"" truck"
~~~
- Fields with embedded line breaks are not supported, even when quoted.
~~~
1997,Ford,E350,"Go get one now
they are going fast"
~~~
- Spaces are considered part of a field and are not ignored.
~~~
1997, Ford , E350
not same as
1997,Ford,E350
but same as
1997, "Ford" , E350
~~~
- If a header row is provided, it must contain column names for each of the fields.
~~~
Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar
~~~
The current implementation of RCsvDS reads the entire CSV file content into memory before
RDataFrame starts processing it. Therefore, before creating a CSV RDataFrame, it is
important to check both how much memory is available and the size of the CSV file.
*/
// clang-format on
#include <ROOT/RDFUtils.hxx>
#include <ROOT/TSeq.hxx>
#include <ROOT/RCsvDS.hxx>
#include <ROOT/RMakeUnique.hxx>
#include <TError.h>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
namespace ROOT {
namespace RDF {
std::string RCsvDS::AsString()
{
return "CSV data source";
}
// Regular expressions for type inference
TRegexp RCsvDS::intRegex("^[-+]?[0-9]+$");
TRegexp RCsvDS::doubleRegex1("^[-+]?[0-9]+\\.[0-9]*$");
TRegexp RCsvDS::doubleRegex2("^[-+]?[0-9]*\\.[0-9]+$");
TRegexp RCsvDS::trueRegex("^true$");
TRegexp RCsvDS::falseRegex("^false$");
const std::map<RCsvDS::ColType_t, std::string>
RCsvDS::fgColTypeMap({{'b', "bool"}, {'d', "double"}, {'l', "Long64_t"}, {'s', "std::string"}});
void RCsvDS::FillHeaders(const std::string &line)
{
auto columns = ParseColumns(line);
for (auto &col : columns) {
fHeaders.emplace_back(col);
}
}
void RCsvDS::FillRecord(const std::string &line, Record_t &record)
{
std::istringstream lineStream(line);
auto i = 0U;
auto columns = ParseColumns(line);
for (auto &col : columns) {
auto colType = fColTypes[fHeaders[i]];
switch (colType) {
case 'd': {
record.emplace_back(new double(std::stod(col)));
break;
}
case 'l': {
record.emplace_back(new Long64_t(std::stoll(col)));
break;
}
case 'b': {
auto b = new bool();
record.emplace_back(b);
std::istringstream is(col);
is >> std::boolalpha >> *b;
break;
}
case 's': {
record.emplace_back(new std::string(col));
break;
}
}
++i;
}
}
void RCsvDS::GenerateHeaders(size_t size)
{
for (size_t i = 0; i < size; ++i) {
fHeaders.push_back("Col" + std::to_string(i));
}
}
std::vector<void *> RCsvDS::GetColumnReadersImpl(std::string_view colName, const std::type_info &ti)
{
const auto colType = GetType(colName);
if ((colType == 'd' && typeid(double) != ti) || (colType == 'l' && typeid(Long64_t) != ti) ||
(colType == 's' && typeid(std::string) != ti) || (colType == 'b' && typeid(bool) != ti)) {
std::string err = "The type selected for column \"";
err += colName;
err += "\" does not correspond to column type, which is ";
err += fgColTypeMap.at(colType);
throw std::runtime_error(err);
}
const auto &colNames = GetColumnNames();
const auto index = std::distance(colNames.begin(), std::find(colNames.begin(), colNames.end(), colName));
std::vector<void *> ret(fNSlots);
for (auto slot : ROOT::TSeqU(fNSlots)) {
auto &val = fColAddresses[index][slot];
if (ti == typeid(double)) {
val = &fDoubleEvtValues[index][slot];
} else if (ti == typeid(Long64_t)) {
val = &fLong64EvtValues[index][slot];
} else if (ti == typeid(std::string)) {
val = &fStringEvtValues[index][slot];
} else {
val = &fBoolEvtValues[index][slot];
}
ret[slot] = &val;
}
return ret;
}
void RCsvDS::InferColTypes(std::vector<std::string> &columns)
{
auto i = 0U;
for (auto &col : columns) {
InferType(col, i);
++i;
}
}
void RCsvDS::InferType(const std::string &col, unsigned int idxCol)
{
ColType_t type;
int dummy;
if (intRegex.Index(col, &dummy) != -1) {
type = 'l'; // Long64_t
} else if (doubleRegex1.Index(col, &dummy) != -1 || doubleRegex2.Index(col, &dummy) != -1) {
type = 'd'; // double
} else if (trueRegex.Index(col, &dummy) != -1 || falseRegex.Index(col, &dummy) != -1) {
type = 'b'; // bool
} else { // everything else is a string
type = 's'; // std::string
}
// TODO: Date
fColTypes[fHeaders[idxCol]] = type;
fColTypesList.push_back(type);
}
std::vector<std::string> RCsvDS::ParseColumns(const std::string &line)
{
std::vector<std::string> columns;
for (size_t i = 0; i < line.size(); ++i) {
i = ParseValue(line, columns, i);
}
return columns;
}
size_t RCsvDS::ParseValue(const std::string &line, std::vector<std::string> &columns, size_t i)
{
std::stringstream val;
bool quoted = false;
for (; i < line.size(); ++i) {
if (line[i] == fDelimiter && !quoted) {
break;
} else if (line[i] == '"') {
// Keep just one quote for escaped quotes, none for the normal quotes
if (line[i + 1] != '"') {
quoted = !quoted;
} else {
val << line[++i];
}
} else {
val << line[i];
}
}
columns.emplace_back(val.str());
return i;
}
////////////////////////////////////////////////////////////////////////
/// Constructor to create a CSV RDataSource for RDataFrame.
/// \param[in] fileName Path of the CSV file.
/// \param[in] readHeaders `true` if the CSV file contains headers as first row, `false` otherwise
/// (default `true`).
/// \param[in] delimiter Delimiter character (default ',').
RCsvDS::RCsvDS(std::string_view fileName, bool readHeaders, char delimiter, Long64_t linesChunkSize) // TODO: Let users specify types?
: fReadHeaders(readHeaders),
fStream(std::string(fileName)),
fDelimiter(delimiter),
fLinesChunkSize(linesChunkSize)
{
std::string line;
// Read the headers if present
if (fReadHeaders) {
if (std::getline(fStream, line)) {
FillHeaders(line);
} else {
throw std::runtime_error("Error reading headers of CSV file ");
}
}
fDataPos = fStream.tellg();
if (std::getline(fStream, line)) {
auto columns = ParseColumns(line);
// Generate headers if not present
if (!fReadHeaders) {
GenerateHeaders(columns.size());
}
// Infer types of columns with first record
InferColTypes(columns);
// rewind one line
fStream.seekg(fDataPos);
}
}
void RCsvDS::FreeRecords()
{
for (auto &record : fRecords) {
for (size_t i = 0; i < record.size(); ++i) {
void *p = record[i];
const auto colType = fColTypes[fHeaders[i]];
switch (colType) {
case 'd': {
delete static_cast<double *>(p);
break;
}
case 'l': {
delete static_cast<Long64_t *>(p);
break;
}
case 'b': {
delete static_cast<bool *>(p);
break;
}
case 's': {
delete static_cast<std::string *>(p);
break;
}
}
}
}
fRecords.clear();
}
////////////////////////////////////////////////////////////////////////
/// Destructor.
RCsvDS::~RCsvDS()
{
FreeRecords();
}
void RCsvDS::Finalise()
{
fStream.clear();
fStream.seekg(fDataPos);
fProcessedLines = 0ULL;
fEntryRangesRequested = 0ULL;
FreeRecords();
}
const std::vector<std::string> &RCsvDS::GetColumnNames() const
{
return fHeaders;
}
std::vector<std::pair<ULong64_t, ULong64_t>> RCsvDS::GetEntryRanges()
{
// Read records and store them in memory
auto linesToRead = fLinesChunkSize;
FreeRecords();
std::string line;
while ((-1LL == fLinesChunkSize || 0 != linesToRead--) && std::getline(fStream, line)) {
fRecords.emplace_back();
FillRecord(line, fRecords.back());
}
std::vector<std::pair<ULong64_t, ULong64_t>> entryRanges;
const auto nRecords = fRecords.size();
if (0 == nRecords)
return entryRanges;
const auto chunkSize = nRecords / fNSlots;
const auto remainder = 1U == fNSlots ? 0 : nRecords % fNSlots;
auto start = 0ULL == fEntryRangesRequested ? 0ULL : fProcessedLines;
auto end = start;
for (auto i : ROOT::TSeqU(fNSlots)) {
start = end;
end += chunkSize;
entryRanges.emplace_back(start, end);
(void)i;
}
entryRanges.back().second += remainder;
fProcessedLines += nRecords;
fEntryRangesRequested++;
return entryRanges;
}
RCsvDS::ColType_t RCsvDS::GetType(std::string_view colName) const
{
if (!HasColumn(colName)) {
std::string msg = "The dataset does not have column ";
msg += colName;
throw std::runtime_error(msg);
}
return fColTypes.at(colName.data());
}
std::string RCsvDS::GetTypeName(std::string_view colName) const
{
return fgColTypeMap.at(GetType(colName));
}
bool RCsvDS::HasColumn(std::string_view colName) const
{
return fHeaders.end() != std::find(fHeaders.begin(), fHeaders.end(), colName);
}
bool RCsvDS::SetEntry(unsigned int slot, ULong64_t entry)
{
// Here we need to normalise the entry to the number of lines we already processed.
const auto offset = (fEntryRangesRequested - 1) * fLinesChunkSize;
const auto recordPos = entry - offset;
int colIndex = 0;
for (auto &colType : fColTypesList) {
auto dataPtr = fRecords[recordPos][colIndex];
switch (colType) {
case 'd': {
fDoubleEvtValues[colIndex][slot] = *static_cast<double *>(dataPtr);
break;
}
case 'l': {
fLong64EvtValues[colIndex][slot] = *static_cast<Long64_t *>(dataPtr);
break;
}
case 'b': {
fBoolEvtValues[colIndex][slot] = *static_cast<bool *>(dataPtr);
break;
}
case 's': {
fStringEvtValues[colIndex][slot] = *static_cast<std::string *>(dataPtr);
break;
}
}
colIndex++;
}
return true;
}
void RCsvDS::SetNSlots(unsigned int nSlots)
{
R__ASSERT(0U == fNSlots && "Setting the number of slots even if the number of slots is different from zero.");
fNSlots = nSlots;
const auto nColumns = fHeaders.size();
// Initialise the entire set of addresses
fColAddresses.resize(nColumns, std::vector<void *>(fNSlots, nullptr));
// Initialize the per event data holders
fDoubleEvtValues.resize(nColumns, std::vector<double>(fNSlots));
fLong64EvtValues.resize(nColumns, std::vector<Long64_t>(fNSlots));
fStringEvtValues.resize(nColumns, std::vector<std::string>(fNSlots));
fBoolEvtValues.resize(nColumns, std::deque<bool>(fNSlots));
}
RDataFrame MakeCsvDataFrame(std::string_view fileName, bool readHeaders, char delimiter, Long64_t linesChunkSize)
{
ROOT::RDataFrame tdf(std::make_unique<RCsvDS>(fileName, readHeaders, delimiter, linesChunkSize));
return tdf;
}
} // ns RDF
} // ns ROOT
<commit_msg>[RDF] Make exception clear again<commit_after>// Author: Enric Tejedor CERN 10/2017
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// clang-format off
/** \class ROOT::RDF::RCsvDS
\ingroup dataframe
\brief RDataFrame data source class for reading CSV files.
The RCsvDS class implements a CSV file reader for RDataFrame.
A RDataFrame that reads from a CSV file can be constructed using the factory method
ROOT::RDF::MakeCsvDataFrame, which accepts three parameters:
1. Path to the CSV file.
2. Boolean that specifies whether the first row of the CSV file contains headers or
not (optional, default `true`). If `false`, header names will be automatically generated as Col0, Col1, ..., ColN.
3. Delimiter (optional, default ',').
The types of the columns in the CSV file are automatically inferred. The supported
types are:
- Integer: stored as a 64-bit long long int.
- Floating point number: stored with double precision.
- Boolean: matches the literals `true` and `false`.
- String: stored as an std::string, matches anything that does not fall into any of the
previous types.
These are some formatting rules expected by the RCsvDS implementation:
- All records must have the same number of fields, in the same order.
- Any field may be quoted.
~~~
"1997","Ford","E350"
~~~
- Fields with embedded delimiters (e.g. comma) must be quoted.
~~~
1997,Ford,E350,"Super, luxurious truck"
~~~
- Fields with double-quote characters must be quoted, and each of the embedded
double-quote characters must be represented by a pair of double-quote characters.
~~~
1997,Ford,E350,"Super, ""luxurious"" truck"
~~~
- Fields with embedded line breaks are not supported, even when quoted.
~~~
1997,Ford,E350,"Go get one now
they are going fast"
~~~
- Spaces are considered part of a field and are not ignored.
~~~
1997, Ford , E350
not same as
1997,Ford,E350
but same as
1997, "Ford" , E350
~~~
- If a header row is provided, it must contain column names for each of the fields.
~~~
Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar
~~~
The current implementation of RCsvDS reads the entire CSV file content into memory before
RDataFrame starts processing it. Therefore, before creating a CSV RDataFrame, it is
important to check both how much memory is available and the size of the CSV file.
*/
// clang-format on
#include <ROOT/RDFUtils.hxx>
#include <ROOT/TSeq.hxx>
#include <ROOT/RCsvDS.hxx>
#include <ROOT/RMakeUnique.hxx>
#include <TError.h>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
namespace ROOT {
namespace RDF {
std::string RCsvDS::AsString()
{
return "CSV data source";
}
// Regular expressions for type inference
TRegexp RCsvDS::intRegex("^[-+]?[0-9]+$");
TRegexp RCsvDS::doubleRegex1("^[-+]?[0-9]+\\.[0-9]*$");
TRegexp RCsvDS::doubleRegex2("^[-+]?[0-9]*\\.[0-9]+$");
TRegexp RCsvDS::trueRegex("^true$");
TRegexp RCsvDS::falseRegex("^false$");
const std::map<RCsvDS::ColType_t, std::string>
RCsvDS::fgColTypeMap({{'b', "bool"}, {'d', "double"}, {'l', "Long64_t"}, {'s', "std::string"}});
void RCsvDS::FillHeaders(const std::string &line)
{
auto columns = ParseColumns(line);
for (auto &col : columns) {
fHeaders.emplace_back(col);
}
}
void RCsvDS::FillRecord(const std::string &line, Record_t &record)
{
std::istringstream lineStream(line);
auto i = 0U;
auto columns = ParseColumns(line);
for (auto &col : columns) {
auto colType = fColTypes[fHeaders[i]];
switch (colType) {
case 'd': {
record.emplace_back(new double(std::stod(col)));
break;
}
case 'l': {
record.emplace_back(new Long64_t(std::stoll(col)));
break;
}
case 'b': {
auto b = new bool();
record.emplace_back(b);
std::istringstream is(col);
is >> std::boolalpha >> *b;
break;
}
case 's': {
record.emplace_back(new std::string(col));
break;
}
}
++i;
}
}
void RCsvDS::GenerateHeaders(size_t size)
{
for (size_t i = 0; i < size; ++i) {
fHeaders.push_back("Col" + std::to_string(i));
}
}
std::vector<void *> RCsvDS::GetColumnReadersImpl(std::string_view colName, const std::type_info &ti)
{
const auto colType = GetType(colName);
if ((colType == 'd' && typeid(double) != ti) || (colType == 'l' && typeid(Long64_t) != ti) ||
(colType == 's' && typeid(std::string) != ti) || (colType == 'b' && typeid(bool) != ti)) {
std::string err = "The type selected for column \"";
err += colName;
err += "\" does not correspond to column type, which is ";
err += fgColTypeMap.at(colType);
throw std::runtime_error(err);
}
const auto &colNames = GetColumnNames();
const auto index = std::distance(colNames.begin(), std::find(colNames.begin(), colNames.end(), colName));
std::vector<void *> ret(fNSlots);
for (auto slot : ROOT::TSeqU(fNSlots)) {
auto &val = fColAddresses[index][slot];
if (ti == typeid(double)) {
val = &fDoubleEvtValues[index][slot];
} else if (ti == typeid(Long64_t)) {
val = &fLong64EvtValues[index][slot];
} else if (ti == typeid(std::string)) {
val = &fStringEvtValues[index][slot];
} else {
val = &fBoolEvtValues[index][slot];
}
ret[slot] = &val;
}
return ret;
}
void RCsvDS::InferColTypes(std::vector<std::string> &columns)
{
auto i = 0U;
for (auto &col : columns) {
InferType(col, i);
++i;
}
}
void RCsvDS::InferType(const std::string &col, unsigned int idxCol)
{
ColType_t type;
int dummy;
if (intRegex.Index(col, &dummy) != -1) {
type = 'l'; // Long64_t
} else if (doubleRegex1.Index(col, &dummy) != -1 || doubleRegex2.Index(col, &dummy) != -1) {
type = 'd'; // double
} else if (trueRegex.Index(col, &dummy) != -1 || falseRegex.Index(col, &dummy) != -1) {
type = 'b'; // bool
} else { // everything else is a string
type = 's'; // std::string
}
// TODO: Date
fColTypes[fHeaders[idxCol]] = type;
fColTypesList.push_back(type);
}
std::vector<std::string> RCsvDS::ParseColumns(const std::string &line)
{
std::vector<std::string> columns;
for (size_t i = 0; i < line.size(); ++i) {
i = ParseValue(line, columns, i);
}
return columns;
}
size_t RCsvDS::ParseValue(const std::string &line, std::vector<std::string> &columns, size_t i)
{
std::stringstream val;
bool quoted = false;
for (; i < line.size(); ++i) {
if (line[i] == fDelimiter && !quoted) {
break;
} else if (line[i] == '"') {
// Keep just one quote for escaped quotes, none for the normal quotes
if (line[i + 1] != '"') {
quoted = !quoted;
} else {
val << line[++i];
}
} else {
val << line[i];
}
}
columns.emplace_back(val.str());
return i;
}
////////////////////////////////////////////////////////////////////////
/// Constructor to create a CSV RDataSource for RDataFrame.
/// \param[in] fileName Path of the CSV file.
/// \param[in] readHeaders `true` if the CSV file contains headers as first row, `false` otherwise
/// (default `true`).
/// \param[in] delimiter Delimiter character (default ',').
RCsvDS::RCsvDS(std::string_view fileName, bool readHeaders, char delimiter, Long64_t linesChunkSize) // TODO: Let users specify types?
: fReadHeaders(readHeaders),
fStream(std::string(fileName)),
fDelimiter(delimiter),
fLinesChunkSize(linesChunkSize)
{
std::string line;
// Read the headers if present
if (fReadHeaders) {
if (std::getline(fStream, line)) {
FillHeaders(line);
} else {
std::string msg = "Error reading headers of CSV file ";
msg += fileName;
throw std::runtime_error(msg);
}
}
fDataPos = fStream.tellg();
if (std::getline(fStream, line)) {
auto columns = ParseColumns(line);
// Generate headers if not present
if (!fReadHeaders) {
GenerateHeaders(columns.size());
}
// Infer types of columns with first record
InferColTypes(columns);
// rewind one line
fStream.seekg(fDataPos);
}
}
void RCsvDS::FreeRecords()
{
for (auto &record : fRecords) {
for (size_t i = 0; i < record.size(); ++i) {
void *p = record[i];
const auto colType = fColTypes[fHeaders[i]];
switch (colType) {
case 'd': {
delete static_cast<double *>(p);
break;
}
case 'l': {
delete static_cast<Long64_t *>(p);
break;
}
case 'b': {
delete static_cast<bool *>(p);
break;
}
case 's': {
delete static_cast<std::string *>(p);
break;
}
}
}
}
fRecords.clear();
}
////////////////////////////////////////////////////////////////////////
/// Destructor.
RCsvDS::~RCsvDS()
{
FreeRecords();
}
void RCsvDS::Finalise()
{
fStream.clear();
fStream.seekg(fDataPos);
fProcessedLines = 0ULL;
fEntryRangesRequested = 0ULL;
FreeRecords();
}
const std::vector<std::string> &RCsvDS::GetColumnNames() const
{
return fHeaders;
}
std::vector<std::pair<ULong64_t, ULong64_t>> RCsvDS::GetEntryRanges()
{
// Read records and store them in memory
auto linesToRead = fLinesChunkSize;
FreeRecords();
std::string line;
while ((-1LL == fLinesChunkSize || 0 != linesToRead--) && std::getline(fStream, line)) {
fRecords.emplace_back();
FillRecord(line, fRecords.back());
}
std::vector<std::pair<ULong64_t, ULong64_t>> entryRanges;
const auto nRecords = fRecords.size();
if (0 == nRecords)
return entryRanges;
const auto chunkSize = nRecords / fNSlots;
const auto remainder = 1U == fNSlots ? 0 : nRecords % fNSlots;
auto start = 0ULL == fEntryRangesRequested ? 0ULL : fProcessedLines;
auto end = start;
for (auto i : ROOT::TSeqU(fNSlots)) {
start = end;
end += chunkSize;
entryRanges.emplace_back(start, end);
(void)i;
}
entryRanges.back().second += remainder;
fProcessedLines += nRecords;
fEntryRangesRequested++;
return entryRanges;
}
RCsvDS::ColType_t RCsvDS::GetType(std::string_view colName) const
{
if (!HasColumn(colName)) {
std::string msg = "The dataset does not have column ";
msg += colName;
throw std::runtime_error(msg);
}
return fColTypes.at(colName.data());
}
std::string RCsvDS::GetTypeName(std::string_view colName) const
{
return fgColTypeMap.at(GetType(colName));
}
bool RCsvDS::HasColumn(std::string_view colName) const
{
return fHeaders.end() != std::find(fHeaders.begin(), fHeaders.end(), colName);
}
bool RCsvDS::SetEntry(unsigned int slot, ULong64_t entry)
{
// Here we need to normalise the entry to the number of lines we already processed.
const auto offset = (fEntryRangesRequested - 1) * fLinesChunkSize;
const auto recordPos = entry - offset;
int colIndex = 0;
for (auto &colType : fColTypesList) {
auto dataPtr = fRecords[recordPos][colIndex];
switch (colType) {
case 'd': {
fDoubleEvtValues[colIndex][slot] = *static_cast<double *>(dataPtr);
break;
}
case 'l': {
fLong64EvtValues[colIndex][slot] = *static_cast<Long64_t *>(dataPtr);
break;
}
case 'b': {
fBoolEvtValues[colIndex][slot] = *static_cast<bool *>(dataPtr);
break;
}
case 's': {
fStringEvtValues[colIndex][slot] = *static_cast<std::string *>(dataPtr);
break;
}
}
colIndex++;
}
return true;
}
void RCsvDS::SetNSlots(unsigned int nSlots)
{
R__ASSERT(0U == fNSlots && "Setting the number of slots even if the number of slots is different from zero.");
fNSlots = nSlots;
const auto nColumns = fHeaders.size();
// Initialise the entire set of addresses
fColAddresses.resize(nColumns, std::vector<void *>(fNSlots, nullptr));
// Initialize the per event data holders
fDoubleEvtValues.resize(nColumns, std::vector<double>(fNSlots));
fLong64EvtValues.resize(nColumns, std::vector<Long64_t>(fNSlots));
fStringEvtValues.resize(nColumns, std::vector<std::string>(fNSlots));
fBoolEvtValues.resize(nColumns, std::deque<bool>(fNSlots));
}
RDataFrame MakeCsvDataFrame(std::string_view fileName, bool readHeaders, char delimiter, Long64_t linesChunkSize)
{
ROOT::RDataFrame tdf(std::make_unique<RCsvDS>(fileName, readHeaders, delimiter, linesChunkSize));
return tdf;
}
} // ns RDF
} // ns ROOT
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parawin.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:43:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_PARAWIN_HXX
#define SC_PARAWIN_HXX
#ifndef SC_FUNCUTL_HXX
#include "funcutl.hxx"
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx" // ScAddress
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_TABPAGE_HXX //autogen
#include <vcl/tabpage.hxx>
#endif
#ifndef _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SV_TABCTRL_HXX //autogen
#include <vcl/tabctrl.hxx>
#endif
class ScFuncDesc;
//============================================================================
#define NOT_FOUND 0xffff
//============================================================================
class ScParaWin : public TabPage
{
private:
Link aScrollLink;
Link aFxLink;
Link aArgModifiedLink;
const ScFuncDesc* pFuncDesc;
ScAnyRefDlg* pMyParent;
USHORT nArgs;
Font aFntBold;
Font aFntLight;
FixedInfo aFtEditDesc;
FixedText aFtArgName;
FixedInfo aFtArgDesc;
ImageButton aBtnFx1;
FixedText aFtArg1;
ArgEdit aEdArg1;
ScRefButton aRefBtn1;
ImageButton aBtnFx2;
FixedText aFtArg2;
ArgEdit aEdArg2;
ScRefButton aRefBtn2;
ImageButton aBtnFx3;
FixedText aFtArg3;
ArgEdit aEdArg3;
ScRefButton aRefBtn3;
ImageButton aBtnFx4;
FixedText aFtArg4;
ArgEdit aEdArg4;
ScRefButton aRefBtn4;
ScrollBar aSlider;
BOOL bRefMode;
USHORT nEdFocus;
USHORT nActiveLine;
ArgInput aArgInput[4];
String aDefaultString;
SvStrings aParaArray;
DECL_LINK( ScrollHdl, ScrollBar* );
DECL_LINK( ModifyHdl, ArgInput* );
DECL_LINK( GetEdFocusHdl, ArgInput* );
DECL_LINK( GetFxFocusHdl, ArgInput* );
DECL_LINK( GetFxHdl, ArgInput* );
protected:
virtual void SliderMoved();
virtual void ArgumentModified();
virtual void FxClick();
void InitArgInput( USHORT nPos, FixedText& rFtArg, ImageButton& rBtnFx,
ArgEdit& rEdArg, ScRefButton& rRefBtn);
void DelParaArray();
void SetArgumentDesc(const String& aText);
void SetArgumentText(const String& aText);
void SetArgName (USHORT no,const String &aArg);
void SetArgNameFont (USHORT no,const Font&);
void SetArgVal (USHORT no,const String &aArg);
void HideParaLine(USHORT no);
void ShowParaLine(USHORT no);
void UpdateArgDesc( USHORT nArg );
void UpdateArgInput( USHORT nOffset, USHORT i );
public:
ScParaWin(ScAnyRefDlg* pParent,Point aPos);
~ScParaWin();
void SetFunctionDesc(const ScFuncDesc* pFDesc);
void SetArgCount(USHORT nArgs, USHORT nOffset);
void SetEditDesc(const String& aText);
void UpdateParas();
void ClearAll();
BOOL IsRefMode() {return bRefMode;}
void SetRefMode(BOOL bFlag) {bRefMode=bFlag;}
USHORT GetActiveLine();
void SetActiveLine(USHORT no);
ScRefEdit* GetActiveEdit();
String GetActiveArgName();
String GetArgument(USHORT no);
void SetArgument(USHORT no, const String& aString);
void SetArgumentFonts(const Font&aBoldFont,const Font&aLightFont);
void SetEdFocus(USHORT nEditLine); //Sichtbare Editzeilen
USHORT GetSliderPos();
void SetSliderPos(USHORT nSliderPos);
void SetScrollHdl( const Link& rLink ) { aScrollLink = rLink; }
const Link& GetScrollHdl() const { return aScrollLink; }
void SetArgModifiedHdl( const Link& rLink ) { aArgModifiedLink = rLink; }
const Link& GetArgModifiedHdl() const { return aArgModifiedLink; }
void SetFxHdl( const Link& rLink ) { aFxLink = rLink; }
const Link& GetFxHdl() const { return aFxLink; }
};
#endif // SC_PARAWIN_HXX
<commit_msg>INTEGRATION: CWS odff02 (1.3.666); FILE MERGED 2008/02/28 16:19:48 er 1.3.666.1: #i86514# preparation for additional functions and parameters not yet implemented but to be added as string resources, suppress in UI<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parawin.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2008-03-07 11:21:01 $
*
* 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_PARAWIN_HXX
#define SC_PARAWIN_HXX
#ifndef SC_FUNCUTL_HXX
#include "funcutl.hxx"
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx" // ScAddress
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_TABPAGE_HXX //autogen
#include <vcl/tabpage.hxx>
#endif
#ifndef _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SV_TABCTRL_HXX //autogen
#include <vcl/tabctrl.hxx>
#endif
#include <vector>
class ScFuncDesc;
//============================================================================
#define NOT_FOUND 0xffff
//============================================================================
class ScParaWin : public TabPage
{
private:
Link aScrollLink;
Link aFxLink;
Link aArgModifiedLink;
::std::vector<USHORT> aVisibleArgMapping;
const ScFuncDesc* pFuncDesc;
ScAnyRefDlg* pMyParent;
USHORT nArgs; // unsuppressed arguments
Font aFntBold;
Font aFntLight;
FixedInfo aFtEditDesc;
FixedText aFtArgName;
FixedInfo aFtArgDesc;
ImageButton aBtnFx1;
FixedText aFtArg1;
ArgEdit aEdArg1;
ScRefButton aRefBtn1;
ImageButton aBtnFx2;
FixedText aFtArg2;
ArgEdit aEdArg2;
ScRefButton aRefBtn2;
ImageButton aBtnFx3;
FixedText aFtArg3;
ArgEdit aEdArg3;
ScRefButton aRefBtn3;
ImageButton aBtnFx4;
FixedText aFtArg4;
ArgEdit aEdArg4;
ScRefButton aRefBtn4;
ScrollBar aSlider;
BOOL bRefMode;
USHORT nEdFocus;
USHORT nActiveLine;
ArgInput aArgInput[4];
String aDefaultString;
SvStrings aParaArray;
DECL_LINK( ScrollHdl, ScrollBar* );
DECL_LINK( ModifyHdl, ArgInput* );
DECL_LINK( GetEdFocusHdl, ArgInput* );
DECL_LINK( GetFxFocusHdl, ArgInput* );
DECL_LINK( GetFxHdl, ArgInput* );
protected:
virtual void SliderMoved();
virtual void ArgumentModified();
virtual void FxClick();
void InitArgInput( USHORT nPos, FixedText& rFtArg, ImageButton& rBtnFx,
ArgEdit& rEdArg, ScRefButton& rRefBtn);
void DelParaArray();
void SetArgumentDesc(const String& aText);
void SetArgumentText(const String& aText);
void SetArgName (USHORT no,const String &aArg);
void SetArgNameFont (USHORT no,const Font&);
void SetArgVal (USHORT no,const String &aArg);
void HideParaLine(USHORT no);
void ShowParaLine(USHORT no);
void UpdateArgDesc( USHORT nArg );
void UpdateArgInput( USHORT nOffset, USHORT i );
public:
ScParaWin(ScAnyRefDlg* pParent,Point aPos);
~ScParaWin();
void SetFunctionDesc(const ScFuncDesc* pFDesc);
void SetArgumentOffset(USHORT nOffset);
void SetEditDesc(const String& aText);
void UpdateParas();
void ClearAll();
BOOL IsRefMode() {return bRefMode;}
void SetRefMode(BOOL bFlag) {bRefMode=bFlag;}
USHORT GetActiveLine();
void SetActiveLine(USHORT no);
ScRefEdit* GetActiveEdit();
String GetActiveArgName();
String GetArgument(USHORT no);
void SetArgument(USHORT no, const String& aString);
void SetArgumentFonts(const Font&aBoldFont,const Font&aLightFont);
void SetEdFocus(USHORT nEditLine); //Sichtbare Editzeilen
USHORT GetSliderPos();
void SetSliderPos(USHORT nSliderPos);
void SetScrollHdl( const Link& rLink ) { aScrollLink = rLink; }
const Link& GetScrollHdl() const { return aScrollLink; }
void SetArgModifiedHdl( const Link& rLink ) { aArgModifiedLink = rLink; }
const Link& GetArgModifiedHdl() const { return aArgModifiedLink; }
void SetFxHdl( const Link& rLink ) { aFxLink = rLink; }
const Link& GetFxHdl() const { return aFxLink; }
};
#endif // SC_PARAWIN_HXX
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: lexer.cpp
* Purpose: Implementation of lexer classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX
#include <wx/tokenzr.h>
#include <wx/extension/lexer.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExAlignText
wxExLexer::wxExLexer(const wxXmlNode* node)
{
m_CommentBegin.clear();
m_CommentBegin2.clear();
m_CommentEnd.clear();
m_CommentEnd2.clear();
m_Colourings.clear();
m_Extensions.clear();
m_Properties.clear();
m_Keywords.clear();
m_KeywordsSet.clear();
m_ScintillaLexer.clear();
if (node != NULL)
{
Set(node);
}
}
const wxString wxExLexer::GetFormattedText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out) const
{
wxString text = lines, header_to_use = header;
size_t nCharIndex;
wxString out;
// Process text between the carriage return line feeds.
while ((nCharIndex = text.find("\n")) != wxString::npos)
{
out << wxExAlignText(
text.substr(0, nCharIndex),
header_to_use,
fill_out_with_space,
fill_out,
*this);
text = text.substr(nCharIndex + 1);
header_to_use = wxString(' ', header.size());
}
if (!text.empty())
{
out << wxExAlignText(
text,
header_to_use,
fill_out_with_space,
fill_out,
*this);
}
return out;
}
const wxString wxExLexer::GetKeywordsString(int keyword_set) const
{
if (keyword_set == -1)
{
return GetKeywordsStringSet(m_Keywords);
}
else
{
std::map< int, std::set<wxString> >::const_iterator it =
m_KeywordsSet.find(keyword_set);
if (it != m_KeywordsSet.end())
{
return GetKeywordsStringSet(it->second);
}
}
return wxEmptyString;
}
const wxString wxExLexer::GetKeywordsStringSet(
const std::set<wxString>& kset) const
{
wxString keywords;
for (
std::set<wxString>::const_iterator it = kset.begin();
it != kset.end();
++it)
{
keywords += *it + " ";
}
return keywords.Trim(); // remove the ending space
}
bool wxExLexer::IsKeyword(const wxString& word) const
{
std::set<wxString>::const_iterator it = m_Keywords.find(word);
return (it != m_Keywords.end());
}
bool wxExLexer::KeywordStartsWith(const wxString& word) const
{
std::set<wxString>::const_iterator it = m_Keywords.lower_bound(word.Lower());
return
it != m_Keywords.end() &&
it->StartsWith(word.Lower());
}
const wxString wxExLexer::MakeComment(
const wxString& text,
bool fill_out_with_space,
bool fill_out) const
{
wxString out;
text.find("\n") != wxString::npos ?
out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out):
out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this);
return out;
}
const wxString wxExLexer::MakeComment(
const wxString& prefix,
const wxString& text) const
{
wxString out;
text.find("\n") != wxString::npos ?
out << GetFormattedText(text, prefix, true, true):
out << wxExAlignText(text, prefix, true, true, *this);
return out;
}
const wxString wxExLexer::MakeSingleLineComment(
const wxString& text,
bool fill_out_with_space,
bool fill_out) const
{
if (m_CommentBegin.empty() && m_CommentEnd.empty())
{
return text;
}
// First set the fill_out_character.
wxUniChar fill_out_character;
if (fill_out_with_space || m_ScintillaLexer == "hypertext")
{
fill_out_character = ' ';
}
else
{
if (text.empty())
{
if (m_CommentBegin == m_CommentEnd)
fill_out_character = '-';
else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1];
}
else fill_out_character = ' ';
}
wxString out = m_CommentBegin + fill_out_character + text;
// Fill out characters.
if (fill_out)
{
// To prevent filling out spaces
if (fill_out_character != ' ' || !m_CommentEnd.empty())
{
const int fill_chars = UsableCharactersPerLine() - text.size();
if (fill_chars > 0)
{
const wxString fill_out(fill_out_character, fill_chars);
out += fill_out;
}
}
}
if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd;
return out;
}
void wxExLexer::Set(const wxXmlNode* node)
{
m_ScintillaLexer = node->GetAttribute("name", "");
m_Extensions = node->GetAttribute(
"extensions",
"*." + m_ScintillaLexer);
if (node->GetAttribute("match", "") != "")
{
m_Colourings =
wxExLexers::Get()->AutoMatch(node->GetAttribute("match", ""));
}
if (m_ScintillaLexer == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
m_CommentBegin = "<!--";
m_CommentEnd = "-->";
}
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
const std::vector<wxString> v =
wxExLexers::Get()->ParseTagColourings(child);
m_Colourings.insert(
m_Colourings.end(),
v.begin(), v.end());
}
else if (child->GetName() == "keywords")
{
if (!SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError(
_("Keywords could not be set on line: %d"),
child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
m_Properties = wxExLexers::Get()->ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
m_CommentBegin = child->GetAttribute("begin1", "");
m_CommentEnd = child->GetAttribute("end1", "");
m_CommentBegin2 = child->GetAttribute("begin2", "");
m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined lexer tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
}
bool wxExLexer::SetKeywords(const wxString& value)
{
if (!m_Keywords.empty())
{
m_Keywords.clear();
}
if (!m_KeywordsSet.empty())
{
m_KeywordsSet.clear();
}
std::set<wxString> keywords_set;
wxStringTokenizer tkz(value, "\r\n ");
int setno = 0;
while (tkz.HasMoreTokens())
{
const wxString line = tkz.GetNextToken();
wxStringTokenizer fields(line, ":");
wxString keyword;
if (fields.CountTokens() > 1)
{
keyword = fields.GetNextToken();
const int new_setno = atoi(fields.GetNextToken().c_str());
if (new_setno >= wxSTC_KEYWORDSET_MAX)
{
return false;
}
if (new_setno != setno)
{
if (!keywords_set.empty())
{
m_KeywordsSet.insert(make_pair(setno, keywords_set));
keywords_set.clear();
}
setno = new_setno;
}
keywords_set.insert(keyword);
}
else
{
keyword = line;
keywords_set.insert(line);
}
m_Keywords.insert(keyword);
}
m_KeywordsSet.insert(make_pair(setno, keywords_set));
return true;
}
int wxExLexer::UsableCharactersPerLine() const
{
// We always use lines with 80 characters. We adjust this here for
// the space the beginning and end of the comment characters occupy.
return 80
- ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0)
- ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0);
}
<commit_msg>assert when lexer is empty<commit_after>/******************************************************************************\
* File: lexer.cpp
* Purpose: Implementation of lexer classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX
#include <wx/tokenzr.h>
#include <wx/extension/lexer.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExAlignText
wxExLexer::wxExLexer(const wxXmlNode* node)
{
m_CommentBegin.clear();
m_CommentBegin2.clear();
m_CommentEnd.clear();
m_CommentEnd2.clear();
m_Colourings.clear();
m_Extensions.clear();
m_Properties.clear();
m_Keywords.clear();
m_KeywordsSet.clear();
m_ScintillaLexer.clear();
if (node != NULL)
{
Set(node);
}
}
const wxString wxExLexer::GetFormattedText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out) const
{
wxString text = lines, header_to_use = header;
size_t nCharIndex;
wxString out;
// Process text between the carriage return line feeds.
while ((nCharIndex = text.find("\n")) != wxString::npos)
{
out << wxExAlignText(
text.substr(0, nCharIndex),
header_to_use,
fill_out_with_space,
fill_out,
*this);
text = text.substr(nCharIndex + 1);
header_to_use = wxString(' ', header.size());
}
if (!text.empty())
{
out << wxExAlignText(
text,
header_to_use,
fill_out_with_space,
fill_out,
*this);
}
return out;
}
const wxString wxExLexer::GetKeywordsString(int keyword_set) const
{
if (keyword_set == -1)
{
return GetKeywordsStringSet(m_Keywords);
}
else
{
std::map< int, std::set<wxString> >::const_iterator it =
m_KeywordsSet.find(keyword_set);
if (it != m_KeywordsSet.end())
{
return GetKeywordsStringSet(it->second);
}
}
return wxEmptyString;
}
const wxString wxExLexer::GetKeywordsStringSet(
const std::set<wxString>& kset) const
{
wxString keywords;
for (
std::set<wxString>::const_iterator it = kset.begin();
it != kset.end();
++it)
{
keywords += *it + " ";
}
return keywords.Trim(); // remove the ending space
}
bool wxExLexer::IsKeyword(const wxString& word) const
{
std::set<wxString>::const_iterator it = m_Keywords.find(word);
return (it != m_Keywords.end());
}
bool wxExLexer::KeywordStartsWith(const wxString& word) const
{
std::set<wxString>::const_iterator it = m_Keywords.lower_bound(word.Lower());
return
it != m_Keywords.end() &&
it->StartsWith(word.Lower());
}
const wxString wxExLexer::MakeComment(
const wxString& text,
bool fill_out_with_space,
bool fill_out) const
{
wxString out;
text.find("\n") != wxString::npos ?
out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out):
out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this);
return out;
}
const wxString wxExLexer::MakeComment(
const wxString& prefix,
const wxString& text) const
{
wxString out;
text.find("\n") != wxString::npos ?
out << GetFormattedText(text, prefix, true, true):
out << wxExAlignText(text, prefix, true, true, *this);
return out;
}
const wxString wxExLexer::MakeSingleLineComment(
const wxString& text,
bool fill_out_with_space,
bool fill_out) const
{
if (m_CommentBegin.empty() && m_CommentEnd.empty())
{
return text;
}
// First set the fill_out_character.
wxUniChar fill_out_character;
if (fill_out_with_space || m_ScintillaLexer == "hypertext")
{
fill_out_character = ' ';
}
else
{
if (text.empty())
{
if (m_CommentBegin == m_CommentEnd)
fill_out_character = '-';
else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1];
}
else fill_out_character = ' ';
}
wxString out = m_CommentBegin + fill_out_character + text;
// Fill out characters.
if (fill_out)
{
// To prevent filling out spaces
if (fill_out_character != ' ' || !m_CommentEnd.empty())
{
const int fill_chars = UsableCharactersPerLine() - text.size();
if (fill_chars > 0)
{
const wxString fill_out(fill_out_character, fill_chars);
out += fill_out;
}
}
}
if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd;
return out;
}
void wxExLexer::Set(const wxXmlNode* node)
{
m_ScintillaLexer = node->GetAttribute("name", "");
wxASSERT(!m_ScintillaLexer.empty());
m_Extensions = node->GetAttribute(
"extensions",
"*." + m_ScintillaLexer);
if (node->GetAttribute("match", "") != "")
{
m_Colourings =
wxExLexers::Get()->AutoMatch(node->GetAttribute("match", ""));
}
if (m_ScintillaLexer == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
m_CommentBegin = "<!--";
m_CommentEnd = "-->";
}
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
const std::vector<wxString> v =
wxExLexers::Get()->ParseTagColourings(child);
m_Colourings.insert(
m_Colourings.end(),
v.begin(), v.end());
}
else if (child->GetName() == "keywords")
{
if (!SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError(
_("Keywords could not be set on line: %d"),
child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
m_Properties = wxExLexers::Get()->ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
m_CommentBegin = child->GetAttribute("begin1", "");
m_CommentEnd = child->GetAttribute("end1", "");
m_CommentBegin2 = child->GetAttribute("begin2", "");
m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined lexer tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
}
bool wxExLexer::SetKeywords(const wxString& value)
{
if (!m_Keywords.empty())
{
m_Keywords.clear();
}
if (!m_KeywordsSet.empty())
{
m_KeywordsSet.clear();
}
std::set<wxString> keywords_set;
wxStringTokenizer tkz(value, "\r\n ");
int setno = 0;
while (tkz.HasMoreTokens())
{
const wxString line = tkz.GetNextToken();
wxStringTokenizer fields(line, ":");
wxString keyword;
if (fields.CountTokens() > 1)
{
keyword = fields.GetNextToken();
const int new_setno = atoi(fields.GetNextToken().c_str());
if (new_setno >= wxSTC_KEYWORDSET_MAX)
{
return false;
}
if (new_setno != setno)
{
if (!keywords_set.empty())
{
m_KeywordsSet.insert(make_pair(setno, keywords_set));
keywords_set.clear();
}
setno = new_setno;
}
keywords_set.insert(keyword);
}
else
{
keyword = line;
keywords_set.insert(line);
}
m_Keywords.insert(keyword);
}
m_KeywordsSet.insert(make_pair(setno, keywords_set));
return true;
}
int wxExLexer::UsableCharactersPerLine() const
{
// We always use lines with 80 characters. We adjust this here for
// the space the beginning and end of the comment characters occupy.
return 80
- ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0)
- ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0);
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: shell.cpp
* Purpose: Implementation of class wxExSTCShell
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/tokenzr.h>
#include <wx/extension/shell.h>
#include <wx/extension/app.h>
#if wxUSE_GUI
using namespace std;
BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC)
EVT_KEY_DOWN(wxExSTCShell::OnKey)
EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand)
END_EVENT_TABLE()
wxExSTCShell::wxExSTCShell(
wxWindow* parent,
const wxString& prompt,
const wxString& command_end,
bool echo,
int commands_save_in_config,
long menu_flags)
: wxExSTC(parent, menu_flags)
, m_Command(wxEmptyString)
, m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end))
, m_CommandStartPosition(0)
, m_Echo(echo)
// take a char that is not likely to appear inside commands
, m_CommandsInConfigDelimiter(wxChar(0x03))
, m_CommandsSaveInConfig(commands_save_in_config)
, m_Prompt(prompt)
{
// Override defaults from config.
SetEdgeMode(wxSTC_EDGE_NONE);
ResetMargins(false); // do not reset divider margin
// Start with a prompt.
Prompt();
if (m_CommandsSaveInConfig == -1)
{
// Fill the list with an empty command.
KeepCommand();
}
else
{
// Get all previous commands.
wxStringTokenizer tkz(wxExApp::GetConfig("Shell"),
m_CommandsInConfigDelimiter);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
m_Commands.push_front(val);
}
// Take care that m_CommandsIterator is valid.
if (!m_Commands.empty())
{
m_CommandsIterator = m_Commands.end();
}
else
{
KeepCommand();
}
}
}
wxExSTCShell::~wxExSTCShell()
{
if (m_CommandsSaveInConfig > 0)
{
wxString values;
int items = 0;
for (
list < wxString >::reverse_iterator it = m_Commands.rbegin();
it != m_Commands.rend() && items < m_CommandsSaveInConfig;
it++)
{
values += *it + m_CommandsInConfigDelimiter;
items++;
}
wxExApp::SetConfig("Shell", values);
}
}
const wxString wxExSTCShell::GetHistory() const
{
wxString commands;
for (
list < wxString >::const_iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
commands += *it + "\n";
}
return commands;
}
void wxExSTCShell::KeepCommand()
{
m_Commands.remove(m_Command);
m_Commands.push_back(m_Command);
if (m_Commands.size() == 1)
{
m_CommandsIterator = m_Commands.end();
}
}
void wxExSTCShell::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
case wxID_PASTE:
// Take care that we cannot paste somewhere inside.
if (GetCurrentPos() < m_CommandStartPosition)
{
DocumentEnd();
}
Paste();
break;
default: command.Skip();
break;
}
}
void wxExSTCShell::OnKey(wxKeyEvent& event)
{
const int key = event.GetKeyCode();
// Enter key pressed, we might have entered a command.
if (key == WXK_RETURN)
{
// First get the command.
SetTargetStart(GetTextLength());
SetTargetEnd(0);
SetSearchFlags(wxSTC_FIND_REGEXP);
if (SearchInTarget("^" + m_Prompt + ".*") != -1)
{
m_Command = GetText().substr(
GetTargetStart() + m_Prompt.length(),
GetTextLength() - 1);
m_Command.Trim();
}
if (m_Command.empty())
{
Prompt();
}
else if (
m_CommandEnd == GetEOL() ||
m_Command.EndsWith(m_CommandEnd))
{
// We have a command.
EmptyUndoBuffer();
// History command.
if (m_Command == wxString("history") +
(m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd))
{
KeepCommand();
ShowHistory();
Prompt();
}
// !.. command, get it from history.
else if (m_Command.StartsWith("!"))
{
if (SetCommandFromHistory(m_Command.substr(1)))
{
AppendText(GetEOL() + m_Command);
// We don't keep the command, so commands are not rearranged and
// repeatingly calling !5 always gives the same command, just as bash does.
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND);
event.SetString(m_Command);
wxPostEvent(GetParent(), event);
}
else
{
Prompt(m_Command + ": " + _("event not found"));
}
}
// Other command, send to parent.
else
{
KeepCommand();
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND);
event.SetString(m_Command);
wxPostEvent(GetParent(), event);
}
m_Command.clear();
}
else
{
if (m_Echo) event.Skip();
}
if (m_Commands.size() > 1)
{
m_CommandsIterator = m_Commands.end();
}
}
// Up or down key pressed, and at the end of document.
else if ((key == WXK_UP || key == WXK_DOWN) &&
GetCurrentPos() == GetTextLength())
{
// There is always an empty command in the list.
if (m_Commands.size() > 1)
{
ShowCommand(key);
}
}
// Home key pressed.
else if (key == WXK_HOME)
{
Home();
const wxString line = GetLine(GetCurrentLine());
if (line.StartsWith(m_Prompt))
{
GotoPos(GetCurrentPos() + m_Prompt.length());
}
}
// Ctrl-Q pressed, used to stop processing.
else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q')
{
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP);
wxPostEvent(GetParent(), event);
}
// Ctrl-V pressed, used for pasting as well.
else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V')
{
if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd();
if (m_Echo) event.Skip();
}
// Backspace or delete key pressed.
else if (key == WXK_BACK || key == WXK_DELETE)
{
if (GetCurrentPos() <= m_CommandStartPosition)
{
// Ignore, so do nothing.
}
else
{
// Allow.
if (m_Echo) event.Skip();
}
}
// The rest.
else
{
// If we enter regular text and not already building a command, first goto end.
if (event.GetModifiers() == wxMOD_NONE &&
key < WXK_START &&
GetCurrentPos() < m_CommandStartPosition)
{
DocumentEnd();
}
if (m_Commands.size() > 1)
{
m_CommandsIterator = m_Commands.end();
}
if (m_Echo) event.Skip();
}
}
void wxExSTCShell::Prompt(const wxString& text, bool add_eol)
{
if (!text.empty())
{
AppendText(text);
}
if (GetTextLength() > 0 && add_eol)
{
AppendText(GetEOL());
}
AppendText(m_Prompt);
DocumentEnd();
m_CommandStartPosition = GetCurrentPos();
EmptyUndoBuffer();
}
bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command)
{
const int no_asked_for = atoi(short_command.c_str());
if (no_asked_for > 0)
{
int no = 0;
for (
list < wxString >::const_iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
if (no == no_asked_for)
{
m_Command = *it;
return true;
}
no++;
}
}
else
{
wxString short_command_check;
if (m_CommandEnd == GetEOL())
{
short_command_check = short_command;
}
else
{
short_command_check =
short_command.substr(
0,
short_command.length() - m_CommandEnd.length());
}
// using a const_reverse_iterator here does not compile under MSW
for (
list < wxString >::reverse_iterator it = m_Commands.rbegin();
it != m_Commands.rend();
it++)
{
const wxString command = *it;
if (command.StartsWith(short_command_check))
{
m_Command = command;
return true;
}
}
}
return false;
}
void wxExSTCShell::ShowCommand(int key)
{
SetTargetStart(GetTextLength());
SetTargetEnd(0);
SetSearchFlags(wxSTC_FIND_REGEXP);
if (SearchInTarget("^" + m_Prompt + ".*") != -1)
{
SetTargetEnd(GetTextLength());
if (key == WXK_UP)
{
if (m_CommandsIterator != m_Commands.begin())
{
m_CommandsIterator--;
}
}
else
{
if (m_CommandsIterator != m_Commands.end())
{
m_CommandsIterator++;
}
}
if (m_CommandsIterator != m_Commands.end())
{
ReplaceTarget(m_Prompt + *m_CommandsIterator);
}
else
{
ReplaceTarget(m_Prompt);
}
DocumentEnd();
}
}
void wxExSTCShell::ShowHistory()
{
int command_no = 1;
for (
list < wxString >::iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
const wxString command = *it;
if (!command.empty())
{
AppendText(wxString::Format("\n%d %s",
command_no++,
command.c_str()));
}
}
}
#endif // wxUSE_GUI
<commit_msg>added GetEOL before event not found message<commit_after>/******************************************************************************\
* File: shell.cpp
* Purpose: Implementation of class wxExSTCShell
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/tokenzr.h>
#include <wx/extension/shell.h>
#include <wx/extension/app.h>
#if wxUSE_GUI
using namespace std;
BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC)
EVT_KEY_DOWN(wxExSTCShell::OnKey)
EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand)
END_EVENT_TABLE()
wxExSTCShell::wxExSTCShell(
wxWindow* parent,
const wxString& prompt,
const wxString& command_end,
bool echo,
int commands_save_in_config,
long menu_flags)
: wxExSTC(parent, menu_flags)
, m_Command(wxEmptyString)
, m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end))
, m_CommandStartPosition(0)
, m_Echo(echo)
// take a char that is not likely to appear inside commands
, m_CommandsInConfigDelimiter(wxChar(0x03))
, m_CommandsSaveInConfig(commands_save_in_config)
, m_Prompt(prompt)
{
// Override defaults from config.
SetEdgeMode(wxSTC_EDGE_NONE);
ResetMargins(false); // do not reset divider margin
// Start with a prompt.
Prompt();
if (m_CommandsSaveInConfig == -1)
{
// Fill the list with an empty command.
KeepCommand();
}
else
{
// Get all previous commands.
wxStringTokenizer tkz(wxExApp::GetConfig("Shell"),
m_CommandsInConfigDelimiter);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
m_Commands.push_front(val);
}
// Take care that m_CommandsIterator is valid.
if (!m_Commands.empty())
{
m_CommandsIterator = m_Commands.end();
}
else
{
KeepCommand();
}
}
}
wxExSTCShell::~wxExSTCShell()
{
if (m_CommandsSaveInConfig > 0)
{
wxString values;
int items = 0;
for (
list < wxString >::reverse_iterator it = m_Commands.rbegin();
it != m_Commands.rend() && items < m_CommandsSaveInConfig;
it++)
{
values += *it + m_CommandsInConfigDelimiter;
items++;
}
wxExApp::SetConfig("Shell", values);
}
}
const wxString wxExSTCShell::GetHistory() const
{
wxString commands;
for (
list < wxString >::const_iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
commands += *it + "\n";
}
return commands;
}
void wxExSTCShell::KeepCommand()
{
m_Commands.remove(m_Command);
m_Commands.push_back(m_Command);
if (m_Commands.size() == 1)
{
m_CommandsIterator = m_Commands.end();
}
}
void wxExSTCShell::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
case wxID_PASTE:
// Take care that we cannot paste somewhere inside.
if (GetCurrentPos() < m_CommandStartPosition)
{
DocumentEnd();
}
Paste();
break;
default: command.Skip();
break;
}
}
void wxExSTCShell::OnKey(wxKeyEvent& event)
{
const int key = event.GetKeyCode();
// Enter key pressed, we might have entered a command.
if (key == WXK_RETURN)
{
// First get the command.
SetTargetStart(GetTextLength());
SetTargetEnd(0);
SetSearchFlags(wxSTC_FIND_REGEXP);
if (SearchInTarget("^" + m_Prompt + ".*") != -1)
{
m_Command = GetText().substr(
GetTargetStart() + m_Prompt.length(),
GetTextLength() - 1);
m_Command.Trim();
}
if (m_Command.empty())
{
Prompt();
}
else if (
m_CommandEnd == GetEOL() ||
m_Command.EndsWith(m_CommandEnd))
{
// We have a command.
EmptyUndoBuffer();
// History command.
if (m_Command == wxString("history") +
(m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd))
{
KeepCommand();
ShowHistory();
Prompt();
}
// !.. command, get it from history.
else if (m_Command.StartsWith("!"))
{
if (SetCommandFromHistory(m_Command.substr(1)))
{
AppendText(GetEOL() + m_Command);
// We don't keep the command, so commands are not rearranged and
// repeatingly calling !5 always gives the same command, just as bash does.
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND);
event.SetString(m_Command);
wxPostEvent(GetParent(), event);
}
else
{
Prompt(GetEOL() + m_Command + ": " + _("event not found"));
}
}
// Other command, send to parent.
else
{
KeepCommand();
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND);
event.SetString(m_Command);
wxPostEvent(GetParent(), event);
}
m_Command.clear();
}
else
{
if (m_Echo) event.Skip();
}
if (m_Commands.size() > 1)
{
m_CommandsIterator = m_Commands.end();
}
}
// Up or down key pressed, and at the end of document.
else if ((key == WXK_UP || key == WXK_DOWN) &&
GetCurrentPos() == GetTextLength())
{
// There is always an empty command in the list.
if (m_Commands.size() > 1)
{
ShowCommand(key);
}
}
// Home key pressed.
else if (key == WXK_HOME)
{
Home();
const wxString line = GetLine(GetCurrentLine());
if (line.StartsWith(m_Prompt))
{
GotoPos(GetCurrentPos() + m_Prompt.length());
}
}
// Ctrl-Q pressed, used to stop processing.
else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q')
{
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP);
wxPostEvent(GetParent(), event);
}
// Ctrl-V pressed, used for pasting as well.
else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V')
{
if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd();
if (m_Echo) event.Skip();
}
// Backspace or delete key pressed.
else if (key == WXK_BACK || key == WXK_DELETE)
{
if (GetCurrentPos() <= m_CommandStartPosition)
{
// Ignore, so do nothing.
}
else
{
// Allow.
if (m_Echo) event.Skip();
}
}
// The rest.
else
{
// If we enter regular text and not already building a command, first goto end.
if (event.GetModifiers() == wxMOD_NONE &&
key < WXK_START &&
GetCurrentPos() < m_CommandStartPosition)
{
DocumentEnd();
}
if (m_Commands.size() > 1)
{
m_CommandsIterator = m_Commands.end();
}
if (m_Echo) event.Skip();
}
}
void wxExSTCShell::Prompt(const wxString& text, bool add_eol)
{
if (!text.empty())
{
AppendText(text);
}
if (GetTextLength() > 0 && add_eol)
{
AppendText(GetEOL());
}
AppendText(m_Prompt);
DocumentEnd();
m_CommandStartPosition = GetCurrentPos();
EmptyUndoBuffer();
}
bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command)
{
const int no_asked_for = atoi(short_command.c_str());
if (no_asked_for > 0)
{
int no = 0;
for (
list < wxString >::const_iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
if (no == no_asked_for)
{
m_Command = *it;
return true;
}
no++;
}
}
else
{
wxString short_command_check;
if (m_CommandEnd == GetEOL())
{
short_command_check = short_command;
}
else
{
short_command_check =
short_command.substr(
0,
short_command.length() - m_CommandEnd.length());
}
// using a const_reverse_iterator here does not compile under MSW
for (
list < wxString >::reverse_iterator it = m_Commands.rbegin();
it != m_Commands.rend();
it++)
{
const wxString command = *it;
if (command.StartsWith(short_command_check))
{
m_Command = command;
return true;
}
}
}
return false;
}
void wxExSTCShell::ShowCommand(int key)
{
SetTargetStart(GetTextLength());
SetTargetEnd(0);
SetSearchFlags(wxSTC_FIND_REGEXP);
if (SearchInTarget("^" + m_Prompt + ".*") != -1)
{
SetTargetEnd(GetTextLength());
if (key == WXK_UP)
{
if (m_CommandsIterator != m_Commands.begin())
{
m_CommandsIterator--;
}
}
else
{
if (m_CommandsIterator != m_Commands.end())
{
m_CommandsIterator++;
}
}
if (m_CommandsIterator != m_Commands.end())
{
ReplaceTarget(m_Prompt + *m_CommandsIterator);
}
else
{
ReplaceTarget(m_Prompt);
}
DocumentEnd();
}
}
void wxExSTCShell::ShowHistory()
{
int command_no = 1;
for (
list < wxString >::iterator it = m_Commands.begin();
it != m_Commands.end();
it++)
{
const wxString command = *it;
if (!command.empty())
{
AppendText(wxString::Format("\n%d %s",
command_no++,
command.c_str()));
}
}
}
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_fit
/// \notebook -js
/// Estimate the error in the integral of a fitted function
/// taking into account the errors in the parameters resulting from the fit.
/// The error is estimated also using the correlations values obtained from
/// the fit
///
/// run the macro doing:
///
/// ~~~ {.cpp}
/// .x ErrorIntegral.C
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Lorenzo Moneta
#include "TF1.h"
#include "TH1D.h"
#include "TVirtualFitter.h"
#include "TMath.h"
#include <assert.h>
#include <iostream>
#include <cmath>
//#define HAVE_OLD_ROOT_VERSION
TF1 * fitFunc; // fit function pointer
const int NPAR = 2; // number of function parameters;
//____________________________________________________________________
double f(double * x, double * p) {
// function used to fit the data
return p[1]*TMath::Sin( p[0] * x[0] );
}
// when TF1::IntegralError was not available
#ifdef HAVE_OLD_ROOT_VERSION
//____________________________________________________________________
double df_dPar(double * x, double * p) {
// derivative of the function w.r..t parameters
// use calculated derivatives from TF1::GradientPar
double grad[NPAR];
// p is used to specify for which parameter the derivative is computed
int ipar = int(p[0] );
assert (ipar >=0 && ipar < NPAR );
assert(fitFunc);
fitFunc->GradientPar(x, grad);
return grad[ipar];
}
//____________________________________________________________________
double IntegralError(int npar, double * c, double * errPar,
double * covMatrix = 0) {
// calculate the error on the integral given the parameter error and
// the integrals of the gradient functions c[]
double err2 = 0;
for (int i = 0; i < npar; ++i) {
if (covMatrix == 0) { // assume error are uncorrelated
err2 += c[i] * c[i] * errPar[i] * errPar[i];
} else {
double s = 0;
for (int j = 0; j < npar; ++j) {
s += covMatrix[i*npar + j] * c[j];
}
err2 += c[i] * s;
}
}
return TMath::Sqrt(err2);
}
#endif
//____________________________________________________________________
void ErrorIntegral() {
fitFunc = new TF1("f",f,0,1,NPAR);
TH1D * h1 = new TH1D("h1","h1",50,0,1);
double par[NPAR] = { 3.14, 1.};
fitFunc->SetParameters(par);
h1->FillRandom("f",1000); // fill histogram sampling fitFunc
fitFunc->SetParameter(0,3.); // vary a little the parameters
h1->Fit(fitFunc); // fit the histogram
h1->Draw();
/* calculate the integral*/
double integral = fitFunc->Integral(0,1);
TVirtualFitter * fitter = TVirtualFitter::GetFitter();
assert(fitter != 0);
double * covMatrix = fitter->GetCovarianceMatrix();
#ifdef HAVE_OLD_ROOT_VERSION
/* calculate now the error (needs the derivatives of the function
w..r.t the parameters)*/
TF1 * deriv_par0 = new TF1("dfdp0",df_dPar,0,1,1);
deriv_par0->SetParameter(0,0);
TF1 * deriv_par1 = new TF1("dfdp1",df_dPar,0,1,1);
deriv_par1->SetParameter(0,1.);
double c[2];
c[0] = deriv_par0->Integral(0,1);
c[1] = deriv_par1->Integral(0,1);
double * epar = fitFunc->GetParErrors();
/* without correlations*/
double sigma_integral_0 = IntegralError(2,c,epar);
/*with correlations*/
double sigma_integral = IntegralError(2,c,epar,covMatrix);
#else
/* using new function in TF1 (from 12/6/2007)*/
double sigma_integral = fitFunc->IntegralError(0,1);
#endif
std::cout << "Integral = " << integral << " +/- " << sigma_integral
<< std::endl;
// estimated integral and error analytically
double * p = fitFunc->GetParameters();
double ic = p[1]* (1-std::cos(p[0]) )/p[0];
double c0c = p[1] * (std::cos(p[0]) + p[0]*std::sin(p[0]) -1.)/p[0]/p[0];
double c1c = (1-std::cos(p[0]) )/p[0];
// estimated error with correlations
double sic = std::sqrt( c0c*c0c * covMatrix[0] + c1c*c1c * covMatrix[3]
+ 2.* c0c*c1c * covMatrix[1]);
if ( std::fabs(sigma_integral-sic) > 1.E-6*sic )
std::cout << " ERROR: test failed : different analytical integral : "
<< ic << " +/- " << sic << std::endl;
}
<commit_msg>Remove confusing old ifdef<commit_after>/// \file
/// \ingroup tutorial_fit
/// \notebook -js
/// Estimate the error in the integral of a fitted function
/// taking into account the errors in the parameters resulting from the fit.
/// The error is estimated also using the correlations values obtained from
/// the fit
///
/// run the macro doing:
///
/// ~~~ {.cpp}
/// .x ErrorIntegral.C
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Lorenzo Moneta
#include "TF1.h"
#include "TH1D.h"
#include "TVirtualFitter.h"
#include "TMath.h"
#include <assert.h>
#include <iostream>
#include <cmath>
TF1 * fitFunc; // fit function pointer
const int NPAR = 2; // number of function parameters;
//____________________________________________________________________
double f(double * x, double * p) {
// function used to fit the data
return p[1]*TMath::Sin( p[0] * x[0] );
}
//____________________________________________________________________
void ErrorIntegral() {
fitFunc = new TF1("f",f,0,1,NPAR);
TH1D * h1 = new TH1D("h1","h1",50,0,1);
double par[NPAR] = { 3.14, 1.};
fitFunc->SetParameters(par);
h1->FillRandom("f",1000); // fill histogram sampling fitFunc
fitFunc->SetParameter(0,3.); // vary a little the parameters
h1->Fit(fitFunc); // fit the histogram
h1->Draw();
/* calculate the integral*/
double integral = fitFunc->Integral(0,1);
TVirtualFitter * fitter = TVirtualFitter::GetFitter();
assert(fitter != 0);
double * covMatrix = fitter->GetCovarianceMatrix();
/* using new function in TF1 (from 12/6/2007)*/
double sigma_integral = fitFunc->IntegralError(0,1);
std::cout << "Integral = " << integral << " +/- " << sigma_integral
<< std::endl;
// estimated integral and error analytically
double * p = fitFunc->GetParameters();
double ic = p[1]* (1-std::cos(p[0]) )/p[0];
double c0c = p[1] * (std::cos(p[0]) + p[0]*std::sin(p[0]) -1.)/p[0]/p[0];
double c1c = (1-std::cos(p[0]) )/p[0];
// estimated error with correlations
double sic = std::sqrt( c0c*c0c * covMatrix[0] + c1c*c1c * covMatrix[3]
+ 2.* c0c*c1c * covMatrix[1]);
if ( std::fabs(sigma_integral-sic) > 1.E-6*sic )
std::cout << " ERROR: test failed : different analytical integral : "
<< ic << " +/- " << sic << std::endl;
}
<|endoftext|> |
<commit_before>#include "Sensor.h"
#include <hidapi.h>
namespace sensor {
Result<double> readTemp() {
hid_device *handle = hid_open(0x16c0, 0x0480, nullptr);
if (!handle) {
return jsz::Error(1, __PRETTY_FUNCTION__, "No sensor found!");
}
unsigned char buf[65];
int num = 0;
for (int i = 0; i < 3; i++) {
num = hid_read(handle, buf, 64);
if (num < 0) {
return jsz::Error(2, __PRETTY_FUNCTION__, "Could not read from sensor!");
}
}
if (num == 64) {
short temp = *(short *) &buf[4]; //holy fuck!
return double(temp);
}
return jsz::Error(3, __PRETTY_FUNCTION__, "Sensor returned unexpected data!");
}
}
<commit_msg>comment<commit_after>#include "Sensor.h"
#include <hidapi.h>
namespace sensor {
Result<double> readTemp() {
hid_device *handle = hid_open(0x16c0, 0x0480, nullptr);
if (!handle) {
return jsz::Error(1, __PRETTY_FUNCTION__, "No sensor found!");
}
unsigned char buf[65];
int num = 0;
//we perform the read 3 times as the sensor sometimes won't wake up on the first try.
for (int i = 0; i < 3; i++) {
num = hid_read(handle, buf, 64);
if (num < 0) {
return jsz::Error(2, __PRETTY_FUNCTION__, "Could not read from sensor!");
}
}
if (num == 64) {
short temp = *(short *) &buf[4]; //holy fuck!
return double(temp);
}
return jsz::Error(3, __PRETTY_FUNCTION__, "Sensor returned unexpected data!");
}
}
<|endoftext|> |
<commit_before>#ifndef ELEMENT_KEY_OF_HPP_
#define ELEMENT_KEY_OF_HPP_
namespace clotho {
namespace powersets {
template < class E >
struct element_key_of {
typedef E key_type;
key_type operator()( const E & e ) {
return e;
}
};
} // namespace powersets
} // namespace cl
#endif // ELEMENT_KEY_OF_HPP_
<commit_msg>Added static method for getting a key from an object<commit_after>#ifndef ELEMENT_KEY_OF_HPP_
#define ELEMENT_KEY_OF_HPP_
namespace clotho {
namespace powersets {
template < class E >
struct element_key_of {
typedef E key_type;
key_type operator()( const E & e ) {
return e;
}
static key_type get_key( const E & e ) {
return e;
}
};
} // namespace powersets
} // namespace cl
#endif // ELEMENT_KEY_OF_HPP_
<|endoftext|> |
<commit_before>namespace mant {
class Printable {
public:
virtual std::string toString() const noexcept = 0;
};
}
inline std::string to_string(
const std::shared_ptr<Printable> printable) noexcept;
//
// Implementation
//
inline std::string to_string(
const std::shared_ptr<Printable> printable) noexcept {
return printable->toString();
}<commit_msg>Fixed namespace<commit_after>namespace mant {
class Printable {
public:
virtual std::string toString() const noexcept = 0;
};
inline std::string to_string(
const std::shared_ptr<Printable> printable) noexcept;
//
// Implementation
//
inline std::string to_string(
const std::shared_ptr<Printable> printable) noexcept {
return printable->toString();
}
}<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/memory_datasource.hpp>
#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
// boost
#include <boost/foreach.hpp>
//stl
#include <vector>
namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
/** Calls the renderer's process function,
* \param output Renderer
* \param f Feature to process
* \param prj_trans Projection
* \param sym Symbolizer object
*/
struct symbol_dispatch : public boost::static_visitor<>
{
symbol_dispatch (Processor & output,
Feature const& f,
proj_transform const& prj_trans)
: output_(output),
f_(f),
prj_trans_(prj_trans) {}
template <typename T>
void operator () (T const& sym) const
{
output_.process(sym,f_,prj_trans_);
}
Processor & output_;
Feature const& f_;
proj_transform const& prj_trans_;
};
public:
explicit feature_style_processor(Map const& m, double scale_factor = 1.0)
: m_(m),
scale_factor_(scale_factor) {}
void apply()
{
#ifdef MAPNIK_DEBUG
//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
Processor & p = static_cast<Processor&>(*this);
p.start_map_processing(m_);
try
{
projection proj(m_.srs()); // map projection
Map::const_metawriter_iterator metaItr = m_.begin_metawriters();
Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->set_size(m_.width(), m_.height());
metaItr->second->set_map_srs(proj);
metaItr->second->start(m_.metawriter_output_properties);
}
double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
scale_denom *= scale_factor_;
#ifdef MAPNIK_DEBUG
std::clog << "scale denominator = " << scale_denom << "\n";
#endif
BOOST_FOREACH ( layer const& lyr, m_.layers() )
{
if (lyr.isVisible(scale_denom))
{
apply_to_layer(lyr, p, proj, scale_denom);
}
}
metaItr = m_.begin_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->stop();
}
}
catch (proj_init_error& ex)
{
std::clog << "proj_init_error:" << ex.what() << "\n";
}
p.end_map_processing(m_);
}
private:
void apply_to_layer(layer const& lay, Processor & p,
projection const& proj0, double scale_denom)
{
#ifdef MAPNIK_DEBUG
//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
boost::shared_ptr<datasource> ds = lay.datasource();
if (!ds)
{
std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n";
return;
}
p.start_layer_processing(lay);
if (ds)
{
box2d<double> ext = m_.get_buffered_extent();
projection proj1(lay.srs());
proj_transform prj_trans(proj0,proj1);
// todo: only display raster if src and dest proj are matched
// todo: add raster re-projection as an optional feature
if (ds->type() == datasource::Raster && !prj_trans.equal())
{
std::clog << "WARNING: Map srs does not match layer srs, skipping raster layer '" << lay.name() << "' as raster re-projection is not currently supported (http://trac.mapnik.org/ticket/663)\n";
std::clog << "map srs: '" << m_.srs() << "'\nlayer srs: '" << lay.srs() << "' \n";
return;
}
//
box2d<double> layer_ext = lay.envelope();
double lx0 = layer_ext.minx();
double ly0 = layer_ext.miny();
double lz0 = 0.0;
double lx1 = layer_ext.maxx();
double ly1 = layer_ext.maxy();
double lz1 = 0.0;
// back project layers extent into main map projection
prj_trans.backward(lx0,ly0,lz0);
prj_trans.backward(lx1,ly1,lz1);
// if no intersection then nothing to do for layer
if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
{
return;
}
// clip query bbox
lx0 = std::max(ext.minx(),lx0);
ly0 = std::max(ext.miny(),ly0);
lx1 = std::min(ext.maxx(),lx1);
ly1 = std::min(ext.maxy(),ly1);
prj_trans.forward(lx0,ly0,lz0);
prj_trans.forward(lx1,ly1,lz1);
box2d<double> bbox(lx0,ly0,lx1,ly1);
query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height());
query q(bbox,res,scale_denom); //BBOX query
std::vector<feature_type_style*> active_styles;
std::set<std::string> names;
attribute_collector collector(names);
double filt_factor = 1;
directive_collector d_collector(&filt_factor);
std::vector<std::string> const& style_names = lay.styles();
// iterate through all named styles collecting active styles and attribute names
BOOST_FOREACH(std::string const& style_name, style_names)
{
boost::optional<feature_type_style const&> style=m_.find_style(style_name);
if (!style)
{
std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n";
continue;
}
const std::vector<rule>& rules=(*style).get_rules();
bool active_rules=false;
BOOST_FOREACH(rule const& r, rules)
{
if (r.active(scale_denom))
{
active_rules = true;
if (ds->type() == datasource::Vector)
{
collector(r);
}
// TODO - in the future rasters should be able to be filtered.
}
}
if (active_rules)
{
active_styles.push_back(const_cast<feature_type_style*>(&(*style)));
}
}
// push all property names
BOOST_FOREACH(std::string const& name, names)
{
q.add_property_name(name);
}
memory_datasource cache;
bool cache_features = lay.cache_features() && style_names.size()>1?true:false;
bool first = true;
BOOST_FOREACH (feature_type_style * style, active_styles)
{
std::vector<rule*> if_rules;
std::vector<rule*> else_rules;
std::vector<rule> const& rules=style->get_rules();
BOOST_FOREACH(rule const& r, rules)
{
if (r.active(scale_denom))
{
if (r.has_else_filter())
{
else_rules.push_back(const_cast<rule*>(&r));
}
else
{
if_rules.push_back(const_cast<rule*>(&r));
}
if ( (ds->type() == datasource::Raster) &&
(ds->params().get<double>("filter_factor",0.0) == 0.0) )
{
rule::symbolizers const& symbols = r.get_symbolizers();
rule::symbolizers::const_iterator symIter = symbols.begin();
rule::symbolizers::const_iterator symEnd = symbols.end();
while (symIter != symEnd)
{
// if multiple raster symbolizers, last will be respected
// should we warn or throw?
boost::apply_visitor(d_collector,*symIter++);
}
q.set_filter_factor(filt_factor);
}
}
}
// process features
featureset_ptr fs;
if (first)
{
if (cache_features)
first = false;
fs = ds->features(q);
}
else
{
fs = cache.features(q);
}
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
bool do_else=true;
if (cache_features)
{
cache.push(feature);
}
BOOST_FOREACH(rule * r, if_rules )
{
expression_ptr const& expr=r->get_filter();
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
if (result.to_bool())
{
do_else=false;
rule::symbolizers const& symbols = r->get_symbolizers();
// if the underlying renderer is not able to process the complete set of symbolizers,
// process one by one.
#ifdef SVG_RENDERER
if(!p.process(symbols,*feature,prj_trans))
#endif
{
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
if (style->get_filter_mode() == FILTER_FIRST)
{
// Stop iterating over rules and proceed with next feature.
break;
}
}
}
if (do_else)
{
BOOST_FOREACH( rule * r, else_rules )
{
rule::symbolizers const& symbols = r->get_symbolizers();
// if the underlying renderer is not able to process the complete set of symbolizers,
// process one by one.
//#ifdef SVG_RENDERER
if(!p.process(symbols,*feature,prj_trans))
//#endif
{
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
}
}
}
}
cache_features = false;
}
}
p.end_layer_processing(lay);
}
Map const& m_;
double scale_factor_;
};
}
#endif //FEATURE_STYLE_PROCESSOR_HPP
<commit_msg>+ restore #ifdefs around -> if(!p.process(symbols,*feature,prj_trans))<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/memory_datasource.hpp>
#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
// boost
#include <boost/foreach.hpp>
//stl
#include <vector>
namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
/** Calls the renderer's process function,
* \param output Renderer
* \param f Feature to process
* \param prj_trans Projection
* \param sym Symbolizer object
*/
struct symbol_dispatch : public boost::static_visitor<>
{
symbol_dispatch (Processor & output,
Feature const& f,
proj_transform const& prj_trans)
: output_(output),
f_(f),
prj_trans_(prj_trans) {}
template <typename T>
void operator () (T const& sym) const
{
output_.process(sym,f_,prj_trans_);
}
Processor & output_;
Feature const& f_;
proj_transform const& prj_trans_;
};
public:
explicit feature_style_processor(Map const& m, double scale_factor = 1.0)
: m_(m),
scale_factor_(scale_factor) {}
void apply()
{
#ifdef MAPNIK_DEBUG
//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
Processor & p = static_cast<Processor&>(*this);
p.start_map_processing(m_);
try
{
projection proj(m_.srs()); // map projection
Map::const_metawriter_iterator metaItr = m_.begin_metawriters();
Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->set_size(m_.width(), m_.height());
metaItr->second->set_map_srs(proj);
metaItr->second->start(m_.metawriter_output_properties);
}
double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
scale_denom *= scale_factor_;
#ifdef MAPNIK_DEBUG
std::clog << "scale denominator = " << scale_denom << "\n";
#endif
BOOST_FOREACH ( layer const& lyr, m_.layers() )
{
if (lyr.isVisible(scale_denom))
{
apply_to_layer(lyr, p, proj, scale_denom);
}
}
metaItr = m_.begin_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->stop();
}
}
catch (proj_init_error& ex)
{
std::clog << "proj_init_error:" << ex.what() << "\n";
}
p.end_map_processing(m_);
}
private:
void apply_to_layer(layer const& lay, Processor & p,
projection const& proj0, double scale_denom)
{
#ifdef MAPNIK_DEBUG
//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
boost::shared_ptr<datasource> ds = lay.datasource();
if (!ds)
{
std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n";
return;
}
p.start_layer_processing(lay);
if (ds)
{
box2d<double> ext = m_.get_buffered_extent();
projection proj1(lay.srs());
proj_transform prj_trans(proj0,proj1);
// todo: only display raster if src and dest proj are matched
// todo: add raster re-projection as an optional feature
if (ds->type() == datasource::Raster && !prj_trans.equal())
{
std::clog << "WARNING: Map srs does not match layer srs, skipping raster layer '" << lay.name() << "' as raster re-projection is not currently supported (http://trac.mapnik.org/ticket/663)\n";
std::clog << "map srs: '" << m_.srs() << "'\nlayer srs: '" << lay.srs() << "' \n";
return;
}
//
box2d<double> layer_ext = lay.envelope();
double lx0 = layer_ext.minx();
double ly0 = layer_ext.miny();
double lz0 = 0.0;
double lx1 = layer_ext.maxx();
double ly1 = layer_ext.maxy();
double lz1 = 0.0;
// back project layers extent into main map projection
prj_trans.backward(lx0,ly0,lz0);
prj_trans.backward(lx1,ly1,lz1);
// if no intersection then nothing to do for layer
if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
{
return;
}
// clip query bbox
lx0 = std::max(ext.minx(),lx0);
ly0 = std::max(ext.miny(),ly0);
lx1 = std::min(ext.maxx(),lx1);
ly1 = std::min(ext.maxy(),ly1);
prj_trans.forward(lx0,ly0,lz0);
prj_trans.forward(lx1,ly1,lz1);
box2d<double> bbox(lx0,ly0,lx1,ly1);
query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height());
query q(bbox,res,scale_denom); //BBOX query
std::vector<feature_type_style*> active_styles;
std::set<std::string> names;
attribute_collector collector(names);
double filt_factor = 1;
directive_collector d_collector(&filt_factor);
std::vector<std::string> const& style_names = lay.styles();
// iterate through all named styles collecting active styles and attribute names
BOOST_FOREACH(std::string const& style_name, style_names)
{
boost::optional<feature_type_style const&> style=m_.find_style(style_name);
if (!style)
{
std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n";
continue;
}
const std::vector<rule>& rules=(*style).get_rules();
bool active_rules=false;
BOOST_FOREACH(rule const& r, rules)
{
if (r.active(scale_denom))
{
active_rules = true;
if (ds->type() == datasource::Vector)
{
collector(r);
}
// TODO - in the future rasters should be able to be filtered.
}
}
if (active_rules)
{
active_styles.push_back(const_cast<feature_type_style*>(&(*style)));
}
}
// push all property names
BOOST_FOREACH(std::string const& name, names)
{
q.add_property_name(name);
}
memory_datasource cache;
bool cache_features = lay.cache_features() && style_names.size()>1?true:false;
bool first = true;
BOOST_FOREACH (feature_type_style * style, active_styles)
{
std::vector<rule*> if_rules;
std::vector<rule*> else_rules;
std::vector<rule> const& rules=style->get_rules();
BOOST_FOREACH(rule const& r, rules)
{
if (r.active(scale_denom))
{
if (r.has_else_filter())
{
else_rules.push_back(const_cast<rule*>(&r));
}
else
{
if_rules.push_back(const_cast<rule*>(&r));
}
if ( (ds->type() == datasource::Raster) &&
(ds->params().get<double>("filter_factor",0.0) == 0.0) )
{
rule::symbolizers const& symbols = r.get_symbolizers();
rule::symbolizers::const_iterator symIter = symbols.begin();
rule::symbolizers::const_iterator symEnd = symbols.end();
while (symIter != symEnd)
{
// if multiple raster symbolizers, last will be respected
// should we warn or throw?
boost::apply_visitor(d_collector,*symIter++);
}
q.set_filter_factor(filt_factor);
}
}
}
// process features
featureset_ptr fs;
if (first)
{
if (cache_features)
first = false;
fs = ds->features(q);
}
else
{
fs = cache.features(q);
}
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
bool do_else=true;
if (cache_features)
{
cache.push(feature);
}
BOOST_FOREACH(rule * r, if_rules )
{
expression_ptr const& expr=r->get_filter();
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
if (result.to_bool())
{
do_else=false;
rule::symbolizers const& symbols = r->get_symbolizers();
// if the underlying renderer is not able to process the complete set of symbolizers,
// process one by one.
#ifdef SVG_RENDERER
if(!p.process(symbols,*feature,prj_trans))
#endif
{
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
if (style->get_filter_mode() == FILTER_FIRST)
{
// Stop iterating over rules and proceed with next feature.
break;
}
}
}
if (do_else)
{
BOOST_FOREACH( rule * r, else_rules )
{
rule::symbolizers const& symbols = r->get_symbolizers();
// if the underlying renderer is not able to process the complete set of symbolizers,
// process one by one.
#ifdef SVG_RENDERER
if(!p.process(symbols,*feature,prj_trans))
#endif
{
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
}
}
}
}
cache_features = false;
}
}
p.end_layer_processing(lay);
}
Map const& m_;
double scale_factor_;
};
}
#endif //FEATURE_STYLE_PROCESSOR_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace sdbusplus
{
namespace message
{
namespace details
{
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_wrapper
{
std::string str;
string_wrapper() = default;
string_wrapper(const string_wrapper&) = default;
string_wrapper& operator=(const string_wrapper&) = default;
string_wrapper(string_wrapper&&) = default;
string_wrapper& operator=(string_wrapper&&) = default;
~string_wrapper() = default;
string_wrapper(const std::string& str) : str(str)
{}
string_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_wrapper& r)
{
return l < r.str;
}
};
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_path_wrapper
{
std::string str;
string_path_wrapper() = default;
string_path_wrapper(const string_path_wrapper&) = default;
string_path_wrapper& operator=(const string_path_wrapper&) = default;
string_path_wrapper(string_path_wrapper&&) = default;
string_path_wrapper& operator=(string_path_wrapper&&) = default;
~string_path_wrapper() = default;
string_path_wrapper(const std::string& str) : str(str)
{}
string_path_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_path_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_path_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_path_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_path_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_path_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_path_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_path_wrapper& r)
{
return l < r.str;
}
std::string filename() const;
string_path_wrapper parent_path() const;
string_path_wrapper operator/(std::string_view) const;
string_path_wrapper& operator/=(std::string_view);
};
/** Typename for sdbus SIGNATURE types. */
struct signature_type
{};
/** Typename for sdbus UNIX_FD types. */
struct unix_fd_type
{
int fd;
unix_fd_type() = default;
unix_fd_type(int f) : fd(f)
{}
operator int() const
{
return fd;
}
};
} // namespace details
/** std::string wrapper for OBJECT_PATH. */
using object_path = details::string_path_wrapper;
/** std::string wrapper for SIGNATURE. */
using signature = details::string_wrapper;
using unix_fd = details::unix_fd_type;
namespace details
{
template <typename T>
struct convert_from_string
{
static auto op(const std::string&) noexcept = delete;
};
template <typename T>
struct convert_to_string
{
static std::string op(T) = delete;
};
} // namespace details
/** @brief Convert from a string to a native type.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion from string functions.
*
* @return A std::optional<T> containing the value if conversion is possible.
*/
template <typename T>
auto convert_from_string(const std::string& str) noexcept
{
return details::convert_from_string<T>::op(str);
};
/** @brief Convert from a native type to a string.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion to string functions.
*
* @return A std::string containing an encoding of the value, if conversion is
* possible.
*/
template <typename T>
std::string convert_to_string(T t)
{
return details::convert_to_string<T>::op(t);
}
namespace details
{
// SFINAE templates to determine if convert_from_string exists for a type.
template <typename T>
auto has_convert_from_string_helper(T)
-> decltype(convert_from_string<T>::op(std::declval<std::string>()),
std::true_type());
auto has_convert_from_string_helper(...) -> std::false_type;
template <typename T>
struct has_convert_from_string :
decltype(has_convert_from_string_helper(std::declval<T>()))
{};
template <typename T>
inline constexpr bool has_convert_from_string_v =
has_convert_from_string<T>::value;
// Specialization of 'convert_from_string' for variant.
template <typename... Types>
struct convert_from_string<std::variant<Types...>>
{
static auto op(const std::string& str)
-> std::optional<std::variant<Types...>>
{
if constexpr (0 < sizeof...(Types))
{
return process<Types...>(str);
}
return {};
}
// We need to iterate through all the variant types and find
// the one which matches the contents of the string. Often,
// a variant can contain both a convertible-type (ie. enum) and
// a string, so we need to iterate through all the convertible-types
// first and convert to string as a last resort.
template <typename T, typename... Args>
static auto process(const std::string& str)
-> std::optional<std::variant<Types...>>
{
// If convert_from_string exists for the type, attempt it.
if constexpr (has_convert_from_string_v<T>)
{
auto r = convert_from_string<T>::op(str);
if (r)
{
return r;
}
}
// If there are any more types in the variant, try them.
if constexpr (0 < sizeof...(Args))
{
auto r = process<Args...>(str);
if (r)
{
return r;
}
}
// Otherwise, if this is a string, do last-resort conversion.
if constexpr (std::is_same_v<std::string, std::remove_cv_t<T>>)
{
return str;
}
return {};
}
};
} // namespace details
} // namespace message
} // namespace sdbusplus
namespace std
{
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_wrapper>
{
using argument_type = sdbusplus::message::details::string_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_path_wrapper>
{
using argument_type = sdbusplus::message::details::string_path_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
} // namespace std
<commit_msg>message: export has_convert_from_string<commit_after>#pragma once
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace sdbusplus
{
namespace message
{
namespace details
{
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_wrapper
{
std::string str;
string_wrapper() = default;
string_wrapper(const string_wrapper&) = default;
string_wrapper& operator=(const string_wrapper&) = default;
string_wrapper(string_wrapper&&) = default;
string_wrapper& operator=(string_wrapper&&) = default;
~string_wrapper() = default;
string_wrapper(const std::string& str) : str(str)
{}
string_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_wrapper& r)
{
return l < r.str;
}
};
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_path_wrapper
{
std::string str;
string_path_wrapper() = default;
string_path_wrapper(const string_path_wrapper&) = default;
string_path_wrapper& operator=(const string_path_wrapper&) = default;
string_path_wrapper(string_path_wrapper&&) = default;
string_path_wrapper& operator=(string_path_wrapper&&) = default;
~string_path_wrapper() = default;
string_path_wrapper(const std::string& str) : str(str)
{}
string_path_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_path_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_path_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_path_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_path_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_path_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_path_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_path_wrapper& r)
{
return l < r.str;
}
std::string filename() const;
string_path_wrapper parent_path() const;
string_path_wrapper operator/(std::string_view) const;
string_path_wrapper& operator/=(std::string_view);
};
/** Typename for sdbus SIGNATURE types. */
struct signature_type
{};
/** Typename for sdbus UNIX_FD types. */
struct unix_fd_type
{
int fd;
unix_fd_type() = default;
unix_fd_type(int f) : fd(f)
{}
operator int() const
{
return fd;
}
};
} // namespace details
/** std::string wrapper for OBJECT_PATH. */
using object_path = details::string_path_wrapper;
/** std::string wrapper for SIGNATURE. */
using signature = details::string_wrapper;
using unix_fd = details::unix_fd_type;
namespace details
{
template <typename T>
struct convert_from_string
{
static auto op(const std::string&) noexcept = delete;
};
template <typename T>
struct convert_to_string
{
static std::string op(T) = delete;
};
} // namespace details
/** @brief Convert from a string to a native type.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion from string functions.
*
* @return A std::optional<T> containing the value if conversion is possible.
*/
template <typename T>
auto convert_from_string(const std::string& str) noexcept
{
return details::convert_from_string<T>::op(str);
};
/** @brief Convert from a native type to a string.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion to string functions.
*
* @return A std::string containing an encoding of the value, if conversion is
* possible.
*/
template <typename T>
std::string convert_to_string(T t)
{
return details::convert_to_string<T>::op(t);
}
namespace details
{
// SFINAE templates to determine if convert_from_string exists for a type.
template <typename T>
auto has_convert_from_string_helper(T)
-> decltype(convert_from_string<T>::op(std::declval<std::string>()),
std::true_type());
auto has_convert_from_string_helper(...) -> std::false_type;
template <typename T>
struct has_convert_from_string :
decltype(has_convert_from_string_helper(std::declval<T>()))
{};
template <typename T>
inline constexpr bool has_convert_from_string_v =
has_convert_from_string<T>::value;
// Specialization of 'convert_from_string' for variant.
template <typename... Types>
struct convert_from_string<std::variant<Types...>>
{
static auto op(const std::string& str)
-> std::optional<std::variant<Types...>>
{
if constexpr (0 < sizeof...(Types))
{
return process<Types...>(str);
}
return {};
}
// We need to iterate through all the variant types and find
// the one which matches the contents of the string. Often,
// a variant can contain both a convertible-type (ie. enum) and
// a string, so we need to iterate through all the convertible-types
// first and convert to string as a last resort.
template <typename T, typename... Args>
static auto process(const std::string& str)
-> std::optional<std::variant<Types...>>
{
// If convert_from_string exists for the type, attempt it.
if constexpr (has_convert_from_string_v<T>)
{
auto r = convert_from_string<T>::op(str);
if (r)
{
return r;
}
}
// If there are any more types in the variant, try them.
if constexpr (0 < sizeof...(Args))
{
auto r = process<Args...>(str);
if (r)
{
return r;
}
}
// Otherwise, if this is a string, do last-resort conversion.
if constexpr (std::is_same_v<std::string, std::remove_cv_t<T>>)
{
return str;
}
return {};
}
};
} // namespace details
/** Export template helper to determine if a type has convert_from_string. */
template <typename T>
inline constexpr bool has_convert_from_string_v =
details::has_convert_from_string_v<T>;
} // namespace message
} // namespace sdbusplus
namespace std
{
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_wrapper>
{
using argument_type = sdbusplus::message::details::string_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_path_wrapper>
{
using argument_type = sdbusplus::message::details::string_path_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
} // namespace std
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 client クラス
@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "main.hpp"
#include "GR/core/ethernet_client.hpp"
#include "sample.hpp"
// #define CLIENT_DEBUG
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief client クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class client {
#ifdef CLIENT_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
static const uint16_t PORT = 3000; ///< クライアント・ポート
net::ethernet_client client_;
typedef utils::basic_format<net::ether_string<net::ethernet::format_id::client0, 2048> > format;
enum class task {
startup,
req_connect,
wait_connect,
time_sync,
make_form,
url_decode,
send_data,
disconnect,
sync_close,
};
task task_;
net::ip_address ip_;
uint16_t port_;
uint32_t delay_;
uint32_t timeout_;
time_t time_;
struct tm tm_;
char form_[1024];
char data_[2048];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
client(net::ethernet& eth) : client_(eth, PORT), task_(task::startup),
#ifdef SEEDA
ip_(192, 168, 1, 3),
#else
ip_(192, 168, 3, 7),
#endif
port_(PORT),
delay_(0), timeout_(0), time_(0) { }
//-----------------------------------------------------------------//
/*!
@brief IP アドレスの取得
@return IP アドレス
*/
//-----------------------------------------------------------------//
const net::ip_address& get_ip() const { return ip_; }
//-----------------------------------------------------------------//
/*!
@brief IP アドレスの参照
@return IP アドレス
*/
//-----------------------------------------------------------------//
net::ip_address& at_ip() { return ip_; }
//-----------------------------------------------------------------//
/*!
@brief ポートの取得
@return ポート
*/
//-----------------------------------------------------------------//
uint16_t get_port() const { return port_; }
//-----------------------------------------------------------------//
/*!
@brief ポートの設定
@param[in] port ポート
*/
//-----------------------------------------------------------------//
void set_port(uint16_t port) { port_ = port; }
//-----------------------------------------------------------------//
/*!
@brief 接続開始
*/
//-----------------------------------------------------------------//
void start_connect()
{
task_ = task::req_connect;
}
//-----------------------------------------------------------------//
/*!
@brief 再接続
*/
//-----------------------------------------------------------------//
void restart()
{
task_ = task::disconnect;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
time_t t;
switch(task_) {
case task::startup:
break;
case task::req_connect:
if(client_.connect(ip_, port_, TMO_NBLK)) {
}
timeout_ = 5 * 100; // 再接続待ち時間
task_ = task::wait_connect;
break;
case task::wait_connect:
if(!client_.connected()) {
if(timeout_ > 0) {
--timeout_;
} else {
auto st = client_.get_ethernet().get_stat(client_.get_cepid());
debug_format("TCP Client stat: %d\n") % static_cast<int>(st);
// 接続しないので、「re_connect」要求を出してみる
if(st == TCP_API_STAT_CLOSED) {
task_ = task::disconnect;
} else {
client_.re_connect();
task_ = task::req_connect;
timeout_ = 5 * 100; // 再接続待ち時間
}
}
break;
} else {
debug_format("Start SEEDA03 Client: %s port(%d), fd(%d)\n")
% ip_.c_str() % port_ % client_.get_cepid();
format::chaout().set_fd(client_.get_cepid());
time_ = get_sample_data().time_;
task_ = task::time_sync;
}
break;
case task::time_sync:
{
auto t = get_sample_data().time_;
if(time_ == t) break;
time_ = t;
struct tm* m = localtime(&t);
tm_ = *m;
task_ = task::make_form;
}
break;
case task::make_form:
utils::sformat("%04d/%02d/%02d,%02d:%02d:%02d", form_, sizeof(form_))
% static_cast<uint32_t>(tm_.tm_year + 1900)
% static_cast<uint32_t>(tm_.tm_mon + 1)
% static_cast<uint32_t>(tm_.tm_mday)
% static_cast<uint32_t>(tm_.tm_hour)
% static_cast<uint32_t>(tm_.tm_min)
% static_cast<uint32_t>(tm_.tm_sec);
{
const sample_data& smd = get_sample_data();
for(int ch = 0; ch < 8; ++ch) {
utils::sformat(",", form_, sizeof(form_), true);
smd.smp_[ch].make_csv2(form_, sizeof(form_), true);
}
}
utils::sformat("\n", form_, sizeof(form_), true);
task_ = task::url_decode;
break;
case task::url_decode:
utils::str::url_decode_to_str(form_, data_, sizeof(data_));
task_ = task::send_data;
break;
case task::send_data:
format::chaout().clear();
format("POST /api/?val=%s HTTP/1.1\n") % data_;
format("Host: %d.%d.%d.%d\n")
% static_cast<int>(ip_[0])
% static_cast<int>(ip_[1])
% static_cast<int>(ip_[2])
% static_cast<int>(ip_[3]);
format("Content-Type: application/x-www-form-urlencoded\n");
format("User-Agent: SEEDA03 Post Client\n");
format("Connection: close\n\n");
format::chaout().flush();
task_ = task::disconnect;
break;
case task::disconnect:
client_.stop();
timeout_ = 5;
task_ = task::sync_close;
break;
case task::sync_close:
if(timeout_ > 0) {
--timeout_;
} else {
debug_format("Client disconnected: %s\n") % ip_.c_str();
task_ = task::req_connect;
}
break;
}
}
};
}
<commit_msg>update client connection management<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 client クラス
@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "main.hpp"
#include "GR/core/ethernet_client.hpp"
#include "sample.hpp"
// #define CLIENT_DEBUG
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief client クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class client {
#ifdef CLIENT_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
static const uint16_t PORT = 3000; ///< クライアント・ポート
net::ethernet_client client_;
typedef utils::basic_format<net::ether_string<net::ethernet::format_id::client0, 2048> > format;
enum class task {
startup,
req_connect,
wait_connect,
time_sync,
make_form,
url_decode,
send_data,
disconnect,
sync_close,
};
task task_;
net::ip_address ip_;
uint16_t port_;
uint32_t delay_;
uint32_t timeout_;
time_t time_;
struct tm tm_;
char form_[1024];
char data_[2048];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
client(net::ethernet& eth) : client_(eth, PORT), task_(task::startup),
#ifdef SEEDA
ip_(192, 168, 1, 3),
#else
ip_(192, 168, 3, 7),
#endif
port_(PORT),
delay_(0), timeout_(0), time_(0) { }
//-----------------------------------------------------------------//
/*!
@brief IP アドレスの取得
@return IP アドレス
*/
//-----------------------------------------------------------------//
const net::ip_address& get_ip() const { return ip_; }
//-----------------------------------------------------------------//
/*!
@brief IP アドレスの参照
@return IP アドレス
*/
//-----------------------------------------------------------------//
net::ip_address& at_ip() { return ip_; }
//-----------------------------------------------------------------//
/*!
@brief ポートの取得
@return ポート
*/
//-----------------------------------------------------------------//
uint16_t get_port() const { return port_; }
//-----------------------------------------------------------------//
/*!
@brief ポートの設定
@param[in] port ポート
*/
//-----------------------------------------------------------------//
void set_port(uint16_t port) { port_ = port; }
//-----------------------------------------------------------------//
/*!
@brief 接続開始
*/
//-----------------------------------------------------------------//
void start_connect()
{
task_ = task::req_connect;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
time_t t;
switch(task_) {
case task::startup:
break;
case task::req_connect:
if(client_.connect(ip_, port_, TMO_NBLK)) {
}
timeout_ = 5 * 100; // 再接続待ち時間
task_ = task::wait_connect;
break;
case task::wait_connect:
if(!client_.connected()) {
if(timeout_ > 0) {
--timeout_;
} else {
auto st = client_.get_ethernet().get_stat(client_.get_cepid());
debug_format("TCP Client re_connect: %d\n") % static_cast<int>(st);
// 接続しないので、「re_connect」要求を出してみる
// ※ re_connect では、タイムアウト(10分)を無効にする。
client_.re_connect();
timeout_ = 5 * 100; // 再接続待ち時間
}
} else {
debug_format("Start SEEDA03 Client: %s port(%d), fd(%d)\n")
% ip_.c_str() % port_ % client_.get_cepid();
format::chaout().set_fd(client_.get_cepid());
time_ = get_sample_data().time_;
task_ = task::time_sync;
}
break;
case task::time_sync:
{
auto t = get_sample_data().time_;
if(time_ == t) break;
time_ = t;
struct tm* m = localtime(&t);
tm_ = *m;
task_ = task::make_form;
}
break;
case task::make_form:
utils::sformat("%04d/%02d/%02d,%02d:%02d:%02d", form_, sizeof(form_))
% static_cast<uint32_t>(tm_.tm_year + 1900)
% static_cast<uint32_t>(tm_.tm_mon + 1)
% static_cast<uint32_t>(tm_.tm_mday)
% static_cast<uint32_t>(tm_.tm_hour)
% static_cast<uint32_t>(tm_.tm_min)
% static_cast<uint32_t>(tm_.tm_sec);
{
const sample_data& smd = get_sample_data();
for(int ch = 0; ch < 8; ++ch) {
utils::sformat(",", form_, sizeof(form_), true);
smd.smp_[ch].make_csv2(form_, sizeof(form_), true);
}
}
utils::sformat("\n", form_, sizeof(form_), true);
task_ = task::url_decode;
break;
case task::url_decode:
utils::str::url_decode_to_str(form_, data_, sizeof(data_));
task_ = task::send_data;
break;
case task::send_data:
format::chaout().clear();
format("POST /api/?val=%s HTTP/1.1\n") % data_;
format("Host: %d.%d.%d.%d\n")
% static_cast<int>(ip_[0])
% static_cast<int>(ip_[1])
% static_cast<int>(ip_[2])
% static_cast<int>(ip_[3]);
format("Content-Type: application/x-www-form-urlencoded\n");
format("User-Agent: SEEDA03 Post Client\n");
format("Connection: close\n\n");
format::chaout().flush();
task_ = task::disconnect;
break;
case task::disconnect:
client_.stop();
timeout_ = 5;
task_ = task::sync_close;
break;
case task::sync_close:
if(timeout_ > 0) {
--timeout_;
} else {
debug_format("Client disconnected: %s\n") % ip_.c_str();
task_ = task::req_connect;
}
break;
}
}
};
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include "algo/loop.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
SYNOPSIS = "Pad an image to increase the FOV";
ARGUMENTS
+ Argument ("image_in",
"the image to be padded").type_image_in()
+ Argument ("image_out",
"the output path for the resulting padded image").type_image_out();
OPTIONS
+ Option ("uniform",
"pad the input image by a uniform number of voxels on all sides (in 3D)")
+ Argument ("number").type_integer (0)
+ Option ("axis",
"pad the input image along the provided axis (defined by index). Lower and upper define "
"the number of voxels to add to the lower and upper bounds of the axis").allow_multiple()
+ Argument ("index").type_integer (0, 2)
+ Argument ("lower").type_integer (0)
+ Argument ("upper").type_integer (0);
}
void run ()
{
Header input_header = Header::open (argument[0]);
auto input = input_header.get_image<float>();
ssize_t bounds[3][2] = { {0, input_header.size (0) - 1},
{0, input_header.size (1) - 1},
{0, input_header.size (2) - 1} };
ssize_t padding[3][2] = { {0, 0}, {0, 0}, {0, 0} };
auto opt = get_options ("uniform");
if (opt.size()) {
ssize_t pad = opt[0][0];
for (size_t axis = 0; axis < 3; axis++) {
padding[axis][0] = pad;
padding[axis][1] = pad;
}
}
opt = get_options ("axis");
for (size_t i = 0; i != opt.size(); ++i) {
// Manual padding of axis overrides uniform padding
const size_t axis = opt[i][0];
padding[axis][0] = opt[i][1];
padding[axis][1] = opt[i][2];
}
Header output_header (input_header);
auto output_transform = input_header.transform();
for (size_t axis = 0; axis < 3; ++axis) {
output_header.size (axis) = output_header.size(axis) + padding[axis][0] + padding[axis][1];
output_transform (axis, 3) += (output_transform (axis, 0) * (bounds[0][0] - padding[0][0]) * input_header.spacing (0))
+ (output_transform (axis, 1) * (bounds[1][0] - padding[0][0]) * input_header.spacing (1))
+ (output_transform (axis, 2) * (bounds[2][0] - padding[0][0]) * input_header.spacing (2));
}
output_header.transform() = output_transform;
auto output = Image<float>::create (argument[1], output_header);
for (auto l = Loop ("padding image... ", output) (output); l; ++l) {
bool in_bounds = true;
for (size_t axis = 0; axis < 3; ++axis) {
input.index(axis) = output.index(axis) - padding[axis][0];
if (input.index(axis) < 0 || input.index(axis) >= input_header.size (axis))
in_bounds = false;
}
if (input.ndim() > 3)
input.index (3) = output.index (3);
if (in_bounds)
output.value() = input.value();
else
output.value() = 0;
}
}
<commit_msg>mrpad: fix header translation of y and z axes<commit_after>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include "algo/loop.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
SYNOPSIS = "Pad an image to increase the FOV";
ARGUMENTS
+ Argument ("image_in",
"the image to be padded").type_image_in()
+ Argument ("image_out",
"the output path for the resulting padded image").type_image_out();
OPTIONS
+ Option ("uniform",
"pad the input image by a uniform number of voxels on all sides (in 3D)")
+ Argument ("number").type_integer (0)
+ Option ("axis",
"pad the input image along the provided axis (defined by index). Lower and upper define "
"the number of voxels to add to the lower and upper bounds of the axis").allow_multiple()
+ Argument ("index").type_integer (0, 2)
+ Argument ("lower").type_integer (0)
+ Argument ("upper").type_integer (0);
}
void run ()
{
Header input_header = Header::open (argument[0]);
auto input = input_header.get_image<float>();
ssize_t bounds[3][2] = { {0, input_header.size (0) - 1},
{0, input_header.size (1) - 1},
{0, input_header.size (2) - 1} };
ssize_t padding[3][2] = { {0, 0}, {0, 0}, {0, 0} };
auto opt = get_options ("uniform");
if (opt.size()) {
ssize_t pad = opt[0][0];
for (size_t axis = 0; axis < 3; axis++) {
padding[axis][0] = pad;
padding[axis][1] = pad;
}
}
opt = get_options ("axis");
for (size_t i = 0; i != opt.size(); ++i) {
// Manual padding of axis overrides uniform padding
const size_t axis = opt[i][0];
padding[axis][0] = opt[i][1];
padding[axis][1] = opt[i][2];
}
Header output_header (input_header);
auto output_transform = input_header.transform();
for (size_t axis = 0; axis < 3; ++axis) {
output_header.size (axis) = output_header.size(axis) + padding[axis][0] + padding[axis][1];
output_transform (axis, 3) += (output_transform (axis, 0) * (bounds[0][0] - padding[0][0]) * input_header.spacing (0))
+ (output_transform (axis, 1) * (bounds[1][0] - padding[1][0]) * input_header.spacing (1))
+ (output_transform (axis, 2) * (bounds[2][0] - padding[2][0]) * input_header.spacing (2));
}
output_header.transform() = output_transform;
auto output = Image<float>::create (argument[1], output_header);
for (auto l = Loop ("padding image... ", output) (output); l; ++l) {
bool in_bounds = true;
for (size_t axis = 0; axis < 3; ++axis) {
input.index(axis) = output.index(axis) - padding[axis][0];
if (input.index(axis) < 0 || input.index(axis) >= input_header.size (axis))
in_bounds = false;
}
if (input.ndim() > 3)
input.index (3) = output.index (3);
if (in_bounds)
output.value() = input.value();
else
output.value() = 0;
}
}
<|endoftext|> |
<commit_before>//
// Macro designed for use with the AliAnalysisTaskDptDptCorrelations task.
//
// Author: Claude Pruneau, Wayne State
/////////////////////////////////////////////////////////////////////////////////
AliAnalysisTaskDptDptCorrelations *AddTaskDptDptCorrelations(int singlesOnly = 1,
int useWeights = 0,
int centralityMethod = 4)
{
// Set Default Configuration of this analysis
// ==========================================
int debugLevel = 0;
int singlesOnly = 1;
int useWeights = 0;
int rejectPileup = 1;
int rejectPairConversion = 1;
int sameFilter = 1;
int centralityMethod = 4;
int nCentrality = 10;
double minCentrality[] = { 0.5, 5., 10., 20., 30., 40., 50., 60., 70., 80. };
double maxCentrality[] = { 5.0, 10., 20., 30., 40., 50., 60., 70., 80., 90. };
int nChargeSets = 1;
int chargeSets[] = { 1, 0, 3 };
double zMin = -10.;
double zMax = 10.;
double ptMin = 0.2;
double ptMax = 2.0;
double etaMin = -1.0;
double etaMax = 1.0;
double dcaZMin = -3.0;
double dcaZMax = 3.0;
double dcaXYMin = -3.0;
double dcaXYMax = 3.0;
double dedxMin = 0.0;
double dedxMax = 20000.0;
int nClusterMin = 70;
int trackFilterBit = 128;
int requestedCharge1 = 1; //default
int requestedCharge2 = -1; //default
// Get the pointer to the existing analysis manager via the static access method.
// ==============================================================================
AliAnalysisManager *analysisManager = AliAnalysisManager::GetAnalysisManager();
if (!analysisManager)
{
::Error("AddTaskDptDptCorrelations", "No analysis manager to connect to.");
return NULL;
}
TString part1Name;
TString part2Name;
TString eventName;
TString prefixName = "Corr_";
TString pileupRejecSuffix = "_PileupRejec";
TString pairRejecSuffix = "_PairRejec";
TString calibSuffix = "_calib";
TString singlesOnlySuffix = "_SO";
TString suffix;
TString inputPath = ".";
TString outputPath = ".";
TString baseName;
TString listName;
TString taskName;
TString inputHistogramFileName;
TString outputHistogramFileName;
// Create the task and add subtask.
// ===========================================================================
int iTask = 0; // task counter
AliAnalysisDataContainer *taskInputContainer;
AliAnalysisDataContainer *taskOutputContainer;
for (int iCentrality=0; iCentrality < nCentrality; ++iCentrality)
{
for (int iChargeSet=0; iChargeSet < nChargeSets; iChargeSet++)
{
switch (chargeSets[iChargeSet])
{
case 0: part1Name = "P_"; part2Name = "P_"; requestedCharge1 = 1; requestedCharge2 = 1; sameFilter = 1; break;
case 1: part1Name = "P_"; part2Name = "M_"; requestedCharge1 = 1; requestedCharge2 = -1; sameFilter = 0; break;
case 2: part1Name = "M_"; part2Name = "P_"; requestedCharge1 = -1; requestedCharge2 = 1; sameFilter = 0; break;
case 3: part1Name = "M_"; part2Name = "M_"; requestedCharge1 = -1; requestedCharge2 = -1; sameFilter = 1; break;
}
//part1Name += int(1000*etaMin);
part1Name += "eta";
part1Name += int(1000*etaMax);
part1Name += "_";
part1Name += int(1000*ptMin);
part1Name += "pt";
part1Name += int(1000*ptMax);
part1Name += "_";
//part2Name += int(1000*etaMin);
part2Name += "eta";
part2Name += int(1000*etaMax);
part2Name += "_";
part2Name += int(1000*ptMin);
part2Name += "pt";
part2Name += int(1000*ptMax);
part2Name += "_";
eventName = "";
eventName += int(10.*minCentrality[iCentrality] );
eventName += "Vo";
eventName += int(10.*maxCentrality[iCentrality] );
//eventName += "_";
//eventName += int(10*zMin );
//eventName += "Z";
//eventName += int(10*zMax );
if (rejectPileup) eventName += pileupRejecSuffix;
if (rejectPairConversion) eventName += pairRejecSuffix;
baseName = prefixName;
baseName += part1Name;
baseName += part2Name;
baseName += eventName;
listName = baseName;
taskName = baseName;
//inputHistogramFileName = inputPath;
//inputHistogramFileName += "/";
inputHistogramFileName = baseName;
inputHistogramFileName += calibSuffix;
inputHistogramFileName += ".root";
//outputHistogramFileName = outputPath;
//outputHistogramFileName += "/";
outputHistogramFileName = baseName;
if (singlesOnly) outputHistogramFileName += singlesOnlySuffix;
outputHistogramFileName += ".root";
cout << " iTask: " << iTask << endl;
cout << " Task Name: " << taskName << endl;
cout << " List Name: " << listName << endl;
cout << " inputHistogramFileName: " << inputHistogramFileName << endl;
cout << " outputHistogramFileName: " << outputHistogramFileName << endl;
cout << " using weights: " << useWeights << endl;
TFile * inputFile = 0;
TList * histoList = 0;
TH3F * weight_1 = 0;
TH3F * weight_2 = 0;
if (useWeights)
{
inputFile = new TFile(inputHistogramFileName);
if (!inputFile)
{
cout << "Requested file:" << inputHistogramFileName << " was not opened. ABORT." << endl;
return;
}
histoList = (TList *) inputFile->Get(listName);
if (!histoList)
{
cout << "Requested list:" << listName << " was not found. ABORT." << endl;
return;
}
if (requestedCharge1 == 1)
weight_1 = (TH3 *) histoList->FindObject("correction_p");
else
weight_1 = (TH3 *) histoList->FindObject("correction_m");
if (!weight_1)
{
cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl;
return;
}
if (!sameFilter)
{
weight_2 = 0;
if (requestedCharge2 == 1)
weight_2 = (TH3 *) histoList->FindObject("correction_p");
else
weight_2 = (TH3 *) histoList->FindObject("correction_m");
if (!weight_2)
{
cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl;
return;
}
}
}
AliAnalysisTaskDptDptCorrelations* task = new AliAnalysisTaskDptDptCorrelations(taskName);
//configure my task
task->SetDebugLevel( debugLevel );
task->SetSameFilter( sameFilter );
task->SetSinglesOnly( singlesOnly );
task->SetUseWeights( useWeights );
task->SetRejectPileup( rejectPileup );
task->SetRejectPairConversion(rejectPairConversion);
task->SetVertexZMin( zMin );
task->SetVertexZMax( zMax );
task->SetVertexXYMin( -1. );
task->SetVertexXYMax( 1. );
task->SetCentralityMethod( centralityMethod);
task->SetCentrality( minCentrality[iCentrality], maxCentrality[iCentrality]);
task->SetPtMin1( ptMin );
task->SetPtMax1( ptMax );
task->SetEtaMin1( etaMin );
task->SetEtaMax1( etaMax );
task->SetPtMin2( ptMin );
task->SetPtMax2( ptMax );
task->SetEtaMin2( etaMin );
task->SetEtaMax2( etaMax );
task->SetDcaZMin( dcaZMin );
task->SetDcaZMax( dcaZMax );
task->SetDcaXYMin( dcaXYMin );
task->SetDcaXYMax( dcaXYMax );
task->SetDedxMin( dedxMin );
task->SetDedxMax( dedxMax );
task->SetNClusterMin( nClusterMin );
task->SetTrackFilterBit( trackFilterBit );
task->SetRequestedCharge_1( requestedCharge1);
task->SetRequestedCharge_2( requestedCharge2);
task->SetWeigth_1( weight_1 );
task->SetWeigth_2( weight_2 );
cout << "Creating task output container" << endl;
taskOutputContainer = analysisManager->CreateContainer(listName,
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:%s", AliAnalysisManager::GetCommonFileName(), listName)); //outputHistogramFileName);
cout << "Add task to analysis manager and connect it to input and output containers" << endl;
analysisManager->AddTask(task);
analysisManager->ConnectInput( task, 0, analysisManager->GetCommonInputContainer());
analysisManager->ConnectOutput(task, 0, taskOutputContainer );
cout << "Task added ...." << endl;
iTask++;
}
}
return task;
}
<commit_msg>changed output file name<commit_after>//
// Macro designed for use with the AliAnalysisTaskDptDptCorrelations task.
//
// Author: Claude Pruneau, Wayne State
/////////////////////////////////////////////////////////////////////////////////
AliAnalysisTaskDptDptCorrelations *AddTaskDptDptCorrelations(int singlesOnly = 1,
int useWeights = 0,
int centralityMethod = 4)
{
// Set Default Configuration of this analysis
// ==========================================
int debugLevel = 0;
int singlesOnly = 1;
int useWeights = 0;
int rejectPileup = 1;
int rejectPairConversion = 1;
int sameFilter = 1;
int centralityMethod = 4;
int nCentrality = 10;
double minCentrality[] = { 0.5, 5., 10., 20., 30., 40., 50., 60., 70., 80. };
double maxCentrality[] = { 5.0, 10., 20., 30., 40., 50., 60., 70., 80., 90. };
int nChargeSets = 1;
int chargeSets[] = { 1, 0, 3 };
double zMin = -10.;
double zMax = 10.;
double ptMin = 0.2;
double ptMax = 2.0;
double etaMin = -1.0;
double etaMax = 1.0;
double dcaZMin = -3.0;
double dcaZMax = 3.0;
double dcaXYMin = -3.0;
double dcaXYMax = 3.0;
double dedxMin = 0.0;
double dedxMax = 20000.0;
int nClusterMin = 70;
int trackFilterBit = 128;
int requestedCharge1 = 1; //default
int requestedCharge2 = -1; //default
// Get the pointer to the existing analysis manager via the static access method.
// ==============================================================================
AliAnalysisManager *analysisManager = AliAnalysisManager::GetAnalysisManager();
if (!analysisManager)
{
::Error("AddTaskDptDptCorrelations", "No analysis manager to connect to.");
return NULL;
}
TString part1Name;
TString part2Name;
TString eventName;
TString prefixName = "Corr_";
TString pileupRejecSuffix = "_PileupRejec";
TString pairRejecSuffix = "_PairRejec";
TString calibSuffix = "_calib";
TString singlesOnlySuffix = "_SO";
TString suffix;
TString inputPath = ".";
TString outputPath = ".";
TString baseName;
TString listName;
TString taskName;
TString inputHistogramFileName;
TString outputHistogramFileName;
// Create the task and add subtask.
// ===========================================================================
int iTask = 0; // task counter
AliAnalysisDataContainer *taskInputContainer;
AliAnalysisDataContainer *taskOutputContainer;
for (int iCentrality=0; iCentrality < nCentrality; ++iCentrality)
{
for (int iChargeSet=0; iChargeSet < nChargeSets; iChargeSet++)
{
switch (chargeSets[iChargeSet])
{
case 0: part1Name = "P_"; part2Name = "P_"; requestedCharge1 = 1; requestedCharge2 = 1; sameFilter = 1; break;
case 1: part1Name = "P_"; part2Name = "M_"; requestedCharge1 = 1; requestedCharge2 = -1; sameFilter = 0; break;
case 2: part1Name = "M_"; part2Name = "P_"; requestedCharge1 = -1; requestedCharge2 = 1; sameFilter = 0; break;
case 3: part1Name = "M_"; part2Name = "M_"; requestedCharge1 = -1; requestedCharge2 = -1; sameFilter = 1; break;
}
//part1Name += int(1000*etaMin);
part1Name += "eta";
part1Name += int(1000*etaMax);
part1Name += "_";
part1Name += int(1000*ptMin);
part1Name += "pt";
part1Name += int(1000*ptMax);
part1Name += "_";
//part2Name += int(1000*etaMin);
part2Name += "eta";
part2Name += int(1000*etaMax);
part2Name += "_";
part2Name += int(1000*ptMin);
part2Name += "pt";
part2Name += int(1000*ptMax);
part2Name += "_";
eventName = "";
eventName += int(10.*minCentrality[iCentrality] );
eventName += "Vo";
eventName += int(10.*maxCentrality[iCentrality] );
//eventName += "_";
//eventName += int(10*zMin );
//eventName += "Z";
//eventName += int(10*zMax );
if (rejectPileup) eventName += pileupRejecSuffix;
if (rejectPairConversion) eventName += pairRejecSuffix;
baseName = prefixName;
baseName += part1Name;
baseName += part2Name;
baseName += eventName;
listName = baseName;
taskName = baseName;
//inputHistogramFileName = inputPath;
//inputHistogramFileName += "/";
inputHistogramFileName = baseName;
inputHistogramFileName += calibSuffix;
inputHistogramFileName += ".root";
//outputHistogramFileName = outputPath;
//outputHistogramFileName += "/";
outputHistogramFileName = baseName;
if (singlesOnly) outputHistogramFileName += singlesOnlySuffix;
outputHistogramFileName += ".root";
cout << " iTask: " << iTask << endl;
cout << " Task Name: " << taskName << endl;
cout << " List Name: " << listName << endl;
cout << " inputHistogramFileName: " << inputHistogramFileName << endl;
cout << " outputHistogramFileName: " << outputHistogramFileName << endl;
cout << " using weights: " << useWeights << endl;
TFile * inputFile = 0;
TList * histoList = 0;
TH3F * weight_1 = 0;
TH3F * weight_2 = 0;
if (useWeights)
{
inputFile = new TFile(inputHistogramFileName);
if (!inputFile)
{
cout << "Requested file:" << inputHistogramFileName << " was not opened. ABORT." << endl;
return;
}
histoList = (TList *) inputFile->Get(listName);
if (!histoList)
{
cout << "Requested list:" << listName << " was not found. ABORT." << endl;
return;
}
if (requestedCharge1 == 1)
weight_1 = (TH3 *) histoList->FindObject("correction_p");
else
weight_1 = (TH3 *) histoList->FindObject("correction_m");
if (!weight_1)
{
cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl;
return;
}
if (!sameFilter)
{
weight_2 = 0;
if (requestedCharge2 == 1)
weight_2 = (TH3 *) histoList->FindObject("correction_p");
else
weight_2 = (TH3 *) histoList->FindObject("correction_m");
if (!weight_2)
{
cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl;
return;
}
}
}
AliAnalysisTaskDptDptCorrelations* task = new AliAnalysisTaskDptDptCorrelations(taskName);
//configure my task
task->SetDebugLevel( debugLevel );
task->SetSameFilter( sameFilter );
task->SetSinglesOnly( singlesOnly );
task->SetUseWeights( useWeights );
task->SetRejectPileup( rejectPileup );
task->SetRejectPairConversion(rejectPairConversion);
task->SetVertexZMin( zMin );
task->SetVertexZMax( zMax );
task->SetVertexXYMin( -1. );
task->SetVertexXYMax( 1. );
task->SetCentralityMethod( centralityMethod);
task->SetCentrality( minCentrality[iCentrality], maxCentrality[iCentrality]);
task->SetPtMin1( ptMin );
task->SetPtMax1( ptMax );
task->SetEtaMin1( etaMin );
task->SetEtaMax1( etaMax );
task->SetPtMin2( ptMin );
task->SetPtMax2( ptMax );
task->SetEtaMin2( etaMin );
task->SetEtaMax2( etaMax );
task->SetDcaZMin( dcaZMin );
task->SetDcaZMax( dcaZMax );
task->SetDcaXYMin( dcaXYMin );
task->SetDcaXYMax( dcaXYMax );
task->SetDedxMin( dedxMin );
task->SetDedxMax( dedxMax );
task->SetNClusterMin( nClusterMin );
task->SetTrackFilterBit( trackFilterBit );
task->SetRequestedCharge_1( requestedCharge1);
task->SetRequestedCharge_2( requestedCharge2);
task->SetWeigth_1( weight_1 );
task->SetWeigth_2( weight_2 );
cout << "Creating task output container" << endl;
taskOutputContainer = analysisManager->CreateContainer(listName,
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:Histos", AliAnalysisManager::GetCommonFileName()));
cout << "Add task to analysis manager and connect it to input and output containers" << endl;
analysisManager->AddTask(task);
analysisManager->ConnectInput( task, 0, analysisManager->GetCommonInputContainer());
analysisManager->ConnectOutput(task, 0, taskOutputContainer );
cout << "Task added ...." << endl;
iTask++;
}
}
return task;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <cmath>
#include <uqEnvironment.h>
#include <uqGslVector.h>
#include <uqGslMatrix.h>
#include <uqVectorSpace.h>
#include <uqVectorSubset.h>
#include <uqVectorRV.h>
using namespace std;
int main(int argc, char **argv) {
int i, j, num_samples = 1e5, seed;
double sigmasq = 1.0;
double *mean;
double *var;
double *sumsq;
double *delta;
FILE *fpRand = fopen("/dev/random", "r");
fread(&seed, sizeof(int), 1, fpRand);
fclose(fpRand);
MPI_Init(&argc, &argv);
uqEnvOptionsValuesClass *opts = new uqEnvOptionsValuesClass();
opts->m_seed = seed;
uqFullEnvironmentClass *env = new uqFullEnvironmentClass(MPI_COMM_WORLD,
NULL, "", opts);
uqVectorSpaceClass<uqGslVectorClass, uqGslMatrixClass> *param_space;
param_space = new uqVectorSpaceClass<uqGslVectorClass, uqGslMatrixClass>(
*env, "param_", 4, NULL);
mean = new double[4];
var = new double[4];
sumsq = new double[4];
delta = new double[4];
uqGslVectorClass mins(param_space->zeroVector());
uqGslVectorClass maxs(param_space->zeroVector());
mins.cwSet(-INFINITY);
maxs.cwSet(INFINITY);
uqBoxSubsetClass<uqGslVectorClass, uqGslMatrixClass> *param_domain;
param_domain = new uqBoxSubsetClass<uqGslVectorClass, uqGslMatrixClass>(
"param_", *param_space, mins, maxs);
// Mean zero
uqGslVectorClass prior_mean_vals(param_space->zeroVector());
// Variance
uqGslVectorClass prior_var_vals(param_space->zeroVector());
prior_var_vals.cwSet(sigmasq);
uqGaussianVectorRVClass<uqGslVectorClass, uqGslMatrixClass> *prior;
prior = new uqGaussianVectorRVClass<uqGslVectorClass, uqGslMatrixClass>(
"prior_", *(param_domain), prior_mean_vals, prior_var_vals);
uqGslVectorClass draw(param_space->zeroVector());
for (j = 0; j < 4; j++) {
mean[j] = 0.0;
sumsq[j] = 0.0;
}
for (i = 1; i < num_samples + 1; i++) {
prior->realizer().realization(draw);
for (j = 0; j < 4; j++) {
delta[j] = draw[j] - mean[j];
mean[j] += (double) delta[j] / i;
sumsq[j] += delta[j] * (draw[j] - mean[j]);
}
}
for (j = 0; j < 4; j++) {
// This is the sample variance
var[j] = sumsq[j] / (num_samples - 1);
}
cout << var[0] << " "
<< var[1] << " "
<< var[2] << " "
<< var[3] << endl;
double mean_min = -3.0 * sqrt(sigmasq) / sqrt(num_samples);
double mean_max = 3.0 * sqrt(sigmasq) / sqrt(num_samples);
int return_val = 0;
for (j = 0; j < 4; j++) {
if (mean[j] < mean_min || mean[j] > mean_max) {
return_val = 1;
break;
}
}
double var_min = sigmasq - 3.0 * sqrt(2.0 * sigmasq * sigmasq / (num_samples - 1));
double var_max = sigmasq + 3.0 * sqrt(2.0 * sigmasq * sigmasq / (num_samples - 1));
// var[j] should be approximately ~ N(sigma^2, 2 sigma^4 / (num_samples - 1))
for (j = 0; j < 4; j++) {
if (var[j] < var_min || var[j] > var_max) {
return_val = 1;
break;
}
}
delete env;
MPI_Finalize();
return return_val;
}
<commit_msg>[queso]: Add conditional MPI checkage. Provide 'free'dom for teh mallocs.<commit_after>#include <stdio.h>
#include <string.h>
#include <cmath>
#include <uqEnvironment.h>
#include <uqGslVector.h>
#include <uqGslMatrix.h>
#include <uqVectorSpace.h>
#include <uqVectorSubset.h>
#include <uqVectorRV.h>
using namespace std;
int main(int argc, char **argv) {
int i, j, num_samples = 1e5, seed;
double sigmasq = 1.0;
double *mean;
double *var;
double *sumsq;
double *delta;
FILE *fpRand = fopen("/dev/random", "r");
fread(&seed, sizeof(int), 1, fpRand);
fclose(fpRand);
uqEnvOptionsValuesClass *opts = new uqEnvOptionsValuesClass();
opts->m_seed = seed;
#ifdef QUESO_HAS_MPI
MPI_Init(&argc, &argv);
#endif
uqFullEnvironmentClass *env =
#ifdef QUESO_HAS_MPI
new uqFullEnvironmentClass(MPI_COMM_WORLD, NULL, "", opts);
#else
new uqFullEnvironmentClass(0, NULL, "", opts);
#endif
uqVectorSpaceClass<uqGslVectorClass, uqGslMatrixClass> *param_space;
param_space = new uqVectorSpaceClass<uqGslVectorClass, uqGslMatrixClass>(
*env, "param_", 4, NULL);
mean = new double[4];
var = new double[4];
sumsq = new double[4];
delta = new double[4];
uqGslVectorClass mins(param_space->zeroVector());
uqGslVectorClass maxs(param_space->zeroVector());
mins.cwSet(-INFINITY);
maxs.cwSet(INFINITY);
uqBoxSubsetClass<uqGslVectorClass, uqGslMatrixClass> *param_domain;
param_domain = new uqBoxSubsetClass<uqGslVectorClass, uqGslMatrixClass>(
"param_", *param_space, mins, maxs);
// Mean zero
uqGslVectorClass prior_mean_vals(param_space->zeroVector());
// Variance
uqGslVectorClass prior_var_vals(param_space->zeroVector());
prior_var_vals.cwSet(sigmasq);
uqGaussianVectorRVClass<uqGslVectorClass, uqGslMatrixClass> *prior;
prior = new uqGaussianVectorRVClass<uqGslVectorClass, uqGslMatrixClass>(
"prior_", *(param_domain), prior_mean_vals, prior_var_vals);
uqGslVectorClass draw(param_space->zeroVector());
for (j = 0; j < 4; j++) {
mean[j] = 0.0;
sumsq[j] = 0.0;
}
for (i = 1; i < num_samples + 1; i++) {
prior->realizer().realization(draw);
for (j = 0; j < 4; j++) {
delta[j] = draw[j] - mean[j];
mean[j] += (double) delta[j] / i;
sumsq[j] += delta[j] * (draw[j] - mean[j]);
}
}
for (j = 0; j < 4; j++) {
// This is the sample variance
var[j] = sumsq[j] / (num_samples - 1);
}
cout << var[0] << " "
<< var[1] << " "
<< var[2] << " "
<< var[3] << endl;
double mean_min = -3.0 * sqrt(sigmasq) / sqrt(num_samples);
double mean_max = 3.0 * sqrt(sigmasq) / sqrt(num_samples);
int return_val = 0;
for (j = 0; j < 4; j++) {
if (mean[j] < mean_min || mean[j] > mean_max) {
return_val = 1;
break;
}
}
double var_min = sigmasq - 3.0 * sqrt(2.0 * sigmasq * sigmasq / (num_samples - 1));
double var_max = sigmasq + 3.0 * sqrt(2.0 * sigmasq * sigmasq / (num_samples - 1));
// var[j] should be approximately ~ N(sigma^2, 2 sigma^4 / (num_samples - 1))
for (j = 0; j < 4; j++) {
if (var[j] < var_min || var[j] > var_max) {
return_val = 1;
break;
}
}
delete env;
delete opts;
delete mean;
delete var;
delete delta;
delete sumsq;
delete param_space;
delete param_domain;
delete prior;
#ifdef QUESO_HAS_MPI
MPI_Finalize();
#endif
return return_val;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RootShadowNode.h"
#include <react/components/view/conversions.h>
namespace facebook {
namespace react {
const char RootComponentName[] = "RootView";
void RootShadowNode::layout() {
ensureUnsealed();
layout(getProps()->layoutContext);
// This is the rare place where shadow node must layout (set `layoutMetrics`)
// itself because there is no a parent node which usually should do it.
setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_));
}
} // namespace react
} // namespace facebook
<commit_msg>Add systrace to calculation of Yoga layout() in Fabric<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RootShadowNode.h"
#include <react/components/view/conversions.h>
#include <react/debug/SystraceSection.h>
namespace facebook {
namespace react {
const char RootComponentName[] = "RootView";
void RootShadowNode::layout() {
SystraceSection s("RootShadowNode::layout");
ensureUnsealed();
layout(getProps()->layoutContext);
// This is the rare place where shadow node must layout (set `layoutMetrics`)
// itself because there is no a parent node which usually should do it.
setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_));
}
} // namespace react
} // namespace facebook
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date 12, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Ruben Dörfel and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief test for filterData function that calls rtproceesing and utils library.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>
#include <utils/ioutils.h>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestFiffRFR
*
* @brief The TestFiffRFR class provides read filter read fiff verification tests
*
*/
class TestFiffRFR: public QObject
{
Q_OBJECT
public:
TestFiffRFR();
private slots:
void initTestCase();
void compareData();
void compareTimes();
void compareInfo();
void cleanupTestCase();
private:
double epsilon;
FiffRawData first_in_raw;
MatrixXd first_in_data;
MatrixXd first_in_times;
MatrixXd dataFiltered;
MatrixXd refDataFiltered;
FiffRawData ref_in_raw;
MatrixXd ref_in_data;
MatrixXd ref_in_times;
};
//*************************************************************************************************************
TestFiffRFR::TestFiffRFR()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestFiffRFR::initTestCase()
{
qDebug() << "Epsilon" << epsilon;
QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/sample_audvis_short_raw.fif");
QFile t_fileRef(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/ref_rtfilter_filterdata_raw.fif");
QFile t_fileOut(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_test_rwr_out.fif");
//
// Make sure test folder exists
//
QFileInfo t_fileOutInfo(t_fileOut);
QDir().mkdir(t_fileOutInfo.path());
//*********************************************************************************************************
// First Read, Filter & Write
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read, Filter & Write >>>>>>>>>>>>>>>>>>>>>>>>>\n");
//
// Setup for reading the raw data
//
first_in_raw = FiffRawData(t_fileIn);
//
// Set up pick list: MEG + STI 014 - bad channels
//
//
bool want_meg = true;
bool want_eeg = false;
bool want_stim = false;
QStringList include;
include << "STI 014";
MatrixXi picks = first_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, first_in_raw.info.bads); // prefer member function
if(picks.cols() == 0)
{
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = first_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, first_in_raw.info.bads);// prefer member function
if(picks.cols() == 0)
{
printf("channel list may need modification\n");
}
}
//
RowVectorXd cals;
FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut,first_in_raw.info, cals/*, picks*/);
//
// Set up the reading parameters
// To read the whole file at once set
//
fiff_int_t from = first_in_raw.first_samp;
fiff_int_t to = first_in_raw.last_samp;
fiff_int_t quantum = to-from+1;
RtFilter rtFilter; // filter object
MatrixXd dataFiltered; // filter output
// channel selection - in this case use every channel
// size = number of channels; value = index channel number
QVector<int> channelList(first_in_raw.info.nchan);
for (int i = 0; i < first_in_raw.info.nchan; i++){
channelList[i] = i;
}
// initialize filter settings
QString filter_name = "example_cosine";
FilterData::FilterType type = FilterData::BPF;
double sFreq = first_in_raw.info.sfreq; // get Sample freq from Data
double centerfreq = 10/(sFreq/2.0); // normed nyquist freq.
double bandwidth = 10/(sFreq/2.0);
double parkswidth = 1/(sFreq/2.0);
//
//
// Read and write all the data
//
bool first_buffer = true;
fiff_int_t first, last;
MatrixXd data;
MatrixXd times;
for(first = from; first < to; first+=quantum)
{
last = first+quantum-1;
if (last > to)
{
last = to;
}
if (!first_in_raw.read_raw_segment(first_in_data,first_in_times,first,last/*,picks*/))
{
printf("error during read_raw_segment\n");
}
//Filtering
printf("Filtering...");
dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);
printf("[done]\n");
printf("Writing...");
if (first_buffer)
{
if (first > 0)
outfid->write_int(FIFF_FIRST_SAMPLE,&first);
first_buffer = false;
}
outfid->write_raw_buffer(dataFiltered,cals);
printf("[done]\n");
}
outfid->finish_writing_raw();
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read, Filter & Write Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
//*********************************************************************************************************
// Read MNE-PYTHON Results As Reference
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read MNE-PYTHON Results As Reference >>>>>>>>>>>>>>>>>>>>>>>>>\n");
ref_in_raw = FiffRawData(t_fileRef);
//
// Set up pick list: MEG + STI 014 - bad channels
//
//
picks = ref_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, ref_in_raw.info.bads); // prefer member function
if(picks.cols() == 0)
{
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = ref_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, ref_in_raw.info.bads);// prefer member function
if(picks.cols() == 0)
{
printf("channel list may need modification\n");
}
}
for(first = from; first < to; first+=quantum)
{
last = first+quantum-1;
if (last > to)
{
last = to;
}
if (!ref_in_raw.read_raw_segment(ref_in_data,ref_in_times,first,last/*,picks*/))
{
printf("error during read_raw_segment\n");
}
}
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read MNE-PYTHON Results Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestFiffRFR::compareData()
{
MatrixXd data_diff = first_in_data - ref_in_data;
// std::cout << "\tCompare data:\n";
// std::cout << "\tFirst data\n" << first_in_data.block(0,0,4,4) << "\n";
// std::cout << "\tSecond data\n" << second_in_data.block(0,0,4,4) << "\n";
QVERIFY( data_diff.sum() < epsilon );
}
//*************************************************************************************************************
void TestFiffRFR::compareTimes()
{
MatrixXd times_diff = first_in_times - ref_in_times;
// std::cout << "\tCompare Times:\n";
// std::cout << "\tFirst times\n" << first_in_times.block(0,0,1,4) << "\n";
// std::cout << "\tSecond times\n" << second_in_times.block(0,0,1,4) << "\n";
QVERIFY( times_diff.sum() < epsilon );
}
//*************************************************************************************************************
void TestFiffRFR::compareInfo()
{
//Sampling frequency
std::cout << "[1] Sampling Frequency Check\n";
QVERIFY( first_in_raw.info.sfreq == ref_in_raw.info.sfreq );
//Projection
std::cout << "[2] Projection Check\n";
QVERIFY( first_in_raw.info.projs.size() == ref_in_raw.info.projs.size() );
for( qint32 i = 0; i < first_in_raw.info.projs.size(); ++i )
{
std::cout << "Projector " << i << std::endl;
MatrixXd tmp = first_in_raw.info.projs[i].data->data - ref_in_raw.info.projs[i].data->data;
QVERIFY( tmp.sum() < epsilon );
}
//Compensators
std::cout << "[3] Compensator Check\n";
QVERIFY( first_in_raw.info.comps.size() == ref_in_raw.info.comps.size() );
for( qint32 i = 0; i < first_in_raw.info.comps.size(); ++i )
{
std::cout << "Compensator " << i << std::endl;
MatrixXd tmp = first_in_raw.info.comps[i].data->data - ref_in_raw.info.comps[i].data->data;
QVERIFY( tmp.sum() < epsilon );
}
}
//*************************************************************************************************************
void TestFiffRFR::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_GUILESS_MAIN(TestFiffRFR)
#include "test_rtfilter_filterdata.moc"
<commit_msg>test_rtfilter: working test; open: still have to get short file working<commit_after>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date 12, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Ruben Dörfel and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief test for filterData function that calls rtproceesing and utils library.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>
#include <utils/ioutils.h>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestFiffRFR
*
* @brief The TestFiffRFR class provides read filter read fiff verification tests
*
*/
class TestFiffRFR: public QObject
{
Q_OBJECT
public:
TestFiffRFR();
private slots:
void initTestCase();
void compareData();
void compareTimes();
void compareInfo();
void cleanupTestCase();
private:
double epsilon;
FiffRawData first_in_raw;
MatrixXd first_in_data;
MatrixXd first_in_times;
MatrixXd first_filtered;
FiffRawData ref_in_raw;
MatrixXd ref_in_data;
MatrixXd ref_in_times;
MatrixXd ref_filtered;
};
//*************************************************************************************************************
TestFiffRFR::TestFiffRFR()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestFiffRFR::initTestCase()
{
qDebug() << "Epsilon" << epsilon;
QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
QFile t_fileRef(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/ref_rtfilter_filterdata_raw.fif"); //Einlesen mne-cpp, schreiben mne-python
QFile t_fileOut(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/rtfilter_filterdata_out_raw.fif"); //schreiben mne-cpp, einlesen mne-python
//
// Make sure test folder exists
//
QFileInfo t_fileOutInfo(t_fileOut);
QDir().mkdir(t_fileOutInfo.path());
//*********************************************************************************************************
// First Read, Filter & Write
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read, Filter & Write >>>>>>>>>>>>>>>>>>>>>>>>>\n");
//
// Setup for reading the raw data
//
first_in_raw = FiffRawData(t_fileIn);
//
// Set up pick list: MEG + STI 014 - bad channels
//
bool want_meg = true;
bool want_eeg = false;
bool want_stim = false;
QStringList include;
include << "STI 014";
MatrixXi picks = first_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, first_in_raw.info.bads); // prefer member function
if(picks.cols() == 0)
{
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = first_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, first_in_raw.info.bads);// prefer member function
if(picks.cols() == 0)
{
printf("channel list may need modification\n");
}
}
//
RowVectorXd cals;
FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut,first_in_raw.info, cals/*, picks*/);
//
// Set up the reading parameters
// To read the whole file at once set
//
fiff_int_t from = first_in_raw.first_samp;
fiff_int_t to = first_in_raw.last_samp;
fiff_int_t quantum = to-from+1;
RtFilter rtFilter; // filter object
// channel selection - in this case use every channel
// size = number of channels; value = index channel number
QVector<int> channelList(first_in_raw.info.nchan);
for (int i = 0; i < first_in_raw.info.nchan; i++){
channelList[i] = i;
}
// initialize filter settings
QString filter_name = "example_cosine";
FilterData::FilterType type = FilterData::BPF;
double sFreq = first_in_raw.info.sfreq; // get Sample freq from Data
double centerfreq = 10/(sFreq/2.0); // normed to nyquist freq.
double bandwidth = 10/(sFreq/2.0);
double parkswidth = 1/(sFreq/2.0);
int order = 8192;
int fftlength = 16384;
//
// Read and write all the data
//
bool first_buffer = true;
fiff_int_t first, last;
for(first = from; first < to; first+=quantum)
{
last = first+quantum-1;
if (last > to)
{
last = to;
}
if (!first_in_raw.read_raw_segment(first_in_data,first_in_times,first,last/*,picks*/))
{
printf("error during read_raw_segment\n");
}
//Filtering
printf("Filtering...");
first_filtered = rtFilter.filterData(first_in_data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList,order, fftlength);
printf("[done]\n");
printf("Writing...");
if (first_buffer)
{
if (first > 0)
outfid->write_int(FIFF_FIRST_SAMPLE,&first);
first_buffer = false;
}
outfid->write_raw_buffer(first_filtered,cals);
printf("[done]\n");
}
outfid->finish_writing_raw();
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read, Filter & Write Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
//*********************************************************************************************************
// Read MNE-PYTHON Results As Reference
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read MNE-PYTHON Results As Reference >>>>>>>>>>>>>>>>>>>>>>>>>\n");
ref_in_raw = FiffRawData(t_fileRef);
//
// Set up pick list: MEG + STI 014 - bad channels
//
//
picks = ref_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, ref_in_raw.info.bads); // prefer member function
if(picks.cols() == 0)
{
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = ref_in_raw.info.pick_types(want_meg, want_eeg, want_stim, include, ref_in_raw.info.bads);// prefer member function
if(picks.cols() == 0)
{
printf("channel list may need modification\n");
}
}
for(first = from; first < to; first+=quantum)
{
last = first+quantum-1;
if (last > to)
{
last = to;
}
if (!ref_in_raw.read_raw_segment(ref_filtered,ref_in_times,first,last/*,picks*/))
{
printf("error during read_raw_segment\n");
}
}
// QString refFileName(QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/ref_rtfilter_filterdata_raw.txt");
// IOUtils::read_eigen_matrix(ref_filtered, refFileName);
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read MNE-PYTHON Results Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestFiffRFR::compareData()
{
MatrixXd data_diff = first_filtered - ref_filtered;
// std::cout << "\tCompare data:\n";
// std::cout << "\tFirst data\n" << first_in_data.block(0,0,4,4) << "\n";
// std::cout << "\tSecond data\n" << second_in_data.block(0,0,4,4) << "\n";
printf("diff: ..%f",data_diff.sum());
QVERIFY( data_diff.sum() < epsilon );
}
//*************************************************************************************************************
void TestFiffRFR::compareTimes()
{
MatrixXd times_diff = first_in_times - ref_in_times;
// std::cout << "\tCompare Times:\n";
// std::cout << "\tFirst times\n" << first_in_times.block(0,0,1,4) << "\n";
// std::cout << "\tSecond times\n" << second_in_times.block(0,0,1,4) << "\n";
QVERIFY( times_diff.sum() < epsilon );
}
//*************************************************************************************************************
void TestFiffRFR::compareInfo()
{
//Sampling frequency
std::cout << "[1] Sampling Frequency Check\n";
QVERIFY( first_in_raw.info.sfreq == ref_in_raw.info.sfreq );
//Projection
std::cout << "[2] Projection Check\n";
QVERIFY( first_in_raw.info.projs.size() == ref_in_raw.info.projs.size() );
for( qint32 i = 0; i < first_in_raw.info.projs.size(); ++i )
{
std::cout << "Projector " << i << std::endl;
MatrixXd tmp = first_in_raw.info.projs[i].data->data - ref_in_raw.info.projs[i].data->data;
QVERIFY( tmp.sum() < epsilon );
}
//Compensators
std::cout << "[3] Compensator Check\n";
QVERIFY( first_in_raw.info.comps.size() == ref_in_raw.info.comps.size() );
for( qint32 i = 0; i < first_in_raw.info.comps.size(); ++i )
{
std::cout << "Compensator " << i << std::endl;
MatrixXd tmp = first_in_raw.info.comps[i].data->data - ref_in_raw.info.comps[i].data->data;
QVERIFY( tmp.sum() < epsilon );
}
}
//*************************************************************************************************************
void TestFiffRFR::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_GUILESS_MAIN(TestFiffRFR)
#include "test_rtfilter_filterdata.moc"
<|endoftext|> |
<commit_before>/** feature-selection.cc ---
*
* Copyright (C) 2011 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <iostream>
#include <fstream>
#include <memory>
#include <stdio.h>
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/range/algorithm/find.hpp>
#include <boost/range/irange.hpp>
#include <opencog/util/Logger.h>
#include <opencog/comboreduct/table/table.h>
#include <opencog/comboreduct/table/table_io.h>
#include <opencog/learning/moses/optimization/hill-climbing.h> // for hc_params
#include "feature-selection.h"
#include "../algo/deme_optimize.h"
#include "../algo/incremental.h"
#include "../algo/random.h"
#include "../algo/simple.h"
#include "../algo/stochastic_max_dependency.h"
namespace opencog {
using namespace combo;
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope
void err_empty_features(const string& outfile)
{
// If the dataset is degenerate, it can happen that feature
// selection will fail to find any features. Rather than just
// crashing as a result, write out an empty file, which at least
// allows downstream processes to infer what happened (i.e. to tell
// apart this case from an outright crash.)
logger().warn() << "No features have been selected.";
cerr << "No features have been selected." << endl;
if (!outfile.empty()) {
ofstream out(outfile.c_str());
out << "# No features have been selected." << endl;
}
exit(0);
}
// Score all individual features of Table
vector<double> score_individual_features(const Table& table,
const feature_selection_parameters& fs_params)
{
typedef set<arity_t> FS;
CTable ctable = table.compressed();
fs_scorer<FS> fs_sc(ctable, fs_params);
vector<double> res;
boost::transform(boost::irange(0, table.get_arity()), back_inserter(res),
[&](arity_t idx) { FS fs = {idx}; return fs_sc(fs); });
return res;
}
// log the set of features and its number
void log_selected_features(arity_t old_arity, const Table& ftable,
const feature_selection_parameters& fs_params)
{
// log the number selected features
logger().info("%d out of %d features have been selected",
ftable.get_arity(), old_arity);
// log set of selected feature set
const string_seq& labs = ftable.itable.get_labels();
const vector<double>& sco = score_individual_features(ftable, fs_params);
for (unsigned i=0; i<labs.size(); i++)
{
logger().info() << "log_selected_features(): " << labs[i] << " " << sco[i];
}
}
/**
* Get indices (aka positions or offsets) of a list of labels given a header
*/
vector<unsigned> get_indices(const vector<string>& labels,
const vector<string>& header)
{
vector<unsigned> res;
for (unsigned i = 0; i < header.size(); ++i)
if (boost::find(labels, header[i]) != labels.end())
res.push_back(i);
return res;
}
unsigned get_index(const string& label, const vector<string>& header)
{
return distance(header.begin(), boost::find(header, label));
}
void write_results(const Table& selected_table,
const feature_selection_parameters& fs_params)
{
Table table_wff = selected_table;
if (fs_params.output_file.empty())
ostreamTable(cout, table_wff);
else
saveTable(fs_params.output_file, table_wff);
}
feature_set initial_features(const vector<string>& ilabels,
const feature_selection_parameters& fs_params)
{
vector<string> vif; // valid initial features, used for logging
feature_set res;
for (const string& f : fs_params.initial_features) {
size_t idx = distance(ilabels.begin(), boost::find(ilabels, f));
if(idx < ilabels.size()) { // feature found
res.insert(idx);
// for logging
vif += f;
}
else // feature not found
logger().warn("No such a feature %s in file %s. It will be ignored as initial feature.", f.c_str(), fs_params.input_file.c_str());
}
// Logger
if(vif.empty())
logger().info("The search will start with the empty feature set");
else {
stringstream ss;
ss << "The search will start with the following feature set: ";
ostreamContainer(ss, vif, ",");
logger().info(ss.str());
}
// ~Logger
return res;
}
feature_set_pop select_feature_sets(const CTable& ctable,
const feature_selection_parameters& fs_params)
{
if (fs_params.algorithm == moses::hc) {
// setting moses optimization parameters
double pop_size_ratio = 20;
size_t max_dist = 4;
score_t min_score_improv = 0.0;
optim_parameters op_params;
op_params.opt_algo = moses::hc;
op_params.pop_size_ratio = pop_size_ratio;
op_params.terminate_if_gte = fs_params.hc_max_score;
op_params.max_dist = max_dist;
op_params.set_min_score_improv(min_score_improv);
hc_parameters hc_params;
hc_params.widen_search = fs_params.hc_widen_search;
hc_params.single_step = false;
hc_params.crossover = fs_params.hc_crossover;
hc_params.crossover_pop_size = fs_params.hc_crossover_pop_size;
hc_params.crossover_min_neighbors = fs_params.hc_crossover_min_neighbors;
hc_params.prefix_stat_deme = "FSDemes";
hill_climbing hc(op_params, hc_params);
return moses_select_feature_sets(ctable, hc, fs_params);
} else if (fs_params.algorithm == "inc") {
return incremental_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "smd") {
return smd_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "random") {
return random_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "simple") {
return simple_select_feature_sets(ctable, fs_params);
} else {
cerr << "Fatal Error: Algorithm '" << fs_params.algorithm
<< "' is unknown, please consult the help for the "
<< "list of algorithms." << endl;
exit(1);
return feature_set_pop(); // to please Mr compiler
}
}
feature_set select_features(const CTable& ctable,
const feature_selection_parameters& fs_params)
{
feature_set_pop fs_pop = select_feature_sets(ctable, fs_params);
OC_ASSERT(!fs_pop.empty(), "There might a bug");
return fs_pop.begin()->second;
}
feature_set select_features(const Table& table,
const feature_selection_parameters& fs_params)
{
CTable ctable = table.compressed();
return select_features(ctable, fs_params);
}
void feature_selection(const Table& table,
const feature_selection_parameters& fs_params)
{
// Select the best features
feature_set selected_features = select_features(table, fs_params);
// Add the enforced features
if (!fs_params.force_features_str.empty()) {
vector<unsigned> force_idxs =
get_indices(fs_params.force_features_str, table.itable.get_labels());
select_features.insert(force_idxs.begin(), force_idxs.end());
}
// Write the features (in log and output)
if (selected_features.empty())
err_empty_features(fs_params.output_file);
else {
Table filt_table = table.filtered(selected_features);
log_selected_features(table.get_arity(), filt_table, fs_params);
write_results(filt_table, fs_params);
}
}
} // ~namespace opencog
<commit_msg>Fix force feature in feature selection<commit_after>/** feature-selection.cc ---
*
* Copyright (C) 2011 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <iostream>
#include <fstream>
#include <memory>
#include <stdio.h>
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/range/algorithm/find.hpp>
#include <boost/range/irange.hpp>
#include <opencog/util/Logger.h>
#include <opencog/comboreduct/table/table.h>
#include <opencog/comboreduct/table/table_io.h>
#include <opencog/learning/moses/optimization/hill-climbing.h> // for hc_params
#include "feature-selection.h"
#include "../algo/deme_optimize.h"
#include "../algo/incremental.h"
#include "../algo/random.h"
#include "../algo/simple.h"
#include "../algo/stochastic_max_dependency.h"
namespace opencog {
using namespace combo;
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope
void err_empty_features(const string& outfile)
{
// If the dataset is degenerate, it can happen that feature
// selection will fail to find any features. Rather than just
// crashing as a result, write out an empty file, which at least
// allows downstream processes to infer what happened (i.e. to tell
// apart this case from an outright crash.)
logger().warn() << "No features have been selected.";
cerr << "No features have been selected." << endl;
if (!outfile.empty()) {
ofstream out(outfile.c_str());
out << "# No features have been selected." << endl;
}
exit(0);
}
// Score all individual features of Table
vector<double> score_individual_features(const Table& table,
const feature_selection_parameters& fs_params)
{
typedef set<arity_t> FS;
CTable ctable = table.compressed();
fs_scorer<FS> fs_sc(ctable, fs_params);
vector<double> res;
boost::transform(boost::irange(0, table.get_arity()), back_inserter(res),
[&](arity_t idx) { FS fs = {idx}; return fs_sc(fs); });
return res;
}
// log the set of features and its number
void log_selected_features(arity_t old_arity, const Table& ftable,
const feature_selection_parameters& fs_params)
{
// log the number selected features
logger().info("%d out of %d features have been selected",
ftable.get_arity(), old_arity);
// log set of selected feature set
const string_seq& labs = ftable.itable.get_labels();
const vector<double>& sco = score_individual_features(ftable, fs_params);
for (unsigned i=0; i<labs.size(); i++)
{
logger().info() << "log_selected_features(): " << labs[i] << " " << sco[i];
}
}
void write_results(const Table& selected_table,
const feature_selection_parameters& fs_params)
{
Table table_wff = selected_table;
if (fs_params.output_file.empty())
ostreamTable(cout, table_wff);
else
saveTable(fs_params.output_file, table_wff);
}
feature_set initial_features(const vector<string>& ilabels,
const feature_selection_parameters& fs_params)
{
vector<string> vif; // valid initial features, used for logging
feature_set res;
for (const string& f : fs_params.initial_features) {
size_t idx = distance(ilabels.begin(), boost::find(ilabels, f));
if(idx < ilabels.size()) { // feature found
res.insert(idx);
// for logging
vif += f;
}
else // feature not found
logger().warn("No such a feature %s in file %s. It will be ignored as initial feature.", f.c_str(), fs_params.input_file.c_str());
}
// Logger
if(vif.empty())
logger().info("The search will start with the empty feature set");
else {
stringstream ss;
ss << "The search will start with the following feature set: ";
ostreamContainer(ss, vif, ",");
logger().info(ss.str());
}
// ~Logger
return res;
}
feature_set_pop select_feature_sets(const CTable& ctable,
const feature_selection_parameters& fs_params)
{
if (fs_params.algorithm == moses::hc) {
// setting moses optimization parameters
double pop_size_ratio = 20;
size_t max_dist = 4;
score_t min_score_improv = 0.0;
optim_parameters op_params;
op_params.opt_algo = moses::hc;
op_params.pop_size_ratio = pop_size_ratio;
op_params.terminate_if_gte = fs_params.hc_max_score;
op_params.max_dist = max_dist;
op_params.set_min_score_improv(min_score_improv);
hc_parameters hc_params;
hc_params.widen_search = fs_params.hc_widen_search;
hc_params.single_step = false;
hc_params.crossover = fs_params.hc_crossover;
hc_params.crossover_pop_size = fs_params.hc_crossover_pop_size;
hc_params.crossover_min_neighbors = fs_params.hc_crossover_min_neighbors;
hc_params.prefix_stat_deme = "FSDemes";
hill_climbing hc(op_params, hc_params);
return moses_select_feature_sets(ctable, hc, fs_params);
} else if (fs_params.algorithm == "inc") {
return incremental_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "smd") {
return smd_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "random") {
return random_select_feature_sets(ctable, fs_params);
} else if (fs_params.algorithm == "simple") {
return simple_select_feature_sets(ctable, fs_params);
} else {
cerr << "Fatal Error: Algorithm '" << fs_params.algorithm
<< "' is unknown, please consult the help for the "
<< "list of algorithms." << endl;
exit(1);
return feature_set_pop(); // to please Mr compiler
}
}
feature_set select_features(const CTable& ctable,
const feature_selection_parameters& fs_params)
{
feature_set_pop fs_pop = select_feature_sets(ctable, fs_params);
OC_ASSERT(!fs_pop.empty(), "There might a bug");
return fs_pop.begin()->second;
}
feature_set select_features(const Table& table,
const feature_selection_parameters& fs_params)
{
CTable ctable = table.compressed();
return select_features(ctable, fs_params);
}
void feature_selection(const Table& table,
const feature_selection_parameters& fs_params)
{
// Select the best features
feature_set selected_features = select_features(table, fs_params);
// Add the enforced features
if (!fs_params.force_features_str.empty()) {
vector<unsigned> force_idxs =
get_indices(fs_params.force_features_str, table.itable.get_labels());
selected_features.insert(force_idxs.begin(), force_idxs.end());
}
// Write the features (in log and output)
if (selected_features.empty())
err_empty_features(fs_params.output_file);
else {
Table filt_table = table.filtered(selected_features);
log_selected_features(table.get_arity(), filt_table, fs_params);
write_results(filt_table, fs_params);
}
}
} // ~namespace opencog
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkNormalDistributionImageSource_hxx
#define itkNormalDistributionImageSource_hxx
#include "itkNormalDistributionImageSource.h"
#include "itkNormalVariateGenerator.h"
#include "itkImageScanlineIterator.h"
#include "itkProgressReporter.h"
namespace itk
{
template< typename TImage >
NormalDistributionImageSource< TImage >
::NormalDistributionImageSource()
{
}
template< typename TImage >
void
NormalDistributionImageSource< TImage >
::PrintSelf( std::ostream& os, Indent indent ) const
{
Superclass::PrintSelf( os, indent );
}
template< typename TImage >
void
NormalDistributionImageSource< TImage >
::DynamicThreadedGenerateData( const OutputRegionType & outputRegion )
{
ImageType * output = this->GetOutput();
typedef itk::Statistics::NormalVariateGenerator NormalGeneratorType;
NormalGeneratorType::Pointer normalGenerator = NormalGeneratorType::New();
normalGenerator->Initialize( 101 );
const SizeValueType size0 = outputRegion.GetSize( 0 );
if( size0 == 0 )
{
return;
}
const SizeValueType numberOfLinesToProcess = outputRegion.GetNumberOfPixels() / size0;
typedef ImageScanlineIterator< ImageType > IteratorType;
IteratorType it( output, outputRegion );
ProgressReporter progress( this, 0, numberOfLinesToProcess );
while( !it.IsAtEnd() )
{
while( !it.IsAtEndOfLine() )
{
it.Set( normalGenerator->GetVariate() );
++it;
}
it.NextLine();
progress.CompletedPixel();
}
}
} // end namespace itk
#endif // itkNormalDistributionImageSource_hxx
<commit_msg>ENH: Remove pixelwise progress report<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkNormalDistributionImageSource_hxx
#define itkNormalDistributionImageSource_hxx
#include "itkNormalDistributionImageSource.h"
#include "itkNormalVariateGenerator.h"
#include "itkImageScanlineIterator.h"
namespace itk
{
template< typename TImage >
NormalDistributionImageSource< TImage >
::NormalDistributionImageSource()
{
}
template< typename TImage >
void
NormalDistributionImageSource< TImage >
::PrintSelf( std::ostream& os, Indent indent ) const
{
Superclass::PrintSelf( os, indent );
}
template< typename TImage >
void
NormalDistributionImageSource< TImage >
::DynamicThreadedGenerateData( const OutputRegionType & outputRegion )
{
ImageType * output = this->GetOutput();
typedef itk::Statistics::NormalVariateGenerator NormalGeneratorType;
NormalGeneratorType::Pointer normalGenerator = NormalGeneratorType::New();
normalGenerator->Initialize( 101 );
const SizeValueType size0 = outputRegion.GetSize( 0 );
if( size0 == 0 )
{
return;
}
const SizeValueType numberOfLinesToProcess = outputRegion.GetNumberOfPixels() / size0;
typedef ImageScanlineIterator< ImageType > IteratorType;
IteratorType it( output, outputRegion );
while( !it.IsAtEnd() )
{
while( !it.IsAtEndOfLine() )
{
it.Set( normalGenerator->GetVariate() );
++it;
}
it.NextLine();
}
}
} // end namespace itk
#endif // itkNormalDistributionImageSource_hxx
<|endoftext|> |
<commit_before>#include <fhe/FHEContext.h>
#include <fhe/FHE.h>
#include <fhe/NumbTh.h>
#include <fhe/EncryptedArray.h>
#include <fhe/replicate.h>
#include <utils/FileUtils.hpp>
#include <utils/timer.hpp>
#include <utils/encoding.hpp>
#include <protocol/Gt.hpp>
#include <thread>
#include <atomic>
#ifdef FHE_THREADS
long WORKER_NR = 8;
#else // ifdef FHE_THREADS
long WORKER_NR = 1;
#endif // ifdef FHE_THREADS
MDL::EncVector sum_ctxts(const std::vector<MDL::EncVector>& ctxts)
{
std::vector<std::thread> workers;
std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey());
std::atomic<size_t> counter(WORKER_NR);
MDL::Timer timer;
timer.start();
for (long i = 0; i < WORKER_NR; i++) {
partials[i] = ctxts[i];
workers.push_back(std::move(std::thread([&counter, &ctxts]
(MDL::EncVector& ct) {
size_t next;
while ((next = counter.fetch_add(1)) < ctxts.size()) {
ct += ctxts[next];
}
}, std::ref(partials[i]))));
}
for (auto && wr : workers) wr.join();
for (long i = 1; i < WORKER_NR; i++) {
partials[0] += partials[i];
}
timer.end();
printf("Sum %zd ctxts with %ld workers costed %f sec\n", ctxts.size(),
WORKER_NR, timer.second());
return partials[0];
}
std::pair<MDL::EncVector, long>load_file(const EncryptedArray& ea,
const FHEPubKey & pk)
{
auto data = load_csv("adult.data", 11);
std::vector<MDL::EncVector> ctxts(data.rows(), pk);
std::atomic<size_t> counter(0);
std::vector<std::thread> workers;
MDL::Timer timer;
timer.start();
for (long wr = 0; wr < WORKER_NR; wr++) {
workers.push_back(std::move(std::thread([&counter, &ea,
&ctxts, &data]() {
size_t next;
while ((next = counter.fetch_add(1)) < data.rows()) {
auto indicator = MDL::encoding::staircase(data[next][0], ea);
ctxts[next].pack(indicator, ea);
}
})));
}
timer.end();
printf("Encrypt %ld records with %ld workers costed %f sec.\n",
data.rows(), WORKER_NR, timer.second());
for (auto && wr : workers) wr.join();
return { sum_ctxts(ctxts), data.rows() };
}
std::vector<MDL::GTResult>k_percentile(const MDL::EncVector& ctxt,
const FHEPubKey& pk,
const EncryptedArray& ea,
long N, long k)
{
MDL::Timer timer;
MDL::EncVector oth(pk);
long kpercentile = k * N / 100;
MDL::Vector<long> percentile(ea.size(), kpercentile);
long plainSpace = ea.getContext().alMod.getPPowR();
long domain = N;
std::vector<MDL::GTResult> gtresults(domain);
std::atomic<size_t> counter(0);
std::vector<std::thread> workers;
oth.pack(percentile, ea);
timer.start();
for (long wr = 0; wr < WORKER_NR; wr++) {
workers.push_back(std::thread([&ctxt, &ea, &counter, &oth,
&domain, &plainSpace, >results]() {
size_t d;
while ((d = counter.fetch_add(1)) < domain) {
auto tmp(ctxt);
replicate(ea, tmp, d);
MDL::GTInput input = { oth, tmp, domain, plainSpace };
gtresults[d] = MDL::GT(input, ea);
}
}));
}
for (auto& wr : workers) wr.join();
timer.end();
printf("call GT on Domain %ld used %ld workers costed %f second\n",
domain, WORKER_NR, timer.second());
return gtresults;
}
int main(int argc, char *argv[]) {
long m, p, r, L;
ArgMapping argmap;
argmap.arg("m", m, "m");
argmap.arg("L", L, "L");
argmap.arg("p", p, "p");
argmap.arg("r", r, "r");
argmap.parse(argc, argv);
FHEcontext context(m, p, r);
buildModChain(context, L);
FHESecKey sk(context);
sk.GenSecKey(64);
addSome1DMatrices(sk);
FHEPubKey pk = sk;
auto G = context.alMod.getFactorsOverZZ()[0];
EncryptedArray ea(context, G);
auto data = load_file(ea, pk);
long kpercent = 50;
auto gtresults = k_percentile(data.first, pk, ea,
data.second, kpercent);
bool prev = true;
for (int d = 0; d < gtresults.size(); d++) {
bool current = MDL::decrypt_gt_result(gtresults[d], sk, ea);
if (prev && !current) {
printf("%ld-percentile is %d\n", kpercent, d);
break;
}
prev = current;
}
return 0;
}
<commit_msg>bug fix<commit_after>#include <fhe/FHEContext.h>
#include <fhe/FHE.h>
#include <fhe/NumbTh.h>
#include <fhe/EncryptedArray.h>
#include <fhe/replicate.h>
#include <utils/FileUtils.hpp>
#include <utils/timer.hpp>
#include <utils/encoding.hpp>
#include <protocol/Gt.hpp>
#include <thread>
#include <atomic>
#ifdef FHE_THREADS
long WORKER_NR = 8;
#else // ifdef FHE_THREADS
long WORKER_NR = 1;
#endif // ifdef FHE_THREADS
MDL::EncVector sum_ctxts(const std::vector<MDL::EncVector>& ctxts)
{
std::vector<std::thread> workers;
std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey());
std::atomic<size_t> counter(WORKER_NR);
MDL::Timer timer;
timer.start();
for (long i = 0; i < WORKER_NR; i++) {
partials[i] = ctxts[i];
workers.push_back(std::move(std::thread([&counter, &ctxts]
(MDL::EncVector& ct) {
size_t next;
while ((next = counter.fetch_add(1)) < ctxts.size()) {
ct += ctxts[next];
}
}, std::ref(partials[i]))));
}
for (auto && wr : workers) wr.join();
for (long i = 1; i < WORKER_NR; i++) {
partials[0] += partials[i];
}
timer.end();
printf("Sum %zd ctxts with %ld workers costed %f sec\n", ctxts.size(),
WORKER_NR, timer.second());
return partials[0];
}
std::pair<MDL::EncVector, long>load_file(const EncryptedArray& ea,
const FHEPubKey & pk)
{
auto data = load_csv("adult.data", 2000);
std::vector<MDL::EncVector> ctxts(data.rows(), pk);
std::atomic<size_t> counter(0);
std::vector<std::thread> workers;
MDL::Timer timer;
timer.start();
for (long wr = 0; wr < WORKER_NR; wr++) {
workers.push_back(std::move(std::thread([&counter, &ea,
&ctxts, &data]() {
size_t next;
while ((next = counter.fetch_add(1)) < data.rows()) {
auto indicator = MDL::encoding::staircase(data[next][0], ea);
ctxts[next].pack(indicator, ea);
}
})));
}
timer.end();
for (auto && wr : workers) wr.join();
printf("Encrypt %ld records with %ld workers costed %f sec.\n",
data.rows(), WORKER_NR, timer.second());
return { sum_ctxts(ctxts), data.rows() };
}
std::vector<MDL::GTResult>k_percentile(const MDL::EncVector& ctxt,
const FHEPubKey & pk,
const EncryptedArray& ea,
long records_nr,
long domain,
long k)
{
MDL::Timer timer;
MDL::EncVector oth(pk);
long kpercentile = k * records_nr / 100;
MDL::Vector<long> percentile(ea.size(), kpercentile);
long plainSpace = ea.getContext().alMod.getPPowR();
std::vector<MDL::GTResult> gtresults(domain);
std::atomic<size_t> counter(0);
std::vector<std::thread> workers;
oth.pack(percentile, ea);
timer.start();
for (long wr = 0; wr < WORKER_NR; wr++) {
workers.push_back(std::thread([&ctxt, &ea, &counter, &oth, &records_nr,
&domain, &plainSpace, >results]() {
size_t d;
while ((d = counter.fetch_add(1)) < domain) {
auto tmp(ctxt);
replicate(ea, tmp, d);
MDL::GTInput input = { oth, tmp, records_nr, plainSpace };
gtresults[d] = MDL::GT(input, ea);
}
}));
}
for (auto& wr : workers) wr.join();
timer.end();
printf("call GT on Domain %ld used %ld workers costed %f second\n",
records_nr, WORKER_NR, timer.second());
return gtresults;
}
int main(int argc, char *argv[]) {
long m, p, r, L;
ArgMapping argmap;
argmap.arg("m", m, "m");
argmap.arg("L", L, "L");
argmap.arg("p", p, "p");
argmap.arg("r", r, "r");
argmap.parse(argc, argv);
FHEcontext context(m, p, r);
buildModChain(context, L);
FHESecKey sk(context);
sk.GenSecKey(64);
addSome1DMatrices(sk);
FHEPubKey pk = sk;
auto G = context.alMod.getFactorsOverZZ()[0];
EncryptedArray ea(context, G);
auto data = load_file(ea, pk);
long kpercent = 50;
auto gtresults = k_percentile(data.first,
pk, ea,
data.second,
100,
kpercent);
bool prev = true;
for (int d = 0; d < gtresults.size(); d++) {
bool current = MDL::decrypt_gt_result(gtresults[d], sk, ea);
if (prev && !current) {
printf("%ld-percentile is %d\n", kpercent, d);
break;
}
prev = current;
}
return 0;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// This software module was originally developed by
//
// University of California Santa Barbara, Kapil Chhabra, Yining Deng.
// Mitsubishi Electric ITE-VIL, Leszek Cieplinski.
// (contributing organizations names)
//
// in the course of development of the MPEG-7 Experimentation Model.
//
// This software module is an implementation of a part of one or more MPEG-7
// Experimentation Model tools as specified by the MPEG-7 Requirements.
//
// ISO/IEC gives users of MPEG-7 free license to this software module or
// modifications thereof for use in hardware or software products claiming
// conformance to MPEG-7.
//
// Those intending to use this software module in hardware or software products
// are advised that its use may infringe existing patents. The original
// developer of this software module and his/her company, the subsequent
// editors and their companies, and ISO/IEC have no liability for use of this
// software module or modifications thereof in an implementation.
//
// Copyright is not released for non MPEG-7 conforming products. The
// organizations named above retain full right to use the code for their own
// purpose, assign or donate the code to a third party and inhibit third parties
// from using the code for non MPEG-7 conforming products.
//
// Copyright (c) 1998-2000.
//
// This notice must be included in all copies or derivative works.
//
// Applicable File Name: DominantColor.cpp
//
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <iostream>
#include "DominantColor.h"
using namespace XM;
DominantColorDescriptor::DominantColorDescriptor():
m_DominantColorsNumber(0),
m_ColorSpacePresent(0),
m_ColorQuantizationPresent(0),
m_VariancePresent(1),
m_SpatialCoherency(0),
m_dc(0),
m_ColorSpace(0),
m_Quantizer(0)
{
m_ColorSpace = new ColorSpaceDescriptor();;
m_Quantizer = new ColorQuantizerDescriptor();
}
//----------------------------------------------------------------------------
DominantColorDescriptor::~DominantColorDescriptor()
{
// will be released by the clients!
}
/*
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
ExportDDL(GenericDSInterfaceABC *aParentDescription)
{
int i, j;
vector<int> cvi(3);
vector<int> var(3);
DOMCOL *DC;
GenericDS l_DDLDescription;
GenericDSInterfaceABC *l_DDLDescriptionInterface;
GenericDS SpatCoher, V, Per, ColValInd, Var;
if(!aParentDescription) return (unsigned long) -1;
l_DDLDescription = aParentDescription->CreateChild("Descriptor");
l_DDLDescription.SetAttribute("xsi:type","DominantColorType");
int dc_number = GetDominantColorsNumber();
//l_DDLDescription.SetAttribute("size", dc_number);
l_DDLDescriptionInterface = l_DDLDescription.GetInterface();
bool colspcpres = GetColorSpacePresent();
if(colspcpres) m_ColorSpace->ExportDDL(l_DDLDescriptionInterface);
bool colquantpres = GetColorQuantizationPresent();
if(colquantpres) m_Quantizer->ExportDDL(l_DDLDescriptionInterface);
bool varpres = GetVariancePresent();
SpatCoher = l_DDLDescription.CreateChild("SpatialCoherency");
int spatcoher = GetSpatialCoherency();
SpatCoher.SetValue(spatcoher);
DC = GetDominantColors();
for(i=0; i<dc_number; i++) {
V = l_DDLDescription.CreateChild("Value");
Per = V.CreateChild("Percentage");
Per.SetValue(DC[i].m_Percentage);
ColValInd = V.CreateChild("Index");
for(j=0; j<3; j++) cvi[j] = DC[i].m_ColorValue[j];
ColValInd.SetValue(cvi);
if(varpres==true) {
Var = V.CreateChild("ColorVariance");
for(j=0; j<3; j++) var[j] = DC[i].m_ColorVariance[j];
Var.SetValue(var);
}
}
return 0;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
ImportDDL(GenericDSInterfaceABC *aDescription)
{
int i, j, dc_number, spatcoher, per;
string xsitype, colspcpres, colquantpres, varpres;
GenericDS l_DDLDescription;
GenericDSInterfaceABC *l_DDLDescriptionInterface = NULL;
GenericDS V, Per, ColValInd, Var;
int *percents, **colors, **variances;
if(!aDescription) return (unsigned long) -1;
// if aDescription is of correct type
if(aDescription->GetDSName() == "Descriptor") {
aDescription->GetTextAttribute("xsi:type", xsitype);
if(xsitype == "DominantColorType") {
l_DDLDescriptionInterface = aDescription;
}
}
// else search for DominantColorType as a child
if(!l_DDLDescriptionInterface) {
l_DDLDescription = aDescription->GetDescription("Descriptor");
// search for correct xsi type
while(!l_DDLDescription.isNull()) {
l_DDLDescription.GetTextAttribute("xsi:type", xsitype);
if(xsitype == "DominantColorType") break;
l_DDLDescription.GetNextSibling("Descriptor");
}
// DominantColorType not found
if(!l_DDLDescription.isNull()) return (unsigned long) -1;
// DominantColorType found
l_DDLDescriptionInterface = l_DDLDescription.GetInterface();
}
l_DDLDescriptionInterface->GetIntAttribute("size",dc_number);
SetDominantColorsNumber(dc_number);
GenericDS ColSpc = l_DDLDescriptionInterface->GetDescription("ColorSpace");
if(!ColSpc.isNull()) {
SetColorSpacePresent(true);
m_ColorSpace->ImportDDL(l_DDLDescriptionInterface);
}
else SetColorSpacePresent(false);
GenericDS ColQuant = l_DDLDescriptionInterface->GetDescription("ColorQuantization");
if(!ColQuant.isNull()) {
SetColorQuantizationPresent(true);
m_Quantizer->ImportDDL(l_DDLDescriptionInterface);
}
else SetColorQuantizationPresent(false);
GenericDS VarPres = l_DDLDescriptionInterface->GetDescription("VariancePresent");
VarPres.GetTextValue(varpres);
if(varpres=="true") SetVariancePresent(true);
else SetVariancePresent(false);
GenericDS SpatCoher = l_DDLDescriptionInterface->GetDescription("SpatialCoherency");
SpatCoher.GetIntValue(spatcoher);
SetSpatialCoherency(spatcoher);
// dominant colors
percents = new int[dc_number];
colors = new int*[dc_number];
for(i=0;i<dc_number;i++) colors[i]= new int[3];
variances = new int*[dc_number];
for(i=0;i<dc_number;i++) variances[i]= new int[3];
for(i=0; i<dc_number; i++) {
vector<int> cvi, var;
V = l_DDLDescriptionInterface->GetDescription("Values");
Per = V.GetDescription("Percentage");
Per.GetIntValue(per);
percents[i] = per;
ColValInd = V.GetDescription("ColorValueIndex");
ColValInd.GetIntVector(cvi);
for(j=0; j<3; j++) colors[i][j] = cvi[j];
Var = V.GetDescription("ColorVariance");
if(!Var.isNull()) {
SetVariancePresent(true);
Var.GetIntVector(var);
for(j=0; j<3; j++) variances[i][j] = var[j];
}
else SetVariancePresent(false);
l_DDLDescriptionInterface->RemoveChild(V);
}
SetDominantColors(percents, colors, variances);
delete [] percents;
for(i=0;i<dc_number;i++) delete [] colors[i];
delete [] colors;
for(i=0;i<dc_number;i++) delete [] variances[i];
delete [] variances;
return 0;
}
*/
//----------------------------------------------------------------------------
ColorQuantizerDescriptor * DominantColorDescriptor::
GetColorQuantizerDescriptor(void)
{
return m_Quantizer;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::SetColorQuantizerDescriptor
(ColorQuantizerDescriptor *quantizer)
{
if (!quantizer) return (unsigned long) -1;
if (m_Quantizer == quantizer) return 0;
if (m_Quantizer) delete m_Quantizer;
m_Quantizer = quantizer;
return 0;
}
//----------------------------------------------------------------------------
ColorSpaceDescriptor* DominantColorDescriptor::GetColorSpaceDescriptor()
{
return m_ColorSpace;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
SetColorSpaceDescriptor(ColorSpaceDescriptor *colorspace)
{
if (m_ColorSpace == colorspace) return 0;
if (m_ColorSpace) delete m_ColorSpace;
m_ColorSpace = colorspace;
return 0;
}
//----------------------------------------------------------------------------
int DominantColorDescriptor::GetDominantColorsNumber()
{
return (m_DominantColorsNumber);
}
//----------------------------------------------------------------------------
int DominantColorDescriptor::GetSpatialCoherency()
{
return (m_SpatialCoherency);
}
//----------------------------------------------------------------------------
DOMCOL* DominantColorDescriptor::GetDominantColors()
{
return (m_dc);
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetDominantColorsNumber(int dc_number)
{
if (dc_number != m_DominantColorsNumber) {
if (m_dc)
delete [] m_dc;
m_dc = new DOMCOL[dc_number];
// set values to zero - by mb - may not be crucial here since they are assigned in SetDominantColors() below (no aggregation, etc)
this->resetDescriptor();
m_DominantColorsNumber = dc_number;
}
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetSpatialCoherency(int sc)
{
m_SpatialCoherency = sc;
}
#include <iostream>
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetDominantColors(int *percents, int **colors, int **variances)
{
int j;
// count the colors with nonzero weight
// to cancel the DCs with zero weight
int index = 0;
for( int i = 0; i < m_DominantColorsNumber; i++ )
{
if(percents[i] > 0)
{
m_dc[index].m_Percentage = percents[i];
for(j=0;j<3;j++)
m_dc[index].m_ColorValue[j] = colors[i][j];
if( m_VariancePresent )
for(j=0;j<3;j++)
m_dc[index].m_ColorVariance[j] = variances[i][j];
index++;
}
}
if(index < m_DominantColorsNumber)
{
//std::cerr << "index < mdc" << std::endl;
m_DominantColorsNumber = index;
}
}
void DominantColorDescriptor::resetDescriptor()
{
for( int i = 0; i < m_DominantColorsNumber; i++ ){
this->m_dc[i].m_Percentage = 0;
memset( this->m_dc[i].m_ColorValue, 0, 3*sizeof(int) );
memset( this->m_dc[i].m_ColorVariance, 0, 3*sizeof(int) );
}
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::Print()
{
int i;
std::cerr << "size: " << m_DominantColorsNumber << " (m_DominantColorsNumber)" << std::endl;
std::cerr << "sc: " << m_SpatialCoherency << " (m_SpatialCoherency)" <<std::endl;
std::cerr << "percentage ||| color values ||| color variances" << std::endl;
for(i=0; i<m_DominantColorsNumber; i++)
std::cerr << "value: " << m_dc[i].m_Percentage << " ||| "
<< m_dc[i].m_ColorValue[0] << " "
<< m_dc[i].m_ColorValue[1] << " "
<< m_dc[i].m_ColorValue[2] << " ||| "
<< m_dc[i].m_ColorVariance[0] << " "
<< m_dc[i].m_ColorVariance[1] << " "
<< m_dc[i].m_ColorVariance[2] << std::endl;
}
<commit_msg>Update DominantColor.cpp<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// This software module was originally developed by
//
// University of California Santa Barbara, Kapil Chhabra, Yining Deng.
// Mitsubishi Electric ITE-VIL, Leszek Cieplinski.
// (contributing organizations names)
//
// in the course of development of the MPEG-7 Experimentation Model.
//
// This software module is an implementation of a part of one or more MPEG-7
// Experimentation Model tools as specified by the MPEG-7 Requirements.
//
// ISO/IEC gives users of MPEG-7 free license to this software module or
// modifications thereof for use in hardware or software products claiming
// conformance to MPEG-7.
//
// Those intending to use this software module in hardware or software products
// are advised that its use may infringe existing patents. The original
// developer of this software module and his/her company, the subsequent
// editors and their companies, and ISO/IEC have no liability for use of this
// software module or modifications thereof in an implementation.
//
// Copyright is not released for non MPEG-7 conforming products. The
// organizations named above retain full right to use the code for their own
// purpose, assign or donate the code to a third party and inhibit third parties
// from using the code for non MPEG-7 conforming products.
//
// Copyright (c) 1998-2000.
//
// This notice must be included in all copies or derivative works.
//
// Applicable File Name: DominantColor.cpp
//
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <iostream>
#include "DominantColor.h"
using namespace XM;
DominantColorDescriptor::DominantColorDescriptor():
m_DominantColorsNumber(0),
m_ColorSpacePresent(0),
m_ColorQuantizationPresent(0),
m_VariancePresent(1),
m_SpatialCoherency(0),
m_dc(0),
m_ColorSpace(0),
m_Quantizer(0)
{
m_ColorSpace = new ColorSpaceDescriptor();;
m_Quantizer = new ColorQuantizerDescriptor();
}
//----------------------------------------------------------------------------
DominantColorDescriptor::~DominantColorDescriptor()
{
delete m_dc;
delete m_ColorSpace;
delete m_Quantizer;
}
/*
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
ExportDDL(GenericDSInterfaceABC *aParentDescription)
{
int i, j;
vector<int> cvi(3);
vector<int> var(3);
DOMCOL *DC;
GenericDS l_DDLDescription;
GenericDSInterfaceABC *l_DDLDescriptionInterface;
GenericDS SpatCoher, V, Per, ColValInd, Var;
if(!aParentDescription) return (unsigned long) -1;
l_DDLDescription = aParentDescription->CreateChild("Descriptor");
l_DDLDescription.SetAttribute("xsi:type","DominantColorType");
int dc_number = GetDominantColorsNumber();
//l_DDLDescription.SetAttribute("size", dc_number);
l_DDLDescriptionInterface = l_DDLDescription.GetInterface();
bool colspcpres = GetColorSpacePresent();
if(colspcpres) m_ColorSpace->ExportDDL(l_DDLDescriptionInterface);
bool colquantpres = GetColorQuantizationPresent();
if(colquantpres) m_Quantizer->ExportDDL(l_DDLDescriptionInterface);
bool varpres = GetVariancePresent();
SpatCoher = l_DDLDescription.CreateChild("SpatialCoherency");
int spatcoher = GetSpatialCoherency();
SpatCoher.SetValue(spatcoher);
DC = GetDominantColors();
for(i=0; i<dc_number; i++) {
V = l_DDLDescription.CreateChild("Value");
Per = V.CreateChild("Percentage");
Per.SetValue(DC[i].m_Percentage);
ColValInd = V.CreateChild("Index");
for(j=0; j<3; j++) cvi[j] = DC[i].m_ColorValue[j];
ColValInd.SetValue(cvi);
if(varpres==true) {
Var = V.CreateChild("ColorVariance");
for(j=0; j<3; j++) var[j] = DC[i].m_ColorVariance[j];
Var.SetValue(var);
}
}
return 0;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
ImportDDL(GenericDSInterfaceABC *aDescription)
{
int i, j, dc_number, spatcoher, per;
string xsitype, colspcpres, colquantpres, varpres;
GenericDS l_DDLDescription;
GenericDSInterfaceABC *l_DDLDescriptionInterface = NULL;
GenericDS V, Per, ColValInd, Var;
int *percents, **colors, **variances;
if(!aDescription) return (unsigned long) -1;
// if aDescription is of correct type
if(aDescription->GetDSName() == "Descriptor") {
aDescription->GetTextAttribute("xsi:type", xsitype);
if(xsitype == "DominantColorType") {
l_DDLDescriptionInterface = aDescription;
}
}
// else search for DominantColorType as a child
if(!l_DDLDescriptionInterface) {
l_DDLDescription = aDescription->GetDescription("Descriptor");
// search for correct xsi type
while(!l_DDLDescription.isNull()) {
l_DDLDescription.GetTextAttribute("xsi:type", xsitype);
if(xsitype == "DominantColorType") break;
l_DDLDescription.GetNextSibling("Descriptor");
}
// DominantColorType not found
if(!l_DDLDescription.isNull()) return (unsigned long) -1;
// DominantColorType found
l_DDLDescriptionInterface = l_DDLDescription.GetInterface();
}
l_DDLDescriptionInterface->GetIntAttribute("size",dc_number);
SetDominantColorsNumber(dc_number);
GenericDS ColSpc = l_DDLDescriptionInterface->GetDescription("ColorSpace");
if(!ColSpc.isNull()) {
SetColorSpacePresent(true);
m_ColorSpace->ImportDDL(l_DDLDescriptionInterface);
}
else SetColorSpacePresent(false);
GenericDS ColQuant = l_DDLDescriptionInterface->GetDescription("ColorQuantization");
if(!ColQuant.isNull()) {
SetColorQuantizationPresent(true);
m_Quantizer->ImportDDL(l_DDLDescriptionInterface);
}
else SetColorQuantizationPresent(false);
GenericDS VarPres = l_DDLDescriptionInterface->GetDescription("VariancePresent");
VarPres.GetTextValue(varpres);
if(varpres=="true") SetVariancePresent(true);
else SetVariancePresent(false);
GenericDS SpatCoher = l_DDLDescriptionInterface->GetDescription("SpatialCoherency");
SpatCoher.GetIntValue(spatcoher);
SetSpatialCoherency(spatcoher);
// dominant colors
percents = new int[dc_number];
colors = new int*[dc_number];
for(i=0;i<dc_number;i++) colors[i]= new int[3];
variances = new int*[dc_number];
for(i=0;i<dc_number;i++) variances[i]= new int[3];
for(i=0; i<dc_number; i++) {
vector<int> cvi, var;
V = l_DDLDescriptionInterface->GetDescription("Values");
Per = V.GetDescription("Percentage");
Per.GetIntValue(per);
percents[i] = per;
ColValInd = V.GetDescription("ColorValueIndex");
ColValInd.GetIntVector(cvi);
for(j=0; j<3; j++) colors[i][j] = cvi[j];
Var = V.GetDescription("ColorVariance");
if(!Var.isNull()) {
SetVariancePresent(true);
Var.GetIntVector(var);
for(j=0; j<3; j++) variances[i][j] = var[j];
}
else SetVariancePresent(false);
l_DDLDescriptionInterface->RemoveChild(V);
}
SetDominantColors(percents, colors, variances);
delete [] percents;
for(i=0;i<dc_number;i++) delete [] colors[i];
delete [] colors;
for(i=0;i<dc_number;i++) delete [] variances[i];
delete [] variances;
return 0;
}
*/
//----------------------------------------------------------------------------
ColorQuantizerDescriptor * DominantColorDescriptor::
GetColorQuantizerDescriptor(void)
{
return m_Quantizer;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::SetColorQuantizerDescriptor
(ColorQuantizerDescriptor *quantizer)
{
if (!quantizer) return (unsigned long) -1;
if (m_Quantizer == quantizer) return 0;
if (m_Quantizer) delete m_Quantizer;
m_Quantizer = quantizer;
return 0;
}
//----------------------------------------------------------------------------
ColorSpaceDescriptor* DominantColorDescriptor::GetColorSpaceDescriptor()
{
return m_ColorSpace;
}
//----------------------------------------------------------------------------
unsigned long DominantColorDescriptor::
SetColorSpaceDescriptor(ColorSpaceDescriptor *colorspace)
{
if (m_ColorSpace == colorspace) return 0;
if (m_ColorSpace) delete m_ColorSpace;
m_ColorSpace = colorspace;
return 0;
}
//----------------------------------------------------------------------------
int DominantColorDescriptor::GetDominantColorsNumber()
{
return (m_DominantColorsNumber);
}
//----------------------------------------------------------------------------
int DominantColorDescriptor::GetSpatialCoherency()
{
return (m_SpatialCoherency);
}
//----------------------------------------------------------------------------
DOMCOL* DominantColorDescriptor::GetDominantColors()
{
return (m_dc);
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetDominantColorsNumber(int dc_number)
{
if (dc_number != m_DominantColorsNumber) {
if (m_dc)
delete [] m_dc;
m_dc = new DOMCOL[dc_number];
// set values to zero - by mb - may not be crucial here since they are assigned in SetDominantColors() below (no aggregation, etc)
this->resetDescriptor();
m_DominantColorsNumber = dc_number;
}
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetSpatialCoherency(int sc)
{
m_SpatialCoherency = sc;
}
#include <iostream>
//----------------------------------------------------------------------------
void DominantColorDescriptor::SetDominantColors(int *percents, int **colors, int **variances)
{
int j;
// count the colors with nonzero weight
// to cancel the DCs with zero weight
int index = 0;
for( int i = 0; i < m_DominantColorsNumber; i++ )
{
if(percents[i] > 0)
{
m_dc[index].m_Percentage = percents[i];
for(j=0;j<3;j++)
m_dc[index].m_ColorValue[j] = colors[i][j];
if( m_VariancePresent )
for(j=0;j<3;j++)
m_dc[index].m_ColorVariance[j] = variances[i][j];
index++;
}
}
if(index < m_DominantColorsNumber)
{
//std::cerr << "index < mdc" << std::endl;
m_DominantColorsNumber = index;
}
}
void DominantColorDescriptor::resetDescriptor()
{
for( int i = 0; i < m_DominantColorsNumber; i++ ){
this->m_dc[i].m_Percentage = 0;
memset( this->m_dc[i].m_ColorValue, 0, 3*sizeof(int) );
memset( this->m_dc[i].m_ColorVariance, 0, 3*sizeof(int) );
}
}
//----------------------------------------------------------------------------
void DominantColorDescriptor::Print()
{
int i;
std::cerr << "size: " << m_DominantColorsNumber << " (m_DominantColorsNumber)" << std::endl;
std::cerr << "sc: " << m_SpatialCoherency << " (m_SpatialCoherency)" <<std::endl;
std::cerr << "percentage ||| color values ||| color variances" << std::endl;
for(i=0; i<m_DominantColorsNumber; i++)
std::cerr << "value: " << m_dc[i].m_Percentage << " ||| "
<< m_dc[i].m_ColorValue[0] << " "
<< m_dc[i].m_ColorValue[1] << " "
<< m_dc[i].m_ColorValue[2] << " ||| "
<< m_dc[i].m_ColorVariance[0] << " "
<< m_dc[i].m_ColorVariance[1] << " "
<< m_dc[i].m_ColorVariance[2] << std::endl;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_intersect_minimum_distance_curve_hpp
#define eli_geom_intersect_minimum_distance_curve_hpp
#include <cmath>
#include <vector>
#include <list>
#ifdef Success // X11 #define collides with Eigen
#undef Success
#endif
#include "Eigen/Eigen"
#include "eli/mutil/nls/newton_raphson_constrained_method.hpp"
#include "eli/geom/point/distance.hpp"
namespace eli
{
namespace geom
{
namespace intersect
{
namespace internal
{
template <typename curve__>
struct curve_g_functor
{
const curve__ *pc;
typename curve__::point_type pt;
typename curve__::data_type operator()(const typename curve__::data_type &t) const
{
typename curve__::data_type tt(t);
assert((tt>=0) && (tt<=1));
return (pc->f(tt)-pt).dot(pc->fp(tt));
}
};
template <typename curve__>
struct curve_gp_functor
{
const curve__ *pc;
typename curve__::point_type pt;
typename curve__::data_type operator()(const typename curve__::data_type &t) const
{
typename curve__::data_type tt(t);
assert((tt>=0) && (tt<=1));
typename curve__::point_type fp(pc->fp(tt));
typename curve__::data_type rtn(fp.dot(fp)+pc->fpp(tt).dot(pc->f(tt)-pt));
typename curve__::tolerance_type tol;
if (tol.approximately_equal(rtn, 0))
{
curve_g_functor<curve__> g;
g.pc=pc;
g.pt=pt;
if (t>=1)
{
rtn=(g(1)-g(static_cast<typename curve__::data_type>(0.99)))/static_cast<typename curve__::data_type>(0.01);
}
else if (t<=0)
{
rtn=(g(static_cast<typename curve__::data_type>(0.01))-g(0))/static_cast<typename curve__::data_type>(0.01);
}
else
{
rtn=(g(t+static_cast<typename curve__::data_type>(0.01))-g(t))/static_cast<typename curve__::data_type>(0.01);
}
}
return rtn;
}
};
}
template<typename curve__>
typename curve__::data_type minimum_distance(typename curve__::data_type &t, const curve__ &c, const typename curve__::point_type &pt, const typename curve__::data_type &t0)
{
eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type> nrm;
int stat;
internal::curve_g_functor<curve__> g;
internal::curve_gp_functor<curve__> gp;
typename curve__::data_type dist0, dist;
typename curve__::tolerance_type tol;
// setup the functors
g.pc=&c;
g.pt=pt;
gp.pc=&c;
gp.pt=pt;
// setup the solver
nrm.set_absolute_tolerance(tol.get_absolute_tolerance());
nrm.set_max_iteration(10);
if (c.open())
{
nrm.set_lower_condition(0, eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type>::NRC_EXCLUSIVE);
nrm.set_upper_condition(1, eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type>::NRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(0, 1);
}
// set the initial guess
nrm.set_initial_guess(t0);
dist0=eli::geom::point::distance(c.f(t0), pt);
// find the root
stat = nrm.find_root(t, g, gp, 0);
// if found root and it is within bounds and is closer than initial guess
if (stat==eli::mutil::nls::newton_raphson_method<typename curve__::data_type>::converged)
{
assert((t>=0) && (t<=1));
dist = eli::geom::point::distance(c.f(t), pt);
if (dist<=dist0)
{
return dist;
}
}
else
{
// std::cout << "# not converged!" << std::endl;
}
// couldn't find better answer so return initial guess
t=t0;
return dist0;
}
template<typename curve__>
typename curve__::data_type minimum_distance(typename curve__::data_type &t, const curve__ &c, const typename curve__::point_type &pt)
{
typename curve__::tolerance_type tol;
std::list<std::pair<typename curve__::data_type, typename curve__::data_type>> tinit;
typename std::list<std::pair<typename curve__::data_type, typename curve__::data_type>>::iterator it;
std::pair<typename curve__::data_type, typename curve__::data_type> cand_pair;
// possible that end points are closest, so start by checking them
typename curve__::data_type dist, tt, dd;
// first check is start, middle and (if needed) end points
{
t=0;
dist=eli::geom::point::distance(c.f(t), pt);
tt=0.5;
dd=eli::geom::point::distance(c.f(tt), pt);
if (dd<dist)
{
t=tt;
dist=dd;
}
if (c.open())
{
tt=1;
dd=eli::geom::point::distance(c.f(tt), pt);
if (dd<dist)
{
t=tt;
dist=dd;
}
}
}
cand_pair.first=t;
cand_pair.second=dist;
tinit.push_back(cand_pair);
// need to pick initial guesses
typename curve__::index_type i, deg(c.degree()), ssize;
std::vector<typename curve__::data_type> tsample(2*deg+1);
typename curve__::point_type p0, p1;
typename curve__::data_type temp, tlen;
// determine the sample parameters from the control polygon points
ssize=tsample.size();
i=0;
p1=c.get_control_point(i);
tsample[i]=0;
for (++i; i<=deg; ++i)
{
p0=p1;
p1=c.get_control_point(i);
temp=eli::geom::point::distance(p0, p1)/2;
tsample[2*i-1]=tsample[2*i-2]+temp;
tsample[2*i]=tsample[2*i-1]+temp;
}
tlen=tsample[tsample.size()-1];
// add points that are minimums
{
// find candidate starting locations using distance between sampled points on curve and point
for (i=0; i<ssize; ++i)
{
temp=eli::geom::point::distance(c.f(tsample[i]/tlen), pt);
// std::cout << "point #=" << i << "\tdist_temp=" << temp << std::endl;
if (temp<=1.01*dist)
{
cand_pair.first=tsample[i]/tlen;
cand_pair.second=temp;
tinit.push_back(cand_pair);
if (temp<dist)
{
t=cand_pair.first;
dist=cand_pair.second;
it=tinit.begin();
while (it!=tinit.end())
{
// check to see if distance is beyond new threshold and remove if so
if (it->second>1.01*dist)
{
it=tinit.erase(it);
}
else
{
++it;
}
}
}
// std::cout << "% added point #=" << i << "\twith t=" << tsample[i]/tlen << std::endl;
}
}
}
// std::cout << "# t guesses=" << tinit.size() << std::endl;
// make sure have some solutions to iterate
// tinit.push_back(0);
// if (c.open())
// {
// tinit.push_back(1);
// }
// cycle through all possible minima to find best
for (it=tinit.begin(); it!=tinit.end(); ++it)
{
dd=minimum_distance(tt, c, pt, it->first);
// std::cout << "% completed root starting at" << *it << std::endl;
assert((tt>=0) && (tt<=1));
dd=eli::geom::point::distance(c.f(tt), pt);
// check to see if is closer than previous minimum
if (dd<dist)
{
t=tt;
dist=dd;
}
// std::cout << "# dd=" << dd << std::endl;
// std::cout << "# j=" << j << "\tnj=" << tinit.size() << std::endl;
}
// std::cout << "# returning dist=" << dist << std::endl;
return dist;
}
}
}
}
#endif
<commit_msg>Simplify minimum distance curve with no supplied starting point.<commit_after>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_intersect_minimum_distance_curve_hpp
#define eli_geom_intersect_minimum_distance_curve_hpp
#include <cmath>
#include <vector>
#include <list>
#ifdef Success // X11 #define collides with Eigen
#undef Success
#endif
#include "Eigen/Eigen"
#include "eli/mutil/nls/newton_raphson_constrained_method.hpp"
#include "eli/geom/point/distance.hpp"
namespace eli
{
namespace geom
{
namespace intersect
{
namespace internal
{
template <typename curve__>
struct curve_g_functor
{
const curve__ *pc;
typename curve__::point_type pt;
typename curve__::data_type operator()(const typename curve__::data_type &t) const
{
typename curve__::data_type tt(t);
assert((tt>=0) && (tt<=1));
return (pc->f(tt)-pt).dot(pc->fp(tt));
}
};
template <typename curve__>
struct curve_gp_functor
{
const curve__ *pc;
typename curve__::point_type pt;
typename curve__::data_type operator()(const typename curve__::data_type &t) const
{
typename curve__::data_type tt(t);
assert((tt>=0) && (tt<=1));
typename curve__::point_type fp(pc->fp(tt));
typename curve__::data_type rtn(fp.dot(fp)+pc->fpp(tt).dot(pc->f(tt)-pt));
typename curve__::tolerance_type tol;
if (tol.approximately_equal(rtn, 0))
{
curve_g_functor<curve__> g;
g.pc=pc;
g.pt=pt;
if (t>=1)
{
rtn=(g(1)-g(static_cast<typename curve__::data_type>(0.99)))/static_cast<typename curve__::data_type>(0.01);
}
else if (t<=0)
{
rtn=(g(static_cast<typename curve__::data_type>(0.01))-g(0))/static_cast<typename curve__::data_type>(0.01);
}
else
{
rtn=(g(t+static_cast<typename curve__::data_type>(0.01))-g(t))/static_cast<typename curve__::data_type>(0.01);
}
}
return rtn;
}
};
}
template<typename curve__>
typename curve__::data_type minimum_distance(typename curve__::data_type &t, const curve__ &c, const typename curve__::point_type &pt, const typename curve__::data_type &t0)
{
eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type> nrm;
int stat;
internal::curve_g_functor<curve__> g;
internal::curve_gp_functor<curve__> gp;
typename curve__::data_type dist0, dist;
typename curve__::tolerance_type tol;
// setup the functors
g.pc=&c;
g.pt=pt;
gp.pc=&c;
gp.pt=pt;
// setup the solver
nrm.set_absolute_tolerance(tol.get_absolute_tolerance());
nrm.set_max_iteration(10);
if (c.open())
{
nrm.set_lower_condition(0, eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type>::NRC_EXCLUSIVE);
nrm.set_upper_condition(1, eli::mutil::nls::newton_raphson_constrained_method<typename curve__::data_type>::NRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(0, 1);
}
// set the initial guess
nrm.set_initial_guess(t0);
dist0=eli::geom::point::distance(c.f(t0), pt);
// find the root
stat = nrm.find_root(t, g, gp, 0);
// if found root and it is within bounds and is closer than initial guess
if (stat==eli::mutil::nls::newton_raphson_method<typename curve__::data_type>::converged)
{
assert((t>=0) && (t<=1));
dist = eli::geom::point::distance(c.f(t), pt);
if (dist<=dist0)
{
return dist;
}
}
else
{
// std::cout << "# not converged!" << std::endl;
}
// couldn't find better answer so return initial guess
t=t0;
return dist0;
}
template<typename curve__>
typename curve__::data_type minimum_distance(typename curve__::data_type &t, const curve__ &c, const typename curve__::point_type &pt)
{
typename curve__::tolerance_type tol;
std::list<std::pair<typename curve__::data_type, typename curve__::data_type>> tinit;
typename std::list<std::pair<typename curve__::data_type, typename curve__::data_type>>::iterator it;
std::pair<typename curve__::data_type, typename curve__::data_type> cand_pair;
// possible that end points are closest, so start by checking them
typename curve__::data_type dist, tt, dd;
typename curve__::index_type i, n;
// Just a guess
n=2*c.degree()+1;
// Evenly spaced in parameter, don't repeat 0/1 if closed curve.
typename curve__::data_type dt;
if (c.open())
{
dt = 1.0/(n-1);
}
else
{
dt = 1.0/n;
}
// Find closest of evenly spaced points.
tt = 0;
dist = std::numeric_limits<typename curve__::data_type>::max();
for (i = 0; i < n; i++)
{
dd=eli::geom::point::distance(c.f(tt), pt);
if( dd < dist )
{
t=tt;
dist=dd;
}
tt+=dt;
if( tt >= 1 )
{
tt=1;
}
}
// Polish best point with Newton's method search.
typename curve__::data_type t0(t);
dist=minimum_distance(t, c, pt, t0);
return dist;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file LocatorSelectorEntry.hpp
*/
#ifndef FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_
#define FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_
#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC
#include "./Guid.h"
#include "./Locator.h"
#include "../../utils/collections/ResourceLimitedVector.hpp"
namespace eprosima {
namespace fastrtps {
namespace rtps {
/**
* An entry for the @ref LocatorSelector.
*
* This class holds the locators of a remote endpoint along with data required for the locator selection algorithm.
* Can be easyly integrated inside other classes, such as @ref ReaderProxyData and @ref WriterProxyData.
*/
struct LocatorSelectorEntry
{
/**
* Holds the selection state of the locators held by a LocatorSelectorEntry
*/
struct EntryState
{
/**
* Construct an EntryState object.
*
* @param max_unicast_locators Maximum number of unicast locators to held by parent LocatorSelectorEntry.
* @param max_multicast_locators Maximum number of multicast locators to held by parent LocatorSelectorEntry.
*/
EntryState(
size_t max_unicast_locators,
size_t max_multicast_locators)
: unicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_unicast_locators))
, multicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_multicast_locators))
{
}
//! Unicast locators selection state
ResourceLimitedVector<size_t> unicast;
//! Multicast locators selection state
ResourceLimitedVector<size_t> multicast;
};
/**
* Construct a LocatorSelectorEntry.
*
* @param max_unicast_locators Maximum number of unicast locators to hold.
* @param max_multicast_locators Maximum number of multicast locators to hold.
*/
LocatorSelectorEntry(
size_t max_unicast_locators,
size_t max_multicast_locators)
: remote_guid(c_Guid_Unknown)
, unicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_unicast_locators))
, multicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_multicast_locators))
, state(max_unicast_locators, max_multicast_locators)
, transport_should_process(false)
{
}
/**
* Set the enabled value.
*
* @param should_enable Whether this entry should be enabled.
*/
void enable(bool should_enable)
{
enabled = should_enable && remote_guid != c_Guid_Unknown;
}
/**
* Reset the selections.
*/
void reset()
{
state.unicast.clear();
state.multicast.clear();
}
//! GUID of the remote entity.
GUID_t remote_guid;
//! List of unicast locators to send data to the remote entity.
ResourceLimitedVector<Locator_t> unicast;
//! List of multicast locators to send data to the remote entity.
ResourceLimitedVector<Locator_t> multicast;
//! State of the entry
EntryState state;
//! Indicates whether this entry should be taken into consideration.
bool enabled;
//! A temporary value for each transport to help optimizing some use cases.
bool transport_should_process;
};
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
#endif /* DOXYGEN_SHOULD_SKIP_THIS_PUBLIC */
#endif /* FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_ */
<commit_msg>Refs #6108. Setting value for enabled on LocatorSelectorEntry ctor. (#635)<commit_after>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file LocatorSelectorEntry.hpp
*/
#ifndef FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_
#define FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_
#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC
#include "./Guid.h"
#include "./Locator.h"
#include "../../utils/collections/ResourceLimitedVector.hpp"
namespace eprosima {
namespace fastrtps {
namespace rtps {
/**
* An entry for the @ref LocatorSelector.
*
* This class holds the locators of a remote endpoint along with data required for the locator selection algorithm.
* Can be easyly integrated inside other classes, such as @ref ReaderProxyData and @ref WriterProxyData.
*/
struct LocatorSelectorEntry
{
/**
* Holds the selection state of the locators held by a LocatorSelectorEntry
*/
struct EntryState
{
/**
* Construct an EntryState object.
*
* @param max_unicast_locators Maximum number of unicast locators to held by parent LocatorSelectorEntry.
* @param max_multicast_locators Maximum number of multicast locators to held by parent LocatorSelectorEntry.
*/
EntryState(
size_t max_unicast_locators,
size_t max_multicast_locators)
: unicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_unicast_locators))
, multicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_multicast_locators))
{
}
//! Unicast locators selection state
ResourceLimitedVector<size_t> unicast;
//! Multicast locators selection state
ResourceLimitedVector<size_t> multicast;
};
/**
* Construct a LocatorSelectorEntry.
*
* @param max_unicast_locators Maximum number of unicast locators to hold.
* @param max_multicast_locators Maximum number of multicast locators to hold.
*/
LocatorSelectorEntry(
size_t max_unicast_locators,
size_t max_multicast_locators)
: remote_guid(c_Guid_Unknown)
, unicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_unicast_locators))
, multicast(ResourceLimitedContainerConfig::fixed_size_configuration(max_multicast_locators))
, state(max_unicast_locators, max_multicast_locators)
, enabled(false)
, transport_should_process(false)
{
}
/**
* Set the enabled value.
*
* @param should_enable Whether this entry should be enabled.
*/
void enable(bool should_enable)
{
enabled = should_enable && remote_guid != c_Guid_Unknown;
}
/**
* Reset the selections.
*/
void reset()
{
state.unicast.clear();
state.multicast.clear();
}
//! GUID of the remote entity.
GUID_t remote_guid;
//! List of unicast locators to send data to the remote entity.
ResourceLimitedVector<Locator_t> unicast;
//! List of multicast locators to send data to the remote entity.
ResourceLimitedVector<Locator_t> multicast;
//! State of the entry
EntryState state;
//! Indicates whether this entry should be taken into consideration.
bool enabled;
//! A temporary value for each transport to help optimizing some use cases.
bool transport_should_process;
};
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
#endif /* DOXYGEN_SHOULD_SKIP_THIS_PUBLIC */
#endif /* FASTRTPS_RTPS_COMMON_LOCATORSELECTORENTRY_HPP_ */
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "AutoSynthesizer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Sema/Sema.h"
using namespace clang;
namespace cling {
class AutoFixer : public RecursiveASTVisitor<AutoFixer> {
private:
Sema* m_Sema;
DeclRefExpr* m_FoundDRE;
llvm::DenseSet<NamedDecl*> m_HandledDecls;
private:
public:
AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(0) {}
void Fix(CompoundStmt* CS) {
if (!CS->size())
return;
typedef llvm::SmallVector<Stmt*, 32> Statements;
Statements Stmts;
Stmts.append(CS->body_begin(), CS->body_end());
for (Statements::iterator I = Stmts.begin(); I != Stmts.end(); ++I) {
if (!TraverseStmt(*I) && !m_HandledDecls.count(m_FoundDRE->getDecl())) {
Sema::DeclGroupPtrTy VDPtrTy
= m_Sema->ConvertDeclToDeclGroup(m_FoundDRE->getDecl());
StmtResult DS = m_Sema->ActOnDeclStmt(VDPtrTy,
m_FoundDRE->getLocStart(),
m_FoundDRE->getLocEnd());
assert(!DS.isInvalid() && "Invalid DeclStmt.");
I = Stmts.insert(I, DS.get());
m_HandledDecls.insert(m_FoundDRE->getDecl());
}
}
CS->setStmts(m_Sema->getASTContext(), Stmts);
}
void Fix(CXXTryStmt* TS) {
Fix(TS->getTryBlock());
for(unsigned int h = 0; h < TS->getNumHandlers(); ++h) {
Stmt *s = TS->getHandler(h)->getHandlerBlock();
if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(s))
Fix(CS);
else if (CXXTryStmt *TS = dyn_cast_or_null<CXXTryStmt>(s))
Fix(TS);
}
}
bool VisitDeclRefExpr(DeclRefExpr* DRE) {
const Decl* D = DRE->getDecl();
if (const AnnotateAttr* A = D->getAttr<AnnotateAttr>())
if (A->getAnnotation().equals("__Auto")) {
m_FoundDRE = DRE;
return false; // we abort on the first found candidate.
}
return true; // returning false will abort the in-depth traversal.
}
};
} // end namespace cling
namespace cling {
AutoSynthesizer::AutoSynthesizer(clang::Sema* S)
: ASTTransformer(S) {
// TODO: We would like to keep that local without keeping track of all
// decls that were handled in the AutoFixer. This can be done by removing
// the __Auto attribute, but for now I am still hesitant to do it. Having
// the __Auto attribute is very useful for debugging because it localize the
// the problem if exists.
m_AutoFixer.reset(new AutoFixer(S));
}
// pin the vtable here.
AutoSynthesizer::~AutoSynthesizer()
{ }
ASTTransformer::Result AutoSynthesizer::Transform(Decl* D) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
// getBody() might return nullptr even though hasBody() is true for
// late template parsed functions. We simply don't do auto auto on
// those.
Stmt *Body = FD->getBody();
if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(Body))
m_AutoFixer->Fix(CS);
else if (CXXTryStmt *TS = dyn_cast_or_null<CXXTryStmt>(Body))
m_AutoFixer->Fix(TS);
}
return Result(D, true);
}
} // end namespace cling
<commit_msg>Fix Coverity CID66882 - clash with parameter name.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "AutoSynthesizer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Sema/Sema.h"
using namespace clang;
namespace cling {
class AutoFixer : public RecursiveASTVisitor<AutoFixer> {
private:
Sema* m_Sema;
DeclRefExpr* m_FoundDRE;
llvm::DenseSet<NamedDecl*> m_HandledDecls;
private:
public:
AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(0) {}
void Fix(CompoundStmt* CS) {
if (!CS->size())
return;
typedef llvm::SmallVector<Stmt*, 32> Statements;
Statements Stmts;
Stmts.append(CS->body_begin(), CS->body_end());
for (Statements::iterator I = Stmts.begin(); I != Stmts.end(); ++I) {
if (!TraverseStmt(*I) && !m_HandledDecls.count(m_FoundDRE->getDecl())) {
Sema::DeclGroupPtrTy VDPtrTy
= m_Sema->ConvertDeclToDeclGroup(m_FoundDRE->getDecl());
StmtResult DS = m_Sema->ActOnDeclStmt(VDPtrTy,
m_FoundDRE->getLocStart(),
m_FoundDRE->getLocEnd());
assert(!DS.isInvalid() && "Invalid DeclStmt.");
I = Stmts.insert(I, DS.get());
m_HandledDecls.insert(m_FoundDRE->getDecl());
}
}
CS->setStmts(m_Sema->getASTContext(), Stmts);
}
void Fix(CXXTryStmt* TS) {
Fix(TS->getTryBlock());
for(unsigned int h = 0; h < TS->getNumHandlers(); ++h) {
Stmt *s = TS->getHandler(h)->getHandlerBlock();
if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(s))
Fix(CS);
else if (CXXTryStmt *HandlerTS = dyn_cast_or_null<CXXTryStmt>(s))
Fix(HandlerTS);
}
}
bool VisitDeclRefExpr(DeclRefExpr* DRE) {
const Decl* D = DRE->getDecl();
if (const AnnotateAttr* A = D->getAttr<AnnotateAttr>())
if (A->getAnnotation().equals("__Auto")) {
m_FoundDRE = DRE;
return false; // we abort on the first found candidate.
}
return true; // returning false will abort the in-depth traversal.
}
};
} // end namespace cling
namespace cling {
AutoSynthesizer::AutoSynthesizer(clang::Sema* S)
: ASTTransformer(S) {
// TODO: We would like to keep that local without keeping track of all
// decls that were handled in the AutoFixer. This can be done by removing
// the __Auto attribute, but for now I am still hesitant to do it. Having
// the __Auto attribute is very useful for debugging because it localize the
// the problem if exists.
m_AutoFixer.reset(new AutoFixer(S));
}
// pin the vtable here.
AutoSynthesizer::~AutoSynthesizer()
{ }
ASTTransformer::Result AutoSynthesizer::Transform(Decl* D) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
// getBody() might return nullptr even though hasBody() is true for
// late template parsed functions. We simply don't do auto auto on
// those.
Stmt *Body = FD->getBody();
if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(Body))
m_AutoFixer->Fix(CS);
else if (CXXTryStmt *TS = dyn_cast_or_null<CXXTryStmt>(Body))
m_AutoFixer->Fix(TS);
}
return Result(D, true);
}
} // end namespace cling
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/memory/lib/utils/conversions.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file conversions.H
/// @brief Functions to convert units
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_CONVERSIONS_H_
#define _MSS_CONVERSIONS_H_
#include <vector>
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/shared/mss_const.H>
#include <lib/utils/find.H>
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint8_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT8_VECTOR_TO_1D_ARRAY(X, Y)\
{\
reinterpret_cast<uint8_t(&)[Y]>(*X.data())\
}
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint16_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT16_VECTOR_TO_1D_ARRAY(X, Y)\
{\
reinterpret_cast<uint16_t(&)[Y]>(*X.data())\
}
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint32_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT32_VECTOR_TO_1D_ARRAY(X, Y)\
{\
reinterpret_cast<uint32_t(&)[Y]>(*X.data())\
}
// Mutiplication factor to go from clocks to simcycles.
// Is this just 2400 speed or does this hold for all? BRS
static const uint64_t SIM_CYCLES_PER_CYCLE = 8;
namespace mss
{
///
/// @brief Return the number of picoseconds
/// @tparam T input and output type
/// @param[in] i_transfer_rate input in MegaTransfers per second (MT/s)
/// @return timing in picoseconds
/// @note clock periods are defined to 1 ps of accuracy, so
/// so 1.0714 ns is defined as 1071 ps as defined by JEDEC's
/// SPD rounding algorithm. This concept is used for this calculation.
///
template<typename T>
inline T freq_to_ps(const T i_transfer_rate)
{
// ATTR_MSS_FREQ is in MT/s, and we know microsecond per clock is 1/(freq/2)
// actual dimm_freq is 1/2 of the speed bin
T l_dimm_freq = i_transfer_rate / 2;
// ps per clock (note value is rounded down)
return CONVERT_PS_IN_A_US / l_dimm_freq;
}
///
/// @brief Return the number in MT/s
/// @tparam T input and output type
/// @param[in] i_time_in_ps time in picoseconds
/// @return speed in MT/s
///
template<typename T>
inline T ps_to_freq(const T i_time_in_ps)
{
// reverse of freq_to_ps function, solving for freq
// since running at DDR, data is transferred on both rising & falling edges
// hence the 2X factor
return (2 * CONVERT_PS_IN_A_US) / i_time_in_ps;
}
///
/// @brief Translate from cycles to sim cycles
/// @param[in] i_cycles the cycles to translate
/// @return uint64_t, the number of sim cycles.
///
inline uint64_t cycles_to_simcycles( const uint64_t i_cycles )
{
// Is this always the case or do we need the freq to really figure this out?
return i_cycles * SIM_CYCLES_PER_CYCLE;
}
///
/// @brief Return the number of cycles contained in a count of picoseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_ps the number of picoseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t ps_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_ps)
{
// The frequency in mHZ
uint64_t l_freq = 0;
uint64_t l_divisor = 0;
uint64_t l_quotient = 0;
uint64_t l_remainder = 0;
FAPI_TRY( mss::freq( find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_freq) );
// Hoping the compiler figures out how to do these together.
l_divisor = freq_to_ps(l_freq);
l_quotient = i_ps / l_divisor;
l_remainder = i_ps % l_divisor;
// Make sure we add a cycle if there wasn't an even number of cycles in the input
FAPI_DBG("converting %llups to %llu cycles", i_ps, l_quotient + (l_remainder == 0 ? 0 : 1));
return l_quotient + (l_remainder == 0 ? 0 : 1);
fapi_try_exit:
// We simply can't work if we can't get the frequency - so this should be ok
FAPI_ERR("Can't get MSS_FREQ - stopping");
fapi2::Assert(false);
// Keeps compiler happy
return 0;
}
///
/// @brief Return the number of ps contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of picoseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_ps(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
// The frequency in mHZ
uint64_t l_freq = 0;
FAPI_TRY( mss::freq( find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_freq) );
FAPI_DBG("converting %llu cycles to %llups", i_cycles, i_cycles * freq_to_ps(l_freq));
return i_cycles * freq_to_ps(l_freq);
fapi_try_exit:
// We simply can't work if we can't get the frequency - so this should be ok
FAPI_ERR("Can't get MSS_FREQ - stopping");
fapi2::Assert(false);
// Keeps compiler happy
return 0;
}
///
/// @brief Return the number of cycles contained in a count of microseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_us the number of microseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t us_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_us)
{
return ps_to_cycles(i_target, i_us * CONVERT_PS_IN_A_US);
}
///
/// @brief Return the number of cycles contained in a count of nanoseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_ps the number of nanoseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t ns_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_ns)
{
return ps_to_cycles(i_target, i_ns * CONVERT_PS_IN_A_NS);
}
///
/// @brief Return the number of microseconds contained in a count of cycles
/// @tparam T the target type
/// @tparam D the time conversion (NS_IN_PS, etc)
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of microseconds
///
template< fapi2::TargetType T, uint64_t D >
inline uint64_t cycles_to_time(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
// Hoping the compiler figures out how to do these together.
uint64_t l_dividend = cycles_to_ps(i_target, i_cycles);
uint64_t l_quotient = l_dividend / D;
uint64_t l_remainder = l_dividend % D;
// Make sure we add time if there wasn't an even number of cycles
return l_quotient + (l_remainder == 0 ? 0 : 1);
}
///
/// @brief Return the number of nanoseconds contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of nanoseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_ns(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
uint64_t l_ns = cycles_to_time<T, CONVERT_PS_IN_A_NS>(i_target, i_cycles);
FAPI_DBG("converting %llu cycles to %lluns", i_cycles, l_ns);
return l_ns;
}
///
/// @brief Return the number of microseconds contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of microseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_us(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
uint64_t l_us = cycles_to_time<T, CONVERT_PS_IN_A_US>(i_target, i_cycles);
FAPI_DBG("converting %llu cycles to %lluus", i_cycles, l_us);
return l_us;
}
///
/// @brief Calculate TWLO_TWLOE - this needs to go in to eff_config and be an attribute
/// @tparam T fapi2::TargetType of the target used to calculate cycles from ns
/// @param[in] i_target the target used to get DIMM clocks
/// @return uint64_t, TWLO_TWLOE in cycles
///
template< fapi2::TargetType T >
inline uint64_t twlo_twloe(const fapi2::Target<T>& i_target)
{
return 12 + mss::ns_to_cycles(i_target, tWLO - tWLOE);
}
///
/// @brief Convert nanoseconds to picoseconds
/// @tparam T input and output type
/// @param[in] i_time_in_ns time in nanoseconds
/// @return time in picoseconds
///
template<typename T>
inline T ns_to_ps(const T i_time_in_ns)
{
return i_time_in_ns * CONVERT_PS_IN_A_NS;
}
///
/// @brief Convert nanoseconds to picoseconds
/// @tparam T input and output type
/// @param[in] i_time_in_ps time in picoseconds
/// @return time in nanoseconds
///
template<typename T>
inline T ps_to_ns(const T i_time_in_ps)
{
T remainder = i_time_in_ps % CONVERT_PS_IN_A_NS;
T l_time_in_ns = i_time_in_ps / CONVERT_PS_IN_A_NS;
// Round up if remainder isn't even
return l_time_in_ns + ( remainder == 0 ? 0 : 1 );
}
};// mss namespace
#endif
<commit_msg>Remove curly brackets for VECTOR_TO_1D_ARRAY macros<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/memory/lib/utils/conversions.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file conversions.H
/// @brief Functions to convert units
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_CONVERSIONS_H_
#define _MSS_CONVERSIONS_H_
#include <vector>
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/shared/mss_const.H>
#include <lib/utils/find.H>
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint8_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT8_VECTOR_TO_1D_ARRAY(X, Y)\
reinterpret_cast<uint8_t(&)[Y]>(*X.data())
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint16_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT16_VECTOR_TO_1D_ARRAY(X, Y)\
reinterpret_cast<uint16_t(&)[Y]>(*X.data())
///
/// @brief Dereferences pointer of the vector's underlying data
// and casts it to uint32_t[Y] that FAPI_ATTR_SET is expecting by deduction
/// @param[in] X is the input vector
/// @param[in] Y is the size of the vector
/// @warn compiler doesn't like the use of vector method size() for the second param
///
#define UINT32_VECTOR_TO_1D_ARRAY(X, Y)\
reinterpret_cast<uint32_t(&)[Y]>(*X.data())
// Mutiplication factor to go from clocks to simcycles.
// Is this just 2400 speed or does this hold for all? BRS
static const uint64_t SIM_CYCLES_PER_CYCLE = 8;
namespace mss
{
///
/// @brief Return the number of picoseconds
/// @tparam T input and output type
/// @param[in] i_transfer_rate input in MegaTransfers per second (MT/s)
/// @return timing in picoseconds
/// @note clock periods are defined to 1 ps of accuracy, so
/// so 1.0714 ns is defined as 1071 ps as defined by JEDEC's
/// SPD rounding algorithm. This concept is used for this calculation.
///
template<typename T>
inline T freq_to_ps(const T i_transfer_rate)
{
// ATTR_MSS_FREQ is in MT/s, and we know microsecond per clock is 1/(freq/2)
// actual dimm_freq is 1/2 of the speed bin
T l_dimm_freq = i_transfer_rate / 2;
// ps per clock (note value is rounded down)
return CONVERT_PS_IN_A_US / l_dimm_freq;
}
///
/// @brief Return the number in MT/s
/// @tparam T input and output type
/// @param[in] i_time_in_ps time in picoseconds
/// @return speed in MT/s
///
template<typename T>
inline T ps_to_freq(const T i_time_in_ps)
{
// reverse of freq_to_ps function, solving for freq
// since running at DDR, data is transferred on both rising & falling edges
// hence the 2X factor
return (2 * CONVERT_PS_IN_A_US) / i_time_in_ps;
}
///
/// @brief Translate from cycles to sim cycles
/// @param[in] i_cycles the cycles to translate
/// @return uint64_t, the number of sim cycles.
///
inline uint64_t cycles_to_simcycles( const uint64_t i_cycles )
{
// Is this always the case or do we need the freq to really figure this out?
return i_cycles * SIM_CYCLES_PER_CYCLE;
}
///
/// @brief Return the number of cycles contained in a count of picoseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_ps the number of picoseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t ps_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_ps)
{
// The frequency in mHZ
uint64_t l_freq = 0;
uint64_t l_divisor = 0;
uint64_t l_quotient = 0;
uint64_t l_remainder = 0;
FAPI_TRY( mss::freq( find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_freq) );
// Hoping the compiler figures out how to do these together.
l_divisor = freq_to_ps(l_freq);
l_quotient = i_ps / l_divisor;
l_remainder = i_ps % l_divisor;
// Make sure we add a cycle if there wasn't an even number of cycles in the input
FAPI_DBG("converting %llups to %llu cycles", i_ps, l_quotient + (l_remainder == 0 ? 0 : 1));
return l_quotient + (l_remainder == 0 ? 0 : 1);
fapi_try_exit:
// We simply can't work if we can't get the frequency - so this should be ok
FAPI_ERR("Can't get MSS_FREQ - stopping");
fapi2::Assert(false);
// Keeps compiler happy
return 0;
}
///
/// @brief Return the number of ps contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of picoseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_ps(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
// The frequency in mHZ
uint64_t l_freq = 0;
FAPI_TRY( mss::freq( find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_freq) );
FAPI_DBG("converting %llu cycles to %llups", i_cycles, i_cycles * freq_to_ps(l_freq));
return i_cycles * freq_to_ps(l_freq);
fapi_try_exit:
// We simply can't work if we can't get the frequency - so this should be ok
FAPI_ERR("Can't get MSS_FREQ - stopping");
fapi2::Assert(false);
// Keeps compiler happy
return 0;
}
///
/// @brief Return the number of cycles contained in a count of microseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_us the number of microseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t us_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_us)
{
return ps_to_cycles(i_target, i_us * CONVERT_PS_IN_A_US);
}
///
/// @brief Return the number of cycles contained in a count of nanoseconds
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_ps the number of nanoseconds to convert
/// @return uint64_t, the number of cycles
///
template< fapi2::TargetType T >
inline uint64_t ns_to_cycles(const fapi2::Target<T>& i_target, const uint64_t i_ns)
{
return ps_to_cycles(i_target, i_ns * CONVERT_PS_IN_A_NS);
}
///
/// @brief Return the number of microseconds contained in a count of cycles
/// @tparam T the target type
/// @tparam D the time conversion (NS_IN_PS, etc)
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of microseconds
///
template< fapi2::TargetType T, uint64_t D >
inline uint64_t cycles_to_time(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
// Hoping the compiler figures out how to do these together.
uint64_t l_dividend = cycles_to_ps(i_target, i_cycles);
uint64_t l_quotient = l_dividend / D;
uint64_t l_remainder = l_dividend % D;
// Make sure we add time if there wasn't an even number of cycles
return l_quotient + (l_remainder == 0 ? 0 : 1);
}
///
/// @brief Return the number of nanoseconds contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of nanoseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_ns(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
uint64_t l_ns = cycles_to_time<T, CONVERT_PS_IN_A_NS>(i_target, i_cycles);
FAPI_DBG("converting %llu cycles to %lluns", i_cycles, l_ns);
return l_ns;
}
///
/// @brief Return the number of microseconds contained in a count of cycles
/// @param[in] i_target target for the frequency attribute
/// @param[in] i_cycles the number of cycles to convert
/// @return uint64_t, the number of microseconds
///
template< fapi2::TargetType T >
inline uint64_t cycles_to_us(const fapi2::Target<T>& i_target, const uint64_t i_cycles)
{
uint64_t l_us = cycles_to_time<T, CONVERT_PS_IN_A_US>(i_target, i_cycles);
FAPI_DBG("converting %llu cycles to %lluus", i_cycles, l_us);
return l_us;
}
///
/// @brief Calculate TWLO_TWLOE - this needs to go in to eff_config and be an attribute
/// @tparam T fapi2::TargetType of the target used to calculate cycles from ns
/// @param[in] i_target the target used to get DIMM clocks
/// @return uint64_t, TWLO_TWLOE in cycles
///
template< fapi2::TargetType T >
inline uint64_t twlo_twloe(const fapi2::Target<T>& i_target)
{
return 12 + mss::ns_to_cycles(i_target, tWLO - tWLOE);
}
///
/// @brief Convert nanoseconds to picoseconds
/// @tparam T input and output type
/// @param[in] i_time_in_ns time in nanoseconds
/// @return time in picoseconds
///
template<typename T>
inline T ns_to_ps(const T i_time_in_ns)
{
return i_time_in_ns * CONVERT_PS_IN_A_NS;
}
///
/// @brief Convert nanoseconds to picoseconds
/// @tparam T input and output type
/// @param[in] i_time_in_ps time in picoseconds
/// @return time in nanoseconds
///
template<typename T>
inline T ps_to_ns(const T i_time_in_ps)
{
T remainder = i_time_in_ps % CONVERT_PS_IN_A_NS;
T l_time_in_ns = i_time_in_ps / CONVERT_PS_IN_A_NS;
// Round up if remainder isn't even
return l_time_in_ns + ( remainder == 0 ? 0 : 1 );
}
};// mss namespace
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_exit_cache_contained.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///----------------------------------------------------------------------------
/// @file p9_exit_cache_contained.C
///
/// @brief Contains inits to be performed before Hostboot expanded from
/// running inside the confines of the L3 cache out to main memory.
///----------------------------------------------------------------------------
// *HWP HWP Owner: Joe McGill <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_exit_cache_contained.H>
extern "C"
{
///
/// p9_exit_cache_contained HWP entry point (Defined in .H file)
///
fapi2::ReturnCode p9_exit_cache_contained(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
& i_target)
{
fapi2::ReturnCode rc;
// Mark Entry
FAPI_INF("Entering ...");
// This procedure is a placeholder to add inits that might need to be
// performed before Hostboot expanded from running inside the confines
// of the L3 cache out to main memory.
// There is nothing specific to be added for P9 at this point.
// Mark Exit
FAPI_INF("Exiting ...");
return rc;
}
} // extern "C"
/* End: */
<commit_msg>L3 updates -- shell HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_exit_cache_contained.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_exit_cache_contained.C
/// @brief Placeholder to apply inits needed prior to HB expansion from L3
/// cache to main memory (FAPI2)
///
/// @author Joe McGill <[email protected]>
///
//
// *HWP HWP Owner: Joe McGill <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Nest
// *HWP Level: 3
// *HWP Consumed by: HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_exit_cache_contained.H>
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_exit_cache_contained(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
// This procedure is a placeholder to add inits that might need to be
// performed before Hostboot expanded from running inside the confines
// of the L3 cache out to main memory.
// There is nothing specific to be added for P9 at this point.
FAPI_INF("Start");
FAPI_INF("End");
return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_DETAIL_LOWER_LEVEL_HOLDER_HPP
#define VIENNAGRID_DETAIL_LOWER_LEVEL_HOLDER_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <iostream>
#include "viennagrid/forwards.h"
//#include "viennagrid/topology/point.hpp"
//#include "viennagrid/iterators.hpp"
#include "viennagrid/detail/element_orientation.hpp"
#include <vector>
/** @file boundary_ncell_layer.hpp
@brief Provides the topological layers for n-cells
*/
namespace viennagrid
{
/************** Level 1: Elements contained by a higher-level element *******/
/** @brief A class holding all information about boundary k-cells of a n-cell
*
* @tparam ConfigType The configuration class
* @tparam ElementTag The n-cell tag
* @tparam dim Topological dimension k of the boundary k-cells
* @tparam handling_tag Whether or not to store references to boundary k-cells
* @tparam orienter_tag Whether or not to store orientations of k-cells with respect to the n-cell
* @tparam LevelNull Helper parameter to avoid ambiguities at vertex level.
*/
template <typename ConfigType,
typename ElementTag,
unsigned long dim,
typename handling_tag = typename result_of::bndcell_handling<ConfigType, ElementTag, dim>::type,
typename orienter_tag = typename result_of::bndcell_orientation<ConfigType, ElementTag, dim>::type,
bool LevelNull = (dim == 0)>
class boundary_ncell_layer { };
//
// Full storage of boundary cell, including orientation
//
/** @brief Implementation of full storage of k-cells including orientations */
template <typename ConfigType, typename ElementTag, unsigned long dim>
class boundary_ncell_layer <ConfigType, ElementTag, dim, full_handling_tag, full_handling_tag, false> :
public boundary_ncell_layer <ConfigType, ElementTag, dim - 1>
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef topology::bndcells<typename LevelSpecs::tag, 0> VertexOnElementSpecs;
typedef boundary_ncell_layer <ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
typedef element_orientation<VertexOnElementSpecs::num> ElementOrientationType;
typedef typename result_of::element_container<element_t<ConfigType, ElementTag>, dim, ElementTag::dim>::type container_type;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
//fill lower level first:
Base::fill_level(dom);
//for (long i=0; i<LevelSpecs::num; ++i)
// orientations_[i].resize(VertexOnElementSpecs::num);
topology::bndcell_filler<ElementTag, dim>::fill(&(elements_[0]),
&(Base::vertices_[0]),
&(orientations_[0]),
dom);
}
public:
boundary_ncell_layer( )
{
for (long i=0; i < LevelSpecs::num; ++i)
elements_[i] = NULL;
};
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh)
{
for (long i=0; i < LevelSpecs::num; ++i)
elements_[i] = llh.elements_[i];
}
/////////////////// access container: ////////////////////
using Base::container;
//non-const:
container_type *
container(dimension_tag<dim>)
{
return &(elements_[0]);
}
//const:
const container_type *
container(dimension_tag<dim>) const
{
return &(elements_[0]);
}
////////////////// orientation: ////////////////////
std::size_t global_to_local_orientation(LevelElementType const & el, long index) const
{
for (std::size_t i=0; i<LevelSpecs::num; ++i)
{
if (elements_[i] == &el)
return orientations_[i](index);
}
assert(false && "Provided k-cell is not a boundary element of the hosting n-cell!");
return index;
}
private:
container_type elements_[LevelSpecs::num];
ElementOrientationType orientations_[LevelSpecs::num];
};
//
// Full storage of boundary cell, but no orientation
//
/** @brief Implementation of boundary k-cell storage without orientation */
template <typename ConfigType, typename ElementTag, unsigned long dim>
class boundary_ncell_layer <ConfigType, ElementTag, dim, full_handling_tag, no_handling_tag, false> :
public boundary_ncell_layer <ConfigType, ElementTag, dim - 1>
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef topology::bndcells<typename LevelSpecs::tag, 0> VertexOnElementSpecs;
typedef boundary_ncell_layer <ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
typedef element_orientation<VertexOnElementSpecs::num> ElementOrientationType;
typedef typename result_of::element_container<element_t<ConfigType, ElementTag>, dim, ElementTag::dim>::type container_type;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
typedef ElementOrientationType * OrientationPointer;
//fill lower level first:
Base::fill_level(dom);
topology::bndcell_filler<ElementTag, dim>::fill(&(elements_[0]),
&(Base::vertices_[0]),
OrientationPointer(NULL),
dom);
}
public:
boundary_ncell_layer( )
{
for (long i=0; i < LevelSpecs::num; ++i)
elements_[i] = NULL;
};
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh)
{
for (long i=0; i < LevelSpecs::num; ++i)
elements_[i] = llh.elements_[i];
}
/////////////////// access container: ////////////////////
using Base::container;
//non-const:
container_type *
container(dimension_tag<dim>)
{
return &(elements_[0]);
}
//const:
const container_type *
container(dimension_tag<dim>) const
{
return &(elements_[0]);
}
private:
container_type elements_[LevelSpecs::num];
};
//
// No storage of boundary elements:
//
/** @brief Implementation of the case that boundary k-cells are not stored at all */
template <typename ConfigType, typename ElementTag, unsigned long dim, typename orienter_tag>
class boundary_ncell_layer <ConfigType, ElementTag, dim, no_handling_tag, orienter_tag, false> :
public boundary_ncell_layer < ConfigType, ElementTag, dim - 1 >
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
//typedef typename DomainTypes<ConfigType>::segment_type SegmentType;
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef boundary_ncell_layer < ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
//fill lower topological levels only:
Base::fill_level(dom);
}
public:
boundary_ncell_layer( ) {};
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh) {}
};
//at level 0, i.e. vertex level, recursion ends:
/** @brief Specialization for the vertex level. Recursion ends here */
template <typename ConfigType, typename ElementTag, typename handling_tag, typename orienter_tag>
class boundary_ncell_layer <ConfigType, ElementTag, 0, handling_tag, orienter_tag, true>
{
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
//typedef typename DomainTypes<ConfigType>::segment_type SegmentType;
typedef topology::bndcells<ElementTag, 0> LevelSpecs;
typedef element_t<ConfigType, typename LevelSpecs::tag> VertexType;
typedef typename result_of::point<ConfigType>::type PointType;
typedef typename result_of::iterator< element_t<ConfigType, ElementTag>, 0>::type VertexIterator;
protected:
//end recursion:
template <typename DomainType>
void fill_level(DomainType & dom) {}
public:
boundary_ncell_layer() {};
boundary_ncell_layer( const boundary_ncell_layer & llh)
{
for (long i=0; i < LevelSpecs::num; ++i)
vertices_[i] = llh.vertices_[i];
}
////////////////// container access: /////////////////////////
//non-const:
VertexType * *
container(dimension_tag<0>)
{
return &(vertices_[0]);
}
//const:
VertexType * const *
container(dimension_tag<0>) const
{
return &(vertices_[0]);
}
protected:
VertexType * vertices_[LevelSpecs::num];
};
}
#endif
<commit_msg>added support for STL like container (instead of TYPE*)<commit_after>#ifndef VIENNAGRID_DETAIL_LOWER_LEVEL_HOLDER_HPP
#define VIENNAGRID_DETAIL_LOWER_LEVEL_HOLDER_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <iostream>
#include "viennagrid/forwards.h"
//#include "viennagrid/topology/point.hpp"
//#include "viennagrid/iterators.hpp"
#include "viennagrid/detail/element_orientation.hpp"
namespace viennagrid
{
/************** Level 1: Elements contained by a higher-level element *******/
/** @brief A class holding all information about boundary k-cells of a n-cell
*
* @tparam ConfigType The configuration class
* @tparam ElementTag The n-cell tag
* @tparam dim Topological dimension k of the boundary k-cells
* @tparam handling_tag Whether or not to store references to boundary k-cells
* @tparam orienter_tag Whether or not to store orientations of k-cells with respect to the n-cell
* @tparam LevelNull Helper parameter to avoid ambiguities at vertex level.
*/
template <typename ConfigType,
typename ElementTag,
unsigned long dim,
typename handling_tag = typename result_of::bndcell_handling<ConfigType, ElementTag, dim>::type,
typename orienter_tag = typename result_of::bndcell_orientation<ConfigType, ElementTag, dim>::type,
bool LevelNull = (dim == 0)>
class boundary_ncell_layer { };
//
// Full storage of boundary cell, including orientation
//
/** @brief Implementation of full storage of k-cells including orientations */
template <typename ConfigType, typename ElementTag, unsigned long dim>
class boundary_ncell_layer <ConfigType, ElementTag, dim, full_handling_tag, full_handling_tag, false> :
public boundary_ncell_layer <ConfigType, ElementTag, dim - 1>
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef topology::bndcells<typename LevelSpecs::tag, 0> VertexOnElementSpecs;
typedef boundary_ncell_layer <ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
typedef element_orientation<VertexOnElementSpecs::num> ElementOrientationType;
typedef typename topology::bndcells<ElementTag, dim>::layout_tag layout_tag;
static const long array_size = topology::bndcells<ElementTag, dim>::num;
typedef typename result_of::ncell<ConfigType, dim>::type element_type;
typedef typename result_of::container<element_type *, layout_tag, array_size>::type element_container_type;
typedef typename result_of::container<ElementOrientationType, layout_tag, array_size>::type orientation_container_type;
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
//fill lower level first:
Base::fill_level(dom);
//for (long i=0; i<LevelSpecs::num; ++i)
// orientations_[i].resize(VertexOnElementSpecs::num);
topology::bndcell_filler<ElementTag, dim>::fill(elements_,
Base::vertices_,
orientations_,
dom);
}
public:
boundary_ncell_layer( )
{
std::fill( elements_.begin(), elements_.end(), static_cast<element_type *>(NULL) );
};
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh), elements_(llh.elements_), orientations_(llh.orientations_) {}
/////////////////// access container: ////////////////////
using Base::container;
//non-const:
element_container_type *
container(dimension_tag<dim>)
{
return &elements_;
}
//const:
const element_container_type *
container(dimension_tag<dim>) const
{
return &elements_;
}
////////////////// orientation: ////////////////////
std::size_t global_to_local_orientation(LevelElementType const & el, long index) const
{
for (std::size_t i=0; i<LevelSpecs::num; ++i)
{
if (elements_[i] == &el)
return orientations_[i](index);
}
assert(false && "Provided k-cell is not a boundary element of the hosting n-cell!");
return index;
}
void fill_vertices(VertexType ** vertices_, size_t num)
{
Base::fill_vertices(vertices_, num);
}
private:
element_container_type elements_;
orientation_container_type orientations_;
};
//
// Full storage of boundary cell, but no orientation
//
/** @brief Implementation of boundary k-cell storage without orientation */
template <typename ConfigType, typename ElementTag, unsigned long dim>
class boundary_ncell_layer <ConfigType, ElementTag, dim, full_handling_tag, no_handling_tag, false> :
public boundary_ncell_layer <ConfigType, ElementTag, dim - 1>
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef topology::bndcells<typename LevelSpecs::tag, 0> VertexOnElementSpecs;
typedef boundary_ncell_layer <ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
typedef element_orientation<VertexOnElementSpecs::num> ElementOrientationType;
typedef typename topology::bndcells<ElementTag, dim>::layout_tag layout_tag;
static const long array_size = topology::bndcells<ElementTag, dim>::num;
typedef typename result_of::ncell<ConfigType, dim>::type element_type;
typedef typename result_of::container<element_type *, layout_tag, array_size>::type element_container_type;
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
typedef ElementOrientationType * OrientationPointer;
//fill lower level first:
Base::fill_level(dom);
topology::bndcell_filler<ElementTag, dim>::fill(elements_,
Base::vertices_,
dom);
}
public:
boundary_ncell_layer( )
{
std::fill( elements_.begin(), elements_.end(), static_cast<element_type *>(NULL) );
}
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh), elements_(llh.elements) {}
/////////////////// access container: ////////////////////
using Base::container;
//non-const:
element_container_type *
container(dimension_tag<dim>)
{
return &elements_;
}
//const:
const element_container_type *
container(dimension_tag<dim>) const
{
return &elements_;
}
void fill_vertices(VertexType ** vertices_, size_t num)
{
Base::fill_vertices(vertices_, num);
}
private:
element_container_type elements_;//[LevelSpecs::num];
};
//
// No storage of boundary elements:
//
/** @brief Implementation of the case that boundary k-cells are not stored at all */
template <typename ConfigType, typename ElementTag, unsigned long dim, typename orienter_tag>
class boundary_ncell_layer <ConfigType, ElementTag, dim, no_handling_tag, orienter_tag, false> :
public boundary_ncell_layer < ConfigType, ElementTag, dim - 1 >
{
//requirements:
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
//typedef typename DomainTypes<ConfigType>::segment_type SegmentType;
typedef topology::bndcells<ElementTag, dim> LevelSpecs;
typedef boundary_ncell_layer < ConfigType, ElementTag, dim - 1 > Base;
typedef element_t<ConfigType, typename LevelSpecs::tag> LevelElementType;
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
protected:
template <typename DomainType>
void fill_level(DomainType & dom)
{
//fill lower topological levels only:
Base::fill_level(dom);
}
void fill_vertices(VertexType ** vertices_, size_t num)
{
Base::fill_vertices(vertices_, num);
}
public:
boundary_ncell_layer( ) {};
boundary_ncell_layer( const boundary_ncell_layer & llh) : Base (llh) {}
};
//at level 0, i.e. vertex level, recursion ends:
/** @brief Specialization for the vertex level. Recursion ends here */
template <typename ConfigType, typename ElementTag, typename handling_tag, typename orienter_tag>
class boundary_ncell_layer <ConfigType, ElementTag, 0, handling_tag, orienter_tag, true>
{
//array of pointers to elements of class 'dim' and a integer representing the orientation within the cell relative to the element it points to.
//typedef typename DomainTypes<ConfigType>::segment_type SegmentType;
typedef topology::bndcells<ElementTag, 0> LevelSpecs;
typedef element_t<ConfigType, typename LevelSpecs::tag> VertexType;
typedef typename result_of::point<ConfigType>::type PointType;
typedef typename result_of::iterator< element_t<ConfigType, ElementTag>, 0>::type VertexIterator;
typedef typename topology::bndcells<ElementTag, 0>::layout_tag layout_tag;
static const long array_size = topology::bndcells<ElementTag, 0>::num;
typedef typename result_of::ncell<ConfigType, 0>::type element_type;
typedef typename result_of::container<element_type *, layout_tag, array_size>::type element_container_type;
protected:
//end recursion:
template <typename DomainType>
void fill_level(DomainType & dom) {}
public:
boundary_ncell_layer() {};
boundary_ncell_layer( const boundary_ncell_layer & llh) : vertices_(llh.vertices_) {}
////////////////// container access: /////////////////////////
//non-const:
element_container_type *
container(dimension_tag<0>)
{
return &vertices_;
}
//const:
const element_container_type *
container(dimension_tag<0>) const
{
return &vertices_;
}
void fill_vertices(VertexType ** vertices_in, size_t num)
{
assert( num <= LevelSpecs::num );
vertices_.resize(num);
std::copy( vertices_in, vertices_in + num, vertices_.begin() );
}
protected:
element_container_type vertices_;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Radu B. Rusu, Suat Gedikli
*
*/
#include <pcl/io/pcd_grabber.h>
#include <pcl/console/parse.h>
#define BOOST_FILESYSTEM_VERSION 2
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/console/print.h>
#include <pcl/visualization/cloud_viewer.h>
using pcl::console::print_error;
using pcl::console::print_info;
using pcl::console::print_value;
boost::mutex mutex_;
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -file file_name = PCD file to be read from\n");
print_info (" -dir directory_path = directory path to PCD file(s) to be read from\n");
print_info (" -fps frequency = frames per second\n");
print_info (" -repeat = optional parameter that tells wheter the PCD file(s) should be \"grabbed\" in a endless loop.\n");
print_info ("\n");
print_info (" -cam (*) = use given camera settings as initial view\n");
print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;
std::vector<double> fcolor_r, fcolor_b, fcolor_g;
bool fcolorparam = false;
struct EventHelper
{
void
cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr & cloud)
{
// Add the cloud to the renderer
boost::mutex::scoped_lock lock (mutex_);
if (!cloud)
return;
if (!p->updatePointCloud (cloud, "PCDCloud"))
{
p->addPointCloud (cloud, "PCDCloud");
p->resetCameraViewpoint ("PCDCloud");
}
}
};
void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
{
std::string* message = (std::string*)cookie;
cout << (*message) << " :: ";
if (event.getKeyCode())
cout << "the key \'" << event.getKeyCode() << "\' (" << (int)event.getKeyCode() << ") was";
else
cout << "the special key \'" << event.getKeySym() << "\' was";
if (event.keyDown())
cout << " pressed" << endl;
else
cout << " released" << endl;
}
void mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
{
std::string* message = (std::string*) cookie;
if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton)
{
cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
}
}
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string (argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
// Command line parsing
double bcolor[3] = {0, 0, 0};
pcl::console::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]);
fcolorparam = pcl::console::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b);
int psize = 0;
pcl::console::parse_argument (argc, argv, "-ps", psize);
double opaque;
pcl::console::parse_argument (argc, argv, "-opaque", opaque);
p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "PCD viewer"));
// // Change the cloud rendered point size
// if (psize > 0)
// p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, "OpenNICloud");
//
// // Change the cloud rendered opacity
// if (opaque >= 0)
// p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opaque, "OpenNICloud");
p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);
// Read axes settings
double axes = 0.0;
pcl::console::parse_argument (argc, argv, "-ax", axes);
if (axes != 0.0 && p)
{
double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;
pcl::console::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false);
// Draw XYZ axes if command-line enabled
p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);
}
pcl::Grabber* grabber = 0;
float frames_per_second = 0; // 0 means only if triggered!
pcl::console::parse (argc, argv, "-fps", frames_per_second);
if (frames_per_second < 0)
frames_per_second = 0.0;
std::cout << pcl::console::find_argument (argc, argv, "-repeat") << " : repaet" << std::endl;
bool repeat = (pcl::console::find_argument (argc, argv, "-repeat") != -1);
std::cout << "fps: " << frames_per_second << " , repeat: " << repeat << std::endl;
std::string path = "";
pcl::console::parse_argument (argc, argv, "-file", path);
std::cout << "path: " << path << std::endl;
if (path != "" && boost::filesystem::exists (path))
{
grabber = new pcl::PCDGrabber<pcl::PointXYZRGB> (path, frames_per_second, repeat);
}
else
{
std::vector<std::string> pcd_files;
pcl::console::parse_argument (argc, argv, "-dir", path);
std::cout << "path: " << path << std::endl;
if (path != "" && boost::filesystem::exists (path))
{
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr (path); itr != end_itr; ++itr)
{
if (!is_directory (itr->status()) && boost::algorithm::to_upper_copy(boost::filesystem::extension (itr->leaf())) == ".PCD" )
{
pcd_files.push_back (itr->path ().string());
std::cout << "added: " << itr->path ().string() << std::endl;
}
}
}
else
{
std::cout << "Neither a pcd file given using the \"-file\" option, nor given a directory containing pcd files using the \"-dir\" option." << std::endl;
}
grabber = new pcl::PCDGrabber<pcl::PointXYZRGB> (pcd_files, frames_per_second, repeat);
}
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = grabber->registerCallback (f);
std::string mouseMsg3D ("Mouse coordinates in PCL Visualizer");
std::string keyMsg3D ("Key event for PCL Visualizer");
p->registerMouseCallback (&mouse_callback, (void*)(&mouseMsg3D));
p->registerKeyboardCallback(&keyboard_callback, (void*)(&keyMsg3D));
grabber->start ();
while (true)
{
boost::this_thread::sleep(boost::posix_time::microseconds(10000));
{
boost::mutex::scoped_lock lock (mutex_);
p->spinOnce ();
if (p->wasStopped ())
break;
}
}
grabber->stop ();
}
/* ]--- */
<commit_msg>attempting a fix for pcd_grabber_viewer on Alex's MacOS<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Radu B. Rusu, Suat Gedikli
*
*/
#include <pcl/io/pcd_grabber.h>
#include <pcl/console/parse.h>
#define BOOST_FILESYSTEM_VERSION 2
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/console/print.h>
#include <pcl/visualization/cloud_viewer.h>
using pcl::console::print_error;
using pcl::console::print_info;
using pcl::console::print_value;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_;
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -file file_name = PCD file to be read from\n");
print_info (" -dir directory_path = directory path to PCD file(s) to be read from\n");
print_info (" -fps frequency = frames per second\n");
print_info (" -repeat = optional parameter that tells wheter the PCD file(s) should be \"grabbed\" in a endless loop.\n");
print_info ("\n");
print_info (" -cam (*) = use given camera settings as initial view\n");
print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;
std::vector<double> fcolor_r, fcolor_b, fcolor_g;
bool fcolorparam = false;
struct EventHelper
{
void
cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr & cloud)
{
// Add the cloud to the renderer
boost::mutex::scoped_lock lock (mutex_);
cloud_ = cloud;
}
};
void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
{
std::string* message = (std::string*)cookie;
cout << (*message) << " :: ";
if (event.getKeyCode())
cout << "the key \'" << event.getKeyCode() << "\' (" << (int)event.getKeyCode() << ") was";
else
cout << "the special key \'" << event.getKeySym() << "\' was";
if (event.keyDown())
cout << " pressed" << endl;
else
cout << " released" << endl;
}
void mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
{
std::string* message = (std::string*) cookie;
if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton)
{
cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
}
}
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string (argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
// Command line parsing
double bcolor[3] = {0, 0, 0};
pcl::console::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]);
fcolorparam = pcl::console::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b);
int psize = 0;
pcl::console::parse_argument (argc, argv, "-ps", psize);
double opaque;
pcl::console::parse_argument (argc, argv, "-opaque", opaque);
p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "PCD viewer"));
// // Change the cloud rendered point size
// if (psize > 0)
// p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, "OpenNICloud");
//
// // Change the cloud rendered opacity
// if (opaque >= 0)
// p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opaque, "OpenNICloud");
p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);
// Read axes settings
double axes = 0.0;
pcl::console::parse_argument (argc, argv, "-ax", axes);
if (axes != 0.0 && p)
{
double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;
pcl::console::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false);
// Draw XYZ axes if command-line enabled
p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);
}
pcl::Grabber* grabber = 0;
float frames_per_second = 0; // 0 means only if triggered!
pcl::console::parse (argc, argv, "-fps", frames_per_second);
if (frames_per_second < 0)
frames_per_second = 0.0;
std::cout << pcl::console::find_argument (argc, argv, "-repeat") << " : repaet" << std::endl;
bool repeat = (pcl::console::find_argument (argc, argv, "-repeat") != -1);
std::cout << "fps: " << frames_per_second << " , repeat: " << repeat << std::endl;
std::string path = "";
pcl::console::parse_argument (argc, argv, "-file", path);
std::cout << "path: " << path << std::endl;
if (path != "" && boost::filesystem::exists (path))
{
grabber = new pcl::PCDGrabber<pcl::PointXYZRGB> (path, frames_per_second, repeat);
}
else
{
std::vector<std::string> pcd_files;
pcl::console::parse_argument (argc, argv, "-dir", path);
std::cout << "path: " << path << std::endl;
if (path != "" && boost::filesystem::exists (path))
{
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr (path); itr != end_itr; ++itr)
{
if (!is_directory (itr->status()) && boost::algorithm::to_upper_copy(boost::filesystem::extension (itr->leaf())) == ".PCD" )
{
pcd_files.push_back (itr->path ().string());
std::cout << "added: " << itr->path ().string() << std::endl;
}
}
}
else
{
std::cout << "Neither a pcd file given using the \"-file\" option, nor given a directory containing pcd files using the \"-dir\" option." << std::endl;
}
grabber = new pcl::PCDGrabber<pcl::PointXYZRGB> (pcd_files, frames_per_second, repeat);
}
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = grabber->registerCallback (f);
std::string mouseMsg3D ("Mouse coordinates in PCL Visualizer");
std::string keyMsg3D ("Key event for PCL Visualizer");
p->registerMouseCallback (&mouse_callback, (void*)(&mouseMsg3D));
p->registerKeyboardCallback(&keyboard_callback, (void*)(&keyMsg3D));
grabber->start ();
while (true)
{
if (!cloud_)
{
boost::this_thread::sleep(boost::posix_time::microseconds(10000));
continue;
}
boost::mutex::scoped_lock lock (mutex_);
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr temp_cloud;
temp_cloud.swap (cloud_);
if (!p->updatePointCloud (temp_cloud, "PCDCloud"))
{
p->addPointCloud (temp_cloud, "PCDCloud");
p->resetCameraViewpoint ("PCDCloud");
}
p->spinOnce ();
if (p->wasStopped ())
break;
}
grabber->stop ();
}
/* ]--- */
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/socket/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif
static const size_t kPathBufSize = 2048;
using WebKit::WebScriptController;
namespace {
// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;
void RemoveSharedMemoryFile(std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(UTF8ToWide(filename));
#endif
}
} // namespace
int main(int argc, char* argv[]) {
base::EnableInProcessStackDumping();
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
bool suppress_error_dialogs = (
base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
bool classic_theme =
parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#if defined(OS_WIN)
bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
// Stop compiler warnings about unused variables.
ux_theme = ux_theme;
#endif
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
bool allow_external_pages =
parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path =
parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, cache_mode, layout_test_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
// On Linux and Mac, load the test root certificate.
net::TestServerLauncher ssl_util;
ssl_util.LoadTestRootCert();
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
TestShellWebTheme::Engine engine;
#endif
if (classic_theme)
platform.SelectUnifiedTheme();
#if defined(OS_WIN)
if (generic_theme)
test_shell_webkit_init.SetThemeEngine(&engine);
#endif
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms =
static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Treat the first loose value as the initial URL to open.
GURL starting_url;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("webkit");
path = path.AppendASCII("data");
path = path.AppendASCII("test_shell");
path = path.AppendASCII("index.html");
starting_url = net::FilePathToFileURL(path);
}
std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
if (loose_values.size() > 0) {
GURL url(WideToUTF16Hack(loose_values[0]));
if (url.is_valid()) {
starting_url = url;
} else {
// Treat as a file path
starting_url =
net::FilePathToFileURL(FilePath::FromWStringHack(loose_values[0]));
}
}
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += L" --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebScriptController::registerExtension(
extensions_v8::ProfilerExtension::Get());
}
if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
WebScriptController::registerExtension(
extensions_v8::HeapProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
std::string stats_filename =
kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
RemoveSharedMemoryFile(stats_filename);
StatsTable *table = new StatsTable(stats_filename,
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(starting_url, &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebScriptController::registerExtension(
extensions_v8::PlaybackExtension::Get());
}
shell->Show(WebKit::WebNavigationPolicyNewWindow);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (!starting_url.is_valid()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
// Set the current path to the directory that contains the test
// files. This is because certain test file may use the relative
// path.
GURL test_url(params.test_url);
FilePath test_file_path;
net::FileURLToFilePath(test_url, &test_file_path);
file_util::SetCurrentDirectory(test_file_path.DirName());
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = WideToUTF8(loose_values[0]);
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
// Flush any remaining messages before we kill ourselves.
// http://code.google.com/p/chromium/issues/detail?id=9500
MessageLoop::current()->RunAllPending();
} else {
MessageLoop::current()->Run();
}
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
RemoveSharedMemoryFile(stats_filename);
return 0;
}
<commit_msg>test_shell: allow relative paths on the command line<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/socket/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif
static const size_t kPathBufSize = 2048;
using WebKit::WebScriptController;
namespace {
// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;
void RemoveSharedMemoryFile(std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(UTF8ToWide(filename));
#endif
}
} // namespace
int main(int argc, char* argv[]) {
base::EnableInProcessStackDumping();
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
bool suppress_error_dialogs = (
base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
bool classic_theme =
parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#if defined(OS_WIN)
bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
// Stop compiler warnings about unused variables.
ux_theme = ux_theme;
#endif
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
bool allow_external_pages =
parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path =
parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, cache_mode, layout_test_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
// On Linux and Mac, load the test root certificate.
net::TestServerLauncher ssl_util;
ssl_util.LoadTestRootCert();
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
TestShellWebTheme::Engine engine;
#endif
if (classic_theme)
platform.SelectUnifiedTheme();
#if defined(OS_WIN)
if (generic_theme)
test_shell_webkit_init.SetThemeEngine(&engine);
#endif
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms =
static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Treat the first loose value as the initial URL to open.
GURL starting_url;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("webkit");
path = path.AppendASCII("data");
path = path.AppendASCII("test_shell");
path = path.AppendASCII("index.html");
starting_url = net::FilePathToFileURL(path);
}
std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
if (loose_values.size() > 0) {
GURL url(WideToUTF16Hack(loose_values[0]));
if (url.is_valid()) {
starting_url = url;
} else {
// Treat as a relative file path.
FilePath path = FilePath::FromWStringHack(loose_values[0]);
file_util::AbsolutePath(&path);
starting_url = net::FilePathToFileURL(path);
}
}
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += L" --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebScriptController::registerExtension(
extensions_v8::ProfilerExtension::Get());
}
if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
WebScriptController::registerExtension(
extensions_v8::HeapProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
std::string stats_filename =
kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
RemoveSharedMemoryFile(stats_filename);
StatsTable *table = new StatsTable(stats_filename,
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(starting_url, &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebScriptController::registerExtension(
extensions_v8::PlaybackExtension::Get());
}
shell->Show(WebKit::WebNavigationPolicyNewWindow);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (!starting_url.is_valid()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
// Set the current path to the directory that contains the test
// files. This is because certain test file may use the relative
// path.
GURL test_url(params.test_url);
FilePath test_file_path;
net::FileURLToFilePath(test_url, &test_file_path);
file_util::SetCurrentDirectory(test_file_path.DirName());
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = WideToUTF8(loose_values[0]);
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
// Flush any remaining messages before we kill ourselves.
// http://code.google.com/p/chromium/issues/detail?id=9500
MessageLoop::current()->RunAllPending();
} else {
MessageLoop::current()->Run();
}
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
RemoveSharedMemoryFile(stats_filename);
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include "GraphicHelpers.hxx"
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <rtl/oustringostreaminserter.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include "dmapperLoggers.hxx"
namespace writerfilter {
namespace dmapper {
using namespace ::com::sun::star;
OLEHandler::OLEHandler() :
LoggedProperties(dmapper_logger, "OLEHandler"),
m_nDxaOrig(0),
m_nDyaOrig(0),
m_nWrapMode(1)
{
}
OLEHandler::~OLEHandler()
{
}
void OLEHandler::lcl_attribute(Id rName, Value & rVal)
{
rtl::OUString sStringValue = rVal.getString();
(void)rName;
switch( rName )
{
case NS_ooxml::LN_CT_OLEObject_Type:
m_sObjectType = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ProgID:
m_sProgId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ShapeID:
m_sShapeId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_DrawAspect:
m_sDrawAspect = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ObjectID:
m_sObjectId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_r_id:
m_sr_id = sStringValue;
break;
case NS_ooxml::LN_inputstream:
rVal.getAny() >>= m_xInputStream;
break;
case NS_ooxml::LN_CT_Object_dxaOrig:
m_nDxaOrig = rVal.getInt();
break;
case NS_ooxml::LN_CT_Object_dyaOrig:
m_nDyaOrig = rVal.getInt();
break;
case NS_ooxml::LN_shape:
{
uno::Reference< drawing::XShape > xTempShape;
rVal.getAny() >>= xTempShape;
if( xTempShape.is() )
{
m_xShape.set( xTempShape );
try
{
m_aShapeSize = xTempShape->getSize();
m_aShapePosition = xTempShape->getPosition();
uno::Reference< beans::XPropertySet > xShapeProps( xTempShape, uno::UNO_QUERY_THROW );
PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();
xShapeProps->getPropertyValue( rNameSupplier.GetName( PROP_BITMAP ) ) >>= m_xReplacement;
xShapeProps->setPropertyValue(
rNameSupplier.GetName( PROP_SURROUND ),
uno::makeAny( m_nWrapMode ) );
}
catch( const uno::Exception& e )
{
SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
}
}
}
break;
default:
OSL_FAIL( "unknown attribute");
}
}
void OLEHandler::lcl_sprm(Sprm & rSprm)
{
sal_uInt32 nSprmId = rSprm.getId();
switch( nSprmId )
{
case NS_ooxml::LN_OLEObject_OLEObject:
{
writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
if( pProperties.get())
{
pProperties->resolve(*this);
}
}
break;
case NS_ooxml::LN_wrap_wrap:
{
writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
if ( pProperties.get( ) )
{
WrapHandlerPtr pHandler( new WrapHandler );
pProperties->resolve( *pHandler );
m_nWrapMode = pHandler->getWrapMode( );
try
{
uno::Reference< beans::XPropertySet > xShapeProps( m_xShape, uno::UNO_QUERY_THROW );
PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();
xShapeProps->setPropertyValue(
rNameSupplier.GetName( PROP_SURROUND ),
uno::makeAny( m_nWrapMode ) );
}
catch( const uno::Exception& e )
{
SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
}
}
}
break;
default:
{
OSL_FAIL( "unknown attribute");
}
}
}
::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
::rtl::OUString sRet;
if( !m_xInputStream.is( ) )
return sRet;
try
{
uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
xFactory->createInstance(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
//hack to work with the ImportEmbeddedObjectResolver
static sal_Int32 nObjectCount = 100;
uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
aURL += ::rtl::OUString::valueOf( nObjectCount++ );
uno::Reference < io::XOutputStream > xOLEStream;
if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
{
const sal_Int32 nReadRequest = 0x1000;
uno::Sequence< sal_Int8 > aData;
while( true )
{
sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
xOLEStream->writeBytes( aData );
if( nRead < nReadRequest )
{
xOLEStream->closeOutput();
break;
}
}
static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
sRet = aPersistName.copy( sProtocol.getLength() );
}
uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
xComp->dispose();
}
catch( const uno::Exception& )
{
OSL_FAIL("exception in OLEHandler::createOLEObject");
}
return sRet;
}
} //namespace dmapper
} //namespace writerfilter
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>n#758883 dmapper: set wrap mode even if determining the position failed<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include "GraphicHelpers.hxx"
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <rtl/oustringostreaminserter.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include "dmapperLoggers.hxx"
namespace writerfilter {
namespace dmapper {
using namespace ::com::sun::star;
OLEHandler::OLEHandler() :
LoggedProperties(dmapper_logger, "OLEHandler"),
m_nDxaOrig(0),
m_nDyaOrig(0),
m_nWrapMode(1)
{
}
OLEHandler::~OLEHandler()
{
}
void OLEHandler::lcl_attribute(Id rName, Value & rVal)
{
rtl::OUString sStringValue = rVal.getString();
(void)rName;
switch( rName )
{
case NS_ooxml::LN_CT_OLEObject_Type:
m_sObjectType = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ProgID:
m_sProgId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ShapeID:
m_sShapeId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_DrawAspect:
m_sDrawAspect = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_ObjectID:
m_sObjectId = sStringValue;
break;
case NS_ooxml::LN_CT_OLEObject_r_id:
m_sr_id = sStringValue;
break;
case NS_ooxml::LN_inputstream:
rVal.getAny() >>= m_xInputStream;
break;
case NS_ooxml::LN_CT_Object_dxaOrig:
m_nDxaOrig = rVal.getInt();
break;
case NS_ooxml::LN_CT_Object_dyaOrig:
m_nDyaOrig = rVal.getInt();
break;
case NS_ooxml::LN_shape:
{
uno::Reference< drawing::XShape > xTempShape;
rVal.getAny() >>= xTempShape;
if( xTempShape.is() )
{
m_xShape.set( xTempShape );
uno::Reference< beans::XPropertySet > xShapeProps( xTempShape, uno::UNO_QUERY );
PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();
try
{
m_aShapeSize = xTempShape->getSize();
m_aShapePosition = xTempShape->getPosition();
xShapeProps->getPropertyValue( rNameSupplier.GetName( PROP_BITMAP ) ) >>= m_xReplacement;
}
catch( const uno::Exception& e )
{
SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
}
try
{
xShapeProps->setPropertyValue(
rNameSupplier.GetName( PROP_SURROUND ),
uno::makeAny( m_nWrapMode ) );
}
catch( const uno::Exception& e )
{
SAL_WARN("writerfilter", "Exception while setting wrap mode: " << e.Message);
}
}
}
break;
default:
OSL_FAIL( "unknown attribute");
}
}
void OLEHandler::lcl_sprm(Sprm & rSprm)
{
sal_uInt32 nSprmId = rSprm.getId();
switch( nSprmId )
{
case NS_ooxml::LN_OLEObject_OLEObject:
{
writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
if( pProperties.get())
{
pProperties->resolve(*this);
}
}
break;
case NS_ooxml::LN_wrap_wrap:
{
writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
if ( pProperties.get( ) )
{
WrapHandlerPtr pHandler( new WrapHandler );
pProperties->resolve( *pHandler );
m_nWrapMode = pHandler->getWrapMode( );
try
{
uno::Reference< beans::XPropertySet > xShapeProps( m_xShape, uno::UNO_QUERY_THROW );
PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();
xShapeProps->setPropertyValue(
rNameSupplier.GetName( PROP_SURROUND ),
uno::makeAny( m_nWrapMode ) );
}
catch( const uno::Exception& e )
{
SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
}
}
}
break;
default:
{
OSL_FAIL( "unknown attribute");
}
}
}
::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
::rtl::OUString sRet;
if( !m_xInputStream.is( ) )
return sRet;
try
{
uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
xFactory->createInstance(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
//hack to work with the ImportEmbeddedObjectResolver
static sal_Int32 nObjectCount = 100;
uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
aURL += ::rtl::OUString::valueOf( nObjectCount++ );
uno::Reference < io::XOutputStream > xOLEStream;
if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
{
const sal_Int32 nReadRequest = 0x1000;
uno::Sequence< sal_Int8 > aData;
while( true )
{
sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
xOLEStream->writeBytes( aData );
if( nRead < nReadRequest )
{
xOLEStream->closeOutput();
break;
}
}
static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
sRet = aPersistName.copy( sProtocol.getLength() );
}
uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
xComp->dispose();
}
catch( const uno::Exception& )
{
OSL_FAIL("exception in OLEHandler::createOLEObject");
}
return sRet;
}
} //namespace dmapper
} //namespace writerfilter
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: util.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdlib.h>
#include <fstream>
#include <string>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/drawing/BitmapMode.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <resourcemodel/WW8ResourceModel.hxx>
namespace writerfilter
{
using namespace com::sun::star;
using namespace std;
using text::TextContentAnchorType;
static string & logger_file()
{
static string _logger_file = string(getenv("TEMP")?getenv("TEMP"):"/tmp") + "/writerfilter.ooxml.tmp";
return _logger_file;
}
static ofstream & logger_stream()
{
static ofstream _logger_stream(logger_file().c_str());
return _logger_stream;
}
void logger(string prefix, string message)
{
logger_stream() << prefix << ":" << message << endl;
logger_stream().flush();
}
string propertysetToString(uno::Reference<beans::XPropertySet> const & xPropSet)
{
string sResult;
static int nAttribNames = 9;
static string sPropertyAttribNames[9] =
{
"MAYBEVOID",
"BOUND",
"CONSTRAINED",
"TRANSIENT",
"READONLY",
"MAYBEAMBIGUOUS",
"MAYBEDEFAULT",
"REMOVEABLE",
"OPTIONAL"
};
uno::Reference<beans::XPropertySetInfo> xPropSetInfo
(xPropSet->getPropertySetInfo());
if (xPropSetInfo.is())
{
uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());
sResult +="<propertyset>";
for (sal_Int32 n = 0; n < aProps.getLength(); n++)
{
::rtl::OUString sPropName(aProps[n].Name);
if (xPropSetInfo->hasPropertyByName(sPropName))
{
uno::Any aAny;
try
{
xPropSet->getPropertyValue(sPropName) >>= aAny;
}
catch (beans::UnknownPropertyException)
{
sResult += "<unknown-property>";
sResult += OUStringToOString
(sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
sResult += "</unknown-property>";
}
if (aAny.hasValue())
{
sResult += "<property name=\"";
sResult += OUStringToOString
(sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
sResult +="\" type=\"";
::rtl::OUString sPropType(aProps[n].Type.getTypeName());
sResult += OUStringToOString
(sPropType, RTL_TEXTENCODING_ASCII_US).getStr();
sResult += "\" attribs=\"";
sal_uInt16 nMask = 1;
bool bFirstAttrib = true;
sal_uInt16 nAttribs = aProps[n].Attributes;
for (int i = 0; i < nAttribNames; i++)
{
if ((nAttribs & nMask) != 0)
{
if (bFirstAttrib)
bFirstAttrib = false;
else
sResult += "|";
sResult += sPropertyAttribNames[i];
}
nMask <<= 1;
}
sResult += "\">";
char buffer[256];
if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("byte")))
{
sal_Int8 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%d", nValue);
sResult += buffer;
}
if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("short")))
{
sal_Int16 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%d", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("long")))
{
sal_Int32 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%" SAL_PRIdINT32, nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("float")))
{
float nValue = 0.0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%f", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("double")))
{
double nValue = 0.0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%lf", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("boolean")))
{
sal_Bool nValue = sal_False;
aAny >>= nValue;
if (nValue)
sResult += "true";
else
sResult += "false";
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("string")))
{
::rtl::OUString sValue;
aAny >>= sValue;
sResult += OUStringToOString
(sValue, RTL_TEXTENCODING_ASCII_US).getStr();
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.text.TextContentAnchorType")))
{
text::TextContentAnchorType nValue;
aAny >>= nValue;
switch (nValue)
{
case text::TextContentAnchorType_AT_PARAGRAPH:
sResult += "AT_PARAGRAPH";
break;
case text::TextContentAnchorType_AS_CHARACTER:
sResult += "AS_CHARACTER";
break;
case text::TextContentAnchorType_AT_PAGE:
sResult += "AT_PAGE";
break;
case text::TextContentAnchorType_AT_FRAME:
sResult += "AT_FRAME";
break;
case text::TextContentAnchorType_AT_CHARACTER:
sResult += "AT_CHARACTER";
break;
case text::TextContentAnchorType_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
default:
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.awt.Point")))
{
awt::Point aPoint;
aAny >>= aPoint;
snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")", aPoint.X,
aPoint.Y);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.awt.Rectangle")))
{
awt::Rectangle aRect;
aAny >>= aRect;
snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")",
aRect.X, aRect.Y, aRect.Width, aRect.Height);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.FillStyle")))
{
drawing::FillStyle nValue;
aAny >>= nValue;
switch (nValue)
{
case drawing::FillStyle_NONE:
sResult += "NONE";
break;
case drawing::FillStyle_SOLID:
sResult += "SOLID";
break;
case drawing::FillStyle_GRADIENT:
sResult += "GRADIENT";
break;
case drawing::FillStyle_HATCH:
sResult += "HATCH";
break;
case drawing::FillStyle_BITMAP:
sResult += "BITMAP";
break;
case drawing::FillStyle_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.BitmapMode")))
{
drawing::BitmapMode nValue;
aAny >>= nValue;
switch (nValue)
{
case drawing::BitmapMode_REPEAT:
sResult += "REPEAT";
break;
case drawing::BitmapMode_STRETCH:
sResult += "STRETCH";
break;
case drawing::BitmapMode_NO_REPEAT:
sResult += "NO_REPEAT";
break;
case drawing::BitmapMode_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.HomogenMatrix3")))
{
drawing::HomogenMatrix3 aMatrix;
aAny >>= aMatrix;
snprintf(buffer, sizeof(buffer),
"((%f %f %f)(%f %f %f)(%f %f %f))",
aMatrix.Line1.Column1,
aMatrix.Line1.Column2,
aMatrix.Line1.Column3,
aMatrix.Line2.Column1,
aMatrix.Line2.Column2,
aMatrix.Line2.Column3,
aMatrix.Line3.Column1,
aMatrix.Line3.Column2,
aMatrix.Line3.Column3);
sResult += buffer;
}
sResult += "</property>";
}
}
}
sResult += "</propertyset>";
}
return sResult;
}
}
<commit_msg>INTEGRATION: CWS hr51 (1.3.10); FILE MERGED 2008/06/06 14:12:15 hr 1.3.10.1: #i88947#: includes<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: util.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/drawing/BitmapMode.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <resourcemodel/WW8ResourceModel.hxx>
namespace writerfilter
{
using namespace com::sun::star;
using namespace std;
using text::TextContentAnchorType;
static string & logger_file()
{
static string _logger_file = string(getenv("TEMP")?getenv("TEMP"):"/tmp") + "/writerfilter.ooxml.tmp";
return _logger_file;
}
static ofstream & logger_stream()
{
static ofstream _logger_stream(logger_file().c_str());
return _logger_stream;
}
void logger(string prefix, string message)
{
logger_stream() << prefix << ":" << message << endl;
logger_stream().flush();
}
string propertysetToString(uno::Reference<beans::XPropertySet> const & xPropSet)
{
string sResult;
static int nAttribNames = 9;
static string sPropertyAttribNames[9] =
{
"MAYBEVOID",
"BOUND",
"CONSTRAINED",
"TRANSIENT",
"READONLY",
"MAYBEAMBIGUOUS",
"MAYBEDEFAULT",
"REMOVEABLE",
"OPTIONAL"
};
uno::Reference<beans::XPropertySetInfo> xPropSetInfo
(xPropSet->getPropertySetInfo());
if (xPropSetInfo.is())
{
uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());
sResult +="<propertyset>";
for (sal_Int32 n = 0; n < aProps.getLength(); n++)
{
::rtl::OUString sPropName(aProps[n].Name);
if (xPropSetInfo->hasPropertyByName(sPropName))
{
uno::Any aAny;
try
{
xPropSet->getPropertyValue(sPropName) >>= aAny;
}
catch (beans::UnknownPropertyException)
{
sResult += "<unknown-property>";
sResult += OUStringToOString
(sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
sResult += "</unknown-property>";
}
if (aAny.hasValue())
{
sResult += "<property name=\"";
sResult += OUStringToOString
(sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
sResult +="\" type=\"";
::rtl::OUString sPropType(aProps[n].Type.getTypeName());
sResult += OUStringToOString
(sPropType, RTL_TEXTENCODING_ASCII_US).getStr();
sResult += "\" attribs=\"";
sal_uInt16 nMask = 1;
bool bFirstAttrib = true;
sal_uInt16 nAttribs = aProps[n].Attributes;
for (int i = 0; i < nAttribNames; i++)
{
if ((nAttribs & nMask) != 0)
{
if (bFirstAttrib)
bFirstAttrib = false;
else
sResult += "|";
sResult += sPropertyAttribNames[i];
}
nMask <<= 1;
}
sResult += "\">";
char buffer[256];
if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("byte")))
{
sal_Int8 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%d", nValue);
sResult += buffer;
}
if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("short")))
{
sal_Int16 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%d", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("long")))
{
sal_Int32 nValue = 0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%" SAL_PRIdINT32, nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("float")))
{
float nValue = 0.0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%f", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("double")))
{
double nValue = 0.0;
aAny >>= nValue;
snprintf(buffer, sizeof(buffer), "%lf", nValue);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("boolean")))
{
sal_Bool nValue = sal_False;
aAny >>= nValue;
if (nValue)
sResult += "true";
else
sResult += "false";
}
else if (sPropType ==
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("string")))
{
::rtl::OUString sValue;
aAny >>= sValue;
sResult += OUStringToOString
(sValue, RTL_TEXTENCODING_ASCII_US).getStr();
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.text.TextContentAnchorType")))
{
text::TextContentAnchorType nValue;
aAny >>= nValue;
switch (nValue)
{
case text::TextContentAnchorType_AT_PARAGRAPH:
sResult += "AT_PARAGRAPH";
break;
case text::TextContentAnchorType_AS_CHARACTER:
sResult += "AS_CHARACTER";
break;
case text::TextContentAnchorType_AT_PAGE:
sResult += "AT_PAGE";
break;
case text::TextContentAnchorType_AT_FRAME:
sResult += "AT_FRAME";
break;
case text::TextContentAnchorType_AT_CHARACTER:
sResult += "AT_CHARACTER";
break;
case text::TextContentAnchorType_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
default:
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.awt.Point")))
{
awt::Point aPoint;
aAny >>= aPoint;
snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")", aPoint.X,
aPoint.Y);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.awt.Rectangle")))
{
awt::Rectangle aRect;
aAny >>= aRect;
snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")",
aRect.X, aRect.Y, aRect.Width, aRect.Height);
sResult += buffer;
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.FillStyle")))
{
drawing::FillStyle nValue;
aAny >>= nValue;
switch (nValue)
{
case drawing::FillStyle_NONE:
sResult += "NONE";
break;
case drawing::FillStyle_SOLID:
sResult += "SOLID";
break;
case drawing::FillStyle_GRADIENT:
sResult += "GRADIENT";
break;
case drawing::FillStyle_HATCH:
sResult += "HATCH";
break;
case drawing::FillStyle_BITMAP:
sResult += "BITMAP";
break;
case drawing::FillStyle_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.BitmapMode")))
{
drawing::BitmapMode nValue;
aAny >>= nValue;
switch (nValue)
{
case drawing::BitmapMode_REPEAT:
sResult += "REPEAT";
break;
case drawing::BitmapMode_STRETCH:
sResult += "STRETCH";
break;
case drawing::BitmapMode_NO_REPEAT:
sResult += "NO_REPEAT";
break;
case drawing::BitmapMode_MAKE_FIXED_SIZE:
sResult += "MAKE_FIXED_SIZE";
break;
}
}
else if (sPropType ==
::rtl::OUString
(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.drawing.HomogenMatrix3")))
{
drawing::HomogenMatrix3 aMatrix;
aAny >>= aMatrix;
snprintf(buffer, sizeof(buffer),
"((%f %f %f)(%f %f %f)(%f %f %f))",
aMatrix.Line1.Column1,
aMatrix.Line1.Column2,
aMatrix.Line1.Column3,
aMatrix.Line2.Column1,
aMatrix.Line2.Column2,
aMatrix.Line2.Column3,
aMatrix.Line3.Column1,
aMatrix.Line3.Column2,
aMatrix.Line3.Column3);
sResult += buffer;
}
sResult += "</property>";
}
}
}
sResult += "</propertyset>";
}
return sResult;
}
}
<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_CONTAINER_HH__
#define __RAPICORN_CONTAINER_HH__
#include <ui/widget.hh>
namespace Rapicorn {
class ResizeContainerImpl;
// == FocusIndicator ==
class FocusIndicator : public virtual Aida::ImplicitBase {
public:
virtual void focusable_container_change (ContainerImpl&) = 0;
};
// == Container ==
struct ContainerImpl : public virtual WidgetImpl, public virtual ContainerIface {
friend class WidgetImpl;
friend class WindowImpl;
void uncross_descendant (WidgetImpl &descendant);
size_t widget_cross_link (WidgetImpl &owner,
WidgetImpl &link,
const WidgetSlot &uncross);
void widget_cross_unlink (WidgetImpl &owner,
WidgetImpl &link,
size_t link_id);
void widget_uncross_links (WidgetImpl &owner,
WidgetImpl &link);
WidgetGroup* retrieve_widget_group (const String &group_name, WidgetGroupType group_type, bool force_create);
protected:
virtual ~ContainerImpl ();
virtual void do_changed (const String &name) override;
virtual void add_child (WidgetImpl &widget) = 0;
virtual void repack_child (WidgetImpl &widget, const PackInfo &orig, const PackInfo &pnew);
virtual void remove_child (WidgetImpl &widget) = 0;
virtual void unparent_child (WidgetImpl &widget);
virtual void dispose_widget (WidgetImpl &widget);
virtual void hierarchy_changed (WidgetImpl *old_toplevel);
virtual bool move_focus (FocusDir fdir);
void expose_enclosure (); /* expose without children */
void change_unviewable (WidgetImpl &child, bool);
virtual void focus_lost () { set_focus_child (NULL); }
virtual void set_focus_child (WidgetImpl *widget);
virtual void scroll_to_child (WidgetImpl &widget);
virtual void dump_test_data (TestStream &tstream);
static Allocation layout_child (WidgetImpl &child, const Allocation &carea);
static Requisition size_request_child (WidgetImpl &child, bool *hspread, bool *vspread);
public:
virtual WidgetImplP* begin () const = 0;
virtual WidgetImplP* end () const = 0;
WidgetImpl* get_focus_child () const;
void register_focus_indicator (FocusIndicator&);
void unregister_focus_indicator (FocusIndicator&);
virtual void foreach_recursive (const std::function<void (WidgetImpl&)> &f) override;
void child_container (ContainerImpl *child_container);
ContainerImpl& child_container ();
virtual size_t n_children () = 0;
virtual WidgetImpl* nth_child (size_t nth) = 0;
bool has_children () { return 0 != n_children(); }
bool remove (WidgetImpl &widget);
bool remove (WidgetImpl *widget) { assert_return (widget != NULL, 0); return remove (*widget); }
void add (WidgetImpl &widget);
void add (WidgetImpl *widget);
virtual Affine child_affine (const WidgetImpl &widget); /* container => widget affine */
virtual void point_children (Point p, /* widget coordinates relative */
std::vector<WidgetImplP> &stack);
void display_window_point_children (Point p, /* display_window coordinates relative */
std::vector<WidgetImplP> &stack);
virtual ContainerImpl* as_container_impl () { return this; }
virtual void render_recursive(RenderContext &rcontext);
void debug_tree (String indent = String());
// ContainerIface
virtual WidgetIfaceP create_widget (const String &widget_identifier, const StringSeq &args) override;
virtual void remove_widget (WidgetIface &child) override;
};
// == Single Child Container ==
class SingleContainerImpl : public virtual ContainerImpl {
WidgetImplP child_widget;
protected:
virtual void size_request (Requisition &requisition);
virtual void size_allocate (Allocation area, bool changed);
virtual void render (RenderContext&, const Rect&) {}
WidgetImpl& get_child () { critical_unless (child_widget != NULL); return *child_widget; }
virtual ~SingleContainerImpl ();
virtual WidgetImplP* begin () const override;
virtual WidgetImplP* end () const override;
virtual size_t n_children () { return child_widget ? 1 : 0; }
virtual WidgetImpl* nth_child (size_t nth) { return nth == 0 ? child_widget.get() : NULL; }
bool has_visible_child () { return child_widget && child_widget->visible(); }
bool has_drawable_child () { return child_widget && child_widget->drawable(); }
virtual void add_child (WidgetImpl &widget);
virtual void remove_child (WidgetImpl &widget);
explicit SingleContainerImpl ();
};
// == AnchorInfo ==
struct AnchorInfo {
ResizeContainerImpl *resize_container;
ViewportImpl *viewport;
WindowImpl *window;
constexpr AnchorInfo() : resize_container (NULL), viewport (NULL), window (NULL) {}
};
// == Resize Container ==
class ResizeContainerImpl : public virtual SingleContainerImpl {
uint tunable_requisition_counter_;
uint resizer_;
AnchorInfo anchor_info_;
void idle_sizing ();
void update_anchor_info ();
protected:
virtual void invalidate_parent ();
virtual void hierarchy_changed (WidgetImpl *old_toplevel);
void negotiate_size (const Allocation *carea);
explicit ResizeContainerImpl ();
virtual ~ResizeContainerImpl ();
public:
bool requisitions_tunable () const { return tunable_requisition_counter_ > 0; }
AnchorInfo* container_anchor_info () { return &anchor_info_; }
};
// == Multi Child Container ==
class MultiContainerImpl : public virtual ContainerImpl {
std::vector<WidgetImplP> widgets;
protected:
virtual ~MultiContainerImpl ();
virtual void render (RenderContext&, const Rect&) {}
virtual WidgetImplP* begin () const override;
virtual WidgetImplP* end () const override;
virtual size_t n_children () { return widgets.size(); }
virtual WidgetImpl* nth_child (size_t nth) { return nth < widgets.size() ? widgets[nth].get() : NULL; }
virtual void add_child (WidgetImpl &widget);
virtual void remove_child (WidgetImpl &widget);
void raise_child (WidgetImpl &widget);
void lower_child (WidgetImpl &widget);
void remove_all_children ();
explicit MultiContainerImpl ();
};
} // Rapicorn
#endif /* __RAPICORN_CONTAINER_HH__ */
<commit_msg>UI: sort out MultiContainerImpl public methods<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_CONTAINER_HH__
#define __RAPICORN_CONTAINER_HH__
#include <ui/widget.hh>
namespace Rapicorn {
class ResizeContainerImpl;
// == FocusIndicator ==
class FocusIndicator : public virtual Aida::ImplicitBase {
public:
virtual void focusable_container_change (ContainerImpl&) = 0;
};
// == Container ==
struct ContainerImpl : public virtual WidgetImpl, public virtual ContainerIface {
friend class WidgetImpl;
friend class WindowImpl;
void uncross_descendant (WidgetImpl &descendant);
size_t widget_cross_link (WidgetImpl &owner,
WidgetImpl &link,
const WidgetSlot &uncross);
void widget_cross_unlink (WidgetImpl &owner,
WidgetImpl &link,
size_t link_id);
void widget_uncross_links (WidgetImpl &owner,
WidgetImpl &link);
WidgetGroup* retrieve_widget_group (const String &group_name, WidgetGroupType group_type, bool force_create);
protected:
virtual ~ContainerImpl ();
virtual void do_changed (const String &name) override;
virtual void add_child (WidgetImpl &widget) = 0;
virtual void repack_child (WidgetImpl &widget, const PackInfo &orig, const PackInfo &pnew);
virtual void remove_child (WidgetImpl &widget) = 0;
virtual void unparent_child (WidgetImpl &widget);
virtual void dispose_widget (WidgetImpl &widget);
virtual void hierarchy_changed (WidgetImpl *old_toplevel);
virtual bool move_focus (FocusDir fdir);
void expose_enclosure (); /* expose without children */
void change_unviewable (WidgetImpl &child, bool);
virtual void focus_lost () { set_focus_child (NULL); }
virtual void set_focus_child (WidgetImpl *widget);
virtual void scroll_to_child (WidgetImpl &widget);
virtual void dump_test_data (TestStream &tstream);
static Allocation layout_child (WidgetImpl &child, const Allocation &carea);
static Requisition size_request_child (WidgetImpl &child, bool *hspread, bool *vspread);
public:
virtual WidgetImplP* begin () const = 0;
virtual WidgetImplP* end () const = 0;
WidgetImpl* get_focus_child () const;
void register_focus_indicator (FocusIndicator&);
void unregister_focus_indicator (FocusIndicator&);
virtual void foreach_recursive (const std::function<void (WidgetImpl&)> &f) override;
void child_container (ContainerImpl *child_container);
ContainerImpl& child_container ();
virtual size_t n_children () = 0;
virtual WidgetImpl* nth_child (size_t nth) = 0;
bool has_children () { return 0 != n_children(); }
bool remove (WidgetImpl &widget);
bool remove (WidgetImpl *widget) { assert_return (widget != NULL, 0); return remove (*widget); }
void add (WidgetImpl &widget);
void add (WidgetImpl *widget);
virtual Affine child_affine (const WidgetImpl &widget); /* container => widget affine */
virtual void point_children (Point p, /* widget coordinates relative */
std::vector<WidgetImplP> &stack);
void display_window_point_children (Point p, /* display_window coordinates relative */
std::vector<WidgetImplP> &stack);
virtual ContainerImpl* as_container_impl () { return this; }
virtual void render_recursive(RenderContext &rcontext);
void debug_tree (String indent = String());
// ContainerIface
virtual WidgetIfaceP create_widget (const String &widget_identifier, const StringSeq &args) override;
virtual void remove_widget (WidgetIface &child) override;
};
// == Single Child Container ==
class SingleContainerImpl : public virtual ContainerImpl {
WidgetImplP child_widget;
protected:
virtual void size_request (Requisition &requisition);
virtual void size_allocate (Allocation area, bool changed);
virtual void render (RenderContext&, const Rect&) {}
WidgetImpl& get_child () { critical_unless (child_widget != NULL); return *child_widget; }
virtual ~SingleContainerImpl ();
virtual WidgetImplP* begin () const override;
virtual WidgetImplP* end () const override;
virtual size_t n_children () { return child_widget ? 1 : 0; }
virtual WidgetImpl* nth_child (size_t nth) { return nth == 0 ? child_widget.get() : NULL; }
bool has_visible_child () { return child_widget && child_widget->visible(); }
bool has_drawable_child () { return child_widget && child_widget->drawable(); }
virtual void add_child (WidgetImpl &widget);
virtual void remove_child (WidgetImpl &widget);
explicit SingleContainerImpl ();
};
// == AnchorInfo ==
struct AnchorInfo {
ResizeContainerImpl *resize_container;
ViewportImpl *viewport;
WindowImpl *window;
constexpr AnchorInfo() : resize_container (NULL), viewport (NULL), window (NULL) {}
};
// == Resize Container ==
class ResizeContainerImpl : public virtual SingleContainerImpl {
uint tunable_requisition_counter_;
uint resizer_;
AnchorInfo anchor_info_;
void idle_sizing ();
void update_anchor_info ();
protected:
virtual void invalidate_parent ();
virtual void hierarchy_changed (WidgetImpl *old_toplevel);
void negotiate_size (const Allocation *carea);
explicit ResizeContainerImpl ();
virtual ~ResizeContainerImpl ();
public:
bool requisitions_tunable () const { return tunable_requisition_counter_ > 0; }
AnchorInfo* container_anchor_info () { return &anchor_info_; }
};
// == Multi Child Container ==
class MultiContainerImpl : public virtual ContainerImpl {
std::vector<WidgetImplP> widgets;
protected:
virtual ~MultiContainerImpl ();
virtual void render (RenderContext&, const Rect&) override {}
virtual void add_child (WidgetImpl &widget) override;
virtual void remove_child (WidgetImpl &widget) override;
explicit MultiContainerImpl ();
public:
virtual WidgetImplP* begin () const override;
virtual WidgetImplP* end () const override;
virtual size_t n_children () override { return widgets.size(); }
virtual WidgetImpl* nth_child (size_t nth) override { return nth < widgets.size() ? widgets[nth].get() : NULL; }
void raise_child (WidgetImpl &widget);
void lower_child (WidgetImpl &widget);
void remove_all_children ();
};
} // Rapicorn
#endif /* __RAPICORN_CONTAINER_HH__ */
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
* Copyright (C) 2010 Dan Leinir Turthra Jensen <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*/
#include "gameprojectprivate.h"
#include "savable.h"
#include "achievement.h"
#include <core/gluonobject.h>
#include <core/debughelper.h>
#include <QtCore/QStringList>
#include <QtCore/QDir>
using namespace GluonEngine;
GameProjectPrivate::GameProjectPrivate()
: entryPoint( 0 )
, icon( 0 )
, screenshot( 0 )
, userName( "user" )
{
}
GameProjectPrivate::GameProjectPrivate( const GameProjectPrivate& other )
: QSharedData( other )
, description( other.description )
, homepage( other.homepage )
, mediaInfo( other.mediaInfo )
, filename( other.filename )
, dirname( other.dirname )
, entryPoint( other.entryPoint )
, icon( other.icon )
, screenshot( other.screenshot )
, userName( other.userName )
{
}
GameProjectPrivate::~GameProjectPrivate()
{
}
bool
GameProjectPrivate::saveChildren( const GluonCore::GluonObject* parent )
{
DEBUG_FUNC_NAME
if( !parent )
{
DEBUG_TEXT( QString( "Object child was null!" ) )
return false;
}
for( int i = 0; i < parent->children().size(); ++i )
{
GluonCore::GluonObject* child = parent->child( i );
if( child && Savable::saveToFile( child ) )
{
DEBUG_TEXT2( "Saved object named %1", child->name() )
}
// Recurse!
saveChildren( qobject_cast<const GluonCore::GluonObject*>( child ) );
}
return true;
}
<commit_msg>Engine: Debug--;<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
* Copyright (C) 2010 Dan Leinir Turthra Jensen <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*/
#include "gameprojectprivate.h"
#include "savable.h"
#include "achievement.h"
#include <core/gluonobject.h>
#include <core/debughelper.h>
#include <QtCore/QStringList>
#include <QtCore/QDir>
using namespace GluonEngine;
GameProjectPrivate::GameProjectPrivate()
: entryPoint( 0 )
, icon( 0 )
, screenshot( 0 )
, userName( "user" )
{
}
GameProjectPrivate::GameProjectPrivate( const GameProjectPrivate& other )
: QSharedData( other )
, description( other.description )
, homepage( other.homepage )
, mediaInfo( other.mediaInfo )
, filename( other.filename )
, dirname( other.dirname )
, entryPoint( other.entryPoint )
, icon( other.icon )
, screenshot( other.screenshot )
, userName( other.userName )
{
}
GameProjectPrivate::~GameProjectPrivate()
{
}
bool
GameProjectPrivate::saveChildren( const GluonCore::GluonObject* parent )
{
if( !parent )
{
return false;
}
for( int i = 0; i < parent->children().size(); ++i )
{
GluonCore::GluonObject* child = parent->child( i );
if( child )
Savable::saveToFile( child );
// Recurse!
saveChildren( qobject_cast<const GluonCore::GluonObject*>( child ) );
}
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cmdlineargs.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2003-03-25 13:51: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 _DESKTOP_COMMANDLINEARGS_HXX_
#define _DESKTOP_COMMANDLINEARGS_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
namespace desktop
{
class CommandLineArgs
{
public:
enum BoolParam // must be zero based!
{
CMD_BOOLPARAM_MINIMIZED,
CMD_BOOLPARAM_INVISIBLE,
CMD_BOOLPARAM_NORESTORE,
CMD_BOOLPARAM_BEAN,
CMD_BOOLPARAM_PLUGIN,
CMD_BOOLPARAM_SERVER,
CMD_BOOLPARAM_HEADLESS,
CMD_BOOLPARAM_QUICKSTART,
CMD_BOOLPARAM_TERMINATEAFTERINIT,
CMD_BOOLPARAM_NOLOGO,
CMD_BOOLPARAM_NOLOCKCHECK,
CMD_BOOLPARAM_NODEFAULT,
CMD_BOOLPARAM_HELP,
CMD_BOOLPARAM_WRITER,
CMD_BOOLPARAM_CALC,
CMD_BOOLPARAM_DRAW,
CMD_BOOLPARAM_IMPRESS,
CMD_BOOLPARAM_GLOBAL,
CMD_BOOLPARAM_MATH,
CMD_BOOLPARAM_WEB,
CMD_BOOLPARAM_COUNT // must be last element!
};
enum StringParam // must be zero based!
{
CMD_STRINGPARAM_PORTAL,
CMD_STRINGPARAM_ACCEPT,
CMD_STRINGPARAM_UNACCEPT,
CMD_STRINGPARAM_USERDIR,
CMD_STRINGPARAM_CLIENTDISPLAY,
CMD_STRINGPARAM_OPENLIST,
CMD_STRINGPARAM_VIEWLIST,
CMD_STRINGPARAM_FORCEOPENLIST,
CMD_STRINGPARAM_FORCENEWLIST,
CMD_STRINGPARAM_PRINTLIST,
CMD_STRINGPARAM_VERSION,
CMD_STRINGPARAM_PRINTTOLIST,
CMD_STRINGPARAM_PRINTERNAME,
CMD_STRINGPARAM_COUNT // must be last element!
};
enum GroupParamId
{
CMD_GRPID_MODULE,
CMD_GRPID_COUNT
};
CommandLineArgs();
CommandLineArgs( const ::vos::OExtCommandLine& aExtCmdLine );
CommandLineArgs( const ::rtl::OUString& aIPCThreadCmdLine );
// generic methods to access parameter
sal_Bool GetBoolParam( BoolParam eParam ) const;
void SetBoolParam( BoolParam eParam, sal_Bool bNewValue );
const rtl::OUString& GetStringParam( BoolParam eParam ) const;
void SetStringParam( BoolParam eParam, const rtl::OUString& bNewValue );
// Access to bool parameters
sal_Bool IsMinimized() const;
sal_Bool IsInvisible() const;
sal_Bool IsNoRestore() const;
sal_Bool IsNoDefault() const;
sal_Bool IsBean() const;
sal_Bool IsPlugin() const;
sal_Bool IsServer() const;
sal_Bool IsHeadless() const;
sal_Bool IsQuickstart() const;
sal_Bool IsTerminateAfterInit() const;
sal_Bool IsNoLogo() const;
sal_Bool IsNoLockcheck() const;
sal_Bool IsHelp() const;
sal_Bool IsWriter() const;
sal_Bool IsCalc() const;
sal_Bool IsDraw() const;
sal_Bool IsImpress() const;
sal_Bool IsGlobal() const;
sal_Bool IsMath() const;
sal_Bool IsWeb() const;
sal_Bool HasModuleParam() const;
// Access to string parameters
sal_Bool GetPortalConnectString( ::rtl::OUString& rPara) const;
sal_Bool GetAcceptString( ::rtl::OUString& rPara) const;
sal_Bool GetUnAcceptString( ::rtl::OUString& rPara) const;
sal_Bool GetUserDir( ::rtl::OUString& rPara) const;
sal_Bool GetClientDisplay( ::rtl::OUString& rPara) const;
sal_Bool GetOpenList( ::rtl::OUString& rPara) const;
sal_Bool GetViewList( ::rtl::OUString& rPara) const;
sal_Bool GetForceOpenList( ::rtl::OUString& rPara) const;
sal_Bool GetForceNewList( ::rtl::OUString& rPara) const;
sal_Bool GetPrintList( ::rtl::OUString& rPara) const;
sal_Bool GetVersionString( ::rtl::OUString& rPara) const;
sal_Bool GetPrintToList( ::rtl::OUString& rPara ) const;
sal_Bool GetPrinterName( ::rtl::OUString& rPara ) const;
private:
struct GroupDefinition
{
sal_Int32 nCount;
BoolParam* pGroupMembers;
};
// no copy and operator=
CommandLineArgs( const CommandLineArgs& );
operator=( const CommandLineArgs& );
sal_Bool InterpretCommandLineParameter( const ::rtl::OUString& );
void ParseCommandLine_Impl( const ::vos::OExtCommandLine& );
void ParseCommandLine_String( const ::rtl::OUString& );
void ResetParamValues();
sal_Bool CheckGroupMembers( GroupParamId nGroup, BoolParam nExcludeMember ) const;
void AddStringListParam_Impl( StringParam eParam, const rtl::OUString& aParam );
void SetBoolParam_Impl( BoolParam eParam, sal_Bool bValue );
sal_Bool m_aBoolParams[ CMD_BOOLPARAM_COUNT ]; // Stores boolean parameters
rtl::OUString m_aStrParams[ CMD_STRINGPARAM_COUNT ]; // Stores string parameters
sal_Bool m_aStrSetParams[ CMD_STRINGPARAM_COUNT ]; // Stores if string parameters are provided on cmdline
mutable ::osl::Mutex m_aMutex;
// static definition for groups where only one member can be true
static GroupDefinition m_pGroupDefinitions[ CMD_GRPID_COUNT ];
};
}
#endif
<commit_msg>INTEGRATION: CWS mav4 (1.13.4); FILE MERGED 2003/04/15 09:05:29 as 1.13.4.1: #108892# establish backing component on startup if no command line parameter exists<commit_after>/*************************************************************************
*
* $RCSfile: cmdlineargs.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2003-04-24 13:35:24 $
*
* 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 _DESKTOP_COMMANDLINEARGS_HXX_
#define _DESKTOP_COMMANDLINEARGS_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
namespace desktop
{
class CommandLineArgs
{
public:
enum BoolParam // must be zero based!
{
CMD_BOOLPARAM_MINIMIZED,
CMD_BOOLPARAM_INVISIBLE,
CMD_BOOLPARAM_NORESTORE,
CMD_BOOLPARAM_BEAN,
CMD_BOOLPARAM_PLUGIN,
CMD_BOOLPARAM_SERVER,
CMD_BOOLPARAM_HEADLESS,
CMD_BOOLPARAM_QUICKSTART,
CMD_BOOLPARAM_TERMINATEAFTERINIT,
CMD_BOOLPARAM_NOLOGO,
CMD_BOOLPARAM_NOLOCKCHECK,
CMD_BOOLPARAM_NODEFAULT,
CMD_BOOLPARAM_HELP,
CMD_BOOLPARAM_WRITER,
CMD_BOOLPARAM_CALC,
CMD_BOOLPARAM_DRAW,
CMD_BOOLPARAM_IMPRESS,
CMD_BOOLPARAM_GLOBAL,
CMD_BOOLPARAM_MATH,
CMD_BOOLPARAM_WEB,
CMD_BOOLPARAM_COUNT // must be last element!
};
enum StringParam // must be zero based!
{
CMD_STRINGPARAM_PORTAL,
CMD_STRINGPARAM_ACCEPT,
CMD_STRINGPARAM_UNACCEPT,
CMD_STRINGPARAM_USERDIR,
CMD_STRINGPARAM_CLIENTDISPLAY,
CMD_STRINGPARAM_OPENLIST,
CMD_STRINGPARAM_VIEWLIST,
CMD_STRINGPARAM_FORCEOPENLIST,
CMD_STRINGPARAM_FORCENEWLIST,
CMD_STRINGPARAM_PRINTLIST,
CMD_STRINGPARAM_VERSION,
CMD_STRINGPARAM_PRINTTOLIST,
CMD_STRINGPARAM_PRINTERNAME,
CMD_STRINGPARAM_COUNT // must be last element!
};
enum GroupParamId
{
CMD_GRPID_MODULE,
CMD_GRPID_COUNT
};
CommandLineArgs();
CommandLineArgs( const ::vos::OExtCommandLine& aExtCmdLine );
CommandLineArgs( const ::rtl::OUString& aIPCThreadCmdLine );
// generic methods to access parameter
sal_Bool GetBoolParam( BoolParam eParam ) const;
void SetBoolParam( BoolParam eParam, sal_Bool bNewValue );
const rtl::OUString& GetStringParam( BoolParam eParam ) const;
void SetStringParam( BoolParam eParam, const rtl::OUString& bNewValue );
// Access to bool parameters
sal_Bool IsMinimized() const;
sal_Bool IsInvisible() const;
sal_Bool IsNoRestore() const;
sal_Bool IsNoDefault() const;
sal_Bool IsBean() const;
sal_Bool IsPlugin() const;
sal_Bool IsServer() const;
sal_Bool IsHeadless() const;
sal_Bool IsQuickstart() const;
sal_Bool IsTerminateAfterInit() const;
sal_Bool IsNoLogo() const;
sal_Bool IsNoLockcheck() const;
sal_Bool IsHelp() const;
sal_Bool IsWriter() const;
sal_Bool IsCalc() const;
sal_Bool IsDraw() const;
sal_Bool IsImpress() const;
sal_Bool IsGlobal() const;
sal_Bool IsMath() const;
sal_Bool IsWeb() const;
sal_Bool HasModuleParam() const;
// Access to string parameters
sal_Bool GetPortalConnectString( ::rtl::OUString& rPara) const;
sal_Bool GetAcceptString( ::rtl::OUString& rPara) const;
sal_Bool GetUnAcceptString( ::rtl::OUString& rPara) const;
sal_Bool GetUserDir( ::rtl::OUString& rPara) const;
sal_Bool GetClientDisplay( ::rtl::OUString& rPara) const;
sal_Bool GetOpenList( ::rtl::OUString& rPara) const;
sal_Bool GetViewList( ::rtl::OUString& rPara) const;
sal_Bool GetForceOpenList( ::rtl::OUString& rPara) const;
sal_Bool GetForceNewList( ::rtl::OUString& rPara) const;
sal_Bool GetPrintList( ::rtl::OUString& rPara) const;
sal_Bool GetVersionString( ::rtl::OUString& rPara) const;
sal_Bool GetPrintToList( ::rtl::OUString& rPara ) const;
sal_Bool GetPrinterName( ::rtl::OUString& rPara ) const;
// Special analyzed states (does not match directly to a command line parameter!)
sal_Bool IsPrinting() const;
sal_Bool IsEmpty() const;
private:
struct GroupDefinition
{
sal_Int32 nCount;
BoolParam* pGroupMembers;
};
// no copy and operator=
CommandLineArgs( const CommandLineArgs& );
operator=( const CommandLineArgs& );
sal_Bool InterpretCommandLineParameter( const ::rtl::OUString& );
void ParseCommandLine_Impl( const ::vos::OExtCommandLine& );
void ParseCommandLine_String( const ::rtl::OUString& );
void ResetParamValues();
sal_Bool CheckGroupMembers( GroupParamId nGroup, BoolParam nExcludeMember ) const;
void AddStringListParam_Impl( StringParam eParam, const rtl::OUString& aParam );
void SetBoolParam_Impl( BoolParam eParam, sal_Bool bValue );
sal_Bool m_aBoolParams[ CMD_BOOLPARAM_COUNT ]; // Stores boolean parameters
rtl::OUString m_aStrParams[ CMD_STRINGPARAM_COUNT ]; // Stores string parameters
sal_Bool m_aStrSetParams[ CMD_STRINGPARAM_COUNT ]; // Stores if string parameters are provided on cmdline
sal_Bool m_bEmpty; // indicates an empty command line
mutable ::osl::Mutex m_aMutex;
// static definition for groups where only one member can be true
static GroupDefinition m_pGroupDefinitions[ CMD_GRPID_COUNT ];
};
}
#endif
<|endoftext|> |
<commit_before>// Ouzel by Elviss Strazdins
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# include <strsafe.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#ifdef __APPLE__
# include "../platform/corefoundation/Pointer.hpp"
#endif
namespace ouzel::storage
{
FileSystem::FileSystem(core::Engine& initEngine):
engine{initEngine}
{
#if defined(_WIN32)
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
const platform::corefoundation::Pointer relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error{"Failed to get resource directory"};
const platform::corefoundation::Pointer absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
if (!absolutePath)
throw std::runtime_error{"Failed to copy absolute URL"};
const platform::corefoundation::Pointer path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
if (!path)
throw std::runtime_error{"Failed to copy file system path"};
const auto maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
const auto resourceDirectory = std::make_unique<char[]>(static_cast<std::size_t>(maximumSize));
if (!CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.get(), maximumSize))
throw std::runtime_error{"Failed to get resource directory"};
appPath = Path{resourceDirectory.get(), Path::Format::native};
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
const auto length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1);
if (length == -1)
throw std::system_error{errno, std::system_category(), "Failed to get current directory"};
executableDirectory[length] = '\0';
const auto executablePath = Path{executableDirectory, Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#else
# error "Unsupported platform"
#endif
}
Path FileSystem::getStorageDirectory([[maybe_unused]] const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
const auto folderId = (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE;
if (const auto hr = SHGetFolderPathW(nullptr,
folderId,
nullptr,
SHGFP_TYPE_CURRENT,
appDataPath); FAILED(hr))
throw std::system_error{hr, std::system_category(), "Failed to get the path of the AppData directory"};
auto path = Path{appDataPath, Path::Format::native};
const auto instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
DWORD handle;
const auto fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
if (!fileVersionSize)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version size"};
auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
0, fileVersionSize,
fileVersionBuffer.get()))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version"};
LPWSTR companyName = nullptr;
LPWSTR productName = nullptr;
struct LANGANDCODEPAGE final
{
WORD wLanguage;
WORD wCodePage;
};
LPVOID translationPointer;
UINT translationLength;
if (VerQueryValueW(fileVersionBuffer.get(),
L"\\VarFileInfo\\Translation",
&translationPointer,
&translationLength))
{
const auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);
for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
{
constexpr std::size_t subBlockSize = 37U;
WCHAR subBlock[subBlockSize];
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\CompanyName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID companyNamePointer;
UINT companyNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&companyNamePointer,
&companyNameLength))
companyName = static_cast<LPWSTR>(companyNamePointer);
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\ProductName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID productNamePointer;
UINT productNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&productNamePointer,
&productNameLength))
productName = static_cast<LPWSTR>(productNamePointer);
}
}
if (companyName)
path /= companyName;
else
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
if (productName)
path /= productName;
else
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error{"Failed to get document directory"};
const auto documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif TARGET_OS_MAC
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error{"Failed to get application support directory"};
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
const auto path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
const auto pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif defined(__ANDROID__)
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
Path path;
if (const char* homeDirectory = std::getenv("XDG_DATA_HOME"))
path = Path{homeDirectory, Path::Format::native};
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int result;
while ((result = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) != 0)
if (result == ERANGE)
buffer.resize(buffer.size() * 2);
else
throw std::system_error{result, std::system_category(), "Failed to get password record"};
if (!pwentp)
throw std::system_error{result, std::system_category(), "No matching password record found"};
path = Path{pwent.pw_dir, Path::Format::native};
path /= ".local";
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= "share";
if (getFileType(path) != FileType::directory)
createDirectory(path);
}
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#else
# error "Unsupported platform"
#endif
}
std::vector<std::byte> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
{
const auto& genericPath = filename.getGeneric();
for (auto& archive : archives)
if (archive.second.fileExists(genericPath))
return archive.second.readFile(genericPath);
}
#ifdef __ANDROID__
if (!filename.isAbsolute())
{
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);
if (!asset)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
for (;;)
{
const auto bytesRead = AAsset_read(asset, buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error{"Failed to read from file"};
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
AAsset_close(asset);
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error{"Failed to find file " + std::string(filename)};
std::ifstream file{path, std::ios::binary};
if (!file)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
while (!file.eof())
{
file.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
data.insert(data.end(), buffer, buffer + file.gcount());
}
return data;
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
auto result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return getFileType(dirname) == FileType::directory;
}
bool FileSystem::fileExists(const Path& filename) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);
if (asset)
{
AAsset_close(asset);
return true;
}
#endif
return getFileType(filename) == FileType::regular;
}
}
<commit_msg>Store asset in unique_ptr<commit_after>// Ouzel by Elviss Strazdins
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# include <strsafe.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#ifdef __APPLE__
# include "../platform/corefoundation/Pointer.hpp"
#endif
namespace ouzel::storage
{
FileSystem::FileSystem(core::Engine& initEngine):
engine{initEngine}
{
#if defined(_WIN32)
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
const platform::corefoundation::Pointer relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error{"Failed to get resource directory"};
const platform::corefoundation::Pointer absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
if (!absolutePath)
throw std::runtime_error{"Failed to copy absolute URL"};
const platform::corefoundation::Pointer path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
if (!path)
throw std::runtime_error{"Failed to copy file system path"};
const auto maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
const auto resourceDirectory = std::make_unique<char[]>(static_cast<std::size_t>(maximumSize));
if (!CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.get(), maximumSize))
throw std::runtime_error{"Failed to get resource directory"};
appPath = Path{resourceDirectory.get(), Path::Format::native};
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
const auto length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1);
if (length == -1)
throw std::system_error{errno, std::system_category(), "Failed to get current directory"};
executableDirectory[length] = '\0';
const auto executablePath = Path{executableDirectory, Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#else
# error "Unsupported platform"
#endif
}
Path FileSystem::getStorageDirectory([[maybe_unused]] const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
const auto folderId = (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE;
if (const auto hr = SHGetFolderPathW(nullptr,
folderId,
nullptr,
SHGFP_TYPE_CURRENT,
appDataPath); FAILED(hr))
throw std::system_error{hr, std::system_category(), "Failed to get the path of the AppData directory"};
auto path = Path{appDataPath, Path::Format::native};
const auto instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
DWORD handle;
const auto fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
if (!fileVersionSize)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version size"};
auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
0, fileVersionSize,
fileVersionBuffer.get()))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version"};
LPWSTR companyName = nullptr;
LPWSTR productName = nullptr;
struct LANGANDCODEPAGE final
{
WORD wLanguage;
WORD wCodePage;
};
LPVOID translationPointer;
UINT translationLength;
if (VerQueryValueW(fileVersionBuffer.get(),
L"\\VarFileInfo\\Translation",
&translationPointer,
&translationLength))
{
const auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);
for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
{
constexpr std::size_t subBlockSize = 37U;
WCHAR subBlock[subBlockSize];
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\CompanyName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID companyNamePointer;
UINT companyNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&companyNamePointer,
&companyNameLength))
companyName = static_cast<LPWSTR>(companyNamePointer);
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\ProductName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID productNamePointer;
UINT productNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&productNamePointer,
&productNameLength))
productName = static_cast<LPWSTR>(productNamePointer);
}
}
if (companyName)
path /= companyName;
else
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
if (productName)
path /= productName;
else
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error{"Failed to get document directory"};
const auto documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif TARGET_OS_MAC
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error{"Failed to get application support directory"};
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
const auto path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
const auto pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif defined(__ANDROID__)
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
Path path;
if (const char* homeDirectory = std::getenv("XDG_DATA_HOME"))
path = Path{homeDirectory, Path::Format::native};
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int result;
while ((result = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) != 0)
if (result == ERANGE)
buffer.resize(buffer.size() * 2);
else
throw std::system_error{result, std::system_category(), "Failed to get password record"};
if (!pwentp)
throw std::system_error{result, std::system_category(), "No matching password record found"};
path = Path{pwent.pw_dir, Path::Format::native};
path /= ".local";
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= "share";
if (getFileType(path) != FileType::directory)
createDirectory(path);
}
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#else
# error "Unsupported platform"
#endif
}
std::vector<std::byte> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
{
const auto& genericPath = filename.getGeneric();
for (auto& archive : archives)
if (archive.second.fileExists(genericPath))
return archive.second.readFile(genericPath);
}
#ifdef __ANDROID__
if (!filename.isAbsolute())
{
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
const std::unique_ptr<AAsset, decltype(&AAsset_close)> asset{
AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING),
AAsset_close
};
if (!asset)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
for (;;)
{
const auto bytesRead = AAsset_read(asset.get(), buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error{"Failed to read from file"};
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error{"Failed to find file " + std::string(filename)};
std::ifstream file{path, std::ios::binary};
if (!file)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
while (!file.eof())
{
file.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
data.insert(data.end(), buffer, buffer + file.gcount());
}
return data;
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
auto result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return getFileType(dirname) == FileType::directory;
}
bool FileSystem::fileExists(const Path& filename) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);
if (asset)
{
AAsset_close(asset);
return true;
}
#endif
return getFileType(filename) == FileType::regular;
}
}
<|endoftext|> |
<commit_before>// Ouzel by Elviss Strazdins
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# include <strsafe.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#ifdef __APPLE__
# include "../platform/corefoundation/Pointer.hpp"
#endif
namespace ouzel::storage
{
FileSystem::FileSystem(core::Engine& initEngine):
engine{initEngine}
{
#if defined(_WIN32)
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
const platform::corefoundation::Pointer relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error{"Failed to get resource directory"};
const platform::corefoundation::Pointer absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
if (!absolutePath)
throw std::runtime_error{"Failed to copy absolute URL"};
const platform::corefoundation::Pointer path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
if (!path)
throw std::runtime_error{"Failed to copy file system path"};
const auto maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
const auto resourceDirectory = std::make_unique<char[]>(static_cast<std::size_t>(maximumSize));
if (!CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.get(), maximumSize))
throw std::runtime_error{"Failed to get resource directory"};
appPath = Path{resourceDirectory.get(), Path::Format::native};
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
const auto length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1);
if (length == -1)
throw std::system_error{errno, std::system_category(), "Failed to get current directory"};
executableDirectory[length] = '\0';
const auto executablePath = Path{executableDirectory, Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#else
# error "Unsupported platform"
#endif
}
Path FileSystem::getStorageDirectory([[maybe_unused]] const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
const auto folderId = (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE;
if (const auto hr = SHGetFolderPathW(nullptr,
folderId,
nullptr,
SHGFP_TYPE_CURRENT,
appDataPath); FAILED(hr))
throw std::system_error{hr, std::system_category(), "Failed to get the path of the AppData directory"};
auto path = Path{appDataPath, Path::Format::native};
const auto instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
DWORD handle;
const auto fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
if (!fileVersionSize)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version size"};
auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
0, fileVersionSize,
fileVersionBuffer.get()))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version"};
LPWSTR companyName = nullptr;
LPWSTR productName = nullptr;
struct LANGANDCODEPAGE final
{
WORD wLanguage;
WORD wCodePage;
};
LPVOID translationPointer;
UINT translationLength;
if (VerQueryValueW(fileVersionBuffer.get(),
L"\\VarFileInfo\\Translation",
&translationPointer,
&translationLength))
{
const auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);
for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
{
constexpr std::size_t subBlockSize = 37U;
WCHAR subBlock[subBlockSize];
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\CompanyName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID companyNamePointer;
UINT companyNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&companyNamePointer,
&companyNameLength))
companyName = static_cast<LPWSTR>(companyNamePointer);
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\ProductName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID productNamePointer;
UINT productNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&productNamePointer,
&productNameLength))
productName = static_cast<LPWSTR>(productNamePointer);
}
}
if (companyName)
path /= companyName;
else
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
if (productName)
path /= productName;
else
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error{"Failed to get document directory"};
const auto documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif TARGET_OS_MAC
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error{"Failed to get application support directory"};
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
const auto path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
const auto pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif defined(__ANDROID__)
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
Path path;
if (const char* homeDirectory = std::getenv("XDG_DATA_HOME"))
path = Path{homeDirectory, Path::Format::native};
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int result;
while ((result = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) != 0)
if (result == ERANGE)
buffer.resize(buffer.size() * 2);
else
throw std::system_error{result, std::system_category(), "Failed to get password record"};
if (!pwentp)
throw std::system_error{result, std::system_category(), "No matching password record found"};
path = Path{pwent.pw_dir, Path::Format::native};
path /= ".local";
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= "share";
if (getFileType(path) != FileType::directory)
createDirectory(path);
}
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#else
# error "Unsupported platform"
#endif
}
std::vector<std::byte> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
{
const auto& genericPath = filename.getGeneric();
for (auto& archive : archives)
if (archive.second.fileExists(genericPath))
return archive.second.readFile(genericPath);
}
#ifdef __ANDROID__
if (!filename.isAbsolute())
{
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
const std::unique_ptr<AAsset, decltype(&AAsset_close)> asset{
AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING),
AAsset_close
};
if (!asset)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
for (;;)
{
const auto bytesRead = AAsset_read(asset.get(), buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error{"Failed to read from file"};
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error{"Failed to find file " + std::string(filename)};
std::ifstream file{path, std::ios::binary};
if (!file)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
while (!file.eof())
{
file.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
data.insert(data.end(), buffer, buffer + file.gcount());
}
return data;
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
auto result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return getFileType(dirname) == FileType::directory;
}
bool FileSystem::fileExists(const Path& filename) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);
if (asset)
{
AAsset_close(asset);
return true;
}
#endif
return getFileType(filename) == FileType::regular;
}
}
<commit_msg>Use unique_ptr for AAsset<commit_after>// Ouzel by Elviss Strazdins
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# include <strsafe.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#ifdef __APPLE__
# include "../platform/corefoundation/Pointer.hpp"
#endif
namespace ouzel::storage
{
FileSystem::FileSystem(core::Engine& initEngine):
engine{initEngine}
{
#if defined(_WIN32)
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
const platform::corefoundation::Pointer relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error{"Failed to get resource directory"};
const platform::corefoundation::Pointer absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
if (!absolutePath)
throw std::runtime_error{"Failed to copy absolute URL"};
const platform::corefoundation::Pointer path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
if (!path)
throw std::runtime_error{"Failed to copy file system path"};
const auto maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
const auto resourceDirectory = std::make_unique<char[]>(static_cast<std::size_t>(maximumSize));
if (!CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.get(), maximumSize))
throw std::runtime_error{"Failed to get resource directory"};
appPath = Path{resourceDirectory.get(), Path::Format::native};
log(Log::Level::info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
const auto length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1);
if (length == -1)
throw std::system_error{errno, std::system_category(), "Failed to get current directory"};
executableDirectory[length] = '\0';
const auto executablePath = Path{executableDirectory, Path::Format::native};
appPath = executablePath.getDirectory();
log(Log::Level::info) << "Application directory: " << appPath;
#else
# error "Unsupported platform"
#endif
}
Path FileSystem::getStorageDirectory([[maybe_unused]] const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
const auto folderId = (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE;
if (const auto hr = SHGetFolderPathW(nullptr,
folderId,
nullptr,
SHGFP_TYPE_CURRENT,
appDataPath); FAILED(hr))
throw std::system_error{hr, std::system_category(), "Failed to get the path of the AppData directory"};
auto path = Path{appDataPath, Path::Format::native};
const auto instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module handle"};
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get module filename"};
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const auto executablePath = Path{buffer.data(), Path::Format::native};
DWORD handle;
const auto fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
if (!fileVersionSize)
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version size"};
auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
0, fileVersionSize,
fileVersionBuffer.get()))
throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to get file version"};
LPWSTR companyName = nullptr;
LPWSTR productName = nullptr;
struct LANGANDCODEPAGE final
{
WORD wLanguage;
WORD wCodePage;
};
LPVOID translationPointer;
UINT translationLength;
if (VerQueryValueW(fileVersionBuffer.get(),
L"\\VarFileInfo\\Translation",
&translationPointer,
&translationLength))
{
const auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);
for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
{
constexpr std::size_t subBlockSize = 37U;
WCHAR subBlock[subBlockSize];
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\CompanyName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID companyNamePointer;
UINT companyNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&companyNamePointer,
&companyNameLength))
companyName = static_cast<LPWSTR>(companyNamePointer);
StringCchPrintfW(subBlock, subBlockSize,
L"\\StringFileInfo\\%04x%04x\\ProductName",
translation[i].wLanguage,
translation[i].wCodePage);
LPVOID productNamePointer;
UINT productNameLength;
if (VerQueryValueW(fileVersionBuffer.get(),
subBlock,
&productNamePointer,
&productNameLength))
productName = static_cast<LPWSTR>(productNamePointer);
}
}
if (companyName)
path /= companyName;
else
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
if (productName)
path /= productName;
else
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error{"Failed to get document directory"};
const auto documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif TARGET_OS_MAC
const auto fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14U;
constexpr NSUInteger NSUserDomainMask = 1U;
constexpr NSUInteger NSLocalDomainMask = 2U;
const auto applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error{"Failed to get application support directory"};
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error{"Failed to get main bundle"};
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
const auto path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
const auto pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
const auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
return Path{pathUtf8String, Path::Format::native};
#elif defined(__ANDROID__)
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
Path path;
if (const char* homeDirectory = std::getenv("XDG_DATA_HOME"))
path = Path{homeDirectory, Path::Format::native};
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int result;
while ((result = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) != 0)
if (result == ERANGE)
buffer.resize(buffer.size() * 2);
else
throw std::system_error{result, std::system_category(), "Failed to get password record"};
if (!pwentp)
throw std::system_error{result, std::system_category(), "No matching password record found"};
path = Path{pwent.pw_dir, Path::Format::native};
path /= ".local";
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= "share";
if (getFileType(path) != FileType::directory)
createDirectory(path);
}
path /= OUZEL_DEVELOPER_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
path /= OUZEL_APPLICATION_NAME;
if (getFileType(path) != FileType::directory)
createDirectory(path);
return path;
#else
# error "Unsupported platform"
#endif
}
std::vector<std::byte> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
{
const auto& genericPath = filename.getGeneric();
for (auto& archive : archives)
if (archive.second.fileExists(genericPath))
return archive.second.readFile(genericPath);
}
#ifdef __ANDROID__
if (!filename.isAbsolute())
{
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
const std::unique_ptr<AAsset, decltype(&AAsset_close)> asset{
AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING),
AAsset_close
};
if (!asset)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
for (;;)
{
const auto bytesRead = AAsset_read(asset.get(), buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error{"Failed to read from file"};
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error{"Failed to find file " + std::string(filename)};
std::ifstream file{path, std::ios::binary};
if (!file)
throw std::runtime_error{"Failed to open file " + std::string(filename)};
std::vector<std::byte> data;
std::byte buffer[1024];
while (!file.eof())
{
file.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
data.insert(data.end(), buffer, buffer + file.gcount());
}
return data;
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
auto result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return getFileType(dirname) == FileType::directory;
}
bool FileSystem::fileExists(const Path& filename) const
{
#ifdef __ANDROID__
auto& engineAndroid = static_cast<core::android::Engine&>(engine);
const std::unique_ptr<AAsset, decltype(&AAsset_close)> asset{
AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING),
AAsset_close
};
if (asset) return true;
#endif
return getFileType(filename) == FileType::regular;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qapplication.h>
#include <qevent.h>
#include <qaction.h>
#include <qmenu.h>
//TESTED_CLASS=
//TESTED_FILES=
class tst_QAction : public QObject
{
Q_OBJECT
public:
tst_QAction();
virtual ~tst_QAction();
void updateState(QActionEvent *e);
public slots:
void initTestCase();
void cleanupTestCase();
private slots:
void getSetCheck();
void setText_data();
void setText();
void setIconText_data() { setText_data(); }
void setIconText();
void actionEvent();
void setStandardKeys();
void alternateShortcuts();
void enabledVisibleInteraction();
void task200823_tooltip();
void task229128TriggeredSignalWithoutActiongroup();
void task229128TriggeredSignalWhenInActiongroup();
private:
int m_lastEventType;
QAction *m_lastAction;
QWidget *m_tstWidget;
};
// Testing get/set functions
void tst_QAction::getSetCheck()
{
QAction obj1(0);
// QActionGroup * QAction::actionGroup()
// void QAction::setActionGroup(QActionGroup *)
QActionGroup *var1 = new QActionGroup(0);
obj1.setActionGroup(var1);
QCOMPARE(var1, obj1.actionGroup());
obj1.setActionGroup((QActionGroup *)0);
QCOMPARE((QActionGroup *)0, obj1.actionGroup());
delete var1;
// QMenu * QAction::menu()
// void QAction::setMenu(QMenu *)
QMenu *var2 = new QMenu(0);
obj1.setMenu(var2);
QCOMPARE(var2, obj1.menu());
obj1.setMenu((QMenu *)0);
QCOMPARE((QMenu *)0, obj1.menu());
delete var2;
QCOMPARE(obj1.priority(), QAction::NormalPriority);
obj1.setPriority(QAction::LowPriority);
QCOMPARE(obj1.priority(), QAction::LowPriority);
}
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(tst_QAction *tst, QWidget *parent = 0) : QWidget(parent) { this->tst = tst; }
protected:
virtual void actionEvent(QActionEvent *e) { tst->updateState(e); }
private:
tst_QAction *tst;
};
tst_QAction::tst_QAction()
{
}
tst_QAction::~tst_QAction()
{
}
void tst_QAction::initTestCase()
{
m_lastEventType = 0;
m_lastAction = 0;
MyWidget *mw = new MyWidget(this);
m_tstWidget = mw;
mw->show();
qApp->setActiveWindow(mw);
}
void tst_QAction::cleanupTestCase()
{
QWidget *testWidget = m_tstWidget;
if (testWidget) {
testWidget->hide();
delete testWidget;
}
}
void tst_QAction::setText_data()
{
QTest::addColumn<QString>("text");
QTest::addColumn<QString>("iconText");
QTest::addColumn<QString>("textFromIconText");
//next we fill it with data
QTest::newRow("Normal") << "Action" << "Action" << "Action";
QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
}
void tst_QAction::setText()
{
QFETCH(QString, text);
QAction action(0);
action.setText(text);
QCOMPARE(action.text(), text);
QFETCH(QString, iconText);
QCOMPARE(action.iconText(), iconText);
}
void tst_QAction::setIconText()
{
QFETCH(QString, iconText);
QAction action(0);
action.setIconText(iconText);
QCOMPARE(action.iconText(), iconText);
QFETCH(QString, textFromIconText);
QCOMPARE(action.text(), textFromIconText);
}
void tst_QAction::updateState(QActionEvent *e)
{
if (!e) {
m_lastEventType = 0;
m_lastAction = 0;
} else {
m_lastEventType = (int)e->type();
m_lastAction = e->action();
}
}
void tst_QAction::actionEvent()
{
QAction a(0);
a.setText("action text");
// add action
m_tstWidget->addAction(&a);
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionAdded);
QCOMPARE(m_lastAction, &a);
// change action
a.setText("new action text");
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionChanged);
QCOMPARE(m_lastAction, &a);
// remove action
m_tstWidget->removeAction(&a);
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionRemoved);
QCOMPARE(m_lastAction, &a);
}
//basic testing of standard keys
void tst_QAction::setStandardKeys()
{
QAction act(0);
act.setShortcut(QKeySequence("CTRL+L"));
QList<QKeySequence> list;
act.setShortcuts(list);
act.setShortcuts(QKeySequence::Copy);
QVERIFY(act.shortcut() == act.shortcuts().first());
QList<QKeySequence> expected;
#ifdef Q_WS_MAC
expected << QKeySequence("CTRL+C");
#elif defined(Q_WS_WIN) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
expected << QKeySequence("CTRL+C") << QKeySequence("CTRL+INSERT");
#else
expected << QKeySequence("CTRL+C") << QKeySequence("F16") << QKeySequence("CTRL+INSERT");
#endif
QVERIFY(act.shortcuts() == expected);
}
void tst_QAction::alternateShortcuts()
{
//test the alternate shortcuts (by adding more than 1 shortcut)
QWidget *wid = m_tstWidget;
{
QAction act(wid);
wid->addAction(&act);
QList<QKeySequence> shlist = QList<QKeySequence>() << QKeySequence("CTRL+P") << QKeySequence("CTRL+A");
act.setShortcuts(shlist);
QSignalSpy spy(&act, SIGNAL(triggered()));
act.setAutoRepeat(true);
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(spy.count(), 1); //act should have been triggered
act.setAutoRepeat(false);
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(spy.count(), 2); //act should have been triggered a 2nd time
//end of the scope of the action, it will be destroyed and removed from wid
//This action should also unregister its shortcuts
}
//this tests a crash (if the action did not unregister its alternate shortcuts)
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
}
void tst_QAction::enabledVisibleInteraction()
{
QAction act(0);
// check defaults
QVERIFY(act.isEnabled());
QVERIFY(act.isVisible());
// !visible => !enabled
act.setVisible(false);
QVERIFY(!act.isEnabled());
act.setVisible(true);
QVERIFY(act.isEnabled());
act.setEnabled(false);
QVERIFY(act.isVisible());
// check if shortcut is disabled if not visible
m_tstWidget->addAction(&act);
act.setShortcut(QKeySequence("Ctrl+T"));
QSignalSpy spy(&act, SIGNAL(triggered()));
act.setEnabled(true);
act.setVisible(false);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
act.setVisible(false);
act.setEnabled(true);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
act.setVisible(true);
act.setEnabled(true);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 1); //act is visible and enabled, so trigger
}
void tst_QAction::task200823_tooltip()
{
QAction *action = new QAction("foo", 0);
QString shortcut("ctrl+o");
action->setShortcut(shortcut);
// we want a non-standard tooltip that shows the shortcut
action->setToolTip(QString("%1 (%2)").arg(action->text()).arg(action->shortcut().toString()));
QString ref = QString("foo (%1)").arg(QKeySequence(shortcut).toString());
QCOMPARE(action->toolTip(), ref);
}
void tst_QAction::task229128TriggeredSignalWithoutActiongroup()
{
// test without a group
QAction *actionWithoutGroup = new QAction("Test", qApp);
QSignalSpy spyWithoutGroup(actionWithoutGroup, SIGNAL(triggered(bool)));
QCOMPARE(spyWithoutGroup.count(), 0);
actionWithoutGroup->trigger();
// signal should be emitted
QCOMPARE(spyWithoutGroup.count(), 1);
// it is now a checkable checked action
actionWithoutGroup->setCheckable(true);
actionWithoutGroup->setChecked(true);
spyWithoutGroup.clear();
QCOMPARE(spyWithoutGroup.count(), 0);
actionWithoutGroup->trigger();
// signal should be emitted
QCOMPARE(spyWithoutGroup.count(), 1);
}
void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
{
QActionGroup ag(0);
QAction *action = new QAction("Test", &ag);
QAction *checkedAction = new QAction("Test 2", &ag);
ag.addAction(action);
action->setCheckable(true);
ag.addAction(checkedAction);
checkedAction->setCheckable(true);
checkedAction->setChecked(true);
QSignalSpy actionSpy(checkedAction, SIGNAL(triggered(bool)));
QSignalSpy actionGroupSpy(&ag, SIGNAL(triggered(QAction *)));
QCOMPARE(actionGroupSpy.count(), 0);
QCOMPARE(actionSpy.count(), 0);
checkedAction->trigger();
// check that both the group and the action have emitted the signal
QCOMPARE(actionGroupSpy.count(), 1);
QCOMPARE(actionSpy.count(), 1);
}
QTEST_MAIN(tst_QAction)
#include "tst_qaction.moc"
<commit_msg>Fixed qaction autotest failures for Symbian.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qapplication.h>
#include <qevent.h>
#include <qaction.h>
#include <qmenu.h>
//TESTED_CLASS=
//TESTED_FILES=
class tst_QAction : public QObject
{
Q_OBJECT
public:
tst_QAction();
virtual ~tst_QAction();
void updateState(QActionEvent *e);
public slots:
void initTestCase();
void cleanupTestCase();
private slots:
void getSetCheck();
void setText_data();
void setText();
void setIconText_data() { setText_data(); }
void setIconText();
void actionEvent();
void setStandardKeys();
void alternateShortcuts();
void enabledVisibleInteraction();
void task200823_tooltip();
void task229128TriggeredSignalWithoutActiongroup();
void task229128TriggeredSignalWhenInActiongroup();
private:
int m_lastEventType;
QAction *m_lastAction;
QWidget *m_tstWidget;
};
// Testing get/set functions
void tst_QAction::getSetCheck()
{
QAction obj1(0);
// QActionGroup * QAction::actionGroup()
// void QAction::setActionGroup(QActionGroup *)
QActionGroup *var1 = new QActionGroup(0);
obj1.setActionGroup(var1);
QCOMPARE(var1, obj1.actionGroup());
obj1.setActionGroup((QActionGroup *)0);
QCOMPARE((QActionGroup *)0, obj1.actionGroup());
delete var1;
// QMenu * QAction::menu()
// void QAction::setMenu(QMenu *)
QMenu *var2 = new QMenu(0);
obj1.setMenu(var2);
QCOMPARE(var2, obj1.menu());
obj1.setMenu((QMenu *)0);
QCOMPARE((QMenu *)0, obj1.menu());
delete var2;
QCOMPARE(obj1.priority(), QAction::NormalPriority);
obj1.setPriority(QAction::LowPriority);
QCOMPARE(obj1.priority(), QAction::LowPriority);
}
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(tst_QAction *tst, QWidget *parent = 0) : QWidget(parent) { this->tst = tst; }
protected:
virtual void actionEvent(QActionEvent *e) { tst->updateState(e); }
private:
tst_QAction *tst;
};
tst_QAction::tst_QAction()
{
}
tst_QAction::~tst_QAction()
{
}
void tst_QAction::initTestCase()
{
m_lastEventType = 0;
m_lastAction = 0;
MyWidget *mw = new MyWidget(this);
m_tstWidget = mw;
mw->show();
qApp->setActiveWindow(mw);
}
void tst_QAction::cleanupTestCase()
{
QWidget *testWidget = m_tstWidget;
if (testWidget) {
testWidget->hide();
delete testWidget;
}
}
void tst_QAction::setText_data()
{
QTest::addColumn<QString>("text");
QTest::addColumn<QString>("iconText");
QTest::addColumn<QString>("textFromIconText");
//next we fill it with data
QTest::newRow("Normal") << "Action" << "Action" << "Action";
QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
}
void tst_QAction::setText()
{
QFETCH(QString, text);
QAction action(0);
action.setText(text);
QCOMPARE(action.text(), text);
QFETCH(QString, iconText);
QCOMPARE(action.iconText(), iconText);
}
void tst_QAction::setIconText()
{
QFETCH(QString, iconText);
QAction action(0);
action.setIconText(iconText);
QCOMPARE(action.iconText(), iconText);
QFETCH(QString, textFromIconText);
QCOMPARE(action.text(), textFromIconText);
}
void tst_QAction::updateState(QActionEvent *e)
{
if (!e) {
m_lastEventType = 0;
m_lastAction = 0;
} else {
m_lastEventType = (int)e->type();
m_lastAction = e->action();
}
}
void tst_QAction::actionEvent()
{
QAction a(0);
a.setText("action text");
// add action
m_tstWidget->addAction(&a);
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionAdded);
QCOMPARE(m_lastAction, &a);
// change action
a.setText("new action text");
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionChanged);
QCOMPARE(m_lastAction, &a);
// remove action
m_tstWidget->removeAction(&a);
qApp->processEvents();
QCOMPARE(m_lastEventType, (int)QEvent::ActionRemoved);
QCOMPARE(m_lastAction, &a);
}
//basic testing of standard keys
void tst_QAction::setStandardKeys()
{
QAction act(0);
act.setShortcut(QKeySequence("CTRL+L"));
QList<QKeySequence> list;
act.setShortcuts(list);
act.setShortcuts(QKeySequence::Copy);
QVERIFY(act.shortcut() == act.shortcuts().first());
QList<QKeySequence> expected;
#if defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
expected << QKeySequence("CTRL+C");
#elif defined(Q_WS_WIN) || defined(Q_WS_QWS)
expected << QKeySequence("CTRL+C") << QKeySequence("CTRL+INSERT");
#else
expected << QKeySequence("CTRL+C") << QKeySequence("F16") << QKeySequence("CTRL+INSERT");
#endif
QVERIFY(act.shortcuts() == expected);
}
void tst_QAction::alternateShortcuts()
{
//test the alternate shortcuts (by adding more than 1 shortcut)
QWidget *wid = m_tstWidget;
{
QAction act(wid);
wid->addAction(&act);
QList<QKeySequence> shlist = QList<QKeySequence>() << QKeySequence("CTRL+P") << QKeySequence("CTRL+A");
act.setShortcuts(shlist);
QSignalSpy spy(&act, SIGNAL(triggered()));
act.setAutoRepeat(true);
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(spy.count(), 1); //act should have been triggered
act.setAutoRepeat(false);
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(spy.count(), 2); //act should have been triggered a 2nd time
//end of the scope of the action, it will be destroyed and removed from wid
//This action should also unregister its shortcuts
}
//this tests a crash (if the action did not unregister its alternate shortcuts)
QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
}
void tst_QAction::enabledVisibleInteraction()
{
QAction act(0);
// check defaults
QVERIFY(act.isEnabled());
QVERIFY(act.isVisible());
// !visible => !enabled
act.setVisible(false);
QVERIFY(!act.isEnabled());
act.setVisible(true);
QVERIFY(act.isEnabled());
act.setEnabled(false);
QVERIFY(act.isVisible());
// check if shortcut is disabled if not visible
m_tstWidget->addAction(&act);
act.setShortcut(QKeySequence("Ctrl+T"));
QSignalSpy spy(&act, SIGNAL(triggered()));
act.setEnabled(true);
act.setVisible(false);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
act.setVisible(false);
act.setEnabled(true);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
act.setVisible(true);
act.setEnabled(true);
QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
QCOMPARE(spy.count(), 1); //act is visible and enabled, so trigger
}
void tst_QAction::task200823_tooltip()
{
QAction *action = new QAction("foo", 0);
QString shortcut("ctrl+o");
action->setShortcut(shortcut);
// we want a non-standard tooltip that shows the shortcut
action->setToolTip(QString("%1 (%2)").arg(action->text()).arg(action->shortcut().toString()));
QString ref = QString("foo (%1)").arg(QKeySequence(shortcut).toString());
QCOMPARE(action->toolTip(), ref);
}
void tst_QAction::task229128TriggeredSignalWithoutActiongroup()
{
// test without a group
QAction *actionWithoutGroup = new QAction("Test", qApp);
QSignalSpy spyWithoutGroup(actionWithoutGroup, SIGNAL(triggered(bool)));
QCOMPARE(spyWithoutGroup.count(), 0);
actionWithoutGroup->trigger();
// signal should be emitted
QCOMPARE(spyWithoutGroup.count(), 1);
// it is now a checkable checked action
actionWithoutGroup->setCheckable(true);
actionWithoutGroup->setChecked(true);
spyWithoutGroup.clear();
QCOMPARE(spyWithoutGroup.count(), 0);
actionWithoutGroup->trigger();
// signal should be emitted
QCOMPARE(spyWithoutGroup.count(), 1);
}
void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
{
QActionGroup ag(0);
QAction *action = new QAction("Test", &ag);
QAction *checkedAction = new QAction("Test 2", &ag);
ag.addAction(action);
action->setCheckable(true);
ag.addAction(checkedAction);
checkedAction->setCheckable(true);
checkedAction->setChecked(true);
QSignalSpy actionSpy(checkedAction, SIGNAL(triggered(bool)));
QSignalSpy actionGroupSpy(&ag, SIGNAL(triggered(QAction *)));
QCOMPARE(actionGroupSpy.count(), 0);
QCOMPARE(actionSpy.count(), 0);
checkedAction->trigger();
// check that both the group and the action have emitted the signal
QCOMPARE(actionGroupSpy.count(), 1);
QCOMPARE(actionSpy.count(), 1);
}
QTEST_MAIN(tst_QAction)
#include "tst_qaction.moc"
<|endoftext|> |
<commit_before>#include "detectPeaks.h"
bool peakDetected(volatile SignalState_t* signalState)
{
float s = 0;
bool peak = false;
signalState->offset = (signalState->x_max - signalState->x_min) / 2.208;
float high_thresh = signalState->x_max - signalState->offset;
float low_thresh = signalState->x_min + signalState->offset;
s = signalState->x[1] - signalState->x[0];
if(s > 0)
{
signalState->slopeIsPositive = true;
signalState->slopeIsNegative = false;
if (signalState->x[1] > signalState->x_max)
{
signalState->x_max = signalState->x[1];
high_thresh = signalState->x_max - signalState->offset;
}
}
else if(s < 0)
{
signalState->slopeIsPositive = false;
signalState->slopeIsNegative = true;
if (signalState->x[1] < signalState->x_min)
{
signalState->x_min = signalState->x[1];
low_thresh = signalState->x_min + signalState->offset;
}
}
if(!signalState->slopeIsNegative && signalState->slopeWasNegative)
{
signalState->currentMin = signalState->x[0];
}
if(!signalState->slopeIsPositive && signalState->slopeWasPositive)
{
signalState->currentMax = signalState->x[0];
if((signalState->currentMax > high_thresh) && (signalState->currentMin < low_thresh))
{
peak = true;
}
}
if(signalState->slopeIsPositive)
signalState->slopeWasPositive = true;
else
signalState->slopeWasPositive = false;
if(signalState->slopeIsNegative)
signalState->slopeWasNegative = true;
else
signalState->slopeWasNegative = false;
/* Data to plot the waveform measured by the magnetometer. For testing purposes. To be removed when no longer needed. */
/* Along with the wavefrom, the calculated peaks are marked, where 1 indicates a peak and -2 indicates no peak.*/
SDPowerUp();
File waveFile = SD.open("waveform.csv", FILE_WRITE);
waveFile.print(SignalState->x[1], 4);
if(peak)
waveFile.print(",1"); // 1 on the graph means a peak
else
waveFile.print(",-2"); // -2 on the graph means no peak
waveFile.println();
waveFile.close();
SDPowerDown();
return peak;
}
<commit_msg>Update magnetometer.cpp<commit_after>#include "magnetometer.h"
#include <Arduino.h>
#include <SD.h>
#include <DebugMacros.h>
#include <LSM303CTypes.h>
#include <SparkFunIMU.h>
#include <SparkFunLSM303C.h>
#include "powerSleep.h"
#include "state.h"
/*********************************************************************\
*
* Library for interfacing with the SparkFun LSM303C magnetometer.
*
* Functions:
* Initialize Magnetomter
* Read Data
* Initialize Data
*
\*********************************************************************/
void magnetometerInit(LSM303C *mag)
{
twiPowerUp();
if (mag->begin(
MODE_I2C,
MAG_DO_20_Hz,
MAG_FS_8_Ga,
MAG_BDU_DISABLE,
MAG_OMXY_LOW_POWER,
MAG_OMZ_MEDIUM_PERFORMANCE,
MAG_MD_CONTINUOUS,
ACC_FS_2g,
ACC_BDU_DISABLE,
ACC_DISABLE_ALL,
ACC_ODR_POWER_DOWN
) != IMU_SUCCESS)
{
Serial.println("Magnetometer setup failed. Check connection and reset.");
while(1);
}
twiPowerDown();
return;
}
void readData(LSM303C* mag, volatile SignalState_t* SignalState)
{
twiPowerUp();
SignalState->x[0] = SignalState->x[1];
SignalState->x[1] = mag->readMagZ();
twiPowerDown();
return;
}
void initializeData(LSM303C* mag, volatile SignalState_t* SignalState)
{
twiPowerUp();
SignalState->x[0] = mag->readMagZ();
SignalState->x[1] = SignalState->x[0];
SignalState->x_max = SignalState->x[1];
SignalState->x_min = SignalState->x[1];
SignalState->currentMax = SignalState->x[1];
SignalState->currentMin = SignalState->x[1];
twiPowerDown();
return;
}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// test the PETSc SparseDirectMumps solver
#include "../tests.h"
#include "../testmatrix.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/vector_memory.h>
#include <typeinfo>
int main(int argc, char **argv)
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog << std::setprecision(4);
deallog.threshold_double(1.e-10);
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
{
const unsigned int size = 32;
unsigned int dim = (size-1)*(size-1);
deallog << "Size " << size << " Unknowns " << dim << std::endl;
// Make matrix
FDMatrix testproblem(size, size);
PETScWrappers::SparseMatrix A(dim, dim, 5);
testproblem.five_point(A);
IndexSet indices(dim);
indices.add_range(0, dim);
PETScWrappers::MPI::Vector f(indices, MPI_COMM_WORLD);
PETScWrappers::MPI::Vector u(indices, MPI_COMM_WORLD);
u = 0.;
f = 1.;
A.compress (VectorOperation::insert);
SolverControl cn;
PETScWrappers::SparseDirectMUMPS solver(cn);
// solver.set_symmetric_mode(true);
solver.solve(A,u,f);
PETScWrappers::MPI::Vector tmp(dim);
deallog << "residual = " << A.residual (tmp, u, f)
<< std::endl;
}
}
<commit_msg>Fix a PETSc test that doesn't compile.<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// test the PETSc SparseDirectMumps solver
#include "../tests.h"
#include "../testmatrix.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/vector_memory.h>
#include <typeinfo>
int main(int argc, char **argv)
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog << std::setprecision(4);
deallog.threshold_double(1.e-10);
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
{
const unsigned int size = 32;
unsigned int dim = (size-1)*(size-1);
deallog << "Size " << size << " Unknowns " << dim << std::endl;
// Make matrix
FDMatrix testproblem(size, size);
PETScWrappers::SparseMatrix A(dim, dim, 5);
testproblem.five_point(A);
IndexSet indices(dim);
indices.add_range(0, dim);
PETScWrappers::MPI::Vector f(indices, MPI_COMM_WORLD);
PETScWrappers::MPI::Vector u(indices, MPI_COMM_WORLD);
u = 0.;
f = 1.;
A.compress (VectorOperation::insert);
SolverControl cn;
PETScWrappers::SparseDirectMUMPS solver(cn);
// solver.set_symmetric_mode(true);
solver.solve(A,u,f);
PETScWrappers::MPI::Vector tmp(indices, MPI_COMM_WORLD);
deallog << "residual = " << A.residual (tmp, u, f)
<< std::endl;
}
}
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Utils/Validation.h"
#include "llvm/Support/ThreadLocal.h"
#include <assert.h>
#include <errno.h>
#ifdef LLVM_ON_WIN32
# include <Windows.h>
#else
#include <fcntl.h>
# include <unistd.h>
#endif
#define CACHESIZE 8
namespace cling {
namespace utils {
#ifndef LLVM_ON_WIN32
struct Cache {
private:
const void* lines[CACHESIZE];
unsigned size, mostRecent;
public:
Cache(): lines{0,0,0,0,0,0,0,0}, size(CACHESIZE), mostRecent(0) {}
bool findInCache(const void* P) {
for (unsigned index = 0; index < size; index++) {
if (lines[index] == P)
return true;
}
return false;
}
void pushToCache(const void* P) {
mostRecent = (mostRecent+1)%size;
lines[mostRecent] = P;
}
};
// Trying to be thread-safe.
// Each thread creates a new cache when needed.
static Cache& getCache() {
static llvm::sys::ThreadLocal<Cache> threadCache;
if (!threadCache.get()) {
threadCache.set(new Cache());
}
return *threadCache.get();
}
static int getNullDevFileDescriptor() {
struct FileDescriptor {
int FD;
const char* file = "/dev/null";
FileDescriptor() { FD = open(file, O_WRONLY); }
~FileDescriptor() {
close(FD);
}
};
static FileDescriptor nullDev;
return nullDev.FD;
}
#endif
// Checking whether the pointer points to a valid memory location
bool isAddressValid(const void *P) {
if (!P || P == (void *) -1)
return false;
#ifdef LLVM_ON_WIN32
MEMORY_BASIC_INFORMATION MBI;
if (!VirtualQuery(P, &MBI, sizeof(MBI)))
return false;
if (MBI.State != MEM_COMMIT)
return false;
return true;
#else
// Look-up the address in the cache.
Cache& currentCache = getCache();
if (currentCache.findInCache(P))
return true;
// There is a POSIX way of finding whether an address
// can be accessed for reading.
if (write(getNullDevFileDescriptor(), P, 1/*byte*/) != 1) {
assert(errno == EFAULT && "unexpected write error at address");
return false;
}
currentCache.pushToCache(P);
return true;
#endif
}
}
}
<commit_msg>Refinements: use std::array+find, comments, func names.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Utils/Validation.h"
#include "llvm/Support/ThreadLocal.h"
#include <assert.h>
#include <errno.h>
#ifdef LLVM_ON_WIN32
# include <Windows.h>
#else
#include <array>
#include <algorithm>
#include <fcntl.h>
# include <unistd.h>
#endif
namespace cling {
namespace utils {
#ifndef LLVM_ON_WIN32
// A simple round-robin cache: what enters first, leaves first.
// MRU cache wasn't worth the extra CPU cycles.
struct Cache {
private:
std::array<const void*, 8> lines;
unsigned mostRecent = 0;
public:
bool contains(const void* P) {
return std::find(lines.begin(), lines.end(), P) != lines.end();
}
void push(const void* P) {
mostRecent = (mostRecent + 1) % lines.size();
lines[mostRecent] = P;
}
};
// Trying to be thread-safe.
// Each thread creates a new cache when needed.
static Cache& getCache() {
static llvm::sys::ThreadLocal<Cache> threadCache;
if (!threadCache.get()) {
// Leak, 1 Cache/thread.
threadCache.set(new Cache());
}
return *threadCache.get();
}
static int getNullDevFileDescriptor() {
struct FileDescriptor {
int FD;
const char* file = "/dev/null";
FileDescriptor() { FD = open(file, O_WRONLY); }
~FileDescriptor() {
close(FD);
}
};
static FileDescriptor nullDev;
return nullDev.FD;
}
#endif
// Checking whether the pointer points to a valid memory location
bool isAddressValid(const void *P) {
if (!P || P == (void *) -1)
return false;
#ifdef LLVM_ON_WIN32
MEMORY_BASIC_INFORMATION MBI;
if (!VirtualQuery(P, &MBI, sizeof(MBI)))
return false;
if (MBI.State != MEM_COMMIT)
return false;
return true;
#else
// Look-up the address in the cache.
Cache& currentCache = getCache();
if (currentCache.contains(P))
return true;
// There is a POSIX way of finding whether an address
// can be accessed for reading.
if (write(getNullDevFileDescriptor(), P, 1/*byte*/) != 1) {
assert(errno == EFAULT && "unexpected write error at address");
return false;
}
currentCache.push(P);
return true;
#endif
}
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// Test runing a file in the same directory `cling CurrentDir.C`
// More info in CIFactory.cpp createCIImpl (line ~850)
// RUN: cd %S && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// RUN: mkdir %T/Remove && cd %T/Remove && rm -rf %T/Remove && %cling -DTEST_CWDRETURN %s -Xclang -verify 2>&1 | FileCheck --check-prefix CHECK --check-prefix CHECKcwd %s
// Test testCurrentDir
extern "C" {
int printf(const char*, ...);
char* getcwd(char *buf, std::size_t size);
}
#ifdef TEST_CWDRETURN
// Make sure include still works
#include <string.h>
#include <vector>
#endif
void CurrentDir() {
#ifdef TEST_CWDRETURN
char thisDir[1024];
const char *rslt = getcwd(thisDir, sizeof(thisDir));
// Make sure cling reported the error
// CHECKcwd: Could not get current working directory: {{.*}}
if (rslt)
printf("Working directory exists\n");
// CHECK-NOT: Working directory exists
#endif
printf("Script ran\n");
// CHECK: Script ran
}
//expected-no-diagnostics
<commit_msg>Simplify; make Windows compatible (cannot delete cwd).<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// Test running a file in the same directory `cling CurrentDir.C`.
// More info in CIFactory.cpp ("<<< cling interactive line includer >>>")
// RUN: cp "%s" "%T/CurrentDir.C" && cd %T && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// Test testCurrentDir
extern "C" {
int printf(const char*, ...);
char* getcwd(char *buf, std::size_t size);
}
void CurrentDir() {
printf("Script ran\n"); // CHECK: Script ran
}
//expected-no-diagnostics
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146
.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1
// ROOT-8036: check that library symbols do not override interpreter symbols
int step = 10 // CHECK: (int) 10
step // CHECK: (int) 10
gCling->process("#ifdef __UNDEFINED__\n42\n#endif")
//CHECK: (cling::Interpreter::CompilationResult) (cling::Interpreter::CompilationResult::kSuccess) : (unsigned int) 0
// ROOT-8300
struct B { static void *fgStaticVar; B(){ printf("B::B()\n"); } };
B b; // CHECK: B::B()
// ROOT-7857
template <class T> void tfunc(T) {}
struct ROOT7857{
void func() { tfunc((ROOT7857*)0); }
};
ROOT7857* root7857;
<commit_msg>Add test against ROOT-5248.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146
.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1
// ROOT-8036: check that library symbols do not override interpreter symbols
int step = 10 // CHECK: (int) 10
step // CHECK: (int) 10
gCling->process("#ifdef __UNDEFINED__\n42\n#endif")
//CHECK: (cling::Interpreter::CompilationResult) (cling::Interpreter::CompilationResult::kSuccess) : (unsigned int) 0
// ROOT-8300
struct B { static void *fgStaticVar; B(){ printf("B::B()\n"); } };
B b; // CHECK: B::B()
// ROOT-7857
template <class T> void tfunc(T) {}
struct ROOT7857{
void func() { tfunc((ROOT7857*)0); }
};
ROOT7857* root7857;
// ROOT-5248
class MyClass;
extern MyClass* my;
class MyClass {public: MyClass* getMyClass() {return 0;}} cl;
MyClass* my = cl.getMyClass();
<|endoftext|> |
<commit_before>// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char [5]) "Root"]
// End PR #98146
<commit_msg>[5] now becomes * because we use the wrapper return type.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
// End PR #98146
<|endoftext|> |
<commit_before><commit_msg>sudeep : fixed issues with image handling<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QtTest>
#include <private/qmlpixmapcache_p.h>
#include <QtDeclarative/qmlengine.h>
#include <QNetworkReply>
// These don't let normal people run tests!
//#include "../network-settings.h"
class tst_qmlpixmapcache : public QObject
{
Q_OBJECT
public:
tst_qmlpixmapcache() :
thisfile(QUrl::fromLocalFile(__FILE__))
{
}
private slots:
void single();
void single_data();
void parallel();
void parallel_data();
private:
QmlEngine engine;
QUrl thisfile;
};
static int slotters=0;
class Slotter : public QObject
{
Q_OBJECT
public:
Slotter()
{
gotslot = false;
slotters++;
}
bool gotslot;
public slots:
void got()
{
gotslot = true;
--slotters;
if (slotters==0)
QTestEventLoop::instance().exitLoop();
}
};
#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
static const bool localfile_optimized = true;
#else
static const bool localfile_optimized = false;
#endif
void tst_qmlpixmapcache::single_data()
{
// Note, since QmlPixmapCache is shared, tests affect each other!
// so use different files fore all test functions.
QTest::addColumn<QUrl>("target");
QTest::addColumn<bool>("incache");
QTest::addColumn<bool>("exists");
QTest::addColumn<bool>("neterror");
// File URLs are optimized
QTest::newRow("local") << thisfile.resolved(QUrl("data/exists.png")) << localfile_optimized << true << false;
QTest::newRow("local") << thisfile.resolved(QUrl("data/notexists.png")) << localfile_optimized << false << false;
QTest::newRow("remote") << QUrl("http://qt.nokia.com/logo.png") << false << true << false;
QTest::newRow("remote") << QUrl("http://qt.nokia.com/thereisnologo.png") << false << false << true;
}
void tst_qmlpixmapcache::single()
{
QFETCH(QUrl, target);
QFETCH(bool, incache);
QFETCH(bool, exists);
QFETCH(bool, neterror);
if (neterror) {
QString expected = "Network error loading \""
+target.toString()+"\" \"Error downloading "
+target.toString()+" - server replied: Not Found\" ";
QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
} else if (!exists) {
QString expected = "Cannot open QUrl( \"" + target.toString() + "\" ) ";
QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
}
QPixmap pixmap;
QVERIFY(pixmap.width() <= 0); // Check Qt assumption
QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
if (incache) {
if (exists) {
QVERIFY(status == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
} else {
QVERIFY(status == QmlPixmapReply::Error);
QVERIFY(pixmap.width() <= 0);
}
} else {
QmlPixmapReply *reply = QmlPixmapCache::request(&engine, target);
QVERIFY(reply);
QVERIFY(pixmap.width() <= 0);
Slotter getter;
connect(reply, SIGNAL(finished()), &getter, SLOT(got()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(getter.gotslot);
if (exists) {
QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
} else {
QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Error);
QVERIFY(pixmap.width() <= 0);
}
}
QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}
void tst_qmlpixmapcache::parallel_data()
{
// Note, since QmlPixmapCache is shared, tests affect each other!
// so use different files fore all test functions.
QTest::addColumn<QUrl>("target1");
QTest::addColumn<QUrl>("target2");
QTest::addColumn<int>("incache");
QTest::addColumn<int>("cancel"); // which one to cancel
QTest::addColumn<int>("requests");
QTest::newRow("local")
<< thisfile.resolved(QUrl("data/exists1.png"))
<< thisfile.resolved(QUrl("data/exists2.png"))
<< (localfile_optimized ? 2 : 0)
<< -1
<< (localfile_optimized ? 0 : 2)
;
QTest::newRow("remote")
<< QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
<< QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
<< 0
<< -1
<< 2
;
QTest::newRow("remoteagain")
<< QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
<< QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
<< 2
<< -1
<< 0
;
QTest::newRow("remotecopy")
<< QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
<< QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
<< 0
<< -1
<< 1
;
QTest::newRow("remotecopycancel")
<< QUrl("http://qt.nokia.com/rounded_block_bg.png")
<< QUrl("http://qt.nokia.com/rounded_block_bg.png")
<< 0
<< 0
<< 1
;
}
void tst_qmlpixmapcache::parallel()
{
QFETCH(QUrl, target1);
QFETCH(QUrl, target2);
QFETCH(int, incache);
QFETCH(int, cancel);
QFETCH(int, requests);
QList<QUrl> targets;
targets << target1 << target2;
QList<QmlPixmapReply*> replies;
QList<Slotter*> getters;
for (int i=0; i<targets.count(); ++i) {
QUrl target = targets.at(i);
QPixmap pixmap;
QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
QmlPixmapReply *reply = 0;
if (status != QmlPixmapReply::Error && status != QmlPixmapReply::Ready)
reply = QmlPixmapCache::request(&engine, target);
replies.append(reply);
if (!reply) {
QVERIFY(pixmap.width() > 0);
getters.append(0);
} else {
QVERIFY(pixmap.width() <= 0);
getters.append(new Slotter);
connect(reply, SIGNAL(finished()), getters[i], SLOT(got()));
}
}
QCOMPARE(incache+slotters, targets.count());
QCOMPARE(QmlPixmapCache::pendingRequests(), requests);
if (cancel >= 0) {
QmlPixmapCache::cancel(targets.at(cancel), getters[cancel]);
slotters--;
}
if (slotters) {
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
for (int i=0; i<targets.count(); ++i) {
QmlPixmapReply *reply = replies[i];
if (reply) {
if (i == cancel) {
QVERIFY(!getters[i]->gotslot);
} else {
QVERIFY(getters[i]->gotslot);
QPixmap pixmap;
QVERIFY(QmlPixmapCache::get(targets[i], &pixmap) == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
}
delete getters[i];
}
}
QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}
QTEST_MAIN(tst_qmlpixmapcache)
#include "tst_qmlpixmapcache.moc"
<commit_msg>Fix expected error message.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QtTest>
#include <private/qmlpixmapcache_p.h>
#include <QtDeclarative/qmlengine.h>
#include <QNetworkReply>
// These don't let normal people run tests!
//#include "../network-settings.h"
class tst_qmlpixmapcache : public QObject
{
Q_OBJECT
public:
tst_qmlpixmapcache() :
thisfile(QUrl::fromLocalFile(__FILE__))
{
}
private slots:
void single();
void single_data();
void parallel();
void parallel_data();
private:
QmlEngine engine;
QUrl thisfile;
};
static int slotters=0;
class Slotter : public QObject
{
Q_OBJECT
public:
Slotter()
{
gotslot = false;
slotters++;
}
bool gotslot;
public slots:
void got()
{
gotslot = true;
--slotters;
if (slotters==0)
QTestEventLoop::instance().exitLoop();
}
};
#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
static const bool localfile_optimized = true;
#else
static const bool localfile_optimized = false;
#endif
void tst_qmlpixmapcache::single_data()
{
// Note, since QmlPixmapCache is shared, tests affect each other!
// so use different files fore all test functions.
QTest::addColumn<QUrl>("target");
QTest::addColumn<bool>("incache");
QTest::addColumn<bool>("exists");
QTest::addColumn<bool>("neterror");
// File URLs are optimized
QTest::newRow("local") << thisfile.resolved(QUrl("data/exists.png")) << localfile_optimized << true << false;
QTest::newRow("local") << thisfile.resolved(QUrl("data/notexists.png")) << localfile_optimized << false << false;
QTest::newRow("remote") << QUrl("http://qt.nokia.com/logo.png") << false << true << false;
QTest::newRow("remote") << QUrl("http://qt.nokia.com/thereisnologo.png") << false << false << true;
}
void tst_qmlpixmapcache::single()
{
QFETCH(QUrl, target);
QFETCH(bool, incache);
QFETCH(bool, exists);
QFETCH(bool, neterror);
if (neterror) {
QString expected = "\"Error downloading " + target.toString() + " - server replied: Not Found\" ";
QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
} else if (!exists) {
QString expected = "Cannot open QUrl( \"" + target.toString() + "\" ) ";
QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
}
QPixmap pixmap;
QVERIFY(pixmap.width() <= 0); // Check Qt assumption
QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
if (incache) {
if (exists) {
QVERIFY(status == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
} else {
QVERIFY(status == QmlPixmapReply::Error);
QVERIFY(pixmap.width() <= 0);
}
} else {
QmlPixmapReply *reply = QmlPixmapCache::request(&engine, target);
QVERIFY(reply);
QVERIFY(pixmap.width() <= 0);
Slotter getter;
connect(reply, SIGNAL(finished()), &getter, SLOT(got()));
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(getter.gotslot);
if (exists) {
QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
} else {
QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Error);
QVERIFY(pixmap.width() <= 0);
}
}
QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}
void tst_qmlpixmapcache::parallel_data()
{
// Note, since QmlPixmapCache is shared, tests affect each other!
// so use different files fore all test functions.
QTest::addColumn<QUrl>("target1");
QTest::addColumn<QUrl>("target2");
QTest::addColumn<int>("incache");
QTest::addColumn<int>("cancel"); // which one to cancel
QTest::addColumn<int>("requests");
QTest::newRow("local")
<< thisfile.resolved(QUrl("data/exists1.png"))
<< thisfile.resolved(QUrl("data/exists2.png"))
<< (localfile_optimized ? 2 : 0)
<< -1
<< (localfile_optimized ? 0 : 2)
;
QTest::newRow("remote")
<< QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
<< QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
<< 0
<< -1
<< 2
;
QTest::newRow("remoteagain")
<< QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
<< QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
<< 2
<< -1
<< 0
;
QTest::newRow("remotecopy")
<< QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
<< QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
<< 0
<< -1
<< 1
;
QTest::newRow("remotecopycancel")
<< QUrl("http://qt.nokia.com/rounded_block_bg.png")
<< QUrl("http://qt.nokia.com/rounded_block_bg.png")
<< 0
<< 0
<< 1
;
}
void tst_qmlpixmapcache::parallel()
{
QFETCH(QUrl, target1);
QFETCH(QUrl, target2);
QFETCH(int, incache);
QFETCH(int, cancel);
QFETCH(int, requests);
QList<QUrl> targets;
targets << target1 << target2;
QList<QmlPixmapReply*> replies;
QList<Slotter*> getters;
for (int i=0; i<targets.count(); ++i) {
QUrl target = targets.at(i);
QPixmap pixmap;
QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
QmlPixmapReply *reply = 0;
if (status != QmlPixmapReply::Error && status != QmlPixmapReply::Ready)
reply = QmlPixmapCache::request(&engine, target);
replies.append(reply);
if (!reply) {
QVERIFY(pixmap.width() > 0);
getters.append(0);
} else {
QVERIFY(pixmap.width() <= 0);
getters.append(new Slotter);
connect(reply, SIGNAL(finished()), getters[i], SLOT(got()));
}
}
QCOMPARE(incache+slotters, targets.count());
QCOMPARE(QmlPixmapCache::pendingRequests(), requests);
if (cancel >= 0) {
QmlPixmapCache::cancel(targets.at(cancel), getters[cancel]);
slotters--;
}
if (slotters) {
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
}
for (int i=0; i<targets.count(); ++i) {
QmlPixmapReply *reply = replies[i];
if (reply) {
if (i == cancel) {
QVERIFY(!getters[i]->gotslot);
} else {
QVERIFY(getters[i]->gotslot);
QPixmap pixmap;
QVERIFY(QmlPixmapCache::get(targets[i], &pixmap) == QmlPixmapReply::Ready);
QVERIFY(pixmap.width() > 0);
}
delete getters[i];
}
}
QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}
QTEST_MAIN(tst_qmlpixmapcache)
#include "tst_qmlpixmapcache.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataBrowser.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2008-02-18 15:40:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART_DATA_BROWSER_HXX
#define CHART_DATA_BROWSER_HXX
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _FMTFIELD_HXX_
#include <svtools/fmtfield.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#include <vector>
#include <memory>
#include <boost/shared_ptr.hpp>
namespace com { namespace sun { namespace star {
namespace chart2 {
class XChartDocument;
}
}}}
namespace chart
{
class DataBrowserModel;
class NumberFormatterWrapper;
namespace impl
{
class SeriesHeader;
class SeriesHeaderEdit;
}
class DataBrowser : public ::svt::EditBrowseBox
{
protected:
// EditBrowseBox overridables
virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const;
virtual sal_Bool SeekRow( long nRow );
virtual sal_Bool IsTabAllowed( sal_Bool bForward ) const;
virtual ::svt::CellController* GetController( long nRow, sal_uInt16 nCol );
virtual void InitController( ::svt::CellControllerRef& rController, long nRow, sal_uInt16 nCol );
virtual sal_Bool SaveModified();
virtual void CursorMoved();
// called whenever the control of the current cell has been modified
virtual void CellModified();
virtual void ColumnResized( USHORT nColId );
virtual void EndScroll();
virtual void MouseButtonDown( const BrowserMouseEvent& rEvt );
void SetDirty();
public:
DataBrowser( Window* pParent, const ResId & rId, bool bLiveUpdate );
virtual ~DataBrowser();
/** GetCellText returns the text at the given position
@param nRow
the number of the row
@param nColId
the ID of the column
@return
the text out of the cell
*/
virtual String GetCellText(long nRow, USHORT nColId) const;
/** returns the number in the given cell. If a cell is empty or contains a
string, the result will be Nan
*/
double GetCellNumber( long nRow, USHORT nColumnId ) const;
// Window
virtual void Resize();
/// @return old state
bool SetReadOnly( bool bNewState );
bool IsReadOnly() const;
/// @return true, if data has been modified
bool IsDirty() const;
/// reset the dirty status, if changes have been saved
void SetClean();
void SetDataFromModel( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > & xChartDoc,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > & xContext );
// void setNumberFormatter();
// predicates to determine what actions are possible at the current cursor
// position. This depends on the implementation of the according mutators
// below. (They are used for enabling toolbar icons)
bool MayInsertRow() const;
bool MayInsertColumn() const;
bool MayDeleteRow() const;
bool MayDeleteColumn() const;
bool MaySwapRows() const;
bool MaySwapColumns() const;
// bool MaySortRow() const;
// bool MaySortColumn() const;
// mutators mutating data
void InsertRow();
void InsertColumn();
void RemoveRow();
void RemoveColumn();
using BrowseBox::RemoveColumn;
using BrowseBox::MouseButtonDown;
void SwapRow();
void SwapColumn();
// void QuickSortRow();
// void QuickSortCol();
// sorting the entire table
// void QuickSortTableCols ();
// void QuickSortTableRows ();
void SetCursorMovedHdl( const Link& rLink );
const Link& GetCursorMovedHdl() const;
void SetCellModifiedHdl( const Link& rLink );
/// confirms all pending changes to be ready to be closed
bool EndEditing();
// calls the protected inline-function BrowseBox::GetFirstVisibleColNumber()
sal_Int16 GetFirstVisibleColumNumber() const;
sal_Int32 GetTotalWidth() const;
bool CellContainsNumbers( sal_Int32 nRow, sal_uInt16 nCol ) const;
sal_uInt32 GetNumberFormatKey( sal_Int32 nRow, sal_uInt16 nCol ) const;
bool IsEnableItem();
bool IsDataValid();
void ShowWarningBox();
bool ShowQueryBox();
private:
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > m_xChartDoc;
::std::auto_ptr< DataBrowserModel > m_apDataBrowserModel;
typedef ::std::vector< ::boost::shared_ptr< impl::SeriesHeader > > tSeriesHeaderContainer;
tSeriesHeaderContainer m_aSeriesHeaders;
::boost::shared_ptr< NumberFormatterWrapper > m_spNumberFormatterWrapper;
/// the row that is currently painted
long m_nSeekRow;
bool m_bIsReadOnly;
bool m_bIsDirty;
bool m_bLiveUpdate;
bool m_bDataValid;
FormattedField m_aNumberEditField;
Edit m_aTextEditField;
/// note: m_aNumberEditField must precede this member!
::svt::CellControllerRef m_rNumberEditController;
/// note: m_aTextEditField must precede this member!
::svt::CellControllerRef m_rTextEditController;
Link m_aCursorMovedHdlLink;
Link m_aCellModifiedLink;
void clearHeaders();
void RenewTable();
void ImplAdjustHeaderControls();
String GetColString( sal_Int32 nColumnId ) const;
String GetRowString( sal_Int32 nRow ) const;
DECL_LINK( SeriesHeaderGotFocus, impl::SeriesHeaderEdit* );
DECL_LINK( SeriesHeaderChanged, impl::SeriesHeaderEdit* );
/// not implemented: inhibit copy construction
DataBrowser( const DataBrowser & );
};
} // namespace chart
#endif // CHART_DATA_BROWSER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.34); FILE MERGED 2008/04/01 15:03:59 thb 1.4.34.3: #i85898# Stripping all external header guards 2008/04/01 10:50:18 thb 1.4.34.2: #i85898# Stripping all external header guards 2008/03/28 16:43:20 rt 1.4.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataBrowser.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CHART_DATA_BROWSER_HXX
#define CHART_DATA_BROWSER_HXX
#include <svtools/editbrowsebox.hxx>
#include <vcl/outdev.hxx>
#include <svtools/fmtfield.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <vector>
#include <memory>
#include <boost/shared_ptr.hpp>
namespace com { namespace sun { namespace star {
namespace chart2 {
class XChartDocument;
}
}}}
namespace chart
{
class DataBrowserModel;
class NumberFormatterWrapper;
namespace impl
{
class SeriesHeader;
class SeriesHeaderEdit;
}
class DataBrowser : public ::svt::EditBrowseBox
{
protected:
// EditBrowseBox overridables
virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const;
virtual sal_Bool SeekRow( long nRow );
virtual sal_Bool IsTabAllowed( sal_Bool bForward ) const;
virtual ::svt::CellController* GetController( long nRow, sal_uInt16 nCol );
virtual void InitController( ::svt::CellControllerRef& rController, long nRow, sal_uInt16 nCol );
virtual sal_Bool SaveModified();
virtual void CursorMoved();
// called whenever the control of the current cell has been modified
virtual void CellModified();
virtual void ColumnResized( USHORT nColId );
virtual void EndScroll();
virtual void MouseButtonDown( const BrowserMouseEvent& rEvt );
void SetDirty();
public:
DataBrowser( Window* pParent, const ResId & rId, bool bLiveUpdate );
virtual ~DataBrowser();
/** GetCellText returns the text at the given position
@param nRow
the number of the row
@param nColId
the ID of the column
@return
the text out of the cell
*/
virtual String GetCellText(long nRow, USHORT nColId) const;
/** returns the number in the given cell. If a cell is empty or contains a
string, the result will be Nan
*/
double GetCellNumber( long nRow, USHORT nColumnId ) const;
// Window
virtual void Resize();
/// @return old state
bool SetReadOnly( bool bNewState );
bool IsReadOnly() const;
/// @return true, if data has been modified
bool IsDirty() const;
/// reset the dirty status, if changes have been saved
void SetClean();
void SetDataFromModel( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > & xChartDoc,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > & xContext );
// void setNumberFormatter();
// predicates to determine what actions are possible at the current cursor
// position. This depends on the implementation of the according mutators
// below. (They are used for enabling toolbar icons)
bool MayInsertRow() const;
bool MayInsertColumn() const;
bool MayDeleteRow() const;
bool MayDeleteColumn() const;
bool MaySwapRows() const;
bool MaySwapColumns() const;
// bool MaySortRow() const;
// bool MaySortColumn() const;
// mutators mutating data
void InsertRow();
void InsertColumn();
void RemoveRow();
void RemoveColumn();
using BrowseBox::RemoveColumn;
using BrowseBox::MouseButtonDown;
void SwapRow();
void SwapColumn();
// void QuickSortRow();
// void QuickSortCol();
// sorting the entire table
// void QuickSortTableCols ();
// void QuickSortTableRows ();
void SetCursorMovedHdl( const Link& rLink );
const Link& GetCursorMovedHdl() const;
void SetCellModifiedHdl( const Link& rLink );
/// confirms all pending changes to be ready to be closed
bool EndEditing();
// calls the protected inline-function BrowseBox::GetFirstVisibleColNumber()
sal_Int16 GetFirstVisibleColumNumber() const;
sal_Int32 GetTotalWidth() const;
bool CellContainsNumbers( sal_Int32 nRow, sal_uInt16 nCol ) const;
sal_uInt32 GetNumberFormatKey( sal_Int32 nRow, sal_uInt16 nCol ) const;
bool IsEnableItem();
bool IsDataValid();
void ShowWarningBox();
bool ShowQueryBox();
private:
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > m_xChartDoc;
::std::auto_ptr< DataBrowserModel > m_apDataBrowserModel;
typedef ::std::vector< ::boost::shared_ptr< impl::SeriesHeader > > tSeriesHeaderContainer;
tSeriesHeaderContainer m_aSeriesHeaders;
::boost::shared_ptr< NumberFormatterWrapper > m_spNumberFormatterWrapper;
/// the row that is currently painted
long m_nSeekRow;
bool m_bIsReadOnly;
bool m_bIsDirty;
bool m_bLiveUpdate;
bool m_bDataValid;
FormattedField m_aNumberEditField;
Edit m_aTextEditField;
/// note: m_aNumberEditField must precede this member!
::svt::CellControllerRef m_rNumberEditController;
/// note: m_aTextEditField must precede this member!
::svt::CellControllerRef m_rTextEditController;
Link m_aCursorMovedHdlLink;
Link m_aCellModifiedLink;
void clearHeaders();
void RenewTable();
void ImplAdjustHeaderControls();
String GetColString( sal_Int32 nColumnId ) const;
String GetRowString( sal_Int32 nRow ) const;
DECL_LINK( SeriesHeaderGotFocus, impl::SeriesHeaderEdit* );
DECL_LINK( SeriesHeaderChanged, impl::SeriesHeaderEdit* );
/// not implemented: inhibit copy construction
DataBrowser( const DataBrowser & );
};
} // namespace chart
#endif // CHART_DATA_BROWSER_HXX
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtorganizer.h"
#include "qorganizeritemid.h"
#include "qorganizercollectionenginelocalid.h"
#include <QSet>
//TESTED_COMPONENT=src/organizer
//TESTED_CLASS=
//TESTED_FILES=
QTM_USE_NAMESPACE
class tst_QOrganizerCollection: public QObject
{
Q_OBJECT
public:
tst_QOrganizerCollection();
virtual ~tst_QOrganizerCollection();
private slots:
void metaData();
void idLessThan();
void idHash();
void hash();
void datastream();
void traits();
void idTraits();
void localIdTraits();
};
tst_QOrganizerCollection::tst_QOrganizerCollection()
{
}
tst_QOrganizerCollection::~tst_QOrganizerCollection()
{
}
void tst_QOrganizerCollection::metaData()
{
QOrganizerCollection c;
QVERIFY(c.metaData().isEmpty());
c.setMetaData("test", 5);
QVERIFY(c.metaData().contains("test"));
QVariantMap mdm;
mdm.insert("test2", 6);
c.setMetaData(mdm);
QCOMPARE(c.metaData(), mdm);
}
class BasicCollectionLocalId : public QOrganizerCollectionEngineId
{
public:
BasicCollectionLocalId(uint id) : m_id(id) {}
bool isEqualTo(const QOrganizerCollectionEngineId* other) const {
return m_id == static_cast<const BasicCollectionLocalId*>(other)->m_id;
}
bool isLessThan(const QOrganizerCollectionEngineId* other) const {
return m_id < static_cast<const BasicCollectionLocalId*>(other)->m_id;
}
uint engineIdType() const {
return 0;
}
const QString managerUri() const {
static const QString uri(QLatin1String("qtorganizer:basic:"));
return uri;
}
QOrganizerCollectionEngineId* clone() const {
BasicCollectionLocalId* cloned = new BasicCollectionLocalId(m_id);
return cloned;
}
QDebug& debugStreamOut(QDebug& dbg) const {
return dbg << m_id;
}
QDataStream& dataStreamOut(QDataStream& out) const {
return out << static_cast<quint32>(m_id);
}
QDataStream& dataStreamIn(QDataStream& in) {
quint32 id;
in >> id;
m_id = id;
return in;
}
uint hash() const {
return m_id;
}
private:
uint m_id;
};
QOrganizerCollectionId makeId(uint id)
{
return QOrganizerCollectionId(new BasicCollectionLocalId(id));
}
void tst_QOrganizerCollection::idLessThan()
{
// TODO: review tests
/* QOrganizerCollectionId id1;
id1.setManagerUri("a");
id1.setId(makeId(1));
QOrganizerCollectionId id2;
id2.setManagerUri("a");
id2.setId(makeId(1));
QVERIFY(!(id1 < id2));
QVERIFY(!(id2 < id1));
QOrganizerCollectionId id3;
id3.setManagerUri("a");
id3.setId(makeId(2));
QOrganizerCollectionId id4;
id4.setManagerUri("b");
id4.setId(makeId(1));
QOrganizerCollectionId id5; // no URI
id5.setId(makeId(2));
QVERIFY(id1 < id3);
QVERIFY(!(id3 < id1));
QVERIFY(id1 < id4);
QVERIFY(!(id4 < id1));
QVERIFY(id3 < id4);
QVERIFY(!(id4 < id3));
QVERIFY(id5 < id1);
QVERIFY(!(id1 < id5));*/
}
void tst_QOrganizerCollection::idHash()
{
// TODO: review tests
/* QOrganizerCollectionId id1;
id1.setManagerUri("a");
id1.setId(makeId(1));
QOrganizerCollectionId id2;
id2.setManagerUri("a");
id2.setId(makeId(1));
QOrganizerCollectionId id3;
id3.setManagerUri("b");
id3.setId(makeId(1));
QVERIFY(qHash(id1) == qHash(id2));
QVERIFY(qHash(id1) != qHash(id3));
QSet<QOrganizerCollectionId> set;
set.insert(id1);
set.insert(id2);
set.insert(id3);
QCOMPARE(set.size(), 2);*/
}
void tst_QOrganizerCollection::hash()
{
// TODO: review tests
/* QOrganizerCollectionId id;
id.setManagerUri("a");
id.setId(makeId(1));
QOrganizerCollection c1;
c1.setId(id);
c1.setMetaData("key", "value");
QOrganizerCollection c2;
c2.setId(id);
c2.setMetaData("key", "value");
QOrganizerCollection c3;
c3.setId(id);
c3.setMetaData("key", "another value");
QOrganizerCollection c4; // no details
c4.setId(id);
QOrganizerCollection c5;
c5.setId(id);
c5.setMetaData("key", "value");
QVERIFY(qHash(c1) == qHash(c2));
QVERIFY(qHash(c1) != qHash(c3));
QVERIFY(qHash(c1) != qHash(c4));
QVERIFY(qHash(c1) == qHash(c5));*/
}
void tst_QOrganizerCollection::datastream()
{
// collection datastreaming
QByteArray buffer;
QOrganizerCollection collectionIn;
collectionIn.setMetaData("key", "value");
QOrganizerCollection collectionOut;
QOrganizerCollectionId originalId;
// first, stream an item with a complete id
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
QOrganizerManager om("memory");
QVERIFY(om.saveCollection(&collectionIn)); // fill in its ID
originalId = collectionIn.id();
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
}
// second, stream an item with an id with the mgr uri set, local id null
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
collectionIn.setId(QOrganizerCollectionId());
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
}
/* TODO: Review tests
// third, stream an item with an id with the mgr uri null, local id set
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
QOrganizerCollectionId modifiedId = originalId;
modifiedId.setManagerUri(QString()); // this will clear the local id!
modifiedId.setId(originalId.localId()); // so reset it and make sure nothing bad happens.
collectionIn.setId(modifiedId);
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QVERIFY(collectionOut.metaData() == collectionIn.metaData());
QVERIFY(collectionOut.id() != collectionIn.id()); // no manager uri of input :. won't be serialized.
}*/
// fourth, stream an item with a null id
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
collectionIn.setId(QOrganizerCollectionId());
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QVERIFY(collectionOut.metaData() == collectionIn.metaData());
QVERIFY(collectionOut.id() == collectionIn.id()); // should both be null ids.
}
// id datastreaming
buffer.clear();
QOrganizerCollectionId inputId;
QOrganizerCollectionId outputId;
// first, stream the whole id (mgr uri set, local id set)
{
inputId = originalId;
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
/* TODO: review test
// second, stream a partial id (mgr uri null, local id set)
{
inputId.setManagerUri(QString());
inputId.setId(originalId.localId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
// because the manager uri is null, we cannot stream it in.
QVERIFY(outputId.isNull());
QVERIFY(!inputId.isNull());
}
// third, stream a partial id (mgr uri set, local id null).
{
inputId.setManagerUri(originalId.managerUri());
inputId.setId(QOrganizerCollectionId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}*/
// fourth, stream a null id
{
inputId = QOrganizerCollectionId();
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
/* TODO: review test
// fifth, stream an id after changing it's manager uri.
{
inputId.setManagerUri(originalId.managerUri());
inputId.setId(originalId.localId());
inputId.setManagerUri("test manager uri"); // should clear the local id.
QVERIFY(inputId.localId() == QOrganizerCollectionId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
// sixth, stream an id after changing it's manager uri and resetting the local id.
// this should cause great problems, because the manager doesn't exist so it shouldn't
// be able to deserialize. Make sure it's handled gracefully.
{
inputId.setManagerUri(originalId.managerUri());
inputId.setManagerUri("test manager uri"); // should clear the local id.
inputId.setId(originalId.localId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QVERIFY(outputId.isNull());
} */
}
void tst_QOrganizerCollection::traits()
{
QVERIFY(sizeof(QOrganizerCollection) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollection)> ti;
QVERIFY(ti.isComplex);
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
void tst_QOrganizerCollection::idTraits()
{
QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
QVERIFY(ti.isComplex);
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
void tst_QOrganizerCollection::localIdTraits()
{
QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
QVERIFY(ti.isComplex); // unlike QContactLocalId (int typedef), we have a ctor
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
QTEST_MAIN(tst_QOrganizerCollection)
#include "tst_qorganizercollection.moc"
<commit_msg>Removed an invalid include from tst_qorganizercollection<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtorganizer.h"
#include "qorganizeritemid.h"
#include <QSet>
//TESTED_COMPONENT=src/organizer
//TESTED_CLASS=
//TESTED_FILES=
QTM_USE_NAMESPACE
class tst_QOrganizerCollection: public QObject
{
Q_OBJECT
public:
tst_QOrganizerCollection();
virtual ~tst_QOrganizerCollection();
private slots:
void metaData();
void idLessThan();
void idHash();
void hash();
void datastream();
void traits();
void idTraits();
void localIdTraits();
};
tst_QOrganizerCollection::tst_QOrganizerCollection()
{
}
tst_QOrganizerCollection::~tst_QOrganizerCollection()
{
}
void tst_QOrganizerCollection::metaData()
{
QOrganizerCollection c;
QVERIFY(c.metaData().isEmpty());
c.setMetaData("test", 5);
QVERIFY(c.metaData().contains("test"));
QVariantMap mdm;
mdm.insert("test2", 6);
c.setMetaData(mdm);
QCOMPARE(c.metaData(), mdm);
}
class BasicCollectionLocalId : public QOrganizerCollectionEngineId
{
public:
BasicCollectionLocalId(uint id) : m_id(id) {}
bool isEqualTo(const QOrganizerCollectionEngineId* other) const {
return m_id == static_cast<const BasicCollectionLocalId*>(other)->m_id;
}
bool isLessThan(const QOrganizerCollectionEngineId* other) const {
return m_id < static_cast<const BasicCollectionLocalId*>(other)->m_id;
}
uint engineIdType() const {
return 0;
}
const QString managerUri() const {
static const QString uri(QLatin1String("qtorganizer:basic:"));
return uri;
}
QOrganizerCollectionEngineId* clone() const {
BasicCollectionLocalId* cloned = new BasicCollectionLocalId(m_id);
return cloned;
}
QDebug& debugStreamOut(QDebug& dbg) const {
return dbg << m_id;
}
QDataStream& dataStreamOut(QDataStream& out) const {
return out << static_cast<quint32>(m_id);
}
QDataStream& dataStreamIn(QDataStream& in) {
quint32 id;
in >> id;
m_id = id;
return in;
}
uint hash() const {
return m_id;
}
private:
uint m_id;
};
QOrganizerCollectionId makeId(uint id)
{
return QOrganizerCollectionId(new BasicCollectionLocalId(id));
}
void tst_QOrganizerCollection::idLessThan()
{
// TODO: review tests
/* QOrganizerCollectionId id1;
id1.setManagerUri("a");
id1.setId(makeId(1));
QOrganizerCollectionId id2;
id2.setManagerUri("a");
id2.setId(makeId(1));
QVERIFY(!(id1 < id2));
QVERIFY(!(id2 < id1));
QOrganizerCollectionId id3;
id3.setManagerUri("a");
id3.setId(makeId(2));
QOrganizerCollectionId id4;
id4.setManagerUri("b");
id4.setId(makeId(1));
QOrganizerCollectionId id5; // no URI
id5.setId(makeId(2));
QVERIFY(id1 < id3);
QVERIFY(!(id3 < id1));
QVERIFY(id1 < id4);
QVERIFY(!(id4 < id1));
QVERIFY(id3 < id4);
QVERIFY(!(id4 < id3));
QVERIFY(id5 < id1);
QVERIFY(!(id1 < id5));*/
}
void tst_QOrganizerCollection::idHash()
{
// TODO: review tests
/* QOrganizerCollectionId id1;
id1.setManagerUri("a");
id1.setId(makeId(1));
QOrganizerCollectionId id2;
id2.setManagerUri("a");
id2.setId(makeId(1));
QOrganizerCollectionId id3;
id3.setManagerUri("b");
id3.setId(makeId(1));
QVERIFY(qHash(id1) == qHash(id2));
QVERIFY(qHash(id1) != qHash(id3));
QSet<QOrganizerCollectionId> set;
set.insert(id1);
set.insert(id2);
set.insert(id3);
QCOMPARE(set.size(), 2);*/
}
void tst_QOrganizerCollection::hash()
{
// TODO: review tests
/* QOrganizerCollectionId id;
id.setManagerUri("a");
id.setId(makeId(1));
QOrganizerCollection c1;
c1.setId(id);
c1.setMetaData("key", "value");
QOrganizerCollection c2;
c2.setId(id);
c2.setMetaData("key", "value");
QOrganizerCollection c3;
c3.setId(id);
c3.setMetaData("key", "another value");
QOrganizerCollection c4; // no details
c4.setId(id);
QOrganizerCollection c5;
c5.setId(id);
c5.setMetaData("key", "value");
QVERIFY(qHash(c1) == qHash(c2));
QVERIFY(qHash(c1) != qHash(c3));
QVERIFY(qHash(c1) != qHash(c4));
QVERIFY(qHash(c1) == qHash(c5));*/
}
void tst_QOrganizerCollection::datastream()
{
// collection datastreaming
QByteArray buffer;
QOrganizerCollection collectionIn;
collectionIn.setMetaData("key", "value");
QOrganizerCollection collectionOut;
QOrganizerCollectionId originalId;
// first, stream an item with a complete id
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
QOrganizerManager om("memory");
QVERIFY(om.saveCollection(&collectionIn)); // fill in its ID
originalId = collectionIn.id();
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
}
// second, stream an item with an id with the mgr uri set, local id null
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
collectionIn.setId(QOrganizerCollectionId());
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
}
/* TODO: Review tests
// third, stream an item with an id with the mgr uri null, local id set
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
QOrganizerCollectionId modifiedId = originalId;
modifiedId.setManagerUri(QString()); // this will clear the local id!
modifiedId.setId(originalId.localId()); // so reset it and make sure nothing bad happens.
collectionIn.setId(modifiedId);
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QVERIFY(collectionOut.metaData() == collectionIn.metaData());
QVERIFY(collectionOut.id() != collectionIn.id()); // no manager uri of input :. won't be serialized.
}*/
// fourth, stream an item with a null id
{
QDataStream stream1(&buffer, QIODevice::WriteOnly);
collectionIn.setId(QOrganizerCollectionId());
stream1 << collectionIn;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> collectionOut;
QVERIFY(collectionOut.metaData() == collectionIn.metaData());
QVERIFY(collectionOut.id() == collectionIn.id()); // should both be null ids.
}
// id datastreaming
buffer.clear();
QOrganizerCollectionId inputId;
QOrganizerCollectionId outputId;
// first, stream the whole id (mgr uri set, local id set)
{
inputId = originalId;
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
/* TODO: review test
// second, stream a partial id (mgr uri null, local id set)
{
inputId.setManagerUri(QString());
inputId.setId(originalId.localId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
// because the manager uri is null, we cannot stream it in.
QVERIFY(outputId.isNull());
QVERIFY(!inputId.isNull());
}
// third, stream a partial id (mgr uri set, local id null).
{
inputId.setManagerUri(originalId.managerUri());
inputId.setId(QOrganizerCollectionId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}*/
// fourth, stream a null id
{
inputId = QOrganizerCollectionId();
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
/* TODO: review test
// fifth, stream an id after changing it's manager uri.
{
inputId.setManagerUri(originalId.managerUri());
inputId.setId(originalId.localId());
inputId.setManagerUri("test manager uri"); // should clear the local id.
QVERIFY(inputId.localId() == QOrganizerCollectionId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QCOMPARE(inputId, outputId);
}
// sixth, stream an id after changing it's manager uri and resetting the local id.
// this should cause great problems, because the manager doesn't exist so it shouldn't
// be able to deserialize. Make sure it's handled gracefully.
{
inputId.setManagerUri(originalId.managerUri());
inputId.setManagerUri("test manager uri"); // should clear the local id.
inputId.setId(originalId.localId());
buffer.clear();
QDataStream stream1(&buffer, QIODevice::WriteOnly);
stream1 << inputId;
QVERIFY(buffer.size() > 0);
QDataStream stream2(buffer);
stream2 >> outputId;
QVERIFY(outputId.isNull());
} */
}
void tst_QOrganizerCollection::traits()
{
QVERIFY(sizeof(QOrganizerCollection) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollection)> ti;
QVERIFY(ti.isComplex);
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
void tst_QOrganizerCollection::idTraits()
{
QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
QVERIFY(ti.isComplex);
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
void tst_QOrganizerCollection::localIdTraits()
{
QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
QVERIFY(ti.isComplex); // unlike QContactLocalId (int typedef), we have a ctor
QVERIFY(!ti.isStatic);
QVERIFY(!ti.isLarge);
QVERIFY(!ti.isPointer);
QVERIFY(!ti.isDummy);
}
QTEST_MAIN(tst_QOrganizerCollection)
#include "tst_qorganizercollection.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: DrawViewWrapper.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: bm $ $Date: 2003-10-06 09:58:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_DRAW_VIEW_WRAPPER_HXX
#define _CHART2_DRAW_VIEW_WRAPPER_HXX
#ifndef _E3D_VIEW3D_HXX
#include <svx/view3d.hxx>
#endif
class SdrModel;
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.
Another task is to hide functionality we do not need, for example more than one page.
*/
class MarkHandleProvider
{
public:
virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;
virtual bool getFrameDragSingles() =0;
};
class DrawViewWrapper : public E3dView
{
public:
DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut);
virtual ~DrawViewWrapper();
//fill list of selection handles 'aHdl'
virtual void SetMarkHandles();
//SdrPageView* GetPageView() { return m_pWrappedDLPageView; };
SdrObject* getHitObject( const Point& rPnt ) const;
//BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;
//BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;
//BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }
//void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);
void MarkObject( SdrObject* pObj );
//----------------------
//pMarkHandleProvider can be NULL; ownership is not taken
void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );
void InitRedraw( OutputDevice* pOut, const Region& rReg );
private:
mutable SdrPageView* m_pWrappedDLPageView;
mutable MarkHandleProvider* m_pMarkHandleProvider;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>added text-edit-outliner support<commit_after>/*************************************************************************
*
* $RCSfile: DrawViewWrapper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: iha $ $Date: 2003-10-28 16:24:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_DRAW_VIEW_WRAPPER_HXX
#define _CHART2_DRAW_VIEW_WRAPPER_HXX
#ifndef _E3D_VIEW3D_HXX
#include <svx/view3d.hxx>
#endif
class SdrModel;
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.
Another task is to hide functionality we do not need, for example more than one page.
*/
class MarkHandleProvider
{
public:
virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;
virtual bool getFrameDragSingles() =0;
};
class DrawViewWrapper : public E3dView
{
public:
DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut);
virtual ~DrawViewWrapper();
//fill list of selection handles 'aHdl'
virtual void SetMarkHandles();
SdrPageView* GetPageView() { return m_pWrappedDLPageView; };
SdrObject* getHitObject( const Point& rPnt ) const;
//BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;
//BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;
//BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }
//void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);
void MarkObject( SdrObject* pObj );
//----------------------
//pMarkHandleProvider can be NULL; ownership is not taken
void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );
void InitRedraw( OutputDevice* pOut, const Region& rReg );
SdrObject* getTextEditObject() const;
SdrOutliner* getOutliner() const;
private:
mutable SdrPageView* m_pWrappedDLPageView;
mutable MarkHandleProvider* m_pMarkHandleProvider;
::std::auto_ptr< SdrOutliner > m_apOutliner;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/background_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
using views::WidgetGtk;
namespace chromeos {
BackgroundView::BackgroundView() : status_area_(NULL),
os_version_label_(NULL),
boot_times_label_(NULL),
did_paint_(false) {
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kWizardBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitStatusArea();
InitInfoLabels();
}
static void ResetXCursor() {
// TODO(sky): nuke this once new window manager is in place.
// This gets rid of the ugly X default cursor.
Display* display = x11_util::GetXDisplay();
Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
XID root_window = x11_util::GetX11RootWindow();
XSetWindowAttributes attr;
attr.cursor = cursor;
XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}
// static
views::Widget* BackgroundView::CreateWindowContainingView(
const gfx::Rect& bounds,
BackgroundView** view) {
ResetXCursor();
WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
window->Init(NULL, bounds);
*view = new BackgroundView();
window->SetContentsView(*view);
(*view)->UpdateWindowType();
// This keeps the window from flashing at startup.
GdkWindow* gdk_window = window->GetNativeView()->window;
gdk_window_set_back_pixmap(gdk_window, NULL, false);
return window;
}
void BackgroundView::SetStatusAreaVisible(bool visible) {
status_area_->SetVisible(visible);
}
void BackgroundView::Paint(gfx::Canvas* canvas) {
views::View::Paint(canvas);
if (!did_paint_) {
did_paint_ = true;
UpdateWindowType();
}
}
void BackgroundView::Layout() {
int corner_padding =
chromeos::BorderDefinition::kWizardBorder.padding +
chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
int kInfoLeftPadding = 60;
int kInfoBottomPadding = 40;
int kInfoBetweenLinesPadding = 4;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - corner_padding,
corner_padding,
status_area_size.width(),
status_area_size.height());
gfx::Size version_size = os_version_label_->GetPreferredSize();
os_version_label_->SetBounds(
kInfoLeftPadding,
height() -
((2 * version_size.height()) +
kInfoBottomPadding +
kInfoBetweenLinesPadding),
width() - 2 * kInfoLeftPadding,
version_size.height());
boot_times_label_->SetBounds(
kInfoLeftPadding,
height() - (version_size.height() + kInfoBottomPadding),
width() - 2 * corner_padding,
version_size.height());
}
void BackgroundView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
gfx::NativeWindow BackgroundView::GetNativeWindow() const {
return
GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}
bool BackgroundView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->clock_view() ||
button_view == status_area_->feedback_view() ||
button_view == status_area_->language_view() ||
button_view == status_area_->network_view()) {
return false;
}
return true;
}
void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
// TODO(avayvod): Add some dialog for options or remove them completely.
}
bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
return true;
}
bool BackgroundView::IsBrowserMode() const {
return false;
}
void BackgroundView::LocaleChanged() {
Layout();
SchedulePaint();
}
void BackgroundView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
AddChildView(status_area_);
}
void BackgroundView::InitInfoLabels() {
const SkColor kVersionColor = 0xff8eb1f4;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
os_version_label_ = new views::Label();
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(os_version_label_);
boot_times_label_ = new views::Label();
boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
boot_times_label_->SetColor(kVersionColor);
boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(boot_times_label_);
if (CrosLibrary::Get()->EnsureLoaded()) {
version_loader_.GetVersion(
&version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
boot_times_loader_.GetBootTimes(
&boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
} else {
os_version_label_->SetText(
ASCIIToWide(CrosLibrary::Get()->load_error_string()));
}
}
void BackgroundView::UpdateWindowType() {
std::vector<int> params;
params.push_back(did_paint_ ? 1 : 0);
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_BACKGROUND,
¶ms);
}
void BackgroundView::OnVersion(
VersionLoader::Handle handle, std::string version) {
std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
version_text += ' ';
version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
version_text += ' ';
version_text += version;
os_version_label_->SetText(ASCIIToWide(version_text));
}
void BackgroundView::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
// TODO(davemoore) if we decide to keep these times visible we will need
// to localize the strings.
const char* kBootTimesNoChromeExec =
"Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Boot took %.2f seconds "
"(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome_exec > 0) {
boot_times_text =
StringPrintf(
kBootTimesChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.chrome_exec - boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.chrome_exec);
} else {
boot_times_text =
StringPrintf(
kBootTimesNoChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.pre_startup);
}
boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}
} // namespace chromeos
<commit_msg>Made feedback icon hidden on login screen.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/background_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
using views::WidgetGtk;
namespace chromeos {
BackgroundView::BackgroundView() : status_area_(NULL),
os_version_label_(NULL),
boot_times_label_(NULL),
did_paint_(false) {
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kWizardBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitStatusArea();
InitInfoLabels();
}
static void ResetXCursor() {
// TODO(sky): nuke this once new window manager is in place.
// This gets rid of the ugly X default cursor.
Display* display = x11_util::GetXDisplay();
Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
XID root_window = x11_util::GetX11RootWindow();
XSetWindowAttributes attr;
attr.cursor = cursor;
XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}
// static
views::Widget* BackgroundView::CreateWindowContainingView(
const gfx::Rect& bounds,
BackgroundView** view) {
ResetXCursor();
WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
window->Init(NULL, bounds);
*view = new BackgroundView();
window->SetContentsView(*view);
(*view)->UpdateWindowType();
// This keeps the window from flashing at startup.
GdkWindow* gdk_window = window->GetNativeView()->window;
gdk_window_set_back_pixmap(gdk_window, NULL, false);
return window;
}
void BackgroundView::SetStatusAreaVisible(bool visible) {
status_area_->SetVisible(visible);
}
void BackgroundView::Paint(gfx::Canvas* canvas) {
views::View::Paint(canvas);
if (!did_paint_) {
did_paint_ = true;
UpdateWindowType();
}
}
void BackgroundView::Layout() {
int corner_padding =
chromeos::BorderDefinition::kWizardBorder.padding +
chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
int kInfoLeftPadding = 60;
int kInfoBottomPadding = 40;
int kInfoBetweenLinesPadding = 4;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - corner_padding,
corner_padding,
status_area_size.width(),
status_area_size.height());
gfx::Size version_size = os_version_label_->GetPreferredSize();
os_version_label_->SetBounds(
kInfoLeftPadding,
height() -
((2 * version_size.height()) +
kInfoBottomPadding +
kInfoBetweenLinesPadding),
width() - 2 * kInfoLeftPadding,
version_size.height());
boot_times_label_->SetBounds(
kInfoLeftPadding,
height() - (version_size.height() + kInfoBottomPadding),
width() - 2 * corner_padding,
version_size.height());
}
void BackgroundView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
gfx::NativeWindow BackgroundView::GetNativeWindow() const {
return
GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}
bool BackgroundView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->clock_view() ||
button_view == status_area_->feedback_view() ||
button_view == status_area_->language_view() ||
button_view == status_area_->network_view()) {
return false;
}
return true;
}
void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
// TODO(avayvod): Add some dialog for options or remove them completely.
}
bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
if (button_view == status_area_->feedback_view())
return false;
return true;
}
bool BackgroundView::IsBrowserMode() const {
return false;
}
void BackgroundView::LocaleChanged() {
Layout();
SchedulePaint();
}
void BackgroundView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
status_area_->Update();
AddChildView(status_area_);
}
void BackgroundView::InitInfoLabels() {
const SkColor kVersionColor = 0xff8eb1f4;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
os_version_label_ = new views::Label();
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(os_version_label_);
boot_times_label_ = new views::Label();
boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
boot_times_label_->SetColor(kVersionColor);
boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(boot_times_label_);
if (CrosLibrary::Get()->EnsureLoaded()) {
version_loader_.GetVersion(
&version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
boot_times_loader_.GetBootTimes(
&boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
} else {
os_version_label_->SetText(
ASCIIToWide(CrosLibrary::Get()->load_error_string()));
}
}
void BackgroundView::UpdateWindowType() {
std::vector<int> params;
params.push_back(did_paint_ ? 1 : 0);
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_BACKGROUND,
¶ms);
}
void BackgroundView::OnVersion(
VersionLoader::Handle handle, std::string version) {
std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
version_text += ' ';
version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
version_text += ' ';
version_text += version;
os_version_label_->SetText(ASCIIToWide(version_text));
}
void BackgroundView::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
// TODO(davemoore) if we decide to keep these times visible we will need
// to localize the strings.
const char* kBootTimesNoChromeExec =
"Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Boot took %.2f seconds "
"(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome_exec > 0) {
boot_times_text =
StringPrintf(
kBootTimesChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.chrome_exec - boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.chrome_exec);
} else {
boot_times_text =
StringPrintf(
kBootTimesNoChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.pre_startup);
}
boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/i18n/rtl.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif
#include "chrome/browser/appcache/view_appcache_internals_job_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/shared_resources_data_source.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/net/view_http_cache_job_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/url_util.h"
#include "grit/platform_locale_settings.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"
// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
public:
explicit URLRequestChromeJob(URLRequest* request);
// URLRequestJob implementation.
virtual void Start();
virtual void Kill();
virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
virtual bool GetMimeType(std::string* mime_type) const;
// Called by ChromeURLDataManager to notify us that the data blob is ready
// for us.
void DataAvailable(RefCountedMemory* bytes);
void SetMimeType(const std::string& mime_type) {
mime_type_ = mime_type;
}
private:
virtual ~URLRequestChromeJob();
// Helper for Start(), to let us start asynchronously.
// (This pattern is shared by most URLRequestJob implementations.)
void StartAsync();
// Do the actual copy from data_ (the data we're serving) into |buf|.
// Separate from ReadRawData so we can handle async I/O.
void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);
// The actual data we're serving. NULL until it's been fetched.
scoped_refptr<RefCountedMemory> data_;
// The current offset into the data that we're handing off to our
// callers via the Read interfaces.
int data_offset_;
// For async reads, we keep around a pointer to the buffer that
// we're reading into.
scoped_refptr<net::IOBuffer> pending_buf_;
int pending_buf_size_;
std::string mime_type_;
DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
};
// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
public:
URLRequestChromeFileJob(URLRequest* request, const FilePath& path);
private:
virtual ~URLRequestChromeFileJob();
DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob);
};
void RegisterURLRequestChromeJob() {
FilePath inspector_dir;
if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
Singleton<ChromeURLDataManager>()->AddFileSource(
chrome::kChromeUIDevToolsHost, inspector_dir);
}
SharedResourcesDataSource::Register();
URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme,
&ChromeURLDataManager::Factory);
}
void UnregisterURLRequestChromeJob() {
FilePath inspector_dir;
if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
Singleton<ChromeURLDataManager>()->RemoveFileSource(
chrome::kChromeUIDevToolsHost);
}
}
// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
std::string* source_name,
std::string* path) {
DCHECK(url.SchemeIs(chrome::kChromeUIScheme));
if (!url.is_valid()) {
NOTREACHED();
return;
}
// Our input looks like: chrome://source_name/extra_bits?foo .
// So the url's "host" is our source, and everything after the host is
// the path.
source_name->assign(url.host());
const std::string& spec = url.possibly_invalid_spec();
const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
// + 1 to skip the slash at the beginning of the path.
int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1;
if (offset < static_cast<int>(spec.size()))
path->assign(spec.substr(offset));
}
// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
FilePath* file_path) {
// Parse the URL into a request for a source and path.
std::string source_name;
std::string relative_path;
// Remove Query and Ref from URL.
GURL stripped_url;
GURL::Replacements replacements;
replacements.ClearQuery();
replacements.ClearRef();
stripped_url = url.ReplaceComponents(replacements);
URLToRequest(stripped_url, &source_name, &relative_path);
FileSourceMap::const_iterator i(
Singleton<ChromeURLDataManager>()->file_sources_.find(source_name));
if (i == Singleton<ChromeURLDataManager>()->file_sources_.end())
return false;
*file_path = i->second.AppendASCII(relative_path);
return true;
}
ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }
ChromeURLDataManager::~ChromeURLDataManager() { }
void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
// TODO(jackson): A new data source with same name should not clobber the
// existing one.
data_sources_[source->source_name()] = source;
}
void ChromeURLDataManager::AddFileSource(const std::string& source_name,
const FilePath& file_path) {
DCHECK(file_sources_.count(source_name) == 0);
file_sources_[source_name] = file_path;
}
void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
DCHECK(file_sources_.count(source_name) == 1);
file_sources_.erase(source_name);
}
bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const {
for (PendingRequestMap::const_iterator i = pending_requests_.begin();
i != pending_requests_.end(); ++i) {
if (i->second == job)
return true;
}
return false;
}
bool ChromeURLDataManager::StartRequest(const GURL& url,
URLRequestChromeJob* job) {
// Parse the URL into a request for a source and path.
std::string source_name;
std::string path;
URLToRequest(url, &source_name, &path);
// Look up the data source for the request.
DataSourceMap::iterator i = data_sources_.find(source_name);
if (i == data_sources_.end())
return false;
DataSource* source = i->second;
// Save this request so we know where to send the data.
RequestID request_id = next_request_id_++;
pending_requests_.insert(std::make_pair(request_id, job));
// TODO(eroman): would be nicer if the mimetype were set at the same time
// as the data blob. For now do it here, since NotifyHeadersComplete() is
// going to get called once we return.
job->SetMimeType(source->GetMimeType(path));
ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>(
job->request()->context());
// Forward along the request to the data source.
MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path);
if (!target_message_loop) {
// The DataSource is agnostic to which thread StartDataRequest is called
// on for this path. Call directly into it from this thread, the IO
// thread.
source->StartDataRequest(path, context->is_off_the_record(), request_id);
} else {
// The DataSource wants StartDataRequest to be called on a specific thread,
// usually the UI thread, for this path.
target_message_loop->PostTask(FROM_HERE,
NewRunnableMethod(source, &DataSource::StartDataRequest,
path, context->is_off_the_record(), request_id));
}
return true;
}
void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
// Remove the request from our list of pending requests.
// If/when the source sends the data that was requested, the data will just
// be thrown away.
for (PendingRequestMap::iterator i = pending_requests_.begin();
i != pending_requests_.end(); ++i) {
if (i->second == job) {
pending_requests_.erase(i);
return;
}
}
}
void ChromeURLDataManager::DataAvailable(
RequestID request_id,
scoped_refptr<RefCountedMemory> bytes) {
// Forward this data on to the pending URLRequest, if it exists.
PendingRequestMap::iterator i = pending_requests_.find(request_id);
if (i != pending_requests_.end()) {
// We acquire a reference to the job so that it doesn't disappear under the
// feet of any method invoked here (we could trigger a callback).
scoped_refptr<URLRequestChromeJob> job = i->second;
pending_requests_.erase(i);
job->DataAvailable(bytes);
}
}
void ChromeURLDataManager::DataSource::SendResponse(
RequestID request_id,
RefCountedMemory* bytes) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(Singleton<ChromeURLDataManager>::get(),
&ChromeURLDataManager::DataAvailable,
request_id, scoped_refptr<RefCountedMemory>(bytes)));
}
MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath(
const std::string& path) const {
return message_loop_;
}
// static
void ChromeURLDataManager::DataSource::SetFontAndTextDirection(
DictionaryValue* localized_strings) {
localized_strings->SetString(L"fontfamily",
l10n_util::GetString(IDS_WEB_FONT_FAMILY));
int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
// Some fonts used for some languages changed a lot in terms of the font
// metric in Vista. So, we need to use different size before Vista.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
web_font_size_id = IDS_WEB_FONT_SIZE_XP;
#endif
localized_strings->SetString(L"fontsize",
l10n_util::GetString(web_font_size_id));
localized_strings->SetString(L"textdirection",
base::i18n::IsRTL() ? L"rtl" : L"ltr");
}
URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
const std::string& scheme) {
// Try first with a file handler
FilePath path;
if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
return new URLRequestChromeFileJob(request, path);
// Next check for chrome://view-http-cache/*, which uses its own job type.
if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
return ViewHttpCacheJobFactory::CreateJobForRequest(request);
// Next check for chrome://appcache-internals/, which uses its own job type.
if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url()))
return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request);
// Fall back to using a custom handler
return new URLRequestChromeJob(request);
}
URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
: URLRequestJob(request),
data_offset_(0),
pending_buf_size_(0) {
}
URLRequestChromeJob::~URLRequestChromeJob() {
CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this));
}
void URLRequestChromeJob::Start() {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestChromeJob::StartAsync));
}
void URLRequestChromeJob::Kill() {
Singleton<ChromeURLDataManager>()->RemoveRequest(this);
}
bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
*mime_type = mime_type_;
return !mime_type_.empty();
}
void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) {
if (bytes) {
// The request completed, and we have all the data.
// Clear any IO pending status.
SetStatus(URLRequestStatus());
data_ = bytes;
int bytes_read;
if (pending_buf_.get()) {
CHECK(pending_buf_->data());
CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
pending_buf_ = NULL;
NotifyReadComplete(bytes_read);
}
} else {
// The request failed.
NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED));
}
}
bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
int* bytes_read) {
if (!data_.get()) {
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
DCHECK(!pending_buf_.get());
CHECK(buf->data());
pending_buf_ = buf;
pending_buf_size_ = buf_size;
return false; // Tell the caller we're still waiting for data.
}
// Otherwise, the data is available.
CompleteRead(buf, buf_size, bytes_read);
return true;
}
void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
int* bytes_read) {
int remaining = static_cast<int>(data_->size()) - data_offset_;
if (buf_size > remaining)
buf_size = remaining;
if (buf_size > 0) {
memcpy(buf->data(), data_->front() + data_offset_, buf_size);
data_offset_ += buf_size;
}
*bytes_read = buf_size;
}
void URLRequestChromeJob::StartAsync() {
if (!request_)
return;
if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) {
NotifyHeadersComplete();
} else {
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
net::ERR_INVALID_URL));
}
}
URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
const FilePath& path)
: URLRequestFileJob(request, path) {
}
URLRequestChromeFileJob::~URLRequestChromeFileJob() { }
<commit_msg>Prevent hitting DCHECK when multiple slashes are specified in chrome://devtools///.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/i18n/rtl.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif
#include "chrome/browser/appcache/view_appcache_internals_job_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/shared_resources_data_source.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/net/view_http_cache_job_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/url_util.h"
#include "grit/platform_locale_settings.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"
// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
public:
explicit URLRequestChromeJob(URLRequest* request);
// URLRequestJob implementation.
virtual void Start();
virtual void Kill();
virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
virtual bool GetMimeType(std::string* mime_type) const;
// Called by ChromeURLDataManager to notify us that the data blob is ready
// for us.
void DataAvailable(RefCountedMemory* bytes);
void SetMimeType(const std::string& mime_type) {
mime_type_ = mime_type;
}
private:
virtual ~URLRequestChromeJob();
// Helper for Start(), to let us start asynchronously.
// (This pattern is shared by most URLRequestJob implementations.)
void StartAsync();
// Do the actual copy from data_ (the data we're serving) into |buf|.
// Separate from ReadRawData so we can handle async I/O.
void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);
// The actual data we're serving. NULL until it's been fetched.
scoped_refptr<RefCountedMemory> data_;
// The current offset into the data that we're handing off to our
// callers via the Read interfaces.
int data_offset_;
// For async reads, we keep around a pointer to the buffer that
// we're reading into.
scoped_refptr<net::IOBuffer> pending_buf_;
int pending_buf_size_;
std::string mime_type_;
DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
};
// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
public:
URLRequestChromeFileJob(URLRequest* request, const FilePath& path);
private:
virtual ~URLRequestChromeFileJob();
DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob);
};
void RegisterURLRequestChromeJob() {
FilePath inspector_dir;
if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
Singleton<ChromeURLDataManager>()->AddFileSource(
chrome::kChromeUIDevToolsHost, inspector_dir);
}
SharedResourcesDataSource::Register();
URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme,
&ChromeURLDataManager::Factory);
}
void UnregisterURLRequestChromeJob() {
FilePath inspector_dir;
if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
Singleton<ChromeURLDataManager>()->RemoveFileSource(
chrome::kChromeUIDevToolsHost);
}
}
// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
std::string* source_name,
std::string* path) {
DCHECK(url.SchemeIs(chrome::kChromeUIScheme));
if (!url.is_valid()) {
NOTREACHED();
return;
}
// Our input looks like: chrome://source_name/extra_bits?foo .
// So the url's "host" is our source, and everything after the host is
// the path.
source_name->assign(url.host());
const std::string& spec = url.possibly_invalid_spec();
const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
// + 1 to skip the slash at the beginning of the path.
int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1;
if (offset < static_cast<int>(spec.size()))
path->assign(spec.substr(offset));
}
// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
FilePath* file_path) {
// Parse the URL into a request for a source and path.
std::string source_name;
std::string relative_path;
// Remove Query and Ref from URL.
GURL stripped_url;
GURL::Replacements replacements;
replacements.ClearQuery();
replacements.ClearRef();
stripped_url = url.ReplaceComponents(replacements);
URLToRequest(stripped_url, &source_name, &relative_path);
FileSourceMap::const_iterator i(
Singleton<ChromeURLDataManager>()->file_sources_.find(source_name));
if (i == Singleton<ChromeURLDataManager>()->file_sources_.end())
return false;
// Check that |relative_path| is not an absolute path (otherwise AppendASCII()
// will DCHECK). The awkward use of StringType is because on some systems
// FilePath expects a std::string, but on others a std::wstring.
FilePath p(FilePath::StringType(relative_path.begin(), relative_path.end()));
if (p.IsAbsolute())
return false;
*file_path = i->second.AppendASCII(relative_path);
return true;
}
ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }
ChromeURLDataManager::~ChromeURLDataManager() { }
void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
// TODO(jackson): A new data source with same name should not clobber the
// existing one.
data_sources_[source->source_name()] = source;
}
void ChromeURLDataManager::AddFileSource(const std::string& source_name,
const FilePath& file_path) {
DCHECK(file_sources_.count(source_name) == 0);
file_sources_[source_name] = file_path;
}
void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
DCHECK(file_sources_.count(source_name) == 1);
file_sources_.erase(source_name);
}
bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const {
for (PendingRequestMap::const_iterator i = pending_requests_.begin();
i != pending_requests_.end(); ++i) {
if (i->second == job)
return true;
}
return false;
}
bool ChromeURLDataManager::StartRequest(const GURL& url,
URLRequestChromeJob* job) {
// Parse the URL into a request for a source and path.
std::string source_name;
std::string path;
URLToRequest(url, &source_name, &path);
// Look up the data source for the request.
DataSourceMap::iterator i = data_sources_.find(source_name);
if (i == data_sources_.end())
return false;
DataSource* source = i->second;
// Save this request so we know where to send the data.
RequestID request_id = next_request_id_++;
pending_requests_.insert(std::make_pair(request_id, job));
// TODO(eroman): would be nicer if the mimetype were set at the same time
// as the data blob. For now do it here, since NotifyHeadersComplete() is
// going to get called once we return.
job->SetMimeType(source->GetMimeType(path));
ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>(
job->request()->context());
// Forward along the request to the data source.
MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path);
if (!target_message_loop) {
// The DataSource is agnostic to which thread StartDataRequest is called
// on for this path. Call directly into it from this thread, the IO
// thread.
source->StartDataRequest(path, context->is_off_the_record(), request_id);
} else {
// The DataSource wants StartDataRequest to be called on a specific thread,
// usually the UI thread, for this path.
target_message_loop->PostTask(FROM_HERE,
NewRunnableMethod(source, &DataSource::StartDataRequest,
path, context->is_off_the_record(), request_id));
}
return true;
}
void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
// Remove the request from our list of pending requests.
// If/when the source sends the data that was requested, the data will just
// be thrown away.
for (PendingRequestMap::iterator i = pending_requests_.begin();
i != pending_requests_.end(); ++i) {
if (i->second == job) {
pending_requests_.erase(i);
return;
}
}
}
void ChromeURLDataManager::DataAvailable(
RequestID request_id,
scoped_refptr<RefCountedMemory> bytes) {
// Forward this data on to the pending URLRequest, if it exists.
PendingRequestMap::iterator i = pending_requests_.find(request_id);
if (i != pending_requests_.end()) {
// We acquire a reference to the job so that it doesn't disappear under the
// feet of any method invoked here (we could trigger a callback).
scoped_refptr<URLRequestChromeJob> job = i->second;
pending_requests_.erase(i);
job->DataAvailable(bytes);
}
}
void ChromeURLDataManager::DataSource::SendResponse(
RequestID request_id,
RefCountedMemory* bytes) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(Singleton<ChromeURLDataManager>::get(),
&ChromeURLDataManager::DataAvailable,
request_id, scoped_refptr<RefCountedMemory>(bytes)));
}
MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath(
const std::string& path) const {
return message_loop_;
}
// static
void ChromeURLDataManager::DataSource::SetFontAndTextDirection(
DictionaryValue* localized_strings) {
localized_strings->SetString(L"fontfamily",
l10n_util::GetString(IDS_WEB_FONT_FAMILY));
int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
// Some fonts used for some languages changed a lot in terms of the font
// metric in Vista. So, we need to use different size before Vista.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
web_font_size_id = IDS_WEB_FONT_SIZE_XP;
#endif
localized_strings->SetString(L"fontsize",
l10n_util::GetString(web_font_size_id));
localized_strings->SetString(L"textdirection",
base::i18n::IsRTL() ? L"rtl" : L"ltr");
}
URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
const std::string& scheme) {
// Try first with a file handler
FilePath path;
if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
return new URLRequestChromeFileJob(request, path);
// Next check for chrome://view-http-cache/*, which uses its own job type.
if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
return ViewHttpCacheJobFactory::CreateJobForRequest(request);
// Next check for chrome://appcache-internals/, which uses its own job type.
if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url()))
return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request);
// Fall back to using a custom handler
return new URLRequestChromeJob(request);
}
URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
: URLRequestJob(request),
data_offset_(0),
pending_buf_size_(0) {
}
URLRequestChromeJob::~URLRequestChromeJob() {
CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this));
}
void URLRequestChromeJob::Start() {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestChromeJob::StartAsync));
}
void URLRequestChromeJob::Kill() {
Singleton<ChromeURLDataManager>()->RemoveRequest(this);
}
bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
*mime_type = mime_type_;
return !mime_type_.empty();
}
void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) {
if (bytes) {
// The request completed, and we have all the data.
// Clear any IO pending status.
SetStatus(URLRequestStatus());
data_ = bytes;
int bytes_read;
if (pending_buf_.get()) {
CHECK(pending_buf_->data());
CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
pending_buf_ = NULL;
NotifyReadComplete(bytes_read);
}
} else {
// The request failed.
NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED));
}
}
bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
int* bytes_read) {
if (!data_.get()) {
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
DCHECK(!pending_buf_.get());
CHECK(buf->data());
pending_buf_ = buf;
pending_buf_size_ = buf_size;
return false; // Tell the caller we're still waiting for data.
}
// Otherwise, the data is available.
CompleteRead(buf, buf_size, bytes_read);
return true;
}
void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
int* bytes_read) {
int remaining = static_cast<int>(data_->size()) - data_offset_;
if (buf_size > remaining)
buf_size = remaining;
if (buf_size > 0) {
memcpy(buf->data(), data_->front() + data_offset_, buf_size);
data_offset_ += buf_size;
}
*bytes_read = buf_size;
}
void URLRequestChromeJob::StartAsync() {
if (!request_)
return;
if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) {
NotifyHeadersComplete();
} else {
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
net::ERR_INVALID_URL));
}
}
URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
const FilePath& path)
: URLRequestFileJob(request, path) {
}
URLRequestChromeFileJob::~URLRequestChromeFileJob() { }
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MediaPlayerBrowserTest : public InProcessBrowserTest {
public:
MediaPlayerBrowserTest() {}
GURL GetMusicTestURL() {
return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
}
bool IsPlayerVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost) {
return true;
}
}
}
return false;
}
bool IsPlaylistVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost &&
url.ref() == "playlist") {
return true;
}
}
}
return false;
}
};
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
ASSERT_TRUE(StartHTTPServer());
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
// Check that its not currently visible
ASSERT_FALSE(IsPlayerVisible());
player->EnqueueMediaURL(GetMusicTestURL());
ASSERT_TRUE(IsPlayerVisible());
}
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
ASSERT_TRUE(StartHTTPServer());
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
player->EnqueueMediaURL(GetMusicTestURL());
EXPECT_FALSE(IsPlaylistVisible());
player->TogglePlaylistWindowVisible();
EXPECT_TRUE(IsPlaylistVisible());
}
} // namespace
<commit_msg>Revert 47363 - Fix build on ChromeOS by adding required return value checks.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MediaPlayerBrowserTest : public InProcessBrowserTest {
public:
MediaPlayerBrowserTest() {}
GURL GetMusicTestURL() {
return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
}
bool IsPlayerVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost) {
return true;
}
}
}
return false;
}
bool IsPlaylistVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost &&
url.ref() == "playlist") {
return true;
}
}
}
return false;
}
};
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
StartHTTPServer();
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
// Check that its not currently visible
ASSERT_FALSE(IsPlayerVisible());
player->EnqueueMediaURL(GetMusicTestURL());
ASSERT_TRUE(IsPlayerVisible());
}
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
StartHTTPServer();
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
player->EnqueueMediaURL(GetMusicTestURL());
EXPECT_FALSE(IsPlaylistVisible());
player->TogglePlaylistWindowVisible();
EXPECT_TRUE(IsPlaylistVisible());
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
class AdViewTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableAdview);
command_line->AppendSwitch(switches::kEnableAdviewSrcAttribute);
}
};
// This test checks the "loadcommit" event is called when the page inside an
// <adview> is loaded.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8.
#define MAYBE_LoadCommitEventIsCalled DISABLED_LoadCommitEventIsCalled
#else
#define MAYBE_LoadCommitEventIsCalled LoadCommitEventIsCalled
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_LoadCommitEventIsCalled) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/loadcommit_event")) << message_;
}
// This test checks the "loadabort" event is called when the "src" attribute
// of an <adview> is an invalid URL.
IN_PROC_BROWSER_TEST_F(AdViewTest, LoadAbortEventIsCalled) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/loadabort_event")) << message_;
}
// This test checks the page loaded inside an <adview> has the ability to
// 1) receive "message" events from the application, and 2) use
// "window.postMessage" to post back a message to the application.
#if defined(OS_WIN)
// Flaky, or takes too long time on Win7. (http://crbug.com/230271)
#define MAYBE_CommitMessageFromAdNetwork DISABLED_CommitMessageFromAdNetwork
#else
#define MAYBE_CommitMessageFromAdNetwork CommitMessageFromAdNetwork
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_CommitMessageFromAdNetwork) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/onloadcommit_ack")) << message_;
}
// This test checks the page running inside an <adview> has the ability to load
// and display an image inside an <iframe>.
// Note: Disabled for initial checkin because the test depends on a binary
// file (image035.png) which the trybots don't process correctly when
// first checked-in.
IN_PROC_BROWSER_TEST_F(AdViewTest, DISABLED_DisplayFirstAd) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/display_first_ad")) << message_;
}
// This test checks that <adview> attributes are also exposed as properties
// (with the same name and value).
IN_PROC_BROWSER_TEST_F(AdViewTest, PropertiesAreInSyncWithAttributes) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/properties_exposed")) << message_;
}
// This test checks an <adview> element has no behavior when the "adview"
// permission is missing from the application manifest.
IN_PROC_BROWSER_TEST_F(AdViewTest, AdViewPermissionIsRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/permission_required")) << message_;
}
// This test checks that 1) it is possible change the value of the "ad-network"
// attribute of an <adview> element and 2) changing the value will reset the
// "src" attribute.
IN_PROC_BROWSER_TEST_F(AdViewTest, ChangeAdNetworkValue) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/change_ad_network")) << message_;
}
class AdViewNoSrcTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableAdview);
//Note: The "kEnableAdviewSrcAttribute" flag is not here!
}
};
// This test checks an invalid "ad-network" value (i.e. not whitelisted)
// is ignored.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, InvalidAdNetworkIsIgnored) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/invalid_ad_network")) << message_;
}
// This test checks the "src" attribute is ignored when the
// "kEnableAdviewSrcAttribute" is missing.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, EnableAdviewSrcAttributeFlagRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/src_flag_required")) << message_;
}
// This test checks 1) an <adview> works end-to-end (i.e. page is loaded) when
// using a whitelisted ad-network, and 2) the "src" attribute is never exposed
// to the application.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, SrcNotExposed) {
base::FilePath file_path = test_data_dir_
.AppendASCII("platform_apps")
.AppendASCII("ad_view/src_not_exposed")
.AppendASCII("ad_network_fake_website.html");
// Note: The following URL is identical to the whitelisted url
// for "admob" (see ad_view.js).
GURL url = GURL("https://admob-sdk.doubleclick.net/chromeapps");
std::string scheme = url.scheme();
std::string hostname = url.host();
content::URLRequestPrepackagedInterceptor interceptor(scheme, hostname);
interceptor.SetResponse(url, file_path);
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/src_not_exposed")) << message_;
ASSERT_EQ(1, interceptor.GetHitCount());
}
class AdViewNotEnabledTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
//Note: The "kEnableAdview" flag is not here!
}
};
// This test checks an <adview> element has no behavior when the "kEnableAdview"
// flag is missing.
IN_PROC_BROWSER_TEST_F(AdViewNotEnabledTest, EnableAdviewFlagRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/flag_required")) << message_;
}
<commit_msg>Disable AdviewTest.ChangeAdNetworkValue browsertest (flaky on Mac10.8).<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
class AdViewTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableAdview);
command_line->AppendSwitch(switches::kEnableAdviewSrcAttribute);
}
};
// This test checks the "loadcommit" event is called when the page inside an
// <adview> is loaded.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8.
#define MAYBE_LoadCommitEventIsCalled DISABLED_LoadCommitEventIsCalled
#else
#define MAYBE_LoadCommitEventIsCalled LoadCommitEventIsCalled
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_LoadCommitEventIsCalled) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/loadcommit_event")) << message_;
}
// This test checks the "loadabort" event is called when the "src" attribute
// of an <adview> is an invalid URL.
IN_PROC_BROWSER_TEST_F(AdViewTest, LoadAbortEventIsCalled) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/loadabort_event")) << message_;
}
// This test checks the page loaded inside an <adview> has the ability to
// 1) receive "message" events from the application, and 2) use
// "window.postMessage" to post back a message to the application.
#if defined(OS_WIN)
// Flaky, or takes too long time on Win7. (http://crbug.com/230271)
#define MAYBE_CommitMessageFromAdNetwork DISABLED_CommitMessageFromAdNetwork
#else
#define MAYBE_CommitMessageFromAdNetwork CommitMessageFromAdNetwork
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_CommitMessageFromAdNetwork) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/onloadcommit_ack")) << message_;
}
// This test checks the page running inside an <adview> has the ability to load
// and display an image inside an <iframe>.
// Note: Disabled for initial checkin because the test depends on a binary
// file (image035.png) which the trybots don't process correctly when
// first checked-in.
IN_PROC_BROWSER_TEST_F(AdViewTest, DISABLED_DisplayFirstAd) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/display_first_ad")) << message_;
}
// This test checks that <adview> attributes are also exposed as properties
// (with the same name and value).
IN_PROC_BROWSER_TEST_F(AdViewTest, PropertiesAreInSyncWithAttributes) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/properties_exposed")) << message_;
}
// This test checks an <adview> element has no behavior when the "adview"
// permission is missing from the application manifest.
IN_PROC_BROWSER_TEST_F(AdViewTest, AdViewPermissionIsRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/permission_required")) << message_;
}
// This test checks that 1) it is possible change the value of the "ad-network"
// attribute of an <adview> element and 2) changing the value will reset the
// "src" attribute.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8 - crbug.com/253644.
#define MAYBE_ChangeAdNetworkValue DISABLED_ChangeAdNetworkValue
#else
#define MAYBE_ChangeAdNetworkValue ChangeAdNetworkValue
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, ChangeAdNetworkValue) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/change_ad_network")) << message_;
}
class AdViewNoSrcTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableAdview);
//Note: The "kEnableAdviewSrcAttribute" flag is not here!
}
};
// This test checks an invalid "ad-network" value (i.e. not whitelisted)
// is ignored.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, InvalidAdNetworkIsIgnored) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/invalid_ad_network")) << message_;
}
// This test checks the "src" attribute is ignored when the
// "kEnableAdviewSrcAttribute" is missing.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, EnableAdviewSrcAttributeFlagRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/src_flag_required")) << message_;
}
// This test checks 1) an <adview> works end-to-end (i.e. page is loaded) when
// using a whitelisted ad-network, and 2) the "src" attribute is never exposed
// to the application.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, SrcNotExposed) {
base::FilePath file_path = test_data_dir_
.AppendASCII("platform_apps")
.AppendASCII("ad_view/src_not_exposed")
.AppendASCII("ad_network_fake_website.html");
// Note: The following URL is identical to the whitelisted url
// for "admob" (see ad_view.js).
GURL url = GURL("https://admob-sdk.doubleclick.net/chromeapps");
std::string scheme = url.scheme();
std::string hostname = url.host();
content::URLRequestPrepackagedInterceptor interceptor(scheme, hostname);
interceptor.SetResponse(url, file_path);
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/src_not_exposed")) << message_;
ASSERT_EQ(1, interceptor.GetHitCount());
}
class AdViewNotEnabledTest : public extensions::PlatformAppBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
//Note: The "kEnableAdview" flag is not here!
}
};
// This test checks an <adview> element has no behavior when the "kEnableAdview"
// flag is missing.
IN_PROC_BROWSER_TEST_F(AdViewNotEnabledTest, EnableAdviewFlagRequired) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunPlatformAppTest(
"platform_apps/ad_view/flag_required")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
// TODO(gregoryd): run the NaCl test on all systems once
// http://code.google.com/p/chromium/issues/detail?id=51335 is fixed.
// Meanwhile we run it on Mac OSX only, since we can be sure that an x86-32 NaCl
// module will work there.
// Mark as Flaky. http://crbug.com/51861
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_NaClPermissionEnabled) {
ASSERT_TRUE(RunExtensionTest("permissions/nacl_enabled")) << message_;
}
#endif
<commit_msg>Copyright change to kick off new build.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
// TODO(gregoryd): run the NaCl test on all systems once
// http://code.google.com/p/chromium/issues/detail?id=51335 is fixed.
// Meanwhile we run it on Mac OSX only, since we can be sure that an x86-32 NaCl
// module will work there.
// Mark as Flaky. http://crbug.com/51861
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_NaClPermissionEnabled) {
ASSERT_TRUE(RunExtensionTest("permissions/nacl_enabled")) << message_;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/search_terms_data.h"
#include "chrome/browser/sync/glue/synced_window_delegate_android.h"
#include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
using content::NotificationService;
TabModel::TabModel(Profile* profile)
: profile_(profile),
synced_window_delegate_(
new browser_sync::SyncedWindowDelegateAndroid(this)),
toolbar_model_(new ToolbarModelImpl(this)) {
if (profile) {
// A normal Profile creates an OTR profile if it does not exist when
// GetOffTheRecordProfile() is called, so we guard it with
// HasOffTheRecordProfile(). An OTR profile returns itself when you call
// GetOffTheRecordProfile().
is_off_the_record_ = (profile->HasOffTheRecordProfile() &&
profile == profile->GetOffTheRecordProfile());
// A profile can be destroyed, for example in the case of closing all
// incognito tabs. We therefore must listen for when this happens, and
// remove our pointer to the profile accordingly.
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
content::Source<Profile>(profile_));
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
content::NotificationService::AllSources());
} else {
is_off_the_record_ = false;
}
}
TabModel::TabModel()
: profile_(NULL),
is_off_the_record_(false),
synced_window_delegate_(
new browser_sync::SyncedWindowDelegateAndroid(this)) {
}
TabModel::~TabModel() {
}
content::WebContents* TabModel::GetActiveWebContents() const {
if (GetTabCount() == 0 || GetActiveIndex() < 0 ||
GetActiveIndex() > GetTabCount())
return NULL;
return GetWebContentsAt(GetActiveIndex());
}
Profile* TabModel::GetProfile() const {
return profile_;
}
bool TabModel::IsOffTheRecord() const {
return is_off_the_record_;
}
browser_sync::SyncedWindowDelegate* TabModel::GetSyncedWindowDelegate() const {
return synced_window_delegate_.get();
}
SessionID::id_type TabModel::GetSessionId() const {
return session_id_.id();
}
void TabModel::BroadcastSessionRestoreComplete() {
if (profile_) {
NotificationService::current()->Notify(
chrome::NOTIFICATION_SESSION_RESTORE_COMPLETE,
content::Source<Profile>(profile_),
NotificationService::NoDetails());
} else {
// TODO(nyquist): Uncomment this once downstream Android uses new
// constructor that takes a Profile* argument. See crbug.com/159704.
// NOTREACHED();
}
}
ToolbarModel* TabModel::GetToolbarModel() {
return toolbar_model_.get();
}
ToolbarModel::SecurityLevel TabModel::GetSecurityLevelForCurrentTab() {
return toolbar_model_->GetSecurityLevel();
}
string16 TabModel::GetSearchTermsForCurrentTab() {
return toolbar_model_->GetText(true);
}
std::string TabModel::GetQueryExtractionParam() {
if (!profile_)
return std::string();
UIThreadSearchTermsData search_terms_data(profile_);
return search_terms_data.InstantExtendedEnabledParam();
}
string16 TabModel::GetCorpusNameForCurrentTab() {
return toolbar_model_->GetCorpusNameForMobile();
}
void TabModel::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_PROFILE_DESTROYED:
// Our profile just got destroyed, so we delete our pointer to it.
profile_ = NULL;
break;
case chrome::NOTIFICATION_PROFILE_CREATED:
// Our incognito tab model out lives the profile, so we need to recapture
// the pointer if ours was previously deleted.
// NOTIFICATION_PROFILE_DESTROYED is not sent for every destruction, so
// we overwrite the pointer regardless of whether it's NULL.
if (is_off_the_record_) {
Profile* profile = content::Source<Profile>(source).ptr();
if (profile && profile->IsOffTheRecord())
profile_ = profile;
}
break;
default:
NOTREACHED();
}
}
<commit_msg>Set toolbar model to support extraction of url like search terms<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/search_terms_data.h"
#include "chrome/browser/sync/glue/synced_window_delegate_android.h"
#include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
using content::NotificationService;
TabModel::TabModel(Profile* profile)
: profile_(profile),
synced_window_delegate_(
new browser_sync::SyncedWindowDelegateAndroid(this)),
toolbar_model_(new ToolbarModelImpl(this)) {
if (profile) {
// A normal Profile creates an OTR profile if it does not exist when
// GetOffTheRecordProfile() is called, so we guard it with
// HasOffTheRecordProfile(). An OTR profile returns itself when you call
// GetOffTheRecordProfile().
is_off_the_record_ = (profile->HasOffTheRecordProfile() &&
profile == profile->GetOffTheRecordProfile());
// A profile can be destroyed, for example in the case of closing all
// incognito tabs. We therefore must listen for when this happens, and
// remove our pointer to the profile accordingly.
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
content::Source<Profile>(profile_));
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
content::NotificationService::AllSources());
} else {
is_off_the_record_ = false;
}
toolbar_model_->SetSupportsExtractionOfURLLikeSearchTerms(true);
}
TabModel::TabModel()
: profile_(NULL),
is_off_the_record_(false),
synced_window_delegate_(
new browser_sync::SyncedWindowDelegateAndroid(this)) {
}
TabModel::~TabModel() {
}
content::WebContents* TabModel::GetActiveWebContents() const {
if (GetTabCount() == 0 || GetActiveIndex() < 0 ||
GetActiveIndex() > GetTabCount())
return NULL;
return GetWebContentsAt(GetActiveIndex());
}
Profile* TabModel::GetProfile() const {
return profile_;
}
bool TabModel::IsOffTheRecord() const {
return is_off_the_record_;
}
browser_sync::SyncedWindowDelegate* TabModel::GetSyncedWindowDelegate() const {
return synced_window_delegate_.get();
}
SessionID::id_type TabModel::GetSessionId() const {
return session_id_.id();
}
void TabModel::BroadcastSessionRestoreComplete() {
if (profile_) {
NotificationService::current()->Notify(
chrome::NOTIFICATION_SESSION_RESTORE_COMPLETE,
content::Source<Profile>(profile_),
NotificationService::NoDetails());
} else {
// TODO(nyquist): Uncomment this once downstream Android uses new
// constructor that takes a Profile* argument. See crbug.com/159704.
// NOTREACHED();
}
}
ToolbarModel* TabModel::GetToolbarModel() {
return toolbar_model_.get();
}
ToolbarModel::SecurityLevel TabModel::GetSecurityLevelForCurrentTab() {
return toolbar_model_->GetSecurityLevel();
}
string16 TabModel::GetSearchTermsForCurrentTab() {
return toolbar_model_->GetText(true);
}
std::string TabModel::GetQueryExtractionParam() {
if (!profile_)
return std::string();
UIThreadSearchTermsData search_terms_data(profile_);
return search_terms_data.InstantExtendedEnabledParam();
}
string16 TabModel::GetCorpusNameForCurrentTab() {
return toolbar_model_->GetCorpusNameForMobile();
}
void TabModel::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_PROFILE_DESTROYED:
// Our profile just got destroyed, so we delete our pointer to it.
profile_ = NULL;
break;
case chrome::NOTIFICATION_PROFILE_CREATED:
// Our incognito tab model out lives the profile, so we need to recapture
// the pointer if ours was previously deleted.
// NOTIFICATION_PROFILE_DESTROYED is not sent for every destruction, so
// we overwrite the pointer regardless of whether it's NULL.
if (is_off_the_record_) {
Profile* profile = content::Source<Profile>(source).ptr();
if (profile && profile->IsOffTheRecord())
profile_ = profile;
}
break;
default:
NOTREACHED();
}
}
<|endoftext|> |
<commit_before>#include "omp.h"
inline
kth_cv_svm::kth_cv_svm(const std::string in_path,
const std::string in_actionNames,
const field<std::string> in_all_people,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_dim
):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim)
{
actions.load( actionNames );
}
// Log-Euclidean Distance
inline
void
kth_cv_svm::logEucl()
{
//logEucl_distances();
logEucl_CV(); //cross validation;
}
inline
void
kth_cv_svm::logEucl_CV()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3
int n_dim = n_test;
int sc = 1; // = total scenes
fvec dist_vector;
float acc=0;
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_peo*n_actions);
real_labels.zeros(n_peo*n_actions);
est_labels.zeros(n_peo*n_actions);
int j =0;
for (int pe_ts=0; pe_ts<n_peo; ++pe_ts)
{
fmat training_data;
fvec lab;
training_data.zeros(n_dim,n_test);
lab.zeros(n_test);
int k=0;
for (int pe_tr=0; pe_tr<n_peo; ++pe_tr)
{
if(pe_tr!=pe_ts)
for (int act=0; act<n_actions; act++)
{
std::stringstream load_vec_dist;
load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ;
dist_vector.load( load_vec_dist.str() );
training_data.col(k) = dist_vector;
lab(k) = act;
++k;
}
}
//Training the model with OpenCV
cout << "Using SVM to classify " << all_people (pe_ts) << endl;
//cout << "Preparing data to train the data" << endl;
cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1);
float fl_labels[n_test] ;
for (uword m=0; m<n_test; ++m)
{
for (uword d=0; d<n_dim; ++d)
{
cvMatTraining.at<float>(m,d) = training_data(d,m);
//cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m);
}
fl_labels[m] = lab(m);
//cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl;
}
cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels );
//cout << "Setting parameters" << endl;
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::LINEAR;
//params.gamma = 1;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6);
//params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
// Train the SVM
//cout << "Training" << endl;
CvSVM SVM;
SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params);
// y luego si for act=0:total_act
//acc para este run
//ACC = [ACC acc];
for (int act_ts =0; act_ts<n_actions; ++act_ts)
{
vec test_dist;
std::stringstream load_vec_dist;
load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ;
test_dist.load( load_vec_dist.str() );
//cout << all_people (pe_ts) << "_" << actions(act_ts) << endl;
cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1);
for (uword d=0; d<n_dim; ++d)
{
cvMatTesting_onevideo.at<float>(0,d) = test_dist(d);
}
float response = SVM.predict(cvMatTesting_onevideo, true);
//cout << "response " << response << endl;
real_labels(j) = act_ts;
est_labels(j) = response;
test_video_list(j) = load_vec_dist.str();
j++;
if (response == act_ts) {
acc++;
}
}
///cambiar nombres
real_labels.save("svm_LogEucl_real_labels.dat", raw_ascii);
est_labels.save("svm_LogEucl_est_labels.dat", raw_ascii);
test_video_list.save("svm_LogEucl_test_video_list.dat", raw_ascii);
//getchar();
}
cout << "Performance: " << acc*100/(n_peo*n_actions) << " %" << endl;
}
///
inline
void
kth_cv_svm::logEucl_distances()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3
int k=0;
int sc = 1; // = total scenes
mat peo_act(n_test,2);
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
peo_act (k,0) = pe;
peo_act (k,1) = act;
k++;
}
}
std::stringstream load_sub_path;
load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
//omp_set_num_threads(8); //Use only 8 processors
#pragma omp parallel for
for (int n = 0; n< n_test; ++n)
{
int pe = peo_act (n,0);
int act = peo_act (n,1);
int tid=omp_get_thread_num();
vec dist_video_i;
#pragma omp critical
cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl;
std::stringstream load_cov;
load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//#pragma omp critical
//cout << load_cov_seg.str() << endl;
dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str());
//save dist_video_i person, action
std::stringstream save_vec_dist;
save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ;
#pragma omp critical
dist_video_i.save(save_vec_dist.str(), hdf5_binary);
}
}
inline
vec
kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov)
{
//wall_clock timer;
//timer.tic();
mat logMtest_cov;
logMtest_cov.load(load_cov);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//double dist;
double tmp_dist;
vec dist;
int num_dist = (n_peo-1)*n_actions;
dist.zeros(num_dist);
tmp_dist = datum::inf;
double est_lab;
int sc =1;
int k=0;
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_cov_tr;
load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
mat logMtrain_cov;
logMtrain_cov.load( load_cov_tr.str() );
tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro");
dist(k) = tmp_dist;
++k;
}
}
}
return dist;
}
<commit_msg>Test svm_LogEucl. Linear SVM<commit_after>#include "omp.h"
inline
kth_cv_svm::kth_cv_svm(const std::string in_path,
const std::string in_actionNames,
const field<std::string> in_all_people,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_dim
):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim)
{
actions.load( actionNames );
}
// Log-Euclidean Distance
inline
void
kth_cv_svm::logEucl()
{
//logEucl_distances();
logEucl_CV(); //cross validation;
}
inline
void
kth_cv_svm::logEucl_CV()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3
int n_dim = n_test;
int sc = 1; // = total scenes
fvec dist_vector;
float acc=0;
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_peo*n_actions);
real_labels.zeros(n_peo*n_actions);
est_labels.zeros(n_peo*n_actions);
int j =0;
for (int pe_ts=0; pe_ts<n_peo; ++pe_ts)
{
fmat training_data;
fvec lab;
training_data.zeros(n_dim,n_test);
lab.zeros(n_test);
int k=0;
for (int pe_tr=0; pe_tr<n_peo; ++pe_tr)
{
if(pe_tr!=pe_ts)
for (int act=0; act<n_actions; act++)
{
std::stringstream load_vec_dist;
load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ;
dist_vector.load( load_vec_dist.str() );
training_data.col(k) = dist_vector;
lab(k) = act;
++k;
}
}
//Training the model with OpenCV
cout << "Using SVM to classify " << all_people (pe_ts) << endl;
//cout << "Preparing data to train the data" << endl;
cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1);
float fl_labels[n_test] ;
for (uword m=0; m<n_test; ++m)
{
for (uword d=0; d<n_dim; ++d)
{
cvMatTraining.at<float>(m,d) = training_data(d,m);
//cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m);
}
fl_labels[m] = lab(m);
//cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl;
}
cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels );
//cout << "Setting parameters" << endl;
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::LINEAR;
//params.gamma = 1;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6);
//params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
// Train the SVM
//cout << "Training" << endl;
CvSVM SVM;
SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params);
// y luego si for act=0:total_act
//acc para este run
//ACC = [ACC acc];
for (int act_ts =0; act_ts<n_actions; ++act_ts)
{
vec test_dist;
std::stringstream load_vec_dist;
load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ;
test_dist.load( load_vec_dist.str() );
//cout << all_people (pe_ts) << "_" << actions(act_ts) << endl;
cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1);
for (uword d=0; d<n_dim; ++d)
{
cvMatTesting_onevideo.at<float>(0,d) = test_dist(d);
}
float response = SVM.predict(cvMatTesting_onevideo, true);
//cout << "response " << response << endl;
real_labels(j) = act_ts;
est_labels(j) = response;
test_video_list(j) = load_vec_dist.str();
j++;
if (response == act_ts) {
acc++;
}
}
///cambiar nombres
real_labels.save("./svm_results/svm_LogEucl_real_labels.dat", raw_ascii);
est_labels.save("./svm_results/svm_LogEucl_est_labels.dat", raw_ascii);
test_video_list.save("./svm_results/svm_LogEucl_test_video_list.dat", raw_ascii);
//getchar();
}
cout << "Performance: " << acc*100/(n_peo*n_actions) << " %" << endl;
}
///
inline
void
kth_cv_svm::logEucl_distances()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3
int k=0;
int sc = 1; // = total scenes
mat peo_act(n_test,2);
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
peo_act (k,0) = pe;
peo_act (k,1) = act;
k++;
}
}
std::stringstream load_sub_path;
load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
//omp_set_num_threads(8); //Use only 8 processors
#pragma omp parallel for
for (int n = 0; n< n_test; ++n)
{
int pe = peo_act (n,0);
int act = peo_act (n,1);
int tid=omp_get_thread_num();
vec dist_video_i;
#pragma omp critical
cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl;
std::stringstream load_cov;
load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//#pragma omp critical
//cout << load_cov_seg.str() << endl;
dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str());
//save dist_video_i person, action
std::stringstream save_vec_dist;
save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ;
#pragma omp critical
dist_video_i.save(save_vec_dist.str(), hdf5_binary);
}
}
inline
vec
kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov)
{
//wall_clock timer;
//timer.tic();
mat logMtest_cov;
logMtest_cov.load(load_cov);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//double dist;
double tmp_dist;
vec dist;
int num_dist = (n_peo-1)*n_actions;
dist.zeros(num_dist);
tmp_dist = datum::inf;
double est_lab;
int sc =1;
int k=0;
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_cov_tr;
load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
mat logMtrain_cov;
logMtrain_cov.load( load_cov_tr.str() );
tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro");
dist(k) = tmp_dist;
++k;
}
}
}
return dist;
}
<|endoftext|> |
<commit_before>// Jonathan Eastep, Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.
#include <iostream>
#include <assert.h>
#include <set>
#include <sys/syscall.h>
#include <unistd.h>
#include "pin.H"
#include "log.h"
#include "run_models.h"
#include "analysis.h"
#include "routine_replace.h"
// FIXME: This list could probably be trimmed down a lot.
#include "simulator.h"
#include "core_manager.h"
#include "core.h"
#include "syscall_model.h"
#include "thread_manager.h"
#include "config_file.hpp"
#include "handle_args.h"
config::ConfigFile *cfg;
INT32 usage()
{
cerr << "This tool implements a multicore simulator." << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
void routineCallback(RTN rtn, void *v)
{
string rtn_name = RTN_Name(rtn);
bool did_func_replace = replaceUserAPIFunction(rtn, rtn_name);
if (!did_func_replace)
replaceInstruction(rtn, rtn_name);
}
// syscall model wrappers
void SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
Core *core = Sim()->getCoreManager()->getCurrentCore();
if (core)
{
UInt8 syscall_number = (UInt8) PIN_GetSyscallNumber(ctxt, std);
SyscallMdl::syscall_args_t args;
args.arg0 = PIN_GetSyscallArgument(ctxt, std, 0);
args.arg1 = PIN_GetSyscallArgument(ctxt, std, 1);
args.arg2 = PIN_GetSyscallArgument(ctxt, std, 2);
args.arg3 = PIN_GetSyscallArgument(ctxt, std, 3);
args.arg4 = PIN_GetSyscallArgument(ctxt, std, 4);
args.arg5 = PIN_GetSyscallArgument(ctxt, std, 5);
UInt8 new_syscall = core->getSyscallMdl()->runEnter(syscall_number, args);
PIN_SetSyscallNumber(ctxt, std, new_syscall);
}
}
void SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
Core *core = Sim()->getCoreManager()->getCurrentCore();
if (core)
{
carbon_reg_t old_return =
#ifdef TARGET_IA32E
PIN_GetContextReg(ctxt, REG_RAX);
#else
PIN_GetContextReg(ctxt, REG_EAX);
#endif
carbon_reg_t syscall_return = core->getSyscallMdl()->runExit(old_return);
#ifdef TARGET_IA32E
PIN_SetContextReg(ctxt, REG_RAX, syscall_return);
#else
PIN_SetContextReg(ctxt, REG_EAX, syscall_return);
#endif
}
}
void ApplicationStart()
{
}
void ApplicationExit(int, void*)
{
LOG_PRINT("Application exit.");
Simulator::release();
delete cfg;
}
void SimSpawnThreadSpawner(CONTEXT *ctx, AFUNPTR fp_main)
{
// Get the function for the thread spawner
PIN_LockClient();
AFUNPTR thread_spawner;
IMG img = IMG_FindByAddress((ADDRINT)fp_main);
RTN rtn = RTN_FindByName(img, "CarbonSpawnThreadSpawner");
thread_spawner = RTN_Funptr(rtn);
PIN_UnlockClient();
// Get the address of the thread spawner
int res;
PIN_CallApplicationFunction(ctx,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
thread_spawner,
PIN_PARG(int), &res,
PIN_PARG_END());
}
int CarbonMain(CONTEXT *ctx, AFUNPTR fp_main, int argc, char *argv[])
{
ApplicationStart();
SimSpawnThreadSpawner(ctx, fp_main);
if (Config::getSingleton()->getCurrentProcessNum() == 0)
{
LOG_PRINT("Calling main()...");
Sim()->getCoreManager()->initializeThread(0);
// call main()
int res;
PIN_CallApplicationFunction(ctx,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
fp_main,
PIN_PARG(int), &res,
PIN_PARG(int), argc,
PIN_PARG(char**), argv,
PIN_PARG_END());
}
else
{
LOG_PRINT("Waiting for main process to finish...");
while (!Sim()->finished())
usleep(100);
LOG_PRINT("Finished!");
}
LOG_PRINT("Leaving CarbonMain...");
return 0;
}
int main(int argc, char *argv[])
{
// Global initialization
PIN_InitSymbols();
PIN_Init(argc,argv);
string_vec args;
// Set the default config path if it isn't
// overwritten on the command line.
std::string config_path = "carbon_sim.cfg";
parse_args(args, config_path, argc, argv);
cfg = new config::ConfigFile();
cfg->load(config_path);
handle_args(args, *cfg);
Simulator::setConfig(cfg);
Simulator::allocate();
Sim()->start();
// Instrumentation
LOG_PRINT("Start of instrumentation.");
RTN_AddInstrumentFunction(routineCallback, 0);
if(cfg->getBool("general/enable_syscall_modeling"))
{
PIN_AddSyscallEntryFunction(SyscallEntry, 0);
PIN_AddSyscallExitFunction(SyscallExit, 0);
}
PIN_AddFiniFunction(ApplicationExit, 0);
// Just in case ... might not be strictly necessary
Transport::getSingleton()->barrier();
// Never returns
LOG_PRINT("Running program...");
PIN_StartProgram();
return 0;
}
<commit_msg>[print] Printing out all the routines<commit_after>// Jonathan Eastep, Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.
#include <iostream>
#include <assert.h>
#include <set>
#include <sys/syscall.h>
#include <unistd.h>
#include "pin.H"
#include "log.h"
#include "run_models.h"
#include "analysis.h"
#include "routine_replace.h"
// FIXME: This list could probably be trimmed down a lot.
#include "simulator.h"
#include "core_manager.h"
#include "core.h"
#include "syscall_model.h"
#include "thread_manager.h"
#include "config_file.hpp"
#include "handle_args.h"
config::ConfigFile *cfg;
INT32 usage()
{
cerr << "This tool implements a multicore simulator." << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
void printRtnName(ADDRINT rtn_address)
{
// printf ("RTN: Name = %s, Address = 0x%x\n", RTN_FindNameByAddress(rtn_address).c_str(), rtn_address);
}
void routineCallback(RTN rtn, void *v)
{
RTN_Open(rtn);
string rtn_name = RTN_Name(rtn);
ADDRINT rtn_address = RTN_Address(rtn);
RTN_InsertCall(rtn, IPOINT_BEFORE,
AFUNPTR(printRtnName),
IARG_ADDRINT, rtn_address,
IARG_END);
replaceUserAPIFunction(rtn, rtn_name);
RTN_Close(rtn);
// bool did_func_replace = replaceUserAPIFunction(rtn, rtn_name);
// We dont need this for now
// if (!did_func_replace)
// replaceInstruction(rtn, rtn_name);
}
// syscall model wrappers
void SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
Core *core = Sim()->getCoreManager()->getCurrentCore();
if (core)
{
UInt8 syscall_number = (UInt8) PIN_GetSyscallNumber(ctxt, std);
SyscallMdl::syscall_args_t args;
args.arg0 = PIN_GetSyscallArgument(ctxt, std, 0);
args.arg1 = PIN_GetSyscallArgument(ctxt, std, 1);
args.arg2 = PIN_GetSyscallArgument(ctxt, std, 2);
args.arg3 = PIN_GetSyscallArgument(ctxt, std, 3);
args.arg4 = PIN_GetSyscallArgument(ctxt, std, 4);
args.arg5 = PIN_GetSyscallArgument(ctxt, std, 5);
UInt8 new_syscall = core->getSyscallMdl()->runEnter(syscall_number, args);
PIN_SetSyscallNumber(ctxt, std, new_syscall);
}
}
void SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
Core *core = Sim()->getCoreManager()->getCurrentCore();
if (core)
{
carbon_reg_t old_return =
#ifdef TARGET_IA32E
PIN_GetContextReg(ctxt, REG_RAX);
#else
PIN_GetContextReg(ctxt, REG_EAX);
#endif
carbon_reg_t syscall_return = core->getSyscallMdl()->runExit(old_return);
#ifdef TARGET_IA32E
PIN_SetContextReg(ctxt, REG_RAX, syscall_return);
#else
PIN_SetContextReg(ctxt, REG_EAX, syscall_return);
#endif
}
}
void ApplicationStart()
{
}
void ApplicationExit(int, void*)
{
LOG_PRINT("Application exit.");
Simulator::release();
delete cfg;
}
void SimSpawnThreadSpawner(CONTEXT *ctx, AFUNPTR fp_main)
{
// Get the function for the thread spawner
PIN_LockClient();
AFUNPTR thread_spawner;
IMG img = IMG_FindByAddress((ADDRINT)fp_main);
RTN rtn = RTN_FindByName(img, "CarbonSpawnThreadSpawner");
thread_spawner = RTN_Funptr(rtn);
PIN_UnlockClient();
// Get the address of the thread spawner
int res;
PIN_CallApplicationFunction(ctx,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
thread_spawner,
PIN_PARG(int), &res,
PIN_PARG_END());
}
int CarbonMain(CONTEXT *ctx, AFUNPTR fp_main, int argc, char *argv[])
{
ApplicationStart();
SimSpawnThreadSpawner(ctx, fp_main);
if (Config::getSingleton()->getCurrentProcessNum() == 0)
{
LOG_PRINT("Calling main()...");
Sim()->getCoreManager()->initializeThread(0);
// call main()
int res;
PIN_CallApplicationFunction(ctx,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
fp_main,
PIN_PARG(int), &res,
PIN_PARG(int), argc,
PIN_PARG(char**), argv,
PIN_PARG_END());
}
else
{
LOG_PRINT("Waiting for main process to finish...");
while (!Sim()->finished())
usleep(100);
LOG_PRINT("Finished!");
}
LOG_PRINT("Leaving CarbonMain...");
return 0;
}
int main(int argc, char *argv[])
{
// Global initialization
PIN_InitSymbols();
PIN_Init(argc,argv);
string_vec args;
// Set the default config path if it isn't
// overwritten on the command line.
std::string config_path = "carbon_sim.cfg";
parse_args(args, config_path, argc, argv);
cfg = new config::ConfigFile();
cfg->load(config_path);
handle_args(args, *cfg);
Simulator::setConfig(cfg);
Simulator::allocate();
Sim()->start();
// Instrumentation
LOG_PRINT("Start of instrumentation.");
RTN_AddInstrumentFunction(routineCallback, 0);
if(cfg->getBool("general/enable_syscall_modeling"))
{
PIN_AddSyscallEntryFunction(SyscallEntry, 0);
PIN_AddSyscallExitFunction(SyscallExit, 0);
}
PIN_AddFiniFunction(ApplicationExit, 0);
// Just in case ... might not be strictly necessary
Transport::getSingleton()->barrier();
// Never returns
LOG_PRINT("Running program...");
PIN_StartProgram();
return 0;
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/compute/kernels/sort_to_indices.h"
#include <algorithm>
#include <limits>
#include <numeric>
#include <vector>
#include "arrow/builder.h"
#include "arrow/compute/context.h"
#include "arrow/compute/expression.h"
#include "arrow/compute/logical_type.h"
#include "arrow/type_traits.h"
#include "arrow/visitor_inline.h"
namespace arrow {
class Array;
namespace compute {
/// \brief UnaryKernel implementing SortToIndices operation
class ARROW_EXPORT SortToIndicesKernel : public UnaryKernel {
protected:
std::shared_ptr<DataType> type_;
public:
/// \brief UnaryKernel interface
///
/// delegates to subclasses via SortToIndices()
Status Call(FunctionContext* ctx, const Datum& values, Datum* offsets) override = 0;
/// \brief output type of this kernel
std::shared_ptr<DataType> out_type() const override { return uint64(); }
/// \brief single-array implementation
virtual Status SortToIndices(FunctionContext* ctx, const std::shared_ptr<Array>& values,
std::shared_ptr<Array>* offsets) = 0;
/// \brief factory for SortToIndicesKernel
///
/// \param[in] value_type constructed SortToIndicesKernel will support sorting
/// values of this type
/// \param[out] out created kernel
static Status Make(const std::shared_ptr<DataType>& value_type,
std::unique_ptr<SortToIndicesKernel>* out);
};
template <typename ArrayType>
bool CompareValues(const ArrayType& array, uint64_t lhs, uint64_t rhs) {
return array.Value(lhs) < array.Value(rhs);
}
template <typename ArrayType>
bool CompareViews(const ArrayType& array, uint64_t lhs, uint64_t rhs) {
return array.GetView(lhs) < array.GetView(rhs);
}
template <typename ArrowType, typename Comparator>
class CompareSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
public:
explicit CompareSorter(Comparator compare) : compare_(compare) {}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
std::iota(indices_begin, indices_end, 0);
auto nulls_begin = indices_end;
if (values.null_count()) {
nulls_begin =
std::stable_partition(indices_begin, indices_end,
[&values](uint64_t ind) { return !values.IsNull(ind); });
}
std::stable_sort(indices_begin, nulls_begin,
[&values, this](uint64_t left, uint64_t right) {
return compare_(values, left, right);
});
}
private:
Comparator compare_;
};
template <typename ArrowType>
class CountSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
using c_type = typename ArrowType::c_type;
public:
CountSorter() = default;
explicit CountSorter(c_type min, c_type max) { SetMinMax(min, max); }
// Assume: max >= min && (max - min) < 4Gi
void SetMinMax(c_type min, c_type max) {
min_ = min;
value_range_ = static_cast<uint32_t>(max - min) + 1;
}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
// 32bit counter performs much better than 64bit one
if (values.length() < (1LL << 32)) {
SortInternal<uint32_t>(indices_begin, indices_end, values);
} else {
SortInternal<uint64_t>(indices_begin, indices_end, values);
}
}
private:
c_type min_{0};
uint32_t value_range_{0};
template <typename CounterType>
void SortInternal(int64_t* indices_begin, int64_t* indices_end,
const ArrayType& values) {
const uint32_t value_range = value_range_;
// first slot reserved for prefix sum, last slot for null value
std::vector<CounterType> counts(1 + value_range + 1);
struct UpdateCounts {
Status VisitNull() {
++counts[value_range];
return Status::OK();
}
Status VisitValue(c_type v) {
++counts[v - min];
return Status::OK();
}
CounterType* counts;
const uint32_t value_range;
c_type min;
};
{
UpdateCounts update_counts{&counts[1], value_range, min_};
ARROW_CHECK_OK(ArrayDataVisitor<ArrowType>().Visit(*values.data(), &update_counts));
}
for (uint32_t i = 1; i <= value_range; ++i) {
counts[i] += counts[i - 1];
}
struct OutputIndices {
Status VisitNull() {
out_indices[counts[value_range]++] = index++;
return Status::OK();
}
Status VisitValue(c_type v) {
out_indices[counts[v - min]++] = index++;
return Status::OK();
}
CounterType* counts;
const uint32_t value_range;
c_type min;
int64_t* out_indices;
int64_t index;
};
{
OutputIndices output_indices{&counts[0], value_range, min_, indices_begin, 0};
ARROW_CHECK_OK(
ArrayDataVisitor<ArrowType>().Visit(*values.data(), &output_indices));
}
}
};
// Sort integers with counting sort or comparison based sorting algorithm
// - Use O(n) counting sort if values are in a small range
// - Use O(nlogn) std::stable_sort otherwise
template <typename ArrowType, typename Comparator>
class CountOrCompareSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
using c_type = typename ArrowType::c_type;
public:
explicit CountOrCompareSorter(Comparator compare) : compare_sorter_(compare) {}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
if (values.length() >= countsort_min_len_ && values.length() > values.null_count()) {
struct MinMaxScanner {
Status VisitNull() { return Status::OK(); }
Status VisitValue(c_type v) {
min = std::min(min, v);
max = std::max(max, v);
return Status::OK();
}
c_type min{std::numeric_limits<c_type>::max()};
c_type max{std::numeric_limits<c_type>::min()};
};
ArrayDataVisitor<ArrowType> visitor;
MinMaxScanner minmax_scanner;
ARROW_CHECK_OK(visitor.Visit(*values.data(), &minmax_scanner));
// For signed int32/64, (max - min) may overflow and trigger UBSAN.
// Cast to largest unsigned type(uint64_t) before substraction.
const uint64_t min = static_cast<uint64_t>(minmax_scanner.min);
const uint64_t max = static_cast<uint64_t>(minmax_scanner.max);
if ((max - min) <= countsort_max_range_) {
count_sorter_.SetMinMax(minmax_scanner.min, minmax_scanner.max);
count_sorter_.Sort(indices_begin, indices_end, values);
return;
}
}
compare_sorter_.Sort(indices_begin, indices_end, values);
}
private:
CompareSorter<ArrowType, Comparator> compare_sorter_;
CountSorter<ArrowType> count_sorter_;
// Cross point to prefer counting sort than stl::stable_sort(merge sort)
// - array to be sorted is longer than "count_min_len_"
// - value range (max-min) is within "count_max_range_"
//
// The optimal setting depends heavily on running CPU. Below setting is
// conservative to adapt to various hardware and keep code simple.
// It's possible to decrease array-len and/or increase value-range to cover
// more cases, or setup a table for best array-len/value-range combinations.
// See https://issues.apache.org/jira/browse/ARROW-1571 for detailed analysis.
static const uint32_t countsort_min_len_ = 1024;
static const uint32_t countsort_max_range_ = 4096;
};
template <typename ArrowType, typename Sorter>
class SortToIndicesKernelImpl : public SortToIndicesKernel {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
public:
explicit SortToIndicesKernelImpl(Sorter sorter) : sorter_(sorter) {}
Status SortToIndices(FunctionContext* ctx, const std::shared_ptr<Array>& values,
std::shared_ptr<Array>* offsets) {
return SortToIndicesImpl(ctx, std::static_pointer_cast<ArrayType>(values), offsets);
}
Status Call(FunctionContext* ctx, const Datum& values, Datum* offsets) {
if (!values.is_array()) {
return Status::Invalid("SortToIndicesKernel expects array values");
}
auto values_array = values.make_array();
std::shared_ptr<Array> offsets_array;
RETURN_NOT_OK(this->SortToIndices(ctx, values_array, &offsets_array));
*offsets = offsets_array;
return Status::OK();
}
std::shared_ptr<DataType> out_type() const { return type_; }
private:
Sorter sorter_;
Status SortToIndicesImpl(FunctionContext* ctx, const std::shared_ptr<ArrayType>& values,
std::shared_ptr<Array>* offsets) {
std::shared_ptr<Buffer> indices_buf;
int64_t buf_size = values->length() * sizeof(uint64_t);
RETURN_NOT_OK(AllocateBuffer(ctx->memory_pool(), buf_size, &indices_buf));
int64_t* indices_begin = reinterpret_cast<int64_t*>(indices_buf->mutable_data());
int64_t* indices_end = indices_begin + values->length();
sorter_.Sort(indices_begin, indices_end, *values.get());
*offsets = std::make_shared<UInt64Array>(values->length(), indices_buf);
return Status::OK();
}
};
template <typename ArrowType, typename Comparator,
typename Sorter = CompareSorter<ArrowType, Comparator>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCompareKernel(Comparator comparator) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(comparator));
}
template <typename ArrowType, typename Sorter = CountSorter<ArrowType>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCountKernel(int min, int max) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(min, max));
}
template <typename ArrowType, typename Comparator,
typename Sorter = CountOrCompareSorter<ArrowType, Comparator>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCountOrCompareKernel(
Comparator comparator) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(comparator));
}
Status SortToIndicesKernel::Make(const std::shared_ptr<DataType>& value_type,
std::unique_ptr<SortToIndicesKernel>* out) {
SortToIndicesKernel* kernel;
switch (value_type->id()) {
case Type::UINT8:
kernel = MakeCountKernel<UInt8Type>(0, 255);
break;
case Type::INT8:
kernel = MakeCountKernel<Int8Type>(-128, 127);
break;
case Type::UINT16:
kernel = MakeCountOrCompareKernel<UInt16Type>(CompareValues<UInt16Array>);
break;
case Type::INT16:
kernel = MakeCountOrCompareKernel<Int16Type>(CompareValues<Int16Array>);
break;
case Type::UINT32:
kernel = MakeCountOrCompareKernel<UInt32Type>(CompareValues<UInt32Array>);
break;
case Type::INT32:
kernel = MakeCountOrCompareKernel<Int32Type>(CompareValues<Int32Array>);
break;
case Type::UINT64:
kernel = MakeCountOrCompareKernel<UInt64Type>(CompareValues<UInt64Array>);
break;
case Type::INT64:
kernel = MakeCountOrCompareKernel<Int64Type>(CompareValues<Int64Array>);
break;
case Type::FLOAT:
kernel = MakeCompareKernel<FloatType>(CompareValues<FloatArray>);
break;
case Type::DOUBLE:
kernel = MakeCompareKernel<DoubleType>(CompareValues<DoubleArray>);
break;
case Type::BINARY:
kernel = MakeCompareKernel<BinaryType>(CompareViews<BinaryArray>);
break;
case Type::STRING:
kernel = MakeCompareKernel<StringType>(CompareViews<StringArray>);
break;
default:
return Status::NotImplemented("Sorting of ", *value_type, " arrays");
}
out->reset(kernel);
return Status::OK();
}
Status SortToIndices(FunctionContext* ctx, const Datum& values, Datum* offsets) {
std::unique_ptr<SortToIndicesKernel> kernel;
RETURN_NOT_OK(SortToIndicesKernel::Make(values.type(), &kernel));
return kernel->Call(ctx, values, offsets);
}
Status SortToIndices(FunctionContext* ctx, const Array& values,
std::shared_ptr<Array>* offsets) {
Datum offsets_datum;
RETURN_NOT_OK(SortToIndices(ctx, Datum(values.data()), &offsets_datum));
*offsets = offsets_datum.make_array();
return Status::OK();
}
} // namespace compute
} // namespace arrow
<commit_msg>ARROW-7992: [C++] Fix MSVC warning (#6525)<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/compute/kernels/sort_to_indices.h"
#include <algorithm>
#include <limits>
#include <numeric>
#include <vector>
#include "arrow/builder.h"
#include "arrow/compute/context.h"
#include "arrow/compute/expression.h"
#include "arrow/compute/logical_type.h"
#include "arrow/type_traits.h"
#include "arrow/visitor_inline.h"
namespace arrow {
class Array;
namespace compute {
/// \brief UnaryKernel implementing SortToIndices operation
class ARROW_EXPORT SortToIndicesKernel : public UnaryKernel {
protected:
std::shared_ptr<DataType> type_;
public:
/// \brief UnaryKernel interface
///
/// delegates to subclasses via SortToIndices()
Status Call(FunctionContext* ctx, const Datum& values, Datum* offsets) override = 0;
/// \brief output type of this kernel
std::shared_ptr<DataType> out_type() const override { return uint64(); }
/// \brief single-array implementation
virtual Status SortToIndices(FunctionContext* ctx, const std::shared_ptr<Array>& values,
std::shared_ptr<Array>* offsets) = 0;
/// \brief factory for SortToIndicesKernel
///
/// \param[in] value_type constructed SortToIndicesKernel will support sorting
/// values of this type
/// \param[out] out created kernel
static Status Make(const std::shared_ptr<DataType>& value_type,
std::unique_ptr<SortToIndicesKernel>* out);
};
template <typename ArrayType>
bool CompareValues(const ArrayType& array, uint64_t lhs, uint64_t rhs) {
return array.Value(lhs) < array.Value(rhs);
}
template <typename ArrayType>
bool CompareViews(const ArrayType& array, uint64_t lhs, uint64_t rhs) {
return array.GetView(lhs) < array.GetView(rhs);
}
template <typename ArrowType, typename Comparator>
class CompareSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
public:
explicit CompareSorter(Comparator compare) : compare_(compare) {}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
std::iota(indices_begin, indices_end, 0);
auto nulls_begin = indices_end;
if (values.null_count()) {
nulls_begin =
std::stable_partition(indices_begin, indices_end,
[&values](uint64_t ind) { return !values.IsNull(ind); });
}
std::stable_sort(indices_begin, nulls_begin,
[&values, this](uint64_t left, uint64_t right) {
return compare_(values, left, right);
});
}
private:
Comparator compare_;
};
template <typename ArrowType>
class CountSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
using c_type = typename ArrowType::c_type;
public:
CountSorter() = default;
explicit CountSorter(c_type min, c_type max) { SetMinMax(min, max); }
// Assume: max >= min && (max - min) < 4Gi
void SetMinMax(c_type min, c_type max) {
min_ = min;
value_range_ = static_cast<uint32_t>(max - min) + 1;
}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
// 32bit counter performs much better than 64bit one
if (values.length() < (1LL << 32)) {
SortInternal<uint32_t>(indices_begin, indices_end, values);
} else {
SortInternal<uint64_t>(indices_begin, indices_end, values);
}
}
private:
c_type min_{0};
uint32_t value_range_{0};
template <typename CounterType>
void SortInternal(int64_t* indices_begin, int64_t* indices_end,
const ArrayType& values) {
const uint32_t value_range = value_range_;
// first slot reserved for prefix sum, last slot for null value
std::vector<CounterType> counts(1 + value_range + 1);
struct UpdateCounts {
Status VisitNull() {
++counts[value_range];
return Status::OK();
}
Status VisitValue(c_type v) {
++counts[v - min];
return Status::OK();
}
CounterType* counts;
const uint32_t value_range;
c_type min;
};
{
UpdateCounts update_counts{&counts[1], value_range, min_};
ARROW_CHECK_OK(ArrayDataVisitor<ArrowType>().Visit(*values.data(), &update_counts));
}
for (uint32_t i = 1; i <= value_range; ++i) {
counts[i] += counts[i - 1];
}
struct OutputIndices {
Status VisitNull() {
out_indices[counts[value_range]++] = index++;
return Status::OK();
}
Status VisitValue(c_type v) {
out_indices[counts[v - min]++] = index++;
return Status::OK();
}
CounterType* counts;
const uint32_t value_range;
c_type min;
int64_t* out_indices;
int64_t index;
};
{
OutputIndices output_indices{&counts[0], value_range, min_, indices_begin, 0};
ARROW_CHECK_OK(
ArrayDataVisitor<ArrowType>().Visit(*values.data(), &output_indices));
}
}
};
// Sort integers with counting sort or comparison based sorting algorithm
// - Use O(n) counting sort if values are in a small range
// - Use O(nlogn) std::stable_sort otherwise
template <typename ArrowType, typename Comparator>
class CountOrCompareSorter {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
using c_type = typename ArrowType::c_type;
public:
explicit CountOrCompareSorter(Comparator compare) : compare_sorter_(compare) {}
void Sort(int64_t* indices_begin, int64_t* indices_end, const ArrayType& values) {
if (values.length() >= countsort_min_len_ && values.length() > values.null_count()) {
struct MinMaxScanner {
Status VisitNull() { return Status::OK(); }
Status VisitValue(c_type v) {
min = std::min(min, v);
max = std::max(max, v);
return Status::OK();
}
c_type min{std::numeric_limits<c_type>::max()};
c_type max{std::numeric_limits<c_type>::min()};
};
MinMaxScanner minmax_scanner;
ARROW_CHECK_OK(
ArrayDataVisitor<ArrowType>().Visit(*values.data(), &minmax_scanner));
// For signed int32/64, (max - min) may overflow and trigger UBSAN.
// Cast to largest unsigned type(uint64_t) before substraction.
const uint64_t min = static_cast<uint64_t>(minmax_scanner.min);
const uint64_t max = static_cast<uint64_t>(minmax_scanner.max);
if ((max - min) <= countsort_max_range_) {
count_sorter_.SetMinMax(minmax_scanner.min, minmax_scanner.max);
count_sorter_.Sort(indices_begin, indices_end, values);
return;
}
}
compare_sorter_.Sort(indices_begin, indices_end, values);
}
private:
CompareSorter<ArrowType, Comparator> compare_sorter_;
CountSorter<ArrowType> count_sorter_;
// Cross point to prefer counting sort than stl::stable_sort(merge sort)
// - array to be sorted is longer than "count_min_len_"
// - value range (max-min) is within "count_max_range_"
//
// The optimal setting depends heavily on running CPU. Below setting is
// conservative to adapt to various hardware and keep code simple.
// It's possible to decrease array-len and/or increase value-range to cover
// more cases, or setup a table for best array-len/value-range combinations.
// See https://issues.apache.org/jira/browse/ARROW-1571 for detailed analysis.
static const uint32_t countsort_min_len_ = 1024;
static const uint32_t countsort_max_range_ = 4096;
};
template <typename ArrowType, typename Sorter>
class SortToIndicesKernelImpl : public SortToIndicesKernel {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
public:
explicit SortToIndicesKernelImpl(Sorter sorter) : sorter_(sorter) {}
Status SortToIndices(FunctionContext* ctx, const std::shared_ptr<Array>& values,
std::shared_ptr<Array>* offsets) {
return SortToIndicesImpl(ctx, std::static_pointer_cast<ArrayType>(values), offsets);
}
Status Call(FunctionContext* ctx, const Datum& values, Datum* offsets) {
if (!values.is_array()) {
return Status::Invalid("SortToIndicesKernel expects array values");
}
auto values_array = values.make_array();
std::shared_ptr<Array> offsets_array;
RETURN_NOT_OK(this->SortToIndices(ctx, values_array, &offsets_array));
*offsets = offsets_array;
return Status::OK();
}
std::shared_ptr<DataType> out_type() const { return type_; }
private:
Sorter sorter_;
Status SortToIndicesImpl(FunctionContext* ctx, const std::shared_ptr<ArrayType>& values,
std::shared_ptr<Array>* offsets) {
std::shared_ptr<Buffer> indices_buf;
int64_t buf_size = values->length() * sizeof(uint64_t);
RETURN_NOT_OK(AllocateBuffer(ctx->memory_pool(), buf_size, &indices_buf));
int64_t* indices_begin = reinterpret_cast<int64_t*>(indices_buf->mutable_data());
int64_t* indices_end = indices_begin + values->length();
sorter_.Sort(indices_begin, indices_end, *values.get());
*offsets = std::make_shared<UInt64Array>(values->length(), indices_buf);
return Status::OK();
}
};
template <typename ArrowType, typename Comparator,
typename Sorter = CompareSorter<ArrowType, Comparator>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCompareKernel(Comparator comparator) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(comparator));
}
template <typename ArrowType, typename Sorter = CountSorter<ArrowType>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCountKernel(int min, int max) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(min, max));
}
template <typename ArrowType, typename Comparator,
typename Sorter = CountOrCompareSorter<ArrowType, Comparator>>
SortToIndicesKernelImpl<ArrowType, Sorter>* MakeCountOrCompareKernel(
Comparator comparator) {
return new SortToIndicesKernelImpl<ArrowType, Sorter>(Sorter(comparator));
}
Status SortToIndicesKernel::Make(const std::shared_ptr<DataType>& value_type,
std::unique_ptr<SortToIndicesKernel>* out) {
SortToIndicesKernel* kernel;
switch (value_type->id()) {
case Type::UINT8:
kernel = MakeCountKernel<UInt8Type>(0, 255);
break;
case Type::INT8:
kernel = MakeCountKernel<Int8Type>(-128, 127);
break;
case Type::UINT16:
kernel = MakeCountOrCompareKernel<UInt16Type>(CompareValues<UInt16Array>);
break;
case Type::INT16:
kernel = MakeCountOrCompareKernel<Int16Type>(CompareValues<Int16Array>);
break;
case Type::UINT32:
kernel = MakeCountOrCompareKernel<UInt32Type>(CompareValues<UInt32Array>);
break;
case Type::INT32:
kernel = MakeCountOrCompareKernel<Int32Type>(CompareValues<Int32Array>);
break;
case Type::UINT64:
kernel = MakeCountOrCompareKernel<UInt64Type>(CompareValues<UInt64Array>);
break;
case Type::INT64:
kernel = MakeCountOrCompareKernel<Int64Type>(CompareValues<Int64Array>);
break;
case Type::FLOAT:
kernel = MakeCompareKernel<FloatType>(CompareValues<FloatArray>);
break;
case Type::DOUBLE:
kernel = MakeCompareKernel<DoubleType>(CompareValues<DoubleArray>);
break;
case Type::BINARY:
kernel = MakeCompareKernel<BinaryType>(CompareViews<BinaryArray>);
break;
case Type::STRING:
kernel = MakeCompareKernel<StringType>(CompareViews<StringArray>);
break;
default:
return Status::NotImplemented("Sorting of ", *value_type, " arrays");
}
out->reset(kernel);
return Status::OK();
}
Status SortToIndices(FunctionContext* ctx, const Datum& values, Datum* offsets) {
std::unique_ptr<SortToIndicesKernel> kernel;
RETURN_NOT_OK(SortToIndicesKernel::Make(values.type(), &kernel));
return kernel->Call(ctx, values, offsets);
}
Status SortToIndices(FunctionContext* ctx, const Array& values,
std::shared_ptr<Array>* offsets) {
Datum offsets_datum;
RETURN_NOT_OK(SortToIndices(ctx, Datum(values.data()), &offsets_datum));
*offsets = offsets_datum.make_array();
return Status::OK();
}
} // namespace compute
} // namespace arrow
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
// https://cp-algorithms.com/data_structures/segment_tree.html
const int maxn = 200000;
int tmax[4 * maxn];
int tadd[4 * maxn]; // tadd[i] applies to tmax[i], tadd[2*i+1] and tadd[2*i+2]
void push(int root) {
tmax[root] += tadd[root];
tadd[2 * root + 1] += tadd[root];
tadd[2 * root + 2] += tadd[root];
tadd[root] = 0;
}
int max(int from, int to, int root = 0, int left = 0, int right = maxn - 1) {
if (from > right || left > to)
return INT_MIN;
if (from <= left && right <= to) {
return tmax[root] + tadd[root];
}
push(root);
int mid = (left + right) / 2;
int res = std::max(max(from, to, 2 * root + 1, left, mid),
max(from, to, 2 * root + 2, mid + 1, right));
return res;
}
void add(int from, int to, int delta, int root = 0, int left = 0, int right = maxn - 1) {
if (from > right || left > to)
return;
if (from <= left && right <= to) {
tadd[root] += delta;
return;
}
push(root); // this push may be omitted for add, but is necessary for other operations such as set
int mid = (left + right) / 2;
add(from, to, delta, 2 * root + 1, left, mid);
add(from, to, delta, 2 * root + 2, mid + 1, right);
tmax[root] = std::max(tmax[2 * root + 1] + tadd[2 * root + 1], tmax[2 * root + 2] + tadd[2 * root + 2]);
}
// usage example
int main() {
add(0, 9, 1);
add(2, 4, 2);
add(3, 5, 3);
cout << (6 == max(0, 9)) << endl;
cout << (6 == tmax[0] + tadd[0]) << endl;
cout << (1 == max(0, 0)) << endl;
}
<commit_msg>update<commit_after>#include <bits/stdc++.h>
using namespace std;
// https://cp-algorithms.com/data_structures/segment_tree.html
const int maxn = 200000;
int tmax[4 * maxn];
int tadd[4 * maxn]; // tadd[i] applies to tmax[i], tadd[2*i+1] and tadd[2*i+2]
void push(int root) {
tmax[root] += tadd[root];
tadd[2 * root + 1] += tadd[root];
tadd[2 * root + 2] += tadd[root];
tadd[root] = 0;
}
int max(int from, int to, int root = 0, int left = 0, int right = maxn - 1) {
if (from > right || left > to)
return INT_MIN;
if (from <= left && right <= to) {
return tmax[root] + tadd[root];
}
push(root);
int mid = (left + right) / 2;
return std::max(max(from, to, 2 * root + 1, left, mid), max(from, to, 2 * root + 2, mid + 1, right));
}
void add(int from, int to, int delta, int root = 0, int left = 0, int right = maxn - 1) {
if (from > right || left > to)
return;
if (from <= left && right <= to) {
tadd[root] += delta;
return;
}
push(root); // this push may be omitted for add, but is necessary for other operations such as set
int mid = (left + right) / 2;
add(from, to, delta, 2 * root + 1, left, mid);
add(from, to, delta, 2 * root + 2, mid + 1, right);
tmax[root] = std::max(tmax[2 * root + 1] + tadd[2 * root + 1], tmax[2 * root + 2] + tadd[2 * root + 2]);
}
// usage example
int main() {
add(0, 9, 1);
add(2, 4, 2);
add(3, 5, 3);
cout << (6 == max(0, 9)) << endl;
cout << (6 == tmax[0] + tadd[0]) << endl;
cout << (1 == max(0, 0)) << endl;
}
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <chrono>
#include <cmath>
#include <cstdint>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/ClusterControllerSettings.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MutableMessage.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/TimePoint.h"
#include "libjoynrclustercontroller/mqtt/MosquittoConnection.h"
#include "tests/JoynrTest.h"
using namespace joynr;
class MosquittoConnectionTest : public ::testing::Test
{
public:
MosquittoConnectionTest() :
_settings("test-resources/MqttJoynrClusterControllerRuntimeTest.settings"),
_messagingSettings(_settings),
_ccSettings(_settings),
_brokerUrl(_messagingSettings.getBrokerUrl()),
_mqttKeepAliveTimeSeconds(_messagingSettings.getMqttKeepAliveTimeSeconds()),
_mqttReconnectDelayTimeSeconds(_messagingSettings.getMqttReconnectDelayTimeSeconds()),
_mqttReconnectMaxDelayTimeSeconds(_messagingSettings.getMqttReconnectMaxDelayTimeSeconds()),
_isMqttExponentialBackoffEnabled(_messagingSettings.getMqttExponentialBackoffEnabled())
{
}
~MosquittoConnectionTest() = default;
protected:
std::shared_ptr<ImmutableMessage> createMessage(const TimePoint& expiryDate,
const std::string& recipient,
const std::string& payload = "")
{
MutableMessage mutableMsg;
mutableMsg.setExpiryDate(expiryDate);
mutableMsg.setRecipient(recipient);
mutableMsg.setPayload(payload);
return mutableMsg.getImmutableMessage();
}
static std::string payloadAsString(std::shared_ptr<ImmutableMessage> message)
{
const smrf::ByteArrayView& byteArrayView = message->getUnencryptedBody();
return std::string(
reinterpret_cast<const char*>(byteArrayView.data()), byteArrayView.size());
}
std::shared_ptr<MosquittoConnection> createMosquittoConnection(
std::shared_ptr<joynr::Semaphore> readyToSendSemaphore,
const std::string clientId,
const std::string channelId
)
{
auto mosquittoConnection = std::make_shared<MosquittoConnection>(
_ccSettings,
_brokerUrl,
_mqttKeepAliveTimeSeconds,
_mqttReconnectDelayTimeSeconds,
_mqttReconnectMaxDelayTimeSeconds,
_isMqttExponentialBackoffEnabled,
clientId);
// register connection to channelId
mosquittoConnection->registerChannelId(channelId);
// connection is established and ready to send messages
mosquittoConnection->registerReadyToSendChangedCallback([readyToSendSemaphore](bool readyToSend) {
if (readyToSend) {
readyToSendSemaphore->notify();
}
});
return mosquittoConnection;
}
Settings _settings;
MessagingSettings _messagingSettings;
ClusterControllerSettings _ccSettings;
const BrokerUrl _brokerUrl;
std::chrono::seconds _mqttKeepAliveTimeSeconds;
const std::chrono::seconds _mqttReconnectDelayTimeSeconds, _mqttReconnectMaxDelayTimeSeconds;
const bool _isMqttExponentialBackoffEnabled;
private:
DISALLOW_COPY_AND_ASSIGN(MosquittoConnectionTest);
};
TEST_F(MosquittoConnectionTest, generalTest)
{
// These values remain persisted in the broker
// use different ones when you need to create other connections
const std::string clientId1("clientId1");
const std::string clientId2("clientId2");
const std::string channelId1("channelId1");
const std::string channelId2("channelId2");
// create two MosquittoConnections using different clientIds and channels,
// both connections connect to the same broker
auto readyToSendSemaphore1 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection1 = createMosquittoConnection(
readyToSendSemaphore1,
clientId1,
channelId1
);
mosquittoConnection1->registerReceiveCallback([](smrf::ByteVector&& msg) {
std::ignore = msg;
});
// after connection is established, subscription to channel based topic
// should be established automatically
mosquittoConnection1->start();
EXPECT_TRUE(readyToSendSemaphore1->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection1->isReadyToSend());
auto readyToSendSemaphore2 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection2 = createMosquittoConnection(
readyToSendSemaphore2,
clientId2,
channelId2
);
auto msgReceived2 = std::make_shared<joynr::Semaphore>(0);
const std::string recipient2 = "recipient2";
const std::string payload2 = "payload2";
mosquittoConnection2->registerReceiveCallback([recipient2, payload2, msgReceived2](smrf::ByteVector&& msg) {
auto immutableMessage = std::make_shared<ImmutableMessage>(msg);
EXPECT_EQ(immutableMessage->getRecipient(), recipient2);
EXPECT_EQ(MosquittoConnectionTest::payloadAsString(immutableMessage), payload2);
msgReceived2->notify();
});
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(10)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
// create a message and send it via mosquittoConnection1 to mosquittoConnection2
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure = nullptr;
const auto now = TimePoint::now();
auto immutableMessage = createMessage(now + 10000, recipient2, payload2);
std::chrono::milliseconds msgTtlMs = immutableMessage->getExpiryDate().relativeFromNow();
std::uint32_t msgTtlSec = static_cast<std::uint32_t>(std::ceil(msgTtlMs.count() / 1000.0));
const smrf::ByteVector& rawMessage = immutableMessage->getSerializedMessage();
const std::string topic = channelId2 + "/low";
const int qosLevel = mosquittoConnection1->getMqttQos();
mosquittoConnection1->publishMessage(topic,
qosLevel,
onFailure,
msgTtlSec,
rawMessage.size(),
rawMessage.data());
// check the message has been received on mosquittoConnection2
EXPECT_TRUE(msgReceived2->waitFor(std::chrono::seconds(10)));
// subscribe and unsubscribe to/from an additional topic
const std::string additionalTopic("additionalTopic");
mosquittoConnection1->subscribeToTopic(additionalTopic);
mosquittoConnection2->subscribeToTopic(additionalTopic);
std::this_thread::sleep_for(std::chrono::seconds(2));
mosquittoConnection1->unsubscribeFromTopic(additionalTopic);
mosquittoConnection2->unsubscribeFromTopic(additionalTopic);
std::this_thread::sleep_for(std::chrono::seconds(2));
// cleanup
mosquittoConnection1->stop();
mosquittoConnection2->stop();
}
<commit_msg>[C++] Unit tests for MQTT message expiry interval in MosquittoConnection<commit_after>/*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <chrono>
#include <cmath>
#include <ctime>
#include <cstdint>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/ClusterControllerSettings.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MutableMessage.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/TimePoint.h"
#include "libjoynrclustercontroller/mqtt/MosquittoConnection.h"
#include "tests/JoynrTest.h"
using namespace joynr;
class MosquittoConnectionTest : public ::testing::Test
{
public:
MosquittoConnectionTest() :
_settings("test-resources/MqttJoynrClusterControllerRuntimeTest.settings"),
_messagingSettings(_settings),
_ccSettings(_settings),
_brokerUrl(_messagingSettings.getBrokerUrl()),
_mqttKeepAliveTimeSeconds(_messagingSettings.getMqttKeepAliveTimeSeconds()),
_mqttReconnectDelayTimeSeconds(_messagingSettings.getMqttReconnectDelayTimeSeconds()),
_mqttReconnectMaxDelayTimeSeconds(_messagingSettings.getMqttReconnectMaxDelayTimeSeconds()),
_isMqttExponentialBackoffEnabled(_messagingSettings.getMqttExponentialBackoffEnabled())
{
}
~MosquittoConnectionTest() = default;
protected:
std::shared_ptr<ImmutableMessage> createMessage(const TimePoint& expiryDate,
const std::string& recipient,
const std::string& payload = "")
{
MutableMessage mutableMsg;
mutableMsg.setExpiryDate(expiryDate);
mutableMsg.setRecipient(recipient);
mutableMsg.setPayload(payload);
return mutableMsg.getImmutableMessage();
}
static std::string payloadAsString(std::shared_ptr<ImmutableMessage> message)
{
const smrf::ByteArrayView& byteArrayView = message->getUnencryptedBody();
return std::string(
reinterpret_cast<const char*>(byteArrayView.data()), byteArrayView.size());
}
std::shared_ptr<MosquittoConnection> createMosquittoConnection(
std::shared_ptr<joynr::Semaphore> readyToSendSemaphore,
const std::string clientId,
const std::string channelId
)
{
auto mosquittoConnection = std::make_shared<MosquittoConnection>(
_ccSettings,
_brokerUrl,
_mqttKeepAliveTimeSeconds,
_mqttReconnectDelayTimeSeconds,
_mqttReconnectMaxDelayTimeSeconds,
_isMqttExponentialBackoffEnabled,
clientId);
// register connection to channelId
mosquittoConnection->registerChannelId(channelId);
// connection is established and ready to send messages
mosquittoConnection->registerReadyToSendChangedCallback([readyToSendSemaphore](bool readyToSend) {
if (readyToSend) {
readyToSendSemaphore->notify();
}
});
return mosquittoConnection;
}
Settings _settings;
MessagingSettings _messagingSettings;
ClusterControllerSettings _ccSettings;
const BrokerUrl _brokerUrl;
std::chrono::seconds _mqttKeepAliveTimeSeconds;
const std::chrono::seconds _mqttReconnectDelayTimeSeconds, _mqttReconnectMaxDelayTimeSeconds;
const bool _isMqttExponentialBackoffEnabled;
private:
DISALLOW_COPY_AND_ASSIGN(MosquittoConnectionTest);
};
TEST_F(MosquittoConnectionTest, generalTest)
{
// These values remain persisted in the broker
// use different ones when you need to create other connections
std::srand(std::time(0));
std::string random = std::to_string(std::rand());
const std::string clientId1("clientId1-" + random);
const std::string clientId2("clientId2-" + random);
const std::string channelId1("channelId1-" + random);
const std::string channelId2("channelId2-" + random);
// create two MosquittoConnections using different clientIds and channels,
// both connections connect to the same broker
auto readyToSendSemaphore1 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection1 = createMosquittoConnection(
readyToSendSemaphore1,
clientId1,
channelId1
);
mosquittoConnection1->registerReceiveCallback([](smrf::ByteVector&& msg) {
std::ignore = msg;
FAIL() << "We do not expect to receive msgs on connection1";
});
// after connection is established, subscription to channel based topic
// should be established automatically
mosquittoConnection1->start();
EXPECT_TRUE(readyToSendSemaphore1->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection1->isReadyToSend());
auto readyToSendSemaphore2 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection2 = createMosquittoConnection(
readyToSendSemaphore2,
clientId2,
channelId2
);
auto msgReceived2 = std::make_shared<joynr::Semaphore>(0);
const std::string recipient2 = "recipient2";
const std::string payload2 = "payload2";
mosquittoConnection2->registerReceiveCallback([recipient2, payload2, msgReceived2](smrf::ByteVector&& msg) {
auto immutableMessage = std::make_shared<ImmutableMessage>(msg);
EXPECT_EQ(immutableMessage->getRecipient(), recipient2);
EXPECT_EQ(MosquittoConnectionTest::payloadAsString(immutableMessage), payload2);
msgReceived2->notify();
});
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(10)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
// create a message and send it via mosquittoConnection1 to mosquittoConnection2
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure = nullptr;
const auto now = TimePoint::now();
auto immutableMessage = createMessage(now + 10000, recipient2, payload2);
const std::uint32_t msgTtlSec = 60;
const smrf::ByteVector& rawMessage = immutableMessage->getSerializedMessage();
const std::string topic = channelId2 + "/low";
const int qosLevel = mosquittoConnection1->getMqttQos();
mosquittoConnection1->publishMessage(topic,
qosLevel,
onFailure,
msgTtlSec,
rawMessage.size(),
rawMessage.data());
// check the message has been received on mosquittoConnection2
EXPECT_TRUE(msgReceived2->waitFor(std::chrono::seconds(10)));
// subscribe and unsubscribe to/from an additional topic
const std::string additionalTopic("additionalTopic");
mosquittoConnection1->subscribeToTopic(additionalTopic);
mosquittoConnection2->subscribeToTopic(additionalTopic);
std::this_thread::sleep_for(std::chrono::seconds(2));
mosquittoConnection1->unsubscribeFromTopic(additionalTopic);
mosquittoConnection2->unsubscribeFromTopic(additionalTopic);
std::this_thread::sleep_for(std::chrono::seconds(2));
// cleanup
mosquittoConnection1->stop();
mosquittoConnection2->stop();
}
TEST_F(MosquittoConnectionTest, deliverMessageWithinItsExpiryIntervalAfterReconnect)
{
std::srand(std::time(0));
std::string random = std::to_string(std::rand());
const std::string clientId3("clientId3-" + random);
const std::string clientId4("clientId4-" + random);
const std::string channelId3("channelId3-" + random);
const std::string channelId4("channelId4-" + random);
// connection1
auto readyToSendSemaphore1 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection1 = createMosquittoConnection(
readyToSendSemaphore1,
clientId3,
channelId3
);
// we do not plan to receive msgs on connection1, but we have to
// set registerReceiveCallback.
mosquittoConnection1->registerReceiveCallback([](smrf::ByteVector&& msg) {
std::ignore = msg;
});
mosquittoConnection1->start();
EXPECT_TRUE(readyToSendSemaphore1->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection1->isReadyToSend());
// connection2
auto readyToSendSemaphore2 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection2 = createMosquittoConnection(
readyToSendSemaphore2,
clientId4,
channelId4
);
const std::string dummyRecipient = "dummyRecipient";
const std::string dummyPayload = "dummyPayload";
// check the message has been received on mosquittoConnection2
auto msgWithExpiryDateReceived = std::make_shared<joynr::Semaphore>(0);
mosquittoConnection2->registerReceiveCallback([dummyRecipient, dummyPayload, msgWithExpiryDateReceived](smrf::ByteVector&& msg) {
auto receivedImmutableMessage = std::make_shared<ImmutableMessage>(msg);
EXPECT_EQ(receivedImmutableMessage->getRecipient(), dummyRecipient);
EXPECT_EQ(MosquittoConnectionTest::payloadAsString(receivedImmutableMessage), dummyPayload);
msgWithExpiryDateReceived->notify();
});
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(10)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
mosquittoConnection2->stop();
// prepare a message and publish it via the broker to connection2 (while it is unavailable)
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure = nullptr;
const auto now = TimePoint::now();
const std::int64_t msgDurationMs = 6000; // 1M
auto immutableMessage = createMessage(now + msgDurationMs, dummyRecipient, dummyPayload);
std::chrono::milliseconds msgTtlMs = immutableMessage->getExpiryDate().relativeFromNow();
std::uint32_t msgTtlSec = static_cast<std::uint32_t>(std::ceil(msgTtlMs.count() / 1000.0));
const smrf::ByteVector& rawMessage = immutableMessage->getSerializedMessage();
const std::string topic = channelId4 + "/low";
const int qosLevel = mosquittoConnection1->getMqttQos();
mosquittoConnection1->publishMessage(topic,
qosLevel,
onFailure,
msgTtlSec,
rawMessage.size(),
rawMessage.data());
std::this_thread::sleep_for(std::chrono::seconds(2));
// The broker should keep the msg for 1M
// start connection2 before message expires at the broker
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
// message still not expired it will be received
EXPECT_TRUE(msgWithExpiryDateReceived->waitFor(std::chrono::seconds(5)));
// cleanup
mosquittoConnection1->stop();
mosquittoConnection2->stop();
}
TEST_F(MosquittoConnectionTest, noMessageDeliveryWhenExceedingItsExpiryIntervalAfterReconnect)
{
std::srand(std::time(0));
std::string random = std::to_string(std::rand());
const std::string clientId5("clientId5-" + random);
const std::string clientId6("clientId6-" + random);
const std::string channelId5("channelId5-" + random);
const std::string channelId6("channelId6-" + random);
// connection1
auto readyToSendSemaphore1 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection1 = createMosquittoConnection(
readyToSendSemaphore1,
clientId5,
channelId5
);
// we do not plan to receive msgs on connection1, but we have to
// set registerReceiveCallback.
mosquittoConnection1->registerReceiveCallback([](smrf::ByteVector&& msg) {
std::ignore = msg;
FAIL() << "We do not expect to receive msgs on connection1";
});
mosquittoConnection1->start();
EXPECT_TRUE(readyToSendSemaphore1->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection1->isReadyToSend());
// connection2
auto readyToSendSemaphore2 = std::make_shared<joynr::Semaphore>(0);
auto mosquittoConnection2 = createMosquittoConnection(
readyToSendSemaphore2,
clientId6,
channelId6
);
const std::string anotherDummyRecipient = "anotherDummyRecipient";
const std::string anotherDummyPayload = "anotherDummyPayload";
// check the message has been received on mosquittoConnection2
auto msgWithExpiryDateReceived = std::make_shared<joynr::Semaphore>(0);
mosquittoConnection2->registerReceiveCallback([anotherDummyRecipient, anotherDummyPayload, msgWithExpiryDateReceived](smrf::ByteVector&& msg) {
msgWithExpiryDateReceived->notify();
});
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(10)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
mosquittoConnection2->stop();
// prepare a message and publish it via the broker to connection2 (while it is unavailable)
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure = nullptr;
const auto now = TimePoint::now();
const std::int64_t msgDurationMs = 3000; // 3sec
auto immutableMessage = createMessage(now + msgDurationMs, anotherDummyRecipient, anotherDummyPayload);
std::chrono::milliseconds msgTtlMs = immutableMessage->getExpiryDate().relativeFromNow();
std::uint32_t msgTtlSec = static_cast<std::uint32_t>(std::ceil(msgTtlMs.count() / 1000.0));
const smrf::ByteVector& rawMessage = immutableMessage->getSerializedMessage();
const std::string topic = channelId6 + "/low";
const int qosLevel = mosquittoConnection1->getMqttQos();
mosquittoConnection1->publishMessage(topic,
qosLevel,
onFailure,
msgTtlSec,
rawMessage.size(),
rawMessage.data());
// The broker should keep the msg for 3sec
std::this_thread::sleep_for(std::chrono::seconds(4));
// start connection2 after message expired at the broker
mosquittoConnection2->start();
EXPECT_TRUE(readyToSendSemaphore2->waitFor(std::chrono::seconds(5)));
EXPECT_TRUE(mosquittoConnection2->isReadyToSend());
// message expired nothing will be received
EXPECT_FALSE(msgWithExpiryDateReceived->waitFor(std::chrono::seconds(3)));
// cleanup
mosquittoConnection1->stop();
mosquittoConnection2->stop();
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <windows.h>
#elif qPlatform_POSIX
#include <unistd.h>
#include <sys/mman.h>
#endif
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Exceptions.h"
#if qPlatform_Windows
#include "../../Execution/Platform/Windows/Exception.h"
#include "../../Execution/Platform/Windows/HRESULTErrorException.h"
#endif
#include "../../Debug/Trace.h"
#include "../../IO/FileAccessException.h"
#include "../../IO/FileBusyException.h"
#include "../../IO/FileFormatException.h"
#include "PathName.h"
#include "MemoryMappedFileReader.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
using namespace Stroika::Foundation::Memory;
#if qPlatform_Windows
using Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif
/*
********************************************************************************
***************************** MemoryMappedFileReader ***************************
********************************************************************************
*/
MemoryMappedFileReader::MemoryMappedFileReader (const String& fileName)
: fFileDataStart_ (nullptr)
, fFileDataEnd_ (nullptr)
#if qPlatform_Windows
, fFileHandle_ (INVALID_HANDLE_VALUE)
, fFileMapping_ (INVALID_HANDLE_VALUE)
#endif
{
#if qPlatform_POSIX
int fd = 3;///tmphack....
AssertNotImplemented (); // chcek results
size_t fileLength = 3;//size of file - compute
void* mmap(void*, size_t, int, int, int, __off_t)
fFileDataStart_ = reinterpret_cast<const Byte*> (::mmap (nullptr, fileLength, PROT_READ, MAP_PRIVATE, fd, 0));
fFileDataEnd_ = fFileDataStart_ + fileLength;
::close (fd);//http://linux.die.net/man/2/mmap says dont need to keep FD open while mmapped
#elif qPlatform_Windows
try {
// FILE_READ_DATA fails on WinME - generates ERROR_INVALID_PARAMETER - so use GENERIC_READ
fFileHandle_ = ::CreateFile (fileName.AsTString ().c_str (), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
ThrowIfFalseGetLastError (fFileHandle_ != INVALID_HANDLE_VALUE);
DWORD fileSize = ::GetFileSize (fFileHandle_, nullptr);
if (fileSize != 0) {
fFileMapping_ = ::CreateFileMapping (fFileHandle_, nullptr, PAGE_READONLY, 0, fileSize, 0);
ThrowIfFalseGetLastError (fFileMapping_ != nullptr);
fFileDataStart_ = reinterpret_cast<const Byte*> (::MapViewOfFile (fFileMapping_, FILE_MAP_READ, 0, 0, 0));
ThrowIfFalseGetLastError (fFileDataStart_ != nullptr);
fFileDataEnd_ = fFileDataStart_ + fileSize;
}
}
catch (...) {
if (fFileMapping_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileMapping_);
}
if (fFileHandle_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileHandle_);
}
Execution::DoReThrow ();
}
#else
AssertNotImplemented ();
#endif
}
MemoryMappedFileReader::~MemoryMappedFileReader ()
{
#if qPlatform_POSIX
int res = ::munmap (const_cast<Byte*> (fFileDataStart_), fFileDataEnd_ - fFileDataStart_);
// check result!
AssertNotImplemented ();
#elif qPlatform_Windows
if (fFileDataStart_ != nullptr) {
(void)::UnmapViewOfFile (fFileDataStart_);
}
if (fFileMapping_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileMapping_);
}
if (fFileHandle_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileHandle_);
}
#else
AssertNotImplemented ();
#endif
}<commit_msg>More POSIX MemoryMappedFileReader fixes (testable - but not yet tested)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <sys/types.h>
#include <fcntl.h>
#if qPlatform_Windows
#include <windows.h>
#elif qPlatform_POSIX
#include <unistd.h>
#include <sys/mman.h>
#endif
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Exceptions.h"
#if qPlatform_Windows
#include "../../Execution/Platform/Windows/Exception.h"
#include "../../Execution/Platform/Windows/HRESULTErrorException.h"
#endif
#include "../../Debug/Trace.h"
#include "../../IO/FileAccessException.h"
#include "../../IO/FileBusyException.h"
#include "../../IO/FileFormatException.h"
#include "FileSystem.h"
#include "PathName.h"
#include "MemoryMappedFileReader.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
using namespace Stroika::Foundation::Memory;
#if qPlatform_Windows
using Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif
/*
********************************************************************************
***************************** MemoryMappedFileReader ***************************
********************************************************************************
*/
MemoryMappedFileReader::MemoryMappedFileReader (const String& fileName)
: fFileDataStart_ (nullptr)
, fFileDataEnd_ (nullptr)
#if qPlatform_Windows
, fFileHandle_ (INVALID_HANDLE_VALUE)
, fFileMapping_ (INVALID_HANDLE_VALUE)
#endif
{
#if qPlatform_POSIX
int fd = -1;
Execution::ThrowErrNoIfNegative (fd = open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY));
size_t fileLength = IO::FileSystem::FileSystem::Default ().GetFileSize (fileName);//
//WRONG BUT NOT GROSSLY - @todo fix -- AssertNotImplemented (); // size of file - compute -- must check for overlflow and throw...
fFileDataStart_ = reinterpret_cast<const Byte*> (::mmap (nullptr, fileLength, PROT_READ, MAP_PRIVATE, fd, 0));
fFileDataEnd_ = fFileDataStart_ + fileLength;
::close (fd);//http://linux.die.net/man/2/mmap says dont need to keep FD open while mmapped
#elif qPlatform_Windows
try {
// FILE_READ_DATA fails on WinME - generates ERROR_INVALID_PARAMETER - so use GENERIC_READ
fFileHandle_ = ::CreateFile (fileName.AsTString ().c_str (), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
ThrowIfFalseGetLastError (fFileHandle_ != INVALID_HANDLE_VALUE);
DWORD fileSize = ::GetFileSize (fFileHandle_, nullptr);
if (fileSize != 0) {
fFileMapping_ = ::CreateFileMapping (fFileHandle_, nullptr, PAGE_READONLY, 0, fileSize, 0);
ThrowIfFalseGetLastError (fFileMapping_ != nullptr);
fFileDataStart_ = reinterpret_cast<const Byte*> (::MapViewOfFile (fFileMapping_, FILE_MAP_READ, 0, 0, 0));
ThrowIfFalseGetLastError (fFileDataStart_ != nullptr);
fFileDataEnd_ = fFileDataStart_ + fileSize;
}
}
catch (...) {
if (fFileMapping_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileMapping_);
}
if (fFileHandle_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileHandle_);
}
Execution::DoReThrow ();
}
#else
AssertNotImplemented ();
#endif
}
MemoryMappedFileReader::~MemoryMappedFileReader ()
{
#if qPlatform_POSIX
int res = ::munmap (const_cast<Byte*> (fFileDataStart_), fFileDataEnd_ - fFileDataStart_);
// check result!
AssertNotImplemented ();
#elif qPlatform_Windows
if (fFileDataStart_ != nullptr) {
(void)::UnmapViewOfFile (fFileDataStart_);
}
if (fFileMapping_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileMapping_);
}
if (fFileHandle_ != INVALID_HANDLE_VALUE) {
::CloseHandle (fFileHandle_);
}
#else
AssertNotImplemented ();
#endif
}
<|endoftext|> |
<commit_before>// Joint work by Rob Mill & J B Coe
#include <iostream>
#include <functional>
class A;
class B;
class C;
class AbstractVisitor
{
public:
virtual void Visit(A& a) = 0;
virtual void Visit(B& b) = 0;
virtual void Visit(C& c) = 0;
protected:
~AbstractVisitor() {}
};
class Visitable
{
public:
virtual void Accept(AbstractVisitor& v) = 0;
protected:
~Visitable() {}
};
class A : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class B : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class C : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
template <typename T, typename F, typename BaseInner, typename ArgsT>
class AddFunction
{
public:
class Inner : public BaseInner
{
public:
using BaseInner::Visit;
Inner(ArgsT&& args) : BaseInner(std::move(args.second)), m_f(std::move(args.first)) {}
void Visit(T& t) final override { m_f(t); }
private:
F m_f;
};
AddFunction(ArgsT&& args) : m_args(std::move(args)) {}
template <typename Tadd, typename Fadd>
AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>> on(Fadd&& f) &&
{
return AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>>(
std::make_pair(std::move(f), std::move(m_args)));
}
Inner end_visitor() && { return Inner(std::move(m_args)); }
ArgsT m_args;
};
template <typename TVisitorBase>
class EmptyVisitor
{
public:
class Inner : public TVisitorBase
{
public:
using TVisitorBase::Visit;
Inner(std::nullptr_t) {}
};
template <typename Tadd, typename Fadd>
AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, std::nullptr_t>> on(Fadd&& f) &&
{
return AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, std::nullptr_t>>(
std::make_pair(std::move(f), nullptr));
}
};
template <typename TVisitorBase>
EmptyVisitor<TVisitorBase> begin_visitor()
{
return EmptyVisitor<TVisitorBase>();
}
int main()
{
A a;
B b;
C c;
int iCounter = 0;
struct CVisitor : public AbstractVisitor
{
CVisitor(int& i) : iCounter_(i) {}
int& iCounter_;
void Visit(A& a) override final
{
std::cout << "I'm an A" << std::endl;
iCounter_ += 1;
}
void Visit(B& a) override final
{
std::cout << "I'm a B" << std::endl;
iCounter_ += 2;
}
void Visit(C& a) override final
{
std::cout << "I'm a C" << std::endl;
iCounter_ += 3;
}
} visitor(iCounter);
/*
auto visitor = begin_visitor<AbstractVisitor>()
.on<A>([&iCounter](A& a)
{
std::cout << "I'm an A" << std::endl;
iCounter += 1;
})
.on<B>([&iCounter](B& a)
{
std::cout << "I'm a B" << std::endl;
iCounter += 2;
})
.on<C>([&iCounter](C& c)
{
std::cout << "I'm a C" << std::endl;
iCounter += 3;
})
.end_visitor();
*/
a.Accept(visitor);
b.Accept(visitor);
c.Accept(visitor);
std::cout << "Count is " << iCounter << std::endl;
return 0;
}
<commit_msg>make_visitor works<commit_after>// Joint work by Rob Mill & J B Coe
#include <iostream>
#include <functional>
class A;
class B;
class C;
class AbstractVisitor
{
public:
virtual void Visit(A& a) = 0;
virtual void Visit(B& b) = 0;
virtual void Visit(C& c) = 0;
protected:
~AbstractVisitor() {}
};
class Visitable
{
public:
virtual void Accept(AbstractVisitor& v) = 0;
protected:
~Visitable() {}
};
class A : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class B : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class C : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
template <typename T, typename F, typename BaseInner, typename ArgsT>
class AddFunction
{
public:
class Inner : public BaseInner
{
public:
using BaseInner::Visit;
Inner(ArgsT&& args) : BaseInner(std::move(args.second)), m_f(std::move(args.first)) {}
void Visit(T& t) final override { m_f(t); }
private:
F m_f;
};
AddFunction(ArgsT&& args) : m_args(std::move(args)) {}
template <typename Tadd, typename Fadd>
AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>> on(Fadd&& f) &&
{
return AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>>(
std::make_pair(std::move(f), std::move(m_args)));
}
Inner end_visitor() && { return Inner(std::move(m_args)); }
ArgsT m_args;
};
template <typename TVisitorBase>
class EmptyVisitor
{
public:
class Inner : public TVisitorBase
{
public:
using TVisitorBase::Visit;
Inner(std::nullptr_t) {}
};
template <typename Tadd, typename Fadd>
AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, std::nullptr_t>> on(Fadd&& f) &&
{
return AddFunction<Tadd, Fadd, Inner, std::pair<Fadd, std::nullptr_t>>(
std::make_pair(std::move(f), nullptr));
}
};
template <typename TVisitorBase>
EmptyVisitor<TVisitorBase> begin_visitor()
{
return EmptyVisitor<TVisitorBase>();
}
int main()
{
A a;
B b;
C c;
int iCounter = 0;
#ifdef USE_CLASS
struct CVisitor : public AbstractVisitor
{
CVisitor(int& i) : iCounter_(i) {}
int& iCounter_;
void Visit(A& a) override final
{
std::cout << "I'm an A" << std::endl;
iCounter_ += 1;
}
void Visit(B& a) override final
{
std::cout << "I'm a B" << std::endl;
iCounter_ += 2;
}
void Visit(C& a) override final
{
std::cout << "I'm a C" << std::endl;
iCounter_ += 3;
}
} visitor(iCounter);
#else
auto visitor = begin_visitor<AbstractVisitor>()
.on<A>([&iCounter](A& a)
{
std::cout << "I'm an A" << std::endl;
iCounter += 1;
})
.on<B>([&iCounter](B& a)
{
std::cout << "I'm a B" << std::endl;
iCounter += 2;
})
.on<C>([&iCounter](C& c)
{
std::cout << "I'm a C" << std::endl;
iCounter += 3;
})
.end_visitor();
#endif
a.Accept(visitor);
b.Accept(visitor);
c.Accept(visitor);
std::cout << "Count is " << iCounter << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: atom.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pl $ $Date: 2000-11-15 11:38:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <unotools/atom.hxx>
using namespace utl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
#define NMSP_UTIL ::com::sun::star::util
AtomProvider::AtomProvider()
{
m_nAtoms = 1;
}
AtomProvider::~AtomProvider()
{
}
int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString );
if( it != m_aAtomMap.end() )
return it->second;
if( ! bCreate )
return INVALID_ATOM;
m_aAtomMap[ rString ] = m_nAtoms;
m_aStringMap[ m_nAtoms ] = rString;
m_nAtoms++;
return m_nAtoms-1;
}
void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
++it;
}
}
void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
if( it->second > atom )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
}
++it;
}
}
const ::rtl::OUString& AtomProvider::getString( int nAtom ) const
{
static ::rtl::OUString aEmpty;
::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom );
return it == m_aStringMap.end() ? aEmpty : it->second;
}
void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description )
{
m_aAtomMap[ description ] = atom;
m_aStringMap[ atom ] = description;
if( m_nAtoms <= atom )
m_nAtoms=atom+1;
}
sal_Bool AtomProvider::hasAtom( int atom ) const
{
return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False;
}
// -----------------------------------------------------------------------
MultiAtomProvider::MultiAtomProvider()
{
}
MultiAtomProvider::~MultiAtomProvider()
{
for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it )
delete it->second;
}
sal_Bool MultiAtomProvider::insertAtomClass( int atomClass )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return sal_False;
m_aAtomLists[ atomClass ] = new AtomProvider();
return sal_True;
}
int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getAtom( rString, bCreate );
if( bCreate )
{
AtomProvider* pNewClass;
m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider();
return pNewClass->getAtom( rString, bCreate );
}
return INVALID_ATOM;
}
int MultiAtomProvider::getLastAtom( int atomClass ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM;
}
void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getRecent( atom, atoms );
else
atoms.clear();
}
const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getString( atom );
static ::rtl::OUString aEmpty;
return aEmpty;
}
sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False;
}
void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getAll( atoms );
else
atoms.clear();
}
void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it == m_aAtomLists.end() )
m_aAtomLists[ atomClass ] = new AtomProvider();
m_aAtomLists[ atomClass ]->overrideAtom( atom, description );
}
// -----------------------------------------------------------------------
AtomServer::AtomServer()
{
}
AtomServer::~AtomServer()
{
}
sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
return m_aProvider.getAtom( atomClass, description, create );
}
Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() );
for( int i = 0; i < atomClasses.getLength(); i++ )
{
aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] );
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getClass( atomClass, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getRecent( atomClass, atom, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
int nStrings = 0, i;
for( i = 0; i < atoms.getLength(); i++ )
nStrings += atoms.getConstArray()[ i ].atoms.getLength();
Sequence< ::rtl::OUString > aRet( nStrings );
for( i = 0, nStrings = 0; i < atoms.getLength(); i++ )
{
const AtomClassRequest& rRequest = atoms.getConstArray()[i];
for( int n = 0; n < rRequest.atoms.getLength(); n++ )
aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] );
}
return aRet;
}
// -----------------------------------------------------------------------
AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) :
m_xServer( xServer )
{
}
AtomClient::~AtomClient()
{
}
int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate )
{
int nAtom = m_aProvider.getAtom( atomClass, description, sal_False );
if( nAtom == INVALID_ATOM && bCreate )
{
nAtom = m_xServer->getAtom( atomClass, description, bCreate );
if( nAtom != INVALID_ATOM )
m_aProvider.overrideAtom( atomClass, nAtom, description );
}
return nAtom;
}
const ::rtl::OUString& AtomClient::getString( int atomClass, int atom )
{
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
Sequence< NMSP_UTIL::AtomDescription > aSeq;
aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) );
const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray();
for( int i = 0; i < aSeq.getLength(); i++ )
m_aProvider.overrideAtom( atomClass,
pDescriptions[i].atom,
pDescriptions[i].description
);
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
// holes may occur by the above procedure!
Sequence< AtomClassRequest > aSeq( 1 );
aSeq.getArray()[0].atomClass = atomClass;
aSeq.getArray()[0].atoms.realloc( 1 );
aSeq.getArray()[0].atoms.getArray()[0] = atom;
Sequence< ::rtl::OUString > aRet = m_xServer->getAtomDescriptions( aSeq );
if( aRet.getLength() == 1 )
m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] );
}
}
return m_aProvider.getString( atomClass, atom );
}
void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses )
{
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate = m_xServer->getClasses( atomClasses );
for( int i = 0; i < atomClasses.getLength(); i++ )
{
int nClass = atomClasses.getConstArray()[i];
const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i];
const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray();
for( int n = 0; n < rClass.getLength(); n++, pDesc++ )
m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description );
}
}
<commit_msg>#89754# catch runtime exceptions<commit_after>/*************************************************************************
*
* $RCSfile: atom.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ssa $ $Date: 2001-07-18 11:57:44 $
*
* 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 <unotools/atom.hxx>
using namespace utl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
#define NMSP_UTIL ::com::sun::star::util
AtomProvider::AtomProvider()
{
m_nAtoms = 1;
}
AtomProvider::~AtomProvider()
{
}
int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString );
if( it != m_aAtomMap.end() )
return it->second;
if( ! bCreate )
return INVALID_ATOM;
m_aAtomMap[ rString ] = m_nAtoms;
m_aStringMap[ m_nAtoms ] = rString;
m_nAtoms++;
return m_nAtoms-1;
}
void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
++it;
}
}
void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
if( it->second > atom )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
}
++it;
}
}
const ::rtl::OUString& AtomProvider::getString( int nAtom ) const
{
static ::rtl::OUString aEmpty;
::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom );
return it == m_aStringMap.end() ? aEmpty : it->second;
}
void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description )
{
m_aAtomMap[ description ] = atom;
m_aStringMap[ atom ] = description;
if( m_nAtoms <= atom )
m_nAtoms=atom+1;
}
sal_Bool AtomProvider::hasAtom( int atom ) const
{
return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False;
}
// -----------------------------------------------------------------------
MultiAtomProvider::MultiAtomProvider()
{
}
MultiAtomProvider::~MultiAtomProvider()
{
for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it )
delete it->second;
}
sal_Bool MultiAtomProvider::insertAtomClass( int atomClass )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return sal_False;
m_aAtomLists[ atomClass ] = new AtomProvider();
return sal_True;
}
int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getAtom( rString, bCreate );
if( bCreate )
{
AtomProvider* pNewClass;
m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider();
return pNewClass->getAtom( rString, bCreate );
}
return INVALID_ATOM;
}
int MultiAtomProvider::getLastAtom( int atomClass ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM;
}
void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getRecent( atom, atoms );
else
atoms.clear();
}
const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getString( atom );
static ::rtl::OUString aEmpty;
return aEmpty;
}
sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False;
}
void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getAll( atoms );
else
atoms.clear();
}
void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it == m_aAtomLists.end() )
m_aAtomLists[ atomClass ] = new AtomProvider();
m_aAtomLists[ atomClass ]->overrideAtom( atom, description );
}
// -----------------------------------------------------------------------
AtomServer::AtomServer()
{
}
AtomServer::~AtomServer()
{
}
sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
return m_aProvider.getAtom( atomClass, description, create );
}
Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() );
for( int i = 0; i < atomClasses.getLength(); i++ )
{
aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] );
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getClass( atomClass, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getRecent( atomClass, atom, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms )
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
int nStrings = 0, i;
for( i = 0; i < atoms.getLength(); i++ )
nStrings += atoms.getConstArray()[ i ].atoms.getLength();
Sequence< ::rtl::OUString > aRet( nStrings );
for( i = 0, nStrings = 0; i < atoms.getLength(); i++ )
{
const AtomClassRequest& rRequest = atoms.getConstArray()[i];
for( int n = 0; n < rRequest.atoms.getLength(); n++ )
aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] );
}
return aRet;
}
// -----------------------------------------------------------------------
AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) :
m_xServer( xServer )
{
}
AtomClient::~AtomClient()
{
}
int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate )
{
int nAtom = m_aProvider.getAtom( atomClass, description, sal_False );
if( nAtom == INVALID_ATOM && bCreate )
{
try
{
nAtom = m_xServer->getAtom( atomClass, description, bCreate );
}
catch( RuntimeException& )
{
return INVALID_ATOM;
}
if( nAtom != INVALID_ATOM )
m_aProvider.overrideAtom( atomClass, nAtom, description );
}
return nAtom;
}
const ::rtl::OUString& AtomClient::getString( int atomClass, int atom )
{
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
Sequence< NMSP_UTIL::AtomDescription > aSeq;
try
{
aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) );
}
catch( RuntimeException& )
{
return ::rtl::OUString();
}
const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray();
for( int i = 0; i < aSeq.getLength(); i++ )
m_aProvider.overrideAtom( atomClass,
pDescriptions[i].atom,
pDescriptions[i].description
);
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
// holes may occur by the above procedure!
Sequence< AtomClassRequest > aSeq( 1 );
aSeq.getArray()[0].atomClass = atomClass;
aSeq.getArray()[0].atoms.realloc( 1 );
aSeq.getArray()[0].atoms.getArray()[0] = atom;
Sequence< ::rtl::OUString > aRet;
try
{
aRet = m_xServer->getAtomDescriptions( aSeq );
}
catch( RuntimeException& )
{
return ::rtl::OUString();
}
if( aRet.getLength() == 1 )
m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] );
}
}
return m_aProvider.getString( atomClass, atom );
}
void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses )
{
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate;
try
{
aUpdate = m_xServer->getClasses( atomClasses );
}
catch( RuntimeException& )
{
return;
}
for( int i = 0; i < atomClasses.getLength(); i++ )
{
int nClass = atomClasses.getConstArray()[i];
const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i];
const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray();
for( int n = 0; n < rClass.getLength(); n++, pDesc++ )
m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description );
}
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// \file
/// Tests for the LinearSolveAndInverse.cpp functions.
#include <windows.h>
#include <gtest/gtest.h>
#include "SurgSim/Math/LinearSolveAndInverse.h"
namespace SurgSim
{
namespace Math
{
class LinearSolveAndInverseTests : public ::testing::Test
{
private:
size_t size;
void initializeVector(Vector* v)
{
v->resize(size);
for (size_t row = 0; row < size; row++)
{
(*v)(row) = fmod(-4.1 * row * row + 3.46, 5.0);
}
}
void initializeDenseMatrix(Matrix* m)
{
m->resize(size, size);
for (size_t row = 0; row < size; row++)
{
for (size_t col = 0; col < size; col++)
{
(*m)(row, col) = fmod((10.3 * cos(static_cast<double>(row * col)) + 3.24), 10.0);
}
}
}
void initializeDiagonalMatrix(Matrix* m)
{
m->resize(size, size);
m->setZero();
for (size_t row = 0; row < size; row++)
{
(*m)(row, row) = fmod((10.3 * cos(static_cast<double>(row * row)) + 3.24), 10.0);
}
}
template <size_t BlockSize>
void initializeTriDiagonalBlockMatrix(Matrix* m, bool isSymmetric)
{
size_t numBlocks = size / BlockSize;
m->resize(size, size);
m->setZero();
for (size_t rowBlockId = 0; rowBlockId < numBlocks; rowBlockId++)
{
for (int colBlockId = static_cast<int>(rowBlockId) - 1;
colBlockId <= static_cast<int>(rowBlockId) + 1;
colBlockId++)
{
if (colBlockId < 0 || colBlockId >= static_cast<int>(numBlocks))
{
continue;
}
for (size_t rowInBlockId = 0; rowInBlockId < BlockSize; ++rowInBlockId)
{
for (size_t colInBlockId = 0; colInBlockId < BlockSize; ++colInBlockId)
{
size_t row = rowBlockId * BlockSize + rowInBlockId;
size_t col = colBlockId * BlockSize + colInBlockId;
(*m)(row, col) = fmod((10.3 * cos(static_cast<double>(row * col)) + 3.24), 10.0);
}
}
}
}
if (isSymmetric)
{
// Force symmetry (lower triangular is copied from the upper triangular)
for (size_t row = 0; row < size; ++row)
{
for (size_t col = row + 1; col < size; ++col)
{
(*m)(col, row) = (*m)(row, col);
}
}
}
}
void setupTest()
{
initializeVector(&b);
expectedInverse = matrix.inverse();
expectedX = expectedInverse * b;
}
public:
void setupDenseMatrixTest()
{
size = 18;
initializeDenseMatrix(&matrix);
setupTest();
}
void setupDiagonalMatrixTest()
{
size = 18;
initializeDiagonalMatrix(&matrix);
setupTest();
}
template <size_t BlockSize>
void setupTriDiagonalBlockMatrixTest(bool isSymmetric = false)
{
size = BlockSize * 6;
initializeTriDiagonalBlockMatrix<BlockSize>(&matrix, isSymmetric);
setupTest();
}
Matrix matrix;
Matrix inverseMatrix, expectedInverse;
Vector b;
Vector x, expectedX;
};
TEST_F(LinearSolveAndInverseTests, DenseMatrixTests)
{
setupDenseMatrixTest();
LinearSolveAndInverseDenseMatrix solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, DiagonalMatrixTests)
{
setupDiagonalMatrixTest();
LinearSolveAndInverseDiagonalMatrix solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize2Tests)
{
setupTriDiagonalBlockMatrixTest<2>();
LinearSolveAndInverseTriDiagonalBlockMatrix<2> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize3Tests)
{
setupTriDiagonalBlockMatrixTest<3>();
LinearSolveAndInverseTriDiagonalBlockMatrix<3> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize4Tests)
{
setupTriDiagonalBlockMatrixTest<4>();
LinearSolveAndInverseTriDiagonalBlockMatrix<4> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize5Tests)
{
setupTriDiagonalBlockMatrixTest<5>();
LinearSolveAndInverseTriDiagonalBlockMatrix<5> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize6Tests)
{
setupTriDiagonalBlockMatrixTest<6>();
LinearSolveAndInverseTriDiagonalBlockMatrix<6> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize2Tests)
{
setupTriDiagonalBlockMatrixTest<2>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<2> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize3Tests)
{
setupTriDiagonalBlockMatrixTest<3>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<3> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize4Tests)
{
setupTriDiagonalBlockMatrixTest<4>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<4> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize5Tests)
{
setupTriDiagonalBlockMatrixTest<5>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<5> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize6Tests)
{
setupTriDiagonalBlockMatrixTest<6>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<6> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
}; // namespace Math
}; // namespace SurgSim
<commit_msg>Clean up unnecessary #include <windows.h><commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// \file
/// Tests for the LinearSolveAndInverse.cpp functions.
#include <gtest/gtest.h>
#include "SurgSim/Math/LinearSolveAndInverse.h"
namespace SurgSim
{
namespace Math
{
class LinearSolveAndInverseTests : public ::testing::Test
{
private:
size_t size;
void initializeVector(Vector* v)
{
v->resize(size);
for (size_t row = 0; row < size; row++)
{
(*v)(row) = fmod(-4.1 * row * row + 3.46, 5.0);
}
}
void initializeDenseMatrix(Matrix* m)
{
m->resize(size, size);
for (size_t row = 0; row < size; row++)
{
for (size_t col = 0; col < size; col++)
{
(*m)(row, col) = fmod((10.3 * cos(static_cast<double>(row * col)) + 3.24), 10.0);
}
}
}
void initializeDiagonalMatrix(Matrix* m)
{
m->resize(size, size);
m->setZero();
for (size_t row = 0; row < size; row++)
{
(*m)(row, row) = fmod((10.3 * cos(static_cast<double>(row * row)) + 3.24), 10.0);
}
}
template <size_t BlockSize>
void initializeTriDiagonalBlockMatrix(Matrix* m, bool isSymmetric)
{
size_t numBlocks = size / BlockSize;
m->resize(size, size);
m->setZero();
for (size_t rowBlockId = 0; rowBlockId < numBlocks; rowBlockId++)
{
for (int colBlockId = static_cast<int>(rowBlockId) - 1;
colBlockId <= static_cast<int>(rowBlockId) + 1;
colBlockId++)
{
if (colBlockId < 0 || colBlockId >= static_cast<int>(numBlocks))
{
continue;
}
for (size_t rowInBlockId = 0; rowInBlockId < BlockSize; ++rowInBlockId)
{
for (size_t colInBlockId = 0; colInBlockId < BlockSize; ++colInBlockId)
{
size_t row = rowBlockId * BlockSize + rowInBlockId;
size_t col = colBlockId * BlockSize + colInBlockId;
(*m)(row, col) = fmod((10.3 * cos(static_cast<double>(row * col)) + 3.24), 10.0);
}
}
}
}
if (isSymmetric)
{
// Force symmetry (lower triangular is copied from the upper triangular)
for (size_t row = 0; row < size; ++row)
{
for (size_t col = row + 1; col < size; ++col)
{
(*m)(col, row) = (*m)(row, col);
}
}
}
}
void setupTest()
{
initializeVector(&b);
expectedInverse = matrix.inverse();
expectedX = expectedInverse * b;
}
public:
void setupDenseMatrixTest()
{
size = 18;
initializeDenseMatrix(&matrix);
setupTest();
}
void setupDiagonalMatrixTest()
{
size = 18;
initializeDiagonalMatrix(&matrix);
setupTest();
}
template <size_t BlockSize>
void setupTriDiagonalBlockMatrixTest(bool isSymmetric = false)
{
size = BlockSize * 6;
initializeTriDiagonalBlockMatrix<BlockSize>(&matrix, isSymmetric);
setupTest();
}
Matrix matrix;
Matrix inverseMatrix, expectedInverse;
Vector b;
Vector x, expectedX;
};
TEST_F(LinearSolveAndInverseTests, DenseMatrixTests)
{
setupDenseMatrixTest();
LinearSolveAndInverseDenseMatrix solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, DiagonalMatrixTests)
{
setupDiagonalMatrixTest();
LinearSolveAndInverseDiagonalMatrix solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize2Tests)
{
setupTriDiagonalBlockMatrixTest<2>();
LinearSolveAndInverseTriDiagonalBlockMatrix<2> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize3Tests)
{
setupTriDiagonalBlockMatrixTest<3>();
LinearSolveAndInverseTriDiagonalBlockMatrix<3> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize4Tests)
{
setupTriDiagonalBlockMatrixTest<4>();
LinearSolveAndInverseTriDiagonalBlockMatrix<4> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize5Tests)
{
setupTriDiagonalBlockMatrixTest<5>();
LinearSolveAndInverseTriDiagonalBlockMatrix<5> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, TriDiagonalBlockMatrixBlockSize6Tests)
{
setupTriDiagonalBlockMatrixTest<6>();
LinearSolveAndInverseTriDiagonalBlockMatrix<6> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize2Tests)
{
setupTriDiagonalBlockMatrixTest<2>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<2> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize3Tests)
{
setupTriDiagonalBlockMatrixTest<3>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<3> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize4Tests)
{
setupTriDiagonalBlockMatrixTest<4>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<4> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize5Tests)
{
setupTriDiagonalBlockMatrixTest<5>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<5> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
TEST_F(LinearSolveAndInverseTests, SymmetricTriDiagonalBlockMatrixBlockSize6Tests)
{
setupTriDiagonalBlockMatrixTest<6>(true);
LinearSolveAndInverseSymmetricTriDiagonalBlockMatrix<6> solveAndInverse;
solveAndInverse.setMatrix(matrix);
x = solveAndInverse.solve(b);
inverseMatrix = solveAndInverse.getInverse();
EXPECT_TRUE(x.isApprox(expectedX));
EXPECT_TRUE(inverseMatrix.isApprox(expectedInverse));
};
}; // namespace Math
}; // namespace SurgSim
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetLogLevel(OF_LOG_VERBOSE);
//disable vertical Sync is too bad with light sometimes
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(10, 10, 10);
ofEnableAntiAliasing();
ofEnableDepthTest();
displaceSphere.setPosition(-550, 0, -500);
displaceSphere.setRadius(150);
displaceSphere.setResolution(50);
alphaBlendSphere.setPosition(0, 0, -500);
alphaBlendSphere.setRadius(150);
alphaBlendSphere.setResolution(50);
colorKeySphere.setPosition(550, 0, -500);
colorKeySphere.setRadius(150);
colorKeySphere.setResolution(50);
colorKeySphere.rotate(90, 1.0f, 0.0f, 0.0f);
directional.setDirectional();
directional.setOrientation( ofVec3f(0, 230, 0) );
colormap.loadImage("earth.jpg");
bumpmap.loadImage("earth-bumps.jpg");
blendMap.loadImage("clouds.jpg");
colorKeyMap.loadImage("colorkey.gif");
displaceSphere.mapTexCoordsFromTexture(colormap.getTextureReference());
alphaBlendSphere.mapTexCoordsFromTexture(colormap.getTextureReference());
colorKeySphere.mapTexCoordsFromTexture(colormap.getTextureReference());
target = 0; // First target at the center sphere
bShowHelp = true;
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(ofColor::lightBlue);
cam.begin();
// DISPLACE SHADER
displaceShader.setColormap(&colormap);
displaceShader.setDisplaceMap(&bumpmap);
if (target == 2) {
displaceShader.setMaximumHeight(mouseX);
}
// Actually mandatory only in OpenGL 3.3 - don't do it if ofIsGLProgrammableRenderer() == false
if (!ofIsGLProgrammableRenderer()) {
const ofMatrix4x4 normalMatrix = ofMatrix4x4::getTransposedOf(cam.getModelViewMatrix().getInverse());
displaceShader.setNormalMatrix(normalMatrix);
}
displaceShader.begin();
displaceSphere.draw();
displaceShader.end();
// ALPHA BLENDING SHADER
alphaBlendShader.setColormap(&colormap);
alphaBlendShader.setAlphaBlendMap(&blendMap);
if (target == 0) {
const float blendAlpha = ofMap(mouseX, 0.0f, ofGetWidth() - 1, 0.0f, 1.0f);
alphaBlendShader.setBlendAlpha(blendAlpha);
}
alphaBlendShader.begin();
alphaBlendSphere.draw();
alphaBlendShader.end();
// COLOR KEY SHADER
colorKeyShader.setColormap(&colormap);
colorKeyShader.setColorKeyMap(&colorKeyMap);
colorKeyShader.setKeyColor(ofFloatColor(1.0f, 0.0f, 0.0f, 1.0f));
colorKeyShader.begin();
colorKeySphere.draw();
colorKeyShader.end();
cam.end();
if (bShowHelp) {
string shaderName;
if (target == 0) {
shaderName = "Alpha Blending Shader";
cam.setTarget(alphaBlendSphere.getPosition());
} else if (target == 1) {
shaderName = "Color Key Shader";
cam.setTarget(colorKeySphere.getPosition());
} else if (target == 2) {
shaderName = "Displacement Shader";
cam.setTarget(displaceSphere.getPosition());
}
ofSetColor(ofColor::black);
ofDrawBitmapString(string("Move your mouse to trigger changes on target (except color key)\nTarget (T): " + shaderName + "\n" +
"Show/Hide help (E)"),
20, 20);
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key) {
case 'e':
bShowHelp = !bShowHelp;
break;
case 't':
target = (target + 1) % 3;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Finish removing deprecated functions in example Mapping project<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetLogLevel(OF_LOG_VERBOSE);
//disable vertical Sync is too bad with light sometimes
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(10, 10, 10);
ofEnableAntiAliasing();
ofEnableDepthTest();
displaceSphere.setPosition(-550, 0, -500);
displaceSphere.setRadius(150);
displaceSphere.setResolution(50);
alphaBlendSphere.setPosition(0, 0, -500);
alphaBlendSphere.setRadius(150);
alphaBlendSphere.setResolution(50);
colorKeySphere.setPosition(550, 0, -500);
colorKeySphere.setRadius(150);
colorKeySphere.setResolution(50);
colorKeySphere.rotate(90, 1.0f, 0.0f, 0.0f);
directional.setDirectional();
directional.setOrientation( ofVec3f(0, 230, 0) );
colormap.load("earth.jpg");
bumpmap.load("earth-bumps.jpg");
blendMap.load("clouds.jpg");
colorKeyMap.load("colorkey.gif");
displaceSphere.mapTexCoordsFromTexture(colormap.getTexture());
alphaBlendSphere.mapTexCoordsFromTexture(colormap.getTexture());
colorKeySphere.mapTexCoordsFromTexture(colormap.getTexture());
target = 0; // First target at the center sphere
bShowHelp = true;
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(ofColor::lightBlue);
cam.begin();
// DISPLACE SHADER
displaceShader.setColormap(&colormap);
displaceShader.setDisplaceMap(&bumpmap);
if (target == 2) {
displaceShader.setMaximumHeight(mouseX);
}
// Actually mandatory only in OpenGL 3.3 - don't do it if ofIsGLProgrammableRenderer() == false
if (!ofIsGLProgrammableRenderer()) {
const ofMatrix4x4 normalMatrix = ofMatrix4x4::getTransposedOf(cam.getModelViewMatrix().getInverse());
displaceShader.setNormalMatrix(normalMatrix);
}
displaceShader.begin();
displaceSphere.draw();
displaceShader.end();
// ALPHA BLENDING SHADER
alphaBlendShader.setColormap(&colormap);
alphaBlendShader.setAlphaBlendMap(&blendMap);
if (target == 0) {
const float blendAlpha = ofMap(mouseX, 0.0f, ofGetWidth() - 1, 0.0f, 1.0f);
alphaBlendShader.setBlendAlpha(blendAlpha);
}
alphaBlendShader.begin();
alphaBlendSphere.draw();
alphaBlendShader.end();
// COLOR KEY SHADER
colorKeyShader.setColormap(&colormap);
colorKeyShader.setColorKeyMap(&colorKeyMap);
colorKeyShader.setKeyColor(ofFloatColor(1.0f, 0.0f, 0.0f, 1.0f));
colorKeyShader.begin();
colorKeySphere.draw();
colorKeyShader.end();
cam.end();
if (bShowHelp) {
string shaderName;
if (target == 0) {
shaderName = "Alpha Blending Shader";
cam.setTarget(alphaBlendSphere.getPosition());
} else if (target == 1) {
shaderName = "Color Key Shader";
cam.setTarget(colorKeySphere.getPosition());
} else if (target == 2) {
shaderName = "Displacement Shader";
cam.setTarget(displaceSphere.getPosition());
}
ofSetColor(ofColor::black);
ofDrawBitmapString(string("Move your mouse to trigger changes on target (except color key)\nTarget (T): " + shaderName + "\n" +
"Show/Hide help (E)"),
20, 20);
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key) {
case 'e':
bShowHelp = !bShowHelp;
break;
case 't':
target = (target + 1) % 3;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Framework/Component.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/Shape.h"
namespace
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation);
}
namespace SurgSim
{
namespace Physics
{
DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
SurgSim::Collision::Representation(name)
{
}
DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}
void DeformableCollisionRepresentation::setMesh(std::shared_ptr<SurgSim::DataStructures::TriangleMesh> mesh)
{
SURGSIM_ASSERT(!isInitialized()) << "Can't set mesh after initialization.";
SURGSIM_ASSERT(mesh != nullptr) << "Can't use nullptr mesh.";
m_shape = std::make_shared<SurgSim::Math::MeshShape>(*mesh);
m_mesh = mesh;
}
std::shared_ptr<SurgSim::DataStructures::TriangleMesh> DeformableCollisionRepresentation::getMesh() const
{
return m_mesh;
}
void DeformableCollisionRepresentation::update(const double& dt)
{
SURGSIM_ASSERT(!m_deformable.expired()) << "Deformable has expired, cannot update the mesh.";
auto state = m_deformable.lock()->getCurrentState();
const size_t numNodes = state->getNumNodes();
SURGSIM_ASSERT(m_mesh->getNumVertices() == numNodes) << "The number of nodes in the deformable does not match " <<
"the number of vertices in the mesh.";
for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
{
m_mesh->setVertexPosition(nodeId, state->getPosition(nodeId));
}
}
bool DeformableCollisionRepresentation::doInitialize()
{
SURGSIM_ASSERT(m_mesh != nullptr) << "Mesh was not set.";
SURGSIM_ASSERT(!m_deformable.expired()) << "Can't startup without a deformable.";
auto state = m_deformable.lock()->getCurrentState();
SURGSIM_ASSERT(m_mesh->getNumVertices() == state->getNumNodes()) <<
"The number of nodes in the deformable does not match " <<
"the number of vertices in the mesh.";
update(0.0);
return true;
}
int DeformableCollisionRepresentation::getShapeType() const
{
SURGSIM_ASSERT(m_shape != nullptr) << "No mesh or shape assigned to DeformableCollisionRepresentation " <<
getName();
return m_shape->getType();
}
void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH) <<
"Deformable collision shape has to be a mesh." <<
" currently " << m_shape->getType();
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape);
m_mesh = meshShape->getMesh();
}
void DeformableCollisionRepresentation::setInitialPose(const SurgSim::Math::RigidTransform3d& pose)
{
SURGSIM_FAILURE() << "The initial pose cannot be set";
}
const SurgSim::Math::RigidTransform3d& DeformableCollisionRepresentation::getInitialPose() const
{
SURGSIM_ASSERT(m_deformable.expired()) <<
"Cannot get the initial pose because the deformable was not initialized.";
return m_deformable.lock()->getInitialPose();
}
void DeformableCollisionRepresentation::setPose(const SurgSim::Math::RigidTransform3d& pose)
{
SURGSIM_FAILURE() << "The pose cannot be set";
}
const SurgSim::Math::RigidTransform3d& DeformableCollisionRepresentation::getPose() const
{
SURGSIM_ASSERT(m_deformable.expired()) << "Cannot get the pose because the deformable was not initialized.";
return m_deformable.lock()->getInitialPose();
}
const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
return m_shape;
}
void DeformableCollisionRepresentation::setDeformableRepresentation(
std::shared_ptr<SurgSim::Physics::DeformableRepresentationBase>representation)
{
m_deformable = representation;
}
}
}
<commit_msg>Define DeformableCollisionRepresentation::getDeformableRepresentation().<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Framework/Component.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/Shape.h"
namespace
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation);
}
namespace SurgSim
{
namespace Physics
{
DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
SurgSim::Collision::Representation(name)
{
}
DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}
void DeformableCollisionRepresentation::setMesh(std::shared_ptr<SurgSim::DataStructures::TriangleMesh> mesh)
{
SURGSIM_ASSERT(!isInitialized()) << "Can't set mesh after initialization.";
SURGSIM_ASSERT(mesh != nullptr) << "Can't use nullptr mesh.";
m_shape = std::make_shared<SurgSim::Math::MeshShape>(*mesh);
m_mesh = mesh;
}
std::shared_ptr<SurgSim::DataStructures::TriangleMesh> DeformableCollisionRepresentation::getMesh() const
{
return m_mesh;
}
void DeformableCollisionRepresentation::update(const double& dt)
{
SURGSIM_ASSERT(!m_deformable.expired()) << "Deformable has expired, cannot update the mesh.";
auto state = m_deformable.lock()->getCurrentState();
const size_t numNodes = state->getNumNodes();
SURGSIM_ASSERT(m_mesh->getNumVertices() == numNodes) << "The number of nodes in the deformable does not match " <<
"the number of vertices in the mesh.";
for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
{
m_mesh->setVertexPosition(nodeId, state->getPosition(nodeId));
}
}
bool DeformableCollisionRepresentation::doInitialize()
{
SURGSIM_ASSERT(m_mesh != nullptr) << "Mesh was not set.";
SURGSIM_ASSERT(!m_deformable.expired()) << "Can't startup without a deformable.";
auto state = m_deformable.lock()->getCurrentState();
SURGSIM_ASSERT(m_mesh->getNumVertices() == state->getNumNodes()) <<
"The number of nodes in the deformable does not match " <<
"the number of vertices in the mesh.";
update(0.0);
return true;
}
int DeformableCollisionRepresentation::getShapeType() const
{
SURGSIM_ASSERT(m_shape != nullptr) << "No mesh or shape assigned to DeformableCollisionRepresentation " <<
getName();
return m_shape->getType();
}
void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH) <<
"Deformable collision shape has to be a mesh." <<
" currently " << m_shape->getType();
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape);
m_mesh = meshShape->getMesh();
}
void DeformableCollisionRepresentation::setInitialPose(const SurgSim::Math::RigidTransform3d& pose)
{
SURGSIM_FAILURE() << "The initial pose cannot be set";
}
const SurgSim::Math::RigidTransform3d& DeformableCollisionRepresentation::getInitialPose() const
{
SURGSIM_ASSERT(m_deformable.expired()) <<
"Cannot get the initial pose because the deformable was not initialized.";
return m_deformable.lock()->getInitialPose();
}
void DeformableCollisionRepresentation::setPose(const SurgSim::Math::RigidTransform3d& pose)
{
SURGSIM_FAILURE() << "The pose cannot be set";
}
const SurgSim::Math::RigidTransform3d& DeformableCollisionRepresentation::getPose() const
{
SURGSIM_ASSERT(m_deformable.expired()) << "Cannot get the pose because the deformable was not initialized.";
return m_deformable.lock()->getInitialPose();
}
const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
return m_shape;
}
void DeformableCollisionRepresentation::setDeformableRepresentation(
std::shared_ptr<SurgSim::Physics::DeformableRepresentationBase>representation)
{
m_deformable = representation;
}
const std::shared_ptr<SurgSim::Physics::DeformableRepresentationBase>
DeformableCollisionRepresentation::getDeformableRepresentation() const
{
SURGSIM_ASSERT(m_deformable.expired())
<< "Cannot get the deformable representation because it was not initialized.";
return m_deformable.lock();
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkExceptionObject.h"
#include <iostream>
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbExtractROI.h"
int otbImageFileReaderRADComplexShort(int argc, char* argv[])
{
// Verify the number of parameters in the command line
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
/*
typedef std::complex<short> InputPixelType;
typedef std::complex<short> OutputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image< InputPixelType, Dimension > InputImageType;
typedef otb::Image< OutputPixelType, Dimension > OutputImageType;
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
writer->SetInput( reader->GetOutput() );
writer->Update();
*/
return EXIT_SUCCESS;
}
<commit_msg>ENH. Update Testing for RAD format<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkExceptionObject.h"
#include <iostream>
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbExtractROI.h"
int otbImageFileReaderRADComplexShort(int argc, char* argv[])
{
// Verify the number of parameters in the command line
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef int InputPixelType;
typedef int OutputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image< InputPixelType, Dimension > InputImageType;
typedef otb::Image< OutputPixelType, Dimension > OutputImageType;
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
writer->SetInput( reader->GetOutput() );
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <UnitTest11.hpp>
#include <UnitTest11/TestFixtureRunner.hpp>
namespace ut11
{
namespace Utility
{
template<> struct ParseToString<ut11::Output*>
{
inline std::string operator()(ut11::Output* value) const
{
std::stringstream stream;
stream << value;
return stream.str();
}
};
}
}
namespace
{
class FakeOutput : public ut11::Output
{
public:
virtual ~FakeOutput() { }
MockAction(Begin)
MockAction(Finish, std::size_t, std::size_t)
MockAction(BeginFixture, std::string)
MockAction(EndFixture, std::string)
MockAction(BeginGiven, std::string)
MockAction(EndGiven, std::string)
MockAction(BeginWhen, std::string)
MockAction(EndWhen, std::string)
MockAction(BeginThen, std::string)
MockAction(EndThen, std::string)
MockAction(BeginFinally, std::string)
MockAction(EndFinally, std::string)
MockAction(OnError, std::size_t, std::string, std::string)
MockAction(OnUnknownError)
ut11::Mock<void (std::exception)> mockOnError1;
virtual void OnError(const std::exception& ex) { mockOnError1(ex); }
};
class FakeTestFixture : public ut11::TestFixtureAbstract
{
private:
ut11::TestFixtureResults m_runResults;
public:
ut11::Output* RunOutputUsed;
FakeTestFixture(ut11::TestFixtureResults runResults)
: m_runResults(runResults), RunOutputUsed(nullptr)
{
}
MockAction(Given, std::string, std::function<void(void)>);
MockAction(When, std::string, std::function<void(void)>);
MockAction(Then, std::string, std::function<void(void)>);
MockAction(Finally, std::string, std::function<void(void)>);
MockFunction(std::string, GetName);
virtual ut11::TestFixtureResults Run(ut11::Output& output)
{
RunOutputUsed = &output;
return m_runResults;
}
};
}
class TestFixtureRunnerTests : public ut11::TestFixture
{
private:
ut11::TestFixtureRunner m_runner;
FakeOutput m_output;
int m_expectedResult;
int m_result;
public:
virtual void Run()
{
Given("a TestFixtureRunner with added Fixture with failing tests", [&]() {
m_runner = ut11::TestFixtureRunner();
ut11::TestFixtureResults fixtureResults;
fixtureResults.ran = 5;
fixtureResults.succeeded = 3;
m_expectedResult = 2;
FakeTestFixture* fixture = new FakeTestFixture(fixtureResults);
fixture->mockGetName.SetReturn("name");
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(fixture));
});
When("running the TestFixtureRunner", [&]() {
m_result = m_runner.Run(m_output);
});
Then("the number of failing tests is returned", [&]() {
AssertThat(m_result, ut11::Is::EqualTo(m_expectedResult));
});
}
};
DeclareFixture(TestFixtureRunnerTests);
class TestFixtureRunnerMultipleFixturesTests : public ut11::TestFixture
{
private:
ut11::TestFixtureRunner m_runner;
FakeOutput m_output;
FakeTestFixture* m_fixtureOne;
FakeTestFixture* m_fixtureTwo;
public:
virtual void Run()
{
Given("a TestFixtureRunner where two fixtures with the same names are added", [&]() {
m_runner = ut11::TestFixtureRunner();
m_output = FakeOutput();
m_fixtureOne = new FakeTestFixture(ut11::TestFixtureResults());
m_fixtureTwo = new FakeTestFixture(ut11::TestFixtureResults());
m_fixtureOne->mockGetName.SetReturn("name");
m_fixtureTwo->mockGetName.SetReturn("name");
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(m_fixtureOne));
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(m_fixtureTwo));
});
When("Running the test fixture runner", [&]() {
m_runner.Run(m_output);
});
Then("only the first test fixture is ran", [&]() {
AssertThat(m_fixtureOne->RunOutputUsed, ut11::Is::Not::Null);
AssertThat(m_fixtureTwo->RunOutputUsed, ut11::Is::Null);
});
}
};
<commit_msg>Adds handling of multiple fixtures with same name in code<commit_after>#include <UnitTest11.hpp>
#include <UnitTest11/TestFixtureRunner.hpp>
namespace ut11
{
namespace Utility
{
template<> struct ParseToString<ut11::Output*>
{
inline std::string operator()(ut11::Output* value) const
{
std::stringstream stream;
stream << value;
return stream.str();
}
};
}
}
namespace
{
class FakeOutput : public ut11::Output
{
public:
virtual ~FakeOutput() { }
MockAction(Begin)
MockAction(Finish, std::size_t, std::size_t)
MockAction(BeginFixture, std::string)
MockAction(EndFixture, std::string)
MockAction(BeginGiven, std::string)
MockAction(EndGiven, std::string)
MockAction(BeginWhen, std::string)
MockAction(EndWhen, std::string)
MockAction(BeginThen, std::string)
MockAction(EndThen, std::string)
MockAction(BeginFinally, std::string)
MockAction(EndFinally, std::string)
MockAction(OnError, std::size_t, std::string, std::string)
MockAction(OnUnknownError)
ut11::Mock<void (std::exception)> mockOnError1;
virtual void OnError(const std::exception& ex) { mockOnError1(ex); }
};
class FakeTestFixture : public ut11::TestFixtureAbstract
{
private:
ut11::TestFixtureResults m_runResults;
public:
ut11::Output* RunOutputUsed;
FakeTestFixture(ut11::TestFixtureResults runResults)
: m_runResults(runResults), RunOutputUsed(nullptr)
{
}
MockAction(Given, std::string, std::function<void(void)>);
MockAction(When, std::string, std::function<void(void)>);
MockAction(Then, std::string, std::function<void(void)>);
MockAction(Finally, std::string, std::function<void(void)>);
MockFunction(std::string, GetName);
virtual ut11::TestFixtureResults Run(ut11::Output& output)
{
RunOutputUsed = &output;
return m_runResults;
}
};
}
class TestFixtureRunnerTests : public ut11::TestFixture
{
private:
ut11::TestFixtureRunner m_runner;
FakeOutput m_output;
int m_expectedResult;
int m_result;
public:
virtual void Run()
{
Given("a TestFixtureRunner with added Fixture with failing tests", [&]() {
m_runner = ut11::TestFixtureRunner();
ut11::TestFixtureResults fixtureResults;
fixtureResults.ran = 5;
fixtureResults.succeeded = 3;
m_expectedResult = 2;
FakeTestFixture* fixture = new FakeTestFixture(fixtureResults);
fixture->mockGetName.SetReturn("name");
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(fixture));
});
When("running the TestFixtureRunner", [&]() {
m_result = m_runner.Run(m_output);
});
Then("the number of failing tests is returned", [&]() {
AssertThat(m_result, ut11::Is::EqualTo(m_expectedResult));
});
}
};
DeclareFixture(TestFixtureRunnerTests);
class TestFixtureRunnerMultipleFixturesTests : public ut11::TestFixture
{
private:
ut11::TestFixtureRunner m_runner;
FakeOutput m_output;
FakeTestFixture* m_fixtureOne;
FakeTestFixture* m_fixtureTwo;
public:
virtual void Run()
{
Given("a TestFixtureRunner where two fixtures with the same names are added", [&]() {
m_runner = ut11::TestFixtureRunner();
m_output = FakeOutput();
m_fixtureOne = new FakeTestFixture(ut11::TestFixtureResults());
m_fixtureTwo = new FakeTestFixture(ut11::TestFixtureResults());
m_fixtureOne->mockGetName.SetReturn("name");
m_fixtureTwo->mockGetName.SetReturn("name");
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(m_fixtureOne));
m_runner.AddFixture(std::unique_ptr<ut11::TestFixtureAbstract>(m_fixtureTwo));
});
When("Running the test fixture runner", [&]() {
m_runner.Run(m_output);
});
Then("only the first test fixture is ran", [&]() {
AssertThat(m_fixtureOne->RunOutputUsed, ut11::Is::Not::Null);
AssertThat(m_fixtureTwo->RunOutputUsed, ut11::Is::Null);
});
}
};
DeclareFixture(TestFixtureRunnerMultipleFixturesTests);
<|endoftext|> |
<commit_before>#ifndef ORM_QUERYSET_HPP
#define ORM_QUERYSET_HPP
#include <ORM/backends/Filter.hpp>
#include <ORM/core/Cache.hpp>
namespace orm
{
template<typename T> class SQLObject;
template <typename T>
class QuerySet
{
public:
QuerySet(QuerySet<T>&& tmp);
template<typename U,typename ... Args>
QuerySet<T>& filter(const U& value,const std::string& operande,const std::string& colum,const Args& ... args);
QuerySet<T>& filter(const std::list<Filter>& filter_list);
QuerySet<T>& filter(std::list<Filter>&& filter_list);
QuerySet<T>& orderBy(const std::string& colum);
QuerySet<T>& orderBy(std::string&& colum);
//QuerySet& orderBy(int,const std::string& colum);
template<typename U,typename ... Args>
QuerySet<T>& exclude(const U& value,const std::string& operande,const std::string& colum,const Args& ... args);
QuerySet<T>& exclude(const std::list<Filter>& exclude_list);
QuerySet<T>& exclude(std::list<Filter>&& exclude_list);
QuerySet<T>& limit(const unsigned int& max);
QuerySet<T>& limit(const unsigned int& min,const unsigned int& max);
//QuerySet& agregate();
bool get(T& obj,int max_depth=ORM_DEFAULT_MAX_DEPTH);
//bool get(typename std::list<Cache<T>::type_ptr>& obj,int max_depth=ORM_DEFAULT_MAX_DEPTH);
void __print__() const;
private:
friend class SQLObject<T>;
explicit QuerySet();
template<typename ... Args>
static std::string makeColumName(const std::string& prefix,const std::string& colum,Args&& ... args);
template<typename ... Args>
static std::string makeColumName(std::string&& prefix,std::string&& colum,Args&& ... args);
static std::string makeColumName(std::string colum);
Query* makeQuery(int max_depth);
QuerySet(const QuerySet&) = delete;
QuerySet& operator=(const QuerySet&) = delete;
std::list<Filter> filters;
std::list<Filter> excludes;
std::vector<std::string> order_by;
int limit_min,limit_max;
};
}
#include <ORM/backends/private/QuerySet.tpl>
#endif
<commit_msg>add doc to QuerySet<commit_after>#ifndef ORM_QUERYSET_HPP
#define ORM_QUERYSET_HPP
#include <ORM/backends/Filter.hpp>
#include <ORM/core/Cache.hpp>
namespace orm
{
template<typename T> class SQLObject;
/**
* \brief A class that allow you to make query on the type T
*
* Note : T must be a SQLObject
*
* \see SQLObject
**/
template <typename T>
class QuerySet
{
public:
/**
* \brief Construct a QuerySet from a tmp value
*
* \param tmp the tmp value to use
*
* Note : tmp as an undefined status after the call of this function
**/
QuerySet(QuerySet<T>&& tmp);
/**
* \brief Construct a filter to apply in the query
*
* \param value The value to compare with
* \param The operator to use see Bdd::Operators for detail
* \param colum The colum to apply the comparasion
* \param args If more than one collum is send, all colum will be concatenate (with the correct format) to create the correct colum name. Args must be std::string
* \return *this
**/
template<typename U,typename ... Args>
QuerySet<T>& filter(const U& value,const std::string& operande,const std::string& colum,const Args& ... args);
/**
* \brief Add some filters to apply in the query
*
* \param filter_list some Filter to apply to the query.
*
* \return *this
**/
QuerySet<T>& filter(const std::list<Filter>& filter_list);
/**
* \brief Add some filters to apply in the query from a tmp value
*
* \param filter_list some Filter to apply to the query.
*
* \return *this
*
* Note : filter_list as an undefined status after the call of this function
**/
QuerySet<T>& filter(std::list<Filter>&& filter_list);
/**
* \brief Add a order by constrait to the query
*
* \param colum The colum to use for ordering
*
* \return *this;
**/
QuerySet<T>& orderBy(const std::string& colum);
/**
* \brief Add a order by constrait to the query
*
* \param colum The colum to use for ordering
*
* \return *this;
**/
QuerySet<T>& orderBy(std::string&& colum);
//QuerySet& orderBy(int,const std::string& colum);
/**
* \brief Add a negatide filter to the query
*
* \param value The value to compare with
* \param The operator to use see Bdd::Operators for detail
* \param colum The colum to apply the comparasion
* \param args If more than one collum is send, all colum will be concatenate (with the correct format) to create the correct colum name. Args must be std::string
*
* \return *this
**/
template<typename U,typename ... Args>
QuerySet<T>& exclude(const U& value,const std::string& operande,const std::string& colum,const Args& ... args);
/**
* \brief Add some negative filters to apply in the query
*
* \param filter_list some Filter to apply to the query.
*
* \return *this
**/
QuerySet<T>& exclude(const std::list<Filter>& exclude_list);
/**
* \brief Add some negative filters to apply in the query
*
* \param filter_list some Filter to apply to the query.
*
* \return *this
**/
QuerySet<T>& exclude(std::list<Filter>&& exclude_list);
/**
* \brief Add a limite of the number of object return by the dbtabase
*
* \param max Maximun number of object
*
* \return *this
**/
QuerySet<T>& limit(const unsigned int& max);
/**
* \brief Add a limite of the number of object return by the dbtabase.
*
* .limite(2,5) will return in maximun 3 (5-2) objects after the execution of the query.
*
* \param min Minimal range of object
* \param max Maximun range of object
*
*
*
* \return *this
**/
QuerySet<T>& limit(const unsigned int& min,const unsigned int& max);
//QuerySet& agregate();
/**
* \brief Execute tho query and return the coresponding object
*
* \param obj Where the result will be stored. If mor than one object are return by the databse, only the fist is construct
* \param max_depth the maximun recursion depth for the object construction (for fk)
*
* \return false if no object match with the query.
**/
bool get(T& obj,int max_depth=ORM_DEFAULT_MAX_DEPTH);
//bool get(typename std::list<Cache<T>::type_ptr>& obj,int max_depth=ORM_DEFAULT_MAX_DEPTH);
/**
* \brief Print the content of the filter for debug help
**/
void __print__() const;
private:
friend class SQLObject<T>;
/**
* \brief Construct a empty QuerySet
**/
explicit QuerySet();
/**
* \brief Merge colum name to build the alias
*
* \param prefix The prefix colum alias
* \param colum The colum alias to merge
* \param args Some optional colum alias
*
* \return the complet alias
**/
template<typename ... Args>
static std::string makeColumName(const std::string& prefix,const std::string& colum,Args&& ... args);
/**
* \brief Merge colum name to build the alias
*
* \param prefix The prefix colum alias
* \param colum The colum alias to merge
* \param args Some optional colum alias
*
* \return the complet alias
**/
template<typename ... Args>
static std::string makeColumName(std::string&& prefix,std::string&& colum,Args&& ... args);
/**
* \brief Do nothing
*
* \param colum The colum alias to merge
*
* \return colum
**/
static std::string makeColumName(std::string colum);
/**
* \brief Construct the query with all constraints
*
* \param max_depth Maximun depth of recursion in join (if object have FK only)
*
* \return NULL if fail or the query to use in othe case
**/
Query* makeQuery(int max_depth);
QuerySet(const QuerySet&) = delete;
QuerySet& operator=(const QuerySet&) = delete;
std::list<Filter> filters; ///< Store all the filters
std::list<Filter> excludes;///< Store all the negative filters
std::vector<std::string> order_by; ///< store the colum name for ordering
int limit_min, ///< minimun limite (default is none)
limit_max; ///< maximun limite (default is none)
};
}
#include <ORM/backends/private/QuerySet.tpl>
#endif
<|endoftext|> |
<commit_before>#include "babylon/babylon_imgui/babylon_studio_layout.h"
#include "imgui_internal.h"
#include "imgui_utils/app_runner/imgui_runner.h"
#include "imgui_utils/icons_font_awesome_5.h"
namespace BABYLON {
BabylonStudioLayout::BabylonStudioLayout()
{
_dockableWindowsInfos = {
{DockableWindowId::Scene3d, {ICON_FA_CUBE " 3D Scene", true}},
{DockableWindowId::SampleBrowser, {ICON_FA_PALETTE " Browse samples", true}},
{DockableWindowId::SamplesCodeViewer, {ICON_FA_EDIT " Samples Code Viewer", true}},
#ifdef BABYLON_BUILD_PLAYGROUND
{DockableWindowId::PlaygroundEditor, {ICON_FA_FLASK " Playground", true}},
#endif
{DockableWindowId::Logs, {ICON_FA_STREAM " Logs", true}},
{DockableWindowId::Inspector, {ICON_FA_EDIT " Inspector", true}},
};
}
std::vector<BABYLON::DockableWindowId> BabylonStudioLayout::dockableWindowsList()
{
std::vector<DockableWindowId> r;
for (const auto& kv : _dockableWindowsInfos) {
r.push_back(kv.first);
}
return r;
}
void BabylonStudioLayout::registerGuiRenderFunction(DockableWindowId id, GuiRenderFunction fn)
{
_dockableWindowsInfos.at(id).RenderFunction = fn;
}
void BabylonStudioLayout::renderGui()
{
for (const auto& kv : _dockableWindowsInfos) {
const DockableWindowInfo& dockableWindowInfo = kv.second;
if (dockableWindowInfo.RenderFunction && dockableWindowInfo.IsVisible) {
bool visible = true;
ImGui::Begin(dockableWindowInfo.Label.c_str(), &visible);
dockableWindowInfo.RenderFunction();
ImGui::End();
setVisible(kv.first, visible);
}
}
}
void BabylonStudioLayout::renderMenu()
{
if (ImGui::BeginMenu("Layout")) {
static std::map<LayoutMode, std::string> layoutModeLabels{
{LayoutMode::Scene, ICON_FA_CUBE " Scene"},
{LayoutMode::SceneAndBrowser, ICON_FA_CUBES " Scene and Samples Browser"},
{LayoutMode::Dev, ICON_FA_FILE_CODE " Dev"},
};
for (const auto& kv : layoutModeLabels) {
if (ImGui::MenuItem(kv.second.c_str(), "", _layoutMode == kv.first)) {
_layoutMode = kv.first;
ApplyLayoutMode(_layoutMode);
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Windows")) {
for (const auto& kv : _dockableWindowsInfos) {
const DockableWindowInfo& dockableWindowInfo = kv.second;
auto id = kv.first;
if (dockableWindowInfo.RenderFunction) {
if (ImGui::MenuItem(dockableWindowInfo.Label.c_str(), "", isVisible(id)))
setVisible(id, !isVisible(id));
}
}
ImGui::EndMenu();
}
}
bool BabylonStudioLayout::isVisible(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).IsVisible;
}
void BabylonStudioLayout::setVisible(DockableWindowId id, bool v)
{
_dockableWindowsInfos.at(id).IsVisible = v;
}
std::string BabylonStudioLayout::Label(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).Label;
}
const char* BabylonStudioLayout::Label_c(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).Label.c_str();
}
void BabylonStudioLayout::DoDock(DockableWindowId id, ImGuiID dockId)
{
ImGui::DockBuilderDockWindow(Label_c(id), dockId);
}
ImGuiID BabylonStudioLayout::DoSplit(ImGuiID* io_dockToSplit, ImGuiDir_ splitDirection, float ratio)
{
ImGuiID new_dock
= ImGui::DockBuilderSplitNode(*io_dockToSplit, splitDirection, ratio, NULL, io_dockToSplit);
return new_dock;
}
bool BabylonStudioLayout::IsShowingSceneOnly()
{
if (!isVisible(DockableWindowId::Scene3d))
return false;
for (auto id : dockableWindowsList())
if (isVisible(id) && id != DockableWindowId::Scene3d)
return false;
return true;
}
void BabylonStudioLayout::PrepareLayout(ImGuiID fullDockSpaceId)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::DockBuilderRemoveNode(fullDockSpaceId); // Clear out existing layout
ImGui::DockBuilderAddNode(fullDockSpaceId); // Add empty node
ImGui::DockBuilderSetNodeSize(fullDockSpaceId, viewport->Size);
ImGuiID dock_main_id = fullDockSpaceId;
ImGuiID dock_id_bottom = DoSplit(&dock_main_id, ImGuiDir_Down, 0.25f);
ImGuiID dock_id_left = DoSplit(&dock_main_id, ImGuiDir_Left, 0.30f);
ImGuiID dock_id_right = DoSplit(&dock_main_id, ImGuiDir_Right, 0.45f);
#ifdef BABYLON_BUILD_PLAYGROUND
DoDock(DockableWindowId::PlaygroundEditor, dock_main_id);
#endif
DoDock(DockableWindowId::SamplesCodeViewer, dock_main_id);
if (_layoutMode == LayoutMode::Dev) {
DoDock(DockableWindowId::Inspector, dock_main_id);
DoDock(DockableWindowId::SampleBrowser, dock_main_id);
}
else {
DoDock(DockableWindowId::Inspector, dock_id_left);
DoDock(DockableWindowId::SampleBrowser, dock_id_left);
}
DoDock(DockableWindowId::Scene3d, dock_id_right);
DoDock(DockableWindowId::Logs, dock_id_bottom);
ImGui::DockBuilderFinish(fullDockSpaceId);
}
void BabylonStudioLayout::FocusWindow(DockableWindowId id)
{
ImGuiWindow* window = ImGui::FindWindowByName(Label_c(id));
ImGui::FocusWindow(window);
}
void BabylonStudioLayout::ApplyLayoutMode(LayoutMode mode)
{
_layoutMode = mode;
switch (_layoutMode) {
case LayoutMode::Scene:
for (auto id : dockableWindowsList())
setVisible(id, false);
setVisible(DockableWindowId::Scene3d, true);
break;
case LayoutMode::SceneAndBrowser:
setVisible(DockableWindowId::Scene3d, true);
setVisible(DockableWindowId::Inspector, false);
setVisible(DockableWindowId::SampleBrowser, true);
setVisible(DockableWindowId::SamplesCodeViewer, false);
setVisible(DockableWindowId::PlaygroundEditor, false);
setVisible(DockableWindowId::Logs, false);
break;
case LayoutMode::Dev:
for (auto id : dockableWindowsList())
setVisible(id, true);
break;
default:
break;
}
ImGuiUtils::ImGuiRunner::ResetDockLayout();
}
} // namespace BABYLON
<commit_msg>babylon_studio_layout: handle cases when playground is not available<commit_after>#include "babylon/babylon_imgui/babylon_studio_layout.h"
#include "imgui_internal.h"
#include "imgui_utils/app_runner/imgui_runner.h"
#include "imgui_utils/icons_font_awesome_5.h"
namespace BABYLON {
BabylonStudioLayout::BabylonStudioLayout()
{
_dockableWindowsInfos = {
{DockableWindowId::Scene3d, {ICON_FA_CUBE " 3D Scene", true}},
{DockableWindowId::SampleBrowser, {ICON_FA_PALETTE " Browse samples", true}},
{DockableWindowId::SamplesCodeViewer, {ICON_FA_EDIT " Samples Code Viewer", true}},
#ifdef BABYLON_BUILD_PLAYGROUND
{DockableWindowId::PlaygroundEditor, {ICON_FA_FLASK " Playground", true}},
#endif
{DockableWindowId::Logs, {ICON_FA_STREAM " Logs", true}},
{DockableWindowId::Inspector, {ICON_FA_EDIT " Inspector", true}},
};
}
std::vector<BABYLON::DockableWindowId> BabylonStudioLayout::dockableWindowsList()
{
std::vector<DockableWindowId> r;
for (const auto& kv : _dockableWindowsInfos) {
r.push_back(kv.first);
}
return r;
}
void BabylonStudioLayout::registerGuiRenderFunction(DockableWindowId id, GuiRenderFunction fn)
{
_dockableWindowsInfos.at(id).RenderFunction = fn;
}
void BabylonStudioLayout::renderGui()
{
for (const auto& kv : _dockableWindowsInfos) {
const DockableWindowInfo& dockableWindowInfo = kv.second;
if (dockableWindowInfo.RenderFunction && dockableWindowInfo.IsVisible) {
bool visible = true;
ImGui::Begin(dockableWindowInfo.Label.c_str(), &visible);
dockableWindowInfo.RenderFunction();
ImGui::End();
setVisible(kv.first, visible);
}
}
}
void BabylonStudioLayout::renderMenu()
{
if (ImGui::BeginMenu("Layout")) {
static std::map<LayoutMode, std::string> layoutModeLabels{
{LayoutMode::Scene, ICON_FA_CUBE " Scene"},
{LayoutMode::SceneAndBrowser, ICON_FA_CUBES " Scene and Samples Browser"},
{LayoutMode::Dev, ICON_FA_FILE_CODE " Dev"},
};
for (const auto& kv : layoutModeLabels) {
if (ImGui::MenuItem(kv.second.c_str(), "", _layoutMode == kv.first)) {
_layoutMode = kv.first;
ApplyLayoutMode(_layoutMode);
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Windows")) {
for (const auto& kv : _dockableWindowsInfos) {
const DockableWindowInfo& dockableWindowInfo = kv.second;
auto id = kv.first;
if (dockableWindowInfo.RenderFunction) {
if (ImGui::MenuItem(dockableWindowInfo.Label.c_str(), "", isVisible(id)))
setVisible(id, !isVisible(id));
}
}
ImGui::EndMenu();
}
}
bool BabylonStudioLayout::isVisible(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).IsVisible;
}
void BabylonStudioLayout::setVisible(DockableWindowId id, bool v)
{
_dockableWindowsInfos.at(id).IsVisible = v;
}
std::string BabylonStudioLayout::Label(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).Label;
}
const char* BabylonStudioLayout::Label_c(DockableWindowId id)
{
return _dockableWindowsInfos.at(id).Label.c_str();
}
void BabylonStudioLayout::DoDock(DockableWindowId id, ImGuiID dockId)
{
ImGui::DockBuilderDockWindow(Label_c(id), dockId);
}
ImGuiID BabylonStudioLayout::DoSplit(ImGuiID* io_dockToSplit, ImGuiDir_ splitDirection, float ratio)
{
ImGuiID new_dock
= ImGui::DockBuilderSplitNode(*io_dockToSplit, splitDirection, ratio, NULL, io_dockToSplit);
return new_dock;
}
bool BabylonStudioLayout::IsShowingSceneOnly()
{
if (!isVisible(DockableWindowId::Scene3d))
return false;
for (auto id : dockableWindowsList())
if (isVisible(id) && id != DockableWindowId::Scene3d)
return false;
return true;
}
void BabylonStudioLayout::PrepareLayout(ImGuiID fullDockSpaceId)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::DockBuilderRemoveNode(fullDockSpaceId); // Clear out existing layout
ImGui::DockBuilderAddNode(fullDockSpaceId); // Add empty node
ImGui::DockBuilderSetNodeSize(fullDockSpaceId, viewport->Size);
ImGuiID dock_main_id = fullDockSpaceId;
ImGuiID dock_id_bottom = DoSplit(&dock_main_id, ImGuiDir_Down, 0.25f);
ImGuiID dock_id_left = DoSplit(&dock_main_id, ImGuiDir_Left, 0.30f);
ImGuiID dock_id_right = DoSplit(&dock_main_id, ImGuiDir_Right, 0.45f);
#ifdef BABYLON_BUILD_PLAYGROUND
DoDock(DockableWindowId::PlaygroundEditor, dock_main_id);
#endif
DoDock(DockableWindowId::SamplesCodeViewer, dock_main_id);
if (_layoutMode == LayoutMode::Dev) {
DoDock(DockableWindowId::Inspector, dock_main_id);
DoDock(DockableWindowId::SampleBrowser, dock_main_id);
}
else {
DoDock(DockableWindowId::Inspector, dock_id_left);
DoDock(DockableWindowId::SampleBrowser, dock_id_left);
}
DoDock(DockableWindowId::Scene3d, dock_id_right);
DoDock(DockableWindowId::Logs, dock_id_bottom);
ImGui::DockBuilderFinish(fullDockSpaceId);
}
void BabylonStudioLayout::FocusWindow(DockableWindowId id)
{
ImGuiWindow* window = ImGui::FindWindowByName(Label_c(id));
ImGui::FocusWindow(window);
}
void BabylonStudioLayout::ApplyLayoutMode(LayoutMode mode)
{
_layoutMode = mode;
switch (_layoutMode) {
case LayoutMode::Scene:
for (auto id : dockableWindowsList())
setVisible(id, false);
setVisible(DockableWindowId::Scene3d, true);
break;
case LayoutMode::SceneAndBrowser:
setVisible(DockableWindowId::Scene3d, true);
setVisible(DockableWindowId::Inspector, false);
setVisible(DockableWindowId::SampleBrowser, true);
setVisible(DockableWindowId::SamplesCodeViewer, false);
#ifdef BABYLON_BUILD_PLAYGROUND
setVisible(DockableWindowId::PlaygroundEditor, false);
#endif
setVisible(DockableWindowId::Logs, false);
break;
case LayoutMode::Dev:
for (auto id : dockableWindowsList())
setVisible(id, true);
break;
default:
break;
}
ImGuiUtils::ImGuiRunner::ResetDockLayout();
}
} // namespace BABYLON
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"
HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));
#else
stack.SetResult_Boolean( false );
#endif
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if(stack.m_customState == 0)
{
stack.m_customState++;
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );
hr = CLR_E_RESCHEDULE; NANOCLR_LEAVE();
}
NANOCLR_NOCLEANUP();
#else
NANOCLR_NOCLEANUP_NOLABEL();
#endif
}
<commit_msg>Fix potential issue with Diagnostics_Debugger::Break<commit_after>//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"
HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));
#else
stack.SetResult_Boolean( false );
#endif
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if(stack.m_customState == 0)
{
stack.m_customState++;
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );
hr = CLR_E_RESCHEDULE; NANOCLR_LEAVE();
}
NANOCLR_NOCLEANUP();
#else
(void)stack;
NANOCLR_NOCLEANUP_NOLABEL();
#endif
}
<|endoftext|> |
<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TTree.h"
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/AliTRDv0Monitor.h"
#endif
#include "PWG1/TRD/macros/helper.C"
void AddTRDv0Monitor(AliAnalysisManager *mgr, Char_t *trd, AliAnalysisDataContainer **ci/*, AliAnalysisDataContainer **co*/)
{
Int_t map = ParseOptions(trd);
if(!TSTBIT(map, kV0Monitor)) return;
printf("AddTRDv0Monitor <- [0]=\"%s\" [1]=\"%s\" [2]=\"%s\"\n", ci[0]->GetName(), ci[1]->GetName(), ci[2]->GetName());
AliTRDv0Monitor *v0Mon = new AliTRDv0Monitor((char*()"TRDv0Monitor"));
mgr->AddTask(v0Mon);
v0Mon->SetDebugLevel(0);
//AliLog::SetClassDebugLevel("AliTRDpidRefMaker", 3);
v0Mon->SetMCdata(mgr->GetMCtruthEventHandler());
v0Mon->SetFriends(kTRUE);
//v0Mon->SetSource(AliTRDpidRefMaker::kV0,AliTRDpidRefMaker::kRec);
mgr->ConnectInput( v0Mon, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput( v0Mon, 1, ci[0]);
mgr->ConnectInput( v0Mon, 2, ci[1]);
mgr->ConnectInput( v0Mon, 3, ci[2]);
mgr->ConnectOutput(v0Mon, 1, mgr->CreateContainer(v0Mon->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())));
//mgr->ConnectOutput(v0Mon, 2, mgr->CreateContainer(v0Mon->GetName(), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD.CalibPIDrefMaker", mgr->GetCommonFileName())));
}
<commit_msg>fix cast statement<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TTree.h"
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/AliTRDv0Monitor.h"
#endif
#include "PWG1/TRD/macros/helper.C"
void AddTRDv0Monitor(AliAnalysisManager *mgr, Char_t *trd, AliAnalysisDataContainer **ci/*, AliAnalysisDataContainer **co*/)
{
Int_t map = ParseOptions(trd);
if(!TSTBIT(map, kV0Monitor)) return;
printf("AddTRDv0Monitor <- [0]=\"%s\" [1]=\"%s\" [2]=\"%s\"\n", ci[0]->GetName(), ci[1]->GetName(), ci[2]->GetName());
AliTRDv0Monitor *v0Mon(NULL);;
mgr->AddTask(v0Mon = new AliTRDv0Monitor((char*)"TRDv0Monitor"));
v0Mon->SetDebugLevel(0);
//AliLog::SetClassDebugLevel("AliTRDpidRefMaker", 3);
v0Mon->SetMCdata(mgr->GetMCtruthEventHandler());
v0Mon->SetFriends(kTRUE);
//v0Mon->SetSource(AliTRDpidRefMaker::kV0,AliTRDpidRefMaker::kRec);
mgr->ConnectInput( v0Mon, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput( v0Mon, 1, ci[0]);
mgr->ConnectInput( v0Mon, 2, ci[1]);
mgr->ConnectInput( v0Mon, 3, ci[2]);
mgr->ConnectOutput(v0Mon, 1, mgr->CreateContainer(v0Mon->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())));
//mgr->ConnectOutput(v0Mon, 2, mgr->CreateContainer(v0Mon->GetName(), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD.CalibPIDrefMaker", mgr->GetCommonFileName())));
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestTDx.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This test covers the 3DConnexion device interface.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkCamera.h"
#include "vtkConeSource.h"
#include "vtkProperty.h"
#include "vtkTDxMotionEventInfo.h"
#include "vtkCommand.h"
class myCommand : public vtkCommand
{
public:
myCommand()
{
this->Camera=0;
}
void Execute(vtkObject *caller, unsigned long eventId,
void *callData)
{
cout << "myCommand::Execute()" << endl;
if(eventId==vtkCommand::TDxMotionEvent)
{
vtkTDxMotionEventInfo *i=
static_cast<vtkTDxMotionEventInfo *>(callData);
cout << "x=" << i->X << " y=" << i->Y << " z=" << i->Z
<< " a=" << i->A << " b=" << i->B << " c=" << i->C << endl;
const double sensitivity=0.02;
this->Camera->Roll(i->B*sensitivity);
this->RenderWindowInteractor->Render();
}
else
{
cout << "unexpected VTK event" << endl;
}
}
void SetCamera(vtkCamera *c)
{
this->Camera=c;
}
void SetRenderWindowInteractor(vtkRenderWindowInteractor *i)
{
this->RenderWindowInteractor=i;
}
protected:
vtkCamera *Camera;
vtkRenderWindowInteractor *RenderWindowInteractor;
};
int TestTDx(int argc, char* argv[])
{
vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
iren->SetUseTDx(true);
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->SetMultiSamples(0);
renWin->SetAlphaBitPlanes(1);
iren->SetRenderWindow(renWin);
renWin->Delete();
vtkRenderer *renderer = vtkRenderer::New();
renWin->AddRenderer(renderer);
renderer->Delete();
vtkConeSource *coneSource1=vtkConeSource::New();
vtkPolyDataMapper *coneMapper1=vtkPolyDataMapper::New();
coneMapper1->SetInputConnection(coneSource1->GetOutputPort());
coneSource1->Delete();
vtkActor *coneActor1=vtkActor::New();
coneActor1->SetMapper(coneMapper1);
coneMapper1->Delete();
coneActor1->SetPosition(-2.0,0.0,0.0);
renderer->AddActor(coneActor1);
coneActor1->Delete();
vtkConeSource *coneSource2=vtkConeSource::New();
vtkPolyDataMapper *coneMapper2=vtkPolyDataMapper::New();
coneMapper2->SetInputConnection(coneSource2->GetOutputPort());
coneSource2->Delete();
vtkActor *coneActor2=vtkActor::New();
coneActor2->SetMapper(coneMapper2);
coneMapper2->Delete();
coneActor2->SetPosition(0.0,0.0,0.0);
coneActor2->GetProperty()->SetLighting(false);
renderer->AddActor(coneActor2);
coneActor2->Delete();
vtkConeSource *coneSource3=vtkConeSource::New();
vtkPolyDataMapper *coneMapper3=vtkPolyDataMapper::New();
coneMapper3->SetInputConnection(coneSource3->GetOutputPort());
coneSource3->Delete();
vtkActor *coneActor3=vtkActor::New();
coneActor3->SetMapper(coneMapper3);
coneMapper3->Delete();
coneActor3->SetPosition(2.0,0.0,0.0);
renderer->AddActor(coneActor3);
coneActor3->Delete();
renderer->SetBackground(0.1,0.3,0.0);
renWin->SetSize(200,200);
renWin->Render();
vtkCamera *camera=renderer->GetActiveCamera();
camera->Azimuth(-40.0);
camera->Elevation(20.0);
renderer->ResetCamera();
renWin->Render();
myCommand *c=new myCommand;
c->Register(0);
c->SetCamera(camera);
c->SetRenderWindowInteractor(iren);
iren->AddObserver(vtkCommand::TDxMotionEvent,c,0);
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
iren->Delete();
c->Delete();
c->Delete();
return !retVal;
}
<commit_msg>COMP:Fixed warning.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestTDx.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This test covers the 3DConnexion device interface.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkCamera.h"
#include "vtkConeSource.h"
#include "vtkProperty.h"
#include "vtkTDxMotionEventInfo.h"
#include "vtkCommand.h"
class myCommand : public vtkCommand
{
public:
myCommand()
{
this->Camera=0;
}
void Execute(vtkObject *caller, unsigned long eventId,
void *vtkNotUsed(callData))
{
cout << "myCommand::Execute()" << endl;
if(eventId==vtkCommand::TDxMotionEvent)
{
vtkTDxMotionEventInfo *i=
static_cast<vtkTDxMotionEventInfo *>(callData);
cout << "x=" << i->X << " y=" << i->Y << " z=" << i->Z
<< " a=" << i->A << " b=" << i->B << " c=" << i->C << endl;
const double sensitivity=0.02;
this->Camera->Roll(i->B*sensitivity);
this->RenderWindowInteractor->Render();
}
else
{
cout << "unexpected VTK event" << endl;
}
}
void SetCamera(vtkCamera *c)
{
this->Camera=c;
}
void SetRenderWindowInteractor(vtkRenderWindowInteractor *i)
{
this->RenderWindowInteractor=i;
}
protected:
vtkCamera *Camera;
vtkRenderWindowInteractor *RenderWindowInteractor;
};
int TestTDx(int argc, char* argv[])
{
vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
iren->SetUseTDx(true);
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->SetMultiSamples(0);
renWin->SetAlphaBitPlanes(1);
iren->SetRenderWindow(renWin);
renWin->Delete();
vtkRenderer *renderer = vtkRenderer::New();
renWin->AddRenderer(renderer);
renderer->Delete();
vtkConeSource *coneSource1=vtkConeSource::New();
vtkPolyDataMapper *coneMapper1=vtkPolyDataMapper::New();
coneMapper1->SetInputConnection(coneSource1->GetOutputPort());
coneSource1->Delete();
vtkActor *coneActor1=vtkActor::New();
coneActor1->SetMapper(coneMapper1);
coneMapper1->Delete();
coneActor1->SetPosition(-2.0,0.0,0.0);
renderer->AddActor(coneActor1);
coneActor1->Delete();
vtkConeSource *coneSource2=vtkConeSource::New();
vtkPolyDataMapper *coneMapper2=vtkPolyDataMapper::New();
coneMapper2->SetInputConnection(coneSource2->GetOutputPort());
coneSource2->Delete();
vtkActor *coneActor2=vtkActor::New();
coneActor2->SetMapper(coneMapper2);
coneMapper2->Delete();
coneActor2->SetPosition(0.0,0.0,0.0);
coneActor2->GetProperty()->SetLighting(false);
renderer->AddActor(coneActor2);
coneActor2->Delete();
vtkConeSource *coneSource3=vtkConeSource::New();
vtkPolyDataMapper *coneMapper3=vtkPolyDataMapper::New();
coneMapper3->SetInputConnection(coneSource3->GetOutputPort());
coneSource3->Delete();
vtkActor *coneActor3=vtkActor::New();
coneActor3->SetMapper(coneMapper3);
coneMapper3->Delete();
coneActor3->SetPosition(2.0,0.0,0.0);
renderer->AddActor(coneActor3);
coneActor3->Delete();
renderer->SetBackground(0.1,0.3,0.0);
renWin->SetSize(200,200);
renWin->Render();
vtkCamera *camera=renderer->GetActiveCamera();
camera->Azimuth(-40.0);
camera->Elevation(20.0);
renderer->ResetCamera();
renWin->Render();
myCommand *c=new myCommand;
c->Register(0);
c->SetCamera(camera);
c->SetRenderWindowInteractor(iren);
iren->AddObserver(vtkCommand::TDxMotionEvent,c,0);
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
iren->Delete();
c->Delete();
c->Delete();
return !retVal;
}
<|endoftext|> |
<commit_before>/*
TLD's work well w/ features (keypts) low-level features
- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??
*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>
#include <opencv2/opencv.hpp>
#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;
int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;
int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;
struct state_t {
lcm_t *lcm;
GMainLoop *mainloop;
BotParam *param;
BotFrames *frames;
int counter;
// Img
cv::Mat img;
// utimes for image
int64_t img_utime;
// UI selection of desired object
Rect selection, selection_virtual;
Point origin, origin_virtual;
bool selectObject, selectObject_virtual;
state_t () {
// LCM, BotFrames, BotParam inits
lcm = bot_lcm_get_global(NULL);
param = bot_param_new_from_server(lcm, 1);
frames = bot_frames_get_global (lcm, param);
// Counter for debug prints
counter = 0;
selectObject = false;
selectObject_virtual = false;
}
~state_t () {
lcm_destroy(lcm);
}
};
state_t * state = NULL;
struct MouseEvent {
MouseEvent() { event = -1; buttonState = 0; }
Point pt;
int event;
int buttonState;
};
MouseEvent mouse;
static void onMouse(int event, int x, int y, int flags, void* userdata) {
MouseEvent* data = (MouseEvent*)userdata;
float sx = 1.f / WINDOW_WIDTH ;
float sy = 1.f / WINDOW_HEIGHT;
if (state->selectObject) {
state->selection.x = MIN(x, state->origin.x);
state->selection.y = MIN(y, state->origin.y);
state->selection.width = std::abs(x - state->origin.x);
state->selection.height = std::abs(y - state->origin.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
if (state->selectObject_virtual) {
state->selection_virtual.x = MIN(x, state->origin_virtual.x);
state->selection_virtual.y = MIN(y, state->origin_virtual.y);
state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
switch (event) {
case CV_EVENT_RBUTTONDOWN:
state->origin_virtual = Point(x, y);
state->selection_virtual = Rect(x, y, 0, 0);
state->selectObject_virtual = true;
break;
case CV_EVENT_RBUTTONUP:
state->selectObject_virtual = false;
std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;
perception_image_roi_t img_vselection;
img_vselection.utime = state->img_utime;
img_vselection.object_id = OBJECT_ID;
img_vselection.feature_id = -1; // FEATURE_ID;
img_vselection.roi.x = state->selection_virtual.x * sx;
img_vselection.roi.y = state->selection_virtual.y * sy;
img_vselection.roi.width = state->selection_virtual.width * sx;
img_vselection.roi.height = state->selection_virtual.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);
destroyWindow(WINDOW_NAME);
state->img = cv::Mat();
break;
case CV_EVENT_LBUTTONDOWN:
state->origin = Point(x, y);
state->selection = Rect(x, y, 0, 0);
state->selectObject = true;
// reset virtual feature
state->selection_virtual = Rect(0,0,0,0);
break;
case CV_EVENT_LBUTTONUP:
state->selectObject = false;
std::cerr << "SEND selection: " << state->img_utime << " - " <<
state->selection.x << " " << state->selection.y << " " <<
state->selection.width << " " << state->selection.height << std::endl;
perception_image_roi_t img_selection;
img_selection.utime = state->img_utime;
img_selection.object_id = OBJECT_ID;
img_selection.feature_id = 1; // FEATURE_ID;
img_selection.roi.x = state->selection.x * sx;
img_selection.roi.y = state->selection.y * sy;
img_selection.roi.width = state->selection.width * sx;
img_selection.roi.height = state->selection.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
}
return;
}
void INThandler(int sig)
{
printf("Exiting\n");
if (state) delete state;
exit(0);
}
void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
int ch = msg->row_stride / (msg->width);
if (img.empty() || img.rows != msg->height || img.cols != msg->width)
if (ch == 3)
img.create(msg->height, msg->width, CV_8UC3);
else
img.create(msg->height, msg->width, CV_8UC1);
std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;
// extract image data
switch (msg->pixelformat) {
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
cv::cvtColor(img, img, CV_RGB2BGR);
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
// for some reason msg->row_stride is 0, so we use msg->width instead.
if (ch == 3) {
jpeg_decompress_8u_rgb(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width * ch);
cv::cvtColor(img, img, CV_RGB2BGR);
} else {
jpeg_decompress_8u_gray(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width);
}
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
break;
default:
fprintf(stderr, "Unrecognized image format\n");
break;
}
return;
}
static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
const bot_core_image_t *msg,
void *user_data ) {
if (!msg->width || !msg->height) return;
if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
MAX_IMAGE_WIDTH = msg->width;
MAX_IMAGE_HEIGHT = msg->height;
}
state_t* state = (state_t*) user_data;
if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
assert(0);
} else {
std::cerr << "One time creation of image" << std::endl;
state->img.create(msg->height, msg->width, CV_8UC3);
}
}
decode_image(msg, state->img);
state->img_utime = msg->utime;
cv::namedWindow( WINDOW_NAME );
cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
state->selectObject_virtual = false;
state->selectObject = false;
return;
}
struct TLDSegmenterOptions {
bool vDEBUG;
std::string vCHANNEL;
TLDSegmenterOptions () :
vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;
int main(int argc, char** argv)
{
std::cout << "============= QUICK MODES ===================\n";
std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
std::cout << "=============================================\n";
ConciseArgs opt(argc, (char**)argv);
opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
opt.add(options.vDEBUG, "d", "debug","Debug mode");
opt.parse();
std::cerr << "=========== TLD Tracker ============" << std::endl;
std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
std::cerr << "===============================================" << std::endl;
// Install signal handler to free data.
signal(SIGINT, INThandler);
// Param server, botframes
state = new state_t();
// cv::namedWindow( WINDOW_NAME );
// cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
// Subscriptions
bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);
// Install signal handler to free data.
signal(SIGINT, INThandler);
while(1) {
unsigned char c = cv::waitKey(1) & 0xff;
lcm_handle(state->lcm);
if (c == 'q') {
break;
// } else if (c == 'd') {
// FEATURE_ID++;
// } else if (c == 'a') {
// FEATURE_ID--;
} else if (c == 'w') {
OBJECT_ID++;
} else if (c == 's') {
OBJECT_ID--;
}
// UI handling
if (!state->img.empty()) {
cv::Mat display;
cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
if (state->selection.width > 0 && state->selection.height > 0) {
cv::Mat roi(display, state->selection);
rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
// bitwise_not(roi, roi);
}
if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {
cv::Mat roi(display, state->selection_virtual);
rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
// bitwise_not(roi, roi);
}
// Show OBJECT_ID, FEATURE_ID
cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);
imshow(WINDOW_NAME, display);
}
}
if (state) delete state;
return 0;
}
<commit_msg>modified tld-segmenter to work with live stream<commit_after>/*
TLD's work well w/ features (keypts) low-level features
- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??
*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>
#include <opencv2/opencv.hpp>
#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;
int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;
int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;
struct state_t {
lcm_t *lcm;
GMainLoop *mainloop;
BotParam *param;
BotFrames *frames;
int counter;
// Img
cv::Mat img;
// utimes for image
int64_t img_utime;
// UI selection of desired object
Rect selection, selection_virtual;
Point origin, origin_virtual;
bool selectObject, selectObject_virtual;
state_t () {
// LCM, BotFrames, BotParam inits
lcm = bot_lcm_get_global(NULL);
param = bot_param_new_from_server(lcm, 1);
frames = bot_frames_get_global (lcm, param);
// Counter for debug prints
counter = 0;
selectObject = false;
selectObject_virtual = false;
}
~state_t () {
lcm_destroy(lcm);
}
};
state_t * state = NULL;
struct MouseEvent {
MouseEvent() { event = -1; buttonState = 0; }
Point pt;
int event;
int buttonState;
};
MouseEvent mouse;
static void onMouse(int event, int x, int y, int flags, void* userdata) {
MouseEvent* data = (MouseEvent*)userdata;
float sx = 1.f / WINDOW_WIDTH ;
float sy = 1.f / WINDOW_HEIGHT;
if (state->selectObject) {
state->selection.x = MIN(x, state->origin.x);
state->selection.y = MIN(y, state->origin.y);
state->selection.width = std::abs(x - state->origin.x);
state->selection.height = std::abs(y - state->origin.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
if (state->selectObject_virtual) {
state->selection_virtual.x = MIN(x, state->origin_virtual.x);
state->selection_virtual.y = MIN(y, state->origin_virtual.y);
state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
switch (event) {
case CV_EVENT_RBUTTONDOWN:
state->origin_virtual = Point(x, y);
state->selection_virtual = Rect(x, y, 0, 0);
state->selectObject_virtual = true;
break;
case CV_EVENT_RBUTTONUP:
state->selectObject_virtual = false;
std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;
perception_image_roi_t img_vselection;
img_vselection.utime = state->img_utime;
img_vselection.object_id = OBJECT_ID;
img_vselection.feature_id = -1; // FEATURE_ID;
img_vselection.roi.x = state->selection_virtual.x * sx;
img_vselection.roi.y = state->selection_virtual.y * sy;
img_vselection.roi.width = state->selection_virtual.width * sx;
img_vselection.roi.height = state->selection_virtual.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
case CV_EVENT_LBUTTONDOWN:
state->origin = Point(x, y);
state->selection = Rect(x, y, 0, 0);
state->selectObject = true;
// reset virtual feature
state->selection_virtual = Rect(0,0,0,0);
break;
case CV_EVENT_LBUTTONUP:
state->selectObject = false;
std::cerr << "SEND selection: " << state->img_utime << " - " <<
state->selection.x << " " << state->selection.y << " " <<
state->selection.width << " " << state->selection.height << std::endl;
perception_image_roi_t img_selection;
img_selection.utime = state->img_utime;
img_selection.object_id = OBJECT_ID;
img_selection.feature_id = 1; // FEATURE_ID;
img_selection.roi.x = state->selection.x * sx;
img_selection.roi.y = state->selection.y * sy;
img_selection.roi.width = state->selection.width * sx;
img_selection.roi.height = state->selection.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
}
return;
}
void INThandler(int sig)
{
printf("Exiting\n");
if (state) delete state;
exit(0);
}
void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
int ch = msg->row_stride / (msg->width);
if (img.empty() || img.rows != msg->height || img.cols != msg->width)
if (ch == 3)
img.create(msg->height, msg->width, CV_8UC3);
else
img.create(msg->height, msg->width, CV_8UC1);
std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;
// extract image data
switch (msg->pixelformat) {
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
cv::cvtColor(img, img, CV_RGB2BGR);
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
// for some reason msg->row_stride is 0, so we use msg->width instead.
if (ch == 3) {
jpeg_decompress_8u_rgb(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width * ch);
cv::cvtColor(img, img, CV_RGB2BGR);
} else {
jpeg_decompress_8u_gray(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width);
}
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
break;
default:
fprintf(stderr, "Unrecognized image format\n");
break;
}
return;
}
static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
const bot_core_image_t *msg,
void *user_data ) {
if (!msg->width || !msg->height) return;
if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
MAX_IMAGE_WIDTH = msg->width;
MAX_IMAGE_HEIGHT = msg->height;
}
state_t* state = (state_t*) user_data;
if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
assert(0);
} else {
std::cerr << "One time creation of image" << std::endl;
state->img.create(msg->height, msg->width, CV_8UC3);
}
}
decode_image(msg, state->img);
state->img_utime = msg->utime;
return;
}
struct TLDSegmenterOptions {
bool vDEBUG;
std::string vCHANNEL;
TLDSegmenterOptions () :
vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;
int main(int argc, char** argv)
{
std::cout << "============= QUICK MODES ===================\n";
std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
std::cout << "=============================================\n";
ConciseArgs opt(argc, (char**)argv);
opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
opt.add(options.vDEBUG, "d", "debug","Debug mode");
opt.parse();
std::cerr << "=========== TLD Tracker ============" << std::endl;
std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
std::cerr << "===============================================" << std::endl;
// Install signal handler to free data.
signal(SIGINT, INThandler);
// Param server, botframes
state = new state_t();
cv::namedWindow( WINDOW_NAME );
cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
// Subscriptions
bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);
// Install signal handler to free data.
signal(SIGINT, INThandler);
while(1) {
unsigned char c = cv::waitKey(1) & 0xff;
lcm_handle(state->lcm);
if (c == 'q') {
break;
// } else if (c == 'd') {
// FEATURE_ID++;
// } else if (c == 'a') {
// FEATURE_ID--;
} else if (c == 'w') {
OBJECT_ID++;
} else if (c == 's') {
OBJECT_ID--;
}
// UI handling
if (!state->img.empty()) {
cv::Mat display;
cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
if (state->selection.width > 0 && state->selection.height > 0) {
cv::Mat roi(display, state->selection);
rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
// bitwise_not(roi, roi);
}
if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {
cv::Mat roi(display, state->selection_virtual);
rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
// bitwise_not(roi, roi);
}
// Show OBJECT_ID, FEATURE_ID
cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);
imshow(WINDOW_NAME, display);
}
}
if (state) delete state;
return 0;
}
<|endoftext|> |
<commit_before>
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1996, California Institute of Technology.
// ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGH
// in this directory.
//
// Author: Todd Karakashian, NASA/Jet Propulsion Laboratory
// [email protected]
//
// $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server
//
// $Log: escaping.cc,v $
// Revision 1.2 1997/02/14 02:18:16 jimg
// Added to DODS core
//
// Revision 1.2 1996/10/07 21:15:17 todd
// Changes escape character to % from _.
//
// Revision 1.1 1996/09/24 22:38:16 todd
// Initial revision
//
//
/////////////////////////////////////////////////////////////////////////////
// These two routines are for escaping/unescaping strings that are identifiers
// in DODS
// id2dods() -- escape (using WWW hex codes) non-allowable characters in a
// DODS identifier
// dods2id() -- given an WWW hexcode escaped identifier, restore it
//
// These two routines are for escaping/unescaping strings storing attribute
// values. They use traditional octal escapes (\nnn) because they are
// intended to be viewed by a user
// escattr() -- escape (using traditional octal backslash) non-allowable
// characters in the value of a DODS attribute
// unescattr() -- given an octally escaped string, restore it
//
// These are routines used by the above, not intended to be called directly:
//
// hexstring()
// unhexstring()
// octstring()
// unoctstring()
//
// -Todd
#include <strstream.h>
#include <iomanip.h>
#include <String.h>
#include <mfhdf.h>
#include <hdfclass.h>
#include "HDFStructure.h"
#include "HDFArray.h"
#include "hdfutil.h"
#include "dhdferr.h"
String hexstring(int val) {
static char buf[hdfclass::MAXSTR];
ostrstream(buf,hdfclass::MAXSTR) << hex << setw(2) << setfill('0') <<
val << ends;
return (String)buf;
}
char unhexstring(String s) {
int val;
static char buf[hdfclass::MAXSTR];
strcpy(buf,(const char *)s);
istrstream(buf,hdfclass::MAXSTR) >> hex >> val;
return (char)val;
}
String octstring(int val) {
static char buf[hdfclass::MAXSTR];
ostrstream(buf,hdfclass::MAXSTR) << oct << setw(3) << setfill('0') <<
val << ends;
return (String)buf;
}
char unoctstring(String s) {
int val;
static char buf[hdfclass::MAXSTR];
strcpy(buf,(const char *)s);
istrstream(buf,hdfclass::MAXSTR) >> oct >> val;
return (char)val;
}
// replace characters that are not allowed in DODS identifiers
String id2dods(String s) {
static Regex badregx = "[^0-9a-zA-Z_%]";
const char ESC = '%';
int index;
while ( (index = s.index(badregx)) >= 0)
s.at(index,1) = ESC + hexstring(toascii(s[index]));
if (isdigit(s[0]))
s.before(0) = '_';
return s;
}
String dods2id(String s) {
static Regex escregx = "%[0-7][0-9a-fA-F]";
int index;
while ( (index = s.index(escregx)) >= 0)
s.at(index,3) = unhexstring(s.at(index+1,2));
return s;
}
// Escape non-printable characters and quotes from an HDF attribute
String escattr(String s) {
static Regex nonprintable = "[^ !-~]";
const char ESC = '\\';
const char QUOTE = '\"';
const String ESCQUOTE = (String)ESC + (String)QUOTE;
// escape non-printing characters with octal escape
int index = 0;
while ( (index = s.index(nonprintable)) >= 0)
s.at(index,1) = ESC + octstring(toascii(s[index]));
// escape " with backslash
index = 0;
while ( (index = s.index(QUOTE,index)) >= 0) {
s.at(index,1) = ESCQUOTE;
index += ESCQUOTE.length();
}
return s;
}
// Un-escape special characters, quotes and backslashes from an HDF attribute.
// Note: A regex to match one \ must be defined as
// Regex foo = "\\\\";
// because both C++ strings and libg++ regex's also employ \ as
// an escape character!
String unescattr(String s) {
static Regex escregx = "\\\\[01][0-7][0-7]"; // matches 4 characters
static Regex escquoteregex = "[^\\\\]\\\\\""; // matches 3 characters
static Regex escescregex = "\\\\\\\\"; // matches 2 characters
const char ESC = '\\';
const char QUOTE = '\"';
const String ESCQUOTE = (String)ESC + (String)QUOTE;
// unescape any octal-escaped ASCII characters
int index = 0;
while ( (index = s.index(escregx,index)) >= 0) {
s.at(index,4) = unoctstring(s.at(index+1,3));
index++;
}
// unescape any escaped quotes
index = 0;
while ( (index = s.index(escquoteregex,index)) >= 0) {
s.at(index+1,2) = QUOTE;
index++;
}
// unescape any escaped backslashes
index = 0;
while ( (index = s.index(escescregex,index)) >= 0) {
s.at(index,2) = ESC;
index++;
}
return s;
}
<commit_msg>Removed reliance on the dods-hdf code. Introduced a const int MAXSTR with value 256. This matches the length of ID_MAX in the parser.h header (which I did not include since it defines a lot of software that is irrelevant to this module).<commit_after>
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1996, California Institute of Technology.
// ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGH
// in this directory.
//
// Author: Todd Karakashian, NASA/Jet Propulsion Laboratory
// [email protected]
//
// $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server
//
// $Log: escaping.cc,v $
// Revision 1.3 1997/02/14 02:24:44 jimg
// Removed reliance on the dods-hdf code.
// Introduced a const int MAXSTR with value 256. This matches the length of
// ID_MAX in the parser.h header (which I did not include since it defines
// a lot of software that is irrelevant to this module).
//
// Revision 1.2 1997/02/14 02:18:16 jimg
// Added to DODS core
//
// Revision 1.2 1996/10/07 21:15:17 todd
// Changes escape character to % from _.
//
// Revision 1.1 1996/09/24 22:38:16 todd
// Initial revision
//
//
/////////////////////////////////////////////////////////////////////////////
// These two routines are for escaping/unescaping strings that are identifiers
// in DODS
// id2dods() -- escape (using WWW hex codes) non-allowable characters in a
// DODS identifier
// dods2id() -- given an WWW hexcode escaped identifier, restore it
//
// These two routines are for escaping/unescaping strings storing attribute
// values. They use traditional octal escapes (\nnn) because they are
// intended to be viewed by a user
// escattr() -- escape (using traditional octal backslash) non-allowable
// characters in the value of a DODS attribute
// unescattr() -- given an octally escaped string, restore it
//
// These are routines used by the above, not intended to be called directly:
//
// hexstring()
// unhexstring()
// octstring()
// unoctstring()
//
// -Todd
#include <ctype.h>
#include <strstream.h>
#include <iomanip.h>
#include <String.h>
#if 0
#include <mfhdf.h>
#include <hdfclass.h>
#include "HDFStructure.h"
#include "HDFArray.h"
#include "hdfutil.h"
#include "dhdferr.h"
#endif
const int MAXSTR = 256;
String hexstring(int val) {
static char buf[MAXSTR];
ostrstream(buf,MAXSTR) << hex << setw(2) << setfill('0') <<
val << ends;
return (String)buf;
}
char unhexstring(String s) {
int val;
static char buf[MAXSTR];
strcpy(buf,(const char *)s);
istrstream(buf,MAXSTR) >> hex >> val;
return (char)val;
}
String octstring(int val) {
static char buf[MAXSTR];
ostrstream(buf,MAXSTR) << oct << setw(3) << setfill('0') <<
val << ends;
return (String)buf;
}
char unoctstring(String s) {
int val;
static char buf[MAXSTR];
strcpy(buf,(const char *)s);
istrstream(buf,MAXSTR) >> oct >> val;
return (char)val;
}
// replace characters that are not allowed in DODS identifiers
String id2dods(String s) {
static Regex badregx = "[^0-9a-zA-Z_%]";
const char ESC = '%';
int index;
while ( (index = s.index(badregx)) >= 0)
s.at(index,1) = ESC + hexstring(toascii(s[index]));
if (isdigit(s[0]))
s.before(0) = '_';
return s;
}
String dods2id(String s) {
static Regex escregx = "%[0-7][0-9a-fA-F]";
int index;
while ( (index = s.index(escregx)) >= 0)
s.at(index,3) = unhexstring(s.at(index+1,2));
return s;
}
// Escape non-printable characters and quotes from an HDF attribute
String escattr(String s) {
static Regex nonprintable = "[^ !-~]";
const char ESC = '\\';
const char QUOTE = '\"';
const String ESCQUOTE = (String)ESC + (String)QUOTE;
// escape non-printing characters with octal escape
int index = 0;
while ( (index = s.index(nonprintable)) >= 0)
s.at(index,1) = ESC + octstring(toascii(s[index]));
// escape " with backslash
index = 0;
while ( (index = s.index(QUOTE,index)) >= 0) {
s.at(index,1) = ESCQUOTE;
index += ESCQUOTE.length();
}
return s;
}
// Un-escape special characters, quotes and backslashes from an HDF attribute.
// Note: A regex to match one \ must be defined as
// Regex foo = "\\\\";
// because both C++ strings and libg++ regex's also employ \ as
// an escape character!
String unescattr(String s) {
static Regex escregx = "\\\\[01][0-7][0-7]"; // matches 4 characters
static Regex escquoteregex = "[^\\\\]\\\\\""; // matches 3 characters
static Regex escescregex = "\\\\\\\\"; // matches 2 characters
const char ESC = '\\';
const char QUOTE = '\"';
const String ESCQUOTE = (String)ESC + (String)QUOTE;
// unescape any octal-escaped ASCII characters
int index = 0;
while ( (index = s.index(escregx,index)) >= 0) {
s.at(index,4) = unoctstring(s.at(index+1,3));
index++;
}
// unescape any escaped quotes
index = 0;
while ( (index = s.index(escquoteregex,index)) >= 0) {
s.at(index+1,2) = QUOTE;
index++;
}
// unescape any escaped backslashes
index = 0;
while ( (index = s.index(escescregex,index)) >= 0) {
s.at(index,2) = ESC;
index++;
}
return s;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.