text stringlengths 54 60.6k |
|---|
<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
//
// Demo code (advanced), about
//
// - using the SCM semi-empirical model for deformable soil
// - using a deformable tire
#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono/physics/ChLoadContainer.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChSystemDEM.h"
#include "chrono_irrlicht/ChIrrApp.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"
#include "chrono_vehicle/wheeled_vehicle/tire/ReissnerTire.h"
#include "chrono_mkl/ChSolverMKL.h"
using namespace chrono;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace irr;
int main(int argc, char* argv[]) {
// Global parameter for tire:
double tire_rad = 0.5;
double tire_vel_z0 = -3;
ChVector<> tire_center(0, tire_rad, 0);
double tire_w0 = tire_vel_z0/tire_rad;
// Create a Chrono::Engine physical system
ChSystemDEM my_system;
// Create the Irrlicht visualization (open the Irrlicht device,
// bind a simple user interface, etc. etc.)
ChIrrApp application(&my_system, L"Deformable soil and deformable tire", core::dimension2d<u32>(1280, 720), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0));
application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512,
video::SColorf(0.8f, 0.8f, 1.0f));
std::shared_ptr<ChBody> mtruss (new ChBody);
mtruss->SetBodyFixed(true);
my_system.Add(mtruss);
//
// CREATE A DEFORMABLE TIRE
//
// the rim:
std::shared_ptr<ChBody> mrim (new ChBody);
my_system.Add(mrim);
mrim->SetMass(100);
mrim->SetInertiaXX(ChVector<>(2,2,2));
mrim->SetPos(tire_center + ChVector<>(0,0.2,0));
mrim->SetRot(Q_from_AngAxis(CH_C_PI_2, VECT_Z));
// the tire:
std::shared_ptr<ChReissnerTire> tire_reissner;
tire_reissner = std::make_shared<ReissnerTire>(vehicle::GetDataFile("hmmwv/tire/HMMWV_ReissnerTire.json"));
tire_reissner->EnablePressure(false);
tire_reissner->EnableContact(true);
tire_reissner->SetContactSurfaceType(ChDeformableTire::TRIANGLE_MESH);
tire_reissner->EnableRimConnection(true);
tire_reissner->Initialize(mrim, LEFT);
tire_reissner->SetVisualizationType(VisualizationType::MESH);
// the engine that rotates the rim:
std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine);
myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM);
myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_ROTATION);
myengine->Set_rot_funct( std::make_shared<ChFunction_Ramp>(0, CH_C_PI / 4.0)); // CH_C_PI / 4.0) ); // phase, speed
myengine->Initialize(mrim, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y)));
my_system.Add(myengine);
//
// THE DEFORMABLE TERRAIN
//
// Create the 'deformable terrain' object
vehicle::DeformableTerrain mterrain(&my_system);
// Optionally, displace/tilt/rotate the terrain reference plane:
mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.3)));
// Initialize the geometry of the soil: use either a regular grid:
mterrain.Initialize(0.2,1.5,5,20,60);
// or use a height map:
//mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3);
// Set the soil terramechanical parameters:
mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi
0, // Bekker Kc
1.1, // Bekker n exponent
0, // Mohr cohesive limit (Pa)
30, // Mohr friction limit (degrees)
0.01,// Janosi shear coefficient (m)
5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi
);
mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut
mterrain.SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut
0.8, // displaced material vs downward pressed material.
5, // number of erosion refinements per timestep
10); // number of concentric vertex selections subject to erosion
// Turn on the automatic level of detail refinement, so a coarse terrain mesh
// is automatically improved by adding more points under the wheel contact patch:
mterrain.SetAutomaticRefinement(true);
mterrain.SetAutomaticRefinementResolution(0.02);
// Set some visualization parameters: either with a texture, or with falsecolor plot, etc.
//mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2);
mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8);
mterrain.GetMesh()->SetWireframe(true);
// ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
application.AssetBindAll();
// ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
application.AssetUpdateAll();
// Use shadows in realtime view
application.AddShadowAll();
// ==IMPORTANT!== Mark completion of system construction
my_system.SetupInitial();
//
// THE SOFT-REAL-TIME CYCLE
//
// change the solver to MKL:
GetLog() << "Using MKL solver\n";
ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>;
ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>;
my_system.ChangeSolverStab(mkl_solver_stab);
my_system.ChangeSolverSpeed(mkl_solver_speed);
mkl_solver_speed->SetSparsityPatternLock(true);
mkl_solver_stab->SetSparsityPatternLock(true);
// Change the timestepper to HHT:
my_system.SetIntegrationType(ChSystem::INT_HHT);
auto integrator = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper());
integrator->SetAlpha(-0.2);
integrator->SetMaxiters(8);
integrator->SetAbsTolerances(5e-05, 1.8e00);
integrator->SetMode(ChTimestepperHHT::POSITION);
integrator->SetModifiedNewton(false);
integrator->SetScaling(true);
integrator->SetVerbose(true);
application.SetTimestep(0.001);
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
application.DoStep();
ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180);
application.EndScene();
}
return 0;
}
<commit_msg>Improve demo for deformable soil/ deformable tire<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
//
// Demo code (advanced), about
//
// - using the SCM semi-empirical model for deformable soil
// - using a deformable tire
#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono/physics/ChLoadContainer.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChSystemDEM.h"
#include "chrono_irrlicht/ChIrrApp.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"
#include "chrono_vehicle/wheeled_vehicle/tire/ReissnerTire.h"
#include "chrono_mkl/ChSolverMKL.h"
using namespace chrono;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace irr;
int main(int argc, char* argv[]) {
// Global parameter for tire:
double tire_rad = 0.5;
double tire_vel_z0 = -3;
ChVector<> tire_center(0, tire_rad, 0);
double tire_w0 = tire_vel_z0/tire_rad;
// Create a Chrono::Engine physical system
ChSystemDEM my_system;
// Create the Irrlicht visualization (open the Irrlicht device,
// bind a simple user interface, etc. etc.)
ChIrrApp application(&my_system, L"Deformable soil and deformable tire", core::dimension2d<u32>(1280, 720), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0));
application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512,
video::SColorf(0.8f, 0.8f, 1.0f));
std::shared_ptr<ChBody> mtruss (new ChBody);
mtruss->SetBodyFixed(true);
my_system.Add(mtruss);
//
// CREATE A DEFORMABLE TIRE
//
// the rim:
std::shared_ptr<ChBody> mrim (new ChBody);
my_system.Add(mrim);
mrim->SetMass(100);
mrim->SetInertiaXX(ChVector<>(2,2,2));
mrim->SetPos(tire_center + ChVector<>(0,0.2,0));
mrim->SetRot(Q_from_AngAxis(CH_C_PI_2, VECT_Z));
// the tire:
std::shared_ptr<ChReissnerTire> tire_reissner;
tire_reissner = std::make_shared<ReissnerTire>(vehicle::GetDataFile("hmmwv/tire/HMMWV_ReissnerTire.json"));
tire_reissner->EnablePressure(false);
tire_reissner->EnableContact(true);
tire_reissner->SetContactSurfaceType(ChDeformableTire::TRIANGLE_MESH);
tire_reissner->EnableRimConnection(true);
tire_reissner->Initialize(mrim, LEFT);
tire_reissner->SetVisualizationType(VisualizationType::MESH);
// the engine that rotates the rim:
std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine);
myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM);
myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_ROTATION);
myengine->Set_rot_funct( std::make_shared<ChFunction_Ramp>(0, CH_C_PI / 4.0)); // CH_C_PI / 4.0) ); // phase, speed
myengine->Initialize(mrim, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y)));
my_system.Add(myengine);
//
// THE DEFORMABLE TERRAIN
//
// Create the 'deformable terrain' object
vehicle::DeformableTerrain mterrain(&my_system);
// Optionally, displace/tilt/rotate the terrain reference plane:
mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.3)));
// Initialize the geometry of the soil: use either a regular grid:
mterrain.Initialize(0.2,1.5,5,20,60);
// or use a height map:
//mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3);
// Set the soil terramechanical parameters:
mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi
0, // Bekker Kc
1.1, // Bekker n exponent
0, // Mohr cohesive limit (Pa)
30, // Mohr friction limit (degrees)
0.01,// Janosi shear coefficient (m)
5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi
);
mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut
mterrain.SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut
0.8, // displaced material vs downward pressed material.
5, // number of erosion refinements per timestep
10); // number of concentric vertex selections subject to erosion
// Turn on the automatic level of detail refinement, so a coarse terrain mesh
// is automatically improved by adding more points under the wheel contact patch:
mterrain.SetAutomaticRefinement(true);
mterrain.SetAutomaticRefinementResolution(0.02);
// Set some visualization parameters: either with a texture, or with falsecolor plot, etc.
//mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2);
mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8);
//mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8);
mterrain.GetMesh()->SetWireframe(true);
// ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
application.AssetBindAll();
// ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
application.AssetUpdateAll();
// Use shadows in realtime view
application.AddShadowAll();
// ==IMPORTANT!== Mark completion of system construction
my_system.SetupInitial();
//
// THE SOFT-REAL-TIME CYCLE
//
// change the solver to MKL:
GetLog() << "Using MKL solver\n";
ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>;
ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>;
my_system.ChangeSolverStab(mkl_solver_stab);
my_system.ChangeSolverSpeed(mkl_solver_speed);
mkl_solver_speed->SetSparsityPatternLock(true);
mkl_solver_stab->SetSparsityPatternLock(true);
// Change the timestepper to HHT:
my_system.SetIntegrationType(ChSystem::INT_HHT);
auto integrator = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper());
integrator->SetAlpha(-0.2);
integrator->SetMaxiters(8);
integrator->SetAbsTolerances(5e-05, 1.8e00);
integrator->SetMode(ChTimestepperHHT::POSITION);
integrator->SetModifiedNewton(false);
integrator->SetScaling(true);
integrator->SetVerbose(true);
application.SetTimestep(0.002);
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
application.DoStep();
ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180);
application.EndScene();
}
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Note this contains experimental highlighting for J.
* Current implementation attempts to suppport:
* strings, numbers, primitive nouns, control words,
* comments, multiline Note.
* There is currently no context aware support (for example to show that control
* words are not valid outside an explicit definition).
*/
#include "base/state.h"
#include "high/high.h"
// ---------------------------------------------------------------------
Highj::Highj(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
init();
HighlightingRule rule;
QStringList controlPatterns;
controlPatterns
<< "\\bassert\\." << "\\bbreak\\." << "\\bcontinue\\."
<< "\\breturn\\." << "\\bdo\\." << "\\bif\\."
<< "\\belse\\." << "\\belseif\\." << "\\bend\\."
<< "\\bfor\\." << "\\bselect\\." << "\\bcase\\."
<< "\\bfcase\\." << "\\bthrow\\." << "\\btry\\."
<< "\\bcatch\\." << "\\bcatchd\\." << "\\bcatcht\\."
<< "\\bwhile\\." << "\\bwhilst\\." << "\\bfor_[a-zA-Z][a-zA-Z0-9_]*\\."
<< "\\bgoto_[a-zA-Z][a-zA-Z0-9_]*\\." << "\\blabel_[a-zA-Z][a-zA-Z0-9_]*\\."
;
foreach (const QString &pattern, controlPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = controlFormat;
highlightingRules.append(rule);
}
rule.pattern = QRegExp("\\b[_0-9][_0-9\\.a-zA-Z]*\\b");
rule.format = numberFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("(_\\.|a\\.|a:)(?![\\.\\:])");
rule.format = nounFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("((_?[0-9]:)|(\\bp\\.\\.)|(\\b[AcCeEiIjLopr]\\.)|(\\b[ipqsux]:)|(\\{::)|([\\<\\>\\+\\*\\-\\%\\^\\$\\~\\|\\,\\#\\{\\}\\\"\\;\\?]\\.)|([\\<\\>\\_\\+\\*\\-\\%\\$\\~\\|\\,\\;\\#\\/\\\\[\\{\\}\\\"]:)|([\\<\\>\\=\\+\\*\\-\\%\\^\\$\\|\\,\\;\\#\\!\\[\\]\\{\\?]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("((_?[0-9]:)| \
(\\bp\\.\\.)| \
(\\b[AcCeEiIjLopr]\\.)| \
(\\b[ipqsux]:)| \
(\\{::)| \
([\\<\\>\\+\\*\\-\\%\\^\\$\\~\\|\\,\\#\\{\\}\\\"\\;\\?]\\.)| \
([\\<\\>\\_\\+\\*\\-\\%\\$\\~\\|\\,\\;\\#\\/\\\\[\\{\\}\\\"]:)| \
([\\<\\>\\=\\+\\*\\-\\%\\^\\$\\|\\,\\;\\#\\!\\[\\]\\{\\?])) \
(?![\\.\\:])");
*/
/* The original gtk regular expressions for verbs.
((_?[0-9]:)|
(\\bp\\.\\.)|
(\\b[AcCeEiIjLopr]\\.)|
(\\b[ipqsux]:)|
({::)|
([<>\+\*\-\%\^\$\~\|\,\#\{\}"\?]\.)|
([<>\_\+\*\-\%\$\~\|\,\;\#\/\\\[\{\}"]:)|
([<>\=\+\*\-\%\^\$\|\,\;\#\!\[\]\{\?]))
(?![\.\:])
*/
rule.format = verbFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("(([\\/\\\\]\\.)|(\\b[bfMt]\\.)|(\\bt:)|([\\~\\/\\\\}]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("(([\\/\\]\\.)| \
(\\b[bfMt]\\.)| \
(\\bt:)| \
([\\~\\/\\\\}])) \
(?![\\.\\:])");
*/
/* The original gtk regular expressions for adverbs.
(([\/\\]\.)|
(\%[[bfMt]\.)|
(\%[t:)|
([\~\/\\\}]))
(?![\.\:])
*/
rule.format = adverbFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("((\\b[dDHT]\\.)|(\\b[DLS]:)|(\\&\\.:)|([\\;\\!\\@\\&]\\.)|([\\^\\!\\`\\@\\&]:)|([\\\"\\`\\@\\&])|(\\s[\\.\\:][\\.\\:])|(\\s[\\.\\:]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("((\\b[dDHT]\\.)|
(\\b[DLS]:)|
(\\&\\.:)|
([\\;\\!\\@\\&]\\.)|
([\\^\\!\\`\\@\\&]:)|
([\\\"\\`\\@\\&])|
(\\s[\\.\\:][\\.\\:])|
(\\s[\\.\\:]))
(?![\\.\\:])");
*/
/* The original gtk regular expressions for conjunctions.
((\%[[dDHT]\.)|
(\%[[DLS]:)|
(&\.:)|
([\;\!\@&]\.)|
([\^\!\`\@&]:)|
([\"\`\@&])|
(\s[\.\:][\.\:])|
(\s[\.\:]))
(?![\.\:])
*/
rule.format = conjunctionFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("'[^']*'");
rule.format = stringFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("\\bNB\\.[^\n]*");
NBPattern = rule.pattern;
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
noundefStartExpression = QRegExp("\\b(0\\s+:\\s*0|noun\\s+define)\\b.*$");
noundefEndExpression = QRegExp("^\\s*\\)\\s*$");
commentStartExpression = QRegExp("^\\s*\\bNote\\b(?!\\s*\\=[:.])\\s*['\\d].*$");
commentEndExpression = QRegExp("^\\s*\\)\\s*$");
}
// ---------------------------------------------------------------------
void Highj::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
int NBIndex = 0;
int NBLength = 0;
int NBL;
if (previousBlockState() != 1) {
NBIndex = NBPattern.indexIn(text);
NBLength = NBPattern.matchedLength();
startIndex = noundefStartExpression.indexIn(text);
if ((NBIndex > -1) && (NBIndex < startIndex)) {
startIndex = noundefStartExpression.indexIn(text, NBLength+NBIndex);
}
}
while (startIndex >= 0) {
int endIndex = noundefEndExpression.indexIn(text, startIndex);
int noundefLength;
if (endIndex == -1) {
setCurrentBlockState(1);
if (NBLength > 0) noundefLength = (text.length() - startIndex) - NBLength;
else
noundefLength = text.length() - startIndex;
} else {
if (NBLength > 0) NBL = noundefEndExpression.matchedLength() - NBLength;
else
NBL = noundefEndExpression.matchedLength();
noundefLength = endIndex - startIndex
+ NBL;
}
setFormat(startIndex, noundefLength, noundefFormat);
startIndex = noundefStartExpression.indexIn(text, startIndex + noundefLength);
}
}
// ---------------------------------------------------------------------
// set up styles
void Highj::init()
{
init1(&adverbFormat, config.adverbStyle);
init1(&singleLineCommentFormat, config.commentStyle);
init1(&multiLineCommentFormat, config.commentStyle);
init1(&conjunctionFormat, config.conjunctionStyle);
init1(&controlFormat, config.controlStyle);
init1(&functionFormat, config.functionStyle);
init1(&nounFormat, config.nounStyle);
init1(&noundefFormat, config.noundefStyle);
init1(&numberFormat, config.numberStyle);
init1(&stringFormat, config.stringStyle);
init1(&verbFormat, config.verbStyle);
}
// ---------------------------------------------------------------------
void Highj::init1(QTextCharFormat *f, Style s)
{
f->setForeground(s.color);
f->setFontItalic(s.italic);
f->setFontWeight(s.weight);
}
<commit_msg>astyle<commit_after>
/*
* Note this contains experimental highlighting for J.
* Current implementation attempts to suppport:
* strings, numbers, primitive nouns, control words,
* comments, multiline Note.
* There is currently no context aware support (for example to show that control
* words are not valid outside an explicit definition).
*/
#include "base/state.h"
#include "high/high.h"
// ---------------------------------------------------------------------
Highj::Highj(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
init();
HighlightingRule rule;
QStringList controlPatterns;
controlPatterns
<< "\\bassert\\." << "\\bbreak\\." << "\\bcontinue\\."
<< "\\breturn\\." << "\\bdo\\." << "\\bif\\."
<< "\\belse\\." << "\\belseif\\." << "\\bend\\."
<< "\\bfor\\." << "\\bselect\\." << "\\bcase\\."
<< "\\bfcase\\." << "\\bthrow\\." << "\\btry\\."
<< "\\bcatch\\." << "\\bcatchd\\." << "\\bcatcht\\."
<< "\\bwhile\\." << "\\bwhilst\\." << "\\bfor_[a-zA-Z][a-zA-Z0-9_]*\\."
<< "\\bgoto_[a-zA-Z][a-zA-Z0-9_]*\\." << "\\blabel_[a-zA-Z][a-zA-Z0-9_]*\\."
;
foreach (const QString &pattern, controlPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = controlFormat;
highlightingRules.append(rule);
}
rule.pattern = QRegExp("\\b[_0-9][_0-9\\.a-zA-Z]*\\b");
rule.format = numberFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("(_\\.|a\\.|a:)(?![\\.\\:])");
rule.format = nounFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("((_?[0-9]:)|(\\bp\\.\\.)|(\\b[AcCeEiIjLopr]\\.)|(\\b[ipqsux]:)|(\\{::)|([\\<\\>\\+\\*\\-\\%\\^\\$\\~\\|\\,\\#\\{\\}\\\"\\;\\?]\\.)|([\\<\\>\\_\\+\\*\\-\\%\\$\\~\\|\\,\\;\\#\\/\\\\[\\{\\}\\\"]:)|([\\<\\>\\=\\+\\*\\-\\%\\^\\$\\|\\,\\;\\#\\!\\[\\]\\{\\?]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("((_?[0-9]:)| \
(\\bp\\.\\.)| \
(\\b[AcCeEiIjLopr]\\.)| \
(\\b[ipqsux]:)| \
(\\{::)| \
([\\<\\>\\+\\*\\-\\%\\^\\$\\~\\|\\,\\#\\{\\}\\\"\\;\\?]\\.)| \
([\\<\\>\\_\\+\\*\\-\\%\\$\\~\\|\\,\\;\\#\\/\\\\[\\{\\}\\\"]:)| \
([\\<\\>\\=\\+\\*\\-\\%\\^\\$\\|\\,\\;\\#\\!\\[\\]\\{\\?])) \
(?![\\.\\:])");
*/
/* The original gtk regular expressions for verbs.
((_?[0-9]:)|
(\\bp\\.\\.)|
(\\b[AcCeEiIjLopr]\\.)|
(\\b[ipqsux]:)|
({::)|
([<>\+\*\-\%\^\$\~\|\,\#\{\}"\?]\.)|
([<>\_\+\*\-\%\$\~\|\,\;\#\/\\\[\{\}"]:)|
([<>\=\+\*\-\%\^\$\|\,\;\#\!\[\]\{\?]))
(?![\.\:])
*/
rule.format = verbFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("(([\\/\\\\]\\.)|(\\b[bfMt]\\.)|(\\bt:)|([\\~\\/\\\\}]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("(([\\/\\]\\.)| \
(\\b[bfMt]\\.)| \
(\\bt:)| \
([\\~\\/\\\\}])) \
(?![\\.\\:])");
*/
/* The original gtk regular expressions for adverbs.
(([\/\\]\.)|
(\%[[bfMt]\.)|
(\%[t:)|
([\~\/\\\}]))
(?![\.\:])
*/
rule.format = adverbFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("((\\b[dDHT]\\.)|(\\b[DLS]:)|(\\&\\.:)|([\\;\\!\\@\\&]\\.)|([\\^\\!\\`\\@\\&]:)|([\\\"\\`\\@\\&])|(\\s[\\.\\:][\\.\\:])|(\\s[\\.\\:]))(?![\\.\\:])");
/* The line continuations below seem to break the RegExp so it doesn't work.
rule.pattern = QRegExp("((\\b[dDHT]\\.)|
(\\b[DLS]:)|
(\\&\\.:)|
([\\;\\!\\@\\&]\\.)|
([\\^\\!\\`\\@\\&]:)|
([\\\"\\`\\@\\&])|
(\\s[\\.\\:][\\.\\:])|
(\\s[\\.\\:]))
(?![\\.\\:])");
*/
/* The original gtk regular expressions for conjunctions.
((\%[[dDHT]\.)|
(\%[[DLS]:)|
(&\.:)|
([\;\!\@&]\.)|
([\^\!\`\@&]:)|
([\"\`\@&])|
(\s[\.\:][\.\:])|
(\s[\.\:]))
(?![\.\:])
*/
rule.format = conjunctionFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("'[^']*'");
rule.format = stringFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("\\bNB\\.[^\n]*");
NBPattern = rule.pattern;
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
noundefStartExpression = QRegExp("\\b(0\\s+:\\s*0|noun\\s+define)\\b.*$");
noundefEndExpression = QRegExp("^\\s*\\)\\s*$");
commentStartExpression = QRegExp("^\\s*\\bNote\\b(?!\\s*\\=[:.])\\s*['\\d].*$");
commentEndExpression = QRegExp("^\\s*\\)\\s*$");
}
// ---------------------------------------------------------------------
void Highj::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
int NBIndex = 0;
int NBLength = 0;
int NBL;
if (previousBlockState() != 1) {
NBIndex = NBPattern.indexIn(text);
NBLength = NBPattern.matchedLength();
startIndex = noundefStartExpression.indexIn(text);
if ((NBIndex > -1) && (NBIndex < startIndex)) {
startIndex = noundefStartExpression.indexIn(text, NBLength+NBIndex);
}
}
while (startIndex >= 0) {
int endIndex = noundefEndExpression.indexIn(text, startIndex);
int noundefLength;
if (endIndex == -1) {
setCurrentBlockState(1);
if (NBLength > 0) noundefLength = (text.length() - startIndex) - NBLength;
else
noundefLength = text.length() - startIndex;
} else {
if (NBLength > 0) NBL = noundefEndExpression.matchedLength() - NBLength;
else
NBL = noundefEndExpression.matchedLength();
noundefLength = endIndex - startIndex
+ NBL;
}
setFormat(startIndex, noundefLength, noundefFormat);
startIndex = noundefStartExpression.indexIn(text, startIndex + noundefLength);
}
}
// ---------------------------------------------------------------------
// set up styles
void Highj::init()
{
init1(&adverbFormat, config.adverbStyle);
init1(&singleLineCommentFormat, config.commentStyle);
init1(&multiLineCommentFormat, config.commentStyle);
init1(&conjunctionFormat, config.conjunctionStyle);
init1(&controlFormat, config.controlStyle);
init1(&functionFormat, config.functionStyle);
init1(&nounFormat, config.nounStyle);
init1(&noundefFormat, config.noundefStyle);
init1(&numberFormat, config.numberStyle);
init1(&stringFormat, config.stringStyle);
init1(&verbFormat, config.verbStyle);
}
// ---------------------------------------------------------------------
void Highj::init1(QTextCharFormat *f, Style s)
{
f->setForeground(s.color);
f->setFontItalic(s.italic);
f->setFontWeight(s.weight);
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"
using namespace libMesh;
unsigned int dim = 2; // This gets overridden by most mesh formats
int main(int argc, char** argv)
{
LibMeshInit init(argc, argv);
Mesh mesh1(dim), mesh2(dim);
EquationSystems es1(mesh1), es2(mesh2);
std::cout << "Usage: " << argv[0]
<< " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;
// We should have one system name for each variable name, and those
// get preceded by an even number of arguments.
libmesh_assert (!(argc % 2));
// We should have at least one system/variable pair following the
// initial arguments
libmesh_assert_greater_equal (argc, 6);
mesh1.read(argv[1]);
std::cout << "Loaded mesh " << argv[1] << std::endl;
mesh2 = mesh1;
es1.read(argv[2]);
std::cout << "Loaded solution " << argv[2] << std::endl;
std::vector<unsigned int> old_sys_num((argc-4)/2),
new_sys_num((argc-4)/2),
old_var_num((argc-4)/2),
new_var_num((argc-4)/2);
std::vector<const System *> old_system((argc-4)/2);
std::vector<System *> new_system((argc-4)/2);
for (int argi = 4; argi < argc; argi += 2)
{
const char* sysname = argv[argi];
const char* varname = argv[argi+1];
const unsigned int pairnum = (argi-4)/2;
libmesh_assert(es1.has_system(sysname));
const System &old_sys = es1.get_system(sysname);
old_system[pairnum] = &old_sys;
old_sys_num[pairnum] = old_sys.number();
libmesh_assert(old_sys.has_variable(varname));
old_var_num[pairnum] = old_sys.variable_number(varname);
const Variable &variable = old_sys.variable(old_var_num[pairnum]);
std::string systype = old_sys.system_type();
System &new_sys = es2.add_system(systype, sysname);
new_system[pairnum] = &new_sys;
new_sys_num[pairnum] = new_sys.number();
new_var_num[pairnum] =
new_sys.add_variable(varname, variable.type(),
&variable.active_subdomains());
}
es2.init();
// Copy over any nodal degree of freedom coefficients
MeshBase::const_node_iterator old_nit = mesh1.local_nodes_begin(),
new_nit = mesh2.local_nodes_begin();
const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end(),
new_nit_end = mesh2.local_nodes_end();
for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
{
const Node* old_node = *old_nit;
const Node* new_node = *new_nit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_node == *new_node);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_node->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_node->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
// Copy over any element degree of freedom coefficients
MeshBase::const_element_iterator old_eit = mesh1.active_local_elements_begin(),
new_eit = mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end(),
new_eit_end = mesh2.active_local_elements_end();
for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
{
const Elem* old_elem = *old_eit;
const Elem* new_elem = *new_eit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_elem == *new_elem);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_elem->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_elem->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
return 0;
}
<commit_msg>Don't accidentally shallow copy a Mesh<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"
using namespace libMesh;
unsigned int dim = 2; // This gets overridden by most mesh formats
int main(int argc, char** argv)
{
LibMeshInit init(argc, argv);
Mesh mesh1(dim);
EquationSystems es1(mesh1);
std::cout << "Usage: " << argv[0]
<< " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;
// We should have one system name for each variable name, and those
// get preceded by an even number of arguments.
libmesh_assert (!(argc % 2));
// We should have at least one system/variable pair following the
// initial arguments
libmesh_assert_greater_equal (argc, 6);
mesh1.read(argv[1]);
std::cout << "Loaded mesh " << argv[1] << std::endl;
Mesh mesh2(mesh1);
EquationSystems es2(mesh2);
es1.read(argv[2],
EquationSystems::READ_HEADER |
EquationSystems::READ_DATA |
EquationSystems::READ_ADDITIONAL_DATA |
EquationSystems::READ_BASIC_ONLY);
std::cout << "Loaded solution " << argv[2] << std::endl;
std::vector<unsigned int> old_sys_num((argc-4)/2),
new_sys_num((argc-4)/2),
old_var_num((argc-4)/2),
new_var_num((argc-4)/2);
std::vector<const System *> old_system((argc-4)/2);
std::vector<System *> new_system((argc-4)/2);
for (int argi = 4; argi < argc; argi += 2)
{
const char* sysname = argv[argi];
const char* varname = argv[argi+1];
const unsigned int pairnum = (argi-4)/2;
libmesh_assert(es1.has_system(sysname));
const System &old_sys = es1.get_system(sysname);
old_system[pairnum] = &old_sys;
old_sys_num[pairnum] = old_sys.number();
libmesh_assert(old_sys.has_variable(varname));
old_var_num[pairnum] = old_sys.variable_number(varname);
const Variable &variable = old_sys.variable(old_var_num[pairnum]);
std::string systype = old_sys.system_type();
System &new_sys = es2.add_system(systype, sysname);
new_system[pairnum] = &new_sys;
new_sys_num[pairnum] = new_sys.number();
new_var_num[pairnum] =
new_sys.add_variable(varname, variable.type(),
&variable.active_subdomains());
}
es2.init();
// A future version of this app should copy variables for
// non-solution vectors too.
// Copy over any nodal degree of freedom coefficients
MeshBase::const_node_iterator old_nit = mesh1.local_nodes_begin(),
new_nit = mesh2.local_nodes_begin();
const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end();
for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
{
const Node* old_node = *old_nit;
const Node* new_node = *new_nit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_node == *new_node);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_node->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_node->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
// Copy over any element degree of freedom coefficients
MeshBase::const_element_iterator old_eit = mesh1.active_local_elements_begin(),
new_eit = mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end();
for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
{
const Elem* old_elem = *old_eit;
const Elem* new_elem = *new_eit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_elem == *new_elem);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_elem->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_elem->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
es2.write(argv[3], EquationSystems::WRITE_DATA);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _MARRAY_MARRAY_SLICE_HPP_
#define _MARRAY_MARRAY_SLICE_HPP_
#include "marray_base.hpp"
namespace MArray
{
namespace detail
{
template <typename It1, typename It2>
void get_slice_dims_helper(It1, It2) {}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims_helper(It1 len, It2 stride,
const slice_dim& dim, const Dims&... dims)
{
*len = dim.len;
*stride = dim.stride;
get_slice_dims_helper(++len, ++stride, dims...);
}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims_helper(It1 len, It2 stride,
const bcast_dim& dim, const Dims&... dims)
{
*len = dim.len;
*stride = 0;
get_slice_dims_helper(++len, ++stride, dims...);
}
template <typename It1, typename It2, typename... Dims, size_t... I>
void get_slice_dims_helper(It1 len, It2 stride,
const std::tuple<Dims...>& dims,
detail::integer_sequence<size_t, I...>)
{
get_slice_dims_helper(len, stride, std::get<I>(dims)...);
}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims(It1 len, It2 stride,
const std::tuple<Dims...>& dims)
{
get_slice_dims_helper(len, stride, dims,
detail::static_range<size_t, sizeof...(Dims)>());
}
}
/*
* Represents a part of an array, where the first NIndexed-1 out of NDim
* Dimensions have either been indexed into (i.e. a single value
* specified for that index) or sliced (i.e. a range of values specified).
* The parameter NSliced specifies how many indices were sliced. The
* reference may be converted into an array view (of Dimension
* NDim-NIndexed+1+NSliced) or further indexed, but may not be used to modify
* data.
*/
template <typename Type, unsigned NDim, unsigned NIndexed, typename... Dims>
class marray_slice
{
template <typename, unsigned, unsigned, typename...> friend class marray_slice;
public:
typedef typename marray_view<Type, NDim>::value_type value_type;
typedef typename marray_view<Type, NDim>::const_pointer const_pointer;
typedef typename marray_view<Type, NDim>::pointer pointer;
typedef typename marray_view<Type, NDim>::const_reference const_reference;
typedef typename marray_view<Type, NDim>::reference reference;
typedef detail::marray_iterator<marray_slice> iterator;
typedef detail::marray_iterator<const marray_slice> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
protected:
const std::array<len_type, NDim>& len_;
const std::array<stride_type, NDim>& stride_;
pointer data_;
std::tuple<Dims...> dims_;
static constexpr unsigned DimsLeft = NDim - NIndexed;
static constexpr unsigned CurDim = NIndexed-1;
static constexpr unsigned NextDim = NIndexed;
static constexpr unsigned NSliced = sizeof...(Dims);
static constexpr unsigned NewNDim = NSliced + DimsLeft;
public:
marray_slice(const marray_slice& other) = default;
template <typename Array, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, len_type i)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data() + i*stride_[CurDim]) {}
template <typename Array, typename I, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, const range_t<I>& slice)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data() + slice.front()*stride_[CurDim]),
dims_(slice_dim{slice.size(), slice.step()*stride_[CurDim]}) {}
template <typename Array, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, bcast_t, len_type len)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data()), dims_(bcast_dim{len}) {}
marray_slice(const marray_slice<Type, NDim, NIndexed-1, Dims...>& parent, len_type i)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_ + i*parent.stride_[CurDim]), dims_(parent.dims_) {}
template <typename... OldDims, typename I>
marray_slice(const marray_slice<Type, NDim, NIndexed-1, OldDims...>& parent,
const range_t<I>& slice)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_ + slice.front()*parent.stride_[CurDim]),
dims_(std::tuple_cat(parent.dims_,
std::make_tuple(slice_dim{slice.size(), slice.step()*stride_[CurDim]}))) {}
template <typename... OldDims>
marray_slice(const marray_slice<Type, NDim, NIndexed, OldDims...>& parent,
bcast_t, len_type len)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_),
dims_(std::tuple_cat(parent.dims_, std::make_tuple(bcast_dim{len}))) {}
const marray_slice& operator=(const marray_slice& other) const
{
assign_expr(*this, other);
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator=(const Expression& other) const
{
assign_expr(*this, other);
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator+=(const Expression& other) const
{
*this = *this + other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator-=(const Expression& other) const
{
*this = *this - other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator*=(const Expression& other) const
{
*this = *this * other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator/=(const Expression& other) const
{
*this = *this / other;
return *this;
}
template <int N=DimsLeft>
detail::enable_if_t<N==1 && !sizeof...(Dims), reference>
operator[](len_type i) const
{
MARRAY_ASSERT(i >= 0 && i < len_[NDim-1]);
return data_[i*stride_[NextDim]];
}
template <int N=DimsLeft>
detail::enable_if_t<N!=1 || sizeof...(Dims),
marray_slice<Type, NDim, NIndexed+1, Dims...>>
operator[](len_type i) const
{
static_assert(DimsLeft, "No more dimensions to index");
MARRAY_ASSERT(i >= 0 && i < len_[NextDim]);
return {*this, i};
}
template <typename I>
marray_slice<Type, NDim, NIndexed+1, Dims..., slice_dim>
operator[](const range_t<I>& x) const
{
static_assert(DimsLeft, "No more dimensions to index");
MARRAY_ASSERT(x.front() >= 0);
MARRAY_ASSERT(x.size() >= 0);
MARRAY_ASSERT(x.front()+x.size() <= len_[NextDim]);
return {*this, x};
}
marray_slice<Type, NDim, NIndexed+1, Dims..., slice_dim>
operator[](all_t) const
{
static_assert(DimsLeft, "No more dimensions to index");
return {*this, range(len_type(), len_[NIndexed])};
}
marray_slice<Type, NDim, NIndexed, Dims..., bcast_dim>
operator[](bcast_t) const
{
return {*this, slice::bcast, len_[NIndexed]};
}
template <typename Arg, typename=
detail::enable_if_t<detail::is_index_or_slice<Arg>::value>>
auto operator()(Arg&& arg) const ->
decltype((*this)[std::forward<Arg>(arg)])
{
return (*this)[std::forward<Arg>(arg)];
}
template <typename Arg, typename... Args, typename=
detail::enable_if_t<sizeof...(Args) &&
detail::are_indices_or_slices<Arg, Args...>::value>>
auto operator()(Arg&& arg, Args&&... args) const ->
decltype((*this)[std::forward<Arg>(arg)](std::forward<Args>(args)...))
{
return (*this)[std::forward<Arg>(arg)](std::forward<Args>(args)...);
}
const_pointer cdata() const
{
return data_;
}
pointer data() const
{
return data_;
}
template <unsigned Dim>
auto dim() const -> decltype((std::get<Dim>(dims_)))
{
return std::get<Dim>(dims_);
}
len_type base_length(unsigned dim) const
{
MARRAY_ASSERT(dim < NDim);
return len_[dim];
}
template <unsigned Dim>
len_type base_length() const
{
static_assert(Dim < NDim, "Dim out of range");
return len_[Dim];
}
stride_type base_stride(unsigned dim) const
{
MARRAY_ASSERT(dim < NDim);
return stride_[dim];
}
template <unsigned Dim>
stride_type base_stride() const
{
static_assert(Dim < NDim, "Dim out of range");
return stride_[Dim];
}
marray_view<const Type, NewNDim> cview() const
{
return view();
}
marray_view<Type, NewNDim> view() const
{
std::array<len_type, NewNDim> len;
std::array<stride_type, NewNDim> stride;
detail::get_slice_dims(len.begin(), stride.begin(), dims_);
std::copy_n(len_.begin()+NextDim, DimsLeft, len.begin()+NSliced);
std::copy_n(stride_.begin()+NextDim, DimsLeft, stride.begin()+NSliced);
return {len, data_, stride};
}
friend marray_view<const Type, NewNDim> cview(const marray_slice& x)
{
return x.cview();
}
friend marray_view<Type, NewNDim> view(const marray_slice& x)
{
return x.view();
}
const_iterator cbegin() const
{
return const_iterator{*this, 0};
}
const_iterator begin() const
{
return const_iterator{*this, 0};
}
iterator begin()
{
return iterator{*this, 0};
}
const_iterator cend() const
{
return const_iterator{*this, len_[NextDim]};
}
const_iterator end() const
{
return const_iterator{*this, len_[NextDim]};
}
iterator end()
{
return iterator{*this, len_[NextDim]};
}
const_reverse_iterator crbegin() const
{
return const_reverse_iterator{end()};
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator{end()};
}
reverse_iterator rbegin()
{
return reverse_iterator{end()};
}
const_reverse_iterator crend() const
{
return const_reverse_iterator{begin()};
}
const_reverse_iterator rend() const
{
return const_reverse_iterator{begin()};
}
reverse_iterator rend()
{
return reverse_iterator{begin()};
}
};
}
#endif
<commit_msg>Add operator<< to marray_slice.<commit_after>#ifndef _MARRAY_MARRAY_SLICE_HPP_
#define _MARRAY_MARRAY_SLICE_HPP_
#include "marray_base.hpp"
namespace MArray
{
namespace detail
{
template <typename It1, typename It2>
void get_slice_dims_helper(It1, It2) {}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims_helper(It1 len, It2 stride,
const slice_dim& dim, const Dims&... dims)
{
*len = dim.len;
*stride = dim.stride;
get_slice_dims_helper(++len, ++stride, dims...);
}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims_helper(It1 len, It2 stride,
const bcast_dim& dim, const Dims&... dims)
{
*len = dim.len;
*stride = 0;
get_slice_dims_helper(++len, ++stride, dims...);
}
template <typename It1, typename It2, typename... Dims, size_t... I>
void get_slice_dims_helper(It1 len, It2 stride,
const std::tuple<Dims...>& dims,
detail::integer_sequence<size_t, I...>)
{
get_slice_dims_helper(len, stride, std::get<I>(dims)...);
}
template <typename It1, typename It2, typename... Dims>
void get_slice_dims(It1 len, It2 stride,
const std::tuple<Dims...>& dims)
{
get_slice_dims_helper(len, stride, dims,
detail::static_range<size_t, sizeof...(Dims)>());
}
}
/*
* Represents a part of an array, where the first NIndexed-1 out of NDim
* Dimensions have either been indexed into (i.e. a single value
* specified for that index) or sliced (i.e. a range of values specified).
* The parameter NSliced specifies how many indices were sliced. The
* reference may be converted into an array view (of Dimension
* NDim-NIndexed+1+NSliced) or further indexed, but may not be used to modify
* data.
*/
template <typename Type, unsigned NDim, unsigned NIndexed, typename... Dims>
class marray_slice
{
template <typename, unsigned, unsigned, typename...> friend class marray_slice;
public:
typedef typename marray_view<Type, NDim>::value_type value_type;
typedef typename marray_view<Type, NDim>::const_pointer const_pointer;
typedef typename marray_view<Type, NDim>::pointer pointer;
typedef typename marray_view<Type, NDim>::const_reference const_reference;
typedef typename marray_view<Type, NDim>::reference reference;
typedef detail::marray_iterator<marray_slice> iterator;
typedef detail::marray_iterator<const marray_slice> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
protected:
const std::array<len_type, NDim>& len_;
const std::array<stride_type, NDim>& stride_;
pointer data_;
std::tuple<Dims...> dims_;
static constexpr unsigned DimsLeft = NDim - NIndexed;
static constexpr unsigned CurDim = NIndexed-1;
static constexpr unsigned NextDim = NIndexed;
static constexpr unsigned NSliced = sizeof...(Dims);
static constexpr unsigned NewNDim = NSliced + DimsLeft;
public:
marray_slice(const marray_slice& other) = default;
template <typename Array, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, len_type i)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data() + i*stride_[CurDim]) {}
template <typename Array, typename I, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, const range_t<I>& slice)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data() + slice.front()*stride_[CurDim]),
dims_(slice_dim{slice.size(), slice.step()*stride_[CurDim]}) {}
template <typename Array, typename=decltype(std::declval<Array>().lengths())>
marray_slice(Array&& array, bcast_t, len_type len)
: len_(array.lengths()), stride_(array.strides()),
data_(array.data()), dims_(bcast_dim{len}) {}
marray_slice(const marray_slice<Type, NDim, NIndexed-1, Dims...>& parent, len_type i)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_ + i*parent.stride_[CurDim]), dims_(parent.dims_) {}
template <typename... OldDims, typename I>
marray_slice(const marray_slice<Type, NDim, NIndexed-1, OldDims...>& parent,
const range_t<I>& slice)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_ + slice.front()*parent.stride_[CurDim]),
dims_(std::tuple_cat(parent.dims_,
std::make_tuple(slice_dim{slice.size(), slice.step()*stride_[CurDim]}))) {}
template <typename... OldDims>
marray_slice(const marray_slice<Type, NDim, NIndexed, OldDims...>& parent,
bcast_t, len_type len)
: len_(parent.len_), stride_(parent.stride_),
data_(parent.data_),
dims_(std::tuple_cat(parent.dims_, std::make_tuple(bcast_dim{len}))) {}
const marray_slice& operator=(const marray_slice& other) const
{
assign_expr(*this, other);
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator=(const Expression& other) const
{
assign_expr(*this, other);
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator+=(const Expression& other) const
{
*this = *this + other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator-=(const Expression& other) const
{
*this = *this - other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator*=(const Expression& other) const
{
*this = *this * other;
return *this;
}
template <typename Expression,
typename=detail::enable_if_t<is_expression_arg_or_scalar<Expression>::value>>
const marray_slice& operator/=(const Expression& other) const
{
*this = *this / other;
return *this;
}
template <int N=DimsLeft>
detail::enable_if_t<N==1 && !sizeof...(Dims), reference>
operator[](len_type i) const
{
MARRAY_ASSERT(i >= 0 && i < len_[NDim-1]);
return data_[i*stride_[NextDim]];
}
template <int N=DimsLeft>
detail::enable_if_t<N!=1 || sizeof...(Dims),
marray_slice<Type, NDim, NIndexed+1, Dims...>>
operator[](len_type i) const
{
static_assert(DimsLeft, "No more dimensions to index");
MARRAY_ASSERT(i >= 0 && i < len_[NextDim]);
return {*this, i};
}
template <typename I>
marray_slice<Type, NDim, NIndexed+1, Dims..., slice_dim>
operator[](const range_t<I>& x) const
{
static_assert(DimsLeft, "No more dimensions to index");
MARRAY_ASSERT(x.front() >= 0);
MARRAY_ASSERT(x.size() >= 0);
MARRAY_ASSERT(x.front()+x.size() <= len_[NextDim]);
return {*this, x};
}
marray_slice<Type, NDim, NIndexed+1, Dims..., slice_dim>
operator[](all_t) const
{
static_assert(DimsLeft, "No more dimensions to index");
return {*this, range(len_type(), len_[NIndexed])};
}
marray_slice<Type, NDim, NIndexed, Dims..., bcast_dim>
operator[](bcast_t) const
{
return {*this, slice::bcast, len_[NIndexed]};
}
template <typename Arg, typename=
detail::enable_if_t<detail::is_index_or_slice<Arg>::value>>
auto operator()(Arg&& arg) const ->
decltype((*this)[std::forward<Arg>(arg)])
{
return (*this)[std::forward<Arg>(arg)];
}
template <typename Arg, typename... Args, typename=
detail::enable_if_t<sizeof...(Args) &&
detail::are_indices_or_slices<Arg, Args...>::value>>
auto operator()(Arg&& arg, Args&&... args) const ->
decltype((*this)[std::forward<Arg>(arg)](std::forward<Args>(args)...))
{
return (*this)[std::forward<Arg>(arg)](std::forward<Args>(args)...);
}
friend std::ostream& operator<<(std::ostream& os, const marray_slice& x)
{
return os << x.view();
}
const_pointer cdata() const
{
return data_;
}
pointer data() const
{
return data_;
}
template <unsigned Dim>
auto dim() const -> decltype((std::get<Dim>(dims_)))
{
return std::get<Dim>(dims_);
}
len_type base_length(unsigned dim) const
{
MARRAY_ASSERT(dim < NDim);
return len_[dim];
}
template <unsigned Dim>
len_type base_length() const
{
static_assert(Dim < NDim, "Dim out of range");
return len_[Dim];
}
stride_type base_stride(unsigned dim) const
{
MARRAY_ASSERT(dim < NDim);
return stride_[dim];
}
template <unsigned Dim>
stride_type base_stride() const
{
static_assert(Dim < NDim, "Dim out of range");
return stride_[Dim];
}
marray_view<const Type, NewNDim> cview() const
{
return view();
}
marray_view<Type, NewNDim> view() const
{
std::array<len_type, NewNDim> len;
std::array<stride_type, NewNDim> stride;
detail::get_slice_dims(len.begin(), stride.begin(), dims_);
std::copy_n(len_.begin()+NextDim, DimsLeft, len.begin()+NSliced);
std::copy_n(stride_.begin()+NextDim, DimsLeft, stride.begin()+NSliced);
return {len, data_, stride};
}
friend marray_view<const Type, NewNDim> cview(const marray_slice& x)
{
return x.cview();
}
friend marray_view<Type, NewNDim> view(const marray_slice& x)
{
return x.view();
}
const_iterator cbegin() const
{
return const_iterator{*this, 0};
}
const_iterator begin() const
{
return const_iterator{*this, 0};
}
iterator begin()
{
return iterator{*this, 0};
}
const_iterator cend() const
{
return const_iterator{*this, len_[NextDim]};
}
const_iterator end() const
{
return const_iterator{*this, len_[NextDim]};
}
iterator end()
{
return iterator{*this, len_[NextDim]};
}
const_reverse_iterator crbegin() const
{
return const_reverse_iterator{end()};
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator{end()};
}
reverse_iterator rbegin()
{
return reverse_iterator{end()};
}
const_reverse_iterator crend() const
{
return const_reverse_iterator{begin()};
}
const_reverse_iterator rend() const
{
return const_reverse_iterator{begin()};
}
reverse_iterator rend()
{
return reverse_iterator{begin()};
}
};
}
#endif
<|endoftext|> |
<commit_before>/**
* @file interactive_search.cpp
* @author Sean Massung
*/
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "caching/all.h"
#include "corpus/document.h"
#include "index/inverted_index.h"
#include "index/ranker/all.h"
#include "analyzers/analyzer.h"
#include "util/printing.h"
#include "util/time.h"
using namespace meta;
std::string get_snippets(const std::string & filename, const std::string & text)
{
std::ifstream in{filename};
std::string str{(std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>()};
std::replace(str.begin(), str.end(), '\n', ' ');
return str;
}
int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cerr << "Usage:\t" << argv[0] << " configFile" << std::endl;
return 1;
}
// Turn on logging to std::cerr.
logging::set_cerr_logging();
// Create an inverted index using a splay cache. The arguments forwarded
// to make_index are the config file for the index and any parameters
// for the cache. In this case, we set the maximum number of nodes in
// the splay_cache to be 10000.
auto idx = index::make_index<index::splay_inverted_index>(argv[1], 10000);
// Create a ranking class based on the config file.
auto config = cpptoml::parse_file(argv[1]);
auto group = config.get_group("ranker");
if (!group)
throw std::runtime_error{"\"ranker\" group needed in config file!"};
auto ranker = index::make_ranker(*group);
std::cout << "Enter a query, or blank query to quit." << std::endl
<< std::endl;
std::string text;
while(true)
{
std::cout << "> ";
std::getline(std::cin, text);
if(text.empty())
break;
corpus::document query{"[user input]", doc_id{0}};
query.content(text);
std::vector<std::pair<doc_id, double>> ranking;
auto time = common::time([&](){
ranking = ranker->score(*idx, query);
});
std::cout << "Showing top 10 of " << ranking.size()
<< " results (" << time.count() << "ms)" << std::endl;
for(size_t i = 0; i < ranking.size() && i < 5; ++i)
{
std::string path{idx->doc_path(ranking[i].first)};
std::cout << printing::make_bold(
std::to_string(i+1) + ". " + path + " ("
+ std::to_string(ranking[i].second) + ")"
) << std::endl;
std::cout << get_snippets(path, text) << std::endl << std::endl;
}
std::cout << std::endl;
}
}
<commit_msg>clean up interactive_search more<commit_after>/**
* @file interactive_search.cpp
* @author Sean Massung
*/
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "corpus/document.h"
#include "index/inverted_index.h"
#include "index/ranker/all.h"
#include "util/printing.h"
#include "util/time.h"
using namespace meta;
/**
* @param filename The name of the file to open
* @return the text content of that file
*/
std::string get_content(const std::string& filename)
{
std::ifstream in{filename};
std::string str{(std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>()};
std::replace(str.begin(), str.end(), '\n', ' ');
return str;
}
/**
* Demo app to allow a user to create queries and search an index.
*/
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cerr << "Usage:\t" << argv[0] << " configFile" << std::endl;
return 1;
}
// Turn on logging to std::cerr.
logging::set_cerr_logging();
// Create an inverted index using a splay cache. The arguments forwarded
// to make_index are the config file for the index and any parameters
// for the cache. In this case, we set the maximum number of nodes in
// the splay_cache to be 10000.
auto idx = index::make_index<index::splay_inverted_index>(argv[1], 10000);
// Create a ranking class based on the config file.
auto config = cpptoml::parse_file(argv[1]);
auto group = config.get_group("ranker");
if (!group)
throw std::runtime_error{"\"ranker\" group needed in config file!"};
auto ranker = index::make_ranker(*group);
std::cout << "Enter a query, or blank to quit." << std::endl << std::endl;
std::string text;
while (true)
{
std::cout << "> ";
std::getline(std::cin, text);
if (text.empty())
break;
corpus::document query{"[user input]", doc_id{0}};
query.content(text); // set the doc's content to be user input
// Use the ranker to score the query over the index.
std::vector<std::pair<doc_id, double>> ranking;
auto time = common::time([&]()
{ ranking = ranker->score(*idx, query, 5); });
std::cout << "Showing top 5 of results (" << time.count() << "ms)"
<< std::endl;
for (size_t i = 0; i < ranking.size() && i < 5; ++i)
{
std::string path{idx->doc_path(ranking[i].first)};
std::cout << printing::make_bold(std::to_string(i + 1) + ". " + path
+ " ("
+ std::to_string(ranking[i].second)
+ ")") << std::endl;
std::cout << get_content(path) << std::endl << std::endl;
}
std::cout << std::endl;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include "document.hxx"
#include "docsh.hxx"
#include "rangelst.hxx"
class Test : public test::BootstrapFixture {
public:
virtual void setUp();
virtual void tearDown();
void testDeleteArea_4Ranges();
void testDeleteArea_2Ranges();
void testDeleteArea_0Ranges();
CPPUNIT_TEST_SUITE(Test);
CPPUNIT_TEST(testDeleteArea_4Ranges);
CPPUNIT_TEST(testDeleteArea_2Ranges);
CPPUNIT_TEST(testDeleteArea_0Ranges);
CPPUNIT_TEST_SUITE_END();
private:
ScDocument *m_pDoc;
ScDocShellRef m_xDocShRef;
};
void Test::setUp()
{
BootstrapFixture::setUp();
ScDLL::Init();
m_xDocShRef = new ScDocShell(
SFXMODEL_STANDARD |
SFXMODEL_DISABLE_EMBEDDED_SCRIPTS |
SFXMODEL_DISABLE_DOCUMENT_RECOVERY);
m_pDoc = m_xDocShRef->GetDocument();
}
void Test::tearDown()
{
m_xDocShRef.Clear();
BootstrapFixture::tearDown();
}
void Test::testDeleteArea_4Ranges()
{
ScRangeList aList(ScRange(0,0,0,5,5,0));
aList.DeleteArea(2,2,0,3,3,0);
CPPUNIT_ASSERT_EQUAL(aList.size(), static_cast<size_t>(4));
for(SCCOL nCol = 0; nCol <= 5; ++nCol)
{
for(SCROW nRow = 0; nRow <= 5; ++nRow)
{
if((nCol == 2 || nCol == 3) && ( nRow == 2 || nRow == 3))
CPPUNIT_ASSERT(!aList.Intersects(ScRange(nCol, nRow, 0)));
else
CPPUNIT_ASSERT(aList.Intersects(ScRange(nCol, nRow, 0)));
}
}
}
void Test::testDeleteArea_2Ranges()
{
ScRangeList aList(ScRange(0,0,0,5,5,5));
ScRangeList aList2(aList);
aList.DeleteArea(4,4,0,6,7,0);
aList2.DeleteArea(4,4,0,6,7,0);
CPPUNIT_ASSERT_EQUAL(aList.size(), static_cast<size_t>(2));
CPPUNIT_ASSERT_EQUAL(aList2.size(), static_cast<size_t>(2));
for(SCCOL nCol = 0; nCol <= 5; ++nCol)
{
for(SCROW nRow = 0; nRow <= 5; ++nRow)
{
if(nCol>=4 && nRow >= 4)
CPPUNIT_ASSERT(!aList.Intersects(ScRange(nCol, nRow, 0)));
else
CPPUNIT_ASSERT(aList.Intersects(ScRange(nCol, nRow, 0)));
}
}
}
void Test::testDeleteArea_0Ranges()
{
ScRangeList aList(ScRange(1,1,0,3,3,0));
aList.DeleteArea(1,1,0,3,3,0);
CPPUNIT_ASSERT(aList.empty());
ScRangeList aList2(ScRange(1,1,0,3,3,0));
aList2.DeleteArea(0,0,0,4,4,0);
CPPUNIT_ASSERT(aList.empty());
}
CPPUNIT_TEST_SUITE_REGISTRATION(Test);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>one more test for ScRangeList::DeleteArea<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include "document.hxx"
#include "docsh.hxx"
#include "rangelst.hxx"
class Test : public test::BootstrapFixture {
public:
virtual void setUp();
virtual void tearDown();
void testDeleteArea_4Ranges();
void testDeleteArea_2Ranges();
void testDeleteArea_2Ranges_Case2();
void testDeleteArea_0Ranges();
void testUpdateReference_DeleteRow();
void testUpdateReference_DeleteCol();
CPPUNIT_TEST_SUITE(Test);
CPPUNIT_TEST(testDeleteArea_4Ranges);
CPPUNIT_TEST(testDeleteArea_2Ranges);
CPPUNIT_TEST(testDeleteArea_2Ranges_Case2);
CPPUNIT_TEST(testDeleteArea_0Ranges);
CPPUNIT_TEST_SUITE_END();
private:
ScDocument *m_pDoc;
ScDocShellRef m_xDocShRef;
};
void Test::setUp()
{
BootstrapFixture::setUp();
ScDLL::Init();
m_xDocShRef = new ScDocShell(
SFXMODEL_STANDARD |
SFXMODEL_DISABLE_EMBEDDED_SCRIPTS |
SFXMODEL_DISABLE_DOCUMENT_RECOVERY);
m_pDoc = m_xDocShRef->GetDocument();
}
void Test::tearDown()
{
m_xDocShRef.Clear();
BootstrapFixture::tearDown();
}
void Test::testDeleteArea_4Ranges()
{
ScRangeList aList(ScRange(0,0,0,5,5,0));
aList.DeleteArea(2,2,0,3,3,0);
CPPUNIT_ASSERT_EQUAL(aList.size(), static_cast<size_t>(4));
for(SCCOL nCol = 0; nCol <= 5; ++nCol)
{
for(SCROW nRow = 0; nRow <= 5; ++nRow)
{
if((nCol == 2 || nCol == 3) && ( nRow == 2 || nRow == 3))
CPPUNIT_ASSERT(!aList.Intersects(ScRange(nCol, nRow, 0)));
else
CPPUNIT_ASSERT(aList.Intersects(ScRange(nCol, nRow, 0)));
}
}
}
void Test::testDeleteArea_2Ranges()
{
ScRangeList aList(ScRange(0,0,0,5,5,5));
ScRangeList aList2(aList);
aList.DeleteArea(4,4,0,6,7,0);
aList2.DeleteArea(4,4,0,6,7,0);
CPPUNIT_ASSERT_EQUAL(aList.size(), static_cast<size_t>(2));
CPPUNIT_ASSERT_EQUAL(aList2.size(), static_cast<size_t>(2));
for(SCCOL nCol = 0; nCol <= 5; ++nCol)
{
for(SCROW nRow = 0; nRow <= 5; ++nRow)
{
if(nCol>=4 && nRow >= 4)
CPPUNIT_ASSERT(!aList.Intersects(ScRange(nCol, nRow, 0)));
else
CPPUNIT_ASSERT(aList.Intersects(ScRange(nCol, nRow, 0)));
}
}
}
void Test::testDeleteArea_2Ranges_Case2()
{
ScRangeList aList(ScRange(1,1,0,1,5,0));
aList.DeleteArea(0,3,0,MAXCOL,3,0);
for(SCROW nRow = 1; nRow <= 5; ++nRow)
{
if(nRow == 3)
CPPUNIT_ASSERT(!aList.Intersects(ScRange(1,3,0)));
else
CPPUNIT_ASSERT(aList.Intersects(ScRange(1,nRow,0)));
}
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), aList.GetCellCount());
}
void Test::testDeleteArea_0Ranges()
{
ScRangeList aList(ScRange(1,1,0,3,3,0));
aList.DeleteArea(1,1,0,3,3,0);
CPPUNIT_ASSERT(aList.empty());
ScRangeList aList2(ScRange(1,1,0,3,3,0));
aList2.DeleteArea(0,0,0,4,4,0);
CPPUNIT_ASSERT(aList.empty());
}
void Test::testUpdateReference_DeleteRow()
{
ScRangeList aList(ScRange(1,1,0,4,4,0));
bool bUpdated = aList.UpdateReference(URM_INSDEL, m_pDoc, ScRange(0,3,0,MAXCOL,MAXROW,0), 0, -1, 0);
CPPUNIT_ASSERT(bUpdated);
}
void Test::testUpdateReference_DeleteCol()
{
}
CPPUNIT_TEST_SUITE_REGISTRATION(Test);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: autofmt.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dr $ $Date: 2001-11-19 13:31:19 $
*
* 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 SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef SV_MOREBTN_HXX
#include <vcl/morebtn.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX
#include <svtools/scriptedtext.hxx>
#endif
//------------------------------------------------------------------------
class ScAutoFormat;
class ScAutoFormatData;
class SvxBoxItem;
class SvxBorderLine;
class AutoFmtPreview; // s.u.
class SvNumberFormatter;
//------------------------------------------------------------------------
enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };
//========================================================================
class ScAutoFormatDlg : public ModalDialog
{
public:
ScAutoFormatDlg( Window* pParent,
ScAutoFormat* pAutoFormat,
const ScAutoFormatData* pSelFormatData,
ScDocument* pDoc );
~ScAutoFormatDlg();
USHORT GetIndex() const { return nIndex; }
String GetCurrFormatName();
private:
FixedLine aFlFormat;
ListBox aLbFormat;
AutoFmtPreview* pWndPreview;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
PushButton aBtnAdd;
PushButton aBtnRemove;
MoreButton aBtnMore;
FixedLine aFlFormatting;
CheckBox aBtnNumFormat;
CheckBox aBtnBorder;
CheckBox aBtnFont;
CheckBox aBtnPattern;
CheckBox aBtnAlignment;
CheckBox aBtnAdjust;
PushButton aBtnRename;
String aStrTitle;
String aStrLabel;
String aStrClose;
String aStrDelTitle;
String aStrDelMsg;
String aStrRename;
//------------------------
ScAutoFormat* pFormat;
const ScAutoFormatData* pSelFmtData;
USHORT nIndex;
BOOL bCoreDataChanged;
BOOL bFmtInserted;
void Init ();
void UpdateChecks ();
//------------------------
DECL_LINK( CheckHdl, Button * );
DECL_LINK( AddHdl, void * );
DECL_LINK( RemoveHdl, void * );
DECL_LINK( SelFmtHdl, void * );
DECL_LINK( CloseHdl, PushButton * );
DECL_LINK( DblClkHdl, void * );
DECL_LINK( RenameHdl, void *);
};
//========================================================================
class AutoFmtPreview : public Window
{
public:
AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
~AutoFmtPreview();
void NotifyChange( ScAutoFormatData* pNewData );
protected:
virtual void Paint( const Rectangle& rRect );
private:
ScAutoFormatData* pCurData;
VirtualDevice aVD;
SvtScriptedTextHelper aScriptedText;
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
BOOL bFitWidth;
static USHORT aFmtMap[25]; // Zuordnung: Zelle->Format
Rectangle aCellArray[25]; // Position und Groesse der Zellen
SvxBoxItem* aLinePtrArray[49]; // LinienAttribute
Size aPrvSize;
const USHORT nLabelColWidth;
const USHORT nDataColWidth1;
const USHORT nDataColWidth2;
const USHORT nRowHeight;
const String aStrJan;
const String aStrFeb;
const String aStrMar;
const String aStrNorth;
const String aStrMid;
const String aStrSouth;
const String aStrSum;
SvNumberFormatter* pNumFmt;
//-------------------------------------------
void Init ();
void DoPaint ( const Rectangle& rRect );
void CalcCellArray ( BOOL bFitWidth );
void CalcLineMap ();
void PaintCells ();
void DrawBackground ( USHORT nIndex );
void DrawFrame ( USHORT nIndex );
void DrawString ( USHORT nIndex );
void MakeFonts ( USHORT nIndex,
Font& rFont,
Font& rCJKFont,
Font& rCTLFont );
String MakeNumberString( String cellString, BOOL bAddDec );
void DrawFrameLine ( const SvxBorderLine& rLineD,
Point from,
Point to,
BOOL bHorizontal,
const SvxBorderLine& rLineLT,
const SvxBorderLine& rLineL,
const SvxBorderLine& rLineLB,
const SvxBorderLine& rLineRT,
const SvxBorderLine& rLineR,
const SvxBorderLine& rLineRB );
void CheckPriority ( USHORT nCurLine,
AutoFmtLine eLine,
SvxBorderLine& rLine );
void GetLines ( USHORT nIndex, AutoFmtLine eLine,
SvxBorderLine& rLineD,
SvxBorderLine& rLineLT,
SvxBorderLine& rLineL,
SvxBorderLine& rLineLB,
SvxBorderLine& rLineRT,
SvxBorderLine& rLineR,
SvxBorderLine& rLineRB );
};
#endif // SC_AUTOFMT_HXX
<commit_msg>INTEGRATION: CWS dialogdiet01 (1.3.388); FILE MERGED 2004/04/22 01:25:20 mwu 1.3.388.1: dialogdiet01_2004_04_22<commit_after>/*************************************************************************
*
* $RCSfile: autofmt.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:00:01 $
*
* 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 SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef SV_MOREBTN_HXX
#include <vcl/morebtn.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX
#include <svtools/scriptedtext.hxx>
#endif
//------------------------------------------------------------------------
class ScAutoFormat;
class ScAutoFormatData;
class SvxBoxItem;
class SvxBorderLine;
class AutoFmtPreview; // s.u.
class SvNumberFormatter;
//------------------------------------------------------------------------
enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };
//========================================================================
//CHINA001 class ScAutoFormatDlg : public ModalDialog
//CHINA001 {
//CHINA001 public:
//CHINA001 ScAutoFormatDlg( Window* pParent,
//CHINA001 ScAutoFormat* pAutoFormat,
//CHINA001 const ScAutoFormatData* pSelFormatData,
//CHINA001 ScDocument* pDoc );
//CHINA001 ~ScAutoFormatDlg();
//CHINA001
//CHINA001 USHORT GetIndex() const { return nIndex; }
//CHINA001 String GetCurrFormatName();
//CHINA001
//CHINA001 private:
//CHINA001 FixedLine aFlFormat;
//CHINA001 ListBox aLbFormat;
//CHINA001 AutoFmtPreview* pWndPreview;
//CHINA001 OKButton aBtnOk;
//CHINA001 CancelButton aBtnCancel;
//CHINA001 HelpButton aBtnHelp;
//CHINA001 PushButton aBtnAdd;
//CHINA001 PushButton aBtnRemove;
//CHINA001 MoreButton aBtnMore;
//CHINA001 FixedLine aFlFormatting;
//CHINA001 CheckBox aBtnNumFormat;
//CHINA001 CheckBox aBtnBorder;
//CHINA001 CheckBox aBtnFont;
//CHINA001 CheckBox aBtnPattern;
//CHINA001 CheckBox aBtnAlignment;
//CHINA001 CheckBox aBtnAdjust;
//CHINA001 PushButton aBtnRename;
//CHINA001 String aStrTitle;
//CHINA001 String aStrLabel;
//CHINA001 String aStrClose;
//CHINA001 String aStrDelTitle;
//CHINA001 String aStrDelMsg;
//CHINA001 String aStrRename;
//CHINA001
//CHINA001 //------------------------
//CHINA001 ScAutoFormat* pFormat;
//CHINA001 const ScAutoFormatData* pSelFmtData;
//CHINA001 USHORT nIndex;
//CHINA001 BOOL bCoreDataChanged;
//CHINA001 BOOL bFmtInserted;
//CHINA001
//CHINA001 void Init ();
//CHINA001 void UpdateChecks ();
//CHINA001 //------------------------
//CHINA001 DECL_LINK( CheckHdl, Button * );
//CHINA001 DECL_LINK( AddHdl, void * );
//CHINA001 DECL_LINK( RemoveHdl, void * );
//CHINA001 DECL_LINK( SelFmtHdl, void * );
//CHINA001 DECL_LINK( CloseHdl, PushButton * );
//CHINA001 DECL_LINK( DblClkHdl, void * );
//CHINA001 DECL_LINK( RenameHdl, void *);
//CHINA001
//CHINA001 };
//CHINA001
//========================================================================
class AutoFmtPreview : public Window
{
public:
AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
~AutoFmtPreview();
void NotifyChange( ScAutoFormatData* pNewData );
protected:
virtual void Paint( const Rectangle& rRect );
private:
ScAutoFormatData* pCurData;
VirtualDevice aVD;
SvtScriptedTextHelper aScriptedText;
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
BOOL bFitWidth;
static USHORT aFmtMap[25]; // Zuordnung: Zelle->Format
Rectangle aCellArray[25]; // Position und Groesse der Zellen
SvxBoxItem* aLinePtrArray[49]; // LinienAttribute
Size aPrvSize;
const USHORT nLabelColWidth;
const USHORT nDataColWidth1;
const USHORT nDataColWidth2;
const USHORT nRowHeight;
const String aStrJan;
const String aStrFeb;
const String aStrMar;
const String aStrNorth;
const String aStrMid;
const String aStrSouth;
const String aStrSum;
SvNumberFormatter* pNumFmt;
//-------------------------------------------
void Init ();
void DoPaint ( const Rectangle& rRect );
void CalcCellArray ( BOOL bFitWidth );
void CalcLineMap ();
void PaintCells ();
void DrawBackground ( USHORT nIndex );
void DrawFrame ( USHORT nIndex );
void DrawString ( USHORT nIndex );
void MakeFonts ( USHORT nIndex,
Font& rFont,
Font& rCJKFont,
Font& rCTLFont );
String MakeNumberString( String cellString, BOOL bAddDec );
void DrawFrameLine ( const SvxBorderLine& rLineD,
Point from,
Point to,
BOOL bHorizontal,
const SvxBorderLine& rLineLT,
const SvxBorderLine& rLineL,
const SvxBorderLine& rLineLB,
const SvxBorderLine& rLineRT,
const SvxBorderLine& rLineR,
const SvxBorderLine& rLineRB );
void CheckPriority ( USHORT nCurLine,
AutoFmtLine eLine,
SvxBorderLine& rLine );
void GetLines ( USHORT nIndex, AutoFmtLine eLine,
SvxBorderLine& rLineD,
SvxBorderLine& rLineLT,
SvxBorderLine& rLineL,
SvxBorderLine& rLineLB,
SvxBorderLine& rLineRT,
SvxBorderLine& rLineR,
SvxBorderLine& rLineRB );
};
#endif // SC_AUTOFMT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hdrcont.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2008-02-19 15:32:59 $
*
* 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_HDRCONT_HXX
#define SC_HDRCONT_HXX
#ifndef _WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _SELENG_HXX //autogen
#include <vcl/seleng.hxx>
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
// ---------------------------------------------------------------------------
#define HDR_HORIZONTAL 0
#define HDR_VERTICAL 1
#define HDR_SIZE_OPTIMUM 0xFFFF
// Groesse des Sliders
#define HDR_SLIDERSIZE 2
class ScHeaderControl : public Window
{
private:
SelectionEngine* pSelEngine;
Font aNormFont;
Font aBoldFont;
BOOL bBoldSet;
USHORT nFlags;
BOOL bVertical; // Vertikal = Zeilenheader
long nWidth;
long nSmallWidth;
long nBigWidth;
SCCOLROW nSize;
SCCOLROW nMarkStart;
SCCOLROW nMarkEnd;
BOOL bMarkRange;
BOOL bDragging; // Groessen aendern
SCCOLROW nDragNo;
long nDragStart;
long nDragPos;
BOOL bDragMoved;
BOOL bIgnoreMove;
long GetScrPos( SCCOLROW nEntryNo );
SCCOLROW GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder );
void ShowDragHelp();
void DoPaint( SCCOLROW nStart, SCCOLROW nEnd );
void DrawShadedRect( long nStart, long nEnd, const Color& rBaseColor );
protected:
// von Window ueberladen
virtual void Paint( const Rectangle& rRect );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void Tracking( const TrackingEvent& rTEvt );
virtual void RequestHelp( const HelpEvent& rHEvt );
// neue Methoden
virtual SCCOLROW GetPos() = 0; // aktuelle Position (Scrolling)
virtual USHORT GetEntrySize( SCCOLROW nEntryNo ) = 0; // Breite / Hoehe (Pixel)
virtual String GetEntryText( SCCOLROW nEntryNo ) = 0;
virtual SCCOLROW GetHiddenCount( SCCOLROW nEntryNo );
virtual BOOL IsLayoutRTL();
virtual BOOL IsMirrored();
virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewWidth ) = 0;
virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ) = 0;
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual String GetDragHelp( long nVal );
virtual void DrawInvert( long nDragPos );
virtual void Command( const CommandEvent& rCEvt );
public:
ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine,
SCCOLROW nNewSize, USHORT nNewFlags );
~ScHeaderControl();
void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; }
void StopMarking();
void SetMark( BOOL bNewSet, SCCOLROW nNewStart, SCCOLROW nNewEnd );
long GetWidth() const { return nWidth; }
long GetSmallWidth() const { return nSmallWidth; }
long GetBigWidth() const { return nBigWidth; }
void SetWidth( long nNew );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.64); FILE MERGED 2008/04/01 15:30:54 thb 1.5.64.3: #i85898# Stripping all external header guards 2008/04/01 12:36:46 thb 1.5.64.2: #i85898# Stripping all external header guards 2008/03/31 17:15:42 rt 1.5.64.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: hdrcont.hxx,v $
* $Revision: 1.6 $
*
* 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 SC_HDRCONT_HXX
#define SC_HDRCONT_HXX
#include <vcl/window.hxx>
#ifndef _SELENG_HXX //autogen
#include <vcl/seleng.hxx>
#endif
#include "address.hxx"
// ---------------------------------------------------------------------------
#define HDR_HORIZONTAL 0
#define HDR_VERTICAL 1
#define HDR_SIZE_OPTIMUM 0xFFFF
// Groesse des Sliders
#define HDR_SLIDERSIZE 2
class ScHeaderControl : public Window
{
private:
SelectionEngine* pSelEngine;
Font aNormFont;
Font aBoldFont;
BOOL bBoldSet;
USHORT nFlags;
BOOL bVertical; // Vertikal = Zeilenheader
long nWidth;
long nSmallWidth;
long nBigWidth;
SCCOLROW nSize;
SCCOLROW nMarkStart;
SCCOLROW nMarkEnd;
BOOL bMarkRange;
BOOL bDragging; // Groessen aendern
SCCOLROW nDragNo;
long nDragStart;
long nDragPos;
BOOL bDragMoved;
BOOL bIgnoreMove;
long GetScrPos( SCCOLROW nEntryNo );
SCCOLROW GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder );
void ShowDragHelp();
void DoPaint( SCCOLROW nStart, SCCOLROW nEnd );
void DrawShadedRect( long nStart, long nEnd, const Color& rBaseColor );
protected:
// von Window ueberladen
virtual void Paint( const Rectangle& rRect );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void Tracking( const TrackingEvent& rTEvt );
virtual void RequestHelp( const HelpEvent& rHEvt );
// neue Methoden
virtual SCCOLROW GetPos() = 0; // aktuelle Position (Scrolling)
virtual USHORT GetEntrySize( SCCOLROW nEntryNo ) = 0; // Breite / Hoehe (Pixel)
virtual String GetEntryText( SCCOLROW nEntryNo ) = 0;
virtual SCCOLROW GetHiddenCount( SCCOLROW nEntryNo );
virtual BOOL IsLayoutRTL();
virtual BOOL IsMirrored();
virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewWidth ) = 0;
virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ) = 0;
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual String GetDragHelp( long nVal );
virtual void DrawInvert( long nDragPos );
virtual void Command( const CommandEvent& rCEvt );
public:
ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine,
SCCOLROW nNewSize, USHORT nNewFlags );
~ScHeaderControl();
void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; }
void StopMarking();
void SetMark( BOOL bNewSet, SCCOLROW nNewStart, SCCOLROW nNewEnd );
long GetWidth() const { return nWidth; }
long GetSmallWidth() const { return nSmallWidth; }
long GetBigWidth() const { return nBigWidth; }
void SetWidth( long nNew );
};
#endif
<|endoftext|> |
<commit_before>//
// WidgetDefProvider.cpp
// Chilli Source
// Created by Scott Downie on 25/07/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/UI/Base/WidgetDefProvider.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/Utils.h>
#include <ChilliSource/Core/Resource/ResourcePool.h>
#include <ChilliSource/Core/String/StringParser.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <ChilliSource/UI/Base/PropertyMap.h>
#include <ChilliSource/UI/Base/PropertyType.h>
#include <ChilliSource/UI/Base/Widget.h>
#include <ChilliSource/UI/Base/WidgetDef.h>
#include <ChilliSource/UI/Base/WidgetHierarchyDesc.h>
#include <ChilliSource/UI/Base/WidgetParserUtils.h>
#include <ChilliSource/UI/Base/WidgetTemplate.h>
#include <ChilliSource/UI/Base/WidgetTemplateProvider.h>
#include <json/json.h>
namespace ChilliSource
{
namespace UI
{
namespace
{
const std::string k_extension("csuidef");
//-------------------------------------------------------
/// From the given JSON value parse the values of the property
/// types into the given container. Some of the properties
/// require conversion from relative to absolute paths
/// hence the definition path info.
///
/// @author S Downie
///
/// @param Json defaults
/// @param Definition location
/// @param Defintion path (no file name)
/// @param [Out] Default property values
/// @param [Out] Custom property values
//-------------------------------------------------------
void ParseDefaultValues(const Json::Value& in_defaults, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, PropertyMap& out_defaultProperties, PropertyMap& out_customProperties);
//-------------------------------------------------------
/// From the given JSON value parse the hierarchy and
/// create definitions for all child widgets. Some of the properties
/// require conversion from relative to absolute paths
/// hence the definition path info.
///
/// @author S Downie
///
/// @param Json hierarchy
/// @param Json widgets
/// @param Definition location
/// @param Defintion path (no file name)
/// @param [Out] Children descriptions
//-------------------------------------------------------
void ParseChildWidgets(const Json::Value& in_hierarchy, const Json::Value& in_widgets, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, std::vector<WidgetHierarchyDesc>& out_children)
{
for(u32 i=0; i<in_hierarchy.size(); ++i)
{
const Json::Value& hierarchyItem = in_hierarchy[i];
std::string name = hierarchyItem["Name"].asString();
const Json::Value& widget = in_widgets[name];
WidgetHierarchyDesc childDesc;
WidgetTemplateProvider::ParseTemplate(widget, in_definitionLocation, in_definitionPath, childDesc);
childDesc.m_defaultProperties.SetProperty("Name", name);
childDesc.m_access = WidgetHierarchyDesc::Access::k_internal;
const Json::Value& children = hierarchyItem["Children"];
if(children.isNull() == false)
{
ParseChildWidgets(children, in_widgets, in_definitionLocation, in_definitionPath, childDesc.m_children);
}
out_children.push_back(childDesc);
}
}
//-------------------------------------------------------
/// From the given JSON value parse the custom property
/// types, names and values into the given container
///
/// @author S Downie
///
/// @param Json properties
/// @param [Out] Custom properties
//-------------------------------------------------------
void ParseCustomProperties(const Json::Value& in_properties, PropertyMap& out_customProperties)
{
std::vector<PropertyMap::PropertyDesc> descs;
descs.reserve(in_properties.size());
for(auto it = in_properties.begin(); it != in_properties.end(); ++it)
{
CS_ASSERT((*it).isString() == true, "WidgetDefProvider: Properties values in file must be strings: " + std::string(it.memberName()));
PropertyMap::PropertyDesc desc;
desc.m_type = ParsePropertyType((*it).asString());
desc.m_name = it.memberName();
descs.push_back(desc);
}
out_customProperties.AllocateKeys(descs);
}
//-------------------------------------------------------
//-------------------------------------------------------
void ParseDefaultValues(const Json::Value& in_defaults, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, PropertyMap& out_defaultProperties, PropertyMap& out_customProperties)
{
out_defaultProperties.AllocateKeys(Widget::GetPropertyDescs());
for(auto it = in_defaults.begin(); it != in_defaults.end(); ++it)
{
if(out_defaultProperties.HasProperty(it.memberName()) == true)
{
if(strcmp(it.memberName(), "Drawable") == 0)
{
//Special case for drawable
CS_ASSERT((*it).isObject(), "Value can only be specified as object: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(it.memberName(), WidgetParserUtils::ParseDrawableValues(*it, in_definitionLocation, in_definitionPath));
}
else if(strcmp(it.memberName(), "Layout") == 0)
{
//Special case for drawable
CS_ASSERT((*it).isObject(), "Value can only be specified as object: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(it.memberName(), WidgetParserUtils::ParseLayoutValues(*it));
}
else
{
CS_ASSERT((*it).isString(), "Value can only be specified as string: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(out_defaultProperties.GetType(it.memberName()), it.memberName(), (*it).asString());
}
}
else if(out_customProperties.HasProperty(it.memberName()) == true)
{
CS_ASSERT((*it).isString(), "Value can only be specified as string: " + std::string(it.memberName()));
out_customProperties.SetProperty(out_customProperties.GetType(it.memberName()), it.memberName(), (*it).asString());
}
else
{
CS_LOG_FATAL("Property with name does not exist: " + std::string(it.memberName()));
}
}
}
//-------------------------------------------------------
/// Performs the heavy lifting for loading a UI
/// widget description from file
///
/// @author S Downie
///
/// @param Storage location
/// @param File path
/// @param Async load delegate
/// @param [Out] Resource
//-------------------------------------------------------
void LoadDesc(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::ResourceProvider::AsyncLoadDelegate& in_delegate, const Core::ResourceSPtr& out_resource)
{
Json::Value root;
Core::Utils::ReadJson(in_storageLocation, in_filepath, &root);
WidgetDef* widgetDef = (WidgetDef*)out_resource.get();
WidgetHierarchyDesc hierarchyDesc;
hierarchyDesc.m_access = WidgetHierarchyDesc::Access::k_internal;
CS_ASSERT(root.isMember("Type"), "Widget def must have Type");
hierarchyDesc.m_type = root["Type"].asString();
std::string definitionFileName;
std::string pathToDefinition;
Core::StringUtils::SplitFilename(in_filepath, definitionFileName, pathToDefinition);
const Json::Value& hierarchy = root["Hierarchy"];
const Json::Value& children = root["Children"];
if(hierarchy.isNull() == false && hierarchy.isArray() == true && children.isNull() == false)
{
ParseChildWidgets(hierarchy, children, in_storageLocation, pathToDefinition, hierarchyDesc.m_children);
}
const Json::Value& customProperties = root["Properties"];
if(customProperties.isNull() == false)
{
ParseCustomProperties(customProperties, hierarchyDesc.m_customProperties);
}
const Json::Value& defaults = root["Defaults"];
if(defaults.isNull() == false)
{
ParseDefaultValues(defaults, in_storageLocation, pathToDefinition, hierarchyDesc.m_defaultProperties, hierarchyDesc.m_customProperties);
}
widgetDef->Build(hierarchyDesc);
out_resource->SetLoadState(CSCore::Resource::LoadState::k_loaded);
if(in_delegate != nullptr)
{
CSCore::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(in_delegate, out_resource));
}
}
}
CS_DEFINE_NAMEDTYPE(WidgetDefProvider);
//-------------------------------------------------------
//-------------------------------------------------------
WidgetDefProviderUPtr WidgetDefProvider::Create()
{
return WidgetDefProviderUPtr(new WidgetDefProvider());
}
//-------------------------------------------------------
//-------------------------------------------------------
bool WidgetDefProvider::IsA(Core::InterfaceIDType in_interfaceId) const
{
return (in_interfaceId == Core::ResourceProvider::InterfaceID || in_interfaceId == WidgetDefProvider::InterfaceID);
}
//-------------------------------------------------------
//-------------------------------------------------------
Core::InterfaceIDType WidgetDefProvider::GetResourceType() const
{
return WidgetDef::InterfaceID;
}
//-------------------------------------------------------
//-------------------------------------------------------
bool WidgetDefProvider::CanCreateResourceWithFileExtension(const std::string& in_extension) const
{
return (in_extension == k_extension);
}
//-------------------------------------------------------
//-------------------------------------------------------
void WidgetDefProvider::CreateResourceFromFile(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::IResourceOptionsBaseCSPtr& in_options, const Core::ResourceSPtr& out_resource)
{
LoadDesc(in_storageLocation, in_filepath, nullptr, out_resource);
}
//----------------------------------------------------
//----------------------------------------------------
void WidgetDefProvider::CreateResourceFromFileAsync(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::IResourceOptionsBaseCSPtr& in_options, const AsyncLoadDelegate& in_delegate, const Core::ResourceSPtr& out_resource)
{
auto task = std::bind(LoadDesc, in_storageLocation, in_filepath, in_delegate, out_resource);
Core::Application::Get()->GetTaskScheduler()->ScheduleTask(task);
}
}
}
<commit_msg>Parsing property links from widget def<commit_after>//
// WidgetDefProvider.cpp
// Chilli Source
// Created by Scott Downie on 25/07/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/UI/Base/WidgetDefProvider.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/Utils.h>
#include <ChilliSource/Core/Resource/ResourcePool.h>
#include <ChilliSource/Core/String/StringParser.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <ChilliSource/UI/Base/PropertyMap.h>
#include <ChilliSource/UI/Base/PropertyType.h>
#include <ChilliSource/UI/Base/Widget.h>
#include <ChilliSource/UI/Base/WidgetDef.h>
#include <ChilliSource/UI/Base/WidgetHierarchyDesc.h>
#include <ChilliSource/UI/Base/WidgetParserUtils.h>
#include <ChilliSource/UI/Base/WidgetTemplate.h>
#include <ChilliSource/UI/Base/WidgetTemplateProvider.h>
#include <json/json.h>
namespace ChilliSource
{
namespace UI
{
namespace
{
const std::string k_extension("csuidef");
//-------------------------------------------------------
/// From the given JSON value parse the values of the property
/// types into the given container. Some of the properties
/// require conversion from relative to absolute paths
/// hence the definition path info.
///
/// @author S Downie
///
/// @param Json defaults
/// @param Definition location
/// @param Defintion path (no file name)
/// @param [Out] Default property values
/// @param [Out] Custom property values
//-------------------------------------------------------
void ParseDefaultValues(const Json::Value& in_defaults, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, PropertyMap& out_defaultProperties, PropertyMap& out_customProperties);
//-------------------------------------------------------
/// From the given JSON value parse the hierarchy and
/// create definitions for all child widgets. Some of the properties
/// require conversion from relative to absolute paths
/// hence the definition path info.
///
/// @author S Downie
///
/// @param Json hierarchy
/// @param Json widgets
/// @param Definition location
/// @param Defintion path (no file name)
/// @param [Out] Children descriptions
//-------------------------------------------------------
void ParseChildWidgets(const Json::Value& in_hierarchy, const Json::Value& in_widgets, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, std::vector<WidgetHierarchyDesc>& out_children)
{
for(u32 i=0; i<in_hierarchy.size(); ++i)
{
const Json::Value& hierarchyItem = in_hierarchy[i];
std::string name = hierarchyItem["Name"].asString();
const Json::Value& widget = in_widgets[name];
WidgetHierarchyDesc childDesc;
WidgetTemplateProvider::ParseTemplate(widget, in_definitionLocation, in_definitionPath, childDesc);
childDesc.m_defaultProperties.SetProperty("Name", name);
childDesc.m_access = WidgetHierarchyDesc::Access::k_internal;
const Json::Value& children = hierarchyItem["Children"];
if(children.isNull() == false)
{
ParseChildWidgets(children, in_widgets, in_definitionLocation, in_definitionPath, childDesc.m_children);
}
out_children.push_back(childDesc);
}
}
//-------------------------------------------------------
/// From the given JSON value parse the custom property
/// types, names and values into the given container
///
/// @author S Downie
///
/// @param Json properties
/// @param [Out] Custom properties
//-------------------------------------------------------
void ParseCustomProperties(const Json::Value& in_properties, PropertyMap& out_customProperties)
{
std::vector<PropertyMap::PropertyDesc> descs;
descs.reserve(in_properties.size());
for(auto it = in_properties.begin(); it != in_properties.end(); ++it)
{
CS_ASSERT((*it).isString() == true, "WidgetDefProvider: Properties values in file must be strings: " + std::string(it.memberName()));
PropertyMap::PropertyDesc desc;
desc.m_type = ParsePropertyType((*it).asString());
desc.m_name = it.memberName();
descs.push_back(desc);
}
out_customProperties.AllocateKeys(descs);
}
//-------------------------------------------------------
//-------------------------------------------------------
void ParseDefaultValues(const Json::Value& in_defaults, Core::StorageLocation in_definitionLocation, const std::string& in_definitionPath, PropertyMap& out_defaultProperties, PropertyMap& out_customProperties)
{
out_defaultProperties.AllocateKeys(Widget::GetPropertyDescs());
for(auto it = in_defaults.begin(); it != in_defaults.end(); ++it)
{
if(out_defaultProperties.HasProperty(it.memberName()) == true)
{
if(strcmp(it.memberName(), "Drawable") == 0)
{
//Special case for drawable
CS_ASSERT((*it).isObject(), "Value can only be specified as object: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(it.memberName(), WidgetParserUtils::ParseDrawableValues(*it, in_definitionLocation, in_definitionPath));
}
else if(strcmp(it.memberName(), "Layout") == 0)
{
//Special case for drawable
CS_ASSERT((*it).isObject(), "Value can only be specified as object: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(it.memberName(), WidgetParserUtils::ParseLayoutValues(*it));
}
else
{
CS_ASSERT((*it).isString(), "Value can only be specified as string: " + std::string(it.memberName()));
out_defaultProperties.SetProperty(out_defaultProperties.GetType(it.memberName()), it.memberName(), (*it).asString());
}
}
else if(out_customProperties.HasProperty(it.memberName()) == true)
{
CS_ASSERT((*it).isString(), "Value can only be specified as string: " + std::string(it.memberName()));
out_customProperties.SetProperty(out_customProperties.GetType(it.memberName()), it.memberName(), (*it).asString());
}
else
{
CS_LOG_FATAL("Property with name does not exist: " + std::string(it.memberName()));
}
}
}
//-------------------------------------------------------
/// Parses and builds the links for a parent property
/// that directly affects a child property
///
/// @author S Downie
///
/// @param JSON object containing all exposed properties
/// @param [Out] Links
//-------------------------------------------------------
void ParseLinkedChildProperties(const Json::Value& in_properties, std::vector<WidgetHierarchyDesc::WidgetPropertyLink>& out_links)
{
for(auto it = in_properties.begin(); it != in_properties.end(); ++it)
{
WidgetHierarchyDesc::WidgetPropertyLink link;
link.m_linkName = it.memberName();
link.m_widgetName = (*it)["Child"].asString();
link.m_propertyName = (*it)["Property"].asString();
out_links.push_back(link);
}
}
//-------------------------------------------------------
/// Performs the heavy lifting for loading a UI
/// widget description from file
///
/// @author S Downie
///
/// @param Storage location
/// @param File path
/// @param Async load delegate
/// @param [Out] Resource
//-------------------------------------------------------
void LoadDesc(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::ResourceProvider::AsyncLoadDelegate& in_delegate, const Core::ResourceSPtr& out_resource)
{
Json::Value root;
Core::Utils::ReadJson(in_storageLocation, in_filepath, &root);
WidgetDef* widgetDef = (WidgetDef*)out_resource.get();
WidgetHierarchyDesc hierarchyDesc;
hierarchyDesc.m_access = WidgetHierarchyDesc::Access::k_internal;
CS_ASSERT(root.isMember("Type"), "Widget def must have Type");
hierarchyDesc.m_type = root["Type"].asString();
std::string definitionFileName;
std::string pathToDefinition;
Core::StringUtils::SplitFilename(in_filepath, definitionFileName, pathToDefinition);
const Json::Value& hierarchy = root["Hierarchy"];
const Json::Value& children = root["Children"];
if(hierarchy.isNull() == false && hierarchy.isArray() == true && children.isNull() == false)
{
ParseChildWidgets(hierarchy, children, in_storageLocation, pathToDefinition, hierarchyDesc.m_children);
}
const Json::Value& customProperties = root["Properties"];
if(customProperties.isNull() == false)
{
ParseCustomProperties(customProperties, hierarchyDesc.m_customProperties);
}
const Json::Value& defaults = root["Defaults"];
if(defaults.isNull() == false)
{
ParseDefaultValues(defaults, in_storageLocation, pathToDefinition, hierarchyDesc.m_defaultProperties, hierarchyDesc.m_customProperties);
}
const Json::Value& childProperties = root["ChildProperties"];
if(childProperties.isNull() == false)
{
ParseLinkedChildProperties(childProperties, hierarchyDesc.m_links);
}
widgetDef->Build(hierarchyDesc);
out_resource->SetLoadState(CSCore::Resource::LoadState::k_loaded);
if(in_delegate != nullptr)
{
CSCore::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(in_delegate, out_resource));
}
}
}
CS_DEFINE_NAMEDTYPE(WidgetDefProvider);
//-------------------------------------------------------
//-------------------------------------------------------
WidgetDefProviderUPtr WidgetDefProvider::Create()
{
return WidgetDefProviderUPtr(new WidgetDefProvider());
}
//-------------------------------------------------------
//-------------------------------------------------------
bool WidgetDefProvider::IsA(Core::InterfaceIDType in_interfaceId) const
{
return (in_interfaceId == Core::ResourceProvider::InterfaceID || in_interfaceId == WidgetDefProvider::InterfaceID);
}
//-------------------------------------------------------
//-------------------------------------------------------
Core::InterfaceIDType WidgetDefProvider::GetResourceType() const
{
return WidgetDef::InterfaceID;
}
//-------------------------------------------------------
//-------------------------------------------------------
bool WidgetDefProvider::CanCreateResourceWithFileExtension(const std::string& in_extension) const
{
return (in_extension == k_extension);
}
//-------------------------------------------------------
//-------------------------------------------------------
void WidgetDefProvider::CreateResourceFromFile(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::IResourceOptionsBaseCSPtr& in_options, const Core::ResourceSPtr& out_resource)
{
LoadDesc(in_storageLocation, in_filepath, nullptr, out_resource);
}
//----------------------------------------------------
//----------------------------------------------------
void WidgetDefProvider::CreateResourceFromFileAsync(Core::StorageLocation in_storageLocation, const std::string& in_filepath, const Core::IResourceOptionsBaseCSPtr& in_options, const AsyncLoadDelegate& in_delegate, const Core::ResourceSPtr& out_resource)
{
auto task = std::bind(LoadDesc, in_storageLocation, in_filepath, in_delegate, out_resource);
Core::Application::Get()->GetTaskScheduler()->ScheduleTask(task);
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "Text.h"
#include "Urho2DTileMap.h"
#include "Zone.h"
#include "TmxFile2D.h"
#include "TileMap2D.h"
#include "Drawable2D.h"
#include "DebugNew.h"
// Number of static sprites to draw
static const StringHash VAR_MOVESPEED("MoveSpeed");
static const StringHash VAR_ROTATESPEED("RotateSpeed");
DEFINE_APPLICATION_MAIN(Urho2DTileMap)
Urho2DTileMap::Urho2DTileMap(Context* context) :
Sample(context)
{
}
void Urho2DTileMap::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void Urho2DTileMap::CreateScene()
{
scene_ = new Scene(context_);
scene_->CreateComponent<Octree>();
// Create camera node
cameraNode_ = scene_->CreateChild("Camera");
// Set camera's position
cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
Camera* camera = cameraNode_->CreateComponent<Camera>();
camera->SetOrthographic(true);
Graphics* graphics = GetSubsystem<Graphics>();
camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
ResourceCache* cache = GetSubsystem<ResourceCache>();
// Get tmx file
// TmxFile2D* tmxFile = cache->GetResource<TmxFile2D>("Urho2D/isometric_grass_and_water.tmx");
TmxFile2D* tmxFile = cache->GetResource<TmxFile2D>("Urho2D/staggered_grass_and_water.tmx");
if (!tmxFile)
return;
SharedPtr<Node> tileMapNode(scene_->CreateChild("TileMap"));
tileMapNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
TileMap2D* tileMap = tileMapNode->CreateComponent<TileMap2D>();
// Set animation
tileMap->SetTmxFile(tmxFile);
// Set camera's position
const TileMapInfo2D& info = tileMap->GetInfo();
float x = info.GetMapWidth() * 0.5f;
float y = info.GetMapHeight() * 0.5f;
cameraNode_->SetPosition(Vector3(x, y, -10.0f));
}
void Urho2DTileMap::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void Urho2DTileMap::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void Urho2DTileMap::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_PAGEUP))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 1.01f);
}
if (input->GetKeyDown(KEY_PAGEDOWN))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 0.99f);
}
}
void Urho2DTileMap::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(Urho2DTileMap, HandleUpdate));
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent(E_SCENEUPDATE);
}
void Urho2DTileMap::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<commit_msg>Revert test code.[ci skip]<commit_after>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "Text.h"
#include "Urho2DTileMap.h"
#include "Zone.h"
#include "TmxFile2D.h"
#include "TileMap2D.h"
#include "Drawable2D.h"
#include "DebugNew.h"
// Number of static sprites to draw
static const StringHash VAR_MOVESPEED("MoveSpeed");
static const StringHash VAR_ROTATESPEED("RotateSpeed");
DEFINE_APPLICATION_MAIN(Urho2DTileMap)
Urho2DTileMap::Urho2DTileMap(Context* context) :
Sample(context)
{
}
void Urho2DTileMap::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void Urho2DTileMap::CreateScene()
{
scene_ = new Scene(context_);
scene_->CreateComponent<Octree>();
// Create camera node
cameraNode_ = scene_->CreateChild("Camera");
// Set camera's position
cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
Camera* camera = cameraNode_->CreateComponent<Camera>();
camera->SetOrthographic(true);
Graphics* graphics = GetSubsystem<Graphics>();
camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
ResourceCache* cache = GetSubsystem<ResourceCache>();
// Get tmx file
TmxFile2D* tmxFile = cache->GetResource<TmxFile2D>("Urho2D/isometric_grass_and_water.tmx");
if (!tmxFile)
return;
SharedPtr<Node> tileMapNode(scene_->CreateChild("TileMap"));
tileMapNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
TileMap2D* tileMap = tileMapNode->CreateComponent<TileMap2D>();
// Set animation
tileMap->SetTmxFile(tmxFile);
// Set camera's position
const TileMapInfo2D& info = tileMap->GetInfo();
float x = info.GetMapWidth() * 0.5f;
float y = info.GetMapHeight() * 0.5f;
cameraNode_->SetPosition(Vector3(x, y, -10.0f));
}
void Urho2DTileMap::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void Urho2DTileMap::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void Urho2DTileMap::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_PAGEUP))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 1.01f);
}
if (input->GetKeyDown(KEY_PAGEDOWN))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 0.99f);
}
}
void Urho2DTileMap::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(Urho2DTileMap, HandleUpdate));
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent(E_SCENEUPDATE);
}
void Urho2DTileMap::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/core/v8/V8GCForContextDispose.h"
#include "bindings/core/v8/V8PerIsolateData.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
#include <v8.h>
namespace blink {
V8GCForContextDispose::V8GCForContextDispose()
: m_pseudoIdleTimer(this, &V8GCForContextDispose::pseudoIdleTimerFired)
{
reset();
}
void V8GCForContextDispose::notifyContextDisposed(bool isMainFrame)
{
m_didDisposeContextForMainFrame = isMainFrame;
m_lastContextDisposalTime = WTF::currentTime();
V8PerIsolateData::mainThreadIsolate()->ContextDisposedNotification();
if (m_pseudoIdleTimer.isActive())
m_pseudoIdleTimer.stop();
}
void V8GCForContextDispose::notifyIdle()
{
double maxTimeSinceLastContextDisposal = .2;
if (!m_didDisposeContextForMainFrame && !m_pseudoIdleTimer.isActive() && m_lastContextDisposalTime + maxTimeSinceLastContextDisposal >= WTF::currentTime()) {
m_pseudoIdleTimer.startOneShot(0, FROM_HERE);
}
}
V8GCForContextDispose& V8GCForContextDispose::instance()
{
DEFINE_STATIC_LOCAL(V8GCForContextDispose, staticInstance, ());
return staticInstance;
}
void V8GCForContextDispose::pseudoIdleTimerFired(Timer<V8GCForContextDispose>*)
{
V8PerIsolateData::mainThreadIsolate()->IdleNotification(0);
reset();
}
void V8GCForContextDispose::reset()
{
m_didDisposeContextForMainFrame = false;
m_lastContextDisposalTime = -1;
}
} // namespace blink
<commit_msg>When notifying V8 about a context disposal include whether it's the main frame<commit_after>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/core/v8/V8GCForContextDispose.h"
#include "bindings/core/v8/V8PerIsolateData.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
#include <v8.h>
namespace blink {
V8GCForContextDispose::V8GCForContextDispose()
: m_pseudoIdleTimer(this, &V8GCForContextDispose::pseudoIdleTimerFired)
{
reset();
}
void V8GCForContextDispose::notifyContextDisposed(bool isMainFrame)
{
m_didDisposeContextForMainFrame = isMainFrame;
m_lastContextDisposalTime = WTF::currentTime();
V8PerIsolateData::mainThreadIsolate()->ContextDisposedNotification(!isMainFrame);
if (m_pseudoIdleTimer.isActive())
m_pseudoIdleTimer.stop();
}
void V8GCForContextDispose::notifyIdle()
{
double maxTimeSinceLastContextDisposal = .2;
if (!m_didDisposeContextForMainFrame && !m_pseudoIdleTimer.isActive() && m_lastContextDisposalTime + maxTimeSinceLastContextDisposal >= WTF::currentTime()) {
m_pseudoIdleTimer.startOneShot(0, FROM_HERE);
}
}
V8GCForContextDispose& V8GCForContextDispose::instance()
{
DEFINE_STATIC_LOCAL(V8GCForContextDispose, staticInstance, ());
return staticInstance;
}
void V8GCForContextDispose::pseudoIdleTimerFired(Timer<V8GCForContextDispose>*)
{
V8PerIsolateData::mainThreadIsolate()->IdleNotification(0);
reset();
}
void V8GCForContextDispose::reset()
{
m_didDisposeContextForMainFrame = false;
m_lastContextDisposalTime = -1;
}
} // namespace blink
<|endoftext|> |
<commit_before>#ifndef KISSFFT_CLASS_HH
#include <complex>
#include <vector>
namespace kissfft_utils {
template <typename T_scalar>
struct traits
{
typedef T_scalar scalar_type;
typedef std::complex<scalar_type> cpx_type;
void fill_twiddles( std::complex<T_scalar> * dst ,int nfft,bool inverse)
{
T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft;
for (int i=0;i<nfft;++i)
dst[i] = exp( std::complex<T_scalar>(0,i*phinc) );
}
void prepare(
std::vector< std::complex<T_scalar> > & dst,
int nfft,bool inverse,
std::vector<int> & stageRadix,
std::vector<int> & stageRemainder )
{
_twiddles.resize(nfft);
fill_twiddles( &_twiddles[0],nfft,inverse);
dst = _twiddles;
//factorize
//start factoring out 4's, then 2's, then 3,5,7,9,...
int n= nfft;
int p=4;
do {
while (n % p) {
switch (p) {
case 4: p = 2; break;
case 2: p = 3; break;
default: p += 2; break;
}
if (p*p>n)
p=n;// no more factors
}
n /= p;
stageRadix.push_back(p);
stageRemainder.push_back(n);
}while(n>1);
}
std::vector<cpx_type> _twiddles;
const cpx_type twiddle(size_t i) { return _twiddles[i]; }
};
}
template <typename T_Scalar,
typename T_traits=kissfft_utils::traits<T_Scalar>
>
class kissfft
{
public:
typedef T_traits traits_type;
typedef typename traits_type::scalar_type scalar_type;
typedef typename traits_type::cpx_type cpx_type;
kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() )
:_nfft(nfft),_inverse(inverse),_traits(traits)
{
_traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder);
}
void transform(const cpx_type * src , cpx_type * dst)
{
kf_work(0, dst, src, 1,1);
}
private:
void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride)
{
int p = _stageRadix[stage];
int m = _stageRemainder[stage];
cpx_type * Fout_beg = Fout;
cpx_type * Fout_end = Fout + p*m;
if (m==1) {
do{
*Fout = *f;
f += fstride*in_stride;
}while(++Fout != Fout_end );
}else{
do{
// recursive call:
// DFT of size m*p performed by doing
// p instances of smaller DFTs of size m,
// each one takes a decimated version of the input
kf_work(stage+1, Fout , f, fstride*p,in_stride);
f += fstride*in_stride;
}while( (Fout += m) != Fout_end );
}
Fout=Fout_beg;
// recombine the p smaller DFTs
switch (p) {
case 2: kf_bfly2(Fout,fstride,m); break;
case 3: kf_bfly3(Fout,fstride,m); break;
case 4: kf_bfly4(Fout,fstride,m); break;
case 5: kf_bfly5(Fout,fstride,m); break;
default: kf_bfly_generic(Fout,fstride,m,p); break;
}
}
// these were #define macros in the original kiss_fft
void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;}
void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;}
void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;}
void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;}
void C_FIXDIV( cpx_type & ,int ) {} // NO-OP for float types
scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;}
scalar_type HALF_OF( const scalar_type & a) { return a*.5;}
void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;}
void kf_bfly2( cpx_type * Fout, const size_t fstride, int m)
{
for (size_t k=0;k<m;++k) {
cpx_type t = Fout[m+k] * _traits.twiddle(k*fstride);
Fout[m+k] = Fout[k] - t;
Fout[k] += t;
}
}
void kf_bfly4( cpx_type * Fout, const size_t fstride, const size_t m)
{
cpx_type scratch[7];
int negative_if_inverse = _inverse * -2 +1;
for (size_t k=0;k<m;++k) {
scratch[0] = Fout[k+m] * _traits.twiddle(k*fstride);
scratch[1] = Fout[k+2*m] * _traits.twiddle(k*fstride*2);
scratch[2] = Fout[k+3*m] * _traits.twiddle(k*fstride*3);
scratch[5] = Fout[k] - scratch[1];
Fout[k] += scratch[1];
scratch[3] = scratch[0] + scratch[2];
scratch[4] = scratch[0] - scratch[2];
scratch[4] = cpx_type( scratch[4].imag()*negative_if_inverse , -scratch[4].real()* negative_if_inverse );
Fout[k+2*m] = Fout[k] - scratch[3];
Fout[k] += scratch[3];
Fout[k+m] = scratch[5] + scratch[4];
Fout[k+3*m] = scratch[5] - scratch[4];
}
}
void kf_bfly3( cpx_type * Fout, const size_t fstride, const size_t m)
{
size_t k=m;
const size_t m2 = 2*m;
cpx_type *tw1,*tw2;
cpx_type scratch[5];
cpx_type epi3;
epi3 = _twiddles[fstride*m];
tw1=tw2=&_twiddles[0];
do{
C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
C_MUL(scratch[1],Fout[m] , *tw1);
C_MUL(scratch[2],Fout[m2] , *tw2);
C_ADD(scratch[3],scratch[1],scratch[2]);
C_SUB(scratch[0],scratch[1],scratch[2]);
tw1 += fstride;
tw2 += fstride*2;
Fout[m] = cpx_type( Fout->real() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) );
C_MULBYSCALAR( scratch[0] , epi3.imag() );
C_ADDTO(*Fout,scratch[3]);
Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() );
C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) );
++Fout;
}while(--k);
}
void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m)
{
cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
size_t u;
cpx_type scratch[13];
cpx_type * twiddles = &_twiddles[0];
cpx_type *tw;
cpx_type ya,yb;
ya = twiddles[fstride*m];
yb = twiddles[fstride*2*m];
Fout0=Fout;
Fout1=Fout0+m;
Fout2=Fout0+2*m;
Fout3=Fout0+3*m;
Fout4=Fout0+4*m;
tw=twiddles;
for ( u=0; u<m; ++u ) {
C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
scratch[0] = *Fout0;
C_MUL(scratch[1] ,*Fout1, tw[u*fstride]);
C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]);
C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]);
C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]);
C_ADD( scratch[7],scratch[1],scratch[4]);
C_SUB( scratch[10],scratch[1],scratch[4]);
C_ADD( scratch[8],scratch[2],scratch[3]);
C_SUB( scratch[9],scratch[2],scratch[3]);
C_ADDTO( *Fout0, scratch[7]);
C_ADDTO( *Fout0, scratch[8]);
scratch[5] = scratch[0] + cpx_type(
S_MUL(scratch[7].real(),ya.real() ) + S_MUL(scratch[8].real() ,yb.real() ),
S_MUL(scratch[7].imag(),ya.real()) + S_MUL(scratch[8].imag(),yb.real())
);
scratch[6] = cpx_type(
S_MUL(scratch[10].imag(),ya.imag()) + S_MUL(scratch[9].imag(),yb.imag()),
-S_MUL(scratch[10].real(),ya.imag()) - S_MUL(scratch[9].real(),yb.imag())
);
C_SUB(*Fout1,scratch[5],scratch[6]);
C_ADD(*Fout4,scratch[5],scratch[6]);
scratch[11] = scratch[0] +
cpx_type(
S_MUL(scratch[7].real(),yb.real()) + S_MUL(scratch[8].real(),ya.real()),
S_MUL(scratch[7].imag(),yb.real()) + S_MUL(scratch[8].imag(),ya.real())
);
scratch[12] = cpx_type(
-S_MUL(scratch[10].imag(),yb.imag()) + S_MUL(scratch[9].imag(),ya.imag()),
S_MUL(scratch[10].real(),yb.imag()) - S_MUL(scratch[9].real(),ya.imag())
);
C_ADD(*Fout2,scratch[11],scratch[12]);
C_SUB(*Fout3,scratch[11],scratch[12]);
++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
}
}
/* perform the butterfly for one stage of a mixed radix FFT */
void kf_bfly_generic(
cpx_type * Fout,
const size_t fstride,
int m,
int p
)
{
int u,k,q1,q;
cpx_type * twiddles = &_twiddles[0];
cpx_type t;
int Norig = _nfft;
cpx_type* scratchbuf = new cpx_type[p];
for ( u=0; u<m; ++u ) {
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
scratchbuf[q1] = Fout[ k ];
C_FIXDIV(scratchbuf[q1],p);
k += m;
}
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
size_t twidx=0;
Fout[ k ] = scratchbuf[0];
for (q=1;q<p;++q ) {
twidx += fstride * k;
if (twidx>=Norig) twidx-=Norig;
C_MUL(t,scratchbuf[q] , twiddles[twidx] );
C_ADDTO( Fout[ k ] ,t);
}
k += m;
}
}
delete[] scratchbuf;
}
int _nfft;
bool _inverse;
std::vector<cpx_type> _twiddles;
std::vector<int> _stageRadix;
std::vector<int> _stageRemainder;
traits_type _traits;
};
#endif
<commit_msg>fix(kissfft): make conversion int <-> size_t explicit<commit_after>#ifndef KISSFFT_CLASS_HH
#include <complex>
#include <vector>
namespace kissfft_utils {
template <typename T_scalar>
struct traits
{
typedef T_scalar scalar_type;
typedef std::complex<scalar_type> cpx_type;
void fill_twiddles( std::complex<T_scalar> * dst ,int nfft,bool inverse)
{
T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft;
for (int i=0;i<nfft;++i)
dst[i] = exp( std::complex<T_scalar>(0,i*phinc) );
}
void prepare(
std::vector< std::complex<T_scalar> > & dst,
int nfft,bool inverse,
std::vector<int> & stageRadix,
std::vector<int> & stageRemainder )
{
_twiddles.resize(nfft);
fill_twiddles( &_twiddles[0],nfft,inverse);
dst = _twiddles;
//factorize
//start factoring out 4's, then 2's, then 3,5,7,9,...
int n= nfft;
int p=4;
do {
while (n % p) {
switch (p) {
case 4: p = 2; break;
case 2: p = 3; break;
default: p += 2; break;
}
if (p*p>n)
p=n;// no more factors
}
n /= p;
stageRadix.push_back(p);
stageRemainder.push_back(n);
}while(n>1);
}
std::vector<cpx_type> _twiddles;
const cpx_type twiddle(size_t i) { return _twiddles[i]; }
};
}
template <typename T_Scalar,
typename T_traits=kissfft_utils::traits<T_Scalar>
>
class kissfft
{
public:
typedef T_traits traits_type;
typedef typename traits_type::scalar_type scalar_type;
typedef typename traits_type::cpx_type cpx_type;
kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() )
:_nfft(nfft),_inverse(inverse),_traits(traits)
{
_traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder);
}
void transform(const cpx_type * src , cpx_type * dst)
{
kf_work(0, dst, src, 1,1);
}
private:
void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride)
{
int p = _stageRadix[stage];
int m = _stageRemainder[stage];
cpx_type * Fout_beg = Fout;
cpx_type * Fout_end = Fout + p*m;
if (m==1) {
do{
*Fout = *f;
f += fstride*in_stride;
}while(++Fout != Fout_end );
}else{
do{
// recursive call:
// DFT of size m*p performed by doing
// p instances of smaller DFTs of size m,
// each one takes a decimated version of the input
kf_work(stage+1, Fout , f, fstride*p,in_stride);
f += fstride*in_stride;
}while( (Fout += m) != Fout_end );
}
Fout=Fout_beg;
// recombine the p smaller DFTs
switch (p) {
case 2: kf_bfly2(Fout,fstride,m); break;
case 3: kf_bfly3(Fout,fstride,m); break;
case 4: kf_bfly4(Fout,fstride,m); break;
case 5: kf_bfly5(Fout,fstride,m); break;
default: kf_bfly_generic(Fout,fstride,m,p); break;
}
}
// these were #define macros in the original kiss_fft
void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;}
void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;}
void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;}
void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;}
void C_FIXDIV( cpx_type & ,int ) {} // NO-OP for float types
scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;}
scalar_type HALF_OF( const scalar_type & a) { return a*.5;}
void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;}
void kf_bfly2( cpx_type * Fout, const size_t fstride, size_t m)
{
for (size_t k=0;k<m;++k) {
cpx_type t = Fout[m+k] * _traits.twiddle(k*fstride);
Fout[m+k] = Fout[k] - t;
Fout[k] += t;
}
}
void kf_bfly4( cpx_type * Fout, const size_t fstride, const size_t m)
{
cpx_type scratch[7];
int negative_if_inverse = _inverse * -2 +1;
for (size_t k=0;k<m;++k) {
scratch[0] = Fout[k+m] * _traits.twiddle(k*fstride);
scratch[1] = Fout[k+2*m] * _traits.twiddle(k*fstride*2);
scratch[2] = Fout[k+3*m] * _traits.twiddle(k*fstride*3);
scratch[5] = Fout[k] - scratch[1];
Fout[k] += scratch[1];
scratch[3] = scratch[0] + scratch[2];
scratch[4] = scratch[0] - scratch[2];
scratch[4] = cpx_type( scratch[4].imag()*negative_if_inverse , -scratch[4].real()* negative_if_inverse );
Fout[k+2*m] = Fout[k] - scratch[3];
Fout[k] += scratch[3];
Fout[k+m] = scratch[5] + scratch[4];
Fout[k+3*m] = scratch[5] - scratch[4];
}
}
void kf_bfly3( cpx_type * Fout, const size_t fstride, const size_t m)
{
size_t k=m;
const size_t m2 = 2*m;
cpx_type *tw1,*tw2;
cpx_type scratch[5];
cpx_type epi3;
epi3 = _twiddles[fstride*m];
tw1=tw2=&_twiddles[0];
do{
C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
C_MUL(scratch[1],Fout[m] , *tw1);
C_MUL(scratch[2],Fout[m2] , *tw2);
C_ADD(scratch[3],scratch[1],scratch[2]);
C_SUB(scratch[0],scratch[1],scratch[2]);
tw1 += fstride;
tw2 += fstride*2;
Fout[m] = cpx_type( Fout->real() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) );
C_MULBYSCALAR( scratch[0] , epi3.imag() );
C_ADDTO(*Fout,scratch[3]);
Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() );
C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) );
++Fout;
}while(--k);
}
void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m)
{
cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
size_t u;
cpx_type scratch[13];
cpx_type * twiddles = &_twiddles[0];
cpx_type *tw;
cpx_type ya,yb;
ya = twiddles[fstride*m];
yb = twiddles[fstride*2*m];
Fout0=Fout;
Fout1=Fout0+m;
Fout2=Fout0+2*m;
Fout3=Fout0+3*m;
Fout4=Fout0+4*m;
tw=twiddles;
for ( u=0; u<m; ++u ) {
C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
scratch[0] = *Fout0;
C_MUL(scratch[1] ,*Fout1, tw[u*fstride]);
C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]);
C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]);
C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]);
C_ADD( scratch[7],scratch[1],scratch[4]);
C_SUB( scratch[10],scratch[1],scratch[4]);
C_ADD( scratch[8],scratch[2],scratch[3]);
C_SUB( scratch[9],scratch[2],scratch[3]);
C_ADDTO( *Fout0, scratch[7]);
C_ADDTO( *Fout0, scratch[8]);
scratch[5] = scratch[0] + cpx_type(
S_MUL(scratch[7].real(),ya.real() ) + S_MUL(scratch[8].real() ,yb.real() ),
S_MUL(scratch[7].imag(),ya.real()) + S_MUL(scratch[8].imag(),yb.real())
);
scratch[6] = cpx_type(
S_MUL(scratch[10].imag(),ya.imag()) + S_MUL(scratch[9].imag(),yb.imag()),
-S_MUL(scratch[10].real(),ya.imag()) - S_MUL(scratch[9].real(),yb.imag())
);
C_SUB(*Fout1,scratch[5],scratch[6]);
C_ADD(*Fout4,scratch[5],scratch[6]);
scratch[11] = scratch[0] +
cpx_type(
S_MUL(scratch[7].real(),yb.real()) + S_MUL(scratch[8].real(),ya.real()),
S_MUL(scratch[7].imag(),yb.real()) + S_MUL(scratch[8].imag(),ya.real())
);
scratch[12] = cpx_type(
-S_MUL(scratch[10].imag(),yb.imag()) + S_MUL(scratch[9].imag(),ya.imag()),
S_MUL(scratch[10].real(),yb.imag()) - S_MUL(scratch[9].real(),ya.imag())
);
C_ADD(*Fout2,scratch[11],scratch[12]);
C_SUB(*Fout3,scratch[11],scratch[12]);
++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
}
}
/* perform the butterfly for one stage of a mixed radix FFT */
void kf_bfly_generic(
cpx_type * Fout,
const size_t fstride,
int m,
int p
)
{
int u,k,q1,q;
cpx_type * twiddles = &_twiddles[0];
cpx_type t;
int Norig = _nfft;
cpx_type* scratchbuf = new cpx_type[p];
for ( u=0; u<m; ++u ) {
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
scratchbuf[q1] = Fout[ k ];
C_FIXDIV(scratchbuf[q1],p);
k += m;
}
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
int twidx=0;
Fout[ k ] = scratchbuf[0];
for (q=1;q<p;++q ) {
twidx += fstride * k;
if (twidx>=Norig) twidx-=Norig;
C_MUL(t,scratchbuf[q] , twiddles[twidx] );
C_ADDTO( Fout[ k ] ,t);
}
k += m;
}
}
delete[] scratchbuf;
}
int _nfft;
bool _inverse;
std::vector<cpx_type> _twiddles;
std::vector<int> _stageRadix;
std::vector<int> _stageRemainder;
traits_type _traits;
};
#endif
<|endoftext|> |
<commit_before><commit_msg>gst/src: Allow opening device with only type defined<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2006, 2007 Apple Computer, Inc.
* Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/fonts/FontPlatformData.h"
#include "platform/LayoutTestSupport.h"
#include "platform/fonts/FontCache.h"
#if USE(HARFBUZZ)
#include "platform/fonts/harfbuzz/HarfBuzzFace.h"
#endif
#include "platform/fonts/skia/SkiaFontWin.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/win/HWndDC.h"
#include "public/platform/Platform.h"
#include "public/platform/win/WebSandboxSupport.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/StdLibExtras.h"
#include <mlang.h>
#include <objidl.h>
#include <windows.h>
namespace WebCore {
void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const
{
const float ts = m_textSize >= 0 ? m_textSize : 12;
paint->setTextSize(SkFloatToScalar(m_textSize));
paint->setTypeface(typeface());
paint->setFakeBoldText(m_syntheticBold);
paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0);
paint->setSubpixelText(m_useSubpixelPositioning);
int textFlags = paintTextFlags();
// Only set painting flags when we're actually painting.
if (context && !context->couldUseLCDRenderedText()) {
textFlags &= ~SkPaint::kLCDRenderText_Flag;
// If we *just* clear our request for LCD, then GDI seems to
// sometimes give us AA text, and sometimes give us BW text. Since the
// original intent was LCD, we want to force AA (rather than BW), so we
// add a special bit to tell Skia to do its best to avoid the BW: by
// drawing LCD offscreen and downsampling that to AA.
textFlags |= SkPaint::kGenA8FromLCD_Flag;
}
static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |
SkPaint::kLCDRenderText_Flag |
SkPaint::kGenA8FromLCD_Flag;
SkASSERT(!(textFlags & ~textFlagsMask));
uint32_t flags = paint->getFlags();
flags &= ~textFlagsMask;
flags |= textFlags;
paint->setFlags(flags);
}
// Lookup the current system settings for font smoothing.
// We cache these values for performance, but if the browser has a way to be
// notified when these change, we could re-query them at that time.
static uint32_t getSystemTextFlags()
{
static bool gInited;
static uint32_t gFlags;
if (!gInited) {
BOOL enabled;
gFlags = 0;
if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) {
gFlags |= SkPaint::kAntiAlias_Flag;
UINT smoothType;
if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) {
if (FE_FONTSMOOTHINGCLEARTYPE == smoothType)
gFlags |= SkPaint::kLCDRenderText_Flag;
}
}
gInited = true;
}
return gFlags;
}
static bool isWebFont(const String& familyName)
{
// Web-fonts have artifical names constructed to always be:
// 1. 24 characters, followed by a '\0'
// 2. the last two characters are '=='
return familyName.length() == 24
&& '=' == familyName[22] && '=' == familyName[23];
}
static int computePaintTextFlags(String fontFamilyName)
{
int textFlags = getSystemTextFlags();
// Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.
// In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,
// even when the System (getSystemTextFlags) tells us to draw only in BW.
if (isWebFont(fontFamilyName) && !isRunningLayoutTest())
textFlags |= SkPaint::kAntiAlias_Flag;
return textFlags;
}
#if !USE(HARFBUZZ)
PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size)
{
LOGFONT info;
GetObject(hfont, sizeof(info), &info);
if (size) {
int height = info.lfHeight;
if (height < 0)
height = -height;
*size = height;
}
return adoptRef(SkCreateTypefaceFromLOGFONT(info));
}
#endif
FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
: m_textSize(-1)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(true)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData()
: m_textSize(0)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
// FIXME: this constructor is needed for SVG fonts but doesn't seem to do much
FontPlatformData::FontPlatformData(float size, bool bold, bool oblique)
: m_textSize(size)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(const FontPlatformData& data)
: m_textSize(data.m_textSize)
, m_syntheticBold(data.m_syntheticBold)
, m_syntheticItalic(data.m_syntheticItalic)
, m_orientation(data.m_orientation)
, m_typeface(data.m_typeface)
, m_paintTextFlags(data.m_paintTextFlags)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(data.m_useSubpixelPositioning)
{
#if !USE(HARFBUZZ)
m_font = data.m_font;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)
: m_textSize(textSize)
, m_syntheticBold(data.m_syntheticBold)
, m_syntheticItalic(data.m_syntheticItalic)
, m_orientation(data.m_orientation)
, m_typeface(data.m_typeface)
, m_paintTextFlags(data.m_paintTextFlags)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(data.m_useSubpixelPositioning)
{
#if !USE(HARFBUZZ)
m_font = data.m_font;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family,
float textSize, bool syntheticBold, bool syntheticItalic, FontOrientation orientation,
bool useSubpixelPositioning)
: m_textSize(textSize)
, m_syntheticBold(syntheticBold)
, m_syntheticItalic(syntheticItalic)
, m_orientation(orientation)
, m_typeface(tf)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(useSubpixelPositioning)
{
m_paintTextFlags = computePaintTextFlags(fontFamilyName());
#if !USE(HARFBUZZ)
// FIXME: This can be removed together with m_font once the last few
// uses of hfont() has been eliminated.
LOGFONT logFont;
SkLOGFONTFromTypeface(m_typeface.get(), &logFont);
logFont.lfHeight = -textSize;
HFONT hFont = CreateFontIndirect(&logFont);
m_font = hFont ? RefCountedHFONT::create(hFont) : 0;
m_scriptCache = 0;
#endif
}
FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)
{
if (this != &data) {
m_textSize = data.m_textSize;
m_syntheticBold = data.m_syntheticBold;
m_syntheticItalic = data.m_syntheticItalic;
m_orientation = data.m_orientation;
m_typeface = data.m_typeface;
m_paintTextFlags = data.m_paintTextFlags;
#if !USE(HARFBUZZ)
m_font = data.m_font;
// The following fields will get re-computed if necessary.
ScriptFreeCache(&m_scriptCache);
m_scriptCache = 0;
m_scriptFontProperties.clear();
#endif
}
return *this;
}
FontPlatformData::~FontPlatformData()
{
#if !USE(HARFBUZZ)
ScriptFreeCache(&m_scriptCache);
m_scriptCache = 0;
#endif
}
String FontPlatformData::fontFamilyName() const
{
// FIXME: This returns the requested name, perhaps a better solution would be to
// return the list of names provided by SkTypeface::createFamilyNameIterator.
ASSERT(typeface());
SkString familyName;
typeface()->getFamilyName(&familyName);
return String::fromUTF8(familyName.c_str());
}
bool FontPlatformData::isFixedPitch() const
{
return typeface() && typeface()->isFixedPitch();
}
bool FontPlatformData::operator==(const FontPlatformData& a) const
{
return SkTypeface::Equal(m_typeface.get(), a.m_typeface.get())
&& m_textSize == a.m_textSize
&& m_syntheticBold == a.m_syntheticBold
&& m_syntheticItalic == a.m_syntheticItalic
&& m_orientation == a.m_orientation
&& m_isHashTableDeletedValue == a.m_isHashTableDeletedValue;
}
#if USE(HARFBUZZ)
HarfBuzzFace* FontPlatformData::harfBuzzFace() const
{
if (!m_harfBuzzFace)
m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID());
return m_harfBuzzFace.get();
}
#else
FontPlatformData::RefCountedHFONT::~RefCountedHFONT()
{
DeleteObject(m_hfont);
}
SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const
{
if (!m_scriptFontProperties) {
m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES);
memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES));
m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES);
HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get());
if (result == E_PENDING) {
HWndDC dc(0);
HGDIOBJ oldFont = SelectObject(dc, hfont());
HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
if (S_OK != hr) {
if (FontPlatformData::ensureFontLoaded(hfont())) {
// FIXME: Handle gracefully the error if this call also fails.
hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
if (S_OK != hr) {
WTF_LOG_ERROR("Unable to get the font properties after second attempt");
}
}
}
SelectObject(dc, oldFont);
}
}
return m_scriptFontProperties.get();
}
bool FontPlatformData::ensureFontLoaded(HFONT font)
{
blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport();
// if there is no sandbox, then we can assume the font
// was able to be loaded successfully already
return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;
}
#endif
bool FontPlatformData::defaultUseSubpixelPositioning()
{
#if OS(WIN)
return FontCache::fontCache()->useSubpixelPositioning();
#else
return false;
#endif
}
#ifndef NDEBUG
String FontPlatformData::description() const
{
return String();
}
#endif
} // namespace WebCore
<commit_msg>Remove redundant ifdef in FontPlatformDataWin.cpp<commit_after>/*
* Copyright (C) 2006, 2007 Apple Computer, Inc.
* Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/fonts/FontPlatformData.h"
#include "platform/LayoutTestSupport.h"
#include "platform/fonts/FontCache.h"
#if USE(HARFBUZZ)
#include "platform/fonts/harfbuzz/HarfBuzzFace.h"
#endif
#include "platform/fonts/skia/SkiaFontWin.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/win/HWndDC.h"
#include "public/platform/Platform.h"
#include "public/platform/win/WebSandboxSupport.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/StdLibExtras.h"
#include <mlang.h>
#include <objidl.h>
#include <windows.h>
namespace WebCore {
void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const
{
const float ts = m_textSize >= 0 ? m_textSize : 12;
paint->setTextSize(SkFloatToScalar(m_textSize));
paint->setTypeface(typeface());
paint->setFakeBoldText(m_syntheticBold);
paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0);
paint->setSubpixelText(m_useSubpixelPositioning);
int textFlags = paintTextFlags();
// Only set painting flags when we're actually painting.
if (context && !context->couldUseLCDRenderedText()) {
textFlags &= ~SkPaint::kLCDRenderText_Flag;
// If we *just* clear our request for LCD, then GDI seems to
// sometimes give us AA text, and sometimes give us BW text. Since the
// original intent was LCD, we want to force AA (rather than BW), so we
// add a special bit to tell Skia to do its best to avoid the BW: by
// drawing LCD offscreen and downsampling that to AA.
textFlags |= SkPaint::kGenA8FromLCD_Flag;
}
static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |
SkPaint::kLCDRenderText_Flag |
SkPaint::kGenA8FromLCD_Flag;
SkASSERT(!(textFlags & ~textFlagsMask));
uint32_t flags = paint->getFlags();
flags &= ~textFlagsMask;
flags |= textFlags;
paint->setFlags(flags);
}
// Lookup the current system settings for font smoothing.
// We cache these values for performance, but if the browser has a way to be
// notified when these change, we could re-query them at that time.
static uint32_t getSystemTextFlags()
{
static bool gInited;
static uint32_t gFlags;
if (!gInited) {
BOOL enabled;
gFlags = 0;
if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) {
gFlags |= SkPaint::kAntiAlias_Flag;
UINT smoothType;
if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) {
if (FE_FONTSMOOTHINGCLEARTYPE == smoothType)
gFlags |= SkPaint::kLCDRenderText_Flag;
}
}
gInited = true;
}
return gFlags;
}
static bool isWebFont(const String& familyName)
{
// Web-fonts have artifical names constructed to always be:
// 1. 24 characters, followed by a '\0'
// 2. the last two characters are '=='
return familyName.length() == 24
&& '=' == familyName[22] && '=' == familyName[23];
}
static int computePaintTextFlags(String fontFamilyName)
{
int textFlags = getSystemTextFlags();
// Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.
// In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,
// even when the System (getSystemTextFlags) tells us to draw only in BW.
if (isWebFont(fontFamilyName) && !isRunningLayoutTest())
textFlags |= SkPaint::kAntiAlias_Flag;
return textFlags;
}
#if !USE(HARFBUZZ)
PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size)
{
LOGFONT info;
GetObject(hfont, sizeof(info), &info);
if (size) {
int height = info.lfHeight;
if (height < 0)
height = -height;
*size = height;
}
return adoptRef(SkCreateTypefaceFromLOGFONT(info));
}
#endif
FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
: m_textSize(-1)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(true)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData()
: m_textSize(0)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
// FIXME: this constructor is needed for SVG fonts but doesn't seem to do much
FontPlatformData::FontPlatformData(float size, bool bold, bool oblique)
: m_textSize(size)
, m_syntheticBold(false)
, m_syntheticItalic(false)
, m_orientation(Horizontal)
, m_typeface(adoptRef(SkTypeface::RefDefault()))
, m_paintTextFlags(0)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(false)
{
#if !USE(HARFBUZZ)
m_font = 0;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(const FontPlatformData& data)
: m_textSize(data.m_textSize)
, m_syntheticBold(data.m_syntheticBold)
, m_syntheticItalic(data.m_syntheticItalic)
, m_orientation(data.m_orientation)
, m_typeface(data.m_typeface)
, m_paintTextFlags(data.m_paintTextFlags)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(data.m_useSubpixelPositioning)
{
#if !USE(HARFBUZZ)
m_font = data.m_font;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)
: m_textSize(textSize)
, m_syntheticBold(data.m_syntheticBold)
, m_syntheticItalic(data.m_syntheticItalic)
, m_orientation(data.m_orientation)
, m_typeface(data.m_typeface)
, m_paintTextFlags(data.m_paintTextFlags)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(data.m_useSubpixelPositioning)
{
#if !USE(HARFBUZZ)
m_font = data.m_font;
m_scriptCache = 0;
#endif
}
FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family,
float textSize, bool syntheticBold, bool syntheticItalic, FontOrientation orientation,
bool useSubpixelPositioning)
: m_textSize(textSize)
, m_syntheticBold(syntheticBold)
, m_syntheticItalic(syntheticItalic)
, m_orientation(orientation)
, m_typeface(tf)
, m_isHashTableDeletedValue(false)
, m_useSubpixelPositioning(useSubpixelPositioning)
{
m_paintTextFlags = computePaintTextFlags(fontFamilyName());
#if !USE(HARFBUZZ)
// FIXME: This can be removed together with m_font once the last few
// uses of hfont() has been eliminated.
LOGFONT logFont;
SkLOGFONTFromTypeface(m_typeface.get(), &logFont);
logFont.lfHeight = -textSize;
HFONT hFont = CreateFontIndirect(&logFont);
m_font = hFont ? RefCountedHFONT::create(hFont) : 0;
m_scriptCache = 0;
#endif
}
FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)
{
if (this != &data) {
m_textSize = data.m_textSize;
m_syntheticBold = data.m_syntheticBold;
m_syntheticItalic = data.m_syntheticItalic;
m_orientation = data.m_orientation;
m_typeface = data.m_typeface;
m_paintTextFlags = data.m_paintTextFlags;
#if !USE(HARFBUZZ)
m_font = data.m_font;
// The following fields will get re-computed if necessary.
ScriptFreeCache(&m_scriptCache);
m_scriptCache = 0;
m_scriptFontProperties.clear();
#endif
}
return *this;
}
FontPlatformData::~FontPlatformData()
{
#if !USE(HARFBUZZ)
ScriptFreeCache(&m_scriptCache);
m_scriptCache = 0;
#endif
}
String FontPlatformData::fontFamilyName() const
{
// FIXME: This returns the requested name, perhaps a better solution would be to
// return the list of names provided by SkTypeface::createFamilyNameIterator.
ASSERT(typeface());
SkString familyName;
typeface()->getFamilyName(&familyName);
return String::fromUTF8(familyName.c_str());
}
bool FontPlatformData::isFixedPitch() const
{
return typeface() && typeface()->isFixedPitch();
}
bool FontPlatformData::operator==(const FontPlatformData& a) const
{
return SkTypeface::Equal(m_typeface.get(), a.m_typeface.get())
&& m_textSize == a.m_textSize
&& m_syntheticBold == a.m_syntheticBold
&& m_syntheticItalic == a.m_syntheticItalic
&& m_orientation == a.m_orientation
&& m_isHashTableDeletedValue == a.m_isHashTableDeletedValue;
}
#if USE(HARFBUZZ)
HarfBuzzFace* FontPlatformData::harfBuzzFace() const
{
if (!m_harfBuzzFace)
m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID());
return m_harfBuzzFace.get();
}
#else
FontPlatformData::RefCountedHFONT::~RefCountedHFONT()
{
DeleteObject(m_hfont);
}
SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const
{
if (!m_scriptFontProperties) {
m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES);
memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES));
m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES);
HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get());
if (result == E_PENDING) {
HWndDC dc(0);
HGDIOBJ oldFont = SelectObject(dc, hfont());
HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
if (S_OK != hr) {
if (FontPlatformData::ensureFontLoaded(hfont())) {
// FIXME: Handle gracefully the error if this call also fails.
hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
if (S_OK != hr) {
WTF_LOG_ERROR("Unable to get the font properties after second attempt");
}
}
}
SelectObject(dc, oldFont);
}
}
return m_scriptFontProperties.get();
}
bool FontPlatformData::ensureFontLoaded(HFONT font)
{
blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport();
// if there is no sandbox, then we can assume the font
// was able to be loaded successfully already
return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;
}
#endif
bool FontPlatformData::defaultUseSubpixelPositioning()
{
return FontCache::fontCache()->useSubpixelPositioning();
}
#ifndef NDEBUG
String FontPlatformData::description() const
{
return String();
}
#endif
} // namespace WebCore
<|endoftext|> |
<commit_before>#include "specializeParenOpExprs.h"
#include "expr.h"
#include "stmt.h"
#include "stringutil.h"
#include "symtab.h"
//#define NO_RESOLVE_CONSTRUCTOR
void SpecializeParenOpExprs::postProcessExpr(Expr* expr) {
Expr* paren_replacement = NULL;
if (ParenOpExpr* paren = dynamic_cast<ParenOpExpr*>(expr)) {
if (dynamic_cast<ArrayType*>(paren->baseExpr->typeInfo())) {
paren_replacement = new ArrayRef(paren->baseExpr, paren->argList);
}
else if (Variable* baseVar = dynamic_cast<Variable*>(paren->baseExpr)) {
if (ClassType* ctype = dynamic_cast<ClassType*>(baseVar->var->type)) {
if (!dynamic_cast<TypeSymbol*>(baseVar->var)) {
USR_FATAL(expr, "Invalid class constructor");
}
DefStmt* constructor = dynamic_cast<DefStmt*>(ctype->constructor);
FnSymbol* fn;
if (constructor) {
fn = constructor->fnDef();
}
if (fn) {
#ifdef NO_RESOLVE_CONSTRUCTOR
paren_replacement = new FnCall(new Variable(new UnresolvedSymbol(fn->name)), paren->argList);
#else
paren_replacement = new FnCall(new Variable(fn), paren->argList);
#endif
}
else {
INT_FATAL(expr, "constructor does not have a DefStmt");
}
}
else if (dynamic_cast<TupleType*>(paren->baseExpr->typeInfo())) {
paren_replacement = new TupleSelect(baseVar, paren->argList);
}
else if (strcmp(baseVar->var->name, "write") == 0) {
paren_replacement = new IOCall(IO_WRITE, paren->baseExpr, paren->argList);
}
else if (strcmp(baseVar->var->name, "writeln") == 0) {
paren_replacement = new IOCall(IO_WRITELN, paren->baseExpr, paren->argList);
}
else if (strcmp(baseVar->var->name, "read") == 0) {
paren_replacement = new IOCall(IO_READ, paren->baseExpr, paren->argList);
}
else if (dynamic_cast<FnSymbol*>(baseVar->var)) {
paren_replacement = new FnCall(baseVar, paren->argList);
}
}
}
if (paren_replacement) {
expr->replace(paren_replacement);
}
}
<commit_msg>In the commented-out section of this code, constructors are now MemberAccesses where the base is the TypeSymbol of the class.<commit_after>#include "specializeParenOpExprs.h"
#include "expr.h"
#include "stmt.h"
#include "stringutil.h"
#include "symtab.h"
//#define NO_RESOLVE_CONSTRUCTOR
void SpecializeParenOpExprs::postProcessExpr(Expr* expr) {
Expr* paren_replacement = NULL;
if (ParenOpExpr* paren = dynamic_cast<ParenOpExpr*>(expr)) {
if (dynamic_cast<ArrayType*>(paren->baseExpr->typeInfo())) {
paren_replacement = new ArrayRef(paren->baseExpr, paren->argList);
}
else if (Variable* baseVar = dynamic_cast<Variable*>(paren->baseExpr)) {
if (ClassType* ctype = dynamic_cast<ClassType*>(baseVar->var->type)) {
if (!dynamic_cast<TypeSymbol*>(baseVar->var)) {
USR_FATAL(expr, "Invalid class constructor");
}
DefStmt* constructor = dynamic_cast<DefStmt*>(ctype->constructor);
FnSymbol* fn;
if (constructor) {
fn = constructor->fnDef();
}
if (fn) {
#ifdef NO_RESOLVE_CONSTRUCTOR
paren_replacement = new FnCall(new MemberAccess(new Variable(ctype->symbol), new UnresolvedSymbol(fn->name)), paren->argList);
#else
paren_replacement = new FnCall(new Variable(fn), paren->argList);
#endif
}
else {
INT_FATAL(expr, "constructor does not have a DefStmt");
}
}
else if (dynamic_cast<TupleType*>(paren->baseExpr->typeInfo())) {
paren_replacement = new TupleSelect(baseVar, paren->argList);
}
else if (strcmp(baseVar->var->name, "write") == 0) {
paren_replacement = new IOCall(IO_WRITE, paren->baseExpr, paren->argList);
}
else if (strcmp(baseVar->var->name, "writeln") == 0) {
paren_replacement = new IOCall(IO_WRITELN, paren->baseExpr, paren->argList);
}
else if (strcmp(baseVar->var->name, "read") == 0) {
paren_replacement = new IOCall(IO_READ, paren->baseExpr, paren->argList);
}
else if (dynamic_cast<FnSymbol*>(baseVar->var)) {
paren_replacement = new FnCall(baseVar, paren->argList);
}
}
}
if (paren_replacement) {
expr->replace(paren_replacement);
}
}
<|endoftext|> |
<commit_before>/**
* @file ThingSpeak.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2014-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "ThingSpeak.hh"
// ThingSpeak server network address
#define API_THINGSPEAK_COM 10,42,0,1
static const char CRLF[] __PROGMEM = "\r\n";
ThingSpeak::Client::Client() :
m_sock(NULL)
{
}
ThingSpeak::Client::~Client()
{
end();
}
bool
ThingSpeak::Client::begin(Socket* sock)
{
if (UNLIKELY(m_sock != NULL)) return (false);
m_sock = sock;
return (true);
}
bool
ThingSpeak::Client::end()
{
if (UNLIKELY(m_sock == NULL)) return (false);
m_sock->close();
m_sock = NULL;
return (true);
}
int
ThingSpeak::Client::connect()
{
uint8_t server[4] = { API_THINGSPEAK_COM };
int res = m_sock->connect(server, 8080);
if (UNLIKELY(res != 0)) return (res);
while ((res = m_sock->is_connected()) == 0) delay(16);
if (UNLIKELY(res < 0)) return (-2);
return (0);
}
int
ThingSpeak::Client::disconnect()
{
m_sock->disconnect();
m_sock->close();
m_sock->open(Socket::TCP, 0, 0);
return (0);
}
ThingSpeak::Channel::Channel(Client* client, const char* key) :
m_client(client),
m_key(key)
{
}
int
ThingSpeak::Channel::post(const char* entry, str_P status)
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
size_t length = strlen(entry);
if (status != NULL) length += strlen_P(status) + 8;
// Connect to the server
int res = m_client->connect();
if (UNLIKELY(res < 0)) goto error;
// Generate the http post request with entry and status
page << PSTR("GET /update HTTP/1.1") << CRLF << CRLF;
// << PSTR("Host:10.42.0.1:8080") << CRLF
// << PSTR("Connection:close") << CRLF << CRLF;
// << PSTR("X-THINGSPEAKAPIKEY: ") << m_key << CRLF;
// << PSTR("Content-Type: application/x-www-form-urlencoded") << CRLF
// << PSTR("Content-Length: ") << strlen(entry) << CRLF
// << CRLF
// << (char*) entry;
if (status != NULL) page << PSTR("&status=") << status;
sock->flush();
res = 0;
error:
// Disconnect and close the socket. Reopen for the next post (if any)
m_client->disconnect();
return (res);
}
void
ThingSpeak::Entry::set_field(uint8_t id, uint16_t value, uint8_t decimals,
bool sign)
{
uint16_t scale = 1;
for (uint8_t i = 0; i < decimals; i++) scale *= 10;
if (!m_buf.is_empty()) m_cout << '&';
m_cout << PSTR("field") << id << '=';
if (sign) m_cout << '-';
m_cout << value / scale;
if (decimals == 0) return;
uint16_t rem = value % scale;
m_cout << '.';
m_cout.print(rem, decimals, IOStream::dec);
}
void
ThingSpeak::Entry::set_field(uint8_t id, uint32_t value, uint8_t decimals,
bool sign)
{
uint16_t scale = 1;
for (uint8_t i = 0; i < decimals; i++) scale *= 10;
if (!m_buf.is_empty()) m_cout << '&';
m_cout << PSTR("field") << id << '=';
if (sign) m_cout << '-';
m_cout << value / scale;
if (decimals == 0) return;
uint16_t rem = value % scale;
m_cout << '.';
m_cout.print(rem, decimals, IOStream::dec);
}
ThingSpeak::TalkBack::TalkBack(Client* client, const char* key, uint16_t id) :
m_client(client),
m_key(key),
m_id(id),
m_first(NULL)
{}
int
ThingSpeak::TalkBack::execute_next_command()
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
// Connect to the server
int res = m_client->connect();
if (UNLIKELY(res < 0)) goto error;
// Generate the http post request with talkback id and key
page << PSTR("POST /talkbacks/") << m_id
<< PSTR("/commands/execute?api_key=") << m_key
<< PSTR(" HTTP/1.1") << CRLF
<< PSTR("Host: api.thingspeak.com") << CRLF
<< PSTR("Connection: close") << CRLF
<< PSTR("Content-Length: 0") << CRLF
<< CRLF;
sock->flush();
// Wait for the reply
while ((res = sock->available()) == 0) delay(16);
if (UNLIKELY(res < 0)) goto error;
// Parse reply header
Command* command;
uint8_t length;
char line[64];
sock->gets(line, sizeof(line));
res = -1;
if (strcmp_P(line, PSTR("HTTP/1.1 200 OK\r"))) goto error;
do {
sock->gets(line, sizeof(line));
} while ((sock->available() > 0) && (strcmp_P(line, PSTR("\r"))));
if (UNLIKELY(sock->available() <= 0)) goto error;
// Parse reply length and command string
sock->gets(line, sizeof(line));
length = (uint8_t) strtol(line, NULL, 16);
if (UNLIKELY(length <= 0)) goto error;
sock->gets(line, sizeof(line));
line[length] = 0;
// Lookup the command and execute. Disconnect before and the command might
// issue an add command request
res = -5;
command = lookup(line);
if (UNLIKELY(command == NULL)) goto error;
m_client->disconnect();
command->execute();
return (0);
error:
m_client->disconnect();
return (res);
}
int
ThingSpeak::TalkBack::add_command_P(str_P string, uint8_t position)
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
// Connect to the server
int res = m_client->connect();
if (UNLIKELY(res < 0)) goto error;
// Generate the http post request with talkback id, key, command and position
page << PSTR("POST /talkbacks/") << m_id
<< PSTR("/commands?api_key=") << m_key
<< PSTR("&command_string=") << string;
if (position != 0) page << PSTR("&position=") << position;
page << PSTR(" HTTP/1.1") << CRLF
<< PSTR("Host: api.thingspeak.com") << CRLF
<< PSTR("Connection: close") << CRLF
<< PSTR("Content-Length: 0") << CRLF
<< CRLF;
sock->flush();
// Wait for the reply
while ((res = sock->available()) == 0) delay(16);
if (UNLIKELY(res < 0)) goto error;
// Parse reply header
char line[64];
sock->gets(line, sizeof(line));
res = strcmp_P(line, PSTR("HTTP/1.1 200 OK\r")) ? -1 : 0;
error:
m_client->disconnect();
return (res);
}
ThingSpeak::TalkBack::Command*
ThingSpeak::TalkBack::lookup(const char* name)
{
for (Command* c = m_first; c != NULL; c = c->m_next)
if (!strcmp_P(name, c->m_string)) return (c);
return (NULL);
}
<commit_msg>Fix HTTP format in POST method<commit_after>/**
* @file ThingSpeak.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2014-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "ThingSpeak.hh"
#include "Cosa/Trace.hh"
// ThingSpeak server network address
#define API_THINGSPEAK_COM 10,42,0,1
static const char CRLF[] __PROGMEM = "\r\n";
ThingSpeak::Client::Client() :
m_sock(NULL)
{
}
ThingSpeak::Client::~Client()
{
end();
}
bool
ThingSpeak::Client::begin(Socket* sock)
{
if (UNLIKELY(m_sock != NULL)) return (false);
m_sock = sock;
return (true);
}
bool
ThingSpeak::Client::end()
{
if (UNLIKELY(m_sock == NULL)) return (false);
m_sock->close();
m_sock = NULL;
return (true);
}
int
ThingSpeak::Client::connect()
{
uint8_t server[4] = { API_THINGSPEAK_COM };
int res = m_sock->connect(server, 8085);
if (UNLIKELY(res != 0)) return (res);
while ((res = m_sock->is_connected()) == 0) delay(16);
if (UNLIKELY(res < 0)) return (-2);
return (0);
}
int
ThingSpeak::Client::disconnect()
{
m_sock->disconnect();
m_sock->close();
m_sock->open(Socket::TCP, 0, 0);
return (0);
}
ThingSpeak::Channel::Channel(Client* client, const char* key) :
m_client(client),
m_key(key)
{
}
int
ThingSpeak::Channel::post(const char* entry, str_P status)
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
size_t length = strlen(entry);
if (status != NULL) length += strlen_P(status) + 8;
//TRACE("\n Trying to connect to server...= ");
// Connect to the server
int res = m_client->connect();
//TRACE(res);
if (UNLIKELY(res < 0)) goto error;
//TRACE("\n No error: doing GET.");
// Generate the http post request with entry and status
//CLRF makes noise -> without it, the GET works fine
//GET request working
//page << PSTR("GET /update HTTP/1.1");
//Original GET request ending with CRLF
//page << PSTR("GET /update HTTP/1.1") << CRLF;
//POST request
page << PSTR("POST /update HTTP/1.1\r\n")// << CRLF << CRLF;
//page << PSTR("POST /update")// << CRLF << CRLF;
<< PSTR("Host:10.42.0.1:8085\r\n") //<< CRLF
<< PSTR("Connection:close\r\n") // << CRLF << CRLF
// << PSTR("X-THINGSPEAKAPIKEY: ") << m_key << CRLF
<< PSTR("Content-Type: application/x-www-form-urlencoded\r\n") // << CRLF
// << PSTR("Content-Type: text/plain\r\n")
<< PSTR("Content-Length: ") << strlen(entry) << "\r\n"// << CRLF
<<"\r\n"
// << CRLF
<< (char*) entry;
// << PSTR(" HTTP/1.1");
//Weird POST request working fine
// page << PSTR("POST /update")
// << (char*) entry
// << PSTR(" HTTP/1.1");
if (status != NULL) page << PSTR("&status=") << status;
sock->flush();
res = 0;
error:
// Disconnect and close the socket. Reopen for the next post (if any)
m_client->disconnect();
return (res);
}
void
ThingSpeak::Entry::set_field(uint8_t id, uint16_t value, uint8_t decimals,
bool sign)
{
uint16_t scale = 1;
for (uint8_t i = 0; i < decimals; i++) scale *= 10;
if (!m_buf.is_empty()) m_cout << '&';
m_cout << PSTR("field") << id << '=';
if (sign) m_cout << '-';
m_cout << value / scale;
if (decimals == 0) return;
uint16_t rem = value % scale;
m_cout << '.';
m_cout.print(rem, decimals, IOStream::dec);
}
void
ThingSpeak::Entry::set_field(uint8_t id, uint32_t value, uint8_t decimals,
bool sign)
{
uint16_t scale = 1;
for (uint8_t i = 0; i < decimals; i++) scale *= 10;
if (!m_buf.is_empty()) m_cout << '&';
m_cout << PSTR("field") << id << '=';
if (sign) m_cout << '-';
m_cout << value / scale;
if (decimals == 0) return;
uint16_t rem = value % scale;
m_cout << '.';
m_cout.print(rem, decimals, IOStream::dec);
}
ThingSpeak::TalkBack::TalkBack(Client* client, const char* key, uint16_t id) :
m_client(client),
m_key(key),
m_id(id),
m_first(NULL)
{}
int
ThingSpeak::TalkBack::execute_next_command()
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
// Connect to the server
int res = m_client->connect();
if (UNLIKELY(res < 0)) goto error;
// Generate the http post request with talkback id and key
page << PSTR("POST /talkbacks/") << m_id
<< PSTR("/commands/execute?api_key=") << m_key
<< PSTR(" HTTP/1.1") << CRLF
<< PSTR("Host: api.thingspeak.com") << CRLF
<< PSTR("Connection: close") << CRLF
<< PSTR("Content-Length: 0") << CRLF
<< CRLF;
sock->flush();
// Wait for the reply
while ((res = sock->available()) == 0) delay(16);
if (UNLIKELY(res < 0)) goto error;
// Parse reply header
Command* command;
uint8_t length;
char line[64];
sock->gets(line, sizeof(line));
res = -1;
if (strcmp_P(line, PSTR("HTTP/1.1 200 OK\r"))) goto error;
do {
sock->gets(line, sizeof(line));
} while ((sock->available() > 0) && (strcmp_P(line, PSTR("\r"))));
if (UNLIKELY(sock->available() <= 0)) goto error;
// Parse reply length and command string
sock->gets(line, sizeof(line));
length = (uint8_t) strtol(line, NULL, 16);
if (UNLIKELY(length <= 0)) goto error;
sock->gets(line, sizeof(line));
line[length] = 0;
// Lookup the command and execute. Disconnect before and the command might
// issue an add command request
res = -5;
command = lookup(line);
if (UNLIKELY(command == NULL)) goto error;
m_client->disconnect();
command->execute();
return (0);
error:
m_client->disconnect();
return (res);
}
int
ThingSpeak::TalkBack::add_command_P(str_P string, uint8_t position)
{
// Use an iostream for the http post request
Socket* sock = m_client->m_sock;
IOStream page(sock);
// Connect to the server
int res = m_client->connect();
if (UNLIKELY(res < 0)) goto error;
// Generate the http post request with talkback id, key, command and position
page << PSTR("POST /talkbacks/") << m_id
<< PSTR("/commands?api_key=") << m_key
<< PSTR("&command_string=") << string;
if (position != 0) page << PSTR("&position=") << position;
page << PSTR(" HTTP/1.1") << CRLF
<< PSTR("Host: api.thingspeak.com") << CRLF
<< PSTR("Connection: close") << CRLF
<< PSTR("Content-Length: 0") << CRLF
<< CRLF;
sock->flush();
// Wait for the reply
while ((res = sock->available()) == 0) delay(16);
if (UNLIKELY(res < 0)) goto error;
// Parse reply header
char line[64];
sock->gets(line, sizeof(line));
res = strcmp_P(line, PSTR("HTTP/1.1 200 OK\r")) ? -1 : 0;
error:
m_client->disconnect();
return (res);
}
ThingSpeak::TalkBack::Command*
ThingSpeak::TalkBack::lookup(const char* name)
{
for (Command* c = m_first; c != NULL; c = c->m_next)
if (!strcmp_P(name, c->m_string)) return (c);
return (NULL);
}
<|endoftext|> |
<commit_before>// Created by cschalk on 3/22/16.
// Challenge 12 : First non duplicate letter
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char ** args) {
std::ifstream input {args[1]};
std::string line;
std::vector<char> foundDuplicates;
std::vector<char> foundLetters;
while (std::getline(input, line)) {
foundDuplicates.clear();
foundLetters.clear();
for (std::string::size_type i = 0 ; i < line.length() ; ++i ) {
if (std::find(foundDuplicates.begin(), foundDuplicates.end(), line[i]) == foundDuplicates.end()) {
if (std::find(foundLetters.begin(), foundLetters.end(), line[i]) == foundLetters.end()) {
foundLetters.push_back(line[i]);
} else {
foundLetters.erase(std::remove(foundLetters.begin(), foundLetters.end(), line[i]), foundLetters.end());
foundDuplicates.push_back(line[i]);
}
}
}
if (!foundLetters.empty()) {
std::cout << foundLetters.front() << std::endl;
}
}
return 0;
}
<commit_msg>added macros to increase readability.<commit_after>// Created by cschalk on 3/22/16.
// Challenge 12 : First non duplicate letter
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#define CONTAINS(x, y) (std::find(x.begin(), x.end(), y) != x.end())
#define REMOVE(x, y) (x.erase(std::remove(x.begin(), x.end(), y), x.end()))
using namespace std;
int main(int argc, char ** args) {
std::ifstream input {args[1]};
std::string line;
std::vector<char> foundDuplicates;
std::vector<char> foundLetters;
while (std::getline(input, line)) {
foundDuplicates.clear();
foundLetters.clear();
for (std::string::size_type i = 0 ; i < line.length() ; ++i ) {
if (!(CONTAINS(foundDuplicates, line[i]))) {
if (!(CONTAINS(foundLetters, line[i]))) {
foundLetters.push_back(line[i]);
} else {
REMOVE(foundLetters, line[i]);
foundDuplicates.push_back(line[i]);
}
}
}
if (!foundLetters.empty()) {
std::cout << foundLetters.front() << std::endl;
}
}
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/dataset/plan.h"
#include "arrow/compute/exec/exec_plan.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/scanner.h"
namespace arrow {
namespace dataset {
namespace internal {
void Initialize() {
static auto registry = compute::default_exec_factory_registry();
if (registry) {
InitializeScanner(registry);
InitializeDatasetWriter(registry);
registry = nullptr;
}
}
} // namespace internal
} // namespace dataset
} // namespace arrow
<commit_msg>ARROW-16390: [C++] Dataset initialization could segfault if called simultaneously<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/dataset/plan.h"
#include "arrow/compute/exec/exec_plan.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/scanner.h"
#include <mutex>
namespace arrow {
namespace dataset {
namespace internal {
void Initialize() {
static std::once_flag flag;
std::call_once(flag, [] {
auto registry = compute::default_exec_factory_registry();
if (registry) {
InitializeScanner(registry);
InitializeDatasetWriter(registry);
}
});
}
} // namespace internal
} // namespace dataset
} // namespace arrow
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basicupdatemerger.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 15:02:26 $
*
* 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_configmgr.hxx"
#include "basicupdatemerger.hxx"
#include "layerdefaultremover.hxx"
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef INCLUDED_ITERATOR
#include <iterator>
#define INCLUDED_ITERATOR
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
BasicUpdateMerger::BasicUpdateMerger( LayerSource const & _xSourceLayer )
: m_xSourceLayer(_xSourceLayer)
, m_xResultHandler()
, m_nNesting(0)
, m_bSkipping(false)
{
}
// -----------------------------------------------------------------------------
BasicUpdateMerger::~BasicUpdateMerger()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::readData( ResultHandler const & _xResultHandler )
throw ( MalformedDataException, lang::NullPointerException,
lang::WrappedTargetException, uno::RuntimeException)
{
if (!_xResultHandler.is())
{
OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("UpdateMerger: Error - NULL output handler unexpected") );
throw lang::NullPointerException(sMsg,*this);
}
if (!m_xSourceLayer.is())
{
OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("UpdateMerger: Error - No source layer set") );
throw lang::NullPointerException(sMsg,*this);
}
try
{
m_xResultHandler = new LayerDefaultRemover(_xResultHandler);
m_xSourceLayer->readData( this );
}
catch (uno::Exception & )
{
m_xResultHandler.clear();
throw;
}
m_xResultHandler.clear();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::startLayer( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (m_nNesting)
raiseMalformedDataException("UpdateMerger: Cannot start layer - layer already in progress");
m_bSkipping = false;
m_xResultHandler->startLayer();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endLayer( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (m_nNesting > 0)
raiseMalformedDataException("UpdateMerger: Cannot end layer - data handling still in progress");
this->flushContext();
m_xResultHandler->endLayer();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->overrideNode(aName, aAttributes, bClear);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addOrReplaceNode(aName, aAttributes);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addOrReplaceNodeFromTemplate( const OUString& aName, const TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addOrReplaceNodeFromTemplate(aName, aTemplate, aAttributes);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endNode( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->endNode();
popLevel();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::dropNode( const OUString& aName )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->dropNode(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->overrideProperty(aName, aAttributes, aType, bClear);
pushLevel( OUString() ); // do not match context path to property names
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endProperty( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->endProperty();
popLevel();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::setPropertyValue( const uno::Any& aValue )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->setPropertyValue(aValue);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::setPropertyValueForLocale( const uno::Any& aValue, const OUString & aLocale )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->setPropertyValueForLocale(aValue,aLocale);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addProperty(aName, aAttributes, aType);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addPropertyWithValue(aName, aAttributes, aValue);
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::raiseMalformedDataException(sal_Char const * pMsg)
{
OUString sMsg = OUString::createFromAscii(pMsg);
throw MalformedDataException(sMsg, *this, uno::Any());
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::startSkipping()
{
OSL_PRECOND( m_nNesting == 0, "BasicUpdateMerger: starting to skip, while already forwarding data");
m_nNesting = 1;
m_bSkipping = true;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: isHandling() is broken");
OSL_POSTCOND( isSkipping(), "BasicUpdateMerger: isSkipping() is broken");
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::pushLevel(OUString const & _aContext)
{
if (m_nNesting > 0)
{
++m_nNesting;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if (m_nNesting < 0)
{
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if (m_aSearchPath.empty())
{
++m_nNesting;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if ( m_aSearchPath.back().equals(_aContext) ) // search path is reverse - see findContext()
{
OSL_ENSURE( m_nNesting == 0, "BasicUpdateMerger: level count while searching must be zero");
m_aSearchPath.pop_back();
}
else // start forwarding
{
m_nNesting = 1;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
OSL_POSTCOND(!isSkipping(), "BasicUpdateMerger: skip flag set while searching " );
}
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::popLevel()
{
OSL_PRECOND( isHandling(), "BasicUpdateMerger: ending a node that wasn't handled here");
if (m_nNesting > 0)
{
if (--m_nNesting == 0)
m_bSkipping = false;
}
else if (m_nNesting == 0) // ending a context level, but the context is not yet gone
{
OSL_ENSURE( !m_aSearchPath.empty(), "BasicUpdateMerger: flushing a context that was already found");
flushContext();
leaveContext();
}
else
{
OSL_ENSURE( m_aSearchPath.empty(), "BasicUpdateMerger: Left an unfinished context" );
}
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::findContext(ContextPath const & _aContext)
{
// make the context a *reverse* copy of the context path
OSL_PRECOND( ! isHandling(), "BasicUpdateMerger: starting context search while still handling data");
m_aSearchPath.clear();
m_aSearchPath.reserve(_aContext.size());
std::copy( _aContext.rbegin(), _aContext.rend(), std::back_inserter(m_aSearchPath) );
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::leaveContext()
{
OSL_PRECOND( !isHandling(), "BasicUpdateMerger: ending the context while still handling data or seaching the context");
// force
m_nNesting = -1;
OSL_POSTCOND( ! isSkipping(), "BasicUpdateMerger: ending the context node while still skipping data");
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: cannot mark context as being handled to the end.");
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::flushContext()
{
ContextPath::size_type nNesting = m_aSearchPath.size();
while (!m_aSearchPath.empty())
{
m_xResultHandler->overrideNode(m_aSearchPath.back(), 0, false);
m_aSearchPath.pop_back();
}
this->flushUpdate();
while (nNesting > 0)
{
m_xResultHandler->endNode();
--nNesting;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<commit_msg>INTEGRATION: CWS changefileheader (1.9.72); FILE MERGED 2008/03/31 12:22:39 rt 1.9.72.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: basicupdatemerger.cxx,v $
* $Revision: 1.10 $
*
* 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_configmgr.hxx"
#include "basicupdatemerger.hxx"
#include "layerdefaultremover.hxx"
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef INCLUDED_ITERATOR
#include <iterator>
#define INCLUDED_ITERATOR
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
BasicUpdateMerger::BasicUpdateMerger( LayerSource const & _xSourceLayer )
: m_xSourceLayer(_xSourceLayer)
, m_xResultHandler()
, m_nNesting(0)
, m_bSkipping(false)
{
}
// -----------------------------------------------------------------------------
BasicUpdateMerger::~BasicUpdateMerger()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::readData( ResultHandler const & _xResultHandler )
throw ( MalformedDataException, lang::NullPointerException,
lang::WrappedTargetException, uno::RuntimeException)
{
if (!_xResultHandler.is())
{
OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("UpdateMerger: Error - NULL output handler unexpected") );
throw lang::NullPointerException(sMsg,*this);
}
if (!m_xSourceLayer.is())
{
OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("UpdateMerger: Error - No source layer set") );
throw lang::NullPointerException(sMsg,*this);
}
try
{
m_xResultHandler = new LayerDefaultRemover(_xResultHandler);
m_xSourceLayer->readData( this );
}
catch (uno::Exception & )
{
m_xResultHandler.clear();
throw;
}
m_xResultHandler.clear();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::startLayer( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (m_nNesting)
raiseMalformedDataException("UpdateMerger: Cannot start layer - layer already in progress");
m_bSkipping = false;
m_xResultHandler->startLayer();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endLayer( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (m_nNesting > 0)
raiseMalformedDataException("UpdateMerger: Cannot end layer - data handling still in progress");
this->flushContext();
m_xResultHandler->endLayer();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->overrideNode(aName, aAttributes, bClear);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addOrReplaceNode(aName, aAttributes);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addOrReplaceNodeFromTemplate( const OUString& aName, const TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addOrReplaceNodeFromTemplate(aName, aTemplate, aAttributes);
pushLevel(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endNode( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->endNode();
popLevel();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::dropNode( const OUString& aName )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->dropNode(aName);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->overrideProperty(aName, aAttributes, aType, bClear);
pushLevel( OUString() ); // do not match context path to property names
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::endProperty( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->endProperty();
popLevel();
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::setPropertyValue( const uno::Any& aValue )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->setPropertyValue(aValue);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::setPropertyValueForLocale( const uno::Any& aValue, const OUString & aLocale )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->setPropertyValueForLocale(aValue,aLocale);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addProperty(aName, aAttributes, aType);
}
// -----------------------------------------------------------------------------
void SAL_CALL BasicUpdateMerger::addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
if (!isSkipping())
m_xResultHandler->addPropertyWithValue(aName, aAttributes, aValue);
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::raiseMalformedDataException(sal_Char const * pMsg)
{
OUString sMsg = OUString::createFromAscii(pMsg);
throw MalformedDataException(sMsg, *this, uno::Any());
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::startSkipping()
{
OSL_PRECOND( m_nNesting == 0, "BasicUpdateMerger: starting to skip, while already forwarding data");
m_nNesting = 1;
m_bSkipping = true;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: isHandling() is broken");
OSL_POSTCOND( isSkipping(), "BasicUpdateMerger: isSkipping() is broken");
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::pushLevel(OUString const & _aContext)
{
if (m_nNesting > 0)
{
++m_nNesting;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if (m_nNesting < 0)
{
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if (m_aSearchPath.empty())
{
++m_nNesting;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
}
else if ( m_aSearchPath.back().equals(_aContext) ) // search path is reverse - see findContext()
{
OSL_ENSURE( m_nNesting == 0, "BasicUpdateMerger: level count while searching must be zero");
m_aSearchPath.pop_back();
}
else // start forwarding
{
m_nNesting = 1;
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: level counting is broken" );
OSL_POSTCOND(!isSkipping(), "BasicUpdateMerger: skip flag set while searching " );
}
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::popLevel()
{
OSL_PRECOND( isHandling(), "BasicUpdateMerger: ending a node that wasn't handled here");
if (m_nNesting > 0)
{
if (--m_nNesting == 0)
m_bSkipping = false;
}
else if (m_nNesting == 0) // ending a context level, but the context is not yet gone
{
OSL_ENSURE( !m_aSearchPath.empty(), "BasicUpdateMerger: flushing a context that was already found");
flushContext();
leaveContext();
}
else
{
OSL_ENSURE( m_aSearchPath.empty(), "BasicUpdateMerger: Left an unfinished context" );
}
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::findContext(ContextPath const & _aContext)
{
// make the context a *reverse* copy of the context path
OSL_PRECOND( ! isHandling(), "BasicUpdateMerger: starting context search while still handling data");
m_aSearchPath.clear();
m_aSearchPath.reserve(_aContext.size());
std::copy( _aContext.rbegin(), _aContext.rend(), std::back_inserter(m_aSearchPath) );
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::leaveContext()
{
OSL_PRECOND( !isHandling(), "BasicUpdateMerger: ending the context while still handling data or seaching the context");
// force
m_nNesting = -1;
OSL_POSTCOND( ! isSkipping(), "BasicUpdateMerger: ending the context node while still skipping data");
OSL_POSTCOND( isHandling(), "BasicUpdateMerger: cannot mark context as being handled to the end.");
}
// -----------------------------------------------------------------------------
void BasicUpdateMerger::flushContext()
{
ContextPath::size_type nNesting = m_aSearchPath.size();
while (!m_aSearchPath.empty())
{
m_xResultHandler->overrideNode(m_aSearchPath.back(), 0, false);
m_aSearchPath.pop_back();
}
this->flushUpdate();
while (nNesting > 0)
{
m_xResultHandler->endNode();
--nNesting;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<|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: HStorageMap.hxx,v $
* $Revision: 1.8 $
*
* 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 CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
#define CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/XTransactionListener.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#include <comphelper/stl_types.hxx>
#include <jni.h>
//........................................................................
namespace connectivity
{
//........................................................................
namespace hsqldb
{
class StreamHelper
{
::com::sun::star::uno::Reference< ::com::sun::star::io::XStream> m_xStream;
::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable> m_xSeek;
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> m_xOutputStream;
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> m_xInputStream;
public:
StreamHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream>& _xStream);
~StreamHelper();
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getInputStream();
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> getOutputStream();
::com::sun::star::uno::Reference< ::com::sun::star::io::XStream> getStream();
::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable> getSeek();
};
DECLARE_STL_USTRINGACCESS_MAP(::boost::shared_ptr<StreamHelper>,TStreamMap);
typedef ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >, ::rtl::OUString > TStorageURLPair;
typedef ::std::pair< TStorageURLPair, TStreamMap> TStoragePair;
DECLARE_STL_USTRINGACCESS_MAP(TStoragePair,TStorages);
/** contains all storages so far accessed.
*/
class StorageContainer
{
public:
static ::rtl::OUString registerStorage(const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>& _xStorage,const ::rtl::OUString& _sURL);
static TStorages::mapped_type getRegisteredStorage(const ::rtl::OUString& _sKey);
static ::rtl::OUString getRegisteredKey(const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>& _xStorage);
static void revokeStorage(const ::rtl::OUString& _sKey,const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XTransactionListener>& _xListener);
static TStreamMap::mapped_type registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode);
static void revokeStream(JNIEnv * env,jstring name, jstring key);
static TStreamMap::mapped_type getRegisteredStream( JNIEnv * env, jstring name, jstring key);
static ::rtl::OUString jstring2ustring(JNIEnv * env, jstring jstr);
static ::rtl::OUString removeURLPrefix(const ::rtl::OUString& _sURL,const ::rtl::OUString& _sFileURL);
static ::rtl::OUString removeOldURLPrefix(const ::rtl::OUString& _sURL);
static void throwJavaException(const ::com::sun::star::uno::Exception& _aException,JNIEnv * env);
};
//........................................................................
} // namespace hsqldb
//........................................................................
//........................................................................
} // namespace connectivity
//........................................................................
#endif // CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
<commit_msg>INTEGRATION: CWS dba31a (1.8.32); FILE MERGED 2008/07/04 15:21:28 oj 1.8.32.1: #i89558# remove unused code<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HStorageMap.hxx,v $
* $Revision: 1.9 $
*
* 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 CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
#define CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/XTransactionListener.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#include <comphelper/stl_types.hxx>
#include <jni.h>
//........................................................................
namespace connectivity
{
//........................................................................
namespace hsqldb
{
class StreamHelper
{
::com::sun::star::uno::Reference< ::com::sun::star::io::XStream> m_xStream;
::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable> m_xSeek;
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> m_xOutputStream;
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> m_xInputStream;
public:
StreamHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream>& _xStream);
~StreamHelper();
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getInputStream();
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> getOutputStream();
::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable> getSeek();
};
DECLARE_STL_USTRINGACCESS_MAP(::boost::shared_ptr<StreamHelper>,TStreamMap);
typedef ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >, ::rtl::OUString > TStorageURLPair;
typedef ::std::pair< TStorageURLPair, TStreamMap> TStoragePair;
DECLARE_STL_USTRINGACCESS_MAP(TStoragePair,TStorages);
/** contains all storages so far accessed.
*/
class StorageContainer
{
public:
static ::rtl::OUString registerStorage(const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>& _xStorage,const ::rtl::OUString& _sURL);
static TStorages::mapped_type getRegisteredStorage(const ::rtl::OUString& _sKey);
static ::rtl::OUString getRegisteredKey(const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>& _xStorage);
static void revokeStorage(const ::rtl::OUString& _sKey,const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XTransactionListener>& _xListener);
static TStreamMap::mapped_type registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode);
static void revokeStream(JNIEnv * env,jstring name, jstring key);
static TStreamMap::mapped_type getRegisteredStream( JNIEnv * env, jstring name, jstring key);
static ::rtl::OUString jstring2ustring(JNIEnv * env, jstring jstr);
static ::rtl::OUString removeURLPrefix(const ::rtl::OUString& _sURL,const ::rtl::OUString& _sFileURL);
static ::rtl::OUString removeOldURLPrefix(const ::rtl::OUString& _sURL);
static void throwJavaException(const ::com::sun::star::uno::Exception& _aException,JNIEnv * env);
};
//........................................................................
} // namespace hsqldb
//........................................................................
//........................................................................
} // namespace connectivity
//........................................................................
#endif // CONNECTIVI_HSQLDB_HSTORAGEMAP_HXX
<|endoftext|> |
<commit_before>#ifndef RINF_CALLER_HXX_
#define RINF_CALLER_HXX_
#include <opengm/opengm.hxx>
#include <opengm/inference/reducedinference.hxx>
#ifdef WITH_CPLEX
#include <opengm/inference/lpcplex.hxx>
#include <opengm/inference/multicut.hxx>
#endif
#ifdef WITH_FASTPD
#include <opengm/inference/external/fastPD.hxx>
#endif
#ifdef WITH_TRWS
#include <opengm/inference/external/trws.hxx>
#endif
#ifdef WITH_GCO
#include <opengm/inference/external/gco.hxx>
#endif
#include "inference_caller_base.hxx"
#include "../argument/argument.hxx"
namespace opengm {
namespace interface {
template <class IO, class GM, class ACC>
class RINFCaller : public InferenceCallerBase<IO, GM, ACC, RINFCaller<IO, GM, ACC> > {
protected:
typedef InferenceCallerBase<IO, GM, ACC, RINFCaller<IO, GM, ACC> > BaseClass;
typedef typename BaseClass::OutputBase OutputBase;
using BaseClass::addArgument;
using BaseClass::io_;
using BaseClass::infer;
virtual void runImpl(GM& model, OutputBase& output, const bool verbose);
bool persistency_;
bool tentacle_;
bool connectedComponents_;
double timeOut_;
int numberOfThreads_;
std::string selectedInfType_;
public:
const static std::string name_;
RINFCaller(IO& ioIn);
~RINFCaller();
};
template <class IO, class GM, class ACC>
inline RINFCaller<IO, GM, ACC>::RINFCaller(IO& ioIn)
: BaseClass(name_, "detailed description of RINF caller...", ioIn) {
std::vector<std::string> inf;
inf.push_back("ILP");
inf.push_back("LP");
inf.push_back("MC");
inf.push_back("MCR");
inf.push_back("TRWS");
inf.push_back("FASTPD");
inf.push_back("EXPANSION");
addArgument(StringArgument<>(selectedInfType_, "i", "inf", "Select inference method for reduced problems.", inf.front(), inf));
addArgument(IntArgument<>(numberOfThreads_, "", "threads", "number of threads", static_cast<int>(1)));
addArgument(BoolArgument(persistency_, "ps", "persistency", "use reduction persistency"));
addArgument(BoolArgument(tentacle_, "t", "tentacle", "use reduction by removing tentacles"));
addArgument(BoolArgument(connectedComponents_, "c", "conectedcomp", "use reduction by finding connect components"));
double to =14400.0;
addArgument(DoubleArgument<>(timeOut_,"","timeout","maximal runtime in seconds",to));
}
template <class IO, class GM, class ACC>
RINFCaller<IO, GM, ACC>::~RINFCaller()
{;}
template <class IO, class GM, class ACC>
inline void RINFCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) {
std::cout << "running RINF caller" << std::endl;
if(selectedInfType_=="ILP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef LPCplex<GM2, ACC> LPCPLEX;
typedef ReducedInference<GM,ACC,LPCPLEX> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.timeLimit_ = timeOut_;
rinfParameter_.subParameter_.numberOfThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.integerConstraint_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("CPLEX is disabled!");
#endif
}
else if(selectedInfType_=="LP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef LPCplex<GM2, ACC> LPCPLEX;
typedef ReducedInference<GM,ACC,LPCPLEX> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.timeLimit_ = timeOut_;
rinfParameter_.subParameter_.numberOfThreads_ = numberOfThreads_;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("CPLEX is disabled!");
#endif
}
else if(selectedInfType_=="MC"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(MTC)(IC)(TTC-I)";
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="MCR"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(MTC)";
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="TRWS"){
#ifdef WITH_TRWS
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::TRWS<GM2> TRWSType;
typedef ReducedInference<GM,ACC,TRWSType> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.energyType_= TRWSType::Parameter::VIEW;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("TRWS is disabled!");
#endif
}
else if(selectedInfType_=="FASTPD"){
#ifdef WITH_FASTPD
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::FastPD<GM2> FastPDType;
typedef ReducedInference<GM,ACC,FastPDType> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("FASTPD is disabled!");
#endif
}
else if(selectedInfType_=="EXPANSION"){
#ifdef WITH_GCO
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::GCOLIB<GM2> GCOLIB;
typedef ReducedInference<GM,ACC,GCOLIB> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.inferenceType_= GCOLIB::Parameter::EXPANSION;
rinfParameter_.subParameter_.energyType_= GCOLIB::Parameter::VIEW;
rinfParameter_.subParameter_.doNotUseGrid_= true;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("GCOLIB is disabled!");
#endif
}
else{
throw RuntimeError("Unknown Inference method for subproblems!");
}
}
template <class IO, class GM, class ACC>
const std::string RINFCaller<IO, GM, ACC>::name_ = "RINF";
} // namespace interface
} // namespace opengm
#endif /* RINF_CALLER_HXX_ */
<commit_msg>add more inference methods<commit_after>#ifndef RINF_CALLER_HXX_
#define RINF_CALLER_HXX_
#include <opengm/opengm.hxx>
#include <opengm/inference/reducedinference.hxx>
#ifdef WITH_CPLEX
#include <opengm/inference/lpcplex.hxx>
#include <opengm/inference/multicut.hxx>
#endif
#ifdef WITH_FASTPD
#include <opengm/inference/external/fastPD.hxx>
#endif
#ifdef WITH_TRWS
#include <opengm/inference/external/trws.hxx>
#endif
#ifdef WITH_GCO
#include <opengm/inference/external/gco.hxx>
#endif
#ifdef WITH_MPLP
#include <opengm/inference/external/mplp.hxx>
#endif
#include "inference_caller_base.hxx"
#include "../argument/argument.hxx"
namespace opengm {
namespace interface {
template <class IO, class GM, class ACC>
class RINFCaller : public InferenceCallerBase<IO, GM, ACC, RINFCaller<IO, GM, ACC> > {
protected:
typedef InferenceCallerBase<IO, GM, ACC, RINFCaller<IO, GM, ACC> > BaseClass;
typedef typename BaseClass::OutputBase OutputBase;
using BaseClass::addArgument;
using BaseClass::io_;
using BaseClass::infer;
virtual void runImpl(GM& model, OutputBase& output, const bool verbose);
bool persistency_;
bool tentacle_;
bool connectedComponents_;
double timeOut_;
int numberOfThreads_;
std::string selectedInfType_;
public:
const static std::string name_;
RINFCaller(IO& ioIn);
~RINFCaller();
};
template <class IO, class GM, class ACC>
inline RINFCaller<IO, GM, ACC>::RINFCaller(IO& ioIn)
: BaseClass(name_, "detailed description of RINF caller...", ioIn) {
std::vector<std::string> inf;
inf.push_back("ILP");
inf.push_back("LP");
inf.push_back("MC");
inf.push_back("MCR");
inf.push_back("MCR-LP");
inf.push_back("MCR-CP");
inf.push_back("MCR-CP2");
inf.push_back("TRWS");
inf.push_back("FASTPD");
inf.push_back("EXPANSION");
inf.push_back("MPLP-C");
addArgument(StringArgument<>(selectedInfType_, "i", "inf", "Select inference method for reduced problems.", inf.front(), inf));
addArgument(IntArgument<>(numberOfThreads_, "", "threads", "number of threads", static_cast<int>(1)));
addArgument(BoolArgument(persistency_, "ps", "persistency", "use reduction persistency"));
addArgument(BoolArgument(tentacle_, "t", "tentacle", "use reduction by removing tentacles"));
addArgument(BoolArgument(connectedComponents_, "c", "conectedcomp", "use reduction by finding connect components"));
double to =14400.0;
addArgument(DoubleArgument<>(timeOut_,"","timeout","maximal runtime in seconds",to));
}
template <class IO, class GM, class ACC>
RINFCaller<IO, GM, ACC>::~RINFCaller()
{;}
template <class IO, class GM, class ACC>
inline void RINFCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) {
std::cout << "running RINF caller" << std::endl;
if(selectedInfType_=="ILP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef LPCplex<GM2, ACC> LPCPLEX;
typedef ReducedInference<GM,ACC,LPCPLEX> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.timeLimit_ = timeOut_;
rinfParameter_.subParameter_.numberOfThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.integerConstraint_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("CPLEX is disabled!");
#endif
}
else if(selectedInfType_=="LP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef LPCplex<GM2, ACC> LPCPLEX;
typedef ReducedInference<GM,ACC,LPCPLEX> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.timeLimit_ = timeOut_;
rinfParameter_.subParameter_.numberOfThreads_ = numberOfThreads_;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("CPLEX is disabled!");
#endif
}
else if(selectedInfType_=="MC"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(MTC)(IC)(TTC-I)";
rinfParameter_.subParameter_.useBufferedStates_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="MCR"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(MTC)";
rinfParameter_.subParameter_.useBufferedStates_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="MCR-LP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(TTC,MTC)";
rinfParameter_.subParameter_.useBufferedStates_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="MCR-CP"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(TTC,MTC)(TTC,MTC,CC-FDB)";
rinfParameter_.subParameter_.useBufferedStates_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="MCR-CP2"){
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef Multicut<GM2, ACC> MultiCut;
typedef ReducedInference<GM,ACC,MultiCut> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numThreads_ = numberOfThreads_;
rinfParameter_.subParameter_.timeOut_ = timeOut_;
rinfParameter_.subParameter_.workFlow_ = "(TTC)(MTC)(TTC,CC)";
rinfParameter_.subParameter_.useBufferedStates_ = true;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MULTICUT is disabled!");
#endif
}
else if(selectedInfType_=="TRWS"){
#ifdef WITH_TRWS
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::TRWS<GM2> TRWSType;
typedef ReducedInference<GM,ACC,TRWSType> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.energyType_= TRWSType::Parameter::VIEW;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("TRWS is disabled!");
#endif
}
else if(selectedInfType_=="FASTPD"){
#ifdef WITH_FASTPD
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::FastPD<GM2> FastPDType;
typedef ReducedInference<GM,ACC,FastPDType> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("FASTPD is disabled!");
#endif
}
else if(selectedInfType_=="EXPANSION"){
#ifdef WITH_GCO
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::GCOLIB<GM2> GCOLIB;
typedef ReducedInference<GM,ACC,GCOLIB> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.inferenceType_= GCOLIB::Parameter::EXPANSION;
rinfParameter_.subParameter_.energyType_= GCOLIB::Parameter::VIEW;
rinfParameter_.subParameter_.doNotUseGrid_= true;
rinfParameter_.subParameter_.numberOfIterations_ = 1000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("GCOLIB is disabled!");
#endif
}
else if(selectedInfType_=="MPLP-C"){
#ifdef WITH_MPLP
std::cout<<" start MPLP"<<std::endl;
typedef typename ReducedInferenceHelper<GM>::InfGmType GM2;
typedef typename opengm::external::MPLP<GM2> MPLP;
typedef ReducedInference<GM,ACC,MPLP> RINF;
typedef typename RINF::VerboseVisitorType VerboseVisitorType;
typedef typename RINF::EmptyVisitorType EmptyVisitorType;
typedef typename RINF::TimingVisitorType TimingVisitorType;
typename RINF::Parameter rinfParameter_;
rinfParameter_.Persistency_ = persistency_;
rinfParameter_.Tentacle_ = tentacle_;
rinfParameter_.ConnectedComponents_ = connectedComponents_;
rinfParameter_.subParameter_.maxTime_= timeOut_;
rinfParameter_.subParameter_.maxTimeLP_= timeOut_/3.0;
rinfParameter_.subParameter_.maxIterLP_ = 10000;
rinfParameter_.subParameter_.maxIterTight_ = 10000;
this-> template infer<RINF, TimingVisitorType, typename RINF::Parameter>(model, output, verbose, rinfParameter_);
#else
throw RuntimeError("MPLP is disabled!");
#endif
}
else{
throw RuntimeError("Unknown Inference method for subproblems!");
}
}
template <class IO, class GM, class ACC>
const std::string RINFCaller<IO, GM, ACC>::name_ = "RINF";
} // namespace interface
} // namespace opengm
#endif /* RINF_CALLER_HXX_ */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: isofallback.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:29:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "isofallback.hxx"
// -----------------------------------------------------------------------
// Return true if valid fallback found
sal_Bool GetIsoFallback( ByteString& rLanguage )
{
rLanguage.EraseLeadingAndTrailingChars();
if( rLanguage.Len() ){
xub_StrLen nSepPos = rLanguage.Search( '-' );
if ( nSepPos == STRING_NOTFOUND ){
if ( rLanguage.Equals("en"))
{
// en -> ""
rLanguage.Erase();
return false;
}
else
{
// de -> en-US ;
rLanguage = ByteString("en-US");
return true;
}
}
else if( !( nSepPos == 1 && ( rLanguage.GetChar(0) == 'x' || rLanguage.GetChar(0) == 'X' ) ) )
{
// de-CH -> de ;
// try erase from -
rLanguage = rLanguage.GetToken( 0, '-');
return true;
}
}
// "" -> ""; x-no-translate -> ""
rLanguage.Erase();
return false;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.120); FILE MERGED 2006/09/01 17:54:55 kaib 1.3.120.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: isofallback.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:59:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include "isofallback.hxx"
// -----------------------------------------------------------------------
// Return true if valid fallback found
sal_Bool GetIsoFallback( ByteString& rLanguage )
{
rLanguage.EraseLeadingAndTrailingChars();
if( rLanguage.Len() ){
xub_StrLen nSepPos = rLanguage.Search( '-' );
if ( nSepPos == STRING_NOTFOUND ){
if ( rLanguage.Equals("en"))
{
// en -> ""
rLanguage.Erase();
return false;
}
else
{
// de -> en-US ;
rLanguage = ByteString("en-US");
return true;
}
}
else if( !( nSepPos == 1 && ( rLanguage.GetChar(0) == 'x' || rLanguage.GetChar(0) == 'X' ) ) )
{
// de-CH -> de ;
// try erase from -
rLanguage = rLanguage.GetToken( 0, '-');
return true;
}
}
// "" -> ""; x-no-translate -> ""
rLanguage.Erase();
return false;
}
<|endoftext|> |
<commit_before>#include "broadcast.hpp"
#include "bd_tool.hpp"
#include <iostream>
#include <netdb.h>
#include <sys/socket.h>
#ifndef SENDER
const int PORT = 7773;
#else
const int PORT = 7774;
#endif
void bd_so::BroadcastCenter::startSend(std::string msg) {
if(this->is_casting || !this->is_sender || this->is_receiving) {
std::cerr << "isn't a client or is broadcasting" << std::endl;
return;
}else {
this->is_casting = true;
strcpy(buf,msg.c_str());
sendto(socket_fd,buf,strlen(buf),0,(struct sockaddr *)&my_addr,sizeof(my_addr));
this->is_casting = false;
}
}
void bd_so::BroadcastCenter::init_addr() {
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
//std::string bd_address = boardcast_addr();
my_addr.sin_addr.s_addr = inet_addr("255.255.255.255");
user_addr.sin_family = AF_INET;
user_addr.sin_port = htons(PORT);
user_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_fd = socket(AF_INET,SOCK_DGRAM,0);
if(-1 == socket_fd) {
perror("socket init failed");
exit(1);
}
setsockopt(socket_fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof(so_broadcast));
if((bind(socket_fd,(struct sockaddr *)&user_addr,sizeof(struct sockaddr)))==-1){
perror("bind failed");
exit(1);
}
}
void bd_so::BroadcastCenter::startReceiving() {
if(is_sender == true || is_receiving) {
std::cerr << "not receiver or is receiving" << std::endl;
exit(1);
}
this->is_receiving = true;
socklen_t size = sizeof(user_addr);
recvfrom(socket_fd,buf,MAXDATASIZE,0,(struct sockaddr *)&user_addr,&size);
std::cout<<"buffer:"<<std::string(buf)<<std::endl;
strcpy(my_ip,inet_ntoa(user_addr.sin_addr));
std::cout<<std::string(my_ip)<<std::endl;
while(1) {
bzero(buf,sizeof(buf));
size = sizeof(user_addr);
recvfrom(socket_fd,buf,MAXDATASIZE,0,(struct sockaddr *)&user_addr,&size);
std::cout<<"buffer:"<<std::string(buf)<<std::endl;
}
}
<commit_msg>change broadcast address<commit_after>#include "broadcast.hpp"
#include "bd_tool.hpp"
#include <iostream>
#include <netdb.h>
#include <sys/socket.h>
#ifndef SENDER
const int PORT = 7773;
#else
const int PORT = 7774;
#endif
void bd_so::BroadcastCenter::startSend(std::string msg) {
// if(this->is_casting || !this->is_sender || this->is_receiving) {
// std::cerr << "isn't a client or is broadcasting" << std::endl;
// return;
// }else {
this->is_casting = true;
strcpy(buf,msg.c_str());
sendto(socket_fd,buf,strlen(buf),0,(struct sockaddr *)&my_addr,sizeof(my_addr));
this->is_casting = false;
// }
}
void bd_so::BroadcastCenter::init_addr() {
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
std::string bd_address = boardcast_addr();
my_addr.sin_addr.s_addr = inet_addr(bd_address.c_str());
user_addr.sin_family = AF_INET;
user_addr.sin_port = htons(PORT);
user_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_fd = socket(AF_INET,SOCK_DGRAM,0);
if(-1 == socket_fd) {
perror("socket init failed");
exit(1);
}
setsockopt(socket_fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof(so_broadcast));
if((bind(socket_fd,(struct sockaddr *)&user_addr,sizeof(struct sockaddr)))==-1){
perror("bind failed");
exit(1);
}
}
void bd_so::BroadcastCenter::startReceiving() {
if(is_sender == true || is_receiving) {
std::cerr << "not receiver or is receiving" << std::endl;
exit(1);
}
this->is_receiving = true;
socklen_t size = sizeof(user_addr);
startSend("hello");
startSend("end");
recvfrom(socket_fd,buf,MAXDATASIZE,0,(struct sockaddr *)&user_addr,&size);
std::cout<<"buffer:"<<std::string(buf)<<std::endl;
strcpy(my_ip,inet_ntoa(user_addr.sin_addr));
std::cout<<std::string(my_ip)<<std::endl;
while(1) {
bzero(buf,sizeof(buf));
size = sizeof(user_addr);
recvfrom(socket_fd,buf,MAXDATASIZE,0,(struct sockaddr *)&user_addr,&size);
std::cout<<"buffer:"<<std::string(buf)<<std::endl;
}
}
<|endoftext|> |
<commit_before>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/msg/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/utility/qt_helper.hpp>
#include <utils_param/parameter_factory.h>
#include <utils_param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/model/node_worker.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_worker.h>
#include <csapex_ros/time_stamp_message.h>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
#include <sensor_msgs/Image.h>
#include <QAction>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t stamp_micro_seconds) {
ros::Time t;
t.fromNSec(stamp_micro_seconds / 1e3);
return t;
}
}
ImportRos::ImportRos()
: connector_(nullptr), retries_(0), running_(true)
{
}
void ImportRos::setup()
{
input_time_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = modifier_->addOutput<connection_types::AnyMessage>("Something");
std::function<bool()> connected_condition = (std::bind(&Input::isConnected, input_time_));
param::Parameter::Ptr buffer_p = param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(buffer_p, connected_condition);
param::Parameter::Ptr max_wait_p = param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupParameters()
{
std::vector<std::string> set;
set.push_back(no_topic_);
addParameter(param::ParameterFactory::declareParameterStringSet("topic", set),
std::bind(&ImportRos::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"),
std::bind(&ImportRos::refresh, this));
addParameter(param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
std::bind(&ImportRos::updateRate, this));
addParameter(param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
std::bind(&ImportRos::updateSubscriber, this));
addParameter(param::ParameterFactory::declareBool("latch", false));
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = std::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
setError(false);
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
setError(true, "no ROS connection", EL_WARNING);
}
void ImportRos::update()
{
retries_ = 5;
waitForTopic();
}
void ImportRos::updateRate()
{
modifier_->setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), std::bind(&ImportRos::callback, this, std::placeholders::_1));
}
}
bool ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
setError(true, "no connection to ROS");
return false;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return true;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return true;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
setError(true, ss.str(), EL_WARNING);
return false;
}
void ImportRos::processROS()
{
// first check if connected -> if not connected, we only use tick
if(!input_time_->isConnected()) {
return;
}
// now that we are connected, check that we have a valid message
if(!input_time_->hasMessage()) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::ConstPtr time = input_time_->getMessage<connection_types::TimeStampMessage>();
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
setError(true, "incoming time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
if(ros::Time(msgs_.back()->stamp_micro_seconds) == ros::Time(0)) {
setError(true, "buffered time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp_micro_seconds) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp_micro_seconds) > time->value) {
// aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp_micro_seconds) << std::endl;
// return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.front()->stamp_micro_seconds) + max_wait_duration < time->value) {
// aerr << "[1] time stamp " << time->value << " is too new" << std::endl;
// return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp_micro_seconds) + max_wait_duration < time->value) {
aerr << "[2] time stamp " << time->value << " is too new, latest stamp is " << rosTime(msgs_.back()->stamp_micro_seconds) << std::endl;
return;
}
}
}
}
if(msgs_.empty()) {
setError(true, "No messages received", EL_WARNING);
return;
}
std::deque<connection_types::Message::ConstPtr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp_micro_seconds) < time->value) {
++first_after;
}
if(first_after == msgs_.begin()) {
connector_->publish(*first_after);
return;
} else if(first_after == msgs_.end()) {
assert(false);
setError(true, "Should not happen.....", EL_WARNING);
return;
} else {
std::deque<connection_types::Message::ConstPtr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp_micro_seconds) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp_micro_seconds) - time->value;
if(diff1 < diff2) {
connector_->publish(*first_after);
} else {
connector_->publish(*last_before);
}
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
return rosTime(msgs_.back()->stamp_micro_seconds) >= stamp;
}
void ImportRos::waitForTopic()
{
ros::WallDuration poll_wait(0.5);
while(retries_ --> 0) {
bool topic_exists = doSetTopic();
if(topic_exists) {
return;
} else {
ROS_WARN_STREAM("waiting for topic " << readParameter<std::string>("topic"));
poll_wait.sleep();
}
}
}
bool ImportRos::canTick()
{
return !input_time_->isConnected();
}
void ImportRos::tickROS()
{
if(retries_ > 0) {
waitForTopic();
}
if(input_time_->isConnected()) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
while(msgs_.size() > 1) {
msgs_.pop_front();
}
if(!current_topic_.name.empty()) {
publishLatestMessage();
}
}
void ImportRos::publishLatestMessage()
{
if(msgs_.empty()) {
ros::WallRate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
if(!running_) {
return;
}
}
connector_->publish(msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
void ImportRos::callback(ConnectionTypeConstPtr message)
{
NodeWorker* nw = getNodeWorker();
if(!nw) {
return;
}
connection_types::Message::ConstPtr msg = std::dynamic_pointer_cast<connection_types::Message const>(message);
if(msg && !nw->isPaused()) {
if(!msgs_.empty() && msg->stamp_micro_seconds < msgs_.front()->stamp_micro_seconds) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
msgs_.push_back(msg);
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
if(RosMessageConversion::instance().canHandle(topic)) {
setError(false);
current_topic_ = topic;
updateSubscriber();
} else {
setError(true, std::string("cannot import topic of type ") + topic.datatype);
return;
}
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<commit_msg>fixes<commit_after>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/msg/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/utility/qt_helper.hpp>
#include <utils_param/parameter_factory.h>
#include <utils_param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/model/node_worker.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_worker.h>
#include <csapex_ros/time_stamp_message.h>
#include <csapex/utility/timer.h>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
#include <sensor_msgs/Image.h>
#include <QAction>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t stamp_micro_seconds) {
ros::Time t;
t.fromNSec(stamp_micro_seconds / 1e3);
return t;
}
}
ImportRos::ImportRos()
: connector_(nullptr), retries_(0), running_(true)
{
}
void ImportRos::setup()
{
input_time_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = modifier_->addOutput<connection_types::AnyMessage>("Something");
std::function<bool()> connected_condition = (std::bind(&Input::isConnected, input_time_));
param::Parameter::Ptr buffer_p = param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(buffer_p, connected_condition);
param::Parameter::Ptr max_wait_p = param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupParameters()
{
std::vector<std::string> set;
set.push_back(no_topic_);
addParameter(param::ParameterFactory::declareParameterStringSet("topic", set),
std::bind(&ImportRos::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"),
std::bind(&ImportRos::refresh, this));
addParameter(param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
std::bind(&ImportRos::updateRate, this));
addParameter(param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
std::bind(&ImportRos::updateSubscriber, this));
addParameter(param::ParameterFactory::declareBool("latch", false));
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = std::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
setError(false);
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
setError(true, "no ROS connection", EL_WARNING);
}
void ImportRos::update()
{
retries_ = 5;
waitForTopic();
}
void ImportRos::updateRate()
{
modifier_->setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), std::bind(&ImportRos::callback, this, std::placeholders::_1));
}
}
bool ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
setError(true, "no connection to ROS");
return false;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return true;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return true;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
setError(true, ss.str(), EL_WARNING);
return false;
}
void ImportRos::processROS()
{
INTERLUDE("process");
// first check if connected -> if not connected, we only use tick
if(!input_time_->isConnected()) {
return;
}
// now that we are connected, check that we have a valid message
if(!input_time_->hasMessage()) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::ConstPtr time = input_time_->getMessage<connection_types::TimeStampMessage>();
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
setError(true, "incoming time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
if(ros::Time(msgs_.back()->stamp_micro_seconds) == ros::Time(0)) {
setError(true, "buffered time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp_micro_seconds) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp_micro_seconds) > time->value) {
// aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp_micro_seconds) << std::endl;
// return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.front()->stamp_micro_seconds) + max_wait_duration < time->value) {
// aerr << "[1] time stamp " << time->value << " is too new" << std::endl;
// return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp_micro_seconds) + max_wait_duration < time->value) {
aerr << "[2] time stamp " << time->value << " is too new, latest stamp is " << rosTime(msgs_.back()->stamp_micro_seconds) << std::endl;
return;
}
}
}
}
if(msgs_.empty()) {
setError(true, "No messages received", EL_WARNING);
return;
}
std::deque<connection_types::Message::ConstPtr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp_micro_seconds) < time->value) {
++first_after;
}
if(first_after == msgs_.begin()) {
connector_->publish(*first_after);
return;
} else if(first_after == msgs_.end()) {
assert(false);
setError(true, "Should not happen.....", EL_WARNING);
return;
} else {
std::deque<connection_types::Message::ConstPtr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp_micro_seconds) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp_micro_seconds) - time->value;
if(diff1 < diff2) {
connector_->publish(*first_after);
} else {
connector_->publish(*last_before);
}
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
return rosTime(msgs_.back()->stamp_micro_seconds) >= stamp;
}
void ImportRos::waitForTopic()
{
INTERLUDE("wait");
ros::WallDuration poll_wait(0.5);
while(retries_ --> 0) {
bool topic_exists = doSetTopic();
if(topic_exists) {
return;
} else {
ROS_WARN_STREAM("waiting for topic " << readParameter<std::string>("topic"));
poll_wait.sleep();
}
}
}
bool ImportRos::canTick()
{
return !input_time_->isConnected() && !msgs_.empty();
}
void ImportRos::tickROS()
{
INTERLUDE("tick");
if(retries_ > 0) {
waitForTopic();
}
if(input_time_->isConnected()) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
{
INTERLUDE("pop");
while(msgs_.size() > 1) {
msgs_.pop_front();
}
}
if(!current_topic_.name.empty()) {
publishLatestMessage();
}
}
void ImportRos::publishLatestMessage()
{
INTERLUDE("publish");
if(msgs_.empty()) {
INTERLUDE("wait for message");
ros::WallRate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
if(!running_) {
return;
}
}
connector_->publish(msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
void ImportRos::callback(ConnectionTypeConstPtr message)
{
NodeWorker* nw = getNodeWorker();
if(!nw) {
return;
}
connection_types::Message::ConstPtr msg = std::dynamic_pointer_cast<connection_types::Message const>(message);
if(msg && !nw->isPaused()) {
if(!msgs_.empty() && msg->stamp_micro_seconds < msgs_.front()->stamp_micro_seconds) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
msgs_.push_back(msg);
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
if(RosMessageConversion::instance().canHandle(topic)) {
setError(false);
current_topic_ = topic;
updateSubscriber();
} else {
setError(true, std::string("cannot import topic of type ") + topic.datatype);
return;
}
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<|endoftext|> |
<commit_before>#ifndef __bootstrap_stl_hpp
#define __bootstrap_stl_hpp__
#include "dispatchkit.hpp"
#include "register_function.hpp"
namespace dispatchkit
{
template<typename Container>
struct Input_Range
{
Input_Range(Container &c)
: m_begin(c.begin()), m_end(c.end())
{
}
Input_Range(typename Container::iterator itr)
: m_begin(itr), m_end(itr)
{
}
Input_Range(const std::pair<typename Container::iterator, typename Container::iterator> &t_p)
: m_begin(t_p.first), m_end(t_p.second)
{
}
bool empty() const
{
return m_begin == m_end;
}
void pop_front()
{
if (empty())
{
throw std::range_error("Range empty");
}
++m_begin;
}
typename std::iterator_traits<typename Container::iterator>::reference front() const
{
if (empty())
{
throw std::range_error("Range empty");
}
return *m_begin;
}
typename Container::iterator m_begin;
typename Container::iterator m_end;
};
template<typename ContainerType>
void bootstrap_input_range(Dispatch_Engine &system, const std::string &type)
{
system.register_function(build_constructor<Input_Range<ContainerType>, ContainerType &>(), "range");
system.register_function(build_constructor<Input_Range<ContainerType>,
typename ContainerType::iterator>(), "range");
system.register_function(build_constructor<Input_Range<ContainerType>,
const std::pair<typename ContainerType::iterator, typename ContainerType::iterator> &>(), "range");
register_function(system, &Input_Range<ContainerType>::empty, "empty");
register_function(system, &Input_Range<ContainerType>::pop_front, "pop_front");
register_function(system, &Input_Range<ContainerType>::front, "front");
system.register_function(build_constructor<Input_Range<ContainerType>, const Input_Range<ContainerType> &>(), "clone");
}
template<typename ContainerType>
void bootstrap_reversible_container(Dispatch_Engine &system, const std::string &type)
{
}
template<typename ContainerType>
void bootstrap_random_access_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_reversible_container<ContainerType>(system, type);
typedef typename ContainerType::reference(ContainerType::*indexoper)(size_t);
//In the interest of runtime safety for the system, we prefer the at() method for [] access,
//to throw an exception in an out of bounds condition.
system.register_function(
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::at)), "[]");
system.register_function(
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::operator[])), "at");
}
template<typename Assignable>
void bootstrap_assignable(Dispatch_Engine &system, const std::string &type)
{
add_basic_constructors<Assignable>(system, type);
add_oper_assign<Assignable>(system);
}
template<typename ContainerType>
void bootstrap_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_assignable<ContainerType>(system, type);
system.register_function(
boost::function<size_t (ContainerType *)>(&ContainerType::size), "size");
system.register_function(
boost::function<size_t (ContainerType *)>(&ContainerType::size), "maxsize");
}
template<typename ContainerType>
void bootstrap_forward_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_input_range<ContainerType>(system, type);
bootstrap_container<ContainerType>(system, type);
}
template<typename Type>
void bootstrap_default_constructible(Dispatch_Engine &system, const std::string &type)
{
system.register_function(build_constructor<Type>(), type);
}
template<typename SequenceType>
void bootstrap_sequence(Dispatch_Engine &system, const std::string &type)
{
bootstrap_forward_container<SequenceType>(system, type);
bootstrap_default_constructible<SequenceType>(system, type);
}
template<typename SequenceType>
void bootstrap_back_insertion_sequence(Dispatch_Engine &system, const std::string &type)
{
bootstrap_sequence<SequenceType>(system, type);
typedef typename SequenceType::reference (SequenceType::*backptr)();
system.register_function(boost::function<typename SequenceType::reference (SequenceType *)>(backptr(&SequenceType::back)), "back");
system.register_function(boost::function<void (SequenceType *,typename SequenceType::value_type)>(&SequenceType::push_back), "push_back_ref");
system.register_function(boost::function<void (SequenceType *)>(&SequenceType::pop_back), "pop_back");
}
template<typename VectorType>
void bootstrap_vector(Dispatch_Engine &system, const std::string &type)
{
system.register_type<VectorType>(type);
bootstrap_random_access_container<VectorType>(system, type);
bootstrap_back_insertion_sequence<VectorType>(system, type);
}
template<typename ContainerType>
void bootstrap_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_forward_container<ContainerType>(system, type);
bootstrap_default_constructible<ContainerType>(system, type);
}
template<typename PairType>
void bootstrap_pair(Dispatch_Engine &system, const std::string &type)
{
register_member(system, &PairType::first, "first");
register_member(system, &PairType::second, "second");
system.register_function(build_constructor<PairType >(), type);
system.register_function(build_constructor<PairType, const PairType &>(), type);
system.register_function(build_constructor<PairType, const PairType &>(), "clone");
system.register_function(build_constructor<PairType, const typename PairType::first_type &, const typename PairType::second_type &>(), type);
}
template<typename ContainerType>
void bootstrap_pair_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_associative_container<ContainerType>(system, type);
bootstrap_pair<typename ContainerType::value_type>(system, type + "_Pair");
}
template<typename ContainerType>
void bootstrap_unique_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_associative_container<ContainerType>(system, type);
register_function(system, &ContainerType::count, "count");
}
template<typename ContainerType>
void bootstrap_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
{
typedef std::pair<typename ContainerType::iterator, typename ContainerType::iterator>
(ContainerType::*eq_range)(const typename ContainerType::key_type &);
bootstrap_reversible_container<ContainerType>(system, type);
bootstrap_associative_container<ContainerType>(system, type);
register_function(system, eq_range(&ContainerType::equal_range), "equal_range");
}
template<typename ContainerType>
void bootstrap_unique_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_sorted_associative_container<ContainerType>(system, type);
bootstrap_unique_associative_container<ContainerType>(system, type);
}
template<typename MapType>
void bootstrap_map(Dispatch_Engine &system, const std::string &type)
{
system.register_type<MapType>(type);
register_function(system, &MapType::operator[], "[]");
bootstrap_unique_sorted_associative_container<MapType>(system, type);
bootstrap_pair_associative_container<MapType>(system, type);
}
template<typename String>
void bootstrap_string(Dispatch_Engine &system, const std::string &type)
{
system.register_type<String>(type);
add_oper_add<String>(system);
add_oper_add_equals<String>(system);
add_opers_comparison<String>(system);
bootstrap_random_access_container<String>(system, type);
bootstrap_sequence<String>(system, type);
}
}
#endif
<commit_msg>Add "empty" support to standard containers.<commit_after>#ifndef __bootstrap_stl_hpp
#define __bootstrap_stl_hpp__
#include "dispatchkit.hpp"
#include "register_function.hpp"
namespace dispatchkit
{
template<typename Container>
struct Input_Range
{
Input_Range(Container &c)
: m_begin(c.begin()), m_end(c.end())
{
}
Input_Range(typename Container::iterator itr)
: m_begin(itr), m_end(itr)
{
}
Input_Range(const std::pair<typename Container::iterator, typename Container::iterator> &t_p)
: m_begin(t_p.first), m_end(t_p.second)
{
}
bool empty() const
{
return m_begin == m_end;
}
void pop_front()
{
if (empty())
{
throw std::range_error("Range empty");
}
++m_begin;
}
typename std::iterator_traits<typename Container::iterator>::reference front() const
{
if (empty())
{
throw std::range_error("Range empty");
}
return *m_begin;
}
typename Container::iterator m_begin;
typename Container::iterator m_end;
};
template<typename ContainerType>
void bootstrap_input_range(Dispatch_Engine &system, const std::string &type)
{
system.register_function(build_constructor<Input_Range<ContainerType>, ContainerType &>(), "range");
system.register_function(build_constructor<Input_Range<ContainerType>,
typename ContainerType::iterator>(), "range");
system.register_function(build_constructor<Input_Range<ContainerType>,
const std::pair<typename ContainerType::iterator, typename ContainerType::iterator> &>(), "range");
register_function(system, &Input_Range<ContainerType>::empty, "empty");
register_function(system, &Input_Range<ContainerType>::pop_front, "pop_front");
register_function(system, &Input_Range<ContainerType>::front, "front");
system.register_function(build_constructor<Input_Range<ContainerType>, const Input_Range<ContainerType> &>(), "clone");
}
template<typename ContainerType>
void bootstrap_reversible_container(Dispatch_Engine &system, const std::string &type)
{
}
template<typename ContainerType>
void bootstrap_random_access_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_reversible_container<ContainerType>(system, type);
typedef typename ContainerType::reference(ContainerType::*indexoper)(size_t);
//In the interest of runtime safety for the system, we prefer the at() method for [] access,
//to throw an exception in an out of bounds condition.
system.register_function(
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::at)), "[]");
system.register_function(
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::operator[])), "at");
}
template<typename Assignable>
void bootstrap_assignable(Dispatch_Engine &system, const std::string &type)
{
add_basic_constructors<Assignable>(system, type);
add_oper_assign<Assignable>(system);
}
template<typename ContainerType>
void bootstrap_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_assignable<ContainerType>(system, type);
system.register_function(
boost::function<size_t (ContainerType *)>(&ContainerType::size), "size");
system.register_function(
boost::function<size_t (ContainerType *)>(&ContainerType::size), "maxsize");
register_function(system, &ContainerType::empty, "empty");
}
template<typename ContainerType>
void bootstrap_forward_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_input_range<ContainerType>(system, type);
bootstrap_container<ContainerType>(system, type);
}
template<typename Type>
void bootstrap_default_constructible(Dispatch_Engine &system, const std::string &type)
{
system.register_function(build_constructor<Type>(), type);
}
template<typename SequenceType>
void bootstrap_sequence(Dispatch_Engine &system, const std::string &type)
{
bootstrap_forward_container<SequenceType>(system, type);
bootstrap_default_constructible<SequenceType>(system, type);
}
template<typename SequenceType>
void bootstrap_back_insertion_sequence(Dispatch_Engine &system, const std::string &type)
{
bootstrap_sequence<SequenceType>(system, type);
typedef typename SequenceType::reference (SequenceType::*backptr)();
system.register_function(boost::function<typename SequenceType::reference (SequenceType *)>(backptr(&SequenceType::back)), "back");
system.register_function(boost::function<void (SequenceType *,typename SequenceType::value_type)>(&SequenceType::push_back), "push_back_ref");
system.register_function(boost::function<void (SequenceType *)>(&SequenceType::pop_back), "pop_back");
}
template<typename VectorType>
void bootstrap_vector(Dispatch_Engine &system, const std::string &type)
{
system.register_type<VectorType>(type);
bootstrap_random_access_container<VectorType>(system, type);
bootstrap_back_insertion_sequence<VectorType>(system, type);
}
template<typename ContainerType>
void bootstrap_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_forward_container<ContainerType>(system, type);
bootstrap_default_constructible<ContainerType>(system, type);
}
template<typename PairType>
void bootstrap_pair(Dispatch_Engine &system, const std::string &type)
{
register_member(system, &PairType::first, "first");
register_member(system, &PairType::second, "second");
system.register_function(build_constructor<PairType >(), type);
system.register_function(build_constructor<PairType, const PairType &>(), type);
system.register_function(build_constructor<PairType, const PairType &>(), "clone");
system.register_function(build_constructor<PairType, const typename PairType::first_type &, const typename PairType::second_type &>(), type);
}
template<typename ContainerType>
void bootstrap_pair_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_associative_container<ContainerType>(system, type);
bootstrap_pair<typename ContainerType::value_type>(system, type + "_Pair");
}
template<typename ContainerType>
void bootstrap_unique_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_associative_container<ContainerType>(system, type);
register_function(system, &ContainerType::count, "count");
}
template<typename ContainerType>
void bootstrap_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
{
typedef std::pair<typename ContainerType::iterator, typename ContainerType::iterator>
(ContainerType::*eq_range)(const typename ContainerType::key_type &);
bootstrap_reversible_container<ContainerType>(system, type);
bootstrap_associative_container<ContainerType>(system, type);
register_function(system, eq_range(&ContainerType::equal_range), "equal_range");
}
template<typename ContainerType>
void bootstrap_unique_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
{
bootstrap_sorted_associative_container<ContainerType>(system, type);
bootstrap_unique_associative_container<ContainerType>(system, type);
}
template<typename MapType>
void bootstrap_map(Dispatch_Engine &system, const std::string &type)
{
system.register_type<MapType>(type);
register_function(system, &MapType::operator[], "[]");
bootstrap_unique_sorted_associative_container<MapType>(system, type);
bootstrap_pair_associative_container<MapType>(system, type);
}
template<typename String>
void bootstrap_string(Dispatch_Engine &system, const std::string &type)
{
system.register_type<String>(type);
add_oper_add<String>(system);
add_oper_add_equals<String>(system);
add_opers_comparison<String>(system);
bootstrap_random_access_container<String>(system, type);
bootstrap_sequence<String>(system, type);
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Novell Inc.
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Amelia Wang <amwang@novell.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include "datafdlg.hxx"
#include "scresid.hxx"
#include "datafdlg.hrc"
#include "viewdata.hxx"
//#include "document.hxx"
#include "docsh.hxx"
#include "refundo.hxx"
#include "undodat.hxx"
#define HDL(hdl) LINK( this, ScDataFormDlg, hdl )
//zhangyun
ScDataFormDlg::ScDataFormDlg( Window* pParent, ScTabViewShell* pTabViewShellOri) :
ModalDialog ( pParent, ScResId( RID_SCDLG_DATAFORM ) ),
//
aBtnNew ( this, ScResId( BTN_DATAFORM_NEW ) ),
aBtnDelete ( this, ScResId( BTN_DATAFORM_DELETE ) ),
aBtnRestore ( this, ScResId( BTN_DATAFORM_RESTORE ) ),
aBtnLast ( this, ScResId( BTN_DATAFORM_LAST ) ),
aBtnNext ( this, ScResId( BTN_DATAFORM_NEXT ) ),
aBtnClose ( this, ScResId( BTN_DATAFORM_CLOSE ) ),
aSlider ( this, ScResId( WND_DATAFORM_SCROLLBAR ) ),
aFixedText ( this, ScResId( LAB_DATAFORM_RECORDNO ) )
{
pTabViewShell = pTabViewShellOri;
FreeResource();
//read header form current document, and add new controls
DBG_ASSERT( pTabViewShell, "pTabViewShell is NULL! :-/" );
ScViewData* pViewData = pTabViewShell->GetViewData();
pDoc = pViewData->GetDocument();
if (pDoc)
{
ScRange aRange;
pViewData->GetSimpleArea( aRange );
ScAddress aStart = aRange.aStart;
ScAddress aEnd = aRange.aEnd;
nStartCol = aStart.Col();
nEndCol = aEnd.Col();
nStartRow = aStart.Row();
nEndRow = aEnd.Row();
nTab = pViewData->GetTabNo();
//if there is no selection
if ((nStartCol == nEndCol) && (nStartRow == nEndRow))
bNoSelection = TRUE;
if (bNoSelection)
{
//find last not blank cell in row
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
nEndCol++;
pDoc->GetString( nEndCol, nStartRow, nTab, aColName );
int nColWidth = pDoc->GetColWidth( nEndCol, nTab );
if ( aColName.Len() == 0 && nColWidth)
{
nEndCol--;
break;
}
}
//find first not blank cell in row
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
if (nStartCol <= 0)
break;
nStartCol--;
pDoc->GetString( nStartCol, nStartRow, nTab, aColName );
int nColWidth = pDoc->GetColWidth( nEndCol, nTab );
if ( aColName.Len() == 0 && nColWidth)
{
nStartCol++;
break;
}
}
//skip leading hide column
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
int nColWidth = pDoc->GetColWidth( nStartCol, nTab );
if (nColWidth)
break;
nStartCol++;
}
if (nEndCol < nStartCol)
nEndCol = nStartCol;
//find last not blank cell in row
for (int i=1;i<=MAX_DATAFORM_ROWS;i++)
{
String aColName;
nEndRow++;
pDoc->GetString( nStartCol, nEndRow, nTab, aColName );
if ( aColName.Len() == 0 )
{
nEndRow--;
break;
}
}
//find first not blank cell in row
for (int i=1;i<=MAX_DATAFORM_ROWS;i++)
{
String aColName;
if (nStartRow <= 0)
break;
nStartRow--;
pDoc->GetString( nStartCol, nStartRow, nTab, aColName );
if ( aColName.Len() == 0 )
{
nStartRow++;
break;
}
}
if (nEndRow < nStartRow)
nEndRow = nStartRow;
}
aCurrentRow = nStartRow + 1;
String aFieldName;
int nTop = 12;
Size nFixedSize(FIXED_WIDTH, CTRL_HEIGHT );
Size nEditSize(EDIT_WIDTH, CTRL_HEIGHT );
//pFtArray = new FixedText(this);
aColLength = nEndCol - nStartCol + 1;
//new the controls
pFixedTexts = new FixedText*[aColLength];
pEdits = new Edit*[aColLength];
for(sal_uInt16 nIndex = 0; nIndex < aColLength; nIndex++)
{
pDoc->GetString( nIndex + nStartCol, nStartRow, nTab, aFieldName );
int nColWidth = pDoc->GetColWidth( nIndex + nStartCol, nTab );
if (nColWidth)
{
pFixedTexts[nIndex] = new FixedText(this);
pEdits[nIndex] = new Edit(this, WB_BORDER);
pFixedTexts[nIndex]->SetSizePixel(nFixedSize);
pEdits[nIndex]->SetSizePixel(nEditSize);
pFixedTexts[nIndex]->SetPosPixel(Point(FIXED_LEFT, nTop));
pEdits[nIndex]->SetPosPixel(Point(EDIT_LEFT, nTop));
//pFixedTexts[nIndex]->SetText(String::CreateFromAscii("W4W-Filter Nr. "));
pFixedTexts[nIndex]->SetText(aFieldName);
pFixedTexts[nIndex]->Show();
pEdits[nIndex]->Show();
nTop += LINE_HEIGHT;
}
else
{
pFixedTexts[nIndex] = NULL;
pEdits[nIndex] = NULL;
}
pEdits[nIndex]->SetModifyHdl( HDL(Impl_DataModifyHdl) );
}
Size nDialogSize = this->GetSizePixel();
if (nTop > nDialogSize.Height())
{
nDialogSize.setHeight(nTop);
this->SetSizePixel(nDialogSize);
}
Size nScrollSize = aSlider.GetSizePixel();
nScrollSize.setHeight(nDialogSize.Height()-20);
aSlider.SetSizePixel(nScrollSize);
}
FillCtrls(aCurrentRow);
aSlider.SetPageSize( 10 );
aSlider.SetVisibleSize( 1 );
aSlider.SetLineSize( 1 );
aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );
aSlider.Show();
aBtnNew.SetClickHdl ( HDL(Impl_NewHdl) );
aBtnLast.SetClickHdl ( HDL(Impl_LastHdl) );
aBtnNext.SetClickHdl ( HDL(Impl_NextHdl) );
aBtnRestore.SetClickHdl ( HDL(Impl_RestoreHdl) );
aBtnDelete.SetClickHdl ( HDL(Impl_DeleteHdl) );
aBtnClose.SetClickHdl ( HDL(Impl_CloseHdl) );
aSlider.SetEndScrollHdl( HDL( Impl_ScrollHdl ) );
SetButtonState();
//end
//FreeResource();
}
ScDataFormDlg::~ScDataFormDlg()
{
for(sal_uInt16 i = 0; i < aColLength; i++)
{
if (pEdits[i])
delete pEdits[i];
if (pFixedTexts[i])
delete pFixedTexts[i];
}
if (pEdits)
delete pEdits;
if (pFixedTexts)
delete pFixedTexts;
}
void ScDataFormDlg::FillCtrls(SCROW /*nCurrentRow*/)
{
//ScViewData* pViewData = pTabViewShell->GetViewData();
//pDoc = pViewData->GetDocument();
String aFieldName;
int nRecordNum = nEndRow - nStartRow;
for(sal_uInt16 i = 0; i < aColLength; i++)
{
if (pEdits[i])
{
if (aCurrentRow<=nEndRow)
{
pDoc->GetString( i + nStartCol, aCurrentRow, nTab, aFieldName );
pEdits[i]->SetText(aFieldName);
}
else
pEdits[i]->SetText(String());
}
}
char sRecordStr[256];
if (aCurrentRow<=nEndRow)
aFixedText.SetText(String::CreateFromAscii(sRecordStr));
else
aFixedText.SetText(String::CreateFromAscii("New Record"));
aSlider.SetThumbPos(aCurrentRow-nStartRow-1);
}
IMPL_LINK( ScDataFormDlg, Impl_DataModifyHdl, Edit*, pEdit)
{
if ( pEdit->IsModified() )
aBtnRestore.Enable( TRUE );
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_NewHdl, PushButton*, EMPTYARG )
{
ScViewData* pViewData = pTabViewShell->GetViewData();
ScDocShell* pDocSh = pViewData->GetDocShell();
if ( pDoc )
{
sal_Bool bHasData = sal_False;
for(sal_uInt16 i = 0; i < aColLength; i++)
if (pEdits[i])
if ( pEdits[i]->GetText().Len() != 0 )
{
bHasData = sal_True;
break;
}
if ( bHasData )
{
pTabViewShell->DataFormPutData( aCurrentRow , nStartRow , nStartCol , nEndRow , nEndCol , pEdits , aColLength );
aCurrentRow++;
if (aCurrentRow >= nEndRow + 2)
{
nEndRow ++ ;
aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );
}
SetButtonState();
FillCtrls(aCurrentRow);
pDocSh->SetDocumentModified();
pDocSh->PostPaintGridAll();
}
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_LastHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
if ( aCurrentRow > nStartRow +1 )
aCurrentRow--;
SetButtonState();
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_NextHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
if ( aCurrentRow <= nEndRow)
aCurrentRow++;
SetButtonState();
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_RestoreHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_DeleteHdl, PushButton*, EMPTYARG )
{
ScViewData* pViewData = pTabViewShell->GetViewData();
ScDocShell* pDocSh = pViewData->GetDocShell();
if (pDoc)
{
ScRange aRange(nStartCol, aCurrentRow, nTab, nEndCol, aCurrentRow, nTab);
pDoc->DeleteRow(aRange);
nEndRow--;
SetButtonState();
pDocSh->GetUndoManager()->Clear();
FillCtrls(aCurrentRow);
pDocSh->SetDocumentModified();
pDocSh->PostPaintGridAll();
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_CloseHdl, PushButton*, EMPTYARG )
{
EndDialog( );
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_ScrollHdl, ScrollBar*, EMPTYARG )
{
long nOffset = aSlider.GetThumbPos();
aCurrentRow = nStartRow + nOffset + 1;
SetButtonState();
FillCtrls(aCurrentRow);
return 0;
}
void ScDataFormDlg::SetButtonState()
{
if ( aCurrentRow > nEndRow )
{
aBtnDelete.Enable( FALSE );
aBtnLast.Enable( TRUE );
aBtnNext.Enable( FALSE );
}
else
{
aBtnDelete.Enable( TRUE );
aBtnNext.Enable( TRUE );
}
if ( 1 == aCurrentRow )
aBtnLast.Enable( FALSE );
aBtnRestore.Enable( FALSE );
if ( pEdits )
pEdits[0]->GrabFocus();
}
<commit_msg>remove unused variables<commit_after>/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Novell Inc.
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Amelia Wang <amwang@novell.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include "datafdlg.hxx"
#include "scresid.hxx"
#include "datafdlg.hrc"
#include "viewdata.hxx"
//#include "document.hxx"
#include "docsh.hxx"
#include "refundo.hxx"
#include "undodat.hxx"
#define HDL(hdl) LINK( this, ScDataFormDlg, hdl )
//zhangyun
ScDataFormDlg::ScDataFormDlg( Window* pParent, ScTabViewShell* pTabViewShellOri) :
ModalDialog ( pParent, ScResId( RID_SCDLG_DATAFORM ) ),
//
aBtnNew ( this, ScResId( BTN_DATAFORM_NEW ) ),
aBtnDelete ( this, ScResId( BTN_DATAFORM_DELETE ) ),
aBtnRestore ( this, ScResId( BTN_DATAFORM_RESTORE ) ),
aBtnLast ( this, ScResId( BTN_DATAFORM_LAST ) ),
aBtnNext ( this, ScResId( BTN_DATAFORM_NEXT ) ),
aBtnClose ( this, ScResId( BTN_DATAFORM_CLOSE ) ),
aSlider ( this, ScResId( WND_DATAFORM_SCROLLBAR ) ),
aFixedText ( this, ScResId( LAB_DATAFORM_RECORDNO ) )
{
pTabViewShell = pTabViewShellOri;
FreeResource();
//read header form current document, and add new controls
DBG_ASSERT( pTabViewShell, "pTabViewShell is NULL! :-/" );
ScViewData* pViewData = pTabViewShell->GetViewData();
pDoc = pViewData->GetDocument();
if (pDoc)
{
ScRange aRange;
pViewData->GetSimpleArea( aRange );
ScAddress aStart = aRange.aStart;
ScAddress aEnd = aRange.aEnd;
nStartCol = aStart.Col();
nEndCol = aEnd.Col();
nStartRow = aStart.Row();
nEndRow = aEnd.Row();
nTab = pViewData->GetTabNo();
//if there is no selection
if ((nStartCol == nEndCol) && (nStartRow == nEndRow))
bNoSelection = TRUE;
if (bNoSelection)
{
//find last not blank cell in row
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
nEndCol++;
pDoc->GetString( nEndCol, nStartRow, nTab, aColName );
int nColWidth = pDoc->GetColWidth( nEndCol, nTab );
if ( aColName.Len() == 0 && nColWidth)
{
nEndCol--;
break;
}
}
//find first not blank cell in row
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
if (nStartCol <= 0)
break;
nStartCol--;
pDoc->GetString( nStartCol, nStartRow, nTab, aColName );
int nColWidth = pDoc->GetColWidth( nEndCol, nTab );
if ( aColName.Len() == 0 && nColWidth)
{
nStartCol++;
break;
}
}
//skip leading hide column
for (int i=1;i<=MAX_DATAFORM_COLS;i++)
{
String aColName;
int nColWidth = pDoc->GetColWidth( nStartCol, nTab );
if (nColWidth)
break;
nStartCol++;
}
if (nEndCol < nStartCol)
nEndCol = nStartCol;
//find last not blank cell in row
for (int i=1;i<=MAX_DATAFORM_ROWS;i++)
{
String aColName;
nEndRow++;
pDoc->GetString( nStartCol, nEndRow, nTab, aColName );
if ( aColName.Len() == 0 )
{
nEndRow--;
break;
}
}
//find first not blank cell in row
for (int i=1;i<=MAX_DATAFORM_ROWS;i++)
{
String aColName;
if (nStartRow <= 0)
break;
nStartRow--;
pDoc->GetString( nStartCol, nStartRow, nTab, aColName );
if ( aColName.Len() == 0 )
{
nStartRow++;
break;
}
}
if (nEndRow < nStartRow)
nEndRow = nStartRow;
}
aCurrentRow = nStartRow + 1;
String aFieldName;
int nTop = 12;
Size nFixedSize(FIXED_WIDTH, CTRL_HEIGHT );
Size nEditSize(EDIT_WIDTH, CTRL_HEIGHT );
//pFtArray = new FixedText(this);
aColLength = nEndCol - nStartCol + 1;
//new the controls
pFixedTexts = new FixedText*[aColLength];
pEdits = new Edit*[aColLength];
for(sal_uInt16 nIndex = 0; nIndex < aColLength; nIndex++)
{
pDoc->GetString( nIndex + nStartCol, nStartRow, nTab, aFieldName );
int nColWidth = pDoc->GetColWidth( nIndex + nStartCol, nTab );
if (nColWidth)
{
pFixedTexts[nIndex] = new FixedText(this);
pEdits[nIndex] = new Edit(this, WB_BORDER);
pFixedTexts[nIndex]->SetSizePixel(nFixedSize);
pEdits[nIndex]->SetSizePixel(nEditSize);
pFixedTexts[nIndex]->SetPosPixel(Point(FIXED_LEFT, nTop));
pEdits[nIndex]->SetPosPixel(Point(EDIT_LEFT, nTop));
//pFixedTexts[nIndex]->SetText(String::CreateFromAscii("W4W-Filter Nr. "));
pFixedTexts[nIndex]->SetText(aFieldName);
pFixedTexts[nIndex]->Show();
pEdits[nIndex]->Show();
nTop += LINE_HEIGHT;
}
else
{
pFixedTexts[nIndex] = NULL;
pEdits[nIndex] = NULL;
}
pEdits[nIndex]->SetModifyHdl( HDL(Impl_DataModifyHdl) );
}
Size nDialogSize = this->GetSizePixel();
if (nTop > nDialogSize.Height())
{
nDialogSize.setHeight(nTop);
this->SetSizePixel(nDialogSize);
}
Size nScrollSize = aSlider.GetSizePixel();
nScrollSize.setHeight(nDialogSize.Height()-20);
aSlider.SetSizePixel(nScrollSize);
}
FillCtrls(aCurrentRow);
aSlider.SetPageSize( 10 );
aSlider.SetVisibleSize( 1 );
aSlider.SetLineSize( 1 );
aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );
aSlider.Show();
aBtnNew.SetClickHdl ( HDL(Impl_NewHdl) );
aBtnLast.SetClickHdl ( HDL(Impl_LastHdl) );
aBtnNext.SetClickHdl ( HDL(Impl_NextHdl) );
aBtnRestore.SetClickHdl ( HDL(Impl_RestoreHdl) );
aBtnDelete.SetClickHdl ( HDL(Impl_DeleteHdl) );
aBtnClose.SetClickHdl ( HDL(Impl_CloseHdl) );
aSlider.SetEndScrollHdl( HDL( Impl_ScrollHdl ) );
SetButtonState();
//end
//FreeResource();
}
ScDataFormDlg::~ScDataFormDlg()
{
for(sal_uInt16 i = 0; i < aColLength; i++)
{
if (pEdits[i])
delete pEdits[i];
if (pFixedTexts[i])
delete pFixedTexts[i];
}
if (pEdits)
delete pEdits;
if (pFixedTexts)
delete pFixedTexts;
}
void ScDataFormDlg::FillCtrls(SCROW /*nCurrentRow*/)
{
//ScViewData* pViewData = pTabViewShell->GetViewData();
String aFieldName;
for (sal_uInt16 i = 0; i < aColLength; ++i)
{
if (pEdits[i])
{
if (aCurrentRow<=nEndRow)
{
pDoc->GetString( i + nStartCol, aCurrentRow, nTab, aFieldName );
pEdits[i]->SetText(aFieldName);
}
else
pEdits[i]->SetText(String());
}
}
char sRecordStr[256];
if (aCurrentRow<=nEndRow)
aFixedText.SetText(String::CreateFromAscii(sRecordStr));
else
aFixedText.SetText(String::CreateFromAscii("New Record"));
aSlider.SetThumbPos(aCurrentRow-nStartRow-1);
}
IMPL_LINK( ScDataFormDlg, Impl_DataModifyHdl, Edit*, pEdit)
{
if ( pEdit->IsModified() )
aBtnRestore.Enable( TRUE );
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_NewHdl, PushButton*, EMPTYARG )
{
ScViewData* pViewData = pTabViewShell->GetViewData();
ScDocShell* pDocSh = pViewData->GetDocShell();
if ( pDoc )
{
sal_Bool bHasData = sal_False;
for(sal_uInt16 i = 0; i < aColLength; i++)
if (pEdits[i])
if ( pEdits[i]->GetText().Len() != 0 )
{
bHasData = sal_True;
break;
}
if ( bHasData )
{
pTabViewShell->DataFormPutData( aCurrentRow , nStartRow , nStartCol , nEndRow , nEndCol , pEdits , aColLength );
aCurrentRow++;
if (aCurrentRow >= nEndRow + 2)
{
nEndRow ++ ;
aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );
}
SetButtonState();
FillCtrls(aCurrentRow);
pDocSh->SetDocumentModified();
pDocSh->PostPaintGridAll();
}
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_LastHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
if ( aCurrentRow > nStartRow +1 )
aCurrentRow--;
SetButtonState();
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_NextHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
if ( aCurrentRow <= nEndRow)
aCurrentRow++;
SetButtonState();
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_RestoreHdl, PushButton*, EMPTYARG )
{
if (pDoc)
{
FillCtrls(aCurrentRow);
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_DeleteHdl, PushButton*, EMPTYARG )
{
ScViewData* pViewData = pTabViewShell->GetViewData();
ScDocShell* pDocSh = pViewData->GetDocShell();
if (pDoc)
{
ScRange aRange(nStartCol, aCurrentRow, nTab, nEndCol, aCurrentRow, nTab);
pDoc->DeleteRow(aRange);
nEndRow--;
SetButtonState();
pDocSh->GetUndoManager()->Clear();
FillCtrls(aCurrentRow);
pDocSh->SetDocumentModified();
pDocSh->PostPaintGridAll();
}
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_CloseHdl, PushButton*, EMPTYARG )
{
EndDialog( );
return 0;
}
IMPL_LINK( ScDataFormDlg, Impl_ScrollHdl, ScrollBar*, EMPTYARG )
{
long nOffset = aSlider.GetThumbPos();
aCurrentRow = nStartRow + nOffset + 1;
SetButtonState();
FillCtrls(aCurrentRow);
return 0;
}
void ScDataFormDlg::SetButtonState()
{
if ( aCurrentRow > nEndRow )
{
aBtnDelete.Enable( FALSE );
aBtnLast.Enable( TRUE );
aBtnNext.Enable( FALSE );
}
else
{
aBtnDelete.Enable( TRUE );
aBtnNext.Enable( TRUE );
}
if ( 1 == aCurrentRow )
aBtnLast.Enable( FALSE );
aBtnRestore.Enable( FALSE );
if ( pEdits )
pEdits[0]->GrabFocus();
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.3.170); FILE MERGED 2008/04/01 15:44:36 thb 1.3.170.3: #i85898# Stripping all external header guards 2008/04/01 12:43:16 thb 1.3.170.2: #i85898# Stripping all external header guards 2008/03/31 13:01:09 rt 1.3.170.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: clipfmtitem.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:09:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#define _SVSTDARR_ULONGS
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#include <clipfmtitem.hxx>
#ifndef _COM_SUN_STAR_FRAME_STATUS_CLIPBOARDFORMATS_HPP_
#include <com/sun/star/frame/status/ClipboardFormats.hpp>
#endif
struct SvxClipboardFmtItem_Impl
{
SvStringsDtor aFmtNms;
SvULongs aFmtIds;
static String sEmptyStr;
SvxClipboardFmtItem_Impl() : aFmtNms( 8, 8 ), aFmtIds( 8, 8 ) {}
SvxClipboardFmtItem_Impl( const SvxClipboardFmtItem_Impl& );
};
String SvxClipboardFmtItem_Impl::sEmptyStr;
TYPEINIT1_AUTOFACTORY( SvxClipboardFmtItem, SfxPoolItem );
SvxClipboardFmtItem_Impl::SvxClipboardFmtItem_Impl(
const SvxClipboardFmtItem_Impl& rCpy )
{
aFmtIds.Insert( &rCpy.aFmtIds, 0 );
for( USHORT n = 0, nEnd = rCpy.aFmtNms.Count(); n < nEnd; ++n )
{
String* pStr = rCpy.aFmtNms[ n ];
if( pStr )
pStr = new String( *pStr );
aFmtNms.Insert( pStr, n );
}
}
SvxClipboardFmtItem::SvxClipboardFmtItem( USHORT nId )
: SfxPoolItem( nId ), pImpl( new SvxClipboardFmtItem_Impl )
{
}
SvxClipboardFmtItem::SvxClipboardFmtItem( const SvxClipboardFmtItem& rCpy )
: SfxPoolItem( rCpy.Which() ),
pImpl( new SvxClipboardFmtItem_Impl( *rCpy.pImpl ) )
{
}
SvxClipboardFmtItem::~SvxClipboardFmtItem()
{
delete pImpl;
}
BOOL SvxClipboardFmtItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
USHORT nCount = Count();
::com::sun::star::frame::status::ClipboardFormats aClipFormats;
aClipFormats.Identifiers.realloc( nCount );
aClipFormats.Names.realloc( nCount );
for ( USHORT n=0; n < nCount; n++ )
{
aClipFormats.Identifiers[n] = (sal_Int64)GetClipbrdFormatId( n );
aClipFormats.Names[n] = GetClipbrdFormatName( n );
}
rVal <<= aClipFormats;
return TRUE;
}
sal_Bool SvxClipboardFmtItem::PutValue( const ::com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
::com::sun::star::frame::status::ClipboardFormats aClipFormats;
if ( rVal >>= aClipFormats )
{
USHORT nCount = USHORT( aClipFormats.Identifiers.getLength() );
pImpl->aFmtIds.Remove( 0, pImpl->aFmtIds.Count() );
pImpl->aFmtNms.Remove( 0, pImpl->aFmtNms.Count() );
for ( USHORT n=0; n < nCount; n++ )
AddClipbrdFormat( ULONG( aClipFormats.Identifiers[n] ), aClipFormats.Names[n], n );
return sal_True;
}
return sal_False;
}
int SvxClipboardFmtItem::operator==( const SfxPoolItem& rComp ) const
{
int nRet = 0;
const SvxClipboardFmtItem& rCmp = (SvxClipboardFmtItem&)rComp;
if( rCmp.pImpl->aFmtNms.Count() == pImpl->aFmtNms.Count() )
{
nRet = 1;
const String* pStr1, *pStr2;
for( USHORT n = 0, nEnd = rCmp.pImpl->aFmtNms.Count(); n < nEnd; ++n )
{
if( pImpl->aFmtIds[ n ] != rCmp.pImpl->aFmtIds[ n ] ||
( (0 == ( pStr1 = pImpl->aFmtNms[ n ] )) ^
(0 == ( pStr2 = rCmp.pImpl->aFmtNms[ n ] ) )) ||
( pStr1 && *pStr1 != *pStr2 ))
{
nRet = 0;
break;
}
}
}
return nRet;
}
SfxPoolItem* SvxClipboardFmtItem::Clone( SfxItemPool *pPool ) const
{
return new SvxClipboardFmtItem( *this );
}
void SvxClipboardFmtItem::AddClipbrdFormat( ULONG nId, USHORT nPos )
{
if( nPos > pImpl->aFmtNms.Count() )
nPos = pImpl->aFmtNms.Count();
String* pStr = 0;
pImpl->aFmtNms.Insert( pStr, nPos );
pImpl->aFmtIds.Insert( nId, nPos );
}
void SvxClipboardFmtItem::AddClipbrdFormat( ULONG nId, const String& rName,
USHORT nPos )
{
if( nPos > pImpl->aFmtNms.Count() )
nPos = pImpl->aFmtNms.Count();
String* pStr = new String( rName );
pImpl->aFmtNms.Insert( pStr, nPos );
pImpl->aFmtIds.Insert( nId, nPos );
}
USHORT SvxClipboardFmtItem::Count() const
{
return pImpl->aFmtIds.Count();
}
ULONG SvxClipboardFmtItem::GetClipbrdFormatId( USHORT nPos ) const
{
return pImpl->aFmtIds[ nPos ];
}
const String& SvxClipboardFmtItem::GetClipbrdFormatName( USHORT nPos ) const
{
const String* pS = pImpl->aFmtNms[ nPos ];
return pS ? *pS : SvxClipboardFmtItem_Impl::sEmptyStr;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.314); FILE MERGED 2005/09/05 14:25:34 rt 1.3.314.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: clipfmtitem.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:33:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#define _SVSTDARR_ULONGS
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#include <clipfmtitem.hxx>
#ifndef _COM_SUN_STAR_FRAME_STATUS_CLIPBOARDFORMATS_HPP_
#include <com/sun/star/frame/status/ClipboardFormats.hpp>
#endif
struct SvxClipboardFmtItem_Impl
{
SvStringsDtor aFmtNms;
SvULongs aFmtIds;
static String sEmptyStr;
SvxClipboardFmtItem_Impl() : aFmtNms( 8, 8 ), aFmtIds( 8, 8 ) {}
SvxClipboardFmtItem_Impl( const SvxClipboardFmtItem_Impl& );
};
String SvxClipboardFmtItem_Impl::sEmptyStr;
TYPEINIT1_AUTOFACTORY( SvxClipboardFmtItem, SfxPoolItem );
SvxClipboardFmtItem_Impl::SvxClipboardFmtItem_Impl(
const SvxClipboardFmtItem_Impl& rCpy )
{
aFmtIds.Insert( &rCpy.aFmtIds, 0 );
for( USHORT n = 0, nEnd = rCpy.aFmtNms.Count(); n < nEnd; ++n )
{
String* pStr = rCpy.aFmtNms[ n ];
if( pStr )
pStr = new String( *pStr );
aFmtNms.Insert( pStr, n );
}
}
SvxClipboardFmtItem::SvxClipboardFmtItem( USHORT nId )
: SfxPoolItem( nId ), pImpl( new SvxClipboardFmtItem_Impl )
{
}
SvxClipboardFmtItem::SvxClipboardFmtItem( const SvxClipboardFmtItem& rCpy )
: SfxPoolItem( rCpy.Which() ),
pImpl( new SvxClipboardFmtItem_Impl( *rCpy.pImpl ) )
{
}
SvxClipboardFmtItem::~SvxClipboardFmtItem()
{
delete pImpl;
}
BOOL SvxClipboardFmtItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
USHORT nCount = Count();
::com::sun::star::frame::status::ClipboardFormats aClipFormats;
aClipFormats.Identifiers.realloc( nCount );
aClipFormats.Names.realloc( nCount );
for ( USHORT n=0; n < nCount; n++ )
{
aClipFormats.Identifiers[n] = (sal_Int64)GetClipbrdFormatId( n );
aClipFormats.Names[n] = GetClipbrdFormatName( n );
}
rVal <<= aClipFormats;
return TRUE;
}
sal_Bool SvxClipboardFmtItem::PutValue( const ::com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
::com::sun::star::frame::status::ClipboardFormats aClipFormats;
if ( rVal >>= aClipFormats )
{
USHORT nCount = USHORT( aClipFormats.Identifiers.getLength() );
pImpl->aFmtIds.Remove( 0, pImpl->aFmtIds.Count() );
pImpl->aFmtNms.Remove( 0, pImpl->aFmtNms.Count() );
for ( USHORT n=0; n < nCount; n++ )
AddClipbrdFormat( ULONG( aClipFormats.Identifiers[n] ), aClipFormats.Names[n], n );
return sal_True;
}
return sal_False;
}
int SvxClipboardFmtItem::operator==( const SfxPoolItem& rComp ) const
{
int nRet = 0;
const SvxClipboardFmtItem& rCmp = (SvxClipboardFmtItem&)rComp;
if( rCmp.pImpl->aFmtNms.Count() == pImpl->aFmtNms.Count() )
{
nRet = 1;
const String* pStr1, *pStr2;
for( USHORT n = 0, nEnd = rCmp.pImpl->aFmtNms.Count(); n < nEnd; ++n )
{
if( pImpl->aFmtIds[ n ] != rCmp.pImpl->aFmtIds[ n ] ||
( (0 == ( pStr1 = pImpl->aFmtNms[ n ] )) ^
(0 == ( pStr2 = rCmp.pImpl->aFmtNms[ n ] ) )) ||
( pStr1 && *pStr1 != *pStr2 ))
{
nRet = 0;
break;
}
}
}
return nRet;
}
SfxPoolItem* SvxClipboardFmtItem::Clone( SfxItemPool *pPool ) const
{
return new SvxClipboardFmtItem( *this );
}
void SvxClipboardFmtItem::AddClipbrdFormat( ULONG nId, USHORT nPos )
{
if( nPos > pImpl->aFmtNms.Count() )
nPos = pImpl->aFmtNms.Count();
String* pStr = 0;
pImpl->aFmtNms.Insert( pStr, nPos );
pImpl->aFmtIds.Insert( nId, nPos );
}
void SvxClipboardFmtItem::AddClipbrdFormat( ULONG nId, const String& rName,
USHORT nPos )
{
if( nPos > pImpl->aFmtNms.Count() )
nPos = pImpl->aFmtNms.Count();
String* pStr = new String( rName );
pImpl->aFmtNms.Insert( pStr, nPos );
pImpl->aFmtIds.Insert( nId, nPos );
}
USHORT SvxClipboardFmtItem::Count() const
{
return pImpl->aFmtIds.Count();
}
ULONG SvxClipboardFmtItem::GetClipbrdFormatId( USHORT nPos ) const
{
return pImpl->aFmtIds[ nPos ];
}
const String& SvxClipboardFmtItem::GetClipbrdFormatName( USHORT nPos ) const
{
const String* pS = pImpl->aFmtNms[ nPos ];
return pS ? *pS : SvxClipboardFmtItem_Impl::sEmptyStr;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: lboxctrl.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: tl $ $Date: 2001-09-24 11:45:50 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SVX_LBOXCTRL_HXX_
#include <lboxctrl.hxx>
#endif
#include <svxids.hrc>
#include <dialogs.hrc>
#include "lboxctrl.hrc"
class SvxPopupWindowListBox;
#define A2S(x) String::CreateFromAscii(x)
/////////////////////////////////////////////////////////////////
class SvxPopupWindowListBox : public SfxPopupWindow
{
FixedInfo aInfo;
ListBox * pListBox;
ToolBox & rToolBox;
USHORT nItemId;
BOOL bUserSel;
// disallow copy-constructor and assignment-operator
SvxPopupWindowListBox(const& );
SvxPopupWindowListBox & operator = (const& );
SvxPopupWindowListBox( USHORT nSlotId,
ToolBox& rTbx, USHORT nTbxItemId );
public:
SvxPopupWindowListBox( USHORT nSlotId,
ToolBox& rTbx, USHORT nTbxItemId,
SfxBindings &rBindings );
virtual ~SvxPopupWindowListBox();
// SfxPopupWindow
virtual SfxPopupWindow * Clone() const;
virtual void PopupModeEnd();
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
void StartSelection();
inline ListBox & GetListBox() { return *pListBox; }
inline FixedInfo & GetInfo() { return aInfo; }
BOOL IsUserSelected() const { return bUserSel; }
void SetUserSelected( BOOL bVal ) { bUserSel = bVal; }
};
/////////////////////////////////////////////////////////////////
SvxPopupWindowListBox::SvxPopupWindowListBox(
USHORT nSlotId,
ToolBox& rTbx, USHORT nTbxItemId,
SfxBindings &rBindings ) :
SfxPopupWindow( nSlotId, SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ), rBindings ),
aInfo ( this, ResId( FT_NUM_OPERATIONS ) ),
rToolBox ( rTbx ),
nItemId ( nTbxItemId ),
bUserSel ( FALSE )
{
DBG_ASSERT( nSlotId == GetId(), "id mismatch" );
pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );
FreeResource();
pListBox->EnableMultiSelection( TRUE, TRUE );
SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
pListBox->GrabFocus();
}
SvxPopupWindowListBox::~SvxPopupWindowListBox()
{
delete pListBox;
}
SfxPopupWindow* SvxPopupWindowListBox::Clone() const
{
return new SvxPopupWindowListBox( GetId(), rToolBox, nItemId,
(SfxBindings &) GetBindings() );
}
void SvxPopupWindowListBox::PopupModeEnd()
{
rToolBox.EndSelection();
SfxPopupWindow::PopupModeEnd();
//FloatingWindow::PopupModeEnd();
rToolBox.SetItemDown( nItemId, FALSE );
}
void SvxPopupWindowListBox::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
rToolBox.EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
SfxPopupWindow::StateChanged( nSID, eState, pState );
}
void SvxPopupWindowListBox::StartSelection()
{
rToolBox.StartSelection();
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );
SvxListBoxControl::SvxListBoxControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SfxToolBoxControl( nId, rTbx, rBind ),
nItemId ( nId ),
pPopupWin ( 0 )
{
ToolBox& rBox = GetToolBox();
rBox.SetItemBits( nId, TIB_DROPDOWN | rBox.GetItemBits( nId ) );
rBox.Invalidate();
}
SvxListBoxControl::~SvxListBoxControl()
{
}
SfxPopupWindow* SvxListBoxControl::CreatePopupWindow()
{
DBG_ERROR( "not implemented" );
return 0;
}
SfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const
{
return SFX_POPUPWINDOW_ONTIMEOUT;
}
void SvxListBoxControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
}
IMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )
{
if (pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&
pPopupWin->IsUserSelected() )
{
USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();
SfxUInt16Item aItem( GetId(), nCount );
GetBindings().GetDispatcher()->Execute( GetId(),
SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}
return 0;
}
void SvxListBoxControl::Impl_SetInfo( USHORT nCount )
{
DBG_ASSERT( pPopupWin, "NULL pointer, PopupWindow missing" );
String aText( aActionStr );
aText.SearchAndReplaceAll( A2S("$(ARG1)"), String::CreateFromInt32( nCount ) );
pPopupWin->GetInfo().SetText( aText );
}
IMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )
{
if (pPopupWin)
{
//pPopupWin->SetUserSelected( FALSE );
ListBox &rListBox = pPopupWin->GetListBox();
if (rListBox.IsTravelSelect())
Impl_SetInfo( rListBox.GetSelectEntryCount() );
else
{
pPopupWin->SetUserSelected( TRUE );
pPopupWin->EndPopupMode( 0 );
}
}
return 0;
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxUndoControl, SfxStringItem );
SvxUndoControl::SvxUndoControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SvxListBoxControl( nId, rTbx, rBind )
{
aActionStr = String( SVX_RES( RID_SVXSTR_NUM_UNDO_ACTIONS ) );
}
SvxUndoControl::~SvxUndoControl()
{
}
SfxPopupWindow* SvxUndoControl::CreatePopupWindow()
{
DBG_ASSERT( SID_UNDO == GetId(), "mismatching ids" );
const SfxPoolItem* pState = 0;
SfxBindings &rBindings = GetBindings();
SfxDispatcher &rDispatch = *GetBindings().GetDispatcher();
SfxItemState eState = rDispatch.QueryState( SID_GETUNDOSTRINGS, pState );
if (eState >= SFX_ITEM_AVAILABLE && pState)
{
ToolBox& rBox = GetToolBox();
pPopupWin = new SvxPopupWindowListBox( GetId(), rBox, nItemId, rBindings );
pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoControl, PopupModeEndHdl ) );
ListBox &rListBox = pPopupWin->GetListBox();
rListBox.SetSelectHdl( LINK( this, SvxUndoControl, SelectHdl ) );
SfxStringListItem &rItem = *(SfxStringListItem *) pState;
const List* pLst = rItem.GetList();
DBG_ASSERT( pLst, "no undo actions available" );
if( pLst )
for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
rListBox.InsertEntry( *((String*)pLst->GetObject( nI )) );
rListBox.SelectEntryPos( 0 );
Impl_SetInfo( rListBox.GetSelectEntryCount() );
// position window at the bottom-left of the toolbox icon
Rectangle aItemRect( rBox.GetItemRect( nItemId ) );
aItemRect.Bottom() += aItemRect.GetHeight() - 2;
rBox.SetItemDown( nItemId, TRUE );
pPopupWin->StartPopupMode( aItemRect );
pPopupWin->StartSelection();
}
return pPopupWin;
}
SfxPopupWindowType SvxUndoControl::GetPopupWindowType() const
{
return SvxListBoxControl::GetPopupWindowType();
}
void SvxUndoControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
SvxListBoxControl::StateChanged( nSID, eState, pState );
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxRedoControl, SfxStringItem );
SvxRedoControl::SvxRedoControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SvxListBoxControl( nId, rTbx, rBind )
{
aActionStr = String( SVX_RES( RID_SVXSTR_NUM_REDO_ACTIONS ) );
}
SvxRedoControl::~SvxRedoControl()
{
}
SfxPopupWindow* SvxRedoControl::CreatePopupWindow()
{
DBG_ASSERT( SID_REDO == GetId(), "mismatching ids" );
const SfxPoolItem* pState = 0;
SfxBindings &rBindings = GetBindings();
SfxDispatcher &rDispatch = *GetBindings().GetDispatcher();
SfxItemState eState = rDispatch.QueryState( SID_GETREDOSTRINGS, pState );
if (eState >= SFX_ITEM_AVAILABLE && pState)
{
ToolBox& rBox = GetToolBox();
pPopupWin = new SvxPopupWindowListBox( GetId(), rBox, nItemId, rBindings );
pPopupWin->SetPopupModeEndHdl( LINK( this, SvxRedoControl, PopupModeEndHdl ) );
ListBox &rListBox = pPopupWin->GetListBox();
rListBox.SetSelectHdl( LINK( this, SvxRedoControl, SelectHdl ) );
SfxStringListItem &rItem = *(SfxStringListItem *) pState;
const List* pLst = rItem.GetList();
DBG_ASSERT( pLst, "no redo actions available" );
if( pLst )
for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
rListBox.InsertEntry( *((String*)pLst->GetObject( nI )) );
rListBox.SelectEntryPos( 0 );
Impl_SetInfo( rListBox.GetSelectEntryCount() );
// position window at the bottom-left of the toolbox icon
Rectangle aItemRect( rBox.GetItemRect( nItemId ) );
aItemRect.Bottom() += aItemRect.GetHeight() - 2;
rBox.SetItemDown( nItemId, TRUE );
pPopupWin->StartPopupMode( aItemRect );
pPopupWin->StartSelection();
}
return pPopupWin;
}
SfxPopupWindowType SvxRedoControl::GetPopupWindowType() const
{
return SvxListBoxControl::GetPopupWindowType();
}
void SvxRedoControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
SvxListBoxControl::StateChanged( nSID, eState, pState );
}
/////////////////////////////////////////////////////////////////
<commit_msg>#92323# focus given back to application when popup-window is closed.<commit_after>/*************************************************************************
*
* $RCSfile: lboxctrl.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: tl $ $Date: 2001-09-26 08:28:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SVX_LBOXCTRL_HXX_
#include <lboxctrl.hxx>
#endif
#include <svxids.hrc>
#include <dialogs.hrc>
#include "lboxctrl.hrc"
class SvxPopupWindowListBox;
#define A2S(x) String::CreateFromAscii(x)
/////////////////////////////////////////////////////////////////
static void ReleaseTbxBtn_Impl( ToolBox &rBox, const Point &rPos )
{
MouseEvent aMEvt( rPos, 1, 0, 0, 0 );
rBox.Tracking( TrackingEvent( aMEvt, ENDTRACK_END ) );
}
/////////////////////////////////////////////////////////////////
class SvxPopupWindowListBox : public SfxPopupWindow
{
FixedInfo aInfo;
ListBox * pListBox;
ToolBox & rToolBox;
BOOL bUserSel;
// disallow copy-constructor and assignment-operator
SvxPopupWindowListBox(const& );
SvxPopupWindowListBox & operator = (const& );
SvxPopupWindowListBox( USHORT nSlotId,
ToolBox& rTbx, USHORT nTbxItemId );
public:
SvxPopupWindowListBox( USHORT nSlotId,
ToolBox& rTbx,
SfxBindings &rBindings );
virtual ~SvxPopupWindowListBox();
// SfxPopupWindow
virtual SfxPopupWindow * Clone() const;
virtual void PopupModeEnd();
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
void StartSelection();
inline ListBox & GetListBox() { return *pListBox; }
inline FixedInfo & GetInfo() { return aInfo; }
BOOL IsUserSelected() const { return bUserSel; }
void SetUserSelected( BOOL bVal ) { bUserSel = bVal; }
};
/////////////////////////////////////////////////////////////////
SvxPopupWindowListBox::SvxPopupWindowListBox(
USHORT nSlotId,
ToolBox& rTbx,
SfxBindings &rBindings ) :
SfxPopupWindow( nSlotId, SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ), rBindings ),
aInfo ( this, ResId( FT_NUM_OPERATIONS ) ),
rToolBox ( rTbx ),
bUserSel ( FALSE )
{
DBG_ASSERT( nSlotId == GetId(), "id mismatch" );
pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );
FreeResource();
pListBox->EnableMultiSelection( TRUE, TRUE );
SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
pListBox->GrabFocus();
}
SvxPopupWindowListBox::~SvxPopupWindowListBox()
{
delete pListBox;
}
SfxPopupWindow* SvxPopupWindowListBox::Clone() const
{
return new SvxPopupWindowListBox( GetId(), rToolBox,
(SfxBindings &) GetBindings() );
}
void SvxPopupWindowListBox::PopupModeEnd()
{
rToolBox.EndSelection();
SfxPopupWindow::PopupModeEnd();
//FloatingWindow::PopupModeEnd();
Window* pShellWnd = SfxViewShell::Current()->GetWindow();
if (pShellWnd)
pShellWnd->GrabFocus();
}
void SvxPopupWindowListBox::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
rToolBox.EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
SfxPopupWindow::StateChanged( nSID, eState, pState );
}
void SvxPopupWindowListBox::StartSelection()
{
rToolBox.StartSelection();
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );
SvxListBoxControl::SvxListBoxControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SfxToolBoxControl( nId, rTbx, rBind ),
nItemId ( nId ),
pPopupWin ( 0 )
{
ToolBox& rBox = GetToolBox();
rBox.SetItemBits( nId, TIB_DROPDOWN | rBox.GetItemBits( nId ) );
rBox.Invalidate();
}
SvxListBoxControl::~SvxListBoxControl()
{
}
SfxPopupWindow* SvxListBoxControl::CreatePopupWindow()
{
DBG_ERROR( "not implemented" );
return 0;
}
SfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const
{
return SFX_POPUPWINDOW_ONTIMEOUT;
}
void SvxListBoxControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
}
IMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )
{
if (pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&
pPopupWin->IsUserSelected() )
{
USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();
SfxUInt16Item aItem( GetId(), nCount );
GetBindings().GetDispatcher()->Execute( GetId(),
SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}
return 0;
}
void SvxListBoxControl::Impl_SetInfo( USHORT nCount )
{
DBG_ASSERT( pPopupWin, "NULL pointer, PopupWindow missing" );
String aText( aActionStr );
aText.SearchAndReplaceAll( A2S("$(ARG1)"), String::CreateFromInt32( nCount ) );
pPopupWin->GetInfo().SetText( aText );
}
IMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )
{
if (pPopupWin)
{
//pPopupWin->SetUserSelected( FALSE );
ListBox &rListBox = pPopupWin->GetListBox();
if (rListBox.IsTravelSelect())
Impl_SetInfo( rListBox.GetSelectEntryCount() );
else
{
pPopupWin->SetUserSelected( TRUE );
pPopupWin->EndPopupMode( 0 );
}
}
return 0;
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxUndoControl, SfxStringItem );
SvxUndoControl::SvxUndoControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SvxListBoxControl( nId, rTbx, rBind )
{
aActionStr = String( SVX_RES( RID_SVXSTR_NUM_UNDO_ACTIONS ) );
}
SvxUndoControl::~SvxUndoControl()
{
}
SfxPopupWindow* SvxUndoControl::CreatePopupWindow()
{
DBG_ASSERT( SID_UNDO == GetId(), "mismatching ids" );
DBG_ASSERT( SID_UNDO == nItemId, "mismatching ids" );
const SfxPoolItem* pState = 0;
SfxBindings &rBindings = GetBindings();
SfxDispatcher &rDispatch = *GetBindings().GetDispatcher();
SfxItemState eState = rDispatch.QueryState( SID_GETUNDOSTRINGS, pState );
if (eState >= SFX_ITEM_AVAILABLE && pState)
{
ToolBox& rBox = GetToolBox();
pPopupWin = new SvxPopupWindowListBox( GetId(), rBox, rBindings );
pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoControl, PopupModeEndHdl ) );
ListBox &rListBox = pPopupWin->GetListBox();
rListBox.SetSelectHdl( LINK( this, SvxUndoControl, SelectHdl ) );
SfxStringListItem &rItem = *(SfxStringListItem *) pState;
const List* pLst = rItem.GetList();
DBG_ASSERT( pLst, "no undo actions available" );
if( pLst )
for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
rListBox.InsertEntry( *((String*)pLst->GetObject( nI )) );
rListBox.SelectEntryPos( 0 );
Impl_SetInfo( rListBox.GetSelectEntryCount() );
// position window at the bottom-left of the toolbox icon.
// The -2 offset takes the distance from the item-rect to
// the toolbox border into account (can't be obtained from
// the toolbox).
Rectangle aItemRect( rBox.GetItemRect( GetId() ) );
aItemRect.Bottom() += aItemRect.GetHeight() - 2;
ReleaseTbxBtn_Impl( rBox, rBox.GetItemRect( GetId() ).TopLeft() );
pPopupWin->StartPopupMode( aItemRect );
pPopupWin->StartSelection();
}
return pPopupWin;
}
SfxPopupWindowType SvxUndoControl::GetPopupWindowType() const
{
return SvxListBoxControl::GetPopupWindowType();
}
void SvxUndoControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
SvxListBoxControl::StateChanged( nSID, eState, pState );
}
/////////////////////////////////////////////////////////////////
SFX_IMPL_TOOLBOX_CONTROL( SvxRedoControl, SfxStringItem );
SvxRedoControl::SvxRedoControl(
USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SvxListBoxControl( nId, rTbx, rBind )
{
aActionStr = String( SVX_RES( RID_SVXSTR_NUM_REDO_ACTIONS ) );
}
SvxRedoControl::~SvxRedoControl()
{
}
SfxPopupWindow* SvxRedoControl::CreatePopupWindow()
{
DBG_ASSERT( SID_REDO == GetId(), "mismatching ids" );
DBG_ASSERT( SID_REDO == nItemId, "mismatching ids" );
const SfxPoolItem* pState = 0;
SfxBindings &rBindings = GetBindings();
SfxDispatcher &rDispatch = *GetBindings().GetDispatcher();
SfxItemState eState = rDispatch.QueryState( SID_GETREDOSTRINGS, pState );
if (eState >= SFX_ITEM_AVAILABLE && pState)
{
ToolBox& rBox = GetToolBox();
pPopupWin = new SvxPopupWindowListBox( GetId(), rBox, rBindings );
pPopupWin->SetPopupModeEndHdl( LINK( this, SvxRedoControl, PopupModeEndHdl ) );
ListBox &rListBox = pPopupWin->GetListBox();
rListBox.SetSelectHdl( LINK( this, SvxRedoControl, SelectHdl ) );
SfxStringListItem &rItem = *(SfxStringListItem *) pState;
const List* pLst = rItem.GetList();
DBG_ASSERT( pLst, "no redo actions available" );
if( pLst )
for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
rListBox.InsertEntry( *((String*)pLst->GetObject( nI )) );
rListBox.SelectEntryPos( 0 );
Impl_SetInfo( rListBox.GetSelectEntryCount() );
// position window at the bottom-left of the toolbox icon.
// The -2 offset takes the distance from the item-rect to
// the toolbox border into account (can't be obtained from
// the toolbox).
Rectangle aItemRect( rBox.GetItemRect( GetId() ) );
aItemRect.Bottom() += aItemRect.GetHeight() - 2;
ReleaseTbxBtn_Impl( rBox, rBox.GetItemRect( GetId() ).TopLeft() );
pPopupWin->StartPopupMode( aItemRect );
pPopupWin->StartSelection();
}
return pPopupWin;
}
SfxPopupWindowType SvxRedoControl::GetPopupWindowType() const
{
return SvxListBoxControl::GetPopupWindowType();
}
void SvxRedoControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
SvxListBoxControl::StateChanged( nSID, eState, pState );
}
/////////////////////////////////////////////////////////////////
<|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.
*
************************************************************************/
#ifndef IDOCUMENTFIELDSACCESS_HXX_INCLUDED
#define IDOCUMENTFIELDSACCESS_HXX_INCLUDED
#include <sal/types.h>
#include <tools/solar.h>
class SwFldTypes;
class SwFieldType;
class SfxPoolItem;
struct SwPosition;
class SwDocUpdtFld;
class SwCalc;
class SwTxtFld;
class SwField;
class SwMsgPoolItem;
class DateTime;
class _SetGetExpFld;
struct SwHash;
class String;
class SwNode;
namespace com { namespace sun { namespace star { namespace uno { class Any; } } } }
/** Document fields related interfaces
*/
class IDocumentFieldsAccess
{
public:
/**
*/
virtual const SwFldTypes *GetFldTypes() const = 0;
/**
*/
virtual SwFieldType *InsertFldType(const SwFieldType &) = 0;
/**
*/
virtual SwFieldType *GetSysFldType( const sal_uInt16 eWhich ) const = 0;
/**
*/
virtual SwFieldType* GetFldType(sal_uInt16 nResId, const String& rName, bool bDbFieldMatching) const = 0;
/**
*/
virtual void RemoveFldType(sal_uInt16 nFld) = 0;
/**
*/
virtual void UpdateFlds( SfxPoolItem* pNewHt, bool bCloseDB) = 0;
/**
*/
virtual void InsDeletedFldType(SwFieldType &) = 0;
/**
Puts a value into a field at a certain position.
A missing field at the given position leads to a failure.
@param rPosition position of the field
@param rVal the value
@param nMId
@retval TRUE putting of value was successful
@retval FALSE else
*/
virtual bool PutValueToField(const SwPosition & rPos, const com::sun::star::uno::Any& rVal, USHORT nWhich) = 0;
// rufe das Update der Expression Felder auf; alle Ausdruecke werden
// neu berechnet.
/** Updates a field.
@param rDstFmtFld field to update
@param rSrcFld field containing the new values
@param pMsgHnt
@param bUpdateTblFlds TRUE: update table fields, too.
@retval TRUE update was successful
@retval FALSE else
*/
virtual bool UpdateFld(SwTxtFld * rDstFmtFld, SwField & rSrcFld, SwMsgPoolItem * pMsgHnt, bool bUpdateTblFlds) = 0;
/**
*/
virtual void UpdateRefFlds(SfxPoolItem* pHt) = 0;
/**
*/
virtual void UpdateTblFlds(SfxPoolItem* pHt) = 0;
/**
*/
virtual void UpdateExpFlds(SwTxtFld* pFld, bool bUpdateRefFlds) = 0;
/**
*/
virtual void UpdateUsrFlds() = 0;
/**
*/
virtual void UpdatePageFlds(SfxPoolItem*) = 0;
/**
*/
virtual void LockExpFlds() = 0;
/**
*/
virtual void UnlockExpFlds() = 0;
/**
*/
virtual bool IsExpFldsLocked() const = 0;
virtual SwDocUpdtFld& GetUpdtFlds() const = 0;
/* @@@MAINTAINABILITY-HORROR@@@
SwNode (see parameter pChk) is (?) part of the private
data structure of SwDoc and should not be exposed
*/
virtual bool SetFieldsDirty(bool b, const SwNode* pChk, ULONG nLen) = 0;
/**
*/
virtual void SetFixFields(bool bOnlyTimeDate, const DateTime* pNewDateTime) = 0;
// Setze im Calculator alle SetExpresion Felder, die bis zur
// angegebenen Position (Node [ + ::com::sun::star::ucb::Content]) gueltig sind. Es kann
// eine erzeugte Liste aller Felder mit uebergegeben werden.
// (ist die Adresse != 0, und der Pointer == 0 wird eine neue
// Liste returnt.)
virtual void FldsToCalc(SwCalc& rCalc, ULONG nLastNd, sal_uInt16 nLastCnt) = 0;
/**
*/
virtual void FldsToCalc(SwCalc& rCalc, const _SetGetExpFld& rToThisFld) = 0;
/**
*/
virtual void FldsToExpand(SwHash**& ppTbl, sal_uInt16& rTblSize, const _SetGetExpFld& rToThisFld) = 0;
/**
*/
virtual bool IsNewFldLst() const = 0;
/**
*/
virtual void SetNewFldLst( bool bFlag) = 0;
/**
*/
virtual void InsDelFldInFldLst(bool bIns, const SwTxtFld& rFld) = 0;
protected:
virtual ~IDocumentFieldsAccess() {};
};
#endif // IDOCUMENTLINKSADMINISTRATION_HXX_INCLUDED
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Transl. German comments in sw/inc/IDocumentFieldsAccess.hxx<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.
*
************************************************************************/
#ifndef IDOCUMENTFIELDSACCESS_HXX_INCLUDED
#define IDOCUMENTFIELDSACCESS_HXX_INCLUDED
#include <sal/types.h>
#include <tools/solar.h>
class SwFldTypes;
class SwFieldType;
class SfxPoolItem;
struct SwPosition;
class SwDocUpdtFld;
class SwCalc;
class SwTxtFld;
class SwField;
class SwMsgPoolItem;
class DateTime;
class _SetGetExpFld;
struct SwHash;
class String;
class SwNode;
namespace com { namespace sun { namespace star { namespace uno { class Any; } } } }
/** Document fields related interfaces
*/
class IDocumentFieldsAccess
{
public:
virtual const SwFldTypes *GetFldTypes() const = 0;
virtual SwFieldType *InsertFldType(const SwFieldType &) = 0;
virtual SwFieldType *GetSysFldType( const sal_uInt16 eWhich ) const = 0;
virtual SwFieldType* GetFldType(sal_uInt16 nResId, const String& rName, bool bDbFieldMatching) const = 0;
virtual void RemoveFldType(sal_uInt16 nFld) = 0;
virtual void UpdateFlds( SfxPoolItem* pNewHt, bool bCloseDB) = 0;
virtual void InsDeletedFldType(SwFieldType &) = 0;
/**
Puts a value into a field at a certain position.
A missing field at the given position leads to a failure.
@param rPosition position of the field
@param rVal the value
@param nMId
@retval TRUE putting of value was successful
@retval FALSE else
*/
virtual bool PutValueToField(const SwPosition & rPos, const com::sun::star::uno::Any& rVal, USHORT nWhich) = 0;
// rufe das Update der Expression Felder auf; alle Ausdruecke werden
// neu berechnet.
/** Updates a field.
@param rDstFmtFld field to update
@param rSrcFld field containing the new values
@param pMsgHnt
@param bUpdateTblFlds TRUE: update table fields, too.
@retval TRUE update was successful
@retval FALSE else
*/
virtual bool UpdateFld(SwTxtFld * rDstFmtFld, SwField & rSrcFld, SwMsgPoolItem * pMsgHnt, bool bUpdateTblFlds) = 0;
virtual void UpdateRefFlds(SfxPoolItem* pHt) = 0;
virtual void UpdateTblFlds(SfxPoolItem* pHt) = 0;
virtual void UpdateExpFlds(SwTxtFld* pFld, bool bUpdateRefFlds) = 0;
virtual void UpdateUsrFlds() = 0;
virtual void UpdatePageFlds(SfxPoolItem*) = 0;
virtual void LockExpFlds() = 0;
virtual void UnlockExpFlds() = 0;
virtual bool IsExpFldsLocked() const = 0;
virtual SwDocUpdtFld& GetUpdtFlds() const = 0;
/* @@@MAINTAINABILITY-HORROR@@@
SwNode (see parameter pChk) is (?) part of the private
data structure of SwDoc and should not be exposed
*/
virtual bool SetFieldsDirty(bool b, const SwNode* pChk, ULONG nLen) = 0;
virtual void SetFixFields(bool bOnlyTimeDate, const DateTime* pNewDateTime) = 0;
// In Calculator set all SetExpression fields that are valid up to the indicated position
// (Node [ + ::com::sun::star::ucb::Content]).
// A generated list of all fields may be passed along too
// (if the addreess != 0 and the pointer == 0 a new list will be returned).
virtual void FldsToCalc(SwCalc& rCalc, ULONG nLastNd, sal_uInt16 nLastCnt) = 0;
virtual void FldsToCalc(SwCalc& rCalc, const _SetGetExpFld& rToThisFld) = 0;
virtual void FldsToExpand(SwHash**& ppTbl, sal_uInt16& rTblSize, const _SetGetExpFld& rToThisFld) = 0;
virtual bool IsNewFldLst() const = 0;
virtual void SetNewFldLst( bool bFlag) = 0;
virtual void InsDelFldInFldLst(bool bIns, const SwTxtFld& rFld) = 0;
protected:
virtual ~IDocumentFieldsAccess() {};
};
#endif // IDOCUMENTLINKSADMINISTRATION_HXX_INCLUDED
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tabcol.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-12-01 16:32:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "tabcol.hxx"
SwTabCols::SwTabCols( USHORT nSize )
: SvLongs( (BYTE)nSize ),
aHidden( (BYTE)nSize ),
nLeftMin( 0 ),
nLeft( 0 ),
nRight( 0 ),
nRightMax( 0 )
{
}
SwTabCols::SwTabCols( const SwTabCols& rCpy )
: SvLongs( (BYTE)rCpy.Count(), 1 ),
aHidden( (BYTE)rCpy.Count(), 1 ),
nLeftMin( rCpy.GetLeftMin() ),
nLeft( rCpy.GetLeft() ),
nRight( rCpy.GetRight() ),
nRightMax( rCpy.GetRightMax() )
{
Insert( &rCpy, 0 );
aHidden.Insert( &rCpy.GetHidden(), 0 );
}
SwTabCols &SwTabCols::operator=( const SwTabCols& rCpy )
{
nLeftMin = rCpy.GetLeftMin();
nLeft = rCpy.GetLeft();
nRight = rCpy.GetRight();
nRightMax= rCpy.GetRightMax();
Remove( 0, Count() );
Insert( &rCpy, 0 );
aHidden.Remove( 0, aHidden.Count() );
aHidden.Insert( &rCpy.GetHidden(), 0 );
return *this;
}
BOOL SwTabCols::operator==( const SwTabCols& rCmp ) const
{
USHORT i;
if ( !(nLeftMin == rCmp.GetLeftMin() &&
nLeft == rCmp.GetLeft() &&
nRight == rCmp.GetRight() &&
nRightMax== rCmp.GetRightMax()&&
Count()== rCmp.Count()) )
return FALSE;
for ( i = 0; i < Count(); ++i )
if ( operator[](i) != rCmp[i] )
return FALSE;
for ( i = 0; i < aHidden.Count(); ++i )
if ( aHidden[i] != rCmp.IsHidden( i ) )
return FALSE;
return TRUE;
}
<commit_msg>INTEGRATION: CWS os27 (1.3.64); FILE MERGED 2004/02/20 14:15:19 fme 1.3.64.4: #i24134# Feature - Modify table rows with the ruler 2004/01/28 11:45:44 fme 1.3.64.3: #i24134# Feature - Modify table rows with the rules 2004/01/23 11:54:45 fme 1.3.64.2: #i24134# Feature - Modify table rows with the ruler 2004/01/23 07:46:31 fme 1.3.64.1: #i24134# Feature - Modify table rows with the ruler<commit_after>/*************************************************************************
*
* $RCSfile: tabcol.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-02-26 11:38: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: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "tabcol.hxx"
#ifndef _ERRHDL_HXX
#include <errhdl.hxx> // fuer Create-Methoden
#endif
SwTabCols::SwTabCols( USHORT nSize ) :
nLeftMin( 0 ),
nLeft( 0 ),
nRight( 0 ),
nRightMax( 0 ),
bLastRowAllowedToChange( true )
{
if ( nSize )
aData.reserve( nSize );
}
SwTabCols::SwTabCols( const SwTabCols& rCpy ) :
aData( rCpy.GetData() ),
nLeftMin( rCpy.GetLeftMin() ),
nLeft( rCpy.GetLeft() ),
nRight( rCpy.GetRight() ),
nRightMax( rCpy.GetRightMax() ),
bLastRowAllowedToChange( rCpy.IsLastRowAllowedToChange() )
{
#if OSL_DEBUG_LEVEL > 1
for ( USHORT i = 0; i < Count(); ++i )
{
SwTabColsEntry aEntry1 = aData[i];
SwTabColsEntry aEntry2 = rCpy.GetData()[i];
ASSERT( aEntry1.nPos == aEntry2.nPos &&
aEntry1.nMin == aEntry2.nMin &&
aEntry1.nMax == aEntry2.nMax &&
aEntry1.bHidden == aEntry2.bHidden,
"CopyContructor of SwTabColsEntries did not succeed!" )
}
#endif
}
SwTabCols &SwTabCols::operator=( const SwTabCols& rCpy )
{
nLeftMin = rCpy.GetLeftMin();
nLeft = rCpy.GetLeft();
nRight = rCpy.GetRight();
nRightMax= rCpy.GetRightMax();
bLastRowAllowedToChange = rCpy.IsLastRowAllowedToChange();
Remove( 0, Count() );
aData = rCpy.GetData();
return *this;
}
BOOL SwTabCols::operator==( const SwTabCols& rCmp ) const
{
USHORT i;
if ( !(nLeftMin == rCmp.GetLeftMin() &&
nLeft == rCmp.GetLeft() &&
nRight == rCmp.GetRight() &&
nRightMax== rCmp.GetRightMax()&&
bLastRowAllowedToChange== rCmp.IsLastRowAllowedToChange() &&
Count()== rCmp.Count()) )
return FALSE;
for ( i = 0; i < Count(); ++i )
{
SwTabColsEntry aEntry1 = aData[i];
SwTabColsEntry aEntry2 = rCmp.GetData()[i];
if ( aEntry1.nPos != aEntry2.nPos || aEntry1.bHidden != aEntry2.bHidden )
return FALSE;
}
return TRUE;
}
void SwTabCols::Insert( long nValue, long nMin, long nMax, BOOL bValue, USHORT nPos )
{
SwTabColsEntry aEntry;
aEntry.nPos = nValue;
aEntry.nMin = nMin;
aEntry.nMax = nMax;
aEntry.bHidden = bValue;
aData.insert( aData.begin() + nPos, aEntry );
}
void SwTabCols::Insert( long nValue, BOOL bValue, USHORT nPos )
{
SwTabColsEntry aEntry;
aEntry.nPos = nValue;
aEntry.nMin = 0;
aEntry.nMax = LONG_MAX;
aEntry.bHidden = bValue;
aData.insert( aData.begin() + nPos, aEntry );
#if OSL_DEBUG_LEVEL > 1
SwTabColsEntries::iterator aPos = aData.begin();
for ( ; aPos != aData.end(); ++aPos )
{
aEntry =(*aPos);
}
#endif
}
void SwTabCols::Remove( USHORT nPos, USHORT nAnz )
{
SwTabColsEntries::iterator aStart = aData.begin() + nPos;
aData.erase( aStart, aStart + nAnz );
}
<|endoftext|> |
<commit_before>// $Id$
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
#include <cassert>
#include "Util.h"
#include "StaticData.h"
#include "ScoreIndexManager.h"
#include "ScoreProducer.h"
#include "ScoreComponentCollection.h" // debugging
namespace Moses
{
using namespace std;
void ScoreIndexManager::AddScoreProducer(const ScoreProducer* sp)
{
// Producers must be inserted in the order they are created
const_cast<ScoreProducer*>(sp)->CreateScoreBookkeepingID();
assert(m_begins.size() == (sp->GetScoreBookkeepingID()));
m_producers.push_back(sp);
m_begins.push_back(m_last);
size_t numScoreCompsProduced = sp->GetNumScoreComponents();
assert(numScoreCompsProduced > 0);
m_last += numScoreCompsProduced;
m_ends.push_back(m_last);
InitFeatureNames();
/*VERBOSE(1,"Added ScoreProducer(" << sp->GetScoreBookkeepingID()
<< " " << sp->GetScoreProducerDescription()
<< ") index=" << m_begins.back() << "-" << m_ends.back()-1 << std::endl);
*/
}
void ScoreIndexManager::PrintLabeledScores(std::ostream& os, const ScoreComponentCollection& scores) const
{
std::vector<float> weights(scores.m_scores.size(), 1.0f);
PrintLabeledWeightedScores(os, scores, weights);
}
void ScoreIndexManager::PrintLabeledWeightedScores(std::ostream& os, const ScoreComponentCollection& scores, const std::vector<float>& weights) const
{
assert(m_featureShortNames.size() == weights.size());
string lastName = "";
for (size_t i = 0; i < m_featureShortNames.size(); ++i)
{
if (i>0)
{
os << " ";
}
if (lastName != m_featureShortNames[i])
{
os << m_featureShortNames[i] << ": ";
lastName = m_featureShortNames[i];
}
os << weights[i] * scores[i];
}
}
void ScoreIndexManager::InitFeatureNames() {
m_featureNames.clear();
m_featureIndexes.clear();
m_featureShortNames.clear();
size_t cur_i = 0;
size_t cur_scoreType = 0;
while (cur_i < m_last) {
size_t nis_idx = 0;
bool add_idx = (m_producers[cur_scoreType]->GetNumInputScores() > 1);
while (nis_idx < m_producers[cur_scoreType]->GetNumInputScores()){
ostringstream os;
//os << m_producers[cur_scoreType]->GetScoreProducerDescription();
//if (add_idx)
//os << '_' << (nis_idx+1);
os << cur_i;
const string &featureName = os.str();
m_featureNames.push_back(featureName);
m_featureIndexes[featureName] = m_featureNames.size() - 1;
nis_idx++;
cur_i++;
}
int ind = 1;
add_idx = (m_ends[cur_scoreType] - cur_i > 1);
while (cur_i < m_ends[cur_scoreType]) {
ostringstream os;
//os << m_producers[cur_scoreType]->GetScoreProducerDescription();
//if (add_idx)
//os << '_' << ind;
os << cur_i;
const string &featureName = os.str();
m_featureNames.push_back(featureName);
m_featureIndexes[featureName] = m_featureNames.size() - 1;
m_featureShortNames.push_back( m_producers[cur_scoreType]->GetScoreProducerWeightShortName() );
++cur_i;
++ind;
}
cur_scoreType++;
}
}
#if 0
void ScoreIndexManager::InitFeatureNamesAles() {
m_featureNames.clear();
m_featureIndexes.clear();
m_featureShortNames.clear();
size_t globalIndex = 0;
vector<const ScoreProducer *>::const_iterator it;
for (it = m_producers.begin(); it != m_producers.end(); ++it) {
size_t scoreCount = (*it)->GetNumInputScores();
for (size_t i = 0; i < scoreCount; ++i) {
ostringstream oStream;
oStream << (*it)->GetScoreProducerDescription() << "_" << globalIndex;
m_featureNames.push_back(oStream.str());
m_featureIndexes[oStream.str()] = globalIndex;
++globalIndex;
}
}
}
#endif
#ifdef HAVE_PROTOBUF
void ScoreIndexManager::SerializeFeatureNamesToPB(hgmert::Hypergraph* hg) const {
for (size_t i = 0; i < m_featureNames.size(); ++i) {
hg->add_feature_names(m_featureNames[i]);
}
}
#endif
void ScoreIndexManager::InitWeightVectorFromFile(const std::string& fnam, vector<float>* m_allWeights) const {
assert(m_allWeights->size() == m_featureNames.size());
ifstream in(fnam.c_str());
assert(in.good());
char buf[2000];
map<string, double> name2val;
while (!in.eof()) {
in.getline(buf, 2000);
if (strlen(buf) == 0) continue;
if (buf[0] == '#') continue;
istringstream is(buf);
string fname;
double val;
is >> fname >> val;
map<string, double>::iterator i = name2val.find(fname);
assert(i == name2val.end()); // duplicate weight name
name2val[fname] = val;
}
assert(m_allWeights->size() == m_featureNames.size());
for (size_t i = 0; i < m_featureNames.size(); ++i) {
map<string, double>::iterator iter = name2val.find(m_featureNames[i]);
if (iter == name2val.end()) {
cerr << "No weight found found for feature: " << m_featureNames[i] << endl;
abort();
}
(*m_allWeights)[i] = iter->second;
}
}
std::ostream& operator<<(std::ostream& os, const ScoreIndexManager& sim)
{
for (size_t i = 0; i < sim.m_featureNames.size(); ++i) {
os << sim.m_featureNames[i] << endl;
}
os << endl;
return os;
}
const std::string &ScoreIndexManager::GetFeatureName(size_t fIndex) const
{
#ifndef NDEBUG
if (m_featureNames.size() <= fIndex) {
printf("%s: %i ScoreIndexManager::GetFeatureName(m_producers.size() = %zd, m_featureNames.size() = %zd, fIndex = %zd)\n", __FILE__, __LINE__, m_producers.size(), m_featureNames.size(), fIndex);
}
#endif
assert(m_featureNames.size() > fIndex);
return m_featureNames[fIndex];
}
//! get the index of a feature by name
size_t ScoreIndexManager::GetFeatureIndex(const std::string& fName) const
{
return m_featureIndexes.find(fName)->second;
}
}
<commit_msg>Reg. tests now pass with shorter InitFeatureNames implementation.<commit_after>// $Id$
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
#include <cassert>
#include "Util.h"
#include "StaticData.h"
#include "ScoreIndexManager.h"
#include "ScoreProducer.h"
#include "ScoreComponentCollection.h" // debugging
namespace Moses
{
using namespace std;
void ScoreIndexManager::AddScoreProducer(const ScoreProducer* sp)
{
// Producers must be inserted in the order they are created
const_cast<ScoreProducer*>(sp)->CreateScoreBookkeepingID();
assert(m_begins.size() == (sp->GetScoreBookkeepingID()));
m_producers.push_back(sp);
m_begins.push_back(m_last);
size_t numScoreCompsProduced = sp->GetNumScoreComponents();
assert(numScoreCompsProduced > 0);
m_last += numScoreCompsProduced;
m_ends.push_back(m_last);
InitFeatureNames();
/*VERBOSE(1,"Added ScoreProducer(" << sp->GetScoreBookkeepingID()
<< " " << sp->GetScoreProducerDescription()
<< ") index=" << m_begins.back() << "-" << m_ends.back()-1 << std::endl);
*/
}
void ScoreIndexManager::PrintLabeledScores(std::ostream& os, const ScoreComponentCollection& scores) const
{
std::vector<float> weights(scores.m_scores.size(), 1.0f);
PrintLabeledWeightedScores(os, scores, weights);
}
void ScoreIndexManager::PrintLabeledWeightedScores(std::ostream& os, const ScoreComponentCollection& scores, const std::vector<float>& weights) const
{
assert(m_featureShortNames.size() == weights.size());
string lastName = "";
for (size_t i = 0; i < m_featureShortNames.size(); ++i)
{
if (i>0)
{
os << " ";
}
if (lastName != m_featureShortNames[i])
{
os << m_featureShortNames[i] << ": ";
lastName = m_featureShortNames[i];
}
os << weights[i] * scores[i];
}
}
void ScoreIndexManager::InitFeatureNames() {
m_featureNames.clear();
m_featureIndexes.clear();
m_featureShortNames.clear();
size_t globalIndex = 0;
vector<const ScoreProducer *>::const_iterator it;
for (it = m_producers.begin(); it != m_producers.end(); ++it) {
size_t scoreCount = (*it)->GetNumScoreComponents();
for (size_t i = 0; i < scoreCount; ++i) {
ostringstream oStream;
oStream << /* (*it)->GetScoreProducerDescription() << "_" << */ globalIndex;
m_featureNames.push_back(oStream.str());
m_featureIndexes[oStream.str()] = globalIndex;
++globalIndex;
}
}
}
#ifdef HAVE_PROTOBUF
void ScoreIndexManager::SerializeFeatureNamesToPB(hgmert::Hypergraph* hg) const {
for (size_t i = 0; i < m_featureNames.size(); ++i) {
hg->add_feature_names(m_featureNames[i]);
}
}
#endif
void ScoreIndexManager::InitWeightVectorFromFile(const std::string& fnam, vector<float>* m_allWeights) const {
assert(m_allWeights->size() == m_featureNames.size());
ifstream in(fnam.c_str());
assert(in.good());
char buf[2000];
map<string, double> name2val;
while (!in.eof()) {
in.getline(buf, 2000);
if (strlen(buf) == 0) continue;
if (buf[0] == '#') continue;
istringstream is(buf);
string fname;
double val;
is >> fname >> val;
map<string, double>::iterator i = name2val.find(fname);
assert(i == name2val.end()); // duplicate weight name
name2val[fname] = val;
}
assert(m_allWeights->size() == m_featureNames.size());
for (size_t i = 0; i < m_featureNames.size(); ++i) {
map<string, double>::iterator iter = name2val.find(m_featureNames[i]);
if (iter == name2val.end()) {
cerr << "No weight found found for feature: " << m_featureNames[i] << endl;
abort();
}
(*m_allWeights)[i] = iter->second;
}
}
std::ostream& operator<<(std::ostream& os, const ScoreIndexManager& sim)
{
for (size_t i = 0; i < sim.m_featureNames.size(); ++i) {
os << sim.m_featureNames[i] << endl;
}
os << endl;
return os;
}
const std::string &ScoreIndexManager::GetFeatureName(size_t fIndex) const
{
#ifndef NDEBUG
if (m_featureNames.size() <= fIndex) {
printf("%s: %i ScoreIndexManager::GetFeatureName(m_producers.size() = %zd, m_featureNames.size() = %zd, fIndex = %zd)\n", __FILE__, __LINE__, m_producers.size(), m_featureNames.size(), fIndex);
}
#endif
assert(m_featureNames.size() > fIndex);
return m_featureNames[fIndex];
}
//! get the index of a feature by name
size_t ScoreIndexManager::GetFeatureIndex(const std::string& fName) const
{
return m_featureIndexes.find(fName)->second;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006, Mathieu Champlon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met :
*
* . Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* . Neither the name of the copyright holders nor the names of the
* 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 THE COPYRIGHT
* OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef xeumeuleu_xistream_hpp
#define xeumeuleu_xistream_hpp
#include <xeumeuleu/streams/detail/input_context.hpp>
#include <xeumeuleu/streams/detail/input_base.hpp>
#include <xeumeuleu/streams/detail/optional_input.hpp>
#include <string>
#include <memory>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4355 )
#endif
namespace xml
{
class xostream;
// =============================================================================
/** @class xistream
@brief Xml input stream
*/
// Created: MAT 2006-01-04
// =============================================================================
class xistream : protected input_context
{
public:
//! @name Constructors/Destructor
//@{
explicit xistream( input_base& input )
: base_ ( input )
, input_ ( &input )
, optional_( input, *this )
{}
virtual ~xistream()
{}
//@}
//! @name Operations
//@{
void start( const std::string& tag )
{
input_->start( tag );
}
void end()
{
input_->end();
}
void read( std::string& value ) const { input_->read( value ); }
void read( bool& value ) const { input_->read( value ); }
void read( short& value ) const { input_->read( value ); }
void read( int& value ) const { input_->read( value ); }
void read( long& value ) const { input_->read( value ); }
void read( long long& value ) const { input_->read( value ); }
void read( float& value ) const { input_->read( value ); }
void read( double& value ) const { input_->read( value ); }
void read( long double& value ) const { input_->read( value ); }
void read( unsigned short& value ) const { input_->read( value ); }
void read( unsigned int& value ) const { input_->read( value ); }
void read( unsigned long& value ) const { input_->read( value ); }
void read( unsigned long long& value ) const { input_->read( value ); }
void read( xostream& xos ) const;
xistream& operator>>( std::string& value ) { input_->read( value ); return *this; }
xistream& operator>>( bool& value ) { input_->read( value ); return *this; }
xistream& operator>>( short& value ) { input_->read( value ); return *this; }
xistream& operator>>( int& value ) { input_->read( value ); return *this; }
xistream& operator>>( long& value ) { input_->read( value ); return *this; }
xistream& operator>>( long long& value ) { input_->read( value ); return *this; }
xistream& operator>>( float& value ) { input_->read( value ); return *this; }
xistream& operator>>( double& value ) { input_->read( value ); return *this; }
xistream& operator>>( long double& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned short& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned int& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned long& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned long long& value ) { input_->read( value ); return *this; }
xistream& operator>>( xostream& xos );
std::auto_ptr< input_base > branch( bool clone ) const
{
return input_->branch( clone );
}
void copy( output& destination ) const
{
input_->copy( destination );
}
void error( const std::string& message ) const
{
input_->error( message );
}
//@}
//! @name Accessors
//@{
bool has_child( const std::string& name ) const
{
return input_->has_child( name );
}
bool has_attribute( const std::string& name ) const
{
return input_->has_attribute( name );
}
bool has_content() const
{
return input_->has_content();
}
template< typename T > void attribute( const std::string& name, T& value ) const
{
input_->attribute( name, value );
}
void nodes( const visitor& v ) const
{
input_->nodes( v );
}
void attributes( const visitor& v ) const
{
input_->attributes( v );
}
//@}
//! @name Modifiers
//@{
void optional()
{
if( input_ == &base_ )
input_ = &optional_;
}
//@}
private:
//! @name Operations
//@{
virtual input_base& reset( input_base& input )
{
input_ = &input;
return *input_;
}
//@}
private:
//! @name Copy/Assignment
//@{
xistream( const xistream& ); //!< Copy constructor
xistream& operator=( const xistream& ); //!< Assignment operator
//@}
private:
//! @name Member data
//@{
input_base& base_;
input_base* input_;
optional_input optional_;
//@}
};
#ifdef _MSC_VER
# pragma warning( pop )
#endif
}
#include <xeumeuleu/streams/xostream.hpp>
namespace xml
{
inline void xistream::read( xostream& xos ) const
{
xos.write( *this );
}
inline xistream& xistream::operator>>( xostream& xos )
{
xos.write( *this );
return *this;
}
}
#endif // xeumeuleu_xistream_hpp
<commit_msg>Cleanup<commit_after>/*
* Copyright (c) 2006, Mathieu Champlon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met :
*
* . Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* . Neither the name of the copyright holders nor the names of the
* 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 THE COPYRIGHT
* OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef xeumeuleu_xistream_hpp
#define xeumeuleu_xistream_hpp
#include <xeumeuleu/streams/detail/input_context.hpp>
#include <xeumeuleu/streams/detail/input_base.hpp>
#include <xeumeuleu/streams/detail/optional_input.hpp>
#include <string>
#include <memory>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4355 )
#endif
namespace xml
{
class xostream;
// =============================================================================
/** @class xistream
@brief Xml input stream
*/
// Created: MAT 2006-01-04
// =============================================================================
class xistream : protected input_context
{
public:
//! @name Constructors/Destructor
//@{
explicit xistream( input_base& input )
: base_ ( input )
, input_ ( &input )
, optional_( input, *this )
{}
virtual ~xistream()
{}
//@}
//! @name Operations
//@{
void start( const std::string& tag )
{
input_->start( tag );
}
void end()
{
input_->end();
}
void read( std::string& value ) const { input_->read( value ); }
void read( bool& value ) const { input_->read( value ); }
void read( short& value ) const { input_->read( value ); }
void read( int& value ) const { input_->read( value ); }
void read( long& value ) const { input_->read( value ); }
void read( long long& value ) const { input_->read( value ); }
void read( float& value ) const { input_->read( value ); }
void read( double& value ) const { input_->read( value ); }
void read( long double& value ) const { input_->read( value ); }
void read( unsigned short& value ) const { input_->read( value ); }
void read( unsigned int& value ) const { input_->read( value ); }
void read( unsigned long& value ) const { input_->read( value ); }
void read( unsigned long long& value ) const { input_->read( value ); }
void read( xostream& xos ) const;
xistream& operator>>( std::string& value ) { input_->read( value ); return *this; }
xistream& operator>>( bool& value ) { input_->read( value ); return *this; }
xistream& operator>>( short& value ) { input_->read( value ); return *this; }
xistream& operator>>( int& value ) { input_->read( value ); return *this; }
xistream& operator>>( long& value ) { input_->read( value ); return *this; }
xistream& operator>>( long long& value ) { input_->read( value ); return *this; }
xistream& operator>>( float& value ) { input_->read( value ); return *this; }
xistream& operator>>( double& value ) { input_->read( value ); return *this; }
xistream& operator>>( long double& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned short& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned int& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned long& value ) { input_->read( value ); return *this; }
xistream& operator>>( unsigned long long& value ) { input_->read( value ); return *this; }
xistream& operator>>( xostream& xos );
std::auto_ptr< input_base > branch( bool clone ) const
{
return input_->branch( clone );
}
void copy( output& destination ) const
{
input_->copy( destination );
}
void error( const std::string& message ) const
{
input_->error( message );
}
//@}
//! @name Accessors
//@{
bool has_child( const std::string& name ) const
{
return input_->has_child( name );
}
bool has_attribute( const std::string& name ) const
{
return input_->has_attribute( name );
}
bool has_content() const
{
return input_->has_content();
}
template< typename T > void attribute( const std::string& name, T& value ) const
{
input_->attribute( name, value );
}
void nodes( const visitor& v ) const
{
input_->nodes( v );
}
void attributes( const visitor& v ) const
{
input_->attributes( v );
}
//@}
//! @name Modifiers
//@{
void optional()
{
if( input_ == &base_ )
input_ = &optional_;
}
//@}
private:
//! @name Operations
//@{
virtual input_base& reset( input_base& input )
{
input_ = &input;
return *input_;
}
//@}
private:
//! @name Copy/Assignment
//@{
xistream( const xistream& ); //!< Copy constructor
xistream& operator=( const xistream& ); //!< Assignment operator
//@}
private:
//! @name Member data
//@{
const input_base& base_;
input_base* input_;
optional_input optional_;
//@}
};
#ifdef _MSC_VER
# pragma warning( pop )
#endif
}
#include <xeumeuleu/streams/xostream.hpp>
namespace xml
{
inline void xistream::read( xostream& xos ) const
{
xos.write( *this );
}
inline xistream& xistream::operator>>( xostream& xos )
{
xos.write( *this );
return *this;
}
}
#endif // xeumeuleu_xistream_hpp
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <uvw.hpp>
TEST(Pipe, ReadWrite) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
#endif
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) {
FAIL();
});
server->once<uvw::ListenEvent>([](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
});
client->once<uvw::WriteEvent>([](const uvw::WriteEvent &, uvw::PipeHandle &handle) {
handle.close();
});
client->once<uvw::ConnectEvent>([](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
ASSERT_TRUE(handle.writable());
ASSERT_TRUE(handle.readable());
auto dataWrite = std::unique_ptr<char[]>(new char[2]{ 'x', 'y' });
handle.write(std::move(dataWrite), 2);
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
TEST(Pipe, SockPeer) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
const std::string peername{ "\\\\?\\pipe\\test.sock" };
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
const auto peernam = sockname;
#endif
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
server->once<uvw::ListenEvent>([&peername](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
ASSERT_EQ(handle.sock(), peername);
});
client->once<uvw::ConnectEvent>([&peername](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
ASSERT_EQ(handle.peer(), peername);
handle.close();
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
TEST(Pipe, Shutdown) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
#endif
auto data = std::unique_ptr<char[]>(new char[3]{ 'a', 'b', 'c' });
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
server->once<uvw::ListenEvent>([](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
});
client->once<uvw::ShutdownEvent>([](const uvw::ShutdownEvent &, uvw::PipeHandle &handle) {
handle.close();
});
client->once<uvw::ConnectEvent>([&data](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
handle.write(data.get(), 3);
handle.shutdown();
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
<commit_msg>fixed typo<commit_after>#include <gtest/gtest.h>
#include <uvw.hpp>
TEST(Pipe, ReadWrite) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
#endif
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) {
FAIL();
});
server->once<uvw::ListenEvent>([](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
});
client->once<uvw::WriteEvent>([](const uvw::WriteEvent &, uvw::PipeHandle &handle) {
handle.close();
});
client->once<uvw::ConnectEvent>([](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
ASSERT_TRUE(handle.writable());
ASSERT_TRUE(handle.readable());
auto dataWrite = std::unique_ptr<char[]>(new char[2]{ 'x', 'y' });
handle.write(std::move(dataWrite), 2);
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
TEST(Pipe, SockPeer) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
const std::string peername{ "\\\\?\\pipe\\test.sock" };
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
const auto peername = sockname;
#endif
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
server->once<uvw::ListenEvent>([&peername](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
ASSERT_EQ(handle.sock(), peername);
});
client->once<uvw::ConnectEvent>([&peername](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
ASSERT_EQ(handle.peer(), peername);
handle.close();
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
TEST(Pipe, Shutdown) {
#ifdef _MSC_VER
const std::string sockname{"\\\\.\\pipe\\test.sock"};
#else
const std::string sockname = std::string{TARGET_PIPE_DIR} + std::string{"/test.sock"};
#endif
auto data = std::unique_ptr<char[]>(new char[3]{ 'a', 'b', 'c' });
auto loop = uvw::Loop::getDefault();
auto server = loop->resource<uvw::PipeHandle>();
auto client = loop->resource<uvw::PipeHandle>();
server->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
client->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); });
server->once<uvw::ListenEvent>([](const uvw::ListenEvent &, uvw::PipeHandle &handle) {
std::shared_ptr<uvw::PipeHandle> socket = handle.loop().resource<uvw::PipeHandle>();
socket->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::PipeHandle &) { FAIL(); });
socket->on<uvw::CloseEvent>([&handle](const uvw::CloseEvent &, uvw::PipeHandle &) { handle.close(); });
socket->on<uvw::EndEvent>([](const uvw::EndEvent &, uvw::PipeHandle &sock) { sock.close(); });
handle.accept(*socket);
socket->read();
});
client->once<uvw::ShutdownEvent>([](const uvw::ShutdownEvent &, uvw::PipeHandle &handle) {
handle.close();
});
client->once<uvw::ConnectEvent>([&data](const uvw::ConnectEvent &, uvw::PipeHandle &handle) {
handle.write(data.get(), 3);
handle.shutdown();
});
server->bind(sockname);
server->listen();
client->connect(sockname);
loop->run();
}
<|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 "config.h"
#include "base/compiler_specific.h"
MSVC_PUSH_WARNING_LEVEL(0);
#include "DOMWindow.h"
#include "FloatRect.h"
#include "InspectorController.h"
#include "Page.h"
#include "Settings.h"
MSVC_POP_WARNING();
#undef LOG
#include "webkit/glue/inspector_client_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webview_impl.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
using namespace WebCore;
static const float kDefaultInspectorXPos = 10;
static const float kDefaultInspectorYPos = 50;
static const float kDefaultInspectorHeight = 640;
static const float kDefaultInspectorWidth = 480;
WebInspectorClient::WebInspectorClient(WebView* webView)
: inspected_web_view_(webView)
, inspector_web_view_(0) {
ASSERT(inspected_web_view_);
}
WebInspectorClient::~WebInspectorClient() {
}
void WebInspectorClient::inspectorDestroyed() {
delete this;
}
Page* WebInspectorClient::createPage() {
WebCore::Page* page;
if (inspector_web_view_ != NULL) {
page = static_cast<WebViewImpl*>(inspector_web_view_)->page();
ASSERT(page != NULL);
if (page != NULL)
return page;
}
WebViewDelegate* delegate = inspected_web_view_->GetDelegate();
if (!delegate)
return NULL;
inspector_web_view_ = delegate->CreateWebView(inspected_web_view_, true);
if (!inspector_web_view_)
return NULL;
GURL inspector_url(webkit_glue::GetInspectorURL());
scoped_ptr<WebRequest> request(WebRequest::Create(inspector_url));
WebViewImpl* inspector_web_view_impl =
static_cast<WebViewImpl*>(inspector_web_view_);
inspector_web_view_impl->main_frame()->LoadRequest(request.get());
page = inspector_web_view_impl->page();
page->chrome()->setToolbarsVisible(false);
page->chrome()->setStatusbarVisible(false);
page->chrome()->setScrollbarsVisible(false);
page->chrome()->setMenubarVisible(false);
page->chrome()->setResizable(true);
// Don't allow inspection of inspector.
page->settings()->setDeveloperExtrasEnabled(false);
page->settings()->setPrivateBrowsingEnabled(true);
page->settings()->setPluginsEnabled(false);
page->settings()->setJavaEnabled(false);
FloatRect windowRect = page->chrome()->windowRect();
FloatSize pageSize = page->chrome()->pageRect().size();
windowRect.setX(kDefaultInspectorXPos);
windowRect.setY(kDefaultInspectorYPos);
windowRect.setWidth(kDefaultInspectorHeight);
windowRect.setHeight(kDefaultInspectorWidth);
page->chrome()->setWindowRect(windowRect);
page->chrome()->show();
return page;
}
void WebInspectorClient::showWindow() {
WebViewImpl* impl = static_cast<WebViewImpl*>(inspected_web_view_.get());
InspectorController* inspector = impl->page()->inspectorController();
inspector->setWindowVisible(true);
// Notify the webview delegate of how many resources we're inspecting.
WebViewDelegate* d = impl->delegate();
DCHECK(d);
d->WebInspectorOpened(inspector->resources().size());
}
void WebInspectorClient::closeWindow() {
inspector_web_view_ = NULL;
WebViewImpl* impl = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(impl->GetMainFrame());
if (frame && frame->inspected_node())
hideHighlight();
if (impl->page())
impl->page()->inspectorController()->setWindowVisible(false);
}
bool WebInspectorClient::windowVisible() {
if (inspector_web_view_ != NULL) {
Page* page = static_cast<WebViewImpl*>(inspector_web_view_)->page();
ASSERT(page != NULL);
if (page != NULL)
return true;
}
return false;
}
void WebInspectorClient::attachWindow() {
// TODO(jackson): Implement this
}
void WebInspectorClient::detachWindow() {
// TODO(jackson): Implement this
}
void WebInspectorClient::setAttachedWindowHeight(unsigned int height) {
// TODO(dglazkov): Implement this
NOTIMPLEMENTED();
}
static void invalidateNodeBoundingRect(WebViewImpl* web_view) {
// TODO(ojan): http://b/1143996 Is it important to just invalidate the rect
// of the node region given that this is not on a critical codepath?
// In order to do so, we'd have to take scrolling into account.
gfx::Size size = web_view->size();
gfx::Rect damaged_rect(0, 0, size.width(), size.height());
web_view->GetDelegate()->DidInvalidateRect(web_view, damaged_rect);
}
void WebInspectorClient::highlight(Node* node) {
WebViewImpl* web_view = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(web_view->GetMainFrame());
if (frame->inspected_node())
hideHighlight();
invalidateNodeBoundingRect(web_view);
frame->selectNodeFromInspector(node);
}
void WebInspectorClient::hideHighlight() {
WebViewImpl* web_view = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(web_view->GetMainFrame());
invalidateNodeBoundingRect(web_view);
frame->selectNodeFromInspector(NULL);
}
void WebInspectorClient::inspectedURLChanged(const String& newURL) {
// TODO(jackson): Implement this
NOTIMPLEMENTED();
}
String WebInspectorClient::localizedStringsURL() {
NOTIMPLEMENTED();
return String();
}
void WebInspectorClient::populateSetting(
const String& key, InspectorController::Setting&) {
NOTIMPLEMENTED();
}
void WebInspectorClient::storeSetting(
const String& key, const InspectorController::Setting&) {
NOTIMPLEMENTED();
}
void WebInspectorClient::removeSetting(const String& key) {
NOTIMPLEMENTED();
}
<commit_msg>Remove a NOTIMPLEMENTED() that is obvious and cluttering our debug output.<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 "config.h"
#include "base/compiler_specific.h"
MSVC_PUSH_WARNING_LEVEL(0);
#include "DOMWindow.h"
#include "FloatRect.h"
#include "InspectorController.h"
#include "Page.h"
#include "Settings.h"
MSVC_POP_WARNING();
#undef LOG
#include "webkit/glue/inspector_client_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webview_impl.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
using namespace WebCore;
static const float kDefaultInspectorXPos = 10;
static const float kDefaultInspectorYPos = 50;
static const float kDefaultInspectorHeight = 640;
static const float kDefaultInspectorWidth = 480;
WebInspectorClient::WebInspectorClient(WebView* webView)
: inspected_web_view_(webView)
, inspector_web_view_(0) {
ASSERT(inspected_web_view_);
}
WebInspectorClient::~WebInspectorClient() {
}
void WebInspectorClient::inspectorDestroyed() {
delete this;
}
Page* WebInspectorClient::createPage() {
WebCore::Page* page;
if (inspector_web_view_ != NULL) {
page = static_cast<WebViewImpl*>(inspector_web_view_)->page();
ASSERT(page != NULL);
if (page != NULL)
return page;
}
WebViewDelegate* delegate = inspected_web_view_->GetDelegate();
if (!delegate)
return NULL;
inspector_web_view_ = delegate->CreateWebView(inspected_web_view_, true);
if (!inspector_web_view_)
return NULL;
GURL inspector_url(webkit_glue::GetInspectorURL());
scoped_ptr<WebRequest> request(WebRequest::Create(inspector_url));
WebViewImpl* inspector_web_view_impl =
static_cast<WebViewImpl*>(inspector_web_view_);
inspector_web_view_impl->main_frame()->LoadRequest(request.get());
page = inspector_web_view_impl->page();
page->chrome()->setToolbarsVisible(false);
page->chrome()->setStatusbarVisible(false);
page->chrome()->setScrollbarsVisible(false);
page->chrome()->setMenubarVisible(false);
page->chrome()->setResizable(true);
// Don't allow inspection of inspector.
page->settings()->setDeveloperExtrasEnabled(false);
page->settings()->setPrivateBrowsingEnabled(true);
page->settings()->setPluginsEnabled(false);
page->settings()->setJavaEnabled(false);
FloatRect windowRect = page->chrome()->windowRect();
FloatSize pageSize = page->chrome()->pageRect().size();
windowRect.setX(kDefaultInspectorXPos);
windowRect.setY(kDefaultInspectorYPos);
windowRect.setWidth(kDefaultInspectorHeight);
windowRect.setHeight(kDefaultInspectorWidth);
page->chrome()->setWindowRect(windowRect);
page->chrome()->show();
return page;
}
void WebInspectorClient::showWindow() {
WebViewImpl* impl = static_cast<WebViewImpl*>(inspected_web_view_.get());
InspectorController* inspector = impl->page()->inspectorController();
inspector->setWindowVisible(true);
// Notify the webview delegate of how many resources we're inspecting.
WebViewDelegate* d = impl->delegate();
DCHECK(d);
d->WebInspectorOpened(inspector->resources().size());
}
void WebInspectorClient::closeWindow() {
inspector_web_view_ = NULL;
WebViewImpl* impl = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(impl->GetMainFrame());
if (frame && frame->inspected_node())
hideHighlight();
if (impl->page())
impl->page()->inspectorController()->setWindowVisible(false);
}
bool WebInspectorClient::windowVisible() {
if (inspector_web_view_ != NULL) {
Page* page = static_cast<WebViewImpl*>(inspector_web_view_)->page();
ASSERT(page != NULL);
if (page != NULL)
return true;
}
return false;
}
void WebInspectorClient::attachWindow() {
// TODO(jackson): Implement this
}
void WebInspectorClient::detachWindow() {
// TODO(jackson): Implement this
}
void WebInspectorClient::setAttachedWindowHeight(unsigned int height) {
// TODO(dglazkov): Implement this
NOTIMPLEMENTED();
}
static void invalidateNodeBoundingRect(WebViewImpl* web_view) {
// TODO(ojan): http://b/1143996 Is it important to just invalidate the rect
// of the node region given that this is not on a critical codepath?
// In order to do so, we'd have to take scrolling into account.
gfx::Size size = web_view->size();
gfx::Rect damaged_rect(0, 0, size.width(), size.height());
web_view->GetDelegate()->DidInvalidateRect(web_view, damaged_rect);
}
void WebInspectorClient::highlight(Node* node) {
WebViewImpl* web_view = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(web_view->GetMainFrame());
if (frame->inspected_node())
hideHighlight();
invalidateNodeBoundingRect(web_view);
frame->selectNodeFromInspector(node);
}
void WebInspectorClient::hideHighlight() {
WebViewImpl* web_view = static_cast<WebViewImpl*>(inspected_web_view_.get());
WebFrameImpl* frame = static_cast<WebFrameImpl*>(web_view->GetMainFrame());
invalidateNodeBoundingRect(web_view);
frame->selectNodeFromInspector(NULL);
}
void WebInspectorClient::inspectedURLChanged(const String& newURL) {
// TODO(jackson): Implement this
}
String WebInspectorClient::localizedStringsURL() {
NOTIMPLEMENTED();
return String();
}
void WebInspectorClient::populateSetting(
const String& key, InspectorController::Setting&) {
NOTIMPLEMENTED();
}
void WebInspectorClient::storeSetting(
const String& key, const InspectorController::Setting&) {
NOTIMPLEMENTED();
}
void WebInspectorClient::removeSetting(const String& key) {
NOTIMPLEMENTED();
}
<|endoftext|> |
<commit_before>//===--- FileDistance.cpp - File contents container -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The FileDistance structure allows calculating the minimum distance to paths
// in a single tree.
// We simply walk up the path's ancestors until we find a node whose cost is
// known, and add the cost of walking back down. Initialization ensures this
// gives the correct path to the roots.
// We cache the results, so that the runtime is O(|A|), where A is the set of
// all distinct ancestors of visited paths.
//
// Example after initialization with /=2, /bar=0, DownCost = 1:
// / = 2
// /bar = 0
//
// After querying /foo/bar and /bar/foo:
// / = 2
// /bar = 0
// /bar/foo = 1
// /foo = 3
// /foo/bar = 4
//
// URIDistance creates FileDistance lazily for each URI scheme encountered. In
// practice this is a small constant factor.
//
//===-------------------------------------------------------------------------//
#include "FileDistance.h"
#include "Logger.h"
#include "llvm/ADT/STLExtras.h"
#include <queue>
#define DEBUG_TYPE "FileDistance"
namespace clang {
namespace clangd {
using namespace llvm;
// Convert a path into the canonical form.
// Canonical form is either "/", or "/segment" * N:
// C:\foo\bar --> /c:/foo/bar
// /foo/ --> /foo
// a/b/c --> /a/b/c
static SmallString<128> canonicalize(StringRef Path) {
SmallString<128> Result = Path.rtrim('/');
native(Result, sys::path::Style::posix);
if (Result.empty() || Result.front() != '/')
Result.insert(Result.begin(), '/');
return Result;
}
const unsigned FileDistance::kUnreachable;
FileDistance::FileDistance(StringMap<SourceParams> Sources,
const FileDistanceOptions &Opts)
: Opts(Opts) {
llvm::DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
// Compute the best distance following only up edges.
// Keep track of down edges, in case we can use them to improve on this.
for (const auto &S : Sources) {
auto Canonical = canonicalize(S.getKey());
LLVM_DEBUG(dbgs() << "Source " << Canonical << " = " << S.second.Cost
<< ", MaxUp=" << S.second.MaxUpTraversals << "\n");
// Walk up to ancestors of this source, assigning cost.
StringRef Rest = Canonical;
llvm::hash_code Hash = hash_value(Rest);
for (unsigned I = 0; !Rest.empty(); ++I) {
Rest = parent_path(Rest, sys::path::Style::posix);
auto NextHash = hash_value(Rest);
auto &Down = DownEdges[NextHash];
if (std::find(Down.begin(), Down.end(), Hash) == Down.end())
DownEdges[NextHash].push_back(Hash);
// We can't just break after MaxUpTraversals, must still set DownEdges.
if (I > S.getValue().MaxUpTraversals) {
if (Cache.find(Hash) != Cache.end())
break;
} else {
unsigned Cost = S.getValue().Cost + I * Opts.UpCost;
auto R = Cache.try_emplace(Hash, Cost);
if (!R.second) {
if (Cost < R.first->second) {
R.first->second = Cost;
} else {
// If we're not the best way to get to this path, stop assigning.
break;
}
}
}
Hash = NextHash;
}
}
// Now propagate scores parent -> child if that's an improvement.
// BFS ensures we propagate down chains (must visit parents before children).
std::queue<hash_code> Next;
for (auto Child : DownEdges.lookup(hash_value(llvm::StringRef(""))))
Next.push(Child);
while (!Next.empty()) {
auto ParentCost = Cache.lookup(Next.front());
for (auto Child : DownEdges.lookup(Next.front())) {
auto &ChildCost =
Cache.try_emplace(Child, kUnreachable).first->getSecond();
if (ParentCost + Opts.DownCost < ChildCost)
ChildCost = ParentCost + Opts.DownCost;
Next.push(Child);
}
Next.pop();
}
}
unsigned FileDistance::distance(StringRef Path) {
auto Canonical = canonicalize(Path);
unsigned Cost = kUnreachable;
SmallVector<hash_code, 16> Ancestors;
// Walk up ancestors until we find a path we know the distance for.
for (StringRef Rest = Canonical; !Rest.empty();
Rest = parent_path(Rest, sys::path::Style::posix)) {
auto Hash = hash_value(Rest);
auto It = Cache.find(Hash);
if (It != Cache.end()) {
Cost = It->second;
break;
}
Ancestors.push_back(Hash);
}
// Now we know the costs for (known node, queried node].
// Fill these in, walking down the directory tree.
for (hash_code Hash : reverse(Ancestors)) {
if (Cost != kUnreachable)
Cost += Opts.DownCost;
Cache.try_emplace(Hash, Cost);
}
LLVM_DEBUG(dbgs() << "distance(" << Path << ") = " << Cost << "\n");
return Cost;
}
unsigned URIDistance::distance(llvm::StringRef URI) {
auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::kUnreachable);
if (!R.second)
return R.first->getSecond();
if (auto U = clangd::URI::parse(URI)) {
LLVM_DEBUG(dbgs() << "distance(" << URI << ") = distance(" << U->body()
<< ")\n");
R.first->second = forScheme(U->scheme()).distance(U->body());
} else {
log("URIDistance::distance() of unparseable " + URI + ": " +
llvm::toString(U.takeError()));
}
return R.first->second;
}
FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
auto &Delegate = ByScheme[Scheme];
if (!Delegate) {
llvm::StringMap<SourceParams> SchemeSources;
for (const auto &Source : Sources) {
if (auto U = clangd::URI::create(Source.getKey(), Scheme))
SchemeSources.try_emplace(U->body(), Source.getValue());
else
consumeError(U.takeError());
}
LLVM_DEBUG(dbgs() << "FileDistance for scheme " << Scheme << ": "
<< SchemeSources.size() << "/" << Sources.size()
<< " sources\n");
Delegate.reset(new FileDistance(std::move(SchemeSources), Opts));
}
return *Delegate;
}
} // namespace clangd
} // namespace clang
<commit_msg>[clangd] FileDistance: missing constexpr<commit_after>//===--- FileDistance.cpp - File contents container -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The FileDistance structure allows calculating the minimum distance to paths
// in a single tree.
// We simply walk up the path's ancestors until we find a node whose cost is
// known, and add the cost of walking back down. Initialization ensures this
// gives the correct path to the roots.
// We cache the results, so that the runtime is O(|A|), where A is the set of
// all distinct ancestors of visited paths.
//
// Example after initialization with /=2, /bar=0, DownCost = 1:
// / = 2
// /bar = 0
//
// After querying /foo/bar and /bar/foo:
// / = 2
// /bar = 0
// /bar/foo = 1
// /foo = 3
// /foo/bar = 4
//
// URIDistance creates FileDistance lazily for each URI scheme encountered. In
// practice this is a small constant factor.
//
//===-------------------------------------------------------------------------//
#include "FileDistance.h"
#include "Logger.h"
#include "llvm/ADT/STLExtras.h"
#include <queue>
#define DEBUG_TYPE "FileDistance"
namespace clang {
namespace clangd {
using namespace llvm;
// Convert a path into the canonical form.
// Canonical form is either "/", or "/segment" * N:
// C:\foo\bar --> /c:/foo/bar
// /foo/ --> /foo
// a/b/c --> /a/b/c
static SmallString<128> canonicalize(StringRef Path) {
SmallString<128> Result = Path.rtrim('/');
native(Result, sys::path::Style::posix);
if (Result.empty() || Result.front() != '/')
Result.insert(Result.begin(), '/');
return Result;
}
constexpr const unsigned FileDistance::kUnreachable;
FileDistance::FileDistance(StringMap<SourceParams> Sources,
const FileDistanceOptions &Opts)
: Opts(Opts) {
llvm::DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
// Compute the best distance following only up edges.
// Keep track of down edges, in case we can use them to improve on this.
for (const auto &S : Sources) {
auto Canonical = canonicalize(S.getKey());
LLVM_DEBUG(dbgs() << "Source " << Canonical << " = " << S.second.Cost
<< ", MaxUp=" << S.second.MaxUpTraversals << "\n");
// Walk up to ancestors of this source, assigning cost.
StringRef Rest = Canonical;
llvm::hash_code Hash = hash_value(Rest);
for (unsigned I = 0; !Rest.empty(); ++I) {
Rest = parent_path(Rest, sys::path::Style::posix);
auto NextHash = hash_value(Rest);
auto &Down = DownEdges[NextHash];
if (std::find(Down.begin(), Down.end(), Hash) == Down.end())
DownEdges[NextHash].push_back(Hash);
// We can't just break after MaxUpTraversals, must still set DownEdges.
if (I > S.getValue().MaxUpTraversals) {
if (Cache.find(Hash) != Cache.end())
break;
} else {
unsigned Cost = S.getValue().Cost + I * Opts.UpCost;
auto R = Cache.try_emplace(Hash, Cost);
if (!R.second) {
if (Cost < R.first->second) {
R.first->second = Cost;
} else {
// If we're not the best way to get to this path, stop assigning.
break;
}
}
}
Hash = NextHash;
}
}
// Now propagate scores parent -> child if that's an improvement.
// BFS ensures we propagate down chains (must visit parents before children).
std::queue<hash_code> Next;
for (auto Child : DownEdges.lookup(hash_value(llvm::StringRef(""))))
Next.push(Child);
while (!Next.empty()) {
auto ParentCost = Cache.lookup(Next.front());
for (auto Child : DownEdges.lookup(Next.front())) {
auto &ChildCost =
Cache.try_emplace(Child, kUnreachable).first->getSecond();
if (ParentCost + Opts.DownCost < ChildCost)
ChildCost = ParentCost + Opts.DownCost;
Next.push(Child);
}
Next.pop();
}
}
unsigned FileDistance::distance(StringRef Path) {
auto Canonical = canonicalize(Path);
unsigned Cost = kUnreachable;
SmallVector<hash_code, 16> Ancestors;
// Walk up ancestors until we find a path we know the distance for.
for (StringRef Rest = Canonical; !Rest.empty();
Rest = parent_path(Rest, sys::path::Style::posix)) {
auto Hash = hash_value(Rest);
auto It = Cache.find(Hash);
if (It != Cache.end()) {
Cost = It->second;
break;
}
Ancestors.push_back(Hash);
}
// Now we know the costs for (known node, queried node].
// Fill these in, walking down the directory tree.
for (hash_code Hash : reverse(Ancestors)) {
if (Cost != kUnreachable)
Cost += Opts.DownCost;
Cache.try_emplace(Hash, Cost);
}
LLVM_DEBUG(dbgs() << "distance(" << Path << ") = " << Cost << "\n");
return Cost;
}
unsigned URIDistance::distance(llvm::StringRef URI) {
auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::kUnreachable);
if (!R.second)
return R.first->getSecond();
if (auto U = clangd::URI::parse(URI)) {
LLVM_DEBUG(dbgs() << "distance(" << URI << ") = distance(" << U->body()
<< ")\n");
R.first->second = forScheme(U->scheme()).distance(U->body());
} else {
log("URIDistance::distance() of unparseable " + URI + ": " +
llvm::toString(U.takeError()));
}
return R.first->second;
}
FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
auto &Delegate = ByScheme[Scheme];
if (!Delegate) {
llvm::StringMap<SourceParams> SchemeSources;
for (const auto &Source : Sources) {
if (auto U = clangd::URI::create(Source.getKey(), Scheme))
SchemeSources.try_emplace(U->body(), Source.getValue());
else
consumeError(U.takeError());
}
LLVM_DEBUG(dbgs() << "FileDistance for scheme " << Scheme << ": "
<< SchemeSources.size() << "/" << Sources.size()
<< " sources\n");
Delegate.reset(new FileDistance(std::move(SchemeSources), Opts));
}
return *Delegate;
}
} // namespace clangd
} // namespace clang
<|endoftext|> |
<commit_before>// Pass -DGHEAP_CPP11 to compiler for gheap_cpp11.hpp tests,
// otherwise gheap_cpp03.hpp will be tested.
#include "gheap.hpp"
#include "galgorithm.hpp"
#include "gpriority_queue.hpp"
#include <algorithm> // for *_heap(), copy(), move()
#include <cstdlib> // for rand(), srand()
#include <ctime> // for clock()
#include <iostream>
#include <memory> // for *_temporary_buffer()
#include <queue> // for priority_queue
#include <utility> // for pair, C++11 move()
#include <vector> // for vector
using namespace std;
namespace {
double get_time()
{
return (double)clock() / CLOCKS_PER_SEC;
}
void print_performance(const double t, const size_t m)
{
cout << ": " << (m / t / 1000) << " Kops/s" << endl;
}
template <class T>
void init_array(T *const a, const size_t n)
{
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
}
// Dummy wrapper for STL heap.
struct stl_heap
{
template <class RandomAccessIterator>
static void make_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::make_heap(first, last);
}
template <class RandomAccessIterator>
static void sort_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::sort_heap(first, last);
}
};
// Dummy wrapper for STL algorithms.
struct stl_algorithm
{
template <class RandomAccessIterator>
static void partial_sort(const RandomAccessIterator &first,
const RandomAccessIterator &middle, const RandomAccessIterator &last)
{
std::partial_sort(first, middle, last);
}
};
template <class T, class Heap>
void perftest_heapsort(T *const a, const size_t n, const size_t m)
{
cout << "perftest_heapsort(n=" << n << ", m=" << m << ")";
typedef galgorithm<Heap> algorithm;
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
algorithm::heapsort(a, a + n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class Algorithm>
void perftest_partial_sort(T *const a, const size_t n, const size_t m)
{
const size_t k = n / 4;
cout << "perftest_partial_sort(n=" << n << ", m=" << m << ", k=" << k << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
Algorithm::partial_sort(a, a + k, a + n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T>
void move_items(T *const src, const size_t n, T *const dst)
{
#ifdef GHEAP_CPP11
move(src, src + n, dst);
#else
copy(src, src + n, dst);
for (size_t i = 0; i < n; ++i) {
src[i].~T();
}
#endif
}
template <class T>
class nway_output_iterator
{
private:
T *_next;
public:
nway_output_iterator(T *const next) : _next(next) {}
nway_output_iterator &operator * () { return *this; }
#ifndef GHEAP_CPP11
void operator = (const T &src)
{
new (_next) T(src);
++_next;
}
#else
void operator = (T &&src)
{
new (_next) T(std::move(src));
++_next;
}
#endif
void operator ++ () { }
};
template <class T, class Heap>
void nway_mergesort(T *const a, const size_t n, T *const tmp_buf,
const size_t input_ranges_count)
{
assert(input_ranges_count > 0);
typedef galgorithm<Heap> algorithm;
const size_t critical_range_size = (1 << 18) - 1;
if (n <= critical_range_size) {
algorithm::heapsort(a, a + n);
return;
}
const size_t range_size = n / input_ranges_count;
const size_t last_full_range = n - n % range_size;
vector<pair<T *, T *> > input_ranges;
for (size_t i = 0; i < last_full_range; i += range_size) {
nway_mergesort<T, Heap>(a + i, range_size, tmp_buf, input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + i, a + (i + range_size)));
}
if (n > last_full_range) {
nway_mergesort<T, Heap>(a + last_full_range, n - last_full_range, tmp_buf,
input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + last_full_range, a + n));
}
algorithm::nway_merge(input_ranges.begin(), input_ranges.end(),
nway_output_iterator<T>(tmp_buf));
move_items(tmp_buf, n, a);
}
template <class T, class Heap>
void perftest_nway_mergesort(T *const a, const size_t n, const size_t m)
{
const size_t input_ranges_count = 15;
cout << "perftest_nway_mergesort(n=" << n << ", m=" << m <<
", input_ranges_count=" << input_ranges_count << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
const pair<T *, ptrdiff_t> tmp_buf = get_temporary_buffer<T>(n);
nway_mergesort<T, Heap>(a, n, tmp_buf.first, input_ranges_count);
return_temporary_buffer(tmp_buf.first);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class PriorityQueue>
void perftest_priority_queue(T *const a, const size_t n, const size_t m)
{
cout << "perftest_priority_queue(n=" << n << ", m=" << m << ")";
init_array(a, n);
PriorityQueue q(a, a + n);
double start = get_time();
for (size_t i = 0; i < m; ++i) {
q.pop();
q.push(rand());
}
double end = get_time();
print_performance(end - start, m);
}
template <class T, class Heap>
void perftest_gheap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, Heap>(a, n, max_n);
perftest_partial_sort<T, galgorithm<Heap> >(a, n, max_n);
perftest_nway_mergesort<T, Heap>(a, n, max_n);
perftest_priority_queue<T, gpriority_queue<Heap, T> >(a, n, max_n);
n >>= 1;
}
}
template <class T>
void perftest_stl_heap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, stl_heap>(a, n, max_n);
perftest_partial_sort<T, stl_algorithm>(a, n, max_n);
// stl heap doesn't provide nway_merge(),
// so skip perftest_nway_mergesort().
perftest_priority_queue<T, priority_queue<T> >(a, n, max_n);
n >>= 1;
}
}
} // end of anonymous namespace.
int main(void)
{
static const size_t MAX_N = 32 * 1024 * 1024;
static const size_t FANOUT = 2;
static const size_t PAGE_CHUNKS = 1;
typedef size_t T;
cout << "fanout=" << FANOUT << ", page_chunks=" << PAGE_CHUNKS <<
", max_n=" << MAX_N << endl;
srand(0);
T *const a = new T[MAX_N];
cout << "* STL heap" << endl;
perftest_stl_heap(a, MAX_N);
cout << "* gheap" << endl;
typedef gheap<FANOUT, PAGE_CHUNKS> heap;
perftest_gheap<T, heap>(a, MAX_N);
delete[] a;
}
<commit_msg>added missing less_comparer parameter for make_heap and sort_heap in stl_heap<commit_after>// Pass -DGHEAP_CPP11 to compiler for gheap_cpp11.hpp tests,
// otherwise gheap_cpp03.hpp will be tested.
#include "gheap.hpp"
#include "galgorithm.hpp"
#include "gpriority_queue.hpp"
#include <algorithm> // for *_heap(), copy(), move()
#include <cstdlib> // for rand(), srand()
#include <ctime> // for clock()
#include <iostream>
#include <memory> // for *_temporary_buffer()
#include <queue> // for priority_queue
#include <utility> // for pair, C++11 move()
#include <vector> // for vector
using namespace std;
namespace {
double get_time()
{
return (double)clock() / CLOCKS_PER_SEC;
}
void print_performance(const double t, const size_t m)
{
cout << ": " << (m / t / 1000) << " Kops/s" << endl;
}
template <class T>
void init_array(T *const a, const size_t n)
{
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
}
// Dummy wrapper for STL heap.
struct stl_heap
{
template <class RandomAccessIterator, class LessComparer>
static void make_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last, const LessComparer &less_comparer)
{
std::make_heap(first, last, less_comparer);
}
template <class RandomAccessIterator, class LessComparer>
static void sort_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last, const LessComparer &less_comparer)
{
std::sort_heap(first, last, less_comparer);
}
};
// Dummy wrapper for STL algorithms.
struct stl_algorithm
{
template <class RandomAccessIterator>
static void partial_sort(const RandomAccessIterator &first,
const RandomAccessIterator &middle, const RandomAccessIterator &last)
{
std::partial_sort(first, middle, last);
}
};
template <class T, class Heap>
void perftest_heapsort(T *const a, const size_t n, const size_t m)
{
cout << "perftest_heapsort(n=" << n << ", m=" << m << ")";
typedef galgorithm<Heap> algorithm;
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
algorithm::heapsort(a, a + n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class Algorithm>
void perftest_partial_sort(T *const a, const size_t n, const size_t m)
{
const size_t k = n / 4;
cout << "perftest_partial_sort(n=" << n << ", m=" << m << ", k=" << k << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
Algorithm::partial_sort(a, a + k, a + n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T>
void move_items(T *const src, const size_t n, T *const dst)
{
#ifdef GHEAP_CPP11
move(src, src + n, dst);
#else
copy(src, src + n, dst);
for (size_t i = 0; i < n; ++i) {
src[i].~T();
}
#endif
}
template <class T>
class nway_output_iterator
{
private:
T *_next;
public:
nway_output_iterator(T *const next) : _next(next) {}
nway_output_iterator &operator * () { return *this; }
#ifndef GHEAP_CPP11
void operator = (const T &src)
{
new (_next) T(src);
++_next;
}
#else
void operator = (T &&src)
{
new (_next) T(std::move(src));
++_next;
}
#endif
void operator ++ () { }
};
template <class T, class Heap>
void nway_mergesort(T *const a, const size_t n, T *const tmp_buf,
const size_t input_ranges_count)
{
assert(input_ranges_count > 0);
typedef galgorithm<Heap> algorithm;
const size_t critical_range_size = (1 << 18) - 1;
if (n <= critical_range_size) {
algorithm::heapsort(a, a + n);
return;
}
const size_t range_size = n / input_ranges_count;
const size_t last_full_range = n - n % range_size;
vector<pair<T *, T *> > input_ranges;
for (size_t i = 0; i < last_full_range; i += range_size) {
nway_mergesort<T, Heap>(a + i, range_size, tmp_buf, input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + i, a + (i + range_size)));
}
if (n > last_full_range) {
nway_mergesort<T, Heap>(a + last_full_range, n - last_full_range, tmp_buf,
input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + last_full_range, a + n));
}
algorithm::nway_merge(input_ranges.begin(), input_ranges.end(),
nway_output_iterator<T>(tmp_buf));
move_items(tmp_buf, n, a);
}
template <class T, class Heap>
void perftest_nway_mergesort(T *const a, const size_t n, const size_t m)
{
const size_t input_ranges_count = 15;
cout << "perftest_nway_mergesort(n=" << n << ", m=" << m <<
", input_ranges_count=" << input_ranges_count << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
const pair<T *, ptrdiff_t> tmp_buf = get_temporary_buffer<T>(n);
nway_mergesort<T, Heap>(a, n, tmp_buf.first, input_ranges_count);
return_temporary_buffer(tmp_buf.first);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class PriorityQueue>
void perftest_priority_queue(T *const a, const size_t n, const size_t m)
{
cout << "perftest_priority_queue(n=" << n << ", m=" << m << ")";
init_array(a, n);
PriorityQueue q(a, a + n);
double start = get_time();
for (size_t i = 0; i < m; ++i) {
q.pop();
q.push(rand());
}
double end = get_time();
print_performance(end - start, m);
}
template <class T, class Heap>
void perftest_gheap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, Heap>(a, n, max_n);
perftest_partial_sort<T, galgorithm<Heap> >(a, n, max_n);
perftest_nway_mergesort<T, Heap>(a, n, max_n);
perftest_priority_queue<T, gpriority_queue<Heap, T> >(a, n, max_n);
n >>= 1;
}
}
template <class T>
void perftest_stl_heap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, stl_heap>(a, n, max_n);
perftest_partial_sort<T, stl_algorithm>(a, n, max_n);
// stl heap doesn't provide nway_merge(),
// so skip perftest_nway_mergesort().
perftest_priority_queue<T, priority_queue<T> >(a, n, max_n);
n >>= 1;
}
}
} // end of anonymous namespace.
int main(void)
{
static const size_t MAX_N = 32 * 1024 * 1024;
static const size_t FANOUT = 2;
static const size_t PAGE_CHUNKS = 1;
typedef size_t T;
cout << "fanout=" << FANOUT << ", page_chunks=" << PAGE_CHUNKS <<
", max_n=" << MAX_N << endl;
srand(0);
T *const a = new T[MAX_N];
cout << "* STL heap" << endl;
perftest_stl_heap(a, MAX_N);
cout << "* gheap" << endl;
typedef gheap<FANOUT, PAGE_CHUNKS> heap;
perftest_gheap<T, heap>(a, MAX_N);
delete[] a;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2020-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "flat_mutation_reader.hh"
#include "mutation_reader.hh"
#include "seastar/core/coroutine.hh"
namespace mutation_writer {
class bucket_writer {
schema_ptr _schema;
queue_reader_handle _handle;
future<> _consume_fut;
private:
bucket_writer(schema_ptr schema, std::pair<flat_mutation_reader, queue_reader_handle> queue_reader, reader_consumer& consumer);
public:
bucket_writer(schema_ptr schema, reader_permit permit, reader_consumer& consumer);
future<> consume(mutation_fragment mf);
void consume_end_of_stream();
void abort(std::exception_ptr ep) noexcept;
future<> close() noexcept;
};
template <typename Writer>
requires MutationFragmentConsumer<Writer, future<>>
future<> feed_writer(flat_mutation_reader&& rd_ref, Writer wr) {
// Only move in reader if stack was successfully allocated, so caller can close reader otherwise.
auto rd = std::move(rd_ref);
std::exception_ptr ex;
try {
while (!rd.is_end_of_stream() || !rd.is_buffer_empty()) {
co_await rd.fill_buffer();
while (!rd.is_buffer_empty()) {
co_await rd.pop_mutation_fragment().consume(wr);
}
}
} catch (...) {
ex = std::current_exception();
}
co_await rd.close();
try {
if (ex) {
wr.abort(ex);
} else {
wr.consume_end_of_stream();
}
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
try {
co_await wr.close();
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
if (ex) {
std::rethrow_exception(ex);
}
}
}
<commit_msg>mutation_writer: add v2 clone of feed_writer and bucket_writer<commit_after>/*
* Copyright (C) 2020-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "flat_mutation_reader.hh"
#include "mutation_reader.hh"
#include "seastar/core/coroutine.hh"
namespace mutation_writer {
class bucket_writer {
schema_ptr _schema;
queue_reader_handle _handle;
future<> _consume_fut;
private:
bucket_writer(schema_ptr schema, std::pair<flat_mutation_reader, queue_reader_handle> queue_reader, reader_consumer& consumer);
public:
bucket_writer(schema_ptr schema, reader_permit permit, reader_consumer& consumer);
future<> consume(mutation_fragment mf);
void consume_end_of_stream();
void abort(std::exception_ptr ep) noexcept;
future<> close() noexcept;
};
template <typename Writer>
requires MutationFragmentConsumer<Writer, future<>>
future<> feed_writer(flat_mutation_reader&& rd_ref, Writer wr) {
// Only move in reader if stack was successfully allocated, so caller can close reader otherwise.
auto rd = std::move(rd_ref);
std::exception_ptr ex;
try {
while (!rd.is_end_of_stream() || !rd.is_buffer_empty()) {
co_await rd.fill_buffer();
while (!rd.is_buffer_empty()) {
co_await rd.pop_mutation_fragment().consume(wr);
}
}
} catch (...) {
ex = std::current_exception();
}
co_await rd.close();
try {
if (ex) {
wr.abort(ex);
} else {
wr.consume_end_of_stream();
}
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
try {
co_await wr.close();
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
if (ex) {
std::rethrow_exception(ex);
}
}
class bucket_writer_v2 {
schema_ptr _schema;
queue_reader_handle_v2 _handle;
future<> _consume_fut;
private:
bucket_writer_v2(schema_ptr schema, std::pair<flat_mutation_reader_v2, queue_reader_handle_v2> queue_reader_v2, reader_consumer_v2& consumer);
public:
bucket_writer_v2(schema_ptr schema, reader_permit permit, reader_consumer_v2& consumer);
future<> consume(mutation_fragment_v2 mf);
void consume_end_of_stream();
void abort(std::exception_ptr ep) noexcept;
future<> close() noexcept;
};
template <typename Writer>
requires MutationFragmentConsumerV2<Writer, future<>>
future<> feed_writer(flat_mutation_reader_v2&& rd_ref, Writer wr) {
// Only move in reader if stack was successfully allocated, so caller can close reader otherwise.
auto rd = std::move(rd_ref);
std::exception_ptr ex;
try {
while (!rd.is_end_of_stream() || !rd.is_buffer_empty()) {
co_await rd.fill_buffer();
while (!rd.is_buffer_empty()) {
co_await rd.pop_mutation_fragment().consume(wr);
}
}
} catch (...) {
ex = std::current_exception();
}
co_await rd.close();
try {
if (ex) {
wr.abort(ex);
} else {
wr.consume_end_of_stream();
}
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
try {
co_await wr.close();
} catch (...) {
if (!ex) {
ex = std::current_exception();
}
}
if (ex) {
std::rethrow_exception(ex);
}
}
}
<|endoftext|> |
<commit_before><commit_msg>before cleaning up old commented lines<commit_after><|endoftext|> |
<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "block_map.h"
#include <algorithm>
#include <cstdint>
#include "third_party/gemmlowp/profiling/instrumentation.h"
#include "check_macros.h"
#include "opt_set.h"
#include "size_util.h"
namespace ruy {
void GetBlockByIndex(const BlockMap& block_map, int index,
SidePair<int>* block) {
gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
const std::uint32_t index_u32 = index;
const std::uint32_t num_blocks_per_local_curve =
1u << (2 * block_map.num_blocks_base_log2);
const std::uint32_t n1 = index_u32 & (num_blocks_per_local_curve - 1);
SidePair<int> local_pos;
if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
local_pos[Side::kLhs] = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
local_pos[Side::kRhs] = n1 >> block_map.num_blocks_base_log2;
} else {
// Decode fractal z-order
const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
((n1 & 0x22222222u) << 1);
const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
((n2 & 0x0c0c0c0cu) << 2);
const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
((n4 & 0x00f000f0u) << 4);
const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
((n8 & 0x0000ff00u) << 8);
local_pos[Side::kLhs] = n16 & 0xffff;
local_pos[Side::kRhs] = n16 >> 16;
if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
// Change fractal z-order to u-order
local_pos[Side::kLhs] ^= local_pos[Side::kRhs];
}
}
const std::uint32_t rectangular_index =
index_u32 >> 2 * block_map.num_blocks_base_log2;
for (Side side : {Side::kLhs, Side::kRhs}) {
const std::uint32_t mask = (1u << block_map.rectangularness_log2[side]) - 1;
const int rectangular_offset = (rectangular_index & mask)
<< block_map.num_blocks_base_log2;
(*block)[side] = local_pos[side] + rectangular_offset;
}
}
namespace {
int floor_log2_quotient(int num, int denom) {
if (num <= denom) {
return 0;
}
int log2_quotient = floor_log2(num) - ceil_log2(denom);
if ((denom << (log2_quotient + 1)) <= num) {
log2_quotient++;
}
return log2_quotient;
}
} // namespace
void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
int cache_friendly_traversal_threshold, BlockMap* block_map) {
gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
RUY_DCHECK_GE(rows, kernel_rows);
RUY_DCHECK_GE(cols, kernel_cols);
RUY_DCHECK_EQ(rows % kernel_rows, 0);
RUY_DCHECK_EQ(cols % kernel_cols, 0);
block_map->traversal_order = BlockMapTraversalOrder::kLinear;
if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
(rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
cache_friendly_traversal_threshold) {
block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
? BlockMapTraversalOrder::kFractalU
: BlockMapTraversalOrder::kFractalZ;
}
// See the comment on BlockMap in block_map.h.
// The destination matrix shape (rows x cols) is to be subdivided into a
// square (N x N) grid of blocks, whose shapes must be multiples of the
// kernel block shape (kernel_rows x kernel_cols).
// Inside each of these N*N blocks, we may have one further level of
// subdivision either along rows or along cols but not both, to handle
// better the highly rectangular cases. That is what we call
// 'rectangularness'. This extra level of subdivision is into
// (1 << rows_rectangularness_log2) blocks along rows dimension, or into
// (1 << cols_rectangularness_log2) blocks along cols dimension.
int rows_rectangularness_log2 = 0;
int cols_rectangularness_log2 = 0;
// In order to compute these rectangularness values, we need to divide
// the destination matrix's aspect ratio,
// rows / cols
// by the kernel block's aspect ratio,
// kernel_block_rows / kernel_block_cols.
// The quotient of these two quotients simplifies to
// (rows * kernel_cols) / (cols * kernel_rows)
// Whence the introduction of the following products:
const int rows_times_kernel_cols = rows * kernel_cols;
const int cols_times_kernel_rows = cols * kernel_rows;
if (rows_times_kernel_cols > cols_times_kernel_rows) {
rows_rectangularness_log2 =
floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);
// Sanity check that we did not over-estimate rows_rectangularness_log2.
RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,
cols_times_kernel_rows);
} else if (cols_times_kernel_rows > rows_times_kernel_cols) {
cols_rectangularness_log2 =
floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);
// Sanity check that we did not over-estimate cols_rectangularness_log2.
RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,
rows_times_kernel_cols);
}
RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);
const int size = std::min(rows, cols);
const int size_floor_log2 = floor_log2(size);
const int depth_ceil_log2 = ceil_log2(depth);
const int kernel_width_log2 = pot_log2(std::max(kernel_cols, kernel_rows));
// l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
// or the number of columns of RHS in a matrix multiplication that we expect,
// to fit in L1 cache.
//
// This initial rationale is not necessarily still relevant. The logic below
// was determined empirically, not in a principled way.
int l1_size_log2;
if (size_floor_log2 <= 3) {
l1_size_log2 = size_floor_log2;
} else if (size_floor_log2 <= 6) {
l1_size_log2 = 4;
} else {
l1_size_log2 = 5;
}
// The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
// Once again this only has a distant memory of being originally motivated
// by such clear principles linking this logic to cache sizes.
l1_size_log2 = std::min(
l1_size_log2, 15 - depth_ceil_log2 -
pot_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
l1_size_log2 = std::min(l1_size_log2, size_floor_log2);
int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
RUY_DCHECK_GE(num_blocks_base_log2, 0);
const int num_blocks_of_rows_log2 =
num_blocks_base_log2 + rows_rectangularness_log2;
const int num_blocks_of_cols_log2 =
num_blocks_base_log2 + cols_rectangularness_log2;
const int smallr =
round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);
const int smallc =
round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);
const int missr =
round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) >>
pot_log2(kernel_rows);
const int missc =
round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) >>
pot_log2(kernel_cols);
block_map->dims[Side::kLhs] = rows;
block_map->dims[Side::kRhs] = cols;
block_map->kernel_dims[Side::kLhs] = kernel_rows;
block_map->kernel_dims[Side::kRhs] = kernel_cols;
block_map->num_blocks_base_log2 = num_blocks_base_log2;
block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
block_map->small_block_dims[Side::kLhs] = smallr;
block_map->small_block_dims[Side::kRhs] = smallc;
block_map->large_blocks[Side::kLhs] = missr;
block_map->large_blocks[Side::kRhs] = missc;
}
void GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,
int* start, int* end) {
gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
*start = block * block_map.small_block_dims[side] +
std::min(block, block_map.large_blocks[side]) *
block_map.kernel_dims[side];
*end =
*start + block_map.small_block_dims[side] +
(block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);
RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
RUY_DCHECK_LE(*end, block_map.dims[side]);
RUY_DCHECK_LT(*start, *end);
RUY_DCHECK_GE(*start, 0);
}
void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
SidePair<int>* start, SidePair<int>* end) {
for (Side side : {Side::kLhs, Side::kRhs}) {
GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],
&(*end)[side]);
}
}
} // namespace ruy
<commit_msg>Rewrite the 'rectangularness' computation. Since 'rectangularness' is now the largest-scale subdivision, it should not (anymore) have anything to do with the kernel layout. Rectangularness is now nothing but the shape 'aspect ratio', (rows/columns), of the destination matrix. This keeps concepts simpler and more orthogonal -- rectangularness is a property of the destination matrix alone, orthogonal to kernel. This will allow writing better, simpler block_map logic.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "block_map.h"
#include <algorithm>
#include <cstdint>
#include "third_party/gemmlowp/profiling/instrumentation.h"
#include "check_macros.h"
#include "opt_set.h"
#include "size_util.h"
namespace ruy {
void GetBlockByIndex(const BlockMap& block_map, int index,
SidePair<int>* block) {
gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
const std::uint32_t index_u32 = index;
const std::uint32_t num_blocks_per_local_curve =
1u << (2 * block_map.num_blocks_base_log2);
const std::uint32_t n1 = index_u32 & (num_blocks_per_local_curve - 1);
SidePair<int> local_pos;
if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
local_pos[Side::kLhs] = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
local_pos[Side::kRhs] = n1 >> block_map.num_blocks_base_log2;
} else {
// Decode fractal z-order
const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
((n1 & 0x22222222u) << 1);
const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
((n2 & 0x0c0c0c0cu) << 2);
const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
((n4 & 0x00f000f0u) << 4);
const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
((n8 & 0x0000ff00u) << 8);
local_pos[Side::kLhs] = n16 & 0xffff;
local_pos[Side::kRhs] = n16 >> 16;
if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
// Change fractal z-order to u-order
local_pos[Side::kLhs] ^= local_pos[Side::kRhs];
}
}
const std::uint32_t rectangular_index =
index_u32 >> 2 * block_map.num_blocks_base_log2;
for (Side side : {Side::kLhs, Side::kRhs}) {
const std::uint32_t mask = (1u << block_map.rectangularness_log2[side]) - 1;
const int rectangular_offset = (rectangular_index & mask)
<< block_map.num_blocks_base_log2;
(*block)[side] = local_pos[side] + rectangular_offset;
}
}
namespace {
int floor_log2_quotient(int num, int denom) {
if (num <= denom) {
return 0;
}
int log2_quotient = floor_log2(num) - ceil_log2(denom);
if ((denom << (log2_quotient + 1)) <= num) {
log2_quotient++;
}
return log2_quotient;
}
} // namespace
void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
int cache_friendly_traversal_threshold, BlockMap* block_map) {
gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
RUY_DCHECK_GE(rows, kernel_rows);
RUY_DCHECK_GE(cols, kernel_cols);
RUY_DCHECK_EQ(rows % kernel_rows, 0);
RUY_DCHECK_EQ(cols % kernel_cols, 0);
block_map->traversal_order = BlockMapTraversalOrder::kLinear;
if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
(rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
cache_friendly_traversal_threshold) {
block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
? BlockMapTraversalOrder::kFractalU
: BlockMapTraversalOrder::kFractalZ;
}
int rows_rectangularness_log2 = 0;
int cols_rectangularness_log2 = 0;
if (rows > cols) {
rows_rectangularness_log2 =
std::min(floor_log2_quotient(rows, cols),
floor_log2(rows) - pot_log2(kernel_rows));
// Sanity check that we did not over-estimate rows_rectangularness_log2.
RUY_DCHECK_GE(rows >> rows_rectangularness_log2, cols);
} else if (cols > rows) {
cols_rectangularness_log2 =
std::min(floor_log2_quotient(cols, rows),
floor_log2(cols) - pot_log2(kernel_cols));
// Sanity check that we did not over-estimate cols_rectangularness_log2.
RUY_DCHECK_GE(cols >> cols_rectangularness_log2, rows);
}
RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);
const int size = std::min(rows, cols);
const int size_floor_log2 = floor_log2(size);
const int depth_ceil_log2 = ceil_log2(depth);
const int kernel_width_log2 = pot_log2(std::max(kernel_cols, kernel_rows));
// l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
// or the number of columns of RHS in a matrix multiplication that we expect,
// to fit in L1 cache.
//
// This initial rationale is not necessarily still relevant. The logic below
// was determined empirically, not in a principled way.
int l1_size_log2;
if (size_floor_log2 <= 3) {
l1_size_log2 = size_floor_log2;
} else if (size_floor_log2 <= 6) {
l1_size_log2 = 4;
} else {
l1_size_log2 = 5;
}
// The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
// Once again this only has a distant memory of being originally motivated
// by such clear principles linking this logic to cache sizes.
l1_size_log2 = std::min(
l1_size_log2, 15 - depth_ceil_log2 -
pot_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
l1_size_log2 = std::min(l1_size_log2, size_floor_log2);
int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
RUY_DCHECK_GE(num_blocks_base_log2, 0);
const int num_blocks_of_rows_log2 =
num_blocks_base_log2 + rows_rectangularness_log2;
const int num_blocks_of_cols_log2 =
num_blocks_base_log2 + cols_rectangularness_log2;
const int smallr =
round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);
const int smallc =
round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);
const int missr =
round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) >>
pot_log2(kernel_rows);
const int missc =
round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) >>
pot_log2(kernel_cols);
block_map->dims[Side::kLhs] = rows;
block_map->dims[Side::kRhs] = cols;
block_map->kernel_dims[Side::kLhs] = kernel_rows;
block_map->kernel_dims[Side::kRhs] = kernel_cols;
block_map->num_blocks_base_log2 = num_blocks_base_log2;
block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
block_map->small_block_dims[Side::kLhs] = smallr;
block_map->small_block_dims[Side::kRhs] = smallc;
block_map->large_blocks[Side::kLhs] = missr;
block_map->large_blocks[Side::kRhs] = missc;
}
void GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,
int* start, int* end) {
gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
*start = block * block_map.small_block_dims[side] +
std::min(block, block_map.large_blocks[side]) *
block_map.kernel_dims[side];
*end =
*start + block_map.small_block_dims[side] +
(block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);
RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
RUY_DCHECK_LE(*end, block_map.dims[side]);
RUY_DCHECK_LT(*start, *end);
RUY_DCHECK_GE(*start, 0);
}
void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
SidePair<int>* start, SidePair<int>* end) {
for (Side side : {Side::kLhs, Side::kRhs}) {
GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],
&(*end)[side]);
}
}
} // namespace ruy
<|endoftext|> |
<commit_before>/*
* lanczosSO.hpp
*
* Created on: Mar 3, 2015
* Author: hugo
*/
#ifndef ALGORITHM_LANCZOSSO_HPP_
#define ALGORITHM_LANCZOSSO_HPP_
#include <cmath>
#include <sstream>
#include <string>
#include "../core/eigenwrapper.hpp"
#include "../core/matrix.hpp"
#include "../core/primitivematrix.hpp"
#include "../core/primitivevector.hpp"
#include "../core/type.hpp"
#include "../core/util.hpp"
#include "../Eigen/Dense"
#include "../log/easylogging++.h"
using namespace std;
namespace mflash{
class LanczosSO{
PrimitiveMatrix<double, EmptyType> *matrix;
int iterations;
int k;
mat build_tridiagonal_matrix(int m, double alpha [], double beta[]);
public:
LanczosSO(PrimitiveMatrix<double, EmptyType> &matrix, int iterations, int k);
void create_ritz_vectors(PrimitiveVector<double> *vectors[], mat &q);
void run();
};
LanczosSO::LanczosSO(PrimitiveMatrix<double, EmptyType> &matrix, int iterations, int k){
this->matrix = &matrix;
this->iterations = iterations;
this->k = k;
}
void LanczosSO::run(){
string path = mflash::get_parent_directory(matrix->get_file());
cout<<path<<endl;
string v_file = path + "v.bin";
string eigens_file = path + "eigen_values.bin";
//string v_tmp = path + FILE_SEPARATOR + "tmp.bin";
string r_file = path + "r.bin";
const int64 block_size = matrix->get_elements_by_block();
const int64 node_count = matrix->size();
double epsilon = sqrt(1E-18);
double *beta = new double[iterations];
double *alpha = new double[iterations];
//orthogonal vectors v
PrimitiveVector<double> *vectors[iterations];// = new PrimitiveVector<double>*[iterations];
PrimitiveVector<double> v (v_file, node_count, block_size);
PrimitiveVector<double> r (r_file, node_count, block_size);
LOG (INFO) << "1: initial values";
vectors[0] = new PrimitiveVector<double> ( path + "v0", node_count, block_size );
vectors[0]->fill_random();
vectors[0]->multiply(((double)1/vectors[0]->pnorm(2)));
for (int i = 0; i < iterations; i++){
LOG (INFO) << "3: Find a new basis vector";
matrix->multiply( *(vectors[i]), v);
LOG (INFO) << "4:";
alpha[i] = vectors[i]->transpose().multiply(v);
LOG (INFO) << "5: v = v - beta[i-1]V[i-1] - alpha[i]V[i]";
if(i>0){
v.linear_combination(3, new double[3]{1, -1*beta[i-1], -1*alpha[i]}, new PrimitiveVector<double>*[3]{&v, vectors[i-1], vectors[i]});
}else{
v.linear_combination(2, new double[2]{1, -1*alpha[i]}, new PrimitiveVector<double>*[2]{&v, vectors[i]});
}
LOG (INFO) << "6: beta[i] = ||v||";
beta[i] = v.pnorm(2);
LOG (INFO) << "7: build tri-diagonal matrix from alpha and beta";
mat ti = build_tridiagonal_matrix(i+1, alpha, beta);
LOG (INFO) << "8: ";
Eigen::SelfAdjointEigenSolver<mat> eigensolver(ti);
mat evalues = eigensolver.eigenvalues();
mat q = eigensolver.eigenvectors();
LOG (INFO) << "Iteration " << i << ", EigenValues: ";
LOG (INFO) << evalues;
mat mtmp(i+1,1);// = alpha;
array2mat(i+1, alpha, mtmp);
LOG (INFO) << "Alphas: ";
LOG (INFO) << mtmp;
array2mat(i+1, beta, mtmp);
LOG (INFO) << "Betas: ";
LOG (INFO) << mtmp;
//Max singular value
double max_sv = abs((double)evalues(0));
for (int i = 1; i <= i; i++){
max_sv = max(max_sv, abs((double)evalues(i)));
}
LOG (INFO) << "Max Singular Value = " << max_sv;
bool so = false;
LOG (INFO) << "9: Reorthogonalization";
for (int j = 0; j <= i; j++){
if (beta[i] * abs((double) q(i,j)) <= epsilon * max_sv){
LOG (INFO) << "Reorthogonalization for ritz vector = "<< j;
double *constants = new double[i+1];
for ( int k = 0; k < i+1; k++ ){
constants[k] = (double)q(k,j);
}
r.linear_combination(i+1, constants, vectors);
//-(r*v)
double constant = -1 * r.transpose().multiply(v);
//v=v-(r*v)r
v.linear_combination(2, new double[2]{1, constant}, new PrimitiveVector<double>*[2]{&v, &r});
so = true;
delete constants;
}
}
LOG (INFO) << "15:";
if ( so ){
LOG (INFO) << "16: Recompute normalization constant beta["<< i <<"]";
beta[i] = v.pnorm(2);
}
LOG (INFO) << "18:";
if ( beta[i] == 0){
iterations = i+1;
break;
}
if ( i < iterations-1 ){
LOG (INFO) << "21: V[i+1] = v/beta[i]";
stringstream filename;
filename << path << "v" << (i+1);
vectors[i+1] = (PrimitiveVector<double> *) new PrimitiveVector<double>(filename.str(), node_count, block_size);
v.multiply(1/beta[i], *vectors[i+1]);
}
}
LOG (INFO) << "Creating EigenValues";
mat ti = build_tridiagonal_matrix(iterations, alpha, beta);
Eigen::SelfAdjointEigenSolver<mat > eigensolver(ti);
mat evalues = eigensolver.eigenvalues();
mat q = eigensolver.eigenvectors();
/*double *eigenValues = new double[iterations];
mat2array(evalues, eigenValues);*/
int64 *ids = sort_and_get_indexes(iterations, evalues.data(), false);
swap_cols(q, ids, k);
//reducing q to k columns
q.resize(k,k);
//storing eigen values
PrimitiveVector<double> eigens(eigens_file, k);
eigens.store_region(0, k, evalues.data());
LOG (INFO) << "Creating RitzVectors";
create_ritz_vectors(vectors, q);
delete ids;
//delete [] vectors;
delete [] alpha;
delete [] beta;
//delete eigenValues;
}
inline void LanczosSO::create_ritz_vectors(PrimitiveVector<double> *vectors[], mat &q){
string path = get_parent_directory(vectors[0]->get_file()) + FILE_SEPARATOR;
int64 node_count = matrix->size();
int64 block_size = matrix->get_elements_by_block();
int nRitzVectors = q.cols();
int iterations = q.rows();
PrimitiveVector<double> *ritz;
for (int i = 0; i < nRitzVectors; i++){
stringstream ritz_file;
ritz_file << path << "RIT" << i;
double *constants = new double[iterations];
for ( int idx = 0; idx < iterations; idx++ ){
constants[idx] = (double)q(idx,i);
}
ritz = new PrimitiveVector<double>(ritz_file.str(), node_count , block_size);
ritz->linear_combination(iterations, constants, vectors);
delete constants;
delete ritz;
}
}
mat LanczosSO::build_tridiagonal_matrix(int m, double alpha [], double beta[]){
mat matrix(m, m);
matrix.fill(0);
matrix(0,0) = alpha[0];
if(m==1) return matrix;
matrix(0,1) = beta[0];
matrix(m-1,m-2) = beta[m-2];
matrix(m-1,m-1) = alpha[m-1];
for(int i=1; i<m-1; i++){
matrix(i,i) = alpha[i];
matrix(i,i+1) = beta[i];
matrix(i,i-1) = beta[i-1];
}
return matrix;
}
}
#endif /* ALGORITHM_LANCZOSSO_HPP_ */
<commit_msg>Solving mistake with the index to find the Max Singular Value<commit_after>/*
* lanczosSO.hpp
*
* Created on: Mar 3, 2015
* Author: hugo
*/
#ifndef ALGORITHM_LANCZOSSO_HPP_
#define ALGORITHM_LANCZOSSO_HPP_
#include <cmath>
#include <sstream>
#include <string>
#include "../core/eigenwrapper.hpp"
#include "../core/matrix.hpp"
#include "../core/primitivematrix.hpp"
#include "../core/primitivevector.hpp"
#include "../core/type.hpp"
#include "../core/util.hpp"
#include "../Eigen/Dense"
#include "../log/easylogging++.h"
using namespace std;
namespace mflash{
class LanczosSO{
PrimitiveMatrix<double, EmptyType> *matrix;
int iterations;
int k;
mat build_tridiagonal_matrix(int m, double alpha [], double beta[]);
public:
LanczosSO(PrimitiveMatrix<double, EmptyType> &matrix, int iterations, int k);
void create_ritz_vectors(PrimitiveVector<double> *vectors[], mat &q);
void run();
};
LanczosSO::LanczosSO(PrimitiveMatrix<double, EmptyType> &matrix, int iterations, int k){
this->matrix = &matrix;
this->iterations = iterations;
this->k = k;
}
void LanczosSO::run(){
string path = mflash::get_parent_directory(matrix->get_file());
cout<<path<<endl;
string v_file = path + "v.bin";
string eigens_file = path + "eigen_values.bin";
//string v_tmp = path + FILE_SEPARATOR + "tmp.bin";
string r_file = path + "r.bin";
const int64 block_size = matrix->get_elements_by_block();
const int64 node_count = matrix->size();
double epsilon = sqrt(1E-18);
double *beta = new double[iterations];
double *alpha = new double[iterations];
//orthogonal vectors v
PrimitiveVector<double> *vectors[iterations];// = new PrimitiveVector<double>*[iterations];
PrimitiveVector<double> v (v_file, node_count, block_size);
PrimitiveVector<double> r (r_file, node_count, block_size);
LOG (INFO) << "1: initial values";
vectors[0] = new PrimitiveVector<double> ( path + "v0", node_count, block_size );
vectors[0]->fill_random();
vectors[0]->multiply(((double)1/vectors[0]->pnorm(2)));
for (int i = 0; i < iterations; i++){
LOG (INFO) << "3: Find a new basis vector";
matrix->multiply( *(vectors[i]), v);
LOG (INFO) << "4:";
alpha[i] = vectors[i]->transpose().multiply(v);
LOG (INFO) << "5: v = v - beta[i-1]V[i-1] - alpha[i]V[i]";
if(i>0){
v.linear_combination(3, new double[3]{1, -1*beta[i-1], -1*alpha[i]}, new PrimitiveVector<double>*[3]{&v, vectors[i-1], vectors[i]});
}else{
v.linear_combination(2, new double[2]{1, -1*alpha[i]}, new PrimitiveVector<double>*[2]{&v, vectors[i]});
}
LOG (INFO) << "6: beta[i] = ||v||";
beta[i] = v.pnorm(2);
LOG (INFO) << "7: build tri-diagonal matrix from alpha and beta";
mat ti = build_tridiagonal_matrix(i+1, alpha, beta);
LOG (INFO) << "8: ";
Eigen::SelfAdjointEigenSolver<mat> eigensolver(ti);
mat evalues = eigensolver.eigenvalues();
mat q = eigensolver.eigenvectors();
LOG (INFO) << "Iteration " << i << ", EigenValues: ";
LOG (INFO) << evalues;
mat mtmp(i+1,1);// = alpha;
array2mat(i+1, alpha, mtmp);
LOG (INFO) << "Alphas: ";
LOG (INFO) << mtmp;
array2mat(i+1, beta, mtmp);
LOG (INFO) << "Betas: ";
LOG (INFO) << mtmp;
//Max singular value
double max_sv = abs((double)evalues(0));
for (int j = 1; j <= i; j++){
max_sv = max(max_sv, abs((double)evalues(j)));
}
LOG (INFO) << "Max Singular Value = " << max_sv;
bool so = false;
LOG (INFO) << "9: Reorthogonalization";
for (int j = 0; j <= i; j++){
if (beta[i] * abs((double) q(i,j)) <= epsilon * max_sv){
LOG (INFO) << "Reorthogonalization for ritz vector = "<< j;
double *constants = new double[i+1];
for ( int k = 0; k < i+1; k++ ){
constants[k] = (double)q(k,j);
}
r.linear_combination(i+1, constants, vectors);
//-(r*v)
double constant = -1 * r.transpose().multiply(v);
//v=v-(r*v)r
v.linear_combination(2, new double[2]{1, constant}, new PrimitiveVector<double>*[2]{&v, &r});
so = true;
delete constants;
}
}
LOG (INFO) << "15:";
if ( so ){
LOG (INFO) << "16: Recompute normalization constant beta["<< i <<"]";
beta[i] = v.pnorm(2);
}
LOG (INFO) << "18:";
if ( beta[i] == 0){
iterations = i+1;
break;
}
if ( i < iterations-1 ){
LOG (INFO) << "21: V[i+1] = v/beta[i]";
stringstream filename;
filename << path << "v" << (i+1);
vectors[i+1] = (PrimitiveVector<double> *) new PrimitiveVector<double>(filename.str(), node_count, block_size);
v.multiply(1/beta[i], *vectors[i+1]);
}
}
LOG (INFO) << "Creating EigenValues";
mat ti = build_tridiagonal_matrix(iterations, alpha, beta);
Eigen::SelfAdjointEigenSolver<mat > eigensolver(ti);
mat evalues = eigensolver.eigenvalues();
mat q = eigensolver.eigenvectors();
/*double *eigenValues = new double[iterations];
mat2array(evalues, eigenValues);*/
int64 *ids = sort_and_get_indexes(iterations, evalues.data(), false);
swap_cols(q, ids, k);
//reducing q to k columns
q.resize(k,k);
//storing eigen values
PrimitiveVector<double> eigens(eigens_file, k);
eigens.store_region(0, k, evalues.data());
LOG (INFO) << "Creating RitzVectors";
create_ritz_vectors(vectors, q);
delete ids;
//delete [] vectors;
delete [] alpha;
delete [] beta;
//delete eigenValues;
}
inline void LanczosSO::create_ritz_vectors(PrimitiveVector<double> *vectors[], mat &q){
string path = get_parent_directory(vectors[0]->get_file()) + FILE_SEPARATOR;
int64 node_count = matrix->size();
int64 block_size = matrix->get_elements_by_block();
int nRitzVectors = q.cols();
int iterations = q.rows();
PrimitiveVector<double> *ritz;
for (int i = 0; i < nRitzVectors; i++){
stringstream ritz_file;
ritz_file << path << "RIT" << i;
double *constants = new double[iterations];
for ( int idx = 0; idx < iterations; idx++ ){
constants[idx] = (double)q(idx,i);
}
ritz = new PrimitiveVector<double>(ritz_file.str(), node_count , block_size);
ritz->linear_combination(iterations, constants, vectors);
delete constants;
delete ritz;
}
}
mat LanczosSO::build_tridiagonal_matrix(int m, double alpha [], double beta[]){
mat matrix(m, m);
matrix.fill(0);
matrix(0,0) = alpha[0];
if(m==1) return matrix;
matrix(0,1) = beta[0];
matrix(m-1,m-2) = beta[m-2];
matrix(m-1,m-1) = alpha[m-1];
for(int i=1; i<m-1; i++){
matrix(i,i) = alpha[i];
matrix(i,i+1) = beta[i];
matrix(i,i-1) = beta[i-1];
}
return matrix;
}
}
#endif /* ALGORITHM_LANCZOSSO_HPP_ */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: srchdlg.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2004-07-30 15:44: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): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_SRCHDLG_HXX
#define _SVX_SRCHDLG_HXX
// include ---------------------------------------------------------------
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _SFX_SRCHDEFS_HXX_
#include <sfx2/srchdefs.hxx>
#endif
// forward ---------------------------------------------------------------
class SvxSearchItem;
class MoreButton;
class SfxStyleSheetBasePool;
class SvxJSearchOptionsPage;
struct SearchDlg_Impl;
#ifndef NO_SVX_SEARCH
// struct SearchAttrItem -------------------------------------------------
struct SearchAttrItem
{
USHORT nSlot;
SfxPoolItem* pItem;
};
// class SearchAttrItemList ----------------------------------------------
SV_DECL_VARARR(SrchAttrItemList, SearchAttrItem, 8, 8);
class SearchAttrItemList : private SrchAttrItemList
{
public:
SearchAttrItemList() {}
SearchAttrItemList( const SearchAttrItemList& rList );
~SearchAttrItemList();
void Put( const SfxItemSet& rSet );
SfxItemSet& Get( SfxItemSet& rSet );
void Clear();
USHORT Count() const { return SrchAttrItemList::Count(); }
SearchAttrItem& operator[](USHORT nPos) const
{ return SrchAttrItemList::operator[]( nPos ); }
SearchAttrItem& GetObject( USHORT nPos ) const
{ return SrchAttrItemList::GetObject( nPos ); }
// der Pointer auf das Item wird nicht kopiert!!! (also nicht l"oschen)
void Insert( const SearchAttrItem& rItem )
{ SrchAttrItemList::Insert( rItem, SrchAttrItemList::Count() ); }
// l"oscht die Pointer auf die Items
void Remove( USHORT nPos, USHORT nLen = 1 );
};
#ifndef SV_NODIALOG
// class SvxSearchDialogWrapper ------------------------------------------
class SvxSearchDialogWrapper : public SfxChildWindow
{
public:
SvxSearchDialogWrapper( Window*pParent, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SvxSearchDialogWrapper);
};
// class SvxSearchDialog -------------------------------------------------
/*
{k:\svx\prototyp\dialog\srchdlg.hxx}
[Beschreibung]
In diesem Modeless-Dialog werden die Attribute einer Suche eingestellt
und damit eine Suche gestartet. Es sind mehrere Sucharten
( Suchen, Alle suchen, Ersetzen, Alle ersetzen ) m"oglich.
[Items]
<SvxSearchItem><SID_ATTR_SEARCH>
*/
class SvxSearchDialog : public SfxModelessDialog
{
friend class SvxSearchController;
friend class SvxSearchDialogWrapper;
friend class SvxJSearchOptionsDialog;
public:
SvxSearchDialog( Window* pParent, SfxBindings& rBind );
SvxSearchDialog( Window* pParent, SfxChildWindow* pChildWin, SfxBindings& rBind );
~SvxSearchDialog();
virtual BOOL Close();
// Window
virtual void Activate();
void GetSearchItems( SfxItemSet& rSet );
void GetReplaceItems( SfxItemSet& rSet );
const SearchAttrItemList* GetSearchItemList() const
{ return pSearchList; }
const SearchAttrItemList* GetReplaceItemList() const
{ return pReplaceList; }
inline BOOL HasSearchAttributes() const;
inline BOOL HasReplaceAttributes() const;
PushButton& GetReplaceBtn() { return aReplaceBtn; }
INT32 GetTransliterationFlags() const;
private:
FixedText aSearchText;
ComboBox aSearchLB;
ListBox aSearchTmplLB;
FixedInfo aSearchAttrText;
#if SUPD < 641 || defined( GT_DEBUG )
MultiLineEdit aSearchFormatsED;
#endif
FixedText aReplaceText;
ComboBox aReplaceLB;
ListBox aReplaceTmplLB;
FixedInfo aReplaceAttrText;
#if SUPD < 641 || defined( GT_DEBUG )
MultiLineEdit aReplaceFormatsED;
#endif
PushButton aSearchAllBtn;
PushButton aSearchBtn;
PushButton aReplaceAllBtn;
PushButton aReplaceBtn;
PushButton aAttributeBtn;
CancelButton aCloseBtn;
PushButton aFormatBtn;
HelpButton aHelpBtn;
PushButton aNoFormatBtn;
MoreButton* pMoreBtn;
CheckBox aWordBtn;
CheckBox aMatchCaseCB;
CheckBox aBackwardsBtn;
CheckBox aSelectionBtn;
CheckBox aRegExpBtn;
CheckBox aLayoutBtn;
// "Ahnlichkeitssuche
CheckBox aSimilarityBox;
PushButton aSimilarityBtn;
CheckBox aJapMatchFullHalfWidthCB;
CheckBox aJapOptionsCB;
PushButton aJapOptionsBtn;
FixedLine aOptionsFL;
// nur f"ur Calc
RadioButton aFormulasBtn;
RadioButton aValuesBtn;
RadioButton aNotesBtn;
FixedLine aSearchFL;
FixedLine aSearchVertFL;
RadioButton aRowsBtn;
RadioButton aColumnsBtn;
FixedLine aSearchDirFL;
FixedLine aSearchDirVertFL;
CheckBox aAllTablesCB;
FixedLine aCalcExtrasFL;
SfxBindings& rBindings;
BOOL bWriter;
BOOL bSearch;
BOOL bFormat;
USHORT nOptions;
FASTBOOL bSet;
FASTBOOL bReadOnly;
FASTBOOL bConstruct;
ULONG nModifyFlag;
String aStylesStr;
String aLayoutStr;
String aCalcStr;
SvStringsDtor aSearchStrings;
SvStringsDtor aReplaceStrings;
SearchDlg_Impl* pImpl;
SearchAttrItemList* pSearchList;
SearchAttrItemList* pReplaceList;
SvxSearchItem* pSearchItem;
SvxSearchController* pSearchController;
SvxSearchController* pOptionsController;
SvxSearchController* pFamilyController;
SvxSearchController* pSearchSetController;
SvxSearchController* pReplaceSetController;
mutable INT32 nTransliterationFlags;
#ifdef _SVX_SRCHDLG_CXX
DECL_LINK( ModifyHdl_Impl, ComboBox* pEdit );
DECL_LINK( FlagHdl_Impl, Button* pBtn );
DECL_LINK( CommandHdl_Impl, Button* pBtn );
DECL_LINK( TemplateHdl_Impl, Button* );
DECL_LINK( FocusHdl_Impl, Control* );
DECL_LINK( LoseFocusHdl_Impl, Control* );
DECL_LINK( FormatHdl_Impl, Button* );
DECL_LINK( NoFormatHdl_Impl, Button* );
DECL_LINK( AttributeHdl_Impl, Button* );
DECL_LINK( TimeoutHdl_Impl, Timer* );
void Construct_Impl();
void InitControls_Impl();
void Init_Impl( int bHasItemSet );
void InitAttrList_Impl( const SfxItemSet* pSSet,
const SfxItemSet* pRSet );
void Remember_Impl( const String &rStr,BOOL bSearch );
void PaintAttrText_Impl();
String& BuildAttrText_Impl( String& rStr, BOOL bSrchFlag ) const;
void TemplatesChanged_Impl( SfxStyleSheetBasePool& rPool );
void EnableControls_Impl( const USHORT nFlags );
void EnableControl_Impl( Control* pCtrl );
void SetItem_Impl( const SvxSearchItem* pItem );
void SetModifyFlag_Impl( const Control* pCtrl );
void SaveToModule_Impl();
void ApplyTransliterationFlags_Impl( INT32 nSettings );
#endif
};
inline BOOL SvxSearchDialog::HasSearchAttributes() const
{
int bLen = aSearchAttrText.GetText().Len();
return ( aSearchAttrText.IsEnabled() && bLen );
}
inline BOOL SvxSearchDialog::HasReplaceAttributes() const
{
int bLen = aReplaceAttrText.GetText().Len();
return ( aReplaceAttrText.IsEnabled() && bLen );
}
//////////////////////////////////////////////////////////////////////
/* //CHINA001
class SvxJSearchOptionsDialog : public SfxSingleTabDialog
{
INT32 nInitialTlFlags;
SvxJSearchOptionsPage *pPage;
// disallow copy-constructor and assignment-operator for now
SvxJSearchOptionsDialog( const SvxJSearchOptionsDialog & );
SvxJSearchOptionsDialog & operator == ( const SvxJSearchOptionsDialog & );
public:
SvxJSearchOptionsDialog( Window *pParent,
const SfxItemSet& rOptionsSet, USHORT nUniqueId,
INT32 nInitialFlags );
virtual ~SvxJSearchOptionsDialog();
// Window
virtual void Activate();
INT32 GetTransliterationFlags() const;
void SetTransliterationFlags( INT32 nSettings );
};
*/ //CHINA001
//////////////////////////////////////////////////////////////////////
#endif // SV_NODIALOG
#endif // NO_SVX_SEARCH
#endif
<commit_msg>INTEGRATION: CWS visibility01 (1.10.142); FILE MERGED 2004/12/06 08:10:41 mnicel 1.10.142.1: Part of symbol visibility markup - #i35758#<commit_after>/*************************************************************************
*
* $RCSfile: srchdlg.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2005-01-21 15:20:21 $
*
* 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 _SVX_SRCHDLG_HXX
#define _SVX_SRCHDLG_HXX
// include ---------------------------------------------------------------
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _SFX_SRCHDEFS_HXX_
#include <sfx2/srchdefs.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// forward ---------------------------------------------------------------
class SvxSearchItem;
class MoreButton;
class SfxStyleSheetBasePool;
class SvxJSearchOptionsPage;
struct SearchDlg_Impl;
#ifndef NO_SVX_SEARCH
// struct SearchAttrItem -------------------------------------------------
struct SearchAttrItem
{
USHORT nSlot;
SfxPoolItem* pItem;
};
// class SearchAttrItemList ----------------------------------------------
SV_DECL_VARARR_VISIBILITY(SrchAttrItemList, SearchAttrItem, 8, 8, SVX_DLLPUBLIC);
class SVX_DLLPUBLIC SearchAttrItemList : private SrchAttrItemList
{
public:
SearchAttrItemList() {}
SearchAttrItemList( const SearchAttrItemList& rList );
~SearchAttrItemList();
void Put( const SfxItemSet& rSet );
SfxItemSet& Get( SfxItemSet& rSet );
void Clear();
USHORT Count() const { return SrchAttrItemList::Count(); }
SearchAttrItem& operator[](USHORT nPos) const
{ return SrchAttrItemList::operator[]( nPos ); }
SearchAttrItem& GetObject( USHORT nPos ) const
{ return SrchAttrItemList::GetObject( nPos ); }
// der Pointer auf das Item wird nicht kopiert!!! (also nicht l"oschen)
void Insert( const SearchAttrItem& rItem )
{ SrchAttrItemList::Insert( rItem, SrchAttrItemList::Count() ); }
// l"oscht die Pointer auf die Items
void Remove( USHORT nPos, USHORT nLen = 1 );
};
#ifndef SV_NODIALOG
// class SvxSearchDialogWrapper ------------------------------------------
class SVX_DLLPUBLIC SvxSearchDialogWrapper : public SfxChildWindow
{
public:
SvxSearchDialogWrapper( Window*pParent, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SvxSearchDialogWrapper);
};
// class SvxSearchDialog -------------------------------------------------
/*
{k:\svx\prototyp\dialog\srchdlg.hxx}
[Beschreibung]
In diesem Modeless-Dialog werden die Attribute einer Suche eingestellt
und damit eine Suche gestartet. Es sind mehrere Sucharten
( Suchen, Alle suchen, Ersetzen, Alle ersetzen ) m"oglich.
[Items]
<SvxSearchItem><SID_ATTR_SEARCH>
*/
class SvxSearchDialog : public SfxModelessDialog
{
friend class SvxSearchController;
friend class SvxSearchDialogWrapper;
friend class SvxJSearchOptionsDialog;
public:
SvxSearchDialog( Window* pParent, SfxBindings& rBind );
SvxSearchDialog( Window* pParent, SfxChildWindow* pChildWin, SfxBindings& rBind );
~SvxSearchDialog();
virtual BOOL Close();
// Window
virtual void Activate();
void GetSearchItems( SfxItemSet& rSet );
void GetReplaceItems( SfxItemSet& rSet );
const SearchAttrItemList* GetSearchItemList() const
{ return pSearchList; }
const SearchAttrItemList* GetReplaceItemList() const
{ return pReplaceList; }
inline BOOL HasSearchAttributes() const;
inline BOOL HasReplaceAttributes() const;
PushButton& GetReplaceBtn() { return aReplaceBtn; }
INT32 GetTransliterationFlags() const;
private:
FixedText aSearchText;
ComboBox aSearchLB;
ListBox aSearchTmplLB;
FixedInfo aSearchAttrText;
#if SUPD < 641 || defined( GT_DEBUG )
MultiLineEdit aSearchFormatsED;
#endif
FixedText aReplaceText;
ComboBox aReplaceLB;
ListBox aReplaceTmplLB;
FixedInfo aReplaceAttrText;
#if SUPD < 641 || defined( GT_DEBUG )
MultiLineEdit aReplaceFormatsED;
#endif
PushButton aSearchAllBtn;
PushButton aSearchBtn;
PushButton aReplaceAllBtn;
PushButton aReplaceBtn;
PushButton aAttributeBtn;
CancelButton aCloseBtn;
PushButton aFormatBtn;
HelpButton aHelpBtn;
PushButton aNoFormatBtn;
MoreButton* pMoreBtn;
CheckBox aWordBtn;
CheckBox aMatchCaseCB;
CheckBox aBackwardsBtn;
CheckBox aSelectionBtn;
CheckBox aRegExpBtn;
CheckBox aLayoutBtn;
// "Ahnlichkeitssuche
CheckBox aSimilarityBox;
PushButton aSimilarityBtn;
CheckBox aJapMatchFullHalfWidthCB;
CheckBox aJapOptionsCB;
PushButton aJapOptionsBtn;
FixedLine aOptionsFL;
// nur f"ur Calc
RadioButton aFormulasBtn;
RadioButton aValuesBtn;
RadioButton aNotesBtn;
FixedLine aSearchFL;
FixedLine aSearchVertFL;
RadioButton aRowsBtn;
RadioButton aColumnsBtn;
FixedLine aSearchDirFL;
FixedLine aSearchDirVertFL;
CheckBox aAllTablesCB;
FixedLine aCalcExtrasFL;
SfxBindings& rBindings;
BOOL bWriter;
BOOL bSearch;
BOOL bFormat;
USHORT nOptions;
FASTBOOL bSet;
FASTBOOL bReadOnly;
FASTBOOL bConstruct;
ULONG nModifyFlag;
String aStylesStr;
String aLayoutStr;
String aCalcStr;
SvStringsDtor aSearchStrings;
SvStringsDtor aReplaceStrings;
SearchDlg_Impl* pImpl;
SearchAttrItemList* pSearchList;
SearchAttrItemList* pReplaceList;
SvxSearchItem* pSearchItem;
SvxSearchController* pSearchController;
SvxSearchController* pOptionsController;
SvxSearchController* pFamilyController;
SvxSearchController* pSearchSetController;
SvxSearchController* pReplaceSetController;
mutable INT32 nTransliterationFlags;
#ifdef _SVX_SRCHDLG_CXX
DECL_LINK( ModifyHdl_Impl, ComboBox* pEdit );
DECL_LINK( FlagHdl_Impl, Button* pBtn );
DECL_LINK( CommandHdl_Impl, Button* pBtn );
DECL_LINK( TemplateHdl_Impl, Button* );
DECL_LINK( FocusHdl_Impl, Control* );
DECL_LINK( LoseFocusHdl_Impl, Control* );
DECL_LINK( FormatHdl_Impl, Button* );
DECL_LINK( NoFormatHdl_Impl, Button* );
DECL_LINK( AttributeHdl_Impl, Button* );
DECL_LINK( TimeoutHdl_Impl, Timer* );
void Construct_Impl();
void InitControls_Impl();
void Init_Impl( int bHasItemSet );
void InitAttrList_Impl( const SfxItemSet* pSSet,
const SfxItemSet* pRSet );
void Remember_Impl( const String &rStr,BOOL bSearch );
void PaintAttrText_Impl();
String& BuildAttrText_Impl( String& rStr, BOOL bSrchFlag ) const;
void TemplatesChanged_Impl( SfxStyleSheetBasePool& rPool );
void EnableControls_Impl( const USHORT nFlags );
void EnableControl_Impl( Control* pCtrl );
void SetItem_Impl( const SvxSearchItem* pItem );
void SetModifyFlag_Impl( const Control* pCtrl );
void SaveToModule_Impl();
void ApplyTransliterationFlags_Impl( INT32 nSettings );
#endif
};
inline BOOL SvxSearchDialog::HasSearchAttributes() const
{
int bLen = aSearchAttrText.GetText().Len();
return ( aSearchAttrText.IsEnabled() && bLen );
}
inline BOOL SvxSearchDialog::HasReplaceAttributes() const
{
int bLen = aReplaceAttrText.GetText().Len();
return ( aReplaceAttrText.IsEnabled() && bLen );
}
//////////////////////////////////////////////////////////////////////
/* //CHINA001
class SvxJSearchOptionsDialog : public SfxSingleTabDialog
{
INT32 nInitialTlFlags;
SvxJSearchOptionsPage *pPage;
// disallow copy-constructor and assignment-operator for now
SvxJSearchOptionsDialog( const SvxJSearchOptionsDialog & );
SvxJSearchOptionsDialog & operator == ( const SvxJSearchOptionsDialog & );
public:
SvxJSearchOptionsDialog( Window *pParent,
const SfxItemSet& rOptionsSet, USHORT nUniqueId,
INT32 nInitialFlags );
virtual ~SvxJSearchOptionsDialog();
// Window
virtual void Activate();
INT32 GetTransliterationFlags() const;
void SetTransliterationFlags( INT32 nSettings );
};
*/ //CHINA001
//////////////////////////////////////////////////////////////////////
#endif // SV_NODIALOG
#endif // NO_SVX_SEARCH
#endif
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
bool sendPacket();
bool seqNum = true;
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
calen = sizeof(ca);
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
seqNum = true;
dropPck = false;
return true;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
bool isSeqNumSet = false;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
if(!isSeqNumSet) {
isSeqNumSet = true;
char * str = new char[1];
memcpy(str, &packet[0], 1);
seqNum = boost::lexical_cast<int>(str);
}
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p ((seqNum) ? false : true, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= (length / BUFSIZE) + 1; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
struct timeval t1, t2;
gettimeofday(&t1, NULL);
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
gettimeofday(&t2, NULL);
cout << "We took " << t2.tv_usec - t1.tv_usec << " us to receive that ack." << endl;
cout << "We had " << toms << " ms to take." << endl;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) usleep(delayT * 1000); //using milliseconds
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
seqNum = (seqNum) ? false : true;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>Change timer test<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
bool sendPacket();
bool seqNum = true;
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
calen = sizeof(ca);
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
seqNum = true;
dropPck = false;
return true;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
bool isSeqNumSet = false;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
if(!isSeqNumSet) {
isSeqNumSet = true;
char * str = new char[1];
memcpy(str, &packet[0], 1);
seqNum = boost::lexical_cast<int>(str);
}
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p ((seqNum) ? false : true, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= (length / BUFSIZE) + 1; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
struct timeval t1, t2;
gettimeofday(&t1, NULL);
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
gettimeofday(&t2, NULL);
cout << "We took " << t2.tv_usec - t1.tv_usec << " us to receive that ack." << endl;
cout << "We had " << toms << " ms to take." << endl;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) { cout << "sleeping for " << delayT * 1000 << "ms..." << endl; usleep(delayT * 1000); }//using milliseconds
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
seqNum = (seqNum) ? false : true;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: FilteredContainer.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-10-22 09:00:01 $
*
* 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 DBACCESS_CORE_FILTERED_CONTAINER_HXX
#define DBACCESS_CORE_FILTERED_CONTAINER_HXX
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include <connectivity/sdbcx/VCollection.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
class WildCard;
namespace dbaccess
{
class IWarningsContainer;
class IRefreshListener;
class OFilteredContainer : public ::connectivity::sdbcx::OCollection
{
protected:
IWarningsContainer* m_pWarningsContainer;
IRefreshListener* m_pRefreshListener;
// holds the original container which where set in construct but they can be null
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xMasterContainer;
::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > m_xConnection;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
mutable sal_Bool m_bConstructed; // late ctor called
virtual sal_Bool isNameValid(const ::rtl::OUString& _rName,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getTableTypeFilter(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter) const = 0;
inline virtual void addMasterContainerListener(){}
inline virtual void removeMasterContainerListener(){}
// ::connectivity::sdbcx::OCollection
virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > cloneObject(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor);
/** tell the container to free all elements and all additional resources.<BR>
After using this method the object may be reconstructed by calling one of the <code>constrcuct</code> methods.
*/
virtual void SAL_CALL disposing();
public:
/** ctor of the container. The parent has to support the <type scope="com::sun::star::sdbc">XConnection</type>
interface.<BR>
@param _rParent the object which acts as parent for the container.
all refcounting is rerouted to this object
@param _rMutex the access safety object of the parent
@param _rTableFilter restricts the visible tables by name
@param _rTableTypeFilter restricts the visible tables by type
@see construct
*/
OFilteredContainer( ::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener = NULL,
IWarningsContainer* _pWarningsContainer = NULL
);
inline void dispose() { disposing(); }
/** late ctor. The container will fill itself with the data got by the connection meta data, considering the
filters given (the connection is the parent object you passed in the ctor).
*/
void construct(
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter
);
/** late ctor. The container will fill itself with wrapper objects for the tables returned by the given
name container.
*/
void construct(
const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxMasterContainer,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter
);
inline sal_Bool isInitialized() const { return m_bConstructed; }
};
// ..............................................................................
} // namespace
// ..............................................................................
#endif // DBACCESS_CORE_FILTERED_CONTAINER_HXX
<commit_msg>INTEGRATION: CWS dba24 (1.4.50); FILE MERGED 2005/02/09 08:12:59 oj 1.4.50.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
*
* $RCSfile: FilteredContainer.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2005-03-10 16:36:29 $
*
* 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 DBACCESS_CORE_FILTERED_CONTAINER_HXX
#define DBACCESS_CORE_FILTERED_CONTAINER_HXX
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include <connectivity/sdbcx/VCollection.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
class WildCard;
namespace dbaccess
{
class IWarningsContainer;
class IRefreshListener;
class OFilteredContainer : public ::connectivity::sdbcx::OCollection
{
protected:
IWarningsContainer* m_pWarningsContainer;
IRefreshListener* m_pRefreshListener;
// holds the original container which where set in construct but they can be null
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xMasterContainer;
::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > m_xConnection;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
mutable sal_Bool m_bConstructed; // late ctor called
virtual sal_Bool isNameValid(const ::rtl::OUString& _rName,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getTableTypeFilter(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter) const = 0;
inline virtual void addMasterContainerListener(){}
inline virtual void removeMasterContainerListener(){}
// ::connectivity::sdbcx::OCollection
virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString getNameForObject(const ::connectivity::sdbcx::ObjectType& _xObject);
/** tell the container to free all elements and all additional resources.<BR>
After using this method the object may be reconstructed by calling one of the <code>constrcuct</code> methods.
*/
virtual void SAL_CALL disposing();
public:
/** ctor of the container. The parent has to support the <type scope="com::sun::star::sdbc">XConnection</type>
interface.<BR>
@param _rParent the object which acts as parent for the container.
all refcounting is rerouted to this object
@param _rMutex the access safety object of the parent
@param _rTableFilter restricts the visible tables by name
@param _rTableTypeFilter restricts the visible tables by type
@see construct
*/
OFilteredContainer( ::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener = NULL,
IWarningsContainer* _pWarningsContainer = NULL
);
inline void dispose() { disposing(); }
/** late ctor. The container will fill itself with the data got by the connection meta data, considering the
filters given (the connection is the parent object you passed in the ctor).
*/
void construct(
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter
);
/** late ctor. The container will fill itself with wrapper objects for the tables returned by the given
name container.
*/
void construct(
const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxMasterContainer,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter
);
inline sal_Bool isInitialized() const { return m_bConstructed; }
};
// ..............................................................................
} // namespace
// ..............................................................................
#endif // DBACCESS_CORE_FILTERED_CONTAINER_HXX
<|endoftext|> |
<commit_before>#include "laser.h"
#include <geometry.h>
#include <digitanks/units/digitank.h>
#include <digitanks/digitanksgame.h>
#include <digitanks/dt_renderer.h>
size_t CLaser::s_iBeam = 0;
REGISTER_ENTITY(CLaser);
NETVAR_TABLE_BEGIN(CLaser);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CLaser);
SAVEDATA_TABLE_END();
void CLaser::Precache()
{
s_iBeam = CRenderer::LoadTextureIntoGL(L"textures/beam-pulse.png");
}
void CLaser::ClientSpawn()
{
BaseClass::ClientSpawn();
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin()) < 0.1f)
{
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin() + AngleVector(GetAngles())*LaserLength()) < 0.1f)
m_bShouldRender = false;
}
}
void CLaser::OnSetOwner(CDigitank* pOwner)
{
BaseClass::OnSetOwner(pOwner);
SetAngles(VectorAngles((pOwner->GetLastAim() - GetOrigin()).Normalized()));
SetOrigin(pOwner->GetOrigin());
SetSimulated(false);
SetVelocity(Vector(0,0,0));
SetGravity(Vector(0,0,0));
m_flTimeExploded = GameServer()->GetGameTime();
Vector vecForward, vecRight;
AngleVectors(GetAngles(), &vecForward, &vecRight, NULL);
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
if (!pEntity)
continue;
if (!pEntity->TakesDamage())
continue;
if (pEntity->GetTeam() == pOwner->GetTeam())
continue;
float flDistance = DistanceToPlane(pEntity->GetOrigin(), GetOrigin(), vecRight);
if (flDistance > 4 + pEntity->GetBoundingRadius())
continue;
// Cull objects behind
if (vecForward.Dot(pEntity->GetOrigin() - GetOrigin()) < 0)
continue;
if (pEntity->Distance(GetOrigin()) > LaserLength())
continue;
pEntity->TakeDamage(pOwner, this, DAMAGE_LASER, m_flDamage + pOwner->GetBonusAttackDamage(), flDistance < pEntity->GetBoundingRadius()-2);
CDigitank* pTank = dynamic_cast<CDigitank*>(pEntity);
if (pTank)
{
float flRockIntensity = 0.5f;
Vector vecDirection = (pTank->GetOrigin() - pOwner->GetOrigin()).Normalized();
pTank->RockTheBoat(flRockIntensity, vecDirection);
}
}
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin()) < 0.1f)
{
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin() + AngleVector(GetAngles())*LaserLength()) < 0.1f)
{
// If the start and end points are both in the fog of war, delete it now that we've aready done the damage so it doesn't get rendered later.
if (CNetwork::IsHost())
Delete();
}
}
}
void CLaser::PostRender(bool bTransparent)
{
BaseClass::PostRender(bTransparent);
if (!bTransparent)
return;
if (!m_bShouldRender)
return;
CRenderingContext r(DigitanksGame()->GetDigitanksRenderer());
r.SetBlend(BLEND_ADDITIVE);
Vector vecForward, vecRight, vecUp;
float flLength = LaserLength();
Vector vecMuzzle = m_hOwner->GetOrigin();
Vector vecTarget = vecMuzzle + AngleVector(GetAngles()) * flLength;
if (m_hOwner != NULL)
{
Vector vecDirection = (m_hOwner->GetLastAim() - m_hOwner->GetOrigin()).Normalized();
vecTarget = vecMuzzle + vecDirection * flLength;
AngleVectors(VectorAngles(vecDirection), &vecForward, &vecRight, &vecUp);
vecMuzzle = m_hOwner->GetOrigin() + vecDirection * 3 + Vector(0, 3, 0);
}
float flBeamWidth = 1.5;
Vector avecRayColors[] =
{
Vector(1, 0, 0),
Vector(0, 1, 0),
Vector(0, 0, 1),
};
float flRayRamp = RemapValClamped(GameServer()->GetGameTime() - GetSpawnTime(), 0.5, 1.5, 0, 1);
float flAlphaRamp = RemapValClamped(GameServer()->GetGameTime() - GetSpawnTime(), 1, 2, 1, 0);
size_t iBeams = 21;
for (size_t i = 0; i < iBeams; i++)
{
float flUp = RemapVal((float)i, 0, (float)iBeams, -flLength, flLength);
Vector vecRay = avecRayColors[i%3] * flRayRamp + Vector(1, 1, 1) * (1-flRayRamp);
Color clrRay = vecRay;
clrRay.SetAlpha((int)(200*flAlphaRamp));
r.SetColor(clrRay);
CRopeRenderer rope(DigitanksGame()->GetDigitanksRenderer(), s_iBeam, vecMuzzle, flBeamWidth);
rope.SetTextureOffset(((float)i/20) - GameServer()->GetGameTime() - GetSpawnTime());
rope.Finish(vecTarget + vecUp*flUp);
}
}
REGISTER_ENTITY(CInfantryLaser);
NETVAR_TABLE_BEGIN(CInfantryLaser);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CInfantryLaser);
SAVEDATA_TABLE_END();
<commit_msg>Fix crash<commit_after>#include "laser.h"
#include <geometry.h>
#include <digitanks/units/digitank.h>
#include <digitanks/digitanksgame.h>
#include <digitanks/dt_renderer.h>
size_t CLaser::s_iBeam = 0;
REGISTER_ENTITY(CLaser);
NETVAR_TABLE_BEGIN(CLaser);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CLaser);
SAVEDATA_TABLE_END();
void CLaser::Precache()
{
s_iBeam = CRenderer::LoadTextureIntoGL(L"textures/beam-pulse.png");
}
void CLaser::ClientSpawn()
{
BaseClass::ClientSpawn();
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin()) < 0.1f)
{
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin() + AngleVector(GetAngles())*LaserLength()) < 0.1f)
m_bShouldRender = false;
}
}
void CLaser::OnSetOwner(CDigitank* pOwner)
{
BaseClass::OnSetOwner(pOwner);
SetAngles(VectorAngles((pOwner->GetLastAim() - GetOrigin()).Normalized()));
SetOrigin(pOwner->GetOrigin());
SetSimulated(false);
SetVelocity(Vector(0,0,0));
SetGravity(Vector(0,0,0));
m_flTimeExploded = GameServer()->GetGameTime();
Vector vecForward, vecRight;
AngleVectors(GetAngles(), &vecForward, &vecRight, NULL);
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
if (!pEntity)
continue;
if (!pEntity->TakesDamage())
continue;
if (pEntity->GetTeam() == pOwner->GetTeam())
continue;
float flDistance = DistanceToPlane(pEntity->GetOrigin(), GetOrigin(), vecRight);
if (flDistance > 4 + pEntity->GetBoundingRadius())
continue;
// Cull objects behind
if (vecForward.Dot(pEntity->GetOrigin() - GetOrigin()) < 0)
continue;
if (pEntity->Distance(GetOrigin()) > LaserLength())
continue;
pEntity->TakeDamage(pOwner, this, DAMAGE_LASER, m_flDamage + pOwner->GetBonusAttackDamage(), flDistance < pEntity->GetBoundingRadius()-2);
CDigitank* pTank = dynamic_cast<CDigitank*>(pEntity);
if (pTank)
{
float flRockIntensity = 0.5f;
Vector vecDirection = (pTank->GetOrigin() - pOwner->GetOrigin()).Normalized();
pTank->RockTheBoat(flRockIntensity, vecDirection);
}
}
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin()) < 0.1f)
{
if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetVisibilityAtPoint(GetOrigin() + AngleVector(GetAngles())*LaserLength()) < 0.1f)
{
// If the start and end points are both in the fog of war, delete it now that we've aready done the damage so it doesn't get rendered later.
if (CNetwork::IsHost())
Delete();
}
}
}
void CLaser::PostRender(bool bTransparent)
{
BaseClass::PostRender(bTransparent);
if (!bTransparent)
return;
if (!m_bShouldRender)
return;
if (m_hOwner == NULL)
return;
CRenderingContext r(DigitanksGame()->GetDigitanksRenderer());
r.SetBlend(BLEND_ADDITIVE);
Vector vecForward, vecRight, vecUp;
float flLength = LaserLength();
Vector vecMuzzle = m_hOwner->GetOrigin();
Vector vecTarget = vecMuzzle + AngleVector(GetAngles()) * flLength;
if (m_hOwner != NULL)
{
Vector vecDirection = (m_hOwner->GetLastAim() - m_hOwner->GetOrigin()).Normalized();
vecTarget = vecMuzzle + vecDirection * flLength;
AngleVectors(VectorAngles(vecDirection), &vecForward, &vecRight, &vecUp);
vecMuzzle = m_hOwner->GetOrigin() + vecDirection * 3 + Vector(0, 3, 0);
}
float flBeamWidth = 1.5;
Vector avecRayColors[] =
{
Vector(1, 0, 0),
Vector(0, 1, 0),
Vector(0, 0, 1),
};
float flRayRamp = RemapValClamped(GameServer()->GetGameTime() - GetSpawnTime(), 0.5, 1.5, 0, 1);
float flAlphaRamp = RemapValClamped(GameServer()->GetGameTime() - GetSpawnTime(), 1, 2, 1, 0);
size_t iBeams = 21;
for (size_t i = 0; i < iBeams; i++)
{
float flUp = RemapVal((float)i, 0, (float)iBeams, -flLength, flLength);
Vector vecRay = avecRayColors[i%3] * flRayRamp + Vector(1, 1, 1) * (1-flRayRamp);
Color clrRay = vecRay;
clrRay.SetAlpha((int)(200*flAlphaRamp));
r.SetColor(clrRay);
CRopeRenderer rope(DigitanksGame()->GetDigitanksRenderer(), s_iBeam, vecMuzzle, flBeamWidth);
rope.SetTextureOffset(((float)i/20) - GameServer()->GetGameTime() - GetSpawnTime());
rope.Finish(vecTarget + vecUp*flUp);
}
}
REGISTER_ENTITY(CInfantryLaser);
NETVAR_TABLE_BEGIN(CInfantryLaser);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CInfantryLaser);
SAVEDATA_TABLE_END();
<|endoftext|> |
<commit_before><commit_msg>Use FilterHeaders() instead of HttpUtil::StripHeaders().<commit_after><|endoftext|> |
<commit_before>#include <x0/DebugLogger.h>
#include <x0/Tokenizer.h>
#include <x0/Buffer.h>
#include <cstdlib>
#include <cstdarg>
namespace x0 {
DebugLogger::Instance::Instance(DebugLogger* logger, const std::string& tag) :
logger_(logger),
tag_(tag),
enabled_(false),
verbosity_(1),
codes_(),
pre_(),
post_()
{
}
DebugLogger::Instance::~Instance()
{
}
void DebugLogger::Instance::enable()
{
enabled_ = true;
}
void DebugLogger::Instance::disable()
{
enabled_ = false;
}
void DebugLogger::Instance::setVerbosity(int value)
{
verbosity_ = value;
}
void DebugLogger::Instance::setPreference(const std::string& value)
{
static const struct {
int value;
const std::string name;
} codes[] = {
{ 1, "bold" },
{ 2, "faint"} ,
{ 3, "italic" },
{ 4, "underline" },
{ 5, "blink" },
{ 11, "font1" },
{ 12, "font2" },
{ 30, "black" },
{ 31, "red" },
{ 32, "green" },
{ 33, "yellow" },
{ 34, "blue" },
{ 35, "magenta" },
{ 36, "cyan" },
{ 37, "white" },
{ 40, "bg-black" },
{ 41, "bg-red" },
{ 42, "bg-green" },
{ 43, "bg-yellow" },
{ 44, "bg-blue" },
{ 45, "bg-magenta" },
{ 46, "bg-cyan" },
{ 47, "bg-white" },
};
bool found = false;
for (const auto& code: codes) {
if (value == code.name) {
codes_.push_back(code.value);
found = true;
break;
}
}
if (!found)
return;
// update ansii code strings
Buffer buf;
buf.push_back("\033[");
for (size_t i = 0; i < codes_.size(); ++i) {
if (likely(i))
buf.push_back(';');
buf.push_back(codes_[i]);
}
buf.push_back("m");
pre_ += buf.str();
if (post_.empty())
post_ = "\033[0m";
}
void DebugLogger::Instance::log(int level, const char* fmt, ...)
{
if (!enabled_)
return;
if (level > verbosity_)
return;
char msg[1024];
va_list va;
va_start(va, fmt);
vsnprintf(msg, sizeof(msg), fmt, va);
va_end(va);
if (logger_->colored()) {
Buffer buf;
buf.printf("%s[%s:%d] %s%s", pre_.c_str(), tag_.c_str(), level, msg, post_.c_str());
logger_->onLogWrite(buf.c_str(), buf.size());
} else {
Buffer buf;
buf.printf("[%s:%d] %s", tag_.c_str(), level, msg);
logger_->onLogWrite(buf.c_str(), buf.size());
}
}
void DebugLogger::Instance::logUntagged(int level, const char* fmt, ...)
{
if (!enabled_)
return;
if (level > verbosity_)
return;
char msg[1024];
va_list va;
va_start(va, fmt);
ssize_t n = vsnprintf(msg, sizeof(msg), fmt, va);
va_end(va);
if (logger_->colored()) {
Buffer buf;
buf.push_back(pre_);
buf.push_back(msg, n);
buf.push_back(post_);
logger_->onLogWrite(buf.c_str(), buf.size());
} else {
logger_->onLogWrite(msg, n);
}
}
void logWriteDefault(const char* msg, size_t n)
{
printf("%s\n", msg);
}
DebugLogger::DebugLogger() :
onLogWrite(std::bind(logWriteDefault, std::placeholders::_1, std::placeholders::_2)),
configured_(false),
map_(),
colored_(true)
{
}
DebugLogger::~DebugLogger()
{
reset();
}
// tagList ::= [tagSpec (':' tagSpec)*]
// tagSpec ::= TOKEN ('/' (VERBOSITY | COLOR))*
//
// "worker/3:director/10:connection:request/2"
// "worker/3/red:director/3/bight/green"
//
void DebugLogger::configure(const char* envvar)
{
if (!envvar || !*envvar)
return;
typedef Tokenizer<BufferRef> Tokenizer;
const char* envp = std::getenv(envvar);
if (!envp || !*envp)
return;
Buffer buf(envp);
auto tags = Tokenizer::tokenize(buf.ref(), ":");
for (const auto& tagSpec: tags) {
auto i = tagSpec.find('/');
if (i == Buffer::npos) {
enable(tagSpec.str().c_str());
} else { // tag
auto ref = tagSpec.ref(0, i);
auto str = ref.str();
auto instance = get(str.c_str());
instance->enable();
auto prefs = Tokenizer::tokenize(tagSpec.ref(i + 1), "/");
for (const auto& pref: prefs) {
if (!std::isdigit(pref[0])) {
instance->setPreference(pref.str());
} else {
instance->setVerbosity(pref.toInt());
}
}
}
}
configured_ = true;
}
void DebugLogger::reset()
{
configured_ = false;
onLogWrite = std::bind(logWriteDefault, std::placeholders::_1, std::placeholders::_2),
each([&](Instance* in) { delete in; });
map_.clear();
}
DebugLogger& DebugLogger::get()
{
static DebugLogger logger;
return logger;
}
void DebugLogger::enable(const std::string& tag)
{
get(tag)->enable();
}
void DebugLogger::disable(const std::string& tag)
{
get(tag)->disable();
}
void DebugLogger::enable()
{
each([&](Instance* dl) { dl->enable(); });
}
void DebugLogger::disable()
{
each([&](Instance* dl) { dl->disable(); });
}
} // namespace x0
<commit_msg>debug logger debug-logging; doh', an inseption<commit_after>#include <x0/DebugLogger.h>
#include <x0/Tokenizer.h>
#include <x0/Buffer.h>
#include <cstdlib>
#include <cstdarg>
#if 0
# define ITRACE(msg...) do { printf("DebugLogger(%s): ", tag_.c_str()); printf(msg); printf("\n"); } while (0)
#else
# define ITRACE(msg...) do {} while (0)
#endif
namespace x0 {
DebugLogger::Instance::Instance(DebugLogger* logger, const std::string& tag) :
logger_(logger),
tag_(tag),
enabled_(false),
verbosity_(1),
codes_(),
pre_(),
post_()
{
ITRACE("spawned");
}
DebugLogger::Instance::~Instance()
{
ITRACE("despawn");
}
void DebugLogger::Instance::enable()
{
enabled_ = true;
ITRACE("enable()");
}
void DebugLogger::Instance::disable()
{
enabled_ = false;
ITRACE("disable()");
}
void DebugLogger::Instance::setVerbosity(int value)
{
verbosity_ = value;
ITRACE("setVerbosity(%d)", value);
}
void DebugLogger::Instance::setPreference(const std::string& value)
{
ITRACE("setPreference(\"%s\")", value.c_str());
static const struct {
int value;
const std::string name;
} codes[] = {
{ 1, "bold" },
{ 2, "faint"} ,
{ 3, "italic" },
{ 4, "underline" },
{ 5, "blink" },
{ 11, "font1" },
{ 12, "font2" },
{ 30, "black" },
{ 31, "red" },
{ 32, "green" },
{ 33, "yellow" },
{ 34, "blue" },
{ 35, "magenta" },
{ 36, "cyan" },
{ 37, "white" },
{ 40, "bg-black" },
{ 41, "bg-red" },
{ 42, "bg-green" },
{ 43, "bg-yellow" },
{ 44, "bg-blue" },
{ 45, "bg-magenta" },
{ 46, "bg-cyan" },
{ 47, "bg-white" },
};
bool found = false;
for (const auto& code: codes) {
if (value == code.name) {
codes_.push_back(code.value);
found = true;
break;
}
}
if (!found)
return;
// update ansii code strings
Buffer buf;
buf.push_back("\033[");
for (size_t i = 0; i < codes_.size(); ++i) {
if (likely(i))
buf.push_back(';');
buf.push_back(codes_[i]);
}
buf.push_back("m");
pre_ += buf.str();
if (post_.empty())
post_ = "\033[0m";
}
void DebugLogger::Instance::log(int level, const char* fmt, ...)
{
ITRACE("log(level=%d); verbosity=%d, enabled=%d", level, verbosity_, enabled_);
if (!enabled_)
return;
if (level > verbosity_)
return;
char msg[1024];
va_list va;
va_start(va, fmt);
vsnprintf(msg, sizeof(msg), fmt, va);
va_end(va);
if (logger_->colored()) {
Buffer buf;
buf.printf("%s[%s:%d] %s%s", pre_.c_str(), tag_.c_str(), level, msg, post_.c_str());
logger_->onLogWrite(buf.c_str(), buf.size());
} else {
Buffer buf;
buf.printf("[%s:%d] %s", tag_.c_str(), level, msg);
logger_->onLogWrite(buf.c_str(), buf.size());
}
}
void DebugLogger::Instance::logUntagged(int level, const char* fmt, ...)
{
if (!enabled_)
return;
if (level > verbosity_)
return;
char msg[1024];
va_list va;
va_start(va, fmt);
ssize_t n = vsnprintf(msg, sizeof(msg), fmt, va);
va_end(va);
if (logger_->colored()) {
Buffer buf;
buf.push_back(pre_);
buf.push_back(msg, n);
buf.push_back(post_);
logger_->onLogWrite(buf.c_str(), buf.size());
} else {
logger_->onLogWrite(msg, n);
}
}
void logWriteDefault(const char* msg, size_t n)
{
printf("%s\n", msg);
}
DebugLogger::DebugLogger() :
onLogWrite(std::bind(logWriteDefault, std::placeholders::_1, std::placeholders::_2)),
configured_(false),
map_(),
colored_(true)
{
}
DebugLogger::~DebugLogger()
{
reset();
}
// tagList ::= [tagSpec (':' tagSpec)*]
// tagSpec ::= TOKEN ('/' (VERBOSITY | COLOR))*
//
// "worker/3:director/10:connection:request/2"
// "worker/3/red:director/3/bight/green"
//
void DebugLogger::configure(const char* envvar)
{
if (!envvar || !*envvar)
return;
typedef Tokenizer<BufferRef> Tokenizer;
const char* envp = std::getenv(envvar);
if (!envp || !*envp)
return;
Buffer buf(envp);
auto tags = Tokenizer::tokenize(buf.ref(), ":");
for (const auto& tagSpec: tags) {
auto i = tagSpec.find('/');
if (i == Buffer::npos) {
enable(tagSpec.str().c_str());
} else { // tag
auto ref = tagSpec.ref(0, i);
auto str = ref.str();
auto instance = get(str.c_str());
instance->enable();
auto prefs = Tokenizer::tokenize(tagSpec.ref(i + 1), "/");
for (const auto& pref: prefs) {
if (!std::isdigit(pref[0])) {
instance->setPreference(pref.str());
} else {
instance->setVerbosity(pref.toInt());
}
}
}
}
configured_ = true;
}
void DebugLogger::reset()
{
configured_ = false;
onLogWrite = std::bind(logWriteDefault, std::placeholders::_1, std::placeholders::_2),
each([&](Instance* in) { delete in; });
map_.clear();
}
DebugLogger& DebugLogger::get()
{
static DebugLogger logger;
return logger;
}
void DebugLogger::enable(const std::string& tag)
{
get(tag)->enable();
}
void DebugLogger::disable(const std::string& tag)
{
get(tag)->disable();
}
void DebugLogger::enable()
{
each([&](Instance* dl) { dl->enable(); });
}
void DebugLogger::disable()
{
each([&](Instance* dl) { dl->disable(); });
}
} // namespace x0
<|endoftext|> |
<commit_before>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/
#include "graphics.hpp"
#include <cstdio>
#ifdef _WIN32
#define APIENTRY __stdcall
#endif
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "cache.hpp"
#include "camera.hpp"
#include "entity.hpp"
#include "entitymanager.hpp"
#include "font.hpp"
#include "modelrenderer.hpp"
#include "rect2d.hpp"
#include "screen.hpp"
#include "shader.hpp"
#include "sprite.hpp"
#include "spriterenderer.hpp"
Graphics::Graphics(uint16_t width, uint16_t height, const char *title, int gl_major, int gl_minor)
{
Initialize(width, height, title, gl_major, gl_minor);
}
void Graphics::Initialize(uint16_t width, uint16_t height, const char *title, int gl_major, int gl_minor)
{
if (!m_Screen.CreateWindow(width, height, title, gl_major, gl_minor))
throw std::runtime_error("Error: could not create GLFW window");
if (!m_Screen.InitGL())
throw std::runtime_error("Error: could not initalize OpenGL");
}
std::string Graphics::GetType()
{
return "Graphics System";
}
void Graphics::AddRenderer(std::unique_ptr<IRenderer> &&renderer, std::type_index index)
{
m_Renderers[index] = std::move(renderer);
}
bool Graphics::LoadShaders(std::string name, std::string v, std::string f,
std::vector<std::string> attributes)
{
m_Shaders[name] = std::unique_ptr<Shader>(new Shader(v, f));
if (m_Shaders[name]->InitProgram() == false) {
printf("Warning: could not initialize shader: %s!\n",
name.c_str());
return false;
}
for (size_t i = 0; i < attributes.size(); i++)
m_Shaders[name]->AddAttribute(attributes[i]);
if (m_Shaders[name]->LinkProgram() == false) {
printf("Warning: could not link shader: %s!\n", name.c_str());
return false;
}
return true;
}
Shader *Graphics::GetShader(std::string name)
{
if (m_Shaders.find(name) != m_Shaders.end())
return m_Shaders[name].get();
else
printf("Warning: could not find shader %s\n", name.c_str());
return nullptr;
}
GLFWwindow *Graphics::GetWindow()
{
return m_Screen.GetWindow();
}
void Graphics::Execute(bool fixed)
{
if (fixed) {
for (auto &e: m_Entities)
e.second->GetComponent<Sprite>().Update();
return;
}
Clear();
for(auto &r: m_Renderers) {
auto &rend = r.second;
if (r.first == std::type_index(typeid(SpriteRenderer))) {
Rect2D floor = {0.0f, 680.0f, 1280.0f, 720.0f};
floor.SetColor(1.0f, 1.0f, 1.0f, 1.0f);
rend->SetCamera(&m_EM->GetEntity("Camera").GetComponent<Camera>());
rend->Begin();
for (auto &e: m_Entities) {
e.second->GetComponent<Sprite>().Update();
Renderable *temp = &e.second->GetComponent<Sprite>();
temp->Render();
rend->Draw(temp);
}
rend->Draw(&floor);
rend->DrawText("TidyEngine V0.2", glm::vec2(0.0f, 0.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), *Res.LoadFont("Acme-Regular.ttf"));
rend->End();
rend->Present();
}
if (r.first == std::type_index(typeid(ModelRenderer))) {
rend->SetCamera(&m_EM->GetEntity("Camera").GetComponent<Camera>());
Res.LoadModel("Models/char.obj")->Draw(GetShader("model"));
Res.LoadModel("Models/wallWindow.obj")->Draw(GetShader("model"));
rend->Present();
}
}
Present();
}
void Graphics::Clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Graphics::Present()
{
glfwSwapBuffers(m_Screen.GetWindow());
}
<commit_msg>Removed sprite update from render function<commit_after>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/
#include "graphics.hpp"
#include <cstdio>
#ifdef _WIN32
#define APIENTRY __stdcall
#endif
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "cache.hpp"
#include "camera.hpp"
#include "entity.hpp"
#include "entitymanager.hpp"
#include "font.hpp"
#include "modelrenderer.hpp"
#include "rect2d.hpp"
#include "screen.hpp"
#include "shader.hpp"
#include "sprite.hpp"
#include "spriterenderer.hpp"
Graphics::Graphics(uint16_t width, uint16_t height, const char *title, int gl_major, int gl_minor)
{
Initialize(width, height, title, gl_major, gl_minor);
}
void Graphics::Initialize(uint16_t width, uint16_t height, const char *title, int gl_major, int gl_minor)
{
if (!m_Screen.CreateWindow(width, height, title, gl_major, gl_minor))
throw std::runtime_error("Error: could not create GLFW window");
if (!m_Screen.InitGL())
throw std::runtime_error("Error: could not initalize OpenGL");
}
std::string Graphics::GetType()
{
return "Graphics System";
}
void Graphics::AddRenderer(std::unique_ptr<IRenderer> &&renderer, std::type_index index)
{
m_Renderers[index] = std::move(renderer);
}
bool Graphics::LoadShaders(std::string name, std::string v, std::string f,
std::vector<std::string> attributes)
{
m_Shaders[name] = std::unique_ptr<Shader>(new Shader(v, f));
if (m_Shaders[name]->InitProgram() == false) {
printf("Warning: could not initialize shader: %s!\n",
name.c_str());
return false;
}
for (size_t i = 0; i < attributes.size(); i++)
m_Shaders[name]->AddAttribute(attributes[i]);
if (m_Shaders[name]->LinkProgram() == false) {
printf("Warning: could not link shader: %s!\n", name.c_str());
return false;
}
return true;
}
Shader *Graphics::GetShader(std::string name)
{
if (m_Shaders.find(name) != m_Shaders.end())
return m_Shaders[name].get();
else
printf("Warning: could not find shader %s\n", name.c_str());
return nullptr;
}
GLFWwindow *Graphics::GetWindow()
{
return m_Screen.GetWindow();
}
void Graphics::Execute(bool fixed)
{
if (fixed) {
for (auto &e: m_Entities)
e.second->GetComponent<Sprite>().Update();
return;
}
Clear();
for(auto &r: m_Renderers) {
auto &rend = r.second;
if (r.first == std::type_index(typeid(SpriteRenderer))) {
Rect2D floor = {0.0f, 680.0f, 1280.0f, 720.0f};
floor.SetColor(1.0f, 1.0f, 1.0f, 1.0f);
rend->SetCamera(&m_EM->GetEntity("Camera").GetComponent<Camera>());
rend->Begin();
for (auto &e: m_Entities) {
Renderable *temp = &e.second->GetComponent<Sprite>();
temp->Render();
rend->Draw(temp);
}
rend->Draw(&floor);
rend->DrawText("TidyEngine V0.2", glm::vec2(0.0f, 0.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), *Res.LoadFont("Acme-Regular.ttf"));
rend->End();
rend->Present();
}
if (r.first == std::type_index(typeid(ModelRenderer))) {
rend->SetCamera(&m_EM->GetEntity("Camera").GetComponent<Camera>());
Res.LoadModel("Models/char.obj")->Draw(GetShader("model"));
Res.LoadModel("Models/wallWindow.obj")->Draw(GetShader("model"));
rend->Present();
}
}
Present();
}
void Graphics::Clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Graphics::Present()
{
glfwSwapBuffers(m_Screen.GetWindow());
}
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------------
// eca-logger.cpp: A logging subsystem implemented as a singleton class
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#include "kvu_locks.h"
#include "eca-logger-interface.h"
#include "eca-logger-default.h"
#include "eca-logger.h"
ECA_LOGGER_INTERFACE* ECA_LOGGER::interface_impl_repp = 0;
pthread_mutex_t ECA_LOGGER::lock_rep = PTHREAD_MUTEX_INITIALIZER;
ECA_LOGGER_INTERFACE& ECA_LOGGER::instance(void)
{
//
// Note! Below we use the Double-Checked Locking Pattern
// to protect against concurrent access
if (ECA_LOGGER::interface_impl_repp == 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp == 0) {
ECA_LOGGER::interface_impl_repp = new ECA_LOGGER_DEFAULT();
}
}
return(*interface_impl_repp);
}
void ECA_LOGGER::attach_logger(ECA_LOGGER_INTERFACE* logger)
{
int oldloglevel = -1;
if (interface_impl_repp != 0) {
interface_impl_repp->get_log_level_bitmask();
}
ECA_LOGGER::detach_logger();
if (ECA_LOGGER::interface_impl_repp == 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp == 0) {
ECA_LOGGER::interface_impl_repp = logger;
if (oldloglevel != -1) {
logger->set_log_level_bitmask(oldloglevel);
}
}
}
}
/**
* Detaches the current logger implementation.
*/
void ECA_LOGGER::detach_logger(void)
{
if (ECA_LOGGER::interface_impl_repp != 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp != 0) {
delete ECA_LOGGER::interface_impl_repp;
ECA_LOGGER::interface_impl_repp = 0;
}
}
}
<commit_msg>Really fix the wellformed-output and loglevels bug this time.<commit_after>// ------------------------------------------------------------------------
// eca-logger.cpp: A logging subsystem implemented as a singleton class
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#include <kvu_dbc.h>
#include <kvu_locks.h>
#include "eca-logger-interface.h"
#include "eca-logger-default.h"
#include "eca-logger.h"
ECA_LOGGER_INTERFACE* ECA_LOGGER::interface_impl_repp = 0;
pthread_mutex_t ECA_LOGGER::lock_rep = PTHREAD_MUTEX_INITIALIZER;
ECA_LOGGER_INTERFACE& ECA_LOGGER::instance(void)
{
//
// Note! Below we use the Double-Checked Locking Pattern
// to protect against concurrent access
if (ECA_LOGGER::interface_impl_repp == 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp == 0) {
ECA_LOGGER::interface_impl_repp = new ECA_LOGGER_DEFAULT();
}
}
return(*interface_impl_repp);
}
void ECA_LOGGER::attach_logger(ECA_LOGGER_INTERFACE* logger)
{
int oldloglevel = -1;
if (interface_impl_repp != 0) {
oldloglevel = interface_impl_repp->get_log_level_bitmask();
}
ECA_LOGGER::detach_logger();
if (ECA_LOGGER::interface_impl_repp == 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp == 0) {
ECA_LOGGER::interface_impl_repp = logger;
if (oldloglevel != -1) {
logger->set_log_level_bitmask(oldloglevel);
}
}
}
DBC_ENSURE(ECA_LOGGER::interface_impl_repp == logger);
}
/**
* Detaches the current logger implementation.
*/
void ECA_LOGGER::detach_logger(void)
{
if (ECA_LOGGER::interface_impl_repp != 0) {
KVU_GUARD_LOCK guard(&ECA_LOGGER::lock_rep);
if (ECA_LOGGER::interface_impl_repp != 0) {
delete ECA_LOGGER::interface_impl_repp;
ECA_LOGGER::interface_impl_repp = 0;
}
}
DBC_ENSURE(ECA_LOGGER::interface_impl_repp == 0);
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <algorithm>
#include "kms++.h"
#include "test.h"
#include "cmdoptions.h"
using namespace std;
using namespace kms;
static map<string, CmdOption> options = {
{ "m", HAS_PARAM("Set display mode, for example 1920x1080") },
};
int main(int argc, char **argv)
{
Card card;
CmdOptions opts(argc, argv, options);
if (card.master() == false)
printf("Not DRM master, modeset may fail\n");
auto pipes = card.get_connected_pipelines();
vector<Framebuffer*> fbs;
for (auto pipe : pipes)
{
auto conn = pipe.connector;
auto crtc = pipe.crtc;
// RG16 XR24 UYVY YUYV NV12
auto mode = conn->get_default_mode();
if (opts.is_set("m"))
mode = conn->get_mode(opts.opt_param("m"));
auto fb = new DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, PixelFormat::XRGB8888);
draw_test_pattern(*fb);
fbs.push_back(fb);
printf("conn %u, crtc %u, fb %u\n", conn->id(), crtc->id(), fb->id());
int r = crtc->set_mode(conn, *fb, mode);
ASSERT(r == 0);
}
for (auto pipe: pipes)
{
auto crtc = pipe.crtc;
Plane* plane = 0;
for (Plane* p : crtc->get_possible_planes()) {
if (p->plane_type() == PlaneType::Overlay) {
plane = p;
break;
}
}
if (plane) {
auto planefb = new DumbFramebuffer(card, 400, 400, PixelFormat::YUYV);
draw_test_pattern(*planefb);
fbs.push_back(planefb);
int r = crtc->set_plane(plane, *planefb,
0, 0, planefb->width(), planefb->height(),
0, 0, planefb->width(), planefb->height());
ASSERT(r == 0);
}
}
printf("press enter to exit\n");
getchar();
for(auto fb : fbs)
delete fb;
}
<commit_msg>testpat: big rewrite<commit_after>#include <cstdio>
#include <algorithm>
#include <regex>
#include <set>
#include "kms++.h"
#include "test.h"
#include "opts.h"
using namespace std;
using namespace kms;
struct PlaneInfo
{
Plane* plane;
unsigned x;
unsigned y;
unsigned w;
unsigned h;
DumbFramebuffer* fb;
};
struct OutputInfo
{
Connector* connector;
Crtc* crtc;
Videomode mode;
bool user_set_crtc;
DumbFramebuffer* fb;
vector<PlaneInfo> planes;
};
static set<Crtc*> s_used_crtcs;
static set<Plane*> s_used_planes;
__attribute__ ((unused))
static void print_regex_match(smatch sm)
{
for (unsigned i = 0; i < sm.size(); ++i) {
string str = sm[i].str();
printf("%u: %s\n", i, str.c_str());
}
}
static void get_default_connector(Card& card, OutputInfo& output)
{
output.connector = card.get_first_connected_connector();
output.mode = output.connector->get_default_mode();
}
static void parse_connector(Card& card, const string& str, OutputInfo& output)
{
Connector* conn = nullptr;
auto connectors = card.get_connectors();
if (str[0] == '@') {
char* endptr;
unsigned idx = strtoul(str.c_str() + 1, &endptr, 10);
if (*endptr == 0) {
if (idx >= connectors.size())
EXIT("Bad connector number '%u'", idx);
conn = connectors[idx];
}
} else {
char* endptr;
unsigned id = strtoul(str.c_str(), &endptr, 10);
if (*endptr == 0) {
Connector* c = card.get_connector(id);
if (!c)
EXIT("Bad connector id '%u'", id);
conn = c;
}
}
if (!conn) {
auto iter = find_if(connectors.begin(), connectors.end(), [&str](Connector *c) { return c->fullname() == str; });
if (iter != connectors.end())
conn = *iter;
}
if (!conn)
EXIT("No connector '%s'", str.c_str());
if (!conn->connected())
EXIT("Connector '%s' not connected", conn->fullname().c_str());
output.connector = conn;
output.mode = output.connector->get_default_mode();
}
static void get_default_crtc(Card& card, OutputInfo& output)
{
Crtc* crtc = output.connector->get_current_crtc();
if (crtc && s_used_crtcs.find(crtc) == s_used_crtcs.end()) {
s_used_crtcs.insert(crtc);
output.crtc = crtc;
return;
}
for (const auto& possible : output.connector->get_possible_crtcs()) {
if (s_used_crtcs.find(possible) == s_used_crtcs.end()) {
s_used_crtcs.insert(possible);
output.crtc = possible;
return;
}
}
EXIT("Could not find available crtc");
}
static void parse_crtc(Card& card, const string& crtc_str, OutputInfo& output)
{
// @12:1920x1200-60
const regex mode_re("(?:(@?)(\\d+):)?(?:(\\d+)x(\\d+))(?:-(\\d+))?");
smatch sm;
if (!regex_match(crtc_str, sm, mode_re))
EXIT("Failed to parse crtc option '%s'", crtc_str.c_str());
if (sm[2].matched) {
bool use_idx = sm[1].length() == 1;
unsigned num = stoul(sm[2].str());
if (use_idx) {
auto crtcs = card.get_crtcs();
if (num >= crtcs.size())
EXIT("Bad crtc number '%u'", num);
output.crtc = crtcs[num];
} else {
Crtc* c = card.get_crtc(num);
if (!c)
EXIT("Bad crtc id '%u'", num);
output.crtc = c;
}
} else {
output.crtc = output.connector->get_current_crtc();
}
unsigned w = stoul(sm[3]);
unsigned h = stoul(sm[4]);
unsigned refresh = 0;
if (sm[5].matched)
refresh = stoul(sm[5]);
output.mode = output.connector->get_mode(w, h, refresh);
}
static void parse_plane(Card& card, const string& plane_str, const OutputInfo& output, PlaneInfo& pinfo)
{
// 3:400,400-400x400
const regex plane_re("(?:(@?)(\\d+):)?(?:(\\d+),(\\d+)-)?(\\d+)x(\\d+)");
smatch sm;
if (!regex_match(plane_str, sm, plane_re))
EXIT("Failed to parse plane option '%s'", plane_str.c_str());
if (sm[2].matched) {
bool use_idx = sm[1].length() == 1;
unsigned num = stoul(sm[2].str());
if (use_idx) {
auto planes = card.get_planes();
if (num >= planes.size())
EXIT("Bad plane number '%u'", num);
pinfo.plane = planes[num];
} else {
Plane* p = card.get_plane(num);
if (!p)
EXIT("Bad plane id '%u'", num);
pinfo.plane = p;
}
} else {
for (Plane* p : output.crtc->get_possible_planes()) {
if (s_used_planes.find(p) != s_used_planes.end())
continue;
if (p->plane_type() != PlaneType::Overlay)
continue;
pinfo.plane = p;
}
if (!pinfo.plane)
EXIT("Failed to find available plane");
}
s_used_planes.insert(pinfo.plane);
pinfo.w = stoul(sm[5]);
pinfo.h = stoul(sm[6]);
if (sm[3].matched)
pinfo.x = stoul(sm[3]);
else
pinfo.x = output.mode.hdisplay / 2 - pinfo.w / 2;
if (sm[4].matched)
pinfo.y = stoul(sm[4]);
else
pinfo.y = output.mode.vdisplay / 2 - pinfo.h / 2;
}
static DumbFramebuffer* get_default_fb(Card& card, unsigned width, unsigned height)
{
auto fb = new DumbFramebuffer(card, width, height, PixelFormat::XRGB8888);
draw_test_pattern(*fb);
return fb;
}
static DumbFramebuffer* parse_fb(Card& card, const string& fb_str, unsigned def_w, unsigned def_h)
{
unsigned w = def_w;
unsigned h = def_h;
PixelFormat format = PixelFormat::XRGB8888;
if (!fb_str.empty()) {
// XXX the regexp is not quite correct
// 400x400-NV12
const regex fb_re("(?:(\\d+)x(\\d+))?(?:-)?(\\w\\w\\w\\w)?");
smatch sm;
if (!regex_match(fb_str, sm, fb_re))
EXIT("Failed to parse fb option '%s'", fb_str.c_str());
if (sm[1].matched)
w = stoul(sm[1]);
if (sm[2].matched)
h = stoul(sm[2]);
if (sm[3].matched)
format = FourCCToPixelFormat(sm[3]);
}
auto fb = new DumbFramebuffer(card, w, h, format);
draw_test_pattern(*fb);
return fb;
}
static const char* usage_str =
"Usage: testpat [OPTION]...\n\n"
"Show a test pattern on a display or plane\n\n"
"Options:\n"
" --device=DEVICE DEVICE is the path to DRM card to open\n"
" -c, --connector=CONN CONN is <connector>\n"
" -r, --crtc=CRTC CRTC is [<crtc>:]<w>x<h>[@<Hz>]\n"
" -p, --plane=PLANE PLANE is [<plane>:][<x>,<y>-]<w>x<h>\n"
" -f, --fb=FB FB is [<w>x<h>][-][<4cc>]\n"
"\n"
"<connector>, <crtc> and <plane> can be given by id (<id>) or index (@<idx>).\n"
"<connector> can also be given by name.\n"
"\n"
"Options can be given multiple times to set up multiple displays or planes.\n"
"Options may apply to previous options, e.g. a plane will be set on a crtc set in\n"
"an earlier option.\n"
"If you omit parameters, testpat tries to guess what you mean\n"
"\n"
"Examples:\n"
"\n"
"Set eDP-1 mode to 1920x1080@60, show XR24 framebuffer on the crtc, and a 400x400 XB24 plane:\n"
" testpat -c eDP-1 -r 1920x1080@60 -f XR24 -p 400x400 -f XB24\n\n"
"XR24 framebuffer on first connected connector in the default mode:\n"
" testpat -f XR24\n\n"
"XR24 framebuffer on a 400x400 plane on the first connected connector in the default mode:\n"
" testpat -p 400x400 -f XR24\n\n"
"Test pattern on the second connector with default mode:\n"
" testpat -c @1\n"
;
static void usage()
{
puts(usage_str);
}
enum class ObjectType
{
Connector,
Crtc,
Plane,
Framebuffer,
};
struct Arg
{
ObjectType type;
string arg;
};
static string s_device_path = "/dev/dri/card0";
static vector<Arg> parse_cmdline(int argc, char **argv)
{
vector<Arg> args;
OptionSet optionset = {
Option("|device=",
[&](string s)
{
s_device_path = s;
}),
Option("c|connector=",
[&](string s)
{
args.push_back(Arg { ObjectType::Connector, s });
}),
Option("r|crtc=", [&](string s)
{
args.push_back(Arg { ObjectType::Crtc, s });
}),
Option("p|plane=", [&](string s)
{
args.push_back(Arg { ObjectType::Plane, s });
}),
Option("f|fb=", [&](string s)
{
args.push_back(Arg { ObjectType::Framebuffer, s });
}),
Option("h|help", [&]()
{
usage();
exit(-1);
}),
};
optionset.parse(argc, argv);
if (optionset.params().size() > 0) {
usage();
exit(-1);
}
return args;
}
static vector<OutputInfo> setups_to_outputs(Card& card, const vector<Arg>& output_args)
{
vector<OutputInfo> outputs;
if (output_args.size() == 0) {
// no output args, show a pattern on all screens
for (auto& pipe : card.get_connected_pipelines()) {
OutputInfo output = { };
output.connector = pipe.connector;
output.crtc = pipe.crtc;
output.mode = output.connector->get_default_mode();
output.fb = get_default_fb(card, output.mode.hdisplay, output.mode.vdisplay);
outputs.push_back(output);
}
return outputs;
}
OutputInfo* current_output = 0;
PlaneInfo* current_plane = 0;
for (auto& arg : output_args) {
switch (arg.type) {
case ObjectType::Connector:
{
outputs.push_back(OutputInfo { });
current_output = &outputs.back();
parse_connector(card, arg.arg, *current_output);
current_plane = 0;
break;
}
case ObjectType::Crtc:
{
if (!current_output) {
outputs.push_back(OutputInfo { });
current_output = &outputs.back();
}
if (!current_output->connector)
get_default_connector(card, *current_output);
parse_crtc(card, arg.arg, *current_output);
current_output->user_set_crtc = true;
current_plane = 0;
break;
}
case ObjectType::Plane:
{
if (!current_output) {
outputs.push_back(OutputInfo { });
current_output = &outputs.back();
}
if (!current_output->connector)
get_default_connector(card, *current_output);
if (!current_output->crtc)
get_default_crtc(card, *current_output);
current_output->planes.push_back(PlaneInfo { });
current_plane = ¤t_output->planes.back();
parse_plane(card, arg.arg, *current_output, *current_plane);
break;
}
case ObjectType::Framebuffer:
{
if (!current_output) {
outputs.push_back(OutputInfo { });
current_output = &outputs.back();
}
if (!current_output->connector)
get_default_connector(card, *current_output);
if (!current_output->crtc)
get_default_crtc(card, *current_output);
int def_w, def_h;
if (current_plane) {
def_w = current_plane->w;
def_h = current_plane->h;
} else {
def_w = current_output->mode.hdisplay;
def_h = current_output->mode.vdisplay;
}
auto fb = parse_fb(card, arg.arg, def_w, def_h);
if (current_plane)
current_plane->fb = fb;
else
current_output->fb = fb;
break;
}
}
}
// create default framebuffers if needed
for (OutputInfo& o : outputs) {
if (!o.crtc) {
get_default_crtc(card, *current_output);
o.user_set_crtc = true;
}
if (!o.fb && o.user_set_crtc)
o.fb = get_default_fb(card, o.mode.hdisplay, o.mode.vdisplay);
for (PlaneInfo &p : o.planes) {
if (!p.fb)
p.fb = get_default_fb(card, p.w, p.h);
}
}
return outputs;
}
static std::string videomode_to_string(const Videomode& mode)
{
unsigned hfp, hsw, hbp;
unsigned vfp, vsw, vbp;
hfp = mode.hsync_start - mode.hdisplay;
hsw = mode.hsync_end - mode.hsync_start;
hbp = mode.htotal - mode.hsync_end;
vfp = mode.vsync_start - mode.vdisplay;
vsw = mode.vsync_end - mode.vsync_start;
vbp = mode.vtotal - mode.vsync_end;
char buf[256];
sprintf(buf, "%.2f MHz %u/%u/%u/%u %u/%u/%u/%u %uHz",
mode.clock / 1000.0,
mode.hdisplay, hfp, hsw, hbp,
mode.vdisplay, vfp, vsw, vbp,
mode.vrefresh);
return std::string(buf);
}
static void print_outputs(const vector<OutputInfo>& outputs)
{
for (unsigned i = 0; i < outputs.size(); ++i) {
const OutputInfo& o = outputs[i];
printf("Connector %u/@%u: %s\n", o.connector->id(), o.connector->idx(),
o.connector->fullname().c_str());
printf(" Crtc %u/@%u: %ux%u-%u (%s)\n", o.crtc->id(), o.crtc->idx(),
o.mode.hdisplay, o.mode.vdisplay, o.mode.vrefresh,
videomode_to_string(o.mode).c_str());
if (o.fb)
printf(" Fb %ux%u-%s\n", o.fb->width(), o.fb->height(),
PixelFormatToFourCC(o.fb->format()).c_str());
for (unsigned j = 0; j < o.planes.size(); ++j) {
const PlaneInfo& p = o.planes[j];
printf(" Plane %u/@%u: %u,%u-%ux%u\n", p.plane->id(), p.plane->idx(),
p.x, p.y, p.w, p.h);
printf(" Fb %ux%u-%s\n", p.fb->width(), p.fb->height(),
PixelFormatToFourCC(p.fb->format()).c_str());
}
}
}
static void set_crtcs_n_planes(Card& card, const vector<OutputInfo>& outputs)
{
for (const OutputInfo& o : outputs) {
auto conn = o.connector;
auto crtc = o.crtc;
if (o.fb) {
int r = crtc->set_mode(conn, *o.fb, o.mode);
if (r)
printf("crtc->set_mode() failed for crtc %u: %s\n",
crtc->id(), strerror(-r));
}
for (const PlaneInfo& p : o.planes) {
int r = crtc->set_plane(p.plane, *p.fb,
p.x, p.y, p.w, p.h,
0, 0, p.fb->width(), p.fb->height());
if (r)
printf("crtc->set_plane() failed for plane %u: %s\n",
p.plane->id(), strerror(-r));
}
}
}
int main(int argc, char **argv)
{
vector<Arg> output_args = parse_cmdline(argc, argv);
Card card(s_device_path);
vector<OutputInfo> outputs = setups_to_outputs(card, output_args);
print_outputs(outputs);
set_crtcs_n_planes(card, outputs);
printf("press enter to exit\n");
getchar();
}
<|endoftext|> |
<commit_before>#include "Suite.h"
#include <list>
#include <functional>
#include <iostream>
#include <string>
void Test::Suite::addTest(string description, function<void()> test)
{
Test::Case c;
c = test;
c.describe(description);
tests_.push_back(c);
}
void Test::Suite::addTest(function<void()> test)
{
Test::Case c;
c = test;
tests_.push_back(c);
}
void Test::Suite::addTest(Test::Case testCase)
{
tests_.push_back(testCase);
}
bool Test::Suite::runTests(ostream& o)
{
// change this to false if any tests fail
bool didItPass = true;
for (list<Case>::iterator it = tests_.begin();
it != tests_.end();
it++)
{
try
{
o << it->describe() << ": ";
(*it)();
}
catch (string msg)
{
o << "FAIL" << endl;
o << " Assert \"" << msg << "\" is false." << endl;
didItPass = false; // no it didn't
continue; // don't print PASS
}
o << "PASS" << endl;
}
o << description_ << ": " << (didItPass ? "PASS" : "FAIL") << endl;
}
void Test::Suite::describe(string description)
{
description_ = description;
}
string Test::Suite::describe()
{
return description_;
}
bool Test::Suite::assert(bool expression, string description)
{
if (!expression)
{
throw description;
}
return true;
}
<commit_msg>Document the Suite::runTests() method<commit_after>#include "Suite.h"
#include <list>
#include <functional>
#include <iostream>
#include <string>
void Test::Suite::addTest(string description, function<void()> test)
{
Test::Case c;
c = test;
c.describe(description);
tests_.push_back(c);
}
void Test::Suite::addTest(function<void()> test)
{
Test::Case c;
c = test;
tests_.push_back(c);
}
void Test::Suite::addTest(Test::Case testCase)
{
tests_.push_back(testCase);
}
bool Test::Suite::runTests(ostream& o)
{
// change this to false if any tests fail
bool didItPass = true;
for (list<Case>::iterator it = tests_.begin();
it != tests_.end();
it++)
{
// Below is a try/catch loop. If a test fails, it will throw a string.
// Catch that string as "msg", and give some output to the user.
// Print PASS to the ostream if it passes, and FAIL if it fails.
try
{
o << it->describe() << ": ";
(*it)();
}
catch (string msg)
{
o << "FAIL" << endl;
o << " Assert \"" << msg << "\" is false." << endl;
didItPass = false; // no it didn't
continue; // don't print PASS
}
o << "PASS" << endl;
} // end for loop
// Now print to the user whether the Suite as a whole passed or failed.
o << description_ << ": " << (didItPass ? "PASS" : "FAIL") << endl;
}
void Test::Suite::describe(string description)
{
description_ = description;
}
string Test::Suite::describe()
{
return description_;
}
bool Test::Suite::assert(bool expression, string description)
{
if (!expression)
{
throw description;
}
return true;
}
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Maintainer: joaander
/*! \file Profiler.cc
\brief Defines the Profiler class
*/
#include <iomanip>
#include <sstream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "Profiler.h"
#include <boost/python.hpp>
using namespace boost::python;
using namespace std;
////////////////////////////////////////////////////
// ProfileDataElem members
int64_t ProfileDataElem::getChildElapsedTime() const
{
// start counting the elapsed time from our time
int64_t total = 0;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.m_elapsed_time;
}
// return the total
return total;
}
int64_t ProfileDataElem::getTotalFlopCount() const
{
// start counting the elapsed time from our time
int64_t total = m_flop_count;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.getTotalFlopCount();
}
// return the total
return total;
}
int64_t ProfileDataElem::getTotalMemByteCount() const
{
// start counting the elapsed time from our time
int64_t total = m_mem_byte_count;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.getTotalMemByteCount();
}
// return the total
return total;
}
/*! Recursive output routine to write results from this profile node and all sub nodes printed in
a tree.
\param o stream to write output to
\param name Name of the node
\param tab_level Current number of tabs in the tree
\param total_time Total number of nanoseconds taken by this node
\param name_width Maximum name width for all siblings of this node (used to align output columns)
*/
void ProfileDataElem::output(std::ostream &o, const std::string& name, int tab_level, int64_t total_time, int name_width) const
{
// create a tab string to output for the current tab level
string tabs = "";
for (int i = 0; i < tab_level; i++)
tabs += " ";
o << tabs;
// start with an overview
// initial tests determined that having a parent node calculate the avg gflops of its
// children is annoying, so default to 0 flops&bytes unless we are a leaf
double sec = double(m_elapsed_time)/1e9;
double perc = double(m_elapsed_time)/double(total_time) * 100.0;
double flops = 0.0;
double bytes = 0.0;
if (m_children.size() == 0)
{
flops = double(getTotalFlopCount())/sec;
bytes = double(getTotalMemByteCount())/sec;
}
output_line(o, name, sec, perc, flops, bytes, name_width);
// start by determining the name width
map<string, ProfileDataElem>::const_iterator i;
// it has at least to be four letters wide ("Self")
int child_max_width = 4;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
int child_width = (int)(*i).first.size();
if (child_width > child_max_width)
child_max_width = child_width;
}
// output each of the children
for (i = m_children.begin(); i != m_children.end(); ++i)
{
(*i).second.output(o, (*i).first, tab_level+1, total_time, child_max_width);
}
// output an "Self" item to account for time actually spent in this data elem
if (m_children.size() > 0)
{
double sec = double(m_elapsed_time - getChildElapsedTime())/1e9;
double perc = double(m_elapsed_time - getChildElapsedTime())/double(total_time) * 100.0;
double flops = double(m_flop_count)/sec;
double bytes = double(m_mem_byte_count)/sec;
// don't print Self unless perc is significant
if (perc >= 0.1)
{
o << tabs << " ";
output_line(o, "Self", sec, perc, flops, bytes, child_max_width);
}
}
}
void ProfileDataElem::output_line(std::ostream &o,
const std::string &name,
double sec,
double perc,
double flops,
double bytes,
unsigned int name_width) const
{
o << setiosflags(ios::fixed);
o << name << ": ";
assert(name_width >= name.size());
for (unsigned int i = 0; i < name_width - name.size(); i++)
o << " ";
o << setw(7) << setprecision(1) << sec << "s";
o << " | " << setprecision(1) << setw(3) << perc << "% ";
//If sec is zero, the values to be printed are garbage. Thus, we skip it all together.
if (sec == 0)
{
o << "n/a" << endl;
return;
}
o << setprecision(2);
// output flops with intelligent units
if (flops > 0)
{
o << setw(6);
if (flops < 1e6)
o << flops << " FLOP/s ";
else if (flops < 1e9)
o << flops/1e6 << " MFLOP/s ";
else
o << flops/1e9 << " GFLOP/s ";
}
//output bytes/s with intelligent units
if (bytes > 0)
{
o << setw(6);
if (bytes < 1e6)
o << bytes << " B/s ";
else if (bytes < 1e9)
o << bytes/1e6 << " MiB/s ";
else
o << bytes/1e9 << " GiB/s ";
}
o << endl;
}
////////////////////////////////////////////////////////////////////
// Profiler
Profiler::Profiler(const std::string& name) : m_name(name)
{
// push the root onto the top of the stack so that it is the default
m_stack.push(&m_root);
// record the start of this profile
m_root.m_start_time = m_clk.getTime();
#ifdef SCOREP_USER_ENABLE
SCOREP_USER_REGION_BEGIN(m_root.m_scorep_region, name.c_str(),SCOREP_USER_REGION_TYPE_COMMON )
#endif
}
void Profiler::output(std::ostream &o)
{
// perform a sanity check, but don't bail out
if (m_stack.top() != &m_root)
{
o << "***Warning! Outputting a profile with incomplete samples" << endl;
}
#ifdef SCOREP_USER_ENABLE
SCOREP_USER_REGION_END( m_root.m_scorep_region )
#endif
// outputting a profile implicitly calls for a time sample
m_root.m_elapsed_time = m_clk.getTime() - m_root.m_start_time;
// startup the recursive output process
m_root.output(o, m_name, 0, m_root.m_elapsed_time, (int)m_name.size());
}
/*! \param o Stream to output to
\param prof Profiler to print
*/
std::ostream& operator<<(ostream &o, Profiler& prof)
{
prof.output(o);
return o;
}
//! Helper function to get the formatted output of a Profiler in python
/*! Outputs the profiler timings to a string
\param prof Profiler to generate output from
*/
string print_profiler(Profiler *prof)
{
assert(prof);
ostringstream s;
s << *prof;
return s.str();
}
void export_Profiler()
{
class_<Profiler>("Profiler", init<const std::string&>())
.def("__str__", &print_profiler)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>Increase number of digits in the profiler output<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Maintainer: joaander
/*! \file Profiler.cc
\brief Defines the Profiler class
*/
#include <iomanip>
#include <sstream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "Profiler.h"
#include <boost/python.hpp>
using namespace boost::python;
using namespace std;
////////////////////////////////////////////////////
// ProfileDataElem members
int64_t ProfileDataElem::getChildElapsedTime() const
{
// start counting the elapsed time from our time
int64_t total = 0;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.m_elapsed_time;
}
// return the total
return total;
}
int64_t ProfileDataElem::getTotalFlopCount() const
{
// start counting the elapsed time from our time
int64_t total = m_flop_count;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.getTotalFlopCount();
}
// return the total
return total;
}
int64_t ProfileDataElem::getTotalMemByteCount() const
{
// start counting the elapsed time from our time
int64_t total = m_mem_byte_count;
// for each of the children
map<string, ProfileDataElem>::const_iterator i;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
// add their time
total += (*i).second.getTotalMemByteCount();
}
// return the total
return total;
}
/*! Recursive output routine to write results from this profile node and all sub nodes printed in
a tree.
\param o stream to write output to
\param name Name of the node
\param tab_level Current number of tabs in the tree
\param total_time Total number of nanoseconds taken by this node
\param name_width Maximum name width for all siblings of this node (used to align output columns)
*/
void ProfileDataElem::output(std::ostream &o, const std::string& name, int tab_level, int64_t total_time, int name_width) const
{
// create a tab string to output for the current tab level
string tabs = "";
for (int i = 0; i < tab_level; i++)
tabs += " ";
o << tabs;
// start with an overview
// initial tests determined that having a parent node calculate the avg gflops of its
// children is annoying, so default to 0 flops&bytes unless we are a leaf
double sec = double(m_elapsed_time)/1e9;
double perc = double(m_elapsed_time)/double(total_time) * 100.0;
double flops = 0.0;
double bytes = 0.0;
if (m_children.size() == 0)
{
flops = double(getTotalFlopCount())/sec;
bytes = double(getTotalMemByteCount())/sec;
}
output_line(o, name, sec, perc, flops, bytes, name_width);
// start by determining the name width
map<string, ProfileDataElem>::const_iterator i;
// it has at least to be four letters wide ("Self")
int child_max_width = 4;
for (i = m_children.begin(); i != m_children.end(); ++i)
{
int child_width = (int)(*i).first.size();
if (child_width > child_max_width)
child_max_width = child_width;
}
// output each of the children
for (i = m_children.begin(); i != m_children.end(); ++i)
{
(*i).second.output(o, (*i).first, tab_level+1, total_time, child_max_width);
}
// output an "Self" item to account for time actually spent in this data elem
if (m_children.size() > 0)
{
double sec = double(m_elapsed_time - getChildElapsedTime())/1e9;
double perc = double(m_elapsed_time - getChildElapsedTime())/double(total_time) * 100.0;
double flops = double(m_flop_count)/sec;
double bytes = double(m_mem_byte_count)/sec;
// don't print Self unless perc is significant
if (perc >= 0.1)
{
o << tabs << " ";
output_line(o, "Self", sec, perc, flops, bytes, child_max_width);
}
}
}
void ProfileDataElem::output_line(std::ostream &o,
const std::string &name,
double sec,
double perc,
double flops,
double bytes,
unsigned int name_width) const
{
o << setiosflags(ios::fixed);
o << name << ": ";
assert(name_width >= name.size());
for (unsigned int i = 0; i < name_width - name.size(); i++)
o << " ";
o << setw(7) << setprecision(4) << sec << "s";
o << " | " << setprecision(3) << setw(6) << perc << "% ";
//If sec is zero, the values to be printed are garbage. Thus, we skip it all together.
if (sec == 0)
{
o << "n/a" << endl;
return;
}
o << setprecision(5);
// output flops with intelligent units
if (flops > 0)
{
o << setw(6);
if (flops < 1e6)
o << flops << " FLOP/s ";
else if (flops < 1e9)
o << flops/1e6 << " MFLOP/s ";
else
o << flops/1e9 << " GFLOP/s ";
}
//output bytes/s with intelligent units
if (bytes > 0)
{
o << setw(6);
if (bytes < 1e6)
o << bytes << " B/s ";
else if (bytes < 1e9)
o << bytes/1e6 << " MiB/s ";
else
o << bytes/1e9 << " GiB/s ";
}
o << endl;
}
////////////////////////////////////////////////////////////////////
// Profiler
Profiler::Profiler(const std::string& name) : m_name(name)
{
// push the root onto the top of the stack so that it is the default
m_stack.push(&m_root);
// record the start of this profile
m_root.m_start_time = m_clk.getTime();
#ifdef SCOREP_USER_ENABLE
SCOREP_USER_REGION_BEGIN(m_root.m_scorep_region, name.c_str(),SCOREP_USER_REGION_TYPE_COMMON )
#endif
}
void Profiler::output(std::ostream &o)
{
// perform a sanity check, but don't bail out
if (m_stack.top() != &m_root)
{
o << "***Warning! Outputting a profile with incomplete samples" << endl;
}
#ifdef SCOREP_USER_ENABLE
SCOREP_USER_REGION_END( m_root.m_scorep_region )
#endif
// outputting a profile implicitly calls for a time sample
m_root.m_elapsed_time = m_clk.getTime() - m_root.m_start_time;
// startup the recursive output process
m_root.output(o, m_name, 0, m_root.m_elapsed_time, (int)m_name.size());
}
/*! \param o Stream to output to
\param prof Profiler to print
*/
std::ostream& operator<<(ostream &o, Profiler& prof)
{
prof.output(o);
return o;
}
//! Helper function to get the formatted output of a Profiler in python
/*! Outputs the profiler timings to a string
\param prof Profiler to generate output from
*/
string print_profiler(Profiler *prof)
{
assert(prof);
ostringstream s;
s << *prof;
return s.str();
}
void export_Profiler()
{
class_<Profiler>("Profiler", init<const std::string&>())
.def("__str__", &print_profiler)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|> |
<commit_before>/*
This file is part of libkcal.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <typeinfo>
#include <stdlib.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/job.h>
#include <kstandarddirs.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"
#include <kresources/resourceconfigwidget.h>
#include "resourceremoteconfig.h"
#include "resourceremote.h"
using namespace KCal;
extern "C"
{
KRES::ResourceConfigWidget *config_widget( QWidget *parent ) {
return new ResourceRemoteConfig( parent, "Configure Remote Calendar" );
}
KRES::Resource *resource( const KConfig *config ) {
return new ResourceRemote( config );
}
}
ResourceRemote::ResourceRemote( const KConfig* config )
: ResourceCalendar( config )
{
if ( config ) {
readConfig( config );
}
init();
}
ResourceRemote::ResourceRemote( const KURL &downloadUrl, const KURL &uploadUrl )
: ResourceCalendar( 0 )
{
mDownloadUrl = downloadUrl;
if ( uploadUrl.isEmpty() ) {
mUploadUrl = mDownloadUrl;
} else {
mUploadUrl = uploadUrl;
}
init();
}
ResourceRemote::~ResourceRemote()
{
close();
if ( mDownloadJob ) mDownloadJob->kill();
if ( mUploadJob ) mUploadJob->kill();
}
void ResourceRemote::init()
{
mDownloadJob = 0;
mUploadJob = 0;
setType( "remote" );
mOpen = false;
}
void ResourceRemote::readConfig( const KConfig *config )
{
QString url = config->readEntry( "DownloadUrl" );
mDownloadUrl = KURL( url );
url = config->readEntry( "UploadUrl" );
mUploadUrl = KURL( url );
}
void ResourceRemote::writeConfig( KConfig *config )
{
kdDebug() << "ResourceRemote::writeConfig()" << endl;
ResourceCalendar::writeConfig( config );
config->writeEntry( "DownloadUrl", mDownloadUrl.url() );
config->writeEntry( "UploadUrl", mUploadUrl.url() );
}
void ResourceRemote::setDownloadUrl( const KURL &url )
{
mDownloadUrl = url;
}
KURL ResourceRemote::downloadUrl() const
{
return mDownloadUrl;
}
void ResourceRemote::setUploadUrl( const KURL &url )
{
mUploadUrl = url;
}
KURL ResourceRemote::uploadUrl() const
{
return mUploadUrl;
}
QString ResourceRemote::cacheFile()
{
QString file = locateLocal( "cache", "kcal/kresources/" + identifier() );
kdDebug() << "ResourceRemote::cacheFile(): " << file;
return file;
}
bool ResourceRemote::doOpen()
{
kdDebug(5800) << "ResourceRemote::doOpen()" << endl;
mOpen = true;
return true;
}
bool ResourceRemote::load()
{
kdDebug() << "ResourceRemote::load()" << endl;
if ( !mOpen ) return true;
if ( mDownloadJob ) {
kdWarning() << "ResourceRemote::load(): download still in progress."
<< endl;
return false;
}
if ( mUploadJob ) {
kdWarning() << "ResourceRemote::load(): upload still in progress."
<< endl;
return false;
}
mCalendar.close();
mCalendar.load( cacheFile() );
mDownloadJob = KIO::file_copy( mDownloadUrl, KURL( cacheFile() ), -1, true );
connect( mDownloadJob, SIGNAL( result( KIO::Job * ) ),
SLOT( slotLoadJobResult( KIO::Job * ) ) );
return true;
}
void ResourceRemote::slotLoadJobResult( KIO::Job *job )
{
if ( job->error() ) {
job->showErrorDialog( 0 );
} else {
kdDebug() << "ResourceRemote::slotLoadJobResult() success" << endl;
mCalendar.close();
mCalendar.load( cacheFile() );
emit resourceChanged( this );
}
mDownloadJob = 0;
emit resourceLoaded( this );
}
bool ResourceRemote::save()
{
kdDebug() << "ResourceRemote::save()" << endl;
if ( !mOpen ) return true;
if ( mDownloadJob ) {
kdWarning() << "ResourceRemote::save(): download still in progress."
<< endl;
return false;
}
if ( mUploadJob ) {
kdWarning() << "ResourceRemote::save(): upload still in progress."
<< endl;
return false;
}
mCalendar.save( cacheFile() );
mUploadJob = KIO::file_copy( KURL( cacheFile() ), mUploadUrl, -1, true );
connect( mUploadJob, SIGNAL( result( KIO::Job * ) ),
SLOT( slotSaveJobResult( KIO::Job * ) ) );
return true;
}
bool ResourceRemote::isSaving()
{
return mUploadJob;
}
void ResourceRemote::slotSaveJobResult( KIO::Job *job )
{
if ( job->error() ) {
job->showErrorDialog( 0 );
} else {
kdDebug() << "ResourceRemote::slotSaveJobResult() success" << endl;
}
mUploadJob = 0;
emit resourceSaved( this );
}
void ResourceRemote::doClose()
{
if ( !mOpen ) return;
mCalendar.close();
mOpen = false;
}
bool ResourceRemote::addEvent(Event *event)
{
return mCalendar.addEvent( event );
}
void ResourceRemote::deleteEvent(Event *event)
{
kdDebug(5800) << "ResourceRemote::deleteEvent" << endl;
mCalendar.deleteEvent( event );
}
Event *ResourceRemote::event( const QString &uid )
{
return mCalendar.event( uid );
}
QPtrList<Event> ResourceRemote::rawEventsForDate(const QDate &qd, bool sorted)
{
return mCalendar.rawEventsForDate( qd, sorted );
}
QPtrList<Event> ResourceRemote::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
return mCalendar.rawEvents( start, end, inclusive );
}
QPtrList<Event> ResourceRemote::rawEventsForDate(const QDateTime &qdt)
{
return mCalendar.rawEventsForDate( qdt.date() );
}
QPtrList<Event> ResourceRemote::rawEvents()
{
return mCalendar.rawEvents();
}
bool ResourceRemote::addTodo(Todo *todo)
{
return mCalendar.addTodo( todo );
}
void ResourceRemote::deleteTodo(Todo *todo)
{
mCalendar.deleteTodo( todo );
}
QPtrList<Todo> ResourceRemote::rawTodos()
{
return mCalendar.rawTodos();
}
Todo *ResourceRemote::todo( const QString &uid )
{
return mCalendar.todo( uid );
}
QPtrList<Todo> ResourceRemote::todos( const QDate &date )
{
return mCalendar.todos( date );
}
bool ResourceRemote::addJournal(Journal *journal)
{
kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
return mCalendar.addJournal( journal );
}
Journal *ResourceRemote::journal(const QDate &date)
{
// kdDebug(5800) << "ResourceRemote::journal() " << date.toString() << endl;
return mCalendar.journal( date );
}
Journal *ResourceRemote::journal(const QString &uid)
{
return mCalendar.journal( uid );
}
QPtrList<Journal> ResourceRemote::journals()
{
return mCalendar.journals();
}
Alarm::List ResourceRemote::alarmsTo( const QDateTime &to )
{
return mCalendar.alarmsTo( to );
}
Alarm::List ResourceRemote::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "ResourceRemote::alarms(" << from.toString() << " - " << to.toString() << ")\n";
return mCalendar.alarms( from, to );
}
void ResourceRemote::update(IncidenceBase *)
{
}
void ResourceRemote::dump() const
{
ResourceCalendar::dump();
kdDebug(5800) << " DownloadUrl: " << mDownloadUrl.url() << endl;
kdDebug(5800) << " UploadUrl: " << mUploadUrl.url() << endl;
}
#include "resourceremote.moc"
<commit_msg>do not try to upload readonly calendars<commit_after>/*
This file is part of libkcal.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <typeinfo>
#include <stdlib.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/job.h>
#include <kstandarddirs.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"
#include <kresources/resourceconfigwidget.h>
#include "resourceremoteconfig.h"
#include "resourceremote.h"
using namespace KCal;
extern "C"
{
KRES::ResourceConfigWidget *config_widget( QWidget *parent ) {
return new ResourceRemoteConfig( parent, "Configure Remote Calendar" );
}
KRES::Resource *resource( const KConfig *config ) {
return new ResourceRemote( config );
}
}
ResourceRemote::ResourceRemote( const KConfig* config )
: ResourceCalendar( config )
{
if ( config ) {
readConfig( config );
}
init();
}
ResourceRemote::ResourceRemote( const KURL &downloadUrl, const KURL &uploadUrl )
: ResourceCalendar( 0 )
{
mDownloadUrl = downloadUrl;
if ( uploadUrl.isEmpty() ) {
mUploadUrl = mDownloadUrl;
} else {
mUploadUrl = uploadUrl;
}
init();
}
ResourceRemote::~ResourceRemote()
{
close();
if ( mDownloadJob ) mDownloadJob->kill();
if ( mUploadJob ) mUploadJob->kill();
}
void ResourceRemote::init()
{
mDownloadJob = 0;
mUploadJob = 0;
setType( "remote" );
mOpen = false;
}
void ResourceRemote::readConfig( const KConfig *config )
{
QString url = config->readEntry( "DownloadUrl" );
mDownloadUrl = KURL( url );
url = config->readEntry( "UploadUrl" );
mUploadUrl = KURL( url );
}
void ResourceRemote::writeConfig( KConfig *config )
{
kdDebug() << "ResourceRemote::writeConfig()" << endl;
ResourceCalendar::writeConfig( config );
config->writeEntry( "DownloadUrl", mDownloadUrl.url() );
config->writeEntry( "UploadUrl", mUploadUrl.url() );
}
void ResourceRemote::setDownloadUrl( const KURL &url )
{
mDownloadUrl = url;
}
KURL ResourceRemote::downloadUrl() const
{
return mDownloadUrl;
}
void ResourceRemote::setUploadUrl( const KURL &url )
{
mUploadUrl = url;
}
KURL ResourceRemote::uploadUrl() const
{
return mUploadUrl;
}
QString ResourceRemote::cacheFile()
{
QString file = locateLocal( "cache", "kcal/kresources/" + identifier() );
kdDebug() << "ResourceRemote::cacheFile(): " << file;
return file;
}
bool ResourceRemote::doOpen()
{
kdDebug(5800) << "ResourceRemote::doOpen()" << endl;
mOpen = true;
return true;
}
bool ResourceRemote::load()
{
kdDebug() << "ResourceRemote::load()" << endl;
if ( !mOpen ) return true;
if ( mDownloadJob ) {
kdWarning() << "ResourceRemote::load(): download still in progress."
<< endl;
return false;
}
if ( mUploadJob ) {
kdWarning() << "ResourceRemote::load(): upload still in progress."
<< endl;
return false;
}
mCalendar.close();
mCalendar.load( cacheFile() );
mDownloadJob = KIO::file_copy( mDownloadUrl, KURL( cacheFile() ), -1, true );
connect( mDownloadJob, SIGNAL( result( KIO::Job * ) ),
SLOT( slotLoadJobResult( KIO::Job * ) ) );
return true;
}
void ResourceRemote::slotLoadJobResult( KIO::Job *job )
{
if ( job->error() ) {
job->showErrorDialog( 0 );
} else {
kdDebug() << "ResourceRemote::slotLoadJobResult() success" << endl;
mCalendar.close();
mCalendar.load( cacheFile() );
emit resourceChanged( this );
}
mDownloadJob = 0;
emit resourceLoaded( this );
}
bool ResourceRemote::save()
{
kdDebug() << "ResourceRemote::save()" << endl;
if ( !mOpen ) return true;
if ( readOnly() ) {
emit resourceSaved( this );
return true;
}
if ( mDownloadJob ) {
kdWarning() << "ResourceRemote::save(): download still in progress."
<< endl;
return false;
}
if ( mUploadJob ) {
kdWarning() << "ResourceRemote::save(): upload still in progress."
<< endl;
return false;
}
mCalendar.save( cacheFile() );
mUploadJob = KIO::file_copy( KURL( cacheFile() ), mUploadUrl, -1, true );
connect( mUploadJob, SIGNAL( result( KIO::Job * ) ),
SLOT( slotSaveJobResult( KIO::Job * ) ) );
return true;
}
bool ResourceRemote::isSaving()
{
return mUploadJob;
}
void ResourceRemote::slotSaveJobResult( KIO::Job *job )
{
if ( job->error() ) {
job->showErrorDialog( 0 );
} else {
kdDebug() << "ResourceRemote::slotSaveJobResult() success" << endl;
}
mUploadJob = 0;
emit resourceSaved( this );
}
void ResourceRemote::doClose()
{
if ( !mOpen ) return;
mCalendar.close();
mOpen = false;
}
bool ResourceRemote::addEvent(Event *event)
{
return mCalendar.addEvent( event );
}
void ResourceRemote::deleteEvent(Event *event)
{
kdDebug(5800) << "ResourceRemote::deleteEvent" << endl;
mCalendar.deleteEvent( event );
}
Event *ResourceRemote::event( const QString &uid )
{
return mCalendar.event( uid );
}
QPtrList<Event> ResourceRemote::rawEventsForDate(const QDate &qd, bool sorted)
{
return mCalendar.rawEventsForDate( qd, sorted );
}
QPtrList<Event> ResourceRemote::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
return mCalendar.rawEvents( start, end, inclusive );
}
QPtrList<Event> ResourceRemote::rawEventsForDate(const QDateTime &qdt)
{
return mCalendar.rawEventsForDate( qdt.date() );
}
QPtrList<Event> ResourceRemote::rawEvents()
{
return mCalendar.rawEvents();
}
bool ResourceRemote::addTodo(Todo *todo)
{
return mCalendar.addTodo( todo );
}
void ResourceRemote::deleteTodo(Todo *todo)
{
mCalendar.deleteTodo( todo );
}
QPtrList<Todo> ResourceRemote::rawTodos()
{
return mCalendar.rawTodos();
}
Todo *ResourceRemote::todo( const QString &uid )
{
return mCalendar.todo( uid );
}
QPtrList<Todo> ResourceRemote::todos( const QDate &date )
{
return mCalendar.todos( date );
}
bool ResourceRemote::addJournal(Journal *journal)
{
kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
return mCalendar.addJournal( journal );
}
Journal *ResourceRemote::journal(const QDate &date)
{
// kdDebug(5800) << "ResourceRemote::journal() " << date.toString() << endl;
return mCalendar.journal( date );
}
Journal *ResourceRemote::journal(const QString &uid)
{
return mCalendar.journal( uid );
}
QPtrList<Journal> ResourceRemote::journals()
{
return mCalendar.journals();
}
Alarm::List ResourceRemote::alarmsTo( const QDateTime &to )
{
return mCalendar.alarmsTo( to );
}
Alarm::List ResourceRemote::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "ResourceRemote::alarms(" << from.toString() << " - " << to.toString() << ")\n";
return mCalendar.alarms( from, to );
}
void ResourceRemote::update(IncidenceBase *)
{
}
void ResourceRemote::dump() const
{
ResourceCalendar::dump();
kdDebug(5800) << " DownloadUrl: " << mDownloadUrl.url() << endl;
kdDebug(5800) << " UploadUrl: " << mUploadUrl.url() << endl;
}
#include "resourceremote.moc"
<|endoftext|> |
<commit_before>/* Copyright 2011 Thomas McGuire <mcguire@kde.org>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "eventinfo.h"
#include "util.h"
#include <KDebug>
#include <KLocalizedString>
#include <KPIMUtils/LinkLocator>
KCalCore::Event::Ptr EventInfo::asEvent() const
{
KCalCore::Event::Ptr event( new KCalCore::Event );
QString desc = description();
desc = KPIMUtils::LinkLocator::convertToHtml( desc, KPIMUtils::LinkLocator::ReplaceSmileys );
if ( !desc.isEmpty() ) {
desc += "<br><br>";
}
desc += "<a href=\"" + QString( "http://www.facebook.com/event.php?eid=%1" ).arg( id() ) +
"\">" + i18n( "View Event on Facebook" ) + "</a>";
event->setSummary( name() );
event->setDescription( desc, true );
event->setLocation( location() );
event->setHasEndDate( endTime().isValid() );
event->setOrganizer( organizer() );
event->setUid( id() );
if ( startTime().isValid() ) {
event->setDtStart( startTime() );
} else {
kWarning() << "WTF, event has no start date??";
}
if ( endTime().isValid() ) {
event->setDtEnd( endTime() );
} else if ( startTime().isValid() && !endTime().isValid() ) {
// Urgh...
KDateTime endDate;
endDate.setDate( startTime().date() );
endDate.setTime( QTime::fromString( "23:59:00" ) );
kWarning() << "Event without end time: " << event->summary() << event->dtStart();
kWarning() << "Making it an event until the end of the day.";
//kWarning() << "Using a duration of 2 hours";
//event->setDuration( KCalCore::Duration( 2 * 60 * 60, KCalCore::Duration::Seconds ) );
}
// TODO: Organizer
// Attendees (accepted, declined)
// Public/Private -> freebusy!
// venue: add to location?
// picture?
return event;
}
KDateTime EventInfo::endTime() const
{
return facebookTimeToKDateTime(mEndTime);
}
QString EventInfo::endTimeString() const
{
return mEndTime;
}
QString EventInfo::id() const
{
return mId;
}
QString EventInfo::location() const
{
return mLocation;
}
QString EventInfo::name() const
{
return mName;
}
void EventInfo::setEndTimeString(const QString& endTime)
{
mEndTime = endTime;
}
void EventInfo::setId(const QString& id)
{
mId = id;
}
void EventInfo::setLocation(const QString& location)
{
mLocation = location;
}
void EventInfo::setName(const QString& name)
{
mName = name;
}
void EventInfo::setStartTimeString(const QString& startTime)
{
mStartTime = startTime;
}
KDateTime EventInfo::startTime() const
{
return facebookTimeToKDateTime(mStartTime);
}
QString EventInfo::startTimeString() const
{
return mStartTime;
}
QString EventInfo::description() const
{
return mDescription;
}
void EventInfo::setDescription( const QString& description )
{
mDescription = description;
}
QString EventInfo::organizer() const
{
return mOrganizer;
}
void EventInfo::setOrganizer(const QString& organizer)
{
mOrganizer = organizer;
}
<commit_msg>Actually set the end date for events without one.<commit_after>/* Copyright 2011 Thomas McGuire <mcguire@kde.org>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "eventinfo.h"
#include "util.h"
#include <KDebug>
#include <KLocalizedString>
#include <KPIMUtils/LinkLocator>
KCalCore::Event::Ptr EventInfo::asEvent() const
{
KCalCore::Event::Ptr event( new KCalCore::Event );
QString desc = description();
desc = KPIMUtils::LinkLocator::convertToHtml( desc, KPIMUtils::LinkLocator::ReplaceSmileys );
if ( !desc.isEmpty() ) {
desc += "<br><br>";
}
desc += "<a href=\"" + QString( "http://www.facebook.com/event.php?eid=%1" ).arg( id() ) +
"\">" + i18n( "View Event on Facebook" ) + "</a>";
event->setSummary( name() );
event->setDescription( desc, true );
event->setLocation( location() );
event->setHasEndDate( endTime().isValid() );
event->setOrganizer( organizer() );
event->setUid( id() );
if ( startTime().isValid() ) {
event->setDtStart( startTime() );
} else {
kWarning() << "WTF, event has no start date??";
}
if ( endTime().isValid() ) {
event->setDtEnd( endTime() );
} else if ( startTime().isValid() && !endTime().isValid() ) {
// Urgh...
KDateTime endDate;
endDate.setDate( startTime().date() );
endDate.setTime( QTime::fromString( "23:59:00" ) );
kWarning() << "Event without end time: " << event->summary() << event->dtStart();
kWarning() << "Making it an event until the end of the day.";
event->setDtEnd( endDate );
//kWarning() << "Using a duration of 2 hours";
//event->setDuration( KCalCore::Duration( 2 * 60 * 60, KCalCore::Duration::Seconds ) );
}
// TODO: Organizer
// Attendees (accepted, declined)
// Public/Private -> freebusy!
// venue: add to location?
// picture?
return event;
}
KDateTime EventInfo::endTime() const
{
return facebookTimeToKDateTime(mEndTime);
}
QString EventInfo::endTimeString() const
{
return mEndTime;
}
QString EventInfo::id() const
{
return mId;
}
QString EventInfo::location() const
{
return mLocation;
}
QString EventInfo::name() const
{
return mName;
}
void EventInfo::setEndTimeString(const QString& endTime)
{
mEndTime = endTime;
}
void EventInfo::setId(const QString& id)
{
mId = id;
}
void EventInfo::setLocation(const QString& location)
{
mLocation = location;
}
void EventInfo::setName(const QString& name)
{
mName = name;
}
void EventInfo::setStartTimeString(const QString& startTime)
{
mStartTime = startTime;
}
KDateTime EventInfo::startTime() const
{
return facebookTimeToKDateTime(mStartTime);
}
QString EventInfo::startTimeString() const
{
return mStartTime;
}
QString EventInfo::description() const
{
return mDescription;
}
void EventInfo::setDescription( const QString& description )
{
mDescription = description;
}
QString EventInfo::organizer() const
{
return mOrganizer;
}
void EventInfo::setOrganizer(const QString& organizer)
{
mOrganizer = organizer;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <random>
#include <stdlib.h>
#define SIZEF 500
struct Position{
int x = 0;
int y = 0;
};
using namespace std;
int walk(Position *p,int board[SIZEF][SIZEF],int size){
//https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
random_device rd;
mt19937_64 gen(rd());
//http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
uniform_real_distribution<> uni(0,99.9);
// cout << uni(gen)<<"\n";
double random = uni(gen);
int pass = 0;
// printf("[%i],[%i]\n",p->x,p->y);
while(1){
random = fmod(random,100);
// cout << board[1][2]<<" BOARD[1][2]\n";
// cout << board[2][1]<<" BOARD[2][1]\n";
// cout << p->x+1<<" p.x\n";
// cout << p->y<<" p.y\n";
// if ((random >= 25)&&(random < 37.5)) {
// cout << "rnd: "<<random<<"\n";
// }
if ((0 <= random)&&(random < 12.5)) { // move 1
if((p->x-2>=0)&&(p->y+1<size)){
if (board[p->x-2][p->y+1] == 0) {
// cout << "oi!1" << '\n';
p->x-=2;
p->y+=1;
return 0;
}
}
pass++;
}else if ((12.5 <= random)&&(random < 25)){ // move 2
if((p->x-1>=0)&&(p->y+2<size)){
if (board[p->x-1][p->y+2] == 0) {
// cout << "oi!2" << '\n';
p->x-=1;
p->y+=2;
return 0;
}
}
pass++;
}else if ((25 <= random)&&(random< 37.5)){ // move 3
if((p->x+1<size)&&(p->y+2<size)){
if (board[p->x+1][p->y+2] == 0) {
// cout << "oi!3" << '\n';
p->x+=1;
p->y+=2;
return 0;
}
}
pass++;
}else if ((37.5 <= random)&&(random < 50)){ // move 4
if((p->x+2<size)&&(p->y+1<size)){
if (board[p->x+2][p->y+1] == 0) {
// cout << "oi!4" << '\n';
p->x+=2;
p->y+=1;
return 0;
}
}
pass++;
}else if ((50 <= random)&&(random < 62.5)){ // move 5
if((p->x+2<size)&&(p->y-1>=0)){
if (board[p->x+2][p->y-1] == 0) {
// cout << "oi!5" << '\n';
p->x+=2;
p->y-=1;
return 0;
}
}
pass++;
}else if ((62.5 <= random)&&(random < 75)){ // move 6
if((p->x+1<size)&&(p->y-2>=0)){
if (board[p->x+1][p->y-2] == 0) {
// cout << "oi!6" << '\n';
p->x+=1;
p->y-=2;
return 0;
}
}
pass++;
}else if ((75 <= random)&&(random < 87.5)){ // move 7
if((p->x-1>=0)&&(p->y-2>=0)){
if (board[p->x-1][p->y-2] == 0) {
// cout << "oi!7" << '\n';
p->x-=1;
p->y-=2;
return 0;
}
}
pass++;
}else{ // move 8
if((p->x-2>=0)&&(p->y-1>=0)){
if (board[p->x-2][p->y-1] == 0) {
// cout << "oi!8" << '\n';
p->x-=2;
p->y-=1;
return 0;
}
}
pass++;
}
random+=12.5;
if (pass == 8) {
return 1;
}
}
}
void printBoard(int board[SIZEF][SIZEF], int size){
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j)
cout << board[i][j] << "\t";
cout << "\n\n";
}
}
int main(int argc, char const *argv[]) {
int size,count,end;
int flag = 0, iter = 0;
int i;
Position *p;
p = (Position *) malloc(sizeof(Position));
cin >> size;
while (1) {
iter++;
int board [SIZEF][SIZEF] = {0};
board[0][0] = 1;
count = 2;
for (i = 0; i < size*size; i++){
end = walk(p,board,size);
if (end == 1) {
flag = 0;
for (int i2 = 0; i2 < size; i2++) {
for (int j2 = 0; j2 < size; j2++) {
if (board[i2][j2] == 0) {
flag++;
}
}
}
if (flag == 0) {
cout << "random is good!" << '\n';
printBoard(board, size);
return 0;
}
cout << "random is mean" << '\n';
break;
}
board[p->x][p->y] = count;
count++;
}
if(flag != 0){
p->x=0;
p->y=0;
}
}
return 0;
}
<commit_msg>suitable<commit_after>#include <iostream>
#include <random>
#include <stdlib.h>
#define SIZEF 500
struct Position{
int x = 0;
int y = 0;
};
using namespace std;
int walk(Position *p,int board[SIZEF][SIZEF],int size){
//https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
random_device rd;
mt19937_64 gen(rd());
//http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
uniform_real_distribution<> uni(0,99.9);
// cout << uni(gen)<<"\n";
double random = uni(gen);
int pass = 0;
// printf("[%i],[%i]\n",p->x,p->y);
while(1){
random = fmod(random,100);
// cout << board[1][2]<<" BOARD[1][2]\n";
// cout << board[2][1]<<" BOARD[2][1]\n";
// cout << p->x+1<<" p.x\n";
// cout << p->y<<" p.y\n";
// if ((random >= 25)&&(random < 37.5)) {
// cout << "rnd: "<<random<<"\n";
// }
if ((0 <= random)&&(random < 12.5)) { // move 1
if((p->x-2>=0)&&(p->y+1<size)){
if (board[p->x-2][p->y+1] == 0) {
// cout << "oi!1" << '\n';
p->x-=2;
p->y+=1;
return 0;
}
}
pass++;
}else if ((12.5 <= random)&&(random < 25)){ // move 2
if((p->x-1>=0)&&(p->y+2<size)){
if (board[p->x-1][p->y+2] == 0) {
// cout << "oi!2" << '\n';
p->x-=1;
p->y+=2;
return 0;
}
}
pass++;
}else if ((25 <= random)&&(random< 37.5)){ // move 3
if((p->x+1<size)&&(p->y+2<size)){
if (board[p->x+1][p->y+2] == 0) {
// cout << "oi!3" << '\n';
p->x+=1;
p->y+=2;
return 0;
}
}
pass++;
}else if ((37.5 <= random)&&(random < 50)){ // move 4
if((p->x+2<size)&&(p->y+1<size)){
if (board[p->x+2][p->y+1] == 0) {
// cout << "oi!4" << '\n';
p->x+=2;
p->y+=1;
return 0;
}
}
pass++;
}else if ((50 <= random)&&(random < 62.5)){ // move 5
if((p->x+2<size)&&(p->y-1>=0)){
if (board[p->x+2][p->y-1] == 0) {
// cout << "oi!5" << '\n';
p->x+=2;
p->y-=1;
return 0;
}
}
pass++;
}else if ((62.5 <= random)&&(random < 75)){ // move 6
if((p->x+1<size)&&(p->y-2>=0)){
if (board[p->x+1][p->y-2] == 0) {
// cout << "oi!6" << '\n';
p->x+=1;
p->y-=2;
return 0;
}
}
pass++;
}else if ((75 <= random)&&(random < 87.5)){ // move 7
if((p->x-1>=0)&&(p->y-2>=0)){
if (board[p->x-1][p->y-2] == 0) {
// cout << "oi!7" << '\n';
p->x-=1;
p->y-=2;
return 0;
}
}
pass++;
}else{ // move 8
if((p->x-2>=0)&&(p->y-1>=0)){
if (board[p->x-2][p->y-1] == 0) {
// cout << "oi!8" << '\n';
p->x-=2;
p->y-=1;
return 0;
}
}
pass++;
}
random+=12.5;
if (pass == 8) {
return 1;
}
}
}
void printBoard(int board[SIZEF][SIZEF], int size){
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j)
cout << board[i][j] << "\t";
cout << "\n\n";
}
}
int main(int argc, char const *argv[]) {
int size,count,end;
int flag = 0, iter = 0;
int i;
Position *p;
p = (Position *) malloc(sizeof(Position));
cin >> size;
while (1) {
iter++;
int board [SIZEF][SIZEF] = {0};
board[0][0] = 1;
count = 2;
for (i = 0; i < size*size; i++){
end = walk(p,board,size);
if (end == 1) {
flag = 0;
for (int i2 = 0; i2 < size; i2++) {
for (int j2 = 0; j2 < size; j2++) {
if (board[i2][j2] == 0) {
flag++;
}
}
}
if (flag == 0) {
cout << "random is good! Iteration:"<< iter << '\n';
printBoard(board, size);
return 0;
}
// cout << "random is mean" << '\n';
break;
}
board[p->x][p->y] = count;
count++;
}
if(flag != 0){
p->x=0;
p->y=0;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 Erik Gilling
*
* 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 <string.h>
#include <StepSequencer.hh>
StepSequencer::StepSequencer(unsigned numChannels, vector<string> *pixelMap)
{
unsigned i;
this->numChannels = numChannels;
this->pixelMap = pixelMap;
frame = new uint32_t[pixelMap->size()];
channels = new ChannelState[numChannels];
for (i = 0; i < numChannels; i++) {
channels[i].state = STATE_OFF;
channels[i].seq = NULL;
}
lastStep.tv_sec = 0;
lastStep.tv_usec = 0;
}
StepSequencer::~StepSequencer()
{
delete channels;
}
void StepSequencer::setChannelSequence(unsigned channel, Sequence *seq)
{
if (channel >= numChannels)
return;
channels[channel].state = STATE_OFF;
channels[channel].seq = seq;
}
void StepSequencer::setChannelState(unsigned channel, int state)
{
if (channel >= numChannels)
return;
channels[channel].state = state;
channels[channel].timeCode = 0.0;
}
void StepSequencer::step(State *state)
{
struct timeval thisStep, stepDelta;
float step;
unsigned c;
gettimeofday(&thisStep, NULL);
if (lastStep.tv_sec == 0 && lastStep.tv_usec == 0)
lastStep = thisStep;
timersub(&thisStep, &lastStep, &stepDelta);
step = stepDelta.tv_sec + stepDelta.tv_usec / 1000000.0;
memset(frame, 0x0, sizeof(uint32_t) * pixelMap->size());
for (c = 0; c < numChannels; c++) {
bool looped;
if (channels[c].state == STATE_OFF ||channels[c].seq == NULL)
continue;
channels[c].timeCode += step;
looped = channels[c].seq->handleFrame(frame, pixelMap->size(),
channels[c].timeCode);
if (looped && channels[c].state == STATE_SINGLE) {
channels[c].state = STATE_OFF;
channels[c].timeCode = 0.0;
}
}
unsigned i;
for (i = 0; i < pixelMap->size(); i++) {
const char *name = (*pixelMap)[i].c_str();
uint8_t r, g, b;
r = frame[i] & 0xff;
g = (frame[i] >> 8) & 0xff;
b = (frame[i] >> 16) & 0xff;
if (state->hasDigitalOut(name)) {
state->setDigitalOut(name, r > 5 || g > 5 || b > 5);
} else if (state->hasLightOut(name)) {
state->setLightOut(name, r, g, b);
} else {
fprintf(stderr, "unknown pixel output %s\n", name);
}
}
lastStep = thisStep;
}
<commit_msg>put old sequence when replacing with a new one<commit_after>/*
* Copyright 2010 Erik Gilling
*
* 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 <string.h>
#include <StepSequencer.hh>
StepSequencer::StepSequencer(unsigned numChannels, vector<string> *pixelMap)
{
unsigned i;
this->numChannels = numChannels;
this->pixelMap = pixelMap;
frame = new uint32_t[pixelMap->size()];
channels = new ChannelState[numChannels];
for (i = 0; i < numChannels; i++) {
channels[i].state = STATE_OFF;
channels[i].seq = NULL;
}
lastStep.tv_sec = 0;
lastStep.tv_usec = 0;
}
StepSequencer::~StepSequencer()
{
delete channels;
}
void StepSequencer::setChannelSequence(unsigned channel, Sequence *seq)
{
if (channel >= numChannels)
return;
if (channels[channel].seq)
channels[channel].seq->put();
channels[channel].state = STATE_OFF;
channels[channel].seq = seq;
}
void StepSequencer::setChannelState(unsigned channel, int state)
{
if (channel >= numChannels)
return;
channels[channel].state = state;
channels[channel].timeCode = 0.0;
}
void StepSequencer::step(State *state)
{
struct timeval thisStep, stepDelta;
float step;
unsigned c;
gettimeofday(&thisStep, NULL);
if (lastStep.tv_sec == 0 && lastStep.tv_usec == 0)
lastStep = thisStep;
timersub(&thisStep, &lastStep, &stepDelta);
step = stepDelta.tv_sec + stepDelta.tv_usec / 1000000.0;
memset(frame, 0x0, sizeof(uint32_t) * pixelMap->size());
for (c = 0; c < numChannels; c++) {
bool looped;
if (channels[c].state == STATE_OFF ||channels[c].seq == NULL)
continue;
channels[c].timeCode += step;
looped = channels[c].seq->handleFrame(frame, pixelMap->size(),
channels[c].timeCode);
if (looped && channels[c].state == STATE_SINGLE) {
channels[c].state = STATE_OFF;
channels[c].timeCode = 0.0;
}
}
unsigned i;
for (i = 0; i < pixelMap->size(); i++) {
const char *name = (*pixelMap)[i].c_str();
uint8_t r, g, b;
r = frame[i] & 0xff;
g = (frame[i] >> 8) & 0xff;
b = (frame[i] >> 16) & 0xff;
if (state->hasDigitalOut(name)) {
state->setDigitalOut(name, r > 5 || g > 5 || b > 5);
} else if (state->hasLightOut(name)) {
state->setLightOut(name, r, g, b);
} else {
fprintf(stderr, "unknown pixel output %s\n", name);
}
}
lastStep = thisStep;
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/global.hpp"
#include "libbirch/Span.hpp"
#include "libbirch/Index.hpp"
#include "libbirch/Range.hpp"
#include "libbirch/View.hpp"
#include "libbirch/Eigen.hpp"
#include <cstddef>
namespace bi {
/**
* Empty frame.
*
* @ingroup libbirch
*
* @see NonemptyFrame
*/
struct EmptyFrame {
EmptyFrame() {
//
}
/**
* Special constructor for Eigen integration where all matrices and vectors
* are treated as matrices, with row and column counts. If this constructor,
* is reached, it means the array is a vector, and @p length should be one
* (and is checked for this).
*/
EmptyFrame(const Eigen::Index cols) {
assert(cols == 1);
}
EmptyFrame operator()(const EmptyView& o) const {
return EmptyFrame();
}
bool conforms(const EmptyFrame& o) const {
return true;
}
template<class Frame1>
bool conforms(const Frame1& o) const {
return false;
}
bool conforms(const Eigen::Index rows, const Eigen::Index cols) {
return false;
}
bool conforms(const Eigen::Index rows) {
return false;
}
void resize(const EmptyFrame& o) {
//
}
template<class T1>
void resize(T1* in) {
//
}
void resize(const Eigen::Index cols) {
// special case for vector represented as N x 1 matrix in Eigen.
assert(cols == 1);
}
ptrdiff_t offset(const ptrdiff_t n) {
return 0;
}
size_t length(const int i) const {
assert(false);
}
size_t stride(const int i) const {
assert(false);
}
template<class T1>
void lengths(T1* out) const {
//
}
template<class T1>
void strides(T1* out) const {
//
}
static constexpr int count() {
return 0;
}
static constexpr size_t size() {
return 1;
}
static constexpr size_t volume() {
return 1;
}
static constexpr size_t block() {
return 1;
}
template<class View>
ptrdiff_t serial(const View& o) const {
return 0;
}
bool contiguous() const {
return true;
}
bool operator==(const EmptyFrame& o) const {
return true;
}
template<class Frame1>
bool operator==(const Frame1& o) const {
return false;
}
template<class Frame1>
bool operator!=(const Frame1& o) const {
return !operator==(o);
}
EmptyFrame& operator*=(const ptrdiff_t n) {
return *this;
}
EmptyFrame operator*(const ptrdiff_t n) const {
EmptyFrame result(*this);
result *= n;
return result;
}
};
/**
* Nonempty frame.
*
* @ingroup libbirch
*
* @tparam Tail Frame type.
* @tparam Head Span type.
*
* A frame describes the `D` dimensions of an array. It consists of a
* @em head span describing the first dimension, and a tail @em tail frame
* describing the remaining `D - 1` dimensions, recursively. The tail frame
* is EmptyFrame for the last dimension.
*/
template<class Head, class Tail>
struct NonemptyFrame {
/**
* Head type.
*/
typedef Head head_type;
/**
* Tail type.
*/
typedef Tail tail_type;
/**
* Default constructor (for zero-size frame).
*/
NonemptyFrame() {
//
}
/*
* Special constructor for Eigen integration where all matrices and vectors
* are treated as matrices, with row and column counts.
*/
NonemptyFrame(const Eigen::Index rows, const Eigen::Index cols = 1) :
head(rows, cols),
tail(cols) {
//
}
/**
* Generic constructor.
*/
template<class Head1, class Tail1>
NonemptyFrame(const Head1 head, const Tail1 tail) :
head(head),
tail(tail) {
//
}
/**
* Generic copy constructor.
*/
template<class Head1, class Tail1>
NonemptyFrame(const NonemptyFrame<Head1,Tail1>& o) :
head(o.head),
tail(o.tail) {
//
}
/**
* View operator.
*/
template<ptrdiff_t offset_value1, size_t length_value1, class Tail1>
auto operator()(
const NonemptyView<Range<offset_value1,length_value1>,Tail1>& o) const {
/* pre-conditions */
assert(o.head.offset >= 0);
assert(o.head.offset + o.head.length <= head.length);
return NonemptyFrame<decltype(head(o.head)),decltype(tail(o.tail))>(
head(o.head), tail(o.tail));
}
/**
* View operator.
*/
template<ptrdiff_t offset_value1, class Tail1>
auto operator()(const NonemptyView<Index<offset_value1>,Tail1>& o) const {
/* pre-condition */
assert(o.head.offset >= 0 && o.head.offset < head.length);
return o.head.offset * head.stride + tail(o.tail);
}
/**
* Does this frame conform to another? Two frames conform if their spans
* conform.
*/
bool conforms(const EmptyFrame& o) const {
return false;
}
template<class Frame1>
bool conforms(const Frame1& o) const {
return head.conforms(o.head) && tail.conforms(o.tail);
}
bool conforms(const Eigen::Index rows, const Eigen::Index cols) {
return head.conforms(rows) && tail.conforms(cols);
}
bool conforms(const Eigen::Index rows) {
return head.conforms(rows);
}
/**
* Resize this frame to conform to another.
*/
template<class Frame1>
void resize(const Frame1& o) {
tail.resize(o.tail);
head.length = o.head.length;
head.stride = tail.volume();
}
template<class T1>
void resize(T1* in) {
tail.resize(in + 1);
head.length = *in;
head.stride = tail.volume();
}
void resize(const Eigen::Index rows, const Eigen::Index cols) {
tail.resize(cols);
head.length = rows;
head.stride = tail.volume();
}
void resize(const Eigen::Index rows) {
head.length = rows;
head.stride = tail.volume();
}
/**
* Compute the offset to the @p n th element in storage order.
*
* @param n Element number.
*/
ptrdiff_t offset(const ptrdiff_t n) {
ptrdiff_t q = n / head.length;
ptrdiff_t r = n % head.length;
return r * head.stride + tail.offset(q);
}
/**
* @name Getters
*/
//@{
/**
* Get the length of the @p i th dimension.
*/
size_t length(const int i) const {
/* pre-condition */
assert(i >= 0 && i < count());
if (i == 0) {
return head.length;
} else {
return tail.length(i - 1);
}
}
/**
* Get the stride of the @p i th dimension.
*/
size_t stride(const int i) const {
/* pre-condition */
assert(i >= 0 && i < count());
if (i == 0) {
return head.stride;
} else {
return tail.stride(i - 1);
}
}
/**
* Get lengths.
*
* @tparam T1 Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class T1>
void lengths(T1* out) const {
*out = head.length;
tail.lengths(out + 1);
}
/**
* Get strides.
*
* @tparam T1 Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class T1>
void strides(T1* out) const {
*out = head.stride;
tail.strides(out + 1);
}
//@}
/**
* @name Reductions
*/
//@{
/**
* Number of dimensions.
*/
static constexpr int count() {
return 1 + Tail::count();
}
/**
* Product of all lengths.
*/
size_t size() const {
return head.length*tail.size();
}
/**
* Product of all strides.
*/
size_t volume() const {
return head.length*head.stride;
}
/**
* Size of contiguous blocks.
*/
size_t block() const {
size_t block = tail.block();
return head.stride == block ? head.length*head.stride : block;
}
/**
* Serial offset for a view.
*/
template<class View>
ptrdiff_t serial(const View& o) const {
return o.head.offset * head.stride + tail.serial(o.tail);
}
/**
* Are all elements stored contiguously in memory?
*/
bool contiguous() const {
return volume() == size();
}
//@}
/**
* Equality operator.
*/
template<class Head1, class Tail1>
bool operator==(const NonemptyFrame<Head1,Tail1>& o) const {
return head == o.head && tail == o.tail;
}
/**
* Equality operator.
*/
bool operator==(const EmptyFrame& o) const {
return false;
}
/**
* Unequality operator.
*/
template<class Frame1>
bool operator!=(const Frame1& o) const {
return !(*this == o);
}
/**
* Head.
*/
Head head;
/**
* Tail
*/
Tail tail;
};
/**
* Default frame for `D` dimensions.
*/
template<int D>
struct DefaultFrame {
typedef NonemptyFrame<Span<>,typename DefaultFrame<D - 1>::type> type;
};
template<>
struct DefaultFrame<0> {
typedef EmptyFrame type;
};
}
<commit_msg>Added additional assertion check for array indexing.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/global.hpp"
#include "libbirch/Span.hpp"
#include "libbirch/Index.hpp"
#include "libbirch/Range.hpp"
#include "libbirch/View.hpp"
#include "libbirch/Eigen.hpp"
#include <cstddef>
namespace bi {
/**
* Empty frame.
*
* @ingroup libbirch
*
* @see NonemptyFrame
*/
struct EmptyFrame {
EmptyFrame() {
//
}
/**
* Special constructor for Eigen integration where all matrices and vectors
* are treated as matrices, with row and column counts. If this constructor,
* is reached, it means the array is a vector, and @p length should be one
* (and is checked for this).
*/
EmptyFrame(const Eigen::Index cols) {
assert(cols == 1);
}
EmptyFrame operator()(const EmptyView& o) const {
return EmptyFrame();
}
bool conforms(const EmptyFrame& o) const {
return true;
}
template<class Frame1>
bool conforms(const Frame1& o) const {
return false;
}
bool conforms(const Eigen::Index rows, const Eigen::Index cols) {
return false;
}
bool conforms(const Eigen::Index rows) {
return false;
}
void resize(const EmptyFrame& o) {
//
}
template<class T1>
void resize(T1* in) {
//
}
void resize(const Eigen::Index cols) {
// special case for vector represented as N x 1 matrix in Eigen.
assert(cols == 1);
}
ptrdiff_t offset(const ptrdiff_t n) {
return 0;
}
size_t length(const int i) const {
assert(false);
}
size_t stride(const int i) const {
assert(false);
}
template<class T1>
void lengths(T1* out) const {
//
}
template<class T1>
void strides(T1* out) const {
//
}
static constexpr int count() {
return 0;
}
static constexpr size_t size() {
return 1;
}
static constexpr size_t volume() {
return 1;
}
static constexpr size_t block() {
return 1;
}
template<class View>
ptrdiff_t serial(const View& o) const {
return 0;
}
bool contiguous() const {
return true;
}
bool operator==(const EmptyFrame& o) const {
return true;
}
template<class Frame1>
bool operator==(const Frame1& o) const {
return false;
}
template<class Frame1>
bool operator!=(const Frame1& o) const {
return !operator==(o);
}
EmptyFrame& operator*=(const ptrdiff_t n) {
return *this;
}
EmptyFrame operator*(const ptrdiff_t n) const {
EmptyFrame result(*this);
result *= n;
return result;
}
};
/**
* Nonempty frame.
*
* @ingroup libbirch
*
* @tparam Tail Frame type.
* @tparam Head Span type.
*
* A frame describes the `D` dimensions of an array. It consists of a
* @em head span describing the first dimension, and a tail @em tail frame
* describing the remaining `D - 1` dimensions, recursively. The tail frame
* is EmptyFrame for the last dimension.
*/
template<class Head, class Tail>
struct NonemptyFrame {
/**
* Head type.
*/
typedef Head head_type;
/**
* Tail type.
*/
typedef Tail tail_type;
/**
* Default constructor (for zero-size frame).
*/
NonemptyFrame() {
//
}
/*
* Special constructor for Eigen integration where all matrices and vectors
* are treated as matrices, with row and column counts.
*/
NonemptyFrame(const Eigen::Index rows, const Eigen::Index cols = 1) :
head(rows, cols),
tail(cols) {
//
}
/**
* Generic constructor.
*/
template<class Head1, class Tail1>
NonemptyFrame(const Head1 head, const Tail1 tail) :
head(head),
tail(tail) {
//
}
/**
* Generic copy constructor.
*/
template<class Head1, class Tail1>
NonemptyFrame(const NonemptyFrame<Head1,Tail1>& o) :
head(o.head),
tail(o.tail) {
//
}
/**
* View operator.
*/
template<ptrdiff_t offset_value1, size_t length_value1, class Tail1>
auto operator()(
const NonemptyView<Range<offset_value1,length_value1>,Tail1>& o) const {
/* pre-conditions */
assert(o.head.offset >= 0);
assert(o.head.offset + o.head.length <= head.length);
return NonemptyFrame<decltype(head(o.head)),decltype(tail(o.tail))>(
head(o.head), tail(o.tail));
}
/**
* View operator.
*/
template<ptrdiff_t offset_value1, class Tail1>
auto operator()(const NonemptyView<Index<offset_value1>,Tail1>& o) const {
/* pre-condition */
assert(o.head.offset >= 0 && o.head.offset < head.length);
return o.head.offset * head.stride + tail(o.tail);
}
/**
* Does this frame conform to another? Two frames conform if their spans
* conform.
*/
bool conforms(const EmptyFrame& o) const {
return false;
}
template<class Frame1>
bool conforms(const Frame1& o) const {
return head.conforms(o.head) && tail.conforms(o.tail);
}
bool conforms(const Eigen::Index rows, const Eigen::Index cols) {
return head.conforms(rows) && tail.conforms(cols);
}
bool conforms(const Eigen::Index rows) {
return head.conforms(rows);
}
/**
* Resize this frame to conform to another.
*/
template<class Frame1>
void resize(const Frame1& o) {
tail.resize(o.tail);
head.length = o.head.length;
head.stride = tail.volume();
}
template<class T1>
void resize(T1* in) {
tail.resize(in + 1);
head.length = *in;
head.stride = tail.volume();
}
void resize(const Eigen::Index rows, const Eigen::Index cols) {
tail.resize(cols);
head.length = rows;
head.stride = tail.volume();
}
void resize(const Eigen::Index rows) {
head.length = rows;
head.stride = tail.volume();
}
/**
* Compute the offset to the @p n th element in storage order.
*
* @param n Element number.
*/
ptrdiff_t offset(const ptrdiff_t n) {
ptrdiff_t q = n / head.length;
ptrdiff_t r = n % head.length;
return r * head.stride + tail.offset(q);
}
/**
* @name Getters
*/
//@{
/**
* Get the length of the @p i th dimension.
*/
size_t length(const int i) const {
/* pre-condition */
assert(i >= 0 && i < count());
if (i == 0) {
return head.length;
} else {
return tail.length(i - 1);
}
}
/**
* Get the stride of the @p i th dimension.
*/
size_t stride(const int i) const {
/* pre-condition */
assert(i >= 0 && i < count());
if (i == 0) {
return head.stride;
} else {
return tail.stride(i - 1);
}
}
/**
* Get lengths.
*
* @tparam T1 Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class T1>
void lengths(T1* out) const {
*out = head.length;
tail.lengths(out + 1);
}
/**
* Get strides.
*
* @tparam T1 Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class T1>
void strides(T1* out) const {
*out = head.stride;
tail.strides(out + 1);
}
//@}
/**
* @name Reductions
*/
//@{
/**
* Number of dimensions.
*/
static constexpr int count() {
return 1 + Tail::count();
}
/**
* Product of all lengths.
*/
size_t size() const {
return head.length*tail.size();
}
/**
* Product of all strides.
*/
size_t volume() const {
return head.length*head.stride;
}
/**
* Size of contiguous blocks.
*/
size_t block() const {
size_t block = tail.block();
return head.stride == block ? head.length*head.stride : block;
}
/**
* Serial offset for a view.
*/
template<class View>
ptrdiff_t serial(const View& o) const {
assert(o.head.offset >= 0 && o.head.offset < head.length);
return o.head.offset * head.stride + tail.serial(o.tail);
}
/**
* Are all elements stored contiguously in memory?
*/
bool contiguous() const {
return volume() == size();
}
//@}
/**
* Equality operator.
*/
template<class Head1, class Tail1>
bool operator==(const NonemptyFrame<Head1,Tail1>& o) const {
return head == o.head && tail == o.tail;
}
/**
* Equality operator.
*/
bool operator==(const EmptyFrame& o) const {
return false;
}
/**
* Unequality operator.
*/
template<class Frame1>
bool operator!=(const Frame1& o) const {
return !(*this == o);
}
/**
* Head.
*/
Head head;
/**
* Tail
*/
Tail tail;
};
/**
* Default frame for `D` dimensions.
*/
template<int D>
struct DefaultFrame {
typedef NonemptyFrame<Span<>,typename DefaultFrame<D - 1>::type> type;
};
template<>
struct DefaultFrame<0> {
typedef EmptyFrame type;
};
}
<|endoftext|> |
<commit_before>// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#include "stdtest.h"
template <typename T, size_t N>
void TestArray (const char* ctrType)
{
cout << "================================================" << endl;
cout << "Testing " << ctrType << endl;
cout << "================================================" << endl;
assert (N <= 8);
#if HAVE_CPP11
array<T,N> pt1 ({1,2,3,4,5,6,7,8});
array<T,N> pt2;
pt2 = {4,4,4,4};
pt2 += {1,2,3,4};
#else
T pt1v[12] = { 1, 2, 3, 4, 5, 6, 7, 8 };
array<T,N> pt1 (pt1v);
array<T,N> pt2 (&pt1v[4]);
#endif
cout << "pt1:\t\t\tsize = " << pt1.size() << ", value = " << pt1 << endl;
cout << "pt2:\t\t\t" << pt2 << endl;
iota (pt2.begin(), pt2.end(), 10);
cout << "pt2:\t\t\t" << pt2 << endl;
pt1 *= 3;
cout << "pt1 *= 3:\t\t" << pt1 << endl;
pt1 /= 3;
cout << "pt1 /= 3:\t\t" << pt1 << endl;
pt1 += 3;
cout << "pt1 += 3:\t\t" << pt1 << endl;
pt1 -= 3;
cout << "pt1 -= 3:\t\t" << pt1 << endl;
pt1 *= pt2;
cout << "pt1 *= pt2:\t\t" << pt1 << endl;
pt1 /= pt2;
cout << "pt1 /= pt2:\t\t" << pt1 << endl;
pt1 += pt2;
cout << "pt1 += pt2:\t\t" << pt1 << endl;
pt1 -= pt2;
cout << "pt1 -= pt2:\t\t" << pt1 << endl;
pt1 = pt1 * pt2;
cout << "pt1 = pt1 * pt2:\t" << pt1 << endl;
pt1 = pt1 / pt2;
cout << "pt1 = pt1 / pt2:\t" << pt1 << endl;
pt1 = pt1 + pt2;
cout << "pt1 = pt1 + pt2:\t" << pt1 << endl;
pt1 = pt1 - pt2;
cout << "pt1 = pt1 - pt2:\t" << pt1 << endl;
}
void TestIntegralArrays (void)
{
TestArray<float,4> ("array<float,4>");
TestArray<float,2> ("array<float,2>");
TestArray<int32_t,4> ("array<int32_t,4>");
TestArray<uint32_t,4> ("array<uint32_t,4>");
TestArray<int32_t,2> ("array<int32_t,2>");
TestArray<uint32_t,2> ("array<uint32_t,2>");
TestArray<int16_t,4> ("array<int16_t,4>");
TestArray<uint16_t,4> ("array<uint16_t,4>");
TestArray<int8_t,8> ("array<int8_t,8>");
TestArray<uint8_t,8> ("array<uint8_t,8>");
cout << "================================================" << endl;
cout << "Testing array<string,3>" << endl;
cout << "================================================" << endl;
array<string,3> strv;
strv[0] = "str0";
strv[1] = "str1";
strv[2] = "str2";
cout << "str: " << strv << endl;
}
StdBvtMain (TestIntegralArrays)
<commit_msg>Fix too short test sequences in array bvt<commit_after>// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#include "stdtest.h"
template <typename T, size_t N>
void TestArray (const char* ctrType)
{
cout << "================================================" << endl;
cout << "Testing " << ctrType << endl;
cout << "================================================" << endl;
assert (N <= 8);
#if HAVE_CPP11
array<T,N> pt1 = {1,2,3,4,5,6,7,8};
array<T,N> pt2;
pt2 = {4,4,4,4,4,4,4,4};
pt2 += {1,2,3,4,1,2,3,4};
#else
T pt1v[12] = { 1, 2, 3, 4, 5, 6, 7, 8 };
array<T,N> pt1 (pt1v);
array<T,N> pt2 (&pt1v[4]);
#endif
cout << "pt1:\t\t\tsize = " << pt1.size() << ", value = " << pt1 << endl;
cout << "pt2:\t\t\t" << pt2 << endl;
iota (pt2.begin(), pt2.end(), 10);
cout << "pt2:\t\t\t" << pt2 << endl;
pt1 *= 3;
cout << "pt1 *= 3:\t\t" << pt1 << endl;
pt1 /= 3;
cout << "pt1 /= 3:\t\t" << pt1 << endl;
pt1 += 3;
cout << "pt1 += 3:\t\t" << pt1 << endl;
pt1 -= 3;
cout << "pt1 -= 3:\t\t" << pt1 << endl;
pt1 *= pt2;
cout << "pt1 *= pt2:\t\t" << pt1 << endl;
pt1 /= pt2;
cout << "pt1 /= pt2:\t\t" << pt1 << endl;
pt1 += pt2;
cout << "pt1 += pt2:\t\t" << pt1 << endl;
pt1 -= pt2;
cout << "pt1 -= pt2:\t\t" << pt1 << endl;
pt1 = pt1 * pt2;
cout << "pt1 = pt1 * pt2:\t" << pt1 << endl;
pt1 = pt1 / pt2;
cout << "pt1 = pt1 / pt2:\t" << pt1 << endl;
pt1 = pt1 + pt2;
cout << "pt1 = pt1 + pt2:\t" << pt1 << endl;
pt1 = pt1 - pt2;
cout << "pt1 = pt1 - pt2:\t" << pt1 << endl;
}
void TestIntegralArrays (void)
{
TestArray<float,4> ("array<float,4>");
TestArray<float,2> ("array<float,2>");
TestArray<int32_t,4> ("array<int32_t,4>");
TestArray<uint32_t,4> ("array<uint32_t,4>");
TestArray<int32_t,2> ("array<int32_t,2>");
TestArray<uint32_t,2> ("array<uint32_t,2>");
TestArray<int16_t,4> ("array<int16_t,4>");
TestArray<uint16_t,4> ("array<uint16_t,4>");
TestArray<int8_t,8> ("array<int8_t,8>");
TestArray<uint8_t,8> ("array<uint8_t,8>");
cout << "================================================" << endl;
cout << "Testing array<string,3>" << endl;
cout << "================================================" << endl;
array<string,3> strv;
strv[0] = "str0";
strv[1] = "str1";
strv[2] = "str2";
cout << "str: " << strv << endl;
}
StdBvtMain (TestIntegralArrays)
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unopool.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:28:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_UNOPOOL_HXX_
#define _SVX_UNOPOOL_HXX_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_
#include <comphelper/propertysethelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
class SdrModel;
class SfxItemPool;
/** This class implements the service com.sun.star.drawing.Defaults.
It works on the SfxItemPool from the given model and the global
draw object item pool.
The class can work in a read only mode without a model. Derivated
classes can set a model on demand by overiding getModelPool().
*/
class SVX_DLLPUBLIC SvxUnoDrawPool : public ::cppu::OWeakAggObject,
public ::com::sun::star::lang::XServiceInfo,
public ::com::sun::star::lang::XTypeProvider,
public comphelper::PropertySetHelper
{
public:
SvxUnoDrawPool( SdrModel* pModel, sal_Int32 nServiceId ) throw();
/** deprecated */
SvxUnoDrawPool( SdrModel* pModel ) throw();
virtual ~SvxUnoDrawPool() throw();
/** This returns the item pool from the given model, or the default pool if there is no model and bReadOnly is true.
If bReadOnly is false and there is no model the default implementation returns NULL.
*/
virtual SfxItemPool* getModelPool( sal_Bool bReadOnly ) throw();
// overiden helpers from comphelper::PropertySetHelper
virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException );
virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );
virtual void _getPropertyStates( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::beans::PropertyState* pStates ) throw(::com::sun::star::beans::UnknownPropertyException );
virtual void _setPropertyToDefault( const comphelper::PropertyMapEntry* pEntry ) throw(::com::sun::star::beans::UnknownPropertyException );
virtual ::com::sun::star::uno::Any _getPropertyDefault( const comphelper::PropertyMapEntry* pEntry ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
protected:
void init();
virtual void getAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException);
virtual void putAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException);
protected:
SdrModel* mpModel;
SfxItemPool* mpDefaultsPool;
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.1256); FILE MERGED 2008/04/01 15:49:25 thb 1.7.1256.3: #i85898# Stripping all external header guards 2008/04/01 12:46:28 thb 1.7.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:18:01 rt 1.7.1256.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: unopool.hxx,v $
* $Revision: 1.8 $
*
* 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 _SVX_UNOPOOL_HXX_
#define _SVX_UNOPOOL_HXX_
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <comphelper/propertysethelper.hxx>
#include <cppuhelper/implbase4.hxx>
#include "svx/svxdllapi.h"
class SdrModel;
class SfxItemPool;
/** This class implements the service com.sun.star.drawing.Defaults.
It works on the SfxItemPool from the given model and the global
draw object item pool.
The class can work in a read only mode without a model. Derivated
classes can set a model on demand by overiding getModelPool().
*/
class SVX_DLLPUBLIC SvxUnoDrawPool : public ::cppu::OWeakAggObject,
public ::com::sun::star::lang::XServiceInfo,
public ::com::sun::star::lang::XTypeProvider,
public comphelper::PropertySetHelper
{
public:
SvxUnoDrawPool( SdrModel* pModel, sal_Int32 nServiceId ) throw();
/** deprecated */
SvxUnoDrawPool( SdrModel* pModel ) throw();
virtual ~SvxUnoDrawPool() throw();
/** This returns the item pool from the given model, or the default pool if there is no model and bReadOnly is true.
If bReadOnly is false and there is no model the default implementation returns NULL.
*/
virtual SfxItemPool* getModelPool( sal_Bool bReadOnly ) throw();
// overiden helpers from comphelper::PropertySetHelper
virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException );
virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );
virtual void _getPropertyStates( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::beans::PropertyState* pStates ) throw(::com::sun::star::beans::UnknownPropertyException );
virtual void _setPropertyToDefault( const comphelper::PropertyMapEntry* pEntry ) throw(::com::sun::star::beans::UnknownPropertyException );
virtual ::com::sun::star::uno::Any _getPropertyDefault( const comphelper::PropertyMapEntry* pEntry ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
protected:
void init();
virtual void getAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException);
virtual void putAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException);
protected:
SdrModel* mpModel;
SfxItemPool* mpDefaultsPool;
};
#endif
<|endoftext|> |
<commit_before>#include <osgUtil/TriStripVisitor>
#include "TriangleStripVisitor"
void TriangleStripVisitor::apply(osg::Geometry& geometry) {
osgUtil::TriStripVisitor tristrip;
tristrip.setCacheSize(_cacheSize);
tristrip.setMinStripSize(_minSize);
tristrip.stripify(geometry);
// merge stritrip to one using degenerated triangles as glue
if (_merge) {
mergeTrianglesStrip(geometry);
}
}
void TriangleStripVisitor::mergeTrianglesStrip(osg::Geometry& geometry)
{
int nbtristrip = 0;
int nbtristripVertexes = 0;
for (unsigned int i = 0; i < geometry.getNumPrimitiveSets(); i++) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
osg::DrawElements* de = ps->getDrawElements();
if (de && de->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP) {
nbtristrip++;
nbtristripVertexes += de->getNumIndices();
}
}
if (nbtristrip > 0) {
osg::notify(osg::NOTICE) << "found " << nbtristrip << " tristrip, "
<< "total vertexes " << nbtristripVertexes
<< " should result to " << nbtristripVertexes + nbtristrip*2
<< " after connection" << std::endl;
osg::DrawElementsUShort* ndw = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP);
for (unsigned int i = 0 ; i < geometry.getNumPrimitiveSets() ; ++ i) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
if (ps && ps->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP) {
osg::DrawElements* de = ps->getDrawElements();
if (de) {
// if connection needed insert degenerate triangles
if (ndw->getNumIndices() != 0 && ndw->back() != de->getElement(0)) {
// duplicate last vertex
ndw->addElement(ndw->back());
// insert first vertex of next strip
ndw->addElement(de->getElement(0));
}
if (ndw->getNumIndices() % 2 != 0 ) {
// add a dummy vertex to reverse the strip
ndw->addElement(de->getElement(0));
}
for (unsigned int j = 0; j < de->getNumIndices(); j++) {
ndw->addElement(de->getElement(j));
}
}
else if (ps->getType() == osg::PrimitiveSet::DrawArraysPrimitiveType) {
// trip strip can generate drawarray of 5 elements we want to merge them too
osg::DrawArrays* da = dynamic_cast<osg::DrawArrays*> (ps);
// if connection needed insert degenerate triangles
if (ndw->getNumIndices() != 0 && ndw->back() != da->getFirst()) {
// duplicate last vertex
ndw->addElement(ndw->back());
// insert first vertex of next strip
ndw->addElement(da->getFirst());
}
if (ndw->getNumIndices() % 2 != 0 ) {
// add a dummy vertex to reverse the strip
ndw->addElement(da->getFirst());
}
for (unsigned int j = 0; j < da->getNumIndices(); j++) {
ndw->addElement(da->getFirst() + j);
}
}
}
}
for (int i = geometry.getNumPrimitiveSets() - 1 ; i >= 0 ; -- i) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
// remove null primitive sets and all primitives that have been merged
// (i.e. all TRIANGLE_STRIP DrawElements and DrawArrays)
if (!ps || (ps && ps->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP)) {
geometry.getPrimitiveSetList().erase(geometry.getPrimitiveSetList().begin() + i);
}
}
geometry.getPrimitiveSetList().insert(geometry.getPrimitiveSetList().begin(), ndw);
}
}
<commit_msg>Added handling of null dynamic_cast.<commit_after>#include <osgUtil/TriStripVisitor>
#include "TriangleStripVisitor"
void TriangleStripVisitor::apply(osg::Geometry& geometry) {
osgUtil::TriStripVisitor tristrip;
tristrip.setCacheSize(_cacheSize);
tristrip.setMinStripSize(_minSize);
tristrip.stripify(geometry);
// merge stritrip to one using degenerated triangles as glue
if (_merge) {
mergeTrianglesStrip(geometry);
}
}
void TriangleStripVisitor::mergeTrianglesStrip(osg::Geometry& geometry)
{
int nbtristrip = 0;
int nbtristripVertexes = 0;
for (unsigned int i = 0; i < geometry.getNumPrimitiveSets(); i++) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
osg::DrawElements* de = ps->getDrawElements();
if (de && de->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP) {
nbtristrip++;
nbtristripVertexes += de->getNumIndices();
}
}
if (nbtristrip > 0) {
osg::notify(osg::NOTICE) << "found " << nbtristrip << " tristrip, "
<< "total vertexes " << nbtristripVertexes
<< " should result to " << nbtristripVertexes + nbtristrip*2
<< " after connection" << std::endl;
osg::DrawElementsUShort* ndw = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP);
for (unsigned int i = 0 ; i < geometry.getNumPrimitiveSets() ; ++ i) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
if (ps && ps->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP) {
osg::DrawElements* de = ps->getDrawElements();
if (de) {
// if connection needed insert degenerate triangles
if (ndw->getNumIndices() != 0 && ndw->back() != de->getElement(0)) {
// duplicate last vertex
ndw->addElement(ndw->back());
// insert first vertex of next strip
ndw->addElement(de->getElement(0));
}
if (ndw->getNumIndices() % 2 != 0 ) {
// add a dummy vertex to reverse the strip
ndw->addElement(de->getElement(0));
}
for (unsigned int j = 0; j < de->getNumIndices(); j++) {
ndw->addElement(de->getElement(j));
}
}
else if (ps->getType() == osg::PrimitiveSet::DrawArraysPrimitiveType) {
// trip strip can generate drawarray of 5 elements we want to merge them too
osg::DrawArrays* da = dynamic_cast<osg::DrawArrays*> (ps);
if (da)
{
// if connection needed insert degenerate triangles
if (ndw->getNumIndices() != 0 && ndw->back() != da->getFirst()) {
// duplicate last vertex
ndw->addElement(ndw->back());
// insert first vertex of next strip
ndw->addElement(da->getFirst());
}
if (ndw->getNumIndices() % 2 != 0 ) {
// add a dummy vertex to reverse the strip
ndw->addElement(da->getFirst());
}
for (unsigned int j = 0; j < da->getNumIndices(); j++) {
ndw->addElement(da->getFirst() + j);
}
}
}
}
}
for (int i = geometry.getNumPrimitiveSets() - 1 ; i >= 0 ; -- i) {
osg::PrimitiveSet* ps = geometry.getPrimitiveSet(i);
// remove null primitive sets and all primitives that have been merged
// (i.e. all TRIANGLE_STRIP DrawElements and DrawArrays)
if (!ps || (ps && ps->getMode() == osg::PrimitiveSet::TRIANGLE_STRIP)) {
geometry.getPrimitiveSetList().erase(geometry.getPrimitiveSetList().begin() + i);
}
}
geometry.getPrimitiveSetList().insert(geometry.getPrimitiveSetList().begin(), ndw);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dbgoutsw.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2005-01-25 13:58:12 $
*
* 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 __DBGOUTSW_HXX
#define __DBGOUTSW_HXX
#ifdef DEBUG
#include <hash_map>
#include <tox.hxx>
class String;
class SwNode;
class SwTxtAttr;
class SwpHints;
class SfxPoolItem;
class SfxItemSet;
struct SwPosition;
class SwPaM;
class SwNodeNum;
class SwUndo;
class SwUndos;
class SwRect;
class SwFrmFmt;
class SwNodes;
class SwRewriter;
class SwNumRuleTbl;
#define DBG_OUT_HERE printf("%s(%d):", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN printf("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT_HERE_LN printf("%s(%d)\n", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN_LN printf("%s(%d) %s\n", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT(x) printf("%s\n", dbg_out(x))
#define DBG_OUT_LN(x) printf("%s(%d): %s\n", __FILE__, __LINE__, dbg_out(x))
#define DBG_OUT_FN_LN(x) printf("%s: %s\n", __FUNCTION__, dbg_out(x))
extern bool bDbgOutStdErr;
extern bool bDbgOutPrintAttrSet;
const char * dbg_out(const void * pVoid);
const char * dbg_out(const String & aStr);
const char * dbg_out(const SwRect & rRect);
const char * dbg_out(const SwFrmFmt & rFrmFmt);
const char * dbg_out(const SwNode & rNode);
const char * dbg_out(const SwTxtAttr & rAttr);
const char * dbg_out(const SwpHints &rHints);
const char * dbg_out(const SfxPoolItem & rItem);
const char * dbg_out(const SfxPoolItem * pItem);
const char * dbg_out(const SfxItemSet & rSet);
const char * dbg_out(SwNodes & rNodes);
const char * dbg_out(const SwPosition & rPos);
const char * dbg_out(const SwPaM & rPam);
const char * dbg_out(const SwNodeNum & rNum);
const char * dbg_out(const SwUndo & rUndo);
const char * dbg_out(const SwUndos & rUndos);
const char * dbg_out(const SwRewriter & rRewriter);
const char * dbg_out(const SwNumRule & rRule);
const char * dbg_out(const SwTxtFmtColl & rFmt);
const char * dbg_out(const SwFrmFmts & rFrmFmts);
const char * dbg_out(const SwNumRuleTbl & rTbl);
template<typename tKey, typename tMember, typename fHashFunction>
String lcl_dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
String aResult("[", RTL_TEXTENCODING_ASCII_US);
typename std::hash_map<tKey, tMember, fHashFunction>::const_iterator aIt;
for (aIt = rMap.begin(); aIt != rMap.end(); aIt++)
{
if (aIt != rMap.begin())
aResult += String(", ", RTL_TEXTENCODING_ASCII_US);
aResult += aIt->first;
char sBuffer[256];
sprintf(sBuffer, "(%p)", aIt->second);
aResult += String(sBuffer, RTL_TEXTENCODING_ASCII_US);
}
aResult += String("]", RTL_TEXTENCODING_ASCII_US);
return aResult;
}
template<typename tKey, typename tMember, typename fHashFunction>
const char * dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
return dbg_out(lcl_dbg_out(rMap));
}
const char * dbg_out(const SwFormToken & rToken);
const char * dbg_out(const SwFormTokens & rTokens);
#endif // DEBUG
#endif // __DBGOUTSW_HXX
<commit_msg>INTEGRATION: CWS swqcore05 (1.9.14); FILE MERGED 2005/01/14 16:26:05 hbrinkm 1.9.14.1: #i39673# output for SwOutlineNodes<commit_after>/*************************************************************************
*
* $RCSfile: dbgoutsw.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2005-02-21 16:01:31 $
*
* 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 __DBGOUTSW_HXX
#define __DBGOUTSW_HXX
#ifdef DEBUG
#include <hash_map>
#include <tox.hxx>
class String;
class SwNode;
class SwTxtAttr;
class SwpHints;
class SfxPoolItem;
class SfxItemSet;
struct SwPosition;
class SwPaM;
class SwNodeNum;
class SwUndo;
class SwUndos;
class SwRect;
class SwFrmFmt;
class SwNodes;
class SwRewriter;
class SwNumRuleTbl;
#define DBG_OUT_HERE printf("%s(%d):", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN printf("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT_HERE_LN printf("%s(%d)\n", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN_LN printf("%s(%d) %s\n", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT(x) printf("%s\n", dbg_out(x))
#define DBG_OUT_LN(x) printf("%s(%d): %s\n", __FILE__, __LINE__, dbg_out(x))
#define DBG_OUT_FN_LN(x) printf("%s: %s\n", __FUNCTION__, dbg_out(x))
extern bool bDbgOutStdErr;
extern bool bDbgOutPrintAttrSet;
const char * dbg_out(const void * pVoid);
const char * dbg_out(const String & aStr);
const char * dbg_out(const SwRect & rRect);
const char * dbg_out(const SwFrmFmt & rFrmFmt);
const char * dbg_out(const SwNode & rNode);
const char * dbg_out(const SwTxtAttr & rAttr);
const char * dbg_out(const SwpHints &rHints);
const char * dbg_out(const SfxPoolItem & rItem);
const char * dbg_out(const SfxPoolItem * pItem);
const char * dbg_out(const SfxItemSet & rSet);
const char * dbg_out(SwNodes & rNodes);
const char * dbg_out(SwOutlineNodes & rNodes);
const char * dbg_out(const SwPosition & rPos);
const char * dbg_out(const SwPaM & rPam);
const char * dbg_out(const SwNodeNum & rNum);
const char * dbg_out(const SwUndo & rUndo);
const char * dbg_out(const SwUndos & rUndos);
const char * dbg_out(const SwRewriter & rRewriter);
const char * dbg_out(const SwNumRule & rRule);
const char * dbg_out(const SwTxtFmtColl & rFmt);
const char * dbg_out(const SwFrmFmts & rFrmFmts);
const char * dbg_out(const SwNumRuleTbl & rTbl);
template<typename tKey, typename tMember, typename fHashFunction>
String lcl_dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
String aResult("[", RTL_TEXTENCODING_ASCII_US);
typename std::hash_map<tKey, tMember, fHashFunction>::const_iterator aIt;
for (aIt = rMap.begin(); aIt != rMap.end(); aIt++)
{
if (aIt != rMap.begin())
aResult += String(", ", RTL_TEXTENCODING_ASCII_US);
aResult += aIt->first;
char sBuffer[256];
sprintf(sBuffer, "(%p)", aIt->second);
aResult += String(sBuffer, RTL_TEXTENCODING_ASCII_US);
}
aResult += String("]", RTL_TEXTENCODING_ASCII_US);
return aResult;
}
template<typename tKey, typename tMember, typename fHashFunction>
const char * dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
return dbg_out(lcl_dbg_out(rMap));
}
const char * dbg_out(const SwFormToken & rToken);
const char * dbg_out(const SwFormTokens & rTokens);
#endif // DEBUG
#endif // __DBGOUTSW_HXX
<|endoftext|> |
<commit_before>#include "globalhandler.h"
#include "ipmid-api.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
const char *control_object_name = "/org/openbmc/control/bmc0";
const char *control_intf_name = "org.openbmc.control.Bmc";
const char *objectmapper_service_name = "org.openbmc.objectmapper";
const char *objectmapper_object_name = "/org/openbmc/objectmapper/objectmapper";
const char *objectmapper_intf_name = "org.openbmc.objectmapper.ObjectMapper";
void register_netfn_global_functions() __attribute__((constructor));
int obj_mapper_get_connection(char** buf, const char* obj_path)
{
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *m = NULL;
sd_bus *bus = NULL;
char *temp_buf = NULL, *intf = NULL;
size_t buf_size = 0;
int r;
//Get the system bus where most system services are provided.
bus = ipmid_get_sd_bus_connection();
/*
* Bus, service, object path, interface and method are provided to call
* the method.
* Signatures and input arguments are provided by the arguments at the
* end.
*/
r = sd_bus_call_method(bus,
objectmapper_service_name, /* service to contact */
objectmapper_object_name, /* object path */
objectmapper_intf_name, /* interface name */
"GetObject", /* method name */
&error, /* object to return error in */
&m, /* return message on success */
"s", /* input signature */
obj_path /* first argument */
);
if (r < 0) {
fprintf(stderr, "Failed to issue method call: %s\n", error.message);
goto finish;
}
// Get the key, aka, the connection name
sd_bus_message_read(m, "a{sas}", 1, &temp_buf, 1, &intf);
/*
* TODO: check the return code. Currently for no reason the message
* parsing of object mapper is always complaining about
* "Device or resource busy", but the result seems OK for now. Need
* further checks.
*/
buf_size = strlen(temp_buf) + 1;
printf("IPMID connection name: %s\n", temp_buf);
*buf = (char*)malloc(buf_size);
if (*buf == NULL) {
fprintf(stderr, "Malloc failed for warm reset");
r = -1;
goto finish;
}
memcpy(*buf, temp_buf, buf_size);
finish:
sd_bus_error_free(&error);
sd_bus_message_unref(m);
return r;
}
int dbus_warm_reset()
{
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *m = NULL;
sd_bus *bus = NULL;
char* temp_buf = NULL;
uint8_t* get_value = NULL;
char* connection = NULL;
int r, i;
r = obj_mapper_get_connection(&connection, control_object_name);
if (r < 0) {
fprintf(stderr, "Failed to get connection, return value: %d.\n", r);
goto finish;
}
printf("connection: %s\n", connection);
// Open the system bus where most system services are provided.
bus = ipmid_get_sd_bus_connection();
/*
* Bus, service, object path, interface and method are provided to call
* the method.
* Signatures and input arguments are provided by the arguments at the
* end.
*/
r = sd_bus_call_method(bus,
connection, /* service to contact */
control_object_name, /* object path */
control_intf_name, /* interface name */
"warmReset", /* method name */
&error, /* object to return error in */
&m, /* return message on success */
NULL,
NULL
);
if (r < 0) {
fprintf(stderr, "Failed to issue method call: %s\n", error.message);
goto finish;
}
finish:
sd_bus_error_free(&error);
sd_bus_message_unref(m);
free(connection);
return r;
}
ipmi_ret_t ipmi_global_warm_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling GLOBAL warmReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// TODO: call the correct dbus method for warmReset.
dbus_warm_reset();
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = 0;
return rc;
}
ipmi_ret_t ipmi_global_wildcard_handler(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling WILDCARD Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = strlen("THIS IS WILDCARD");
// Now pack actual response
memcpy(response, "THIS IS WILDCARD", *data_len);
return rc;
}
void register_netfn_global_functions()
{
printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WARM_RESET);
ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL, ipmi_global_warm_reset);
printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WILDCARD);
ipmi_register_callback(NETFUN_APP, IPMI_CMD_WILDCARD, NULL, ipmi_global_wildcard_handler);
return;
}
<commit_msg>Fixing the Duplicate registration for NetFn [0x6], Cmd:[0xFF]<commit_after>#include "globalhandler.h"
#include "ipmid-api.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
const char *control_object_name = "/org/openbmc/control/bmc0";
const char *control_intf_name = "org.openbmc.control.Bmc";
const char *objectmapper_service_name = "org.openbmc.objectmapper";
const char *objectmapper_object_name = "/org/openbmc/objectmapper/objectmapper";
const char *objectmapper_intf_name = "org.openbmc.objectmapper.ObjectMapper";
void register_netfn_global_functions() __attribute__((constructor));
int obj_mapper_get_connection(char** buf, const char* obj_path)
{
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *m = NULL;
sd_bus *bus = NULL;
char *temp_buf = NULL, *intf = NULL;
size_t buf_size = 0;
int r;
//Get the system bus where most system services are provided.
bus = ipmid_get_sd_bus_connection();
/*
* Bus, service, object path, interface and method are provided to call
* the method.
* Signatures and input arguments are provided by the arguments at the
* end.
*/
r = sd_bus_call_method(bus,
objectmapper_service_name, /* service to contact */
objectmapper_object_name, /* object path */
objectmapper_intf_name, /* interface name */
"GetObject", /* method name */
&error, /* object to return error in */
&m, /* return message on success */
"s", /* input signature */
obj_path /* first argument */
);
if (r < 0) {
fprintf(stderr, "Failed to issue method call: %s\n", error.message);
goto finish;
}
// Get the key, aka, the connection name
sd_bus_message_read(m, "a{sas}", 1, &temp_buf, 1, &intf);
/*
* TODO: check the return code. Currently for no reason the message
* parsing of object mapper is always complaining about
* "Device or resource busy", but the result seems OK for now. Need
* further checks.
*/
buf_size = strlen(temp_buf) + 1;
printf("IPMID connection name: %s\n", temp_buf);
*buf = (char*)malloc(buf_size);
if (*buf == NULL) {
fprintf(stderr, "Malloc failed for warm reset");
r = -1;
goto finish;
}
memcpy(*buf, temp_buf, buf_size);
finish:
sd_bus_error_free(&error);
sd_bus_message_unref(m);
return r;
}
int dbus_warm_reset()
{
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *m = NULL;
sd_bus *bus = NULL;
char* temp_buf = NULL;
uint8_t* get_value = NULL;
char* connection = NULL;
int r, i;
r = obj_mapper_get_connection(&connection, control_object_name);
if (r < 0) {
fprintf(stderr, "Failed to get connection, return value: %d.\n", r);
goto finish;
}
printf("connection: %s\n", connection);
// Open the system bus where most system services are provided.
bus = ipmid_get_sd_bus_connection();
/*
* Bus, service, object path, interface and method are provided to call
* the method.
* Signatures and input arguments are provided by the arguments at the
* end.
*/
r = sd_bus_call_method(bus,
connection, /* service to contact */
control_object_name, /* object path */
control_intf_name, /* interface name */
"warmReset", /* method name */
&error, /* object to return error in */
&m, /* return message on success */
NULL,
NULL
);
if (r < 0) {
fprintf(stderr, "Failed to issue method call: %s\n", error.message);
goto finish;
}
finish:
sd_bus_error_free(&error);
sd_bus_message_unref(m);
free(connection);
return r;
}
ipmi_ret_t ipmi_global_warm_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling GLOBAL warmReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// TODO: call the correct dbus method for warmReset.
dbus_warm_reset();
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = 0;
return rc;
}
ipmi_ret_t ipmi_global_wildcard_handler(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling WILDCARD Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = strlen("THIS IS WILDCARD");
// Now pack actual response
memcpy(response, "THIS IS WILDCARD", *data_len);
return rc;
}
void register_netfn_global_functions()
{
printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WARM_RESET);
ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL, ipmi_global_warm_reset);
return;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "newdialog.h"
#include "ui_newdialog.h"
#include "basefilewizard.h"
#include <utils/stylehelper.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/dialogs/iwizard.h>
#include <QtGui/QAbstractProxyModel>
#include <QtGui/QItemSelectionModel>
#include <QtGui/QHeaderView>
#include <QtGui/QPushButton>
#include <QtGui/QStandardItem>
#include <QtGui/QItemDelegate>
#include <QtGui/QPainter>
#include <QtCore/QDebug>
Q_DECLARE_METATYPE(Core::IWizard*)
namespace {
class TwoLevelProxyModel : public QAbstractProxyModel
{
// Q_OBJECT
public:
TwoLevelProxyModel(QObject *parent = 0): QAbstractProxyModel(parent) {}
QModelIndex index(int row, int column, const QModelIndex &parent) const
{
QModelIndex ourModelIndex = sourceModel()->index(row, column, mapToSource(parent));
return createIndex(row, column, ourModelIndex.internalPointer());
}
QModelIndex parent(const QModelIndex &index) const
{
return mapFromSource(mapToSource(index).parent());
}
int rowCount(const QModelIndex &index) const
{
if (index.isValid() && index.parent().isValid() && !index.parent().parent().isValid())
return 0;
else
return sourceModel()->rowCount(mapToSource(index));
}
int columnCount(const QModelIndex &index) const
{
return sourceModel()->columnCount(mapToSource(index));
}
QModelIndex mapFromSource (const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
return createIndex(index.row(), index.column(), index.internalPointer());
}
QModelIndex mapToSource (const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
return static_cast<TwoLevelProxyModel*>(sourceModel())->createIndex(index.row(), index.column(), index.internalPointer());
}
};
#define ROW_HEIGHT 24
class FancyTopLevelDelegate : public QItemDelegate
{
public:
FancyTopLevelDelegate(QObject *parent = 0)
: QItemDelegate(parent) {}
void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const
{
QStyleOptionViewItem newoption = option;
if (!(option.state & QStyle::State_Enabled)) {
QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
gradient.setColorAt(0, option.palette.window().color().lighter(106));
gradient.setColorAt(1, option.palette.window().color().darker(106));
painter->fillRect(rect, gradient);
painter->setPen(option.palette.window().color().darker(130));
if (rect.top())
painter->drawLine(rect.topRight(), rect.topLeft());
painter->drawLine(rect.bottomRight(), rect.bottomLeft());
// Fake enabled state
newoption.state |= newoption.state | QStyle::State_Enabled;
}
QItemDelegate::drawDisplay(painter, newoption, rect, text);
}
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize size = QItemDelegate::sizeHint(option, index);
size = size.expandedTo(QSize(0, ROW_HEIGHT));
return size;
}
};
inline Core::IWizard *wizardOfItem(const QStandardItem *item = 0)
{
if (!item)
return 0;
return item->data(Qt::UserRole).value<Core::IWizard*>();
}
}
using namespace Core;
using namespace Core::Internal;
NewDialog::NewDialog(QWidget *parent) :
QDialog(parent),
m_ui(new Core::Internal::Ui::NewDialog),
m_okButton(0),
m_preferredWizardKinds(0)
{
typedef QMap<QString, QStandardItem *> CategoryItemMap;
m_ui->setupUi(this);
m_okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
m_okButton->setDefault(true);
m_okButton->setText(tr("&Choose..."));
m_model = new QStandardItemModel(this);
m_proxyModel = new TwoLevelProxyModel(this);
m_proxyModel->setSourceModel(m_model);
m_ui->templateCategoryView->setModel(m_proxyModel);
m_ui->templateCategoryView->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_ui->templateCategoryView->setItemDelegate(new FancyTopLevelDelegate);
m_ui->templatesView->setIconSize(QSize(22, 22));
connect(m_ui->templateCategoryView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(currentCategoryChanged(const QModelIndex&)));
connect(m_ui->templatesView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(currentItemChanged(const QModelIndex&)));
connect(m_ui->templateCategoryView->selectionModel(),
SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)),
this, SLOT(currentCategoryChanged(const QModelIndex&)));
connect(m_ui->templatesView,
SIGNAL(doubleClicked(const QModelIndex&)),
this, SLOT(okButtonClicked()));
connect(m_okButton, SIGNAL(clicked()), this, SLOT(okButtonClicked()));
connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
// Sort by category. id
bool wizardLessThan(const IWizard *w1, const IWizard *w2)
{
if (const int cc = w1->category().compare(w2->category()))
return cc < 0;
return w1->id().compare(w2->id()) < 0;
}
void NewDialog::setPreferredWizardKinds(IWizard::WizardKinds kinds)
{
m_preferredWizardKinds = kinds;
}
void NewDialog::setWizards(QList<IWizard*> wizards)
{
typedef QMap<QString, QStandardItem *> CategoryItemMap;
qStableSort(wizards.begin(), wizards.end(), wizardLessThan);
CategoryItemMap categories;
m_model->clear();
QStandardItem *projectKindItem = new QStandardItem(tr("Projects"));
projectKindItem->setData(IWizard::ProjectWizard, Qt::UserRole);
projectKindItem->setFlags(0); // disable item to prevent focus
QStandardItem *filesClassesKindItem = new QStandardItem(tr("Files and Classes"));
filesClassesKindItem->setData(IWizard::FileWizard, Qt::UserRole);
filesClassesKindItem->setFlags(0); // disable item to prevent focus
QStandardItem *parentItem = m_model->invisibleRootItem();
parentItem->appendRow(projectKindItem);
parentItem->appendRow(filesClassesKindItem);
if (m_dummyIcon.isNull()) {
m_dummyIcon = QPixmap(22, 22);
m_dummyIcon.fill(Qt::transparent);
}
foreach (IWizard *wizard, wizards) {
// ensure category root
const QString categoryName = wizard->category();
CategoryItemMap::iterator cit = categories.find(categoryName);
if (cit == categories.end()) {
QStandardItem *categoryItem = new QStandardItem();
QStandardItem *kindItem;
switch (wizard->kind()) {
case IWizard::ProjectWizard:
kindItem = projectKindItem;
break;
case IWizard::ClassWizard:
case IWizard::FileWizard:
default:
kindItem = filesClassesKindItem;
break;
}
kindItem->appendRow(categoryItem);
categoryItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
categoryItem->setText(wizard->displayCategory());
categoryItem->setData(QVariant::fromValue(0), Qt::UserRole);
cit = categories.insert(categoryName, categoryItem);
}
// add item
QStandardItem *wizardItem = new QStandardItem(wizard->displayName());
QIcon wizardIcon;
// spacing hack. Add proper icons instead
if (wizard->icon().isNull())
wizardIcon = m_dummyIcon;
else
wizardIcon = wizard->icon();
wizardItem->setIcon(wizardIcon);
wizardItem->setData(QVariant::fromValue(wizard), Qt::UserRole);
wizardItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
cit.value()->appendRow(wizardItem);
}
if (!projectKindItem->hasChildren()) {
QModelIndex idx = projectKindItem->index();
m_model->removeRow(idx.row());
}
if (!filesClassesKindItem->hasChildren()) {
QModelIndex idx = filesClassesKindItem->index();
m_model->removeRow(idx.row());
}
}
Core::IWizard *NewDialog::showDialog()
{
// Select first category, first item by default
m_ui->templateCategoryView->setCurrentIndex(m_proxyModel->index(0,0, m_proxyModel->index(0,0)));
// We need to set ensure that the category has default focus
m_ui->templateCategoryView->setFocus(Qt::NoFocusReason);
for (int row = 0; row < m_proxyModel->rowCount(); ++row)
m_ui->templateCategoryView->setExpanded(m_proxyModel->index(row, 0), true);
updateOkButton();
if (exec() != Accepted)
return 0;
return currentWizard();
}
NewDialog::~NewDialog()
{
delete m_ui;
}
IWizard *NewDialog::currentWizard() const
{
return wizardOfItem(m_model->itemFromIndex(m_ui->templatesView->currentIndex()));
}
void NewDialog::currentCategoryChanged(const QModelIndex &index)
{
if (index.parent() != m_model->invisibleRootItem()->index()) {
m_ui->templatesView->setModel(m_model);
m_ui->templatesView->setRootIndex(m_proxyModel->mapToSource(index));
// Focus the first item by default
m_ui->templatesView->setCurrentIndex(m_ui->templatesView->rootIndex().child(0,0));
connect(m_ui->templatesView->selectionModel(),
SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)),
this, SLOT(currentItemChanged(const QModelIndex&)));
}
}
void NewDialog::currentItemChanged(const QModelIndex &index)
{
QStandardItem* cat = m_model->itemFromIndex(index);
if (const IWizard *wizard = wizardOfItem(cat))
m_ui->templateDescription->setText(wizard->description());
else
m_ui->templateDescription->setText(QString());
updateOkButton();
}
void NewDialog::okButtonClicked()
{
if (m_ui->templatesView->currentIndex().isValid())
accept();
}
void NewDialog::updateOkButton()
{
m_okButton->setEnabled(currentWizard() != 0);
}
<commit_msg>Make new dialog description text visible on first show<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "newdialog.h"
#include "ui_newdialog.h"
#include "basefilewizard.h"
#include <utils/stylehelper.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/dialogs/iwizard.h>
#include <QtGui/QAbstractProxyModel>
#include <QtGui/QItemSelectionModel>
#include <QtGui/QHeaderView>
#include <QtGui/QPushButton>
#include <QtGui/QStandardItem>
#include <QtGui/QItemDelegate>
#include <QtGui/QPainter>
#include <QtCore/QDebug>
Q_DECLARE_METATYPE(Core::IWizard*)
namespace {
class TwoLevelProxyModel : public QAbstractProxyModel
{
// Q_OBJECT
public:
TwoLevelProxyModel(QObject *parent = 0): QAbstractProxyModel(parent) {}
QModelIndex index(int row, int column, const QModelIndex &parent) const
{
QModelIndex ourModelIndex = sourceModel()->index(row, column, mapToSource(parent));
return createIndex(row, column, ourModelIndex.internalPointer());
}
QModelIndex parent(const QModelIndex &index) const
{
return mapFromSource(mapToSource(index).parent());
}
int rowCount(const QModelIndex &index) const
{
if (index.isValid() && index.parent().isValid() && !index.parent().parent().isValid())
return 0;
else
return sourceModel()->rowCount(mapToSource(index));
}
int columnCount(const QModelIndex &index) const
{
return sourceModel()->columnCount(mapToSource(index));
}
QModelIndex mapFromSource (const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
return createIndex(index.row(), index.column(), index.internalPointer());
}
QModelIndex mapToSource (const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
return static_cast<TwoLevelProxyModel*>(sourceModel())->createIndex(index.row(), index.column(), index.internalPointer());
}
};
#define ROW_HEIGHT 24
class FancyTopLevelDelegate : public QItemDelegate
{
public:
FancyTopLevelDelegate(QObject *parent = 0)
: QItemDelegate(parent) {}
void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const
{
QStyleOptionViewItem newoption = option;
if (!(option.state & QStyle::State_Enabled)) {
QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
gradient.setColorAt(0, option.palette.window().color().lighter(106));
gradient.setColorAt(1, option.palette.window().color().darker(106));
painter->fillRect(rect, gradient);
painter->setPen(option.palette.window().color().darker(130));
if (rect.top())
painter->drawLine(rect.topRight(), rect.topLeft());
painter->drawLine(rect.bottomRight(), rect.bottomLeft());
// Fake enabled state
newoption.state |= newoption.state | QStyle::State_Enabled;
}
QItemDelegate::drawDisplay(painter, newoption, rect, text);
}
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize size = QItemDelegate::sizeHint(option, index);
size = size.expandedTo(QSize(0, ROW_HEIGHT));
return size;
}
};
inline Core::IWizard *wizardOfItem(const QStandardItem *item = 0)
{
if (!item)
return 0;
return item->data(Qt::UserRole).value<Core::IWizard*>();
}
}
using namespace Core;
using namespace Core::Internal;
NewDialog::NewDialog(QWidget *parent) :
QDialog(parent),
m_ui(new Core::Internal::Ui::NewDialog),
m_okButton(0),
m_preferredWizardKinds(0)
{
typedef QMap<QString, QStandardItem *> CategoryItemMap;
m_ui->setupUi(this);
m_okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
m_okButton->setDefault(true);
m_okButton->setText(tr("&Choose..."));
m_model = new QStandardItemModel(this);
m_proxyModel = new TwoLevelProxyModel(this);
m_proxyModel->setSourceModel(m_model);
m_ui->templateCategoryView->setModel(m_proxyModel);
m_ui->templateCategoryView->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_ui->templateCategoryView->setItemDelegate(new FancyTopLevelDelegate);
m_ui->templatesView->setIconSize(QSize(22, 22));
connect(m_ui->templateCategoryView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(currentCategoryChanged(const QModelIndex&)));
connect(m_ui->templatesView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(currentItemChanged(const QModelIndex&)));
connect(m_ui->templateCategoryView->selectionModel(),
SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)),
this, SLOT(currentCategoryChanged(const QModelIndex&)));
connect(m_ui->templatesView,
SIGNAL(doubleClicked(const QModelIndex&)),
this, SLOT(okButtonClicked()));
connect(m_okButton, SIGNAL(clicked()), this, SLOT(okButtonClicked()));
connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
// Sort by category. id
bool wizardLessThan(const IWizard *w1, const IWizard *w2)
{
if (const int cc = w1->category().compare(w2->category()))
return cc < 0;
return w1->id().compare(w2->id()) < 0;
}
void NewDialog::setPreferredWizardKinds(IWizard::WizardKinds kinds)
{
m_preferredWizardKinds = kinds;
}
void NewDialog::setWizards(QList<IWizard*> wizards)
{
typedef QMap<QString, QStandardItem *> CategoryItemMap;
qStableSort(wizards.begin(), wizards.end(), wizardLessThan);
CategoryItemMap categories;
m_model->clear();
QStandardItem *projectKindItem = new QStandardItem(tr("Projects"));
projectKindItem->setData(IWizard::ProjectWizard, Qt::UserRole);
projectKindItem->setFlags(0); // disable item to prevent focus
QStandardItem *filesClassesKindItem = new QStandardItem(tr("Files and Classes"));
filesClassesKindItem->setData(IWizard::FileWizard, Qt::UserRole);
filesClassesKindItem->setFlags(0); // disable item to prevent focus
QStandardItem *parentItem = m_model->invisibleRootItem();
parentItem->appendRow(projectKindItem);
parentItem->appendRow(filesClassesKindItem);
if (m_dummyIcon.isNull()) {
m_dummyIcon = QPixmap(22, 22);
m_dummyIcon.fill(Qt::transparent);
}
foreach (IWizard *wizard, wizards) {
// ensure category root
const QString categoryName = wizard->category();
CategoryItemMap::iterator cit = categories.find(categoryName);
if (cit == categories.end()) {
QStandardItem *categoryItem = new QStandardItem();
QStandardItem *kindItem;
switch (wizard->kind()) {
case IWizard::ProjectWizard:
kindItem = projectKindItem;
break;
case IWizard::ClassWizard:
case IWizard::FileWizard:
default:
kindItem = filesClassesKindItem;
break;
}
kindItem->appendRow(categoryItem);
categoryItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
categoryItem->setText(wizard->displayCategory());
categoryItem->setData(QVariant::fromValue(0), Qt::UserRole);
cit = categories.insert(categoryName, categoryItem);
}
// add item
QStandardItem *wizardItem = new QStandardItem(wizard->displayName());
QIcon wizardIcon;
// spacing hack. Add proper icons instead
if (wizard->icon().isNull())
wizardIcon = m_dummyIcon;
else
wizardIcon = wizard->icon();
wizardItem->setIcon(wizardIcon);
wizardItem->setData(QVariant::fromValue(wizard), Qt::UserRole);
wizardItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
cit.value()->appendRow(wizardItem);
}
if (!projectKindItem->hasChildren()) {
QModelIndex idx = projectKindItem->index();
m_model->removeRow(idx.row());
}
if (!filesClassesKindItem->hasChildren()) {
QModelIndex idx = filesClassesKindItem->index();
m_model->removeRow(idx.row());
}
}
Core::IWizard *NewDialog::showDialog()
{
// Select first category, first item by default
m_ui->templateCategoryView->setCurrentIndex(m_proxyModel->index(0,0, m_proxyModel->index(0,0)));
// We need to set ensure that the category has default focus
m_ui->templateCategoryView->setFocus(Qt::NoFocusReason);
for (int row = 0; row < m_proxyModel->rowCount(); ++row)
m_ui->templateCategoryView->setExpanded(m_proxyModel->index(row, 0), true);
// Ensure that item description is visible on first show
currentItemChanged(m_ui->templatesView->rootIndex().child(0,0));
updateOkButton();
if (exec() != Accepted)
return 0;
return currentWizard();
}
NewDialog::~NewDialog()
{
delete m_ui;
}
IWizard *NewDialog::currentWizard() const
{
return wizardOfItem(m_model->itemFromIndex(m_ui->templatesView->currentIndex()));
}
void NewDialog::currentCategoryChanged(const QModelIndex &index)
{
if (index.parent() != m_model->invisibleRootItem()->index()) {
m_ui->templatesView->setModel(m_model);
m_ui->templatesView->setRootIndex(m_proxyModel->mapToSource(index));
// Focus the first item by default
m_ui->templatesView->setCurrentIndex(m_ui->templatesView->rootIndex().child(0,0));
connect(m_ui->templatesView->selectionModel(),
SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)),
this, SLOT(currentItemChanged(const QModelIndex&)));
}
}
void NewDialog::currentItemChanged(const QModelIndex &index)
{
QStandardItem* cat = m_model->itemFromIndex(index);
if (const IWizard *wizard = wizardOfItem(cat))
m_ui->templateDescription->setText(wizard->description());
else
m_ui->templateDescription->setText(QString());
updateOkButton();
}
void NewDialog::okButtonClicked()
{
if (m_ui->templatesView->currentIndex().isValid())
accept();
}
void NewDialog::updateOkButton()
{
m_okButton->setEnabled(currentWizard() != 0);
}
<|endoftext|> |
<commit_before>/***************************************************************************
kmsystemtray.cpp - description
-------------------
begin : Fri Aug 31 22:38:44 EDT 2001
copyright : (C) 2001 by Ryan Breen
email : ryan@porivo.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <kapplication.h>
#include <kpopupmenu.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kwin.h>
#include <qevent.h>
#include <qfontmetrics.h>
#include <qlistview.h>
#include <qstring.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qwidgetlist.h>
#include <kglobalsettings.h>
#include <kiconeffect.h>
#include <qpainter.h>
#include <math.h>
#include "kaction.h"
#include "kmsystemtray.h"
#include "kmfolder.h"
#include "kmfoldertree.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwidget.h"
/**
* Construct a KSystemTray icon to be displayed when new mail
* has arrived in a non-system folder. The KMSystemTray listens
* for updateNewMessageNotification events from each non-system
* KMFolder and maintains a store of all folders with unread
* messages.
*
* The KMSystemTray also provides a popup menu listing each folder
* with its count of unread messages, allowing the user to jump
* to the first unread message in each folder.
*/
KMSystemTray::KMSystemTray(QWidget *parent, const char *name) : KSystemTray(parent, name),
mNewMessagePopupId(-1), mPopupMenu(0)
{
setAlignment( AlignCenter );
kdDebug(5006) << "Initting systray" << endl;
mDefaultIcon = SmallIcon( "kmail" );
mTransparentIcon = SmallIcon( "kmail" );
KIconEffect::semiTransparent( mTransparentIcon );
setPixmap(mDefaultIcon);
mParentVisible = true;
mMode = OnNewMail;
/** Initiate connections between folders and this object */
foldersChanged();
connect( kernel->folderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
connect( kernel->imapFolderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
connect( kernel->searchFolderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
}
void KMSystemTray::buildPopupMenu()
{
// Delete any previously created popup menu
delete mPopupMenu;
mPopupMenu = 0;
mPopupMenu = new KPopupMenu();
if (!getKMMainWidget())
return;
mPopupMenu->insertTitle(*(this->pixmap()), "KMail");
getKMMainWidget()->action("check_mail")->plug(mPopupMenu);
getKMMainWidget()->action("check_mail_in")->plug(mPopupMenu);
mPopupMenu->insertSeparator();
getKMMainWidget()->action("new_message")->plug(mPopupMenu);
getKMMainWidget()->action("kmail_configure_kmail")->plug(mPopupMenu);
mPopupMenu->insertSeparator();
if (getKMMainWidget()->action("file_quit"))
getKMMainWidget()->action("file_quit")->plug(mPopupMenu);
}
KMSystemTray::~KMSystemTray()
{
delete mPopupMenu;
mPopupMenu = 0;
}
void KMSystemTray::setMode(int newMode)
{
if(newMode == mMode) return;
kdDebug(5006) << "Setting systray mMode to " << newMode << endl;
mMode = newMode;
if(mMode == AlwaysOn)
{
kdDebug(5006) << "Initting alwayson mMode" << endl;
if(isHidden()) show();
} else
{
if(mCount == 0)
{
hide();
}
}
}
/**
* Update the count of unread messages. If there are unread messages,
* overlay the count on top of a transparent version of the KMail icon.
* If there is no unread mail, restore the normal KMail icon.
*/
void KMSystemTray::updateCount()
{
if(mCount != 0)
{
int oldPixmapWidth = pixmap()->size().width();
int oldPixmapHeight = pixmap()->size().height();
/** Scale the font size down with each increase in the number
* of digits in the count, to a minimum point size of 6 */
int numDigits = ((int) log10((double) mCount) + 1);
QFont countFont = KGlobalSettings::generalFont();
countFont.setBold(true);
int countFontSize = countFont.pointSize();
while(countFontSize > 5)
{
QFontMetrics qfm( countFont );
int fontWidth = qfm.width( QChar( '0' ) );
if((fontWidth * numDigits) > oldPixmapWidth)
{
--countFontSize;
countFont.setPointSize(countFontSize);
} else break;
}
QPixmap bg(oldPixmapWidth, oldPixmapHeight);
bg.fill(this, 0, 0);
/** Overlay count on transparent icon */
QPainter p(&bg);
p.drawPixmap(0, 0, mTransparentIcon);
p.setFont(countFont);
p.setPen(Qt::blue);
p.drawText(pixmap()->rect(), Qt::AlignCenter, QString::number(mCount));
setPixmap(bg);
} else
{
setPixmap(mDefaultIcon);
}
}
/**
* Refreshes the list of folders we are monitoring. This is called on
* startup and is also connected to the 'changed' signal on the KMFolderMgr.
*/
void KMSystemTray::foldersChanged()
{
/**
* Hide and remove all unread mappings to cover the case where the only
* unread message was in a folder that was just removed.
*/
mFoldersWithUnread.clear();
mCount = 0;
if(mMode == OnNewMail)
{
hide();
}
/** Disconnect all previous connections */
disconnect(this, SLOT(updateNewMessageNotification(KMFolder *)));
QStringList folderNames;
QValueList<QGuardedPtr<KMFolder> > folderList;
kernel->folderMgr()->createFolderList(&folderNames, &folderList);
kernel->imapFolderMgr()->createFolderList(&folderNames, &folderList);
kernel->searchFolderMgr()->createFolderList(&folderNames, &folderList);
QStringList::iterator strIt = folderNames.begin();
for(QValueList<QGuardedPtr<KMFolder> >::iterator it = folderList.begin();
it != folderList.end() && strIt != folderNames.end(); ++it, ++strIt)
{
KMFolder * currentFolder = *it;
QString currentName = *strIt;
if((!currentFolder->isSystemFolder() || (currentFolder->name().lower() == "inbox")) ||
(currentFolder->protocol() == "imap"))
{
/** If this is a new folder, start listening for messages */
connect(currentFolder, SIGNAL(numUnreadMsgsChanged(KMFolder *)),
this, SLOT(updateNewMessageNotification(KMFolder *)));
/** Check all new folders to see if we started with any new messages */
updateNewMessageNotification(currentFolder);
}
}
}
/**
* On left mouse click, switch focus to the first KMMainWidget. On right
* click, bring up a list of all folders with a count of unread messages.
*/
void KMSystemTray::mousePressEvent(QMouseEvent *e)
{
// switch to kmail on left mouse button
if( e->button() == LeftButton )
{
if( mParentVisible )
hideKMail();
else
showKMail();
}
// open popup menu on right mouse button
if( e->button() == RightButton )
{
mPopupFolders.clear();
mPopupFolders.resize(mFoldersWithUnread.count());
// Rebuild popup menu at click time to minimize race condition if
// the base KMainWidget is closed.
buildPopupMenu();
if(mNewMessagePopupId != -1)
{
mPopupMenu->removeItem(mNewMessagePopupId);
}
if(mFoldersWithUnread.count() > 0)
{
KPopupMenu *newMessagesPopup = new KPopupMenu();
QMap<QGuardedPtr<KMFolder>, int>::Iterator it = mFoldersWithUnread.begin();
for(uint i=0; it != mFoldersWithUnread.end(); ++i)
{
kdDebug(5006) << "Adding folder" << endl;
if(i > mPopupFolders.size()) mPopupFolders.resize(i * 2);
mPopupFolders.insert(i, it.key());
QString item = prettyName(it.key()) + "(" + QString::number(it.data()) + ")";
newMessagesPopup->insertItem(item, this, SLOT(selectedAccount(int)), 0, i);
++it;
}
mNewMessagePopupId = mPopupMenu->insertItem(i18n("New messages in..."),
newMessagesPopup, mNewMessagePopupId, 3);
kdDebug(5006) << "Folders added" << endl;
}
mPopupMenu->popup(e->globalPos());
}
}
/**
* Return the name of the folder in which the mail is deposited, prepended
* with the account name if the folder is IMAP.
*/
QString KMSystemTray::prettyName(KMFolder * fldr)
{
QString rvalue = fldr->label();
if(fldr->protocol() == "imap")
{
KMFolderImap * imap = dynamic_cast<KMFolderImap*> (fldr);
assert(imap);
if((imap->account() != 0) &&
(imap->account()->name() != 0) )
{
kdDebug(5006) << "IMAP folder, prepend label with type" << endl;
rvalue = imap->account()->name() + "->" + rvalue;
}
}
kdDebug(5006) << "Got label " << rvalue << endl;
return rvalue;
}
/**
* Shows and raises the first KMMainWidget and
* switches to the appropriate virtual desktop.
*/
void KMSystemTray::showKMail()
{
if (!getKMMainWidget())
return;
QWidget *mainWin = getKMMainWidget()->topLevelWidget();
assert(mainWin);
if(mainWin)
{
/** Force window to grab focus */
mainWin->show();
mainWin->raise();
mParentVisible = true;
/** Switch to appropriate desktop */
int desk = KWin::info(mainWin->winId()).desktop;
KWin::setCurrentDesktop(desk);
}
}
void KMSystemTray::hideKMail()
{
if (!getKMMainWidget())
return;
QWidget *mainWin = getKMMainWidget()->topLevelWidget();
assert(mainWin);
if(mainWin)
{
mainWin->hide();
mParentVisible = false;
}
}
/**
* Grab a pointer to the first KMMainWidget.
*/
KMMainWidget * KMSystemTray::getKMMainWidget()
{
QWidgetList *l = kapp->topLevelWidgets();
QWidgetListIt it( *l );
QWidget *wid;
while ( (wid = it.current()) != 0 ) {
++it;
QObjectList *l2 = wid->topLevelWidget()->queryList("KMMainWidget");
if (l2->first())
return dynamic_cast<KMMainWidget *>(l2->first());
}
return 0;
}
/**
* Called on startup of the KMSystemTray and when the numUnreadMsgsChanged signal
* is emitted for one of the watched folders. Shows the system tray icon if there
* are new messages and the icon was hidden, or hides the system tray icon if there
* are no more new messages.
*/
void KMSystemTray::updateNewMessageNotification(KMFolder * fldr)
{
if(!fldr)
{
kdDebug(5006) << "Null folder, can't mess with that" << endl;
return;
}
/** The number of unread messages in that folder */
int unread = fldr->countUnread();
QMap<QGuardedPtr<KMFolder>, int>::Iterator it =
mFoldersWithUnread.find(fldr);
bool unmapped = (it == mFoldersWithUnread.end());
/** If the folder is not mapped yet, increment count by numUnread
in folder */
if(unmapped) mCount += unread;
/* Otherwise, get the difference between the numUnread in the folder and
* our last known version, and adjust mCount with that difference */
else
{
int diff = unread - it.data();
mCount += diff;
}
if(unread > 0)
{
/** Add folder to our internal store, or update unread count if already mapped */
mFoldersWithUnread.insert(fldr, unread);
kdDebug(5006) << "There are now " << mFoldersWithUnread.count() << " folders with unread" << endl;
}
/**
* Look for folder in the list of folders already represented. If there are
* unread messages and the system tray icon is hidden, show it. If there are
* no unread messages, remove the folder from the mapping.
*/
if(unmapped)
{
/** Spurious notification, ignore */
if(unread == 0) return;
/** Make sure the icon will be displayed */
if(mMode == OnNewMail)
{
if(isHidden()) show();
}
} else
{
if(unread == 0)
{
kdDebug(5006) << "Removing folder " << fldr->name() << endl;
/** Remove the folder from the internal store */
mFoldersWithUnread.remove(fldr);
/** if this was the last folder in the dictionary, hide the systemtray icon */
if(mFoldersWithUnread.count() == 0)
{
mPopupFolders.clear();
disconnect(this, SLOT(selectedAccount(int)));
mCount = 0;
if(mMode == OnNewMail)
hide();
}
}
}
updateCount();
/** Update tooltip to reflect count of unread messages */
QToolTip::add(this, i18n("There is 1 unread message.",
"There are %n unread messages.",
mCount));
}
/**
* Called when user selects a folder name from the popup menu. Shows
* the first KMMainWin in the memberlist and jumps to the first unread
* message in the selected folder.
*/
void KMSystemTray::selectedAccount(int id)
{
showKMail();
KMMainWidget * mainWidget = getKMMainWidget();
assert(mainWidget);
/** Select folder */
KMFolder * fldr = mPopupFolders.at(id);
if(!fldr) return;
KMFolderTree * ft = mainWidget->folderTree();
if(!ft) return;
QListViewItem * fldrIdx = ft->indexOfFolder(fldr);
if(!fldrIdx) return;
ft->setCurrentItem(fldrIdx);
ft->selectCurrentFolder();
mainWidget->folderSelectedUnread(fldr);
}
#include "kmsystemtray.moc"
<commit_msg>don't crash if there is no reader window around and we try and look at an unread message via the system tray<commit_after>/***************************************************************************
kmsystemtray.cpp - description
-------------------
begin : Fri Aug 31 22:38:44 EDT 2001
copyright : (C) 2001 by Ryan Breen
email : ryan@porivo.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <kapplication.h>
#include <kpopupmenu.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kwin.h>
#include <qevent.h>
#include <qfontmetrics.h>
#include <qlistview.h>
#include <qstring.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qwidgetlist.h>
#include <kglobalsettings.h>
#include <kiconeffect.h>
#include <qpainter.h>
#include <math.h>
#include "kaction.h"
#include "kmsystemtray.h"
#include "kmfolder.h"
#include "kmfoldertree.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwidget.h"
/**
* Construct a KSystemTray icon to be displayed when new mail
* has arrived in a non-system folder. The KMSystemTray listens
* for updateNewMessageNotification events from each non-system
* KMFolder and maintains a store of all folders with unread
* messages.
*
* The KMSystemTray also provides a popup menu listing each folder
* with its count of unread messages, allowing the user to jump
* to the first unread message in each folder.
*/
KMSystemTray::KMSystemTray(QWidget *parent, const char *name) : KSystemTray(parent, name),
mNewMessagePopupId(-1), mPopupMenu(0)
{
setAlignment( AlignCenter );
kdDebug(5006) << "Initting systray" << endl;
mDefaultIcon = SmallIcon( "kmail" );
mTransparentIcon = SmallIcon( "kmail" );
KIconEffect::semiTransparent( mTransparentIcon );
setPixmap(mDefaultIcon);
mParentVisible = true;
mMode = OnNewMail;
/** Initiate connections between folders and this object */
foldersChanged();
connect( kernel->folderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
connect( kernel->imapFolderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
connect( kernel->searchFolderMgr(), SIGNAL(changed()), SLOT(foldersChanged()));
}
void KMSystemTray::buildPopupMenu()
{
// Delete any previously created popup menu
delete mPopupMenu;
mPopupMenu = 0;
mPopupMenu = new KPopupMenu();
if (!getKMMainWidget())
return;
mPopupMenu->insertTitle(*(this->pixmap()), "KMail");
getKMMainWidget()->action("check_mail")->plug(mPopupMenu);
getKMMainWidget()->action("check_mail_in")->plug(mPopupMenu);
mPopupMenu->insertSeparator();
getKMMainWidget()->action("new_message")->plug(mPopupMenu);
getKMMainWidget()->action("kmail_configure_kmail")->plug(mPopupMenu);
mPopupMenu->insertSeparator();
if (getKMMainWidget()->action("file_quit"))
getKMMainWidget()->action("file_quit")->plug(mPopupMenu);
}
KMSystemTray::~KMSystemTray()
{
delete mPopupMenu;
mPopupMenu = 0;
}
void KMSystemTray::setMode(int newMode)
{
if(newMode == mMode) return;
kdDebug(5006) << "Setting systray mMode to " << newMode << endl;
mMode = newMode;
if(mMode == AlwaysOn)
{
kdDebug(5006) << "Initting alwayson mMode" << endl;
if(isHidden()) show();
} else
{
if(mCount == 0)
{
hide();
}
}
}
/**
* Update the count of unread messages. If there are unread messages,
* overlay the count on top of a transparent version of the KMail icon.
* If there is no unread mail, restore the normal KMail icon.
*/
void KMSystemTray::updateCount()
{
if(mCount != 0)
{
int oldPixmapWidth = pixmap()->size().width();
int oldPixmapHeight = pixmap()->size().height();
/** Scale the font size down with each increase in the number
* of digits in the count, to a minimum point size of 6 */
int numDigits = ((int) log10((double) mCount) + 1);
QFont countFont = KGlobalSettings::generalFont();
countFont.setBold(true);
int countFontSize = countFont.pointSize();
while(countFontSize > 5)
{
QFontMetrics qfm( countFont );
int fontWidth = qfm.width( QChar( '0' ) );
if((fontWidth * numDigits) > oldPixmapWidth)
{
--countFontSize;
countFont.setPointSize(countFontSize);
} else break;
}
QPixmap bg(oldPixmapWidth, oldPixmapHeight);
bg.fill(this, 0, 0);
/** Overlay count on transparent icon */
QPainter p(&bg);
p.drawPixmap(0, 0, mTransparentIcon);
p.setFont(countFont);
p.setPen(Qt::blue);
p.drawText(pixmap()->rect(), Qt::AlignCenter, QString::number(mCount));
setPixmap(bg);
} else
{
setPixmap(mDefaultIcon);
}
}
/**
* Refreshes the list of folders we are monitoring. This is called on
* startup and is also connected to the 'changed' signal on the KMFolderMgr.
*/
void KMSystemTray::foldersChanged()
{
/**
* Hide and remove all unread mappings to cover the case where the only
* unread message was in a folder that was just removed.
*/
mFoldersWithUnread.clear();
mCount = 0;
if(mMode == OnNewMail)
{
hide();
}
/** Disconnect all previous connections */
disconnect(this, SLOT(updateNewMessageNotification(KMFolder *)));
QStringList folderNames;
QValueList<QGuardedPtr<KMFolder> > folderList;
kernel->folderMgr()->createFolderList(&folderNames, &folderList);
kernel->imapFolderMgr()->createFolderList(&folderNames, &folderList);
kernel->searchFolderMgr()->createFolderList(&folderNames, &folderList);
QStringList::iterator strIt = folderNames.begin();
for(QValueList<QGuardedPtr<KMFolder> >::iterator it = folderList.begin();
it != folderList.end() && strIt != folderNames.end(); ++it, ++strIt)
{
KMFolder * currentFolder = *it;
QString currentName = *strIt;
if((!currentFolder->isSystemFolder() || (currentFolder->name().lower() == "inbox")) ||
(currentFolder->protocol() == "imap"))
{
/** If this is a new folder, start listening for messages */
connect(currentFolder, SIGNAL(numUnreadMsgsChanged(KMFolder *)),
this, SLOT(updateNewMessageNotification(KMFolder *)));
/** Check all new folders to see if we started with any new messages */
updateNewMessageNotification(currentFolder);
}
}
}
/**
* On left mouse click, switch focus to the first KMMainWidget. On right
* click, bring up a list of all folders with a count of unread messages.
*/
void KMSystemTray::mousePressEvent(QMouseEvent *e)
{
// switch to kmail on left mouse button
if( e->button() == LeftButton )
{
if( mParentVisible )
hideKMail();
else
showKMail();
}
// open popup menu on right mouse button
if( e->button() == RightButton )
{
mPopupFolders.clear();
mPopupFolders.resize(mFoldersWithUnread.count());
// Rebuild popup menu at click time to minimize race condition if
// the base KMainWidget is closed.
buildPopupMenu();
if(mNewMessagePopupId != -1)
{
mPopupMenu->removeItem(mNewMessagePopupId);
}
if(mFoldersWithUnread.count() > 0)
{
KPopupMenu *newMessagesPopup = new KPopupMenu();
QMap<QGuardedPtr<KMFolder>, int>::Iterator it = mFoldersWithUnread.begin();
for(uint i=0; it != mFoldersWithUnread.end(); ++i)
{
kdDebug(5006) << "Adding folder" << endl;
if(i > mPopupFolders.size()) mPopupFolders.resize(i * 2);
mPopupFolders.insert(i, it.key());
QString item = prettyName(it.key()) + "(" + QString::number(it.data()) + ")";
newMessagesPopup->insertItem(item, this, SLOT(selectedAccount(int)), 0, i);
++it;
}
mNewMessagePopupId = mPopupMenu->insertItem(i18n("New messages in..."),
newMessagesPopup, mNewMessagePopupId, 3);
kdDebug(5006) << "Folders added" << endl;
}
mPopupMenu->popup(e->globalPos());
}
}
/**
* Return the name of the folder in which the mail is deposited, prepended
* with the account name if the folder is IMAP.
*/
QString KMSystemTray::prettyName(KMFolder * fldr)
{
QString rvalue = fldr->label();
if(fldr->protocol() == "imap")
{
KMFolderImap * imap = dynamic_cast<KMFolderImap*> (fldr);
assert(imap);
if((imap->account() != 0) &&
(imap->account()->name() != 0) )
{
kdDebug(5006) << "IMAP folder, prepend label with type" << endl;
rvalue = imap->account()->name() + "->" + rvalue;
}
}
kdDebug(5006) << "Got label " << rvalue << endl;
return rvalue;
}
/**
* Shows and raises the first KMMainWidget and
* switches to the appropriate virtual desktop.
*/
void KMSystemTray::showKMail()
{
if (!getKMMainWidget())
return;
QWidget *mainWin = getKMMainWidget()->topLevelWidget();
assert(mainWin);
if(mainWin)
{
/** Force window to grab focus */
mainWin->show();
mainWin->raise();
mParentVisible = true;
/** Switch to appropriate desktop */
int desk = KWin::info(mainWin->winId()).desktop;
KWin::setCurrentDesktop(desk);
}
}
void KMSystemTray::hideKMail()
{
if (!getKMMainWidget())
return;
QWidget *mainWin = getKMMainWidget()->topLevelWidget();
assert(mainWin);
if(mainWin)
{
mainWin->hide();
mParentVisible = false;
}
}
/**
* Grab a pointer to the first KMMainWidget.
*/
KMMainWidget * KMSystemTray::getKMMainWidget()
{
QWidgetList *l = kapp->topLevelWidgets();
QWidgetListIt it( *l );
QWidget *wid;
while ( (wid = it.current()) != 0 ) {
++it;
QObjectList *l2 = wid->topLevelWidget()->queryList("KMMainWidget");
if (l2->first())
return dynamic_cast<KMMainWidget *>(l2->first());
}
return 0;
}
/**
* Called on startup of the KMSystemTray and when the numUnreadMsgsChanged signal
* is emitted for one of the watched folders. Shows the system tray icon if there
* are new messages and the icon was hidden, or hides the system tray icon if there
* are no more new messages.
*/
void KMSystemTray::updateNewMessageNotification(KMFolder * fldr)
{
if(!fldr)
{
kdDebug(5006) << "Null folder, can't mess with that" << endl;
return;
}
/** The number of unread messages in that folder */
int unread = fldr->countUnread();
QMap<QGuardedPtr<KMFolder>, int>::Iterator it =
mFoldersWithUnread.find(fldr);
bool unmapped = (it == mFoldersWithUnread.end());
/** If the folder is not mapped yet, increment count by numUnread
in folder */
if(unmapped) mCount += unread;
/* Otherwise, get the difference between the numUnread in the folder and
* our last known version, and adjust mCount with that difference */
else
{
int diff = unread - it.data();
mCount += diff;
}
if(unread > 0)
{
/** Add folder to our internal store, or update unread count if already mapped */
mFoldersWithUnread.insert(fldr, unread);
kdDebug(5006) << "There are now " << mFoldersWithUnread.count() << " folders with unread" << endl;
}
/**
* Look for folder in the list of folders already represented. If there are
* unread messages and the system tray icon is hidden, show it. If there are
* no unread messages, remove the folder from the mapping.
*/
if(unmapped)
{
/** Spurious notification, ignore */
if(unread == 0) return;
/** Make sure the icon will be displayed */
if(mMode == OnNewMail)
{
if(isHidden()) show();
}
} else
{
if(unread == 0)
{
kdDebug(5006) << "Removing folder " << fldr->name() << endl;
/** Remove the folder from the internal store */
mFoldersWithUnread.remove(fldr);
/** if this was the last folder in the dictionary, hide the systemtray icon */
if(mFoldersWithUnread.count() == 0)
{
mPopupFolders.clear();
disconnect(this, SLOT(selectedAccount(int)));
mCount = 0;
if(mMode == OnNewMail)
hide();
}
}
}
updateCount();
/** Update tooltip to reflect count of unread messages */
QToolTip::add(this, i18n("There is 1 unread message.",
"There are %n unread messages.",
mCount));
}
/**
* Called when user selects a folder name from the popup menu. Shows
* the first KMMainWin in the memberlist and jumps to the first unread
* message in the selected folder.
*/
void KMSystemTray::selectedAccount(int id)
{
showKMail();
KMMainWidget * mainWidget = getKMMainWidget();
if (!mainWidget)
{
kernel->openReader();
mainWidget = getKMMainWidget();
}
assert(mainWidget);
/** Select folder */
KMFolder * fldr = mPopupFolders.at(id);
if(!fldr) return;
KMFolderTree * ft = mainWidget->folderTree();
if(!ft) return;
QListViewItem * fldrIdx = ft->indexOfFolder(fldr);
if(!fldrIdx) return;
ft->setCurrentItem(fldrIdx);
ft->selectCurrentFolder();
mainWidget->folderSelectedUnread(fldr);
}
#include "kmsystemtray.moc"
<|endoftext|> |
<commit_before>
/*
Bubblehelp class Copyright (C) 1998 Marco Nelissen <marcone@xs4all.nl>
Freely usable in non-commercial applications, as long as proper credit
is given.
Usage:
- Add the file BubbleHelper.cpp to your project
- #include "BubbleHelper.h" in your files where needed
- Create a single instance of BubbleHelper (it will serve your entire
application). It is safe to create one on the stack or as a global.
- Call SetHelp(view,text) for each view to which you wish to attach a text.
- Use SetHelp(view,NULL) to remove text from a view.
This could be implemented as a BMessageFilter as well, but that means using
one bubblehelp-instance for each window to which you wish to add help-bubbles.
Using a single looping thread for everything turned out to be the most practical
solution.
*/
#include <string.h>
#include <malloc.h>
#include <Application.h>
#include <Window.h>
#include <TextView.h>
#include <Region.h>
#include <Screen.h>
#include <Locker.h>
#include <Messenger.h>
#include "BubbleHelper.h"
long BubbleHelper::runcount=0;
struct helppair
{
BView *view;
char *text;
};
BubbleHelper::BubbleHelper()
{
// You only need one instance per application.
if(atomic_add(&runcount,1)==0)
{
helplist=new BList(30);
helperthread=spawn_thread(_helper,"helper",B_NORMAL_PRIORITY,this);
if(helperthread>=0)
resume_thread(helperthread);
enabled=true;
}
else
{
// Since you shouldn't be creating more than one instance
// you may want to jump straight into the debugger here.
debugger("only one BubbleHelper instance allowed/necessary");
// helperthread=-1;
// helplist=NULL;
// enabled=false;
}
}
BubbleHelper::~BubbleHelper()
{
if(helperthread>=0)
{
// force helper thread into a known state
bool locked=textwin->Lock();
// Be rude...
kill_thread(helperthread);
// dispose of window
if(locked)
{
BMessenger(textwin).SendMessage(B_QUIT_REQUESTED);
textwin->Unlock();
}
}
if(helplist)
{
helppair *pair;
int i=helplist->CountItems()-1;
while(i>=0)
{
pair=(helppair*)helplist->RemoveItem(i);
if(pair && pair->text)
free(pair->text);
delete pair;
i--;
}
delete helplist;
}
atomic_add(&runcount,-1);
}
void BubbleHelper::SetHelp(BView *view, char *text)
{
if(this && view)
{
// delete previous text for this view, if any
for(int i=0;;i++)
{
helppair *pair;
pair=(helppair*)helplist->ItemAt(i);
if(!pair)
break;
if(pair->view==view)
{
helplist->RemoveItem(pair);
free(pair->text);
delete pair;
break;
}
}
// add new text, if any
if(text)
{
helppair *pair=new helppair;
pair->view=view;
pair->text=strdup(text);
helplist->AddItem(pair);
}
}
}
char *BubbleHelper::GetHelp(BView *view)
{
int i=0;
helppair *pair;
// This could be sped up by sorting the list and
// doing a binary search.
// Right now this is left as an exercise for the
// reader, or should I say "third party opportunity"?
while((pair=(helppair*)helplist->ItemAt(i++))!=NULL)
{
if(pair->view==view)
return pair->text;
}
return NULL;
}
long BubbleHelper::_helper(void *arg)
{
((BubbleHelper*)arg)->Helper();
return 0;
}
void BubbleHelper::Helper()
{
// Wait until the BApplication becomes valid, in case
// someone creates this as a global variable.
while(!be_app_messenger.IsValid())
snooze(200000);
// wait a little longer, until the BApplication is really up to speed
while(be_app->IsLaunching())
snooze(200000);
textwin=new BWindow(BRect(-100,-100,-50,-50),"",B_BORDERED_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL,
B_NOT_MOVABLE|B_AVOID_FOCUS);
textview=new BTextView(BRect(0,0,50,50),"",BRect(2,2,48,48),B_FOLLOW_ALL_SIDES,B_WILL_DRAW);
textview->MakeEditable(false);
textview->MakeSelectable(false);
textview->SetWordWrap(false);
textview->SetLowColor(240,240,100);
textview->SetViewColor(240,240,100);
textview->SetHighColor(0,0,0);
textwin->AddChild(textview);
textwin->Run();
textwin->Lock();
textwin->Activate(false);
rename_thread(textwin->Thread(),"bubble");
textwin->Unlock();
ulong delaycounter=0;
BPoint lastwhere;
while(be_app_messenger.IsValid())
{
BPoint where;
ulong buttons;
if(enabled)
{
if(textwin->Lock())
{
textview->GetMouse(&where,&buttons);
textview->ConvertToScreen(&where);
if(lastwhere!=where || buttons)
{
delaycounter=0;
}
else
{
// mouse didn't move
if(delaycounter++>5)
{
delaycounter=0;
// mouse didn't move for a while
BView *view=FindView(where);
char *text=NULL;
while(view && (text=GetHelp(view))==NULL)
view=view->Parent();
if(text)
{
DisplayHelp(text,where);
// wait until mouse moves out of view, or wait
// for timeout
long displaycounter=0;
BPoint where2;
long displaytime=max_c(20,strlen(text));
do
{
textwin->Unlock();
snooze(100000);
if(!textwin->Lock())
goto end; //window is apparently gone
textview->GetMouse(&where2,&buttons);
textview->ConvertToScreen(&where2);
} while(!buttons && where2==where && (displaycounter++<displaytime));
HideBubble();
do
{
textwin->Unlock();
snooze(100000);
if(!textwin->Lock())
goto end; //window is apparently gone
textview->GetMouse(&where2,&buttons);
textview->ConvertToScreen(&where2);
} while(where2==where);
}
}
}
lastwhere=where;
textwin->Unlock();
}
}
end:
snooze(100000);
}
// (this thread normally gets killed by the destructor before arriving here)
}
void BubbleHelper::HideBubble()
{
textwin->MoveTo(-1000,-1000); // hide it
if(!textwin->IsHidden())
textwin->Hide();
}
void BubbleHelper::ShowBubble(BPoint dest)
{
textwin->MoveTo(dest);
textwin->SetWorkspaces(B_CURRENT_WORKSPACE);
if(textwin->IsHidden())
textwin->Show();
}
BView *BubbleHelper::FindView(BPoint where)
{
BView *winview=NULL;
BWindow *win;
long windex=0;
while((winview==NULL)&&((win=be_app->WindowAt(windex++))!=NULL))
{
if(win!=textwin)
{
// lock with timeout, in case somebody has a non-running window around
// in their app.
if(win->LockWithTimeout(1E6)==B_OK)
{
BRect frame=win->Frame();
if(frame.Contains(where))
{
BPoint winpoint;
winpoint=where-frame.LeftTop();
winview=win->FindView(winpoint);
if(winview)
{
BRegion region;
BPoint newpoint=where;
winview->ConvertFromScreen(&newpoint);
winview->GetClippingRegion(®ion);
if(!region.Contains(newpoint))
winview=0;
}
}
win->Unlock();
}
}
}
return winview;
}
void BubbleHelper::DisplayHelp(char *text, BPoint where)
{
textview->SetText(text);
float height=textview->TextHeight(0,2E6)+4;
float width=0;
int numlines=textview->CountLines();
int linewidth;
for(int i=0;i<numlines;i++)
if((linewidth=int(textview->LineWidth(i)))>width)
width=linewidth;
textwin->ResizeTo(width+4,height);
textview->SetTextRect(BRect(2,2,width+2,height+2));
BScreen screen;
BPoint dest=where+BPoint(0,20);
BRect screenframe=screen.Frame();
if((dest.y+height)>(screenframe.bottom-3))
dest.y=dest.y-(16+height+8);
if((dest.x+width+4)>(screenframe.right))
dest.x=dest.x-((dest.x+width+4)-screenframe.right);
ShowBubble(dest);
}
void BubbleHelper::EnableHelp(bool enable)
{
enabled=enable;
}
<commit_msg>On Haiku use the tooltipo colors.<commit_after>
/*
Bubblehelp class Copyright (C) 1998 Marco Nelissen <marcone@xs4all.nl>
Freely usable in non-commercial applications, as long as proper credit
is given.
Usage:
- Add the file BubbleHelper.cpp to your project
- #include "BubbleHelper.h" in your files where needed
- Create a single instance of BubbleHelper (it will serve your entire
application). It is safe to create one on the stack or as a global.
- Call SetHelp(view,text) for each view to which you wish to attach a text.
- Use SetHelp(view,NULL) to remove text from a view.
This could be implemented as a BMessageFilter as well, but that means using
one bubblehelp-instance for each window to which you wish to add help-bubbles.
Using a single looping thread for everything turned out to be the most practical
solution.
*/
#include <string.h>
#include <malloc.h>
#include <Application.h>
#include <Window.h>
#include <TextView.h>
#include <Region.h>
#include <Screen.h>
#include <Locker.h>
#include <Messenger.h>
#include "BubbleHelper.h"
long BubbleHelper::runcount=0;
struct helppair
{
BView *view;
char *text;
};
BubbleHelper::BubbleHelper()
{
// You only need one instance per application.
if(atomic_add(&runcount,1)==0)
{
helplist=new BList(30);
helperthread=spawn_thread(_helper,"helper",B_NORMAL_PRIORITY,this);
if(helperthread>=0)
resume_thread(helperthread);
enabled=true;
}
else
{
// Since you shouldn't be creating more than one instance
// you may want to jump straight into the debugger here.
debugger("only one BubbleHelper instance allowed/necessary");
// helperthread=-1;
// helplist=NULL;
// enabled=false;
}
}
BubbleHelper::~BubbleHelper()
{
if(helperthread>=0)
{
// force helper thread into a known state
bool locked=textwin->Lock();
// Be rude...
kill_thread(helperthread);
// dispose of window
if(locked)
{
BMessenger(textwin).SendMessage(B_QUIT_REQUESTED);
textwin->Unlock();
}
}
if(helplist)
{
helppair *pair;
int i=helplist->CountItems()-1;
while(i>=0)
{
pair=(helppair*)helplist->RemoveItem(i);
if(pair && pair->text)
free(pair->text);
delete pair;
i--;
}
delete helplist;
}
atomic_add(&runcount,-1);
}
void BubbleHelper::SetHelp(BView *view, char *text)
{
if(this && view)
{
// delete previous text for this view, if any
for(int i=0;;i++)
{
helppair *pair;
pair=(helppair*)helplist->ItemAt(i);
if(!pair)
break;
if(pair->view==view)
{
helplist->RemoveItem(pair);
free(pair->text);
delete pair;
break;
}
}
// add new text, if any
if(text)
{
helppair *pair=new helppair;
pair->view=view;
pair->text=strdup(text);
helplist->AddItem(pair);
}
}
}
char *BubbleHelper::GetHelp(BView *view)
{
int i=0;
helppair *pair;
// This could be sped up by sorting the list and
// doing a binary search.
// Right now this is left as an exercise for the
// reader, or should I say "third party opportunity"?
while((pair=(helppair*)helplist->ItemAt(i++))!=NULL)
{
if(pair->view==view)
return pair->text;
}
return NULL;
}
long BubbleHelper::_helper(void *arg)
{
((BubbleHelper*)arg)->Helper();
return 0;
}
void BubbleHelper::Helper()
{
// Wait until the BApplication becomes valid, in case
// someone creates this as a global variable.
while(!be_app_messenger.IsValid())
snooze(200000);
// wait a little longer, until the BApplication is really up to speed
while(be_app->IsLaunching())
snooze(200000);
textwin=new BWindow(BRect(-100,-100,-50,-50),"",B_BORDERED_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL,
B_NOT_MOVABLE|B_AVOID_FOCUS);
textview=new BTextView(BRect(0,0,50,50),"",BRect(2,2,48,48),B_FOLLOW_ALL_SIDES,B_WILL_DRAW);
textview->MakeEditable(false);
textview->MakeSelectable(false);
textview->SetWordWrap(false);
#ifdef __HAIKU__
textview->SetHighColor(ui_color(B_TOOLTIP_TEXT_COLOR));
textview->SetLowColor(ui_color(B_TOOLTIP_BACKGROUND_COLOR));
textview->SetViewColor(ui_color(B_TOOLTIP_BACKGROUND_COLOR));
#else
textview->SetLowColor(240,240,100);
textview->SetViewColor(240,240,100);
textview->SetHighColor(0,0,0);
#endif
textwin->AddChild(textview);
textwin->Run();
textwin->Lock();
textwin->Activate(false);
rename_thread(textwin->Thread(),"bubble");
textwin->Unlock();
ulong delaycounter=0;
BPoint lastwhere;
while(be_app_messenger.IsValid())
{
BPoint where;
ulong buttons;
if(enabled)
{
if(textwin->Lock())
{
textview->GetMouse(&where,&buttons);
textview->ConvertToScreen(&where);
if(lastwhere!=where || buttons)
{
delaycounter=0;
}
else
{
// mouse didn't move
if(delaycounter++>5)
{
delaycounter=0;
// mouse didn't move for a while
BView *view=FindView(where);
char *text=NULL;
while(view && (text=GetHelp(view))==NULL)
view=view->Parent();
if(text)
{
DisplayHelp(text,where);
// wait until mouse moves out of view, or wait
// for timeout
long displaycounter=0;
BPoint where2;
long displaytime=max_c(20,strlen(text));
do
{
textwin->Unlock();
snooze(100000);
if(!textwin->Lock())
goto end; //window is apparently gone
textview->GetMouse(&where2,&buttons);
textview->ConvertToScreen(&where2);
} while(!buttons && where2==where && (displaycounter++<displaytime));
HideBubble();
do
{
textwin->Unlock();
snooze(100000);
if(!textwin->Lock())
goto end; //window is apparently gone
textview->GetMouse(&where2,&buttons);
textview->ConvertToScreen(&where2);
} while(where2==where);
}
}
}
lastwhere=where;
textwin->Unlock();
}
}
end:
snooze(100000);
}
// (this thread normally gets killed by the destructor before arriving here)
}
void BubbleHelper::HideBubble()
{
textwin->MoveTo(-1000,-1000); // hide it
if(!textwin->IsHidden())
textwin->Hide();
}
void BubbleHelper::ShowBubble(BPoint dest)
{
textwin->MoveTo(dest);
textwin->SetWorkspaces(B_CURRENT_WORKSPACE);
if(textwin->IsHidden())
textwin->Show();
}
BView *BubbleHelper::FindView(BPoint where)
{
BView *winview=NULL;
BWindow *win;
long windex=0;
while((winview==NULL)&&((win=be_app->WindowAt(windex++))!=NULL))
{
if(win!=textwin)
{
// lock with timeout, in case somebody has a non-running window around
// in their app.
if(win->LockWithTimeout(1E6)==B_OK)
{
BRect frame=win->Frame();
if(frame.Contains(where))
{
BPoint winpoint;
winpoint=where-frame.LeftTop();
winview=win->FindView(winpoint);
if(winview)
{
BRegion region;
BPoint newpoint=where;
winview->ConvertFromScreen(&newpoint);
winview->GetClippingRegion(®ion);
if(!region.Contains(newpoint))
winview=0;
}
}
win->Unlock();
}
}
}
return winview;
}
void BubbleHelper::DisplayHelp(char *text, BPoint where)
{
textview->SetText(text);
float height=textview->TextHeight(0,2E6)+4;
float width=0;
int numlines=textview->CountLines();
int linewidth;
for(int i=0;i<numlines;i++)
if((linewidth=int(textview->LineWidth(i)))>width)
width=linewidth;
textwin->ResizeTo(width+4,height);
textview->SetTextRect(BRect(2,2,width+2,height+2));
BScreen screen;
BPoint dest=where+BPoint(0,20);
BRect screenframe=screen.Frame();
if((dest.y+height)>(screenframe.bottom-3))
dest.y=dest.y-(16+height+8);
if((dest.x+width+4)>(screenframe.right))
dest.x=dest.x-((dest.x+width+4)-screenframe.right);
ShowBubble(dest);
}
void BubbleHelper::EnableHelp(bool enable)
{
enabled=enable;
}
<|endoftext|> |
<commit_before>/*
kopeteiface.cpp - Kopete DCOP Interface
Copyright (c) 2002 by Hendrik vom Lehn <hennevl@hennevl.de>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopeteiface.h"
#include "kopetemetacontact.h"
#include "kopetecontactlist.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetepluginmanager.h"
#include "kopeteprotocol.h"
#include "kopeteuiglobal.h"
#include "kopeteaway.h"
#include "kopetegroup.h"
#include "kopetecontact.h"
#include "kopeteconfig.h"
KopeteIface::KopeteIface() : DCOPObject( "KopeteIface" )
{
KConfig *config = KGlobal::config();
config->setGroup("AutoAway");
if (config->readBoolEntry("UseAutoAway", true))
{
connectDCOPSignal("kdesktop", "KScreensaverIface",
"KDE_start_screensaver()", "setAutoAway()", false);
}
else
{
disconnectDCOPSignal("kdesktop", "KScreensaverIface",
"KDE_start_screensaver()", "setAutoAway()");
}
}
QStringList KopeteIface::contacts()
{
return Kopete::ContactList::self()->contacts();
}
QStringList KopeteIface::reachableContacts()
{
return Kopete::ContactList::self()->reachableContacts();
}
QStringList KopeteIface::onlineContacts()
{
QStringList result;
QPtrList<Kopete::Contact> list = Kopete::ContactList::self()->onlineContacts();
QPtrListIterator<Kopete::Contact> it( list );
for( ; it.current(); ++it )
result.append( it.current()->contactId() );
return result;
}
QStringList KopeteIface::contactsStatus()
{
return Kopete::ContactList::self()->contactStatuses();
}
QStringList KopeteIface::fileTransferContacts()
{
return Kopete::ContactList::self()->fileTransferContacts();
}
QStringList KopeteIface::contactFileProtocols(const QString &displayName)
{
return Kopete::ContactList::self()->contactFileProtocols(displayName);
}
QString KopeteIface::messageContact( const QString &contactId, const QString &messageText )
{
Kopete::MetaContact *mc = Kopete::ContactList::self()->findMetaContactByContactId( contactId );
if ( mc && mc->isReachable() )
Kopete::ContactList::self()->messageContact( contactId, messageText );
else
return "Unable to send message. The contact is not reachable";
//Default return value
return QString::null;
}
/*
void KopeteIface::sendFile(const QString &displayName, const KURL &sourceURL,
const QString &altFileName, uint fileSize)
{
return Kopete::ContactList::self()->sendFile(displayName, sourceURL, altFileName, fileSize);
}
*/
QString KopeteIface::onlineStatus( const QString &metaContactId )
{
Kopete::MetaContact *m = Kopete::ContactList::self()->metaContact( metaContactId );
if( m )
{
Kopete::OnlineStatus status = m->status();
return status.description();
}
return "Unknown Contact";
}
void KopeteIface::messageContactById( const QString &metaContactId )
{
Kopete::MetaContact *m = Kopete::ContactList::self()->metaContact( metaContactId );
if( m )
{
m->execute();
}
}
bool KopeteIface::addContact( const QString &protocolName, const QString &accountId, const QString &contactId,
const QString &displayName, const QString &groupName )
{
//Get the protocol instance
Kopete::Account *myAccount = Kopete::AccountManager::self()->findAccount( protocolName, accountId );
if( myAccount )
{
QString contactName;
Kopete::Group *realGroup=0L;
//If the nickName isn't specified we need to display the userId in the prompt
if( displayName.isEmpty() || displayName.isNull() )
contactName = contactId;
else
contactName = displayName;
if ( !groupName.isEmpty() )
realGroup=Kopete::ContactList::self()->findGroup( groupName );
// Confirm with the user before we add the contact
// FIXME: This is completely bogus since the user may not
// even be at the computer. We just need to add the contact --Matt
if( KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n( "An external application is attempting to add the "
" '%1' contact '%2' to your contact list. Do you want to allow this?" )
.arg( protocolName ).arg( contactName ), i18n( "Allow Contact?" ), i18n("Allow"), i18n("Reject") ) == 3 ) // Yes == 3
{
//User said Yes
myAccount->addContact( contactId, contactName, realGroup, Kopete::Account::DontChangeKABC);
return true;
} else {
//User said No
return false;
}
} else {
//This protocol is not loaded
KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Error,
i18n("An external application has attempted to add a contact using "
" the %1 protocol, which either does not exist or is not loaded.").arg( protocolName ),
i18n("Missing Protocol"));
return false;
}
}
QStringList KopeteIface::accounts()
{
QStringList list;
QPtrList<Kopete::Account> m_accounts=Kopete::AccountManager::self()->accounts();
QPtrListIterator<Kopete::Account> it( m_accounts );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
list += ( account->protocol()->pluginId() +"||" + account->accountId() );
}
return list;
}
void KopeteIface::connect(const QString &protocolId, const QString &accountId )
{
QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
if( ( account->accountId() == accountId) )
{
if( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
{
account->connect();
break;
}
}
}
}
void KopeteIface::disconnect(const QString &protocolId, const QString &accountId )
{
QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
if( ( account->accountId() == accountId) )
{
if( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
{
account->disconnect();
break;
}
}
}
}
void KopeteIface::connectAll()
{
Kopete::AccountManager::self()->connectAll();
}
void KopeteIface::disconnectAll()
{
Kopete::AccountManager::self()->disconnectAll();
}
bool KopeteIface::loadPlugin( const QString &name )
{
if ( Kopete::PluginManager::self()->setPluginEnabled( name ) )
{
QString argument = name;
if ( !argument.startsWith( "kopete_" ) )
argument.prepend( "kopete_" );
return Kopete::PluginManager::self()->loadPlugin( argument );
}
else
{
return false;
}
}
bool KopeteIface::unloadPlugin( const QString &name )
{
if ( Kopete::PluginManager::self()->setPluginEnabled( name, false ) )
{
QString argument = name;
if ( !argument.startsWith( "kopete_" ) )
argument.prepend( "kopete_" );
return Kopete::PluginManager::self()->unloadPlugin( argument );
}
else
{
return false;
}
}
void KopeteIface::setAway()
{
Kopete::AccountManager::self()->setAwayAll();
}
void KopeteIface::setAway(const QString &msg, bool away)
{
Kopete::AccountManager::self()->setAwayAll(msg, away);
}
void KopeteIface::setAvailable()
{
Kopete::AccountManager::self()->setAvailableAll();
}
void KopeteIface::setAutoAway()
{
Kopete::Away::getInstance()->setAutoAway();
}
void KopeteIface::setGlobalNickname( const QString &nickname )
{
if( Kopete::Config::enableGlobalIdentity() )
{
Kopete::MetaContact *myselfMetaContact = Kopete::ContactList::self()->myself();
myselfMetaContact->setDisplayNameSource( Kopete::MetaContact::SourceCustom );
myselfMetaContact->setDisplayName( nickname );
}
}
void KopeteIface::setGlobalPhoto( const KURL &photoUrl )
{
if( Kopete::Config::enableGlobalIdentity() )
{
Kopete::MetaContact *myselfMetaContact = Kopete::ContactList::self()->myself();
myselfMetaContact->setPhoto( photoUrl );
if( myselfMetaContact->photoSource() != Kopete::MetaContact::SourceCustom )
myselfMetaContact->setPhotoSource( Kopete::MetaContact::SourceCustom );
}
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Clarify DCOP reply for messageContact. With previous reply client could not tell if the user the message is being sent to exist or not online. Now client can distinguish such a situtaion.<commit_after>/*
kopeteiface.cpp - Kopete DCOP Interface
Copyright (c) 2002 by Hendrik vom Lehn <hennevl@hennevl.de>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopeteiface.h"
#include "kopetemetacontact.h"
#include "kopetecontactlist.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetepluginmanager.h"
#include "kopeteprotocol.h"
#include "kopeteuiglobal.h"
#include "kopeteaway.h"
#include "kopetegroup.h"
#include "kopetecontact.h"
#include "kopeteconfig.h"
KopeteIface::KopeteIface() : DCOPObject( "KopeteIface" )
{
KConfig *config = KGlobal::config();
config->setGroup("AutoAway");
if (config->readBoolEntry("UseAutoAway", true))
{
connectDCOPSignal("kdesktop", "KScreensaverIface",
"KDE_start_screensaver()", "setAutoAway()", false);
}
else
{
disconnectDCOPSignal("kdesktop", "KScreensaverIface",
"KDE_start_screensaver()", "setAutoAway()");
}
}
QStringList KopeteIface::contacts()
{
return Kopete::ContactList::self()->contacts();
}
QStringList KopeteIface::reachableContacts()
{
return Kopete::ContactList::self()->reachableContacts();
}
QStringList KopeteIface::onlineContacts()
{
QStringList result;
QPtrList<Kopete::Contact> list = Kopete::ContactList::self()->onlineContacts();
QPtrListIterator<Kopete::Contact> it( list );
for( ; it.current(); ++it )
result.append( it.current()->contactId() );
return result;
}
QStringList KopeteIface::contactsStatus()
{
return Kopete::ContactList::self()->contactStatuses();
}
QStringList KopeteIface::fileTransferContacts()
{
return Kopete::ContactList::self()->fileTransferContacts();
}
QStringList KopeteIface::contactFileProtocols(const QString &displayName)
{
return Kopete::ContactList::self()->contactFileProtocols(displayName);
}
QString KopeteIface::messageContact( const QString &contactId, const QString &messageText )
{
Kopete::MetaContact *mc = Kopete::ContactList::self()->findMetaContactByContactId( contactId );
if ( !mc )
{
return "No such contact.";
}
if ( mc->isReachable() )
Kopete::ContactList::self()->messageContact( contactId, messageText );
else
return "The contact is not reachable";
//Default return value
return QString::null;
}
/*
void KopeteIface::sendFile(const QString &displayName, const KURL &sourceURL,
const QString &altFileName, uint fileSize)
{
return Kopete::ContactList::self()->sendFile(displayName, sourceURL, altFileName, fileSize);
}
*/
QString KopeteIface::onlineStatus( const QString &metaContactId )
{
Kopete::MetaContact *m = Kopete::ContactList::self()->metaContact( metaContactId );
if( m )
{
Kopete::OnlineStatus status = m->status();
return status.description();
}
return "Unknown Contact";
}
void KopeteIface::messageContactById( const QString &metaContactId )
{
Kopete::MetaContact *m = Kopete::ContactList::self()->metaContact( metaContactId );
if( m )
{
m->execute();
}
}
bool KopeteIface::addContact( const QString &protocolName, const QString &accountId, const QString &contactId,
const QString &displayName, const QString &groupName )
{
//Get the protocol instance
Kopete::Account *myAccount = Kopete::AccountManager::self()->findAccount( protocolName, accountId );
if( myAccount )
{
QString contactName;
Kopete::Group *realGroup=0L;
//If the nickName isn't specified we need to display the userId in the prompt
if( displayName.isEmpty() || displayName.isNull() )
contactName = contactId;
else
contactName = displayName;
if ( !groupName.isEmpty() )
realGroup=Kopete::ContactList::self()->findGroup( groupName );
// Confirm with the user before we add the contact
// FIXME: This is completely bogus since the user may not
// even be at the computer. We just need to add the contact --Matt
if( KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n( "An external application is attempting to add the "
" '%1' contact '%2' to your contact list. Do you want to allow this?" )
.arg( protocolName ).arg( contactName ), i18n( "Allow Contact?" ), i18n("Allow"), i18n("Reject") ) == 3 ) // Yes == 3
{
//User said Yes
myAccount->addContact( contactId, contactName, realGroup, Kopete::Account::DontChangeKABC);
return true;
} else {
//User said No
return false;
}
} else {
//This protocol is not loaded
KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Error,
i18n("An external application has attempted to add a contact using "
" the %1 protocol, which either does not exist or is not loaded.").arg( protocolName ),
i18n("Missing Protocol"));
return false;
}
}
QStringList KopeteIface::accounts()
{
QStringList list;
QPtrList<Kopete::Account> m_accounts=Kopete::AccountManager::self()->accounts();
QPtrListIterator<Kopete::Account> it( m_accounts );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
list += ( account->protocol()->pluginId() +"||" + account->accountId() );
}
return list;
}
void KopeteIface::connect(const QString &protocolId, const QString &accountId )
{
QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
if( ( account->accountId() == accountId) )
{
if( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
{
account->connect();
break;
}
}
}
}
void KopeteIface::disconnect(const QString &protocolId, const QString &accountId )
{
QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *account;
while ( ( account = it.current() ) != 0 )
{
++it;
if( ( account->accountId() == accountId) )
{
if( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
{
account->disconnect();
break;
}
}
}
}
void KopeteIface::connectAll()
{
Kopete::AccountManager::self()->connectAll();
}
void KopeteIface::disconnectAll()
{
Kopete::AccountManager::self()->disconnectAll();
}
bool KopeteIface::loadPlugin( const QString &name )
{
if ( Kopete::PluginManager::self()->setPluginEnabled( name ) )
{
QString argument = name;
if ( !argument.startsWith( "kopete_" ) )
argument.prepend( "kopete_" );
return Kopete::PluginManager::self()->loadPlugin( argument );
}
else
{
return false;
}
}
bool KopeteIface::unloadPlugin( const QString &name )
{
if ( Kopete::PluginManager::self()->setPluginEnabled( name, false ) )
{
QString argument = name;
if ( !argument.startsWith( "kopete_" ) )
argument.prepend( "kopete_" );
return Kopete::PluginManager::self()->unloadPlugin( argument );
}
else
{
return false;
}
}
void KopeteIface::setAway()
{
Kopete::AccountManager::self()->setAwayAll();
}
void KopeteIface::setAway(const QString &msg, bool away)
{
Kopete::AccountManager::self()->setAwayAll(msg, away);
}
void KopeteIface::setAvailable()
{
Kopete::AccountManager::self()->setAvailableAll();
}
void KopeteIface::setAutoAway()
{
Kopete::Away::getInstance()->setAutoAway();
}
void KopeteIface::setGlobalNickname( const QString &nickname )
{
if( Kopete::Config::enableGlobalIdentity() )
{
Kopete::MetaContact *myselfMetaContact = Kopete::ContactList::self()->myself();
myselfMetaContact->setDisplayNameSource( Kopete::MetaContact::SourceCustom );
myselfMetaContact->setDisplayName( nickname );
}
}
void KopeteIface::setGlobalPhoto( const KURL &photoUrl )
{
if( Kopete::Config::enableGlobalIdentity() )
{
Kopete::MetaContact *myselfMetaContact = Kopete::ContactList::self()->myself();
myselfMetaContact->setPhoto( photoUrl );
if( myselfMetaContact->photoSource() != Kopete::MetaContact::SourceCustom )
myselfMetaContact->setPhotoSource( Kopete::MetaContact::SourceCustom );
}
}
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <memory>
#include "server.h"
#include <node.h>
#include <nan.h>
#include <malloc.h>
#include <vector>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "grpc/support/log.h"
#include "call.h"
#include "completion_queue_async_worker.h"
#include "server_credentials.h"
#include "timeval.h"
namespace grpc {
namespace node {
using std::unique_ptr;
using v8::Arguments;
using v8::Array;
using v8::Boolean;
using v8::Date;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> Server::constructor;
Persistent<FunctionTemplate> Server::fun_tpl;
class NewCallOp : public Op {
public:
NewCallOp() {
call = NULL;
grpc_call_details_init(&details);
grpc_metadata_array_init(&request_metadata);
}
~NewCallOp() {
grpc_call_details_destroy(&details);
grpc_metadata_array_destroy(&request_metadata);
}
Handle<Value> GetNodeValue() const {
NanEscapableScope();
if (call == NULL) {
return NanEscapeScope(NanNull());
}
Handle<Object> obj = NanNew<Object>();
obj->Set(NanNew("call"), Call::WrapStruct(call));
obj->Set(NanNew("method"), NanNew(details.method));
obj->Set(NanNew("host"), NanNew(details.host));
obj->Set(NanNew("deadline"),
NanNew<Date>(TimespecToMilliseconds(details.deadline)));
obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata));
return NanEscapeScope(obj);
}
bool ParseOp(Handle<Value> value, grpc_op *out,
shared_ptr<Resources> resources) {
return true;
}
grpc_call *call;
grpc_call_details details;
grpc_metadata_array request_metadata;
protected:
std::string GetTypeString() const {
return "new call";
}
};
Server::Server(grpc_server *server) : wrapped_server(server) {}
Server::~Server() { grpc_server_destroy(wrapped_server); }
void Server::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("Server"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "requestCall",
FunctionTemplate::New(RequestCall)->GetFunction());
NanSetPrototypeTemplate(tpl, "addHttp2Port",
FunctionTemplate::New(AddHttp2Port)->GetFunction());
NanSetPrototypeTemplate(
tpl, "addSecureHttp2Port",
FunctionTemplate::New(AddSecureHttp2Port)->GetFunction());
NanSetPrototypeTemplate(tpl, "start",
FunctionTemplate::New(Start)->GetFunction());
NanSetPrototypeTemplate(tpl, "shutdown",
FunctionTemplate::New(Shutdown)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(String::NewSymbol("Server"), constructor);
}
bool Server::HasInstance(Handle<Value> val) {
return NanHasInstance(fun_tpl, val);
}
NAN_METHOD(Server::New) {
NanScope();
/* If this is not a constructor call, make a constructor call and return
the result */
if (!args.IsConstructCall()) {
const int argc = 1;
Local<Value> argv[argc] = {args[0]};
NanReturnValue(constructor->NewInstance(argc, argv));
}
grpc_server *wrapped_server;
grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
if (args[0]->IsUndefined()) {
wrapped_server = grpc_server_create(queue, NULL);
} else if (args[0]->IsObject()) {
grpc_server_credentials *creds = NULL;
Handle<Object> args_hash(args[0]->ToObject()->Clone());
if (args_hash->HasOwnProperty(NanNew("credentials"))) {
Handle<Value> creds_value = args_hash->Get(NanNew("credentials"));
if (!ServerCredentials::HasInstance(creds_value)) {
return NanThrowTypeError(
"credentials arg must be a ServerCredentials object");
}
ServerCredentials *creds_object =
ObjectWrap::Unwrap<ServerCredentials>(creds_value->ToObject());
creds = creds_object->GetWrappedServerCredentials();
args_hash->Delete(NanNew("credentials"));
}
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
if (creds == NULL) {
wrapped_server = grpc_server_create(queue, &channel_args);
} else {
wrapped_server = grpc_secure_server_create(creds, queue, &channel_args);
}
free(channel_args.args);
} else {
return NanThrowTypeError("Server expects an object");
}
Server *server = new Server(wrapped_server);
server->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(Server::RequestCall) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("requestCall can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NewCallOp *op = new NewCallOp();
std::vector<unique_ptr<Op> > *ops = new std::vector<unique_ptr<Op> >();
ops->push_back(unique_ptr<Op>(op));
grpc_call_error error = grpc_server_request_call(
server->wrapped_server, &op->call, &op->details, &op->request_metadata,
CompletionQueueAsyncWorker::GetQueue(),
new struct tag(new NanCallback(args[0].As<Function>()), ops,
shared_ptr<Resources>(nullptr)));
if (error != GRPC_CALL_OK) {
return NanThrowError("requestCall failed", error);
}
CompletionQueueAsyncWorker::Next();
NanReturnUndefined();
}
NAN_METHOD(Server::AddHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("addHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError("addHttp2Port's argument must be a String");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NanReturnValue(NanNew<Number>(grpc_server_add_http2_port(
server->wrapped_server, *NanUtf8String(args[0]))));
}
NAN_METHOD(Server::AddSecureHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError(
"addSecureHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError("addSecureHttp2Port's argument must be a String");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NanReturnValue(NanNew<Number>(grpc_server_add_secure_http2_port(
server->wrapped_server, *NanUtf8String(args[0]))));
}
NAN_METHOD(Server::Start) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("start can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
grpc_server_start(server->wrapped_server);
NanReturnUndefined();
}
NAN_METHOD(Server::Shutdown) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("shutdown can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
grpc_server_shutdown(server->wrapped_server);
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<commit_msg>Updated server.cc to match call.cc changes<commit_after>/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <memory>
#include "server.h"
#include <node.h>
#include <nan.h>
#include <malloc.h>
#include <vector>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "grpc/support/log.h"
#include "call.h"
#include "completion_queue_async_worker.h"
#include "server_credentials.h"
#include "timeval.h"
namespace grpc {
namespace node {
using std::unique_ptr;
using v8::Arguments;
using v8::Array;
using v8::Boolean;
using v8::Date;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> Server::constructor;
Persistent<FunctionTemplate> Server::fun_tpl;
class NewCallOp : public Op {
public:
NewCallOp() {
call = NULL;
grpc_call_details_init(&details);
grpc_metadata_array_init(&request_metadata);
}
~NewCallOp() {
grpc_call_details_destroy(&details);
grpc_metadata_array_destroy(&request_metadata);
}
Handle<Value> GetNodeValue() const {
NanEscapableScope();
if (call == NULL) {
return NanEscapeScope(NanNull());
}
Handle<Object> obj = NanNew<Object>();
obj->Set(NanNew("call"), Call::WrapStruct(call));
obj->Set(NanNew("method"), NanNew(details.method));
obj->Set(NanNew("host"), NanNew(details.host));
obj->Set(NanNew("deadline"),
NanNew<Date>(TimespecToMilliseconds(details.deadline)));
obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata));
return NanEscapeScope(obj);
}
bool ParseOp(Handle<Value> value, grpc_op *out,
shared_ptr<Resources> resources) {
return true;
}
grpc_call *call;
grpc_call_details details;
grpc_metadata_array request_metadata;
protected:
std::string GetTypeString() const {
return "new call";
}
};
Server::Server(grpc_server *server) : wrapped_server(server) {}
Server::~Server() { grpc_server_destroy(wrapped_server); }
void Server::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("Server"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "requestCall",
FunctionTemplate::New(RequestCall)->GetFunction());
NanSetPrototypeTemplate(tpl, "addHttp2Port",
FunctionTemplate::New(AddHttp2Port)->GetFunction());
NanSetPrototypeTemplate(
tpl, "addSecureHttp2Port",
FunctionTemplate::New(AddSecureHttp2Port)->GetFunction());
NanSetPrototypeTemplate(tpl, "start",
FunctionTemplate::New(Start)->GetFunction());
NanSetPrototypeTemplate(tpl, "shutdown",
FunctionTemplate::New(Shutdown)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(String::NewSymbol("Server"), constructor);
}
bool Server::HasInstance(Handle<Value> val) {
return NanHasInstance(fun_tpl, val);
}
NAN_METHOD(Server::New) {
NanScope();
/* If this is not a constructor call, make a constructor call and return
the result */
if (!args.IsConstructCall()) {
const int argc = 1;
Local<Value> argv[argc] = {args[0]};
NanReturnValue(constructor->NewInstance(argc, argv));
}
grpc_server *wrapped_server;
grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
if (args[0]->IsUndefined()) {
wrapped_server = grpc_server_create(queue, NULL);
} else if (args[0]->IsObject()) {
grpc_server_credentials *creds = NULL;
Handle<Object> args_hash(args[0]->ToObject()->Clone());
if (args_hash->HasOwnProperty(NanNew("credentials"))) {
Handle<Value> creds_value = args_hash->Get(NanNew("credentials"));
if (!ServerCredentials::HasInstance(creds_value)) {
return NanThrowTypeError(
"credentials arg must be a ServerCredentials object");
}
ServerCredentials *creds_object =
ObjectWrap::Unwrap<ServerCredentials>(creds_value->ToObject());
creds = creds_object->GetWrappedServerCredentials();
args_hash->Delete(NanNew("credentials"));
}
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
if (creds == NULL) {
wrapped_server = grpc_server_create(queue, &channel_args);
} else {
wrapped_server = grpc_secure_server_create(creds, queue, &channel_args);
}
free(channel_args.args);
} else {
return NanThrowTypeError("Server expects an object");
}
Server *server = new Server(wrapped_server);
server->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(Server::RequestCall) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("requestCall can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NewCallOp *op = new NewCallOp();
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
grpc_call_error error = grpc_server_request_call(
server->wrapped_server, &op->call, &op->details, &op->request_metadata,
CompletionQueueAsyncWorker::GetQueue(),
new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),
shared_ptr<Resources>(nullptr)));
if (error != GRPC_CALL_OK) {
return NanThrowError("requestCall failed", error);
}
CompletionQueueAsyncWorker::Next();
NanReturnUndefined();
}
NAN_METHOD(Server::AddHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("addHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError("addHttp2Port's argument must be a String");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NanReturnValue(NanNew<Number>(grpc_server_add_http2_port(
server->wrapped_server, *NanUtf8String(args[0]))));
}
NAN_METHOD(Server::AddSecureHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError(
"addSecureHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError("addSecureHttp2Port's argument must be a String");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
NanReturnValue(NanNew<Number>(grpc_server_add_secure_http2_port(
server->wrapped_server, *NanUtf8String(args[0]))));
}
NAN_METHOD(Server::Start) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("start can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
grpc_server_start(server->wrapped_server);
NanReturnUndefined();
}
NAN_METHOD(Server::Shutdown) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("shutdown can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
grpc_server_shutdown(server->wrapped_server);
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) University College London (UCL).
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 "QmitkCmdLineModuleMenuComboBox.h"
#include <iostream>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QList>
#include <cassert>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleManager.h>
// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)
: ctkMenuComboBox(parent)
, m_ModuleManager(NULL)
{
}
// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()
{
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)
{
if (m_ModuleManager != NULL)
{
QObject::disconnect(manager, 0, this, 0);
}
m_ModuleManager = manager;
connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));
connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));
}
// -------------------------------------------------------------------------
ctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const
{
return m_ModuleManager;
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference&)
{
this->RebuildMenu();
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference&)
{
this->RebuildMenu();
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::AddName(
QList< QHash<QString, QMenu*>* >& listOfHashMaps,
const int& depth,
const QString& name,
QMenu* menu
)
{
if (depth >= listOfHashMaps.size())
{
int need = depth - listOfHashMaps.size();
for (int i = 0; i <= need; i++)
{
QHash<QString, QMenu*> *newHashMap = new QHash<QString, QMenu*>();
listOfHashMaps.push_back(newHashMap);
}
}
listOfHashMaps[depth]->insert(name, menu);
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::RebuildMenu()
{
if (m_ModuleManager == NULL)
{
qDebug() << "QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?";
return;
}
// Can't see another way to get a nested menu, without rebuilding the whole thing each time.
// :-(
QMenu *menu = new QMenu();
QStringList listOfModules;
QList<ctkCmdLineModuleReference> references = m_ModuleManager->moduleReferences();
// Get full names
for (int i = 0; i < references.size(); i++)
{
ctkCmdLineModuleReference reference = references[i];
ctkCmdLineModuleDescription description = reference.description();
QString title = description.title();
QString category = description.category();
QString fullName = category + "." + title;
listOfModules << fullName;
}
// Sort list, so menu comes out in some sort of nice order.
listOfModules.sort();
// Temporary data structure to enable connecting menus together.
QList< QHash<QString, QMenu*>* > list;
// Iterate through all modules.
foreach (QString fullName, listOfModules)
{
// Pointer to keep track of where we are in the menu tree.
QMenu *currentMenu = menu;
// Get individual parts, as they correspond to menu levels.
QStringList nameParts = fullName.split(".", QString::SkipEmptyParts);
// Iterate over each part, building up either a QMenu or QAction.
for (int i = 0; i < nameParts.size(); i++)
{
QString part = nameParts[i];
if (i != nameParts.size() - 1)
{
// Need to add a menu/submenu, not an action.
if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))
{
QMenu *newMenu = new QMenu(part);
currentMenu->addMenu(newMenu);
currentMenu = newMenu;
// Add this newMenu pointer to temporary datastructure,
// so we know we have already created it.
this->AddName(list, i, part, newMenu);
}
else
{
currentMenu = list[i]->value(part);
}
}
else
{
// Leaf node, just add the action.
QAction *action = currentMenu->addAction(part);
// We set the object name, so we can retrieve it later when we want to
// rebuild a new GUI depending on the name of the action.
// see QmitkCmdLineModuleProgressWidget.
action->setObjectName(fullName);
}
}
}
// Clearup termporary data structure
for (int i = 0; i < list.size(); i++)
{
delete list[i];
}
// Set the constructed menu on the base class combo box.
this->setMenu(menu);
}
<commit_msg>Declared ctkCmdLineModuleReference as Qt MetaType to stop ctkMenuComboBox dropping entries<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) University College London (UCL).
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 "QmitkCmdLineModuleMenuComboBox.h"
#include <iostream>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QList>
#include <cassert>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleManager.h>
// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)
: ctkMenuComboBox(parent)
, m_ModuleManager(NULL)
{
qRegisterMetaType<ctkCmdLineModuleReference>();
}
// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()
{
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)
{
if (m_ModuleManager != NULL)
{
QObject::disconnect(manager, 0, this, 0);
}
m_ModuleManager = manager;
connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));
connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));
}
// -------------------------------------------------------------------------
ctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const
{
return m_ModuleManager;
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference&)
{
this->RebuildMenu();
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference&)
{
this->RebuildMenu();
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::AddName(
QList< QHash<QString, QMenu*>* >& listOfHashMaps,
const int& depth,
const QString& name,
QMenu* menu
)
{
if (depth >= listOfHashMaps.size())
{
int need = depth - listOfHashMaps.size();
for (int i = 0; i <= need; i++)
{
QHash<QString, QMenu*> *newHashMap = new QHash<QString, QMenu*>();
listOfHashMaps.push_back(newHashMap);
}
}
listOfHashMaps[depth]->insert(name, menu);
}
// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::RebuildMenu()
{
if (m_ModuleManager == NULL)
{
qDebug() << "QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?";
return;
}
// Can't see another way to get a nested menu, without rebuilding the whole thing each time.
// :-(
QMenu *menu = new QMenu();
QStringList listOfModules;
QList<ctkCmdLineModuleReference> references = m_ModuleManager->moduleReferences();
// Get full names
for (int i = 0; i < references.size(); i++)
{
ctkCmdLineModuleReference reference = references[i];
ctkCmdLineModuleDescription description = reference.description();
QString title = description.title();
QString category = description.category();
QString fullName = category + "." + title;
listOfModules << fullName;
}
// Sort list, so menu comes out in some sort of nice order.
listOfModules.sort();
// Temporary data structure to enable connecting menus together.
QList< QHash<QString, QMenu*>* > list;
// Iterate through all modules.
foreach (QString fullName, listOfModules)
{
// Pointer to keep track of where we are in the menu tree.
QMenu *currentMenu = menu;
// Get individual parts, as they correspond to menu levels.
QStringList nameParts = fullName.split(".", QString::SkipEmptyParts);
// Iterate over each part, building up either a QMenu or QAction.
for (int i = 0; i < nameParts.size(); i++)
{
QString part = nameParts[i];
if (i != nameParts.size() - 1)
{
// Need to add a menu/submenu, not an action.
if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))
{
QMenu *newMenu = new QMenu(part);
currentMenu->addMenu(newMenu);
currentMenu = newMenu;
// Add this newMenu pointer to temporary datastructure,
// so we know we have already created it.
this->AddName(list, i, part, newMenu);
}
else
{
currentMenu = list[i]->value(part);
}
}
else
{
// Leaf node, just add the action.
QAction *action = currentMenu->addAction(part);
// We set the object name, so we can retrieve it later when we want to
// rebuild a new GUI depending on the name of the action.
// see QmitkCmdLineModuleProgressWidget.
action->setObjectName(fullName);
}
}
}
// Clearup termporary data structure
for (int i = 0; i < list.size(); i++)
{
delete list[i];
}
// Set the constructed menu on the base class combo box.
this->setMenu(menu);
}
<|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 "BaseTextShadowNode.h"
#include <react/components/text/RawTextProps.h>
#include <react/components/text/RawTextShadowNode.h>
#include <react/components/text/TextProps.h>
#include <react/components/text/TextShadowNode.h>
#include <react/debug/DebugStringConvertibleItem.h>
namespace facebook {
namespace react {
AttributedString BaseTextShadowNode::getAttributedString(
const TextAttributes &textAttributes,
const SharedShadowNode &parentNode) const {
auto attributedString = AttributedString{};
for (const auto &childNode : parentNode->getChildren()) {
// RawShadowNode
auto rawTextShadowNode =
std::dynamic_pointer_cast<const RawTextShadowNode>(childNode);
if (rawTextShadowNode) {
auto fragment = AttributedString::Fragment{};
fragment.string = rawTextShadowNode->getProps()->text;
fragment.textAttributes = textAttributes;
fragment.parentShadowNode = parentNode;
attributedString.appendFragment(fragment);
continue;
}
// TextShadowNode
auto textShadowNode =
std::dynamic_pointer_cast<const TextShadowNode>(childNode);
if (textShadowNode) {
auto localTextAttributes = textAttributes;
localTextAttributes.apply(textShadowNode->getProps()->textAttributes);
attributedString.appendAttributedString(
textShadowNode->getAttributedString(
localTextAttributes, textShadowNode));
continue;
}
// Any other kind of ShadowNode
auto fragment = AttributedString::Fragment{};
fragment.shadowNode = childNode;
fragment.textAttributes = textAttributes;
attributedString.appendFragment(fragment);
}
return attributedString;
}
} // namespace react
} // namespace facebook
<commit_msg>Fabric: Fixed a retain cycle between ParagraphShadowNode, LocalData and AttributedString<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 "BaseTextShadowNode.h"
#include <react/components/text/RawTextProps.h>
#include <react/components/text/RawTextShadowNode.h>
#include <react/components/text/TextProps.h>
#include <react/components/text/TextShadowNode.h>
#include <react/debug/DebugStringConvertibleItem.h>
namespace facebook {
namespace react {
AttributedString BaseTextShadowNode::getAttributedString(
const TextAttributes &textAttributes,
const SharedShadowNode &parentNode) const {
auto attributedString = AttributedString{};
for (const auto &childNode : parentNode->getChildren()) {
// RawShadowNode
auto rawTextShadowNode =
std::dynamic_pointer_cast<const RawTextShadowNode>(childNode);
if (rawTextShadowNode) {
auto fragment = AttributedString::Fragment{};
fragment.string = rawTextShadowNode->getProps()->text;
fragment.textAttributes = textAttributes;
// Storing a retaining pointer to `ParagraphShadowNode` inside
// `attributedString` causes a retain cycle (besides that fact that we
// don't need it at all). Storing a `ShadowView` instance instead of
// `ShadowNode` should properly fix this problem.
fragment.parentShadowNode =
std::dynamic_pointer_cast<const TextShadowNode>(parentNode)
? parentNode
: nullptr;
attributedString.appendFragment(fragment);
continue;
}
// TextShadowNode
auto textShadowNode =
std::dynamic_pointer_cast<const TextShadowNode>(childNode);
if (textShadowNode) {
auto localTextAttributes = textAttributes;
localTextAttributes.apply(textShadowNode->getProps()->textAttributes);
attributedString.appendAttributedString(
textShadowNode->getAttributedString(
localTextAttributes, textShadowNode));
continue;
}
// Any other kind of ShadowNode
auto fragment = AttributedString::Fragment{};
fragment.shadowNode = childNode;
fragment.textAttributes = textAttributes;
attributedString.appendFragment(fragment);
}
return attributedString;
}
} // namespace react
} // namespace facebook
<|endoftext|> |
<commit_before>#include "musicxmsongsuggestthread.h"
#include "musicdownloadxminterface.h"
#///QJson import
#include "qjson/parser.h"
MusicXMSongSuggestThread::MusicXMSongSuggestThread(QObject *parent)
: MusicDownLoadSongSuggestThread(parent)
{
}
void MusicXMSongSuggestThread::startToSearch(const QString &text)
{
if(!m_manager)
{
return;
}
M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(text));
deleteAll();
const QUrl &musicUrl = MusicUtils::Algorithm::mdII(XM_SUGGEST_URL, false).arg(text);
m_interrupt = true;
qDebug() << musicUrl;
QNetworkRequest request;
request.setUrl(musicUrl);
request.setRawHeader("User-Agent", MusicUtils::Algorithm::mdII(XM_UA_URL_1, ALG_UA_KEY, false).toUtf8());
MusicObject::setSslConfiguration(&request);
m_reply = m_manager->get(request);
connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)));
}
void MusicXMSongSuggestThread::downLoadFinished()
{
if(!m_reply || !m_manager)
{
deleteAll();
return;
}
M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName()));
m_items.clear();
m_interrupt = false;
if(m_reply->error() == QNetworkReply::NoError)
{
const QByteArray &bytes = m_reply->readAll();
QJson::Parser parser;
bool ok;
const QVariant &data = parser.parse(bytes, &ok);
if(ok)
{
const QVariantList &datas = data.toList();
foreach(const QVariant &var, datas)
{
if(m_interrupt) return;
if(var.isNull())
{
continue;
}
const QVariantMap &value = var.toMap();
MusicResultsItem item;
item.m_name = value["song_name"].toString();
item.m_nickName = value["artist_name"].toString();
m_items << item;
}
}
}
emit downLoadDataChanged(QString());
deleteAll();
M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName()));
}
<commit_msg>Remove[987452]<commit_after>#include "musicxmsongsuggestthread.h"
#include "musicdownloadxminterface.h"
#///QJson import
#include "qjson/parser.h"
MusicXMSongSuggestThread::MusicXMSongSuggestThread(QObject *parent)
: MusicDownLoadSongSuggestThread(parent)
{
}
void MusicXMSongSuggestThread::startToSearch(const QString &text)
{
if(!m_manager)
{
return;
}
M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(text));
deleteAll();
const QUrl &musicUrl = MusicUtils::Algorithm::mdII(XM_SUGGEST_URL, false).arg(text);
m_interrupt = true;
QNetworkRequest request;
request.setUrl(musicUrl);
request.setRawHeader("User-Agent", MusicUtils::Algorithm::mdII(XM_UA_URL_1, ALG_UA_KEY, false).toUtf8());
MusicObject::setSslConfiguration(&request);
m_reply = m_manager->get(request);
connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)));
}
void MusicXMSongSuggestThread::downLoadFinished()
{
if(!m_reply || !m_manager)
{
deleteAll();
return;
}
M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName()));
m_items.clear();
m_interrupt = false;
if(m_reply->error() == QNetworkReply::NoError)
{
const QByteArray &bytes = m_reply->readAll();
QJson::Parser parser;
bool ok;
const QVariant &data = parser.parse(bytes, &ok);
if(ok)
{
const QVariantList &datas = data.toList();
foreach(const QVariant &var, datas)
{
if(m_interrupt) return;
if(var.isNull())
{
continue;
}
const QVariantMap &value = var.toMap();
MusicResultsItem item;
item.m_name = value["song_name"].toString();
item.m_nickName = value["artist_name"].toString();
m_items << item;
}
}
}
emit downLoadDataChanged(QString());
deleteAll();
M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName()));
}
<|endoftext|> |
<commit_before>#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osgDB/ReadFile>
#include <osgText/Text>
#include <osgSim/SphereSegment>
#include <osgSim/OverlayNode>
#include <osgParticle/ExplosionEffect>
#include <osgParticle/SmokeEffect>
#include <osgParticle/FireEffect>
#include <osgParticle/ParticleSystemUpdater>
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* glider = osgDB::readNodeFile("glider.osg");
if (glider)
{
const osg::BoundingSphere& bs = glider->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
positioned->addChild(glider);
osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
xform->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
xform->addChild(positioned);
model->addChild(xform);
}
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
osgText::Text* text = new osgText::Text;
float size = radius/bs.radius()*0.3f;
text->setPosition(bs.center());
text->setText("Cessna");
text->setAlignment(osgText::Text::CENTER_CENTER);
text->setAxisAlignment(osgText::Text::SCREEN);
text->setCharacterSize(40.0f);
text->setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(text);
osg::LOD* lod = new osg::LOD;
lod->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
lod->addChild(geode,0.0f,100.0f);
lod->addChild(cessna,100.0f,10000.0f);
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
//positioned->addChild(cessna);
positioned->addChild(lod);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
// add particle effects to cessna.
{
osg::PositionAttitudeTransform* positionEffects = new osg::PositionAttitudeTransform;
positionEffects->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
xform->addChild(positionEffects);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect;
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect;
osgParticle::FireEffect* fire = new osgParticle::FireEffect;
positionEffects->addChild(explosion);
positionEffects->addChild(smoke);
positionEffects->addChild(fire);
}
model->addChild(xform);
}
return model;
}
osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
{
osgUtil::IntersectVisitor iv;
osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
const osg::BoundingSphere& bs = subgraph->getBound();
float zMax = bs.center().z()+bs.radius();
float zMin = bs.center().z()-bs.radius();
segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
iv.addLineSegment(segDown.get());
subgraph->accept(iv);
if (iv.hits())
{
osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
if (!hitList.empty())
{
osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
return ip;
}
}
return osg::Vec3(x,y,0.0f);
}
//////////////////////////////////////////////////////////////////////////////
// MAIN SCENE GRAPH BUILDING FUNCTION
//////////////////////////////////////////////////////////////////////////////
void build_world(osg::Group *root)
{
// create terrain
osg::ref_ptr<osg::Geode> terrainGeode = 0;
{
terrainGeode = new osg::Geode;
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
terrainGeode->setStateSet( stateset );
float size = 1000; // 10km;
float scale = size/39.0f; // 10km;
float z_scale = scale*3.0f;
osg::HeightField* grid = new osg::HeightField;
grid->allocate(38,39);
grid->setXInterval(scale);
grid->setYInterval(scale);
for(unsigned int r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
grid->setHeight(c,r,z_scale*vertex[r+c*39][2]);
}
}
terrainGeode->addDrawable(new osg::ShapeDrawable(grid));
}
// create sphere segment
osg::ref_ptr<osgSim::SphereSegment> ss = 0;
{
ss = new osgSim::SphereSegment(
computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
500.0f, // radius
osg::DegreesToRadians(135.0f),
osg::DegreesToRadians(245.0f),
osg::DegreesToRadians(-10.0f),
osg::DegreesToRadians(30.0f),
60);
ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
root->addChild(ss.get());
}
#if 1
osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
overlayNode->setOverlaySubgraph(ss.get());
overlayNode->setOverlayTextureSizeHint(2048);
overlayNode->addChild(terrainGeode.get());
root->addChild(overlayNode);
#else
root->addChild(terrainGeode);
#endif
// create particle effects
{
osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
root->addChild(explosion);
root->addChild(smoke);
root->addChild(fire);
}
// create particle effects
{
osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
root->addChild(explosion);
root->addChild(smoke);
root->addChild(fire);
}
// create the moving models.
{
root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
}
}
//////////////////////////////////////////////////////////////////////////////
// main()
//////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::Group *root = new osg::Group;
build_world(root);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added a grid of lines into the OverlaySubgraph to demonstate use the OverlayNode for applying general drawing onto terrain.<commit_after>#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/Geometry>
#include <osgDB/ReadFile>
#include <osgText/Text>
#include <osgSim/SphereSegment>
#include <osgSim/OverlayNode>
#include <osgParticle/ExplosionEffect>
#include <osgParticle/SmokeEffect>
#include <osgParticle/FireEffect>
#include <osgParticle/ParticleSystemUpdater>
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* glider = osgDB::readNodeFile("glider.osg");
if (glider)
{
const osg::BoundingSphere& bs = glider->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
positioned->addChild(glider);
osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
xform->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
xform->addChild(positioned);
model->addChild(xform);
}
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
osgText::Text* text = new osgText::Text;
float size = radius/bs.radius()*0.3f;
text->setPosition(bs.center());
text->setText("Cessna");
text->setAlignment(osgText::Text::CENTER_CENTER);
text->setAxisAlignment(osgText::Text::SCREEN);
text->setCharacterSize(40.0f);
text->setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(text);
osg::LOD* lod = new osg::LOD;
lod->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
lod->addChild(geode,0.0f,100.0f);
lod->addChild(cessna,100.0f,10000.0f);
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
//positioned->addChild(cessna);
positioned->addChild(lod);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
// add particle effects to cessna.
{
osg::PositionAttitudeTransform* positionEffects = new osg::PositionAttitudeTransform;
positionEffects->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
xform->addChild(positionEffects);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect;
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect;
osgParticle::FireEffect* fire = new osgParticle::FireEffect;
positionEffects->addChild(explosion);
positionEffects->addChild(smoke);
positionEffects->addChild(fire);
}
model->addChild(xform);
}
return model;
}
osg::Group* createOverlay(const osg::Vec3& center, float radius)
{
osg::Group* group = new osg::Group;
// create a grid of lines.
{
osg::Geometry* geom = new osg::Geometry;
unsigned int num_rows = 10;
osg::Vec3 left = center+osg::Vec3(-radius,-radius,0.0f);
osg::Vec3 right = center+osg::Vec3(radius,-radius,0.0f);
osg::Vec3 delta_row = osg::Vec3(0.0f,2.0f*radius/float(num_rows-1),0.0f);
osg::Vec3 top = center+osg::Vec3(-radius,radius,0.0f);
osg::Vec3 bottom = center+osg::Vec3(-radius,-radius,0.0f);
osg::Vec3 delta_column = osg::Vec3(2.0f*radius/float(num_rows-1),0.0f,0.0f);
osg::Vec3Array* vertices = new osg::Vec3Array;
for(unsigned int i=0; i<num_rows; ++i)
{
vertices->push_back(left);
vertices->push_back(right);
left += delta_row;
right += delta_row;
vertices->push_back(top);
vertices->push_back(bottom);
top += delta_column;
bottom += delta_column;
}
geom->setVertexArray(vertices);
geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES,0,vertices->getNumElements()));
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
group->addChild(geode);
}
return group;
}
osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
{
osgUtil::IntersectVisitor iv;
osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
const osg::BoundingSphere& bs = subgraph->getBound();
float zMax = bs.center().z()+bs.radius();
float zMin = bs.center().z()-bs.radius();
segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
iv.addLineSegment(segDown.get());
subgraph->accept(iv);
if (iv.hits())
{
osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
if (!hitList.empty())
{
osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
return ip;
}
}
return osg::Vec3(x,y,0.0f);
}
//////////////////////////////////////////////////////////////////////////////
// MAIN SCENE GRAPH BUILDING FUNCTION
//////////////////////////////////////////////////////////////////////////////
void build_world(osg::Group *root)
{
// create terrain
osg::ref_ptr<osg::Geode> terrainGeode = 0;
{
terrainGeode = new osg::Geode;
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
terrainGeode->setStateSet( stateset );
float size = 1000; // 10km;
float scale = size/39.0f; // 10km;
float z_scale = scale*3.0f;
osg::HeightField* grid = new osg::HeightField;
grid->allocate(38,39);
grid->setXInterval(scale);
grid->setYInterval(scale);
for(unsigned int r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
grid->setHeight(c,r,z_scale*vertex[r+c*39][2]);
}
}
terrainGeode->addDrawable(new osg::ShapeDrawable(grid));
}
// create sphere segment
osg::ref_ptr<osgSim::SphereSegment> ss = 0;
{
ss = new osgSim::SphereSegment(
computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
500.0f, // radius
osg::DegreesToRadians(135.0f),
osg::DegreesToRadians(245.0f),
osg::DegreesToRadians(-10.0f),
osg::DegreesToRadians(30.0f),
60);
ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
root->addChild(ss.get());
}
#if 1
osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
const osg::BoundingSphere& bs = terrainGeode->getBound();
osg::Group* overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5f);
overlaySubgraph->addChild(ss.get());
overlayNode->setOverlaySubgraph(overlaySubgraph);
overlayNode->setOverlayTextureSizeHint(2048);
overlayNode->addChild(terrainGeode.get());
root->addChild(overlayNode);
#else
root->addChild(terrainGeode);
#endif
// create particle effects
{
osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
root->addChild(explosion);
root->addChild(smoke);
root->addChild(fire);
}
// create particle effects
{
osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
root->addChild(explosion);
root->addChild(smoke);
root->addChild(fire);
}
// create the moving models.
{
root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
}
}
//////////////////////////////////////////////////////////////////////////////
// main()
//////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::Group *root = new osg::Group;
build_world(root);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*
* George Papanikolaou CEID 2014
* Shortest Augmenting Path Maximum Flow algorithm implementation
* aka "Edmonds–Karp algorithm"
*/
#include <cstdlib>
#include <ctime>
#include <vector>
#include <utility>
#include <algorithm>
#include "boost-types.h"
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/property_map.hpp>
/*
* Find minimum value from the target of outgoing edges of a vertex in a graph. Yeah.
*/
static inline int find_min_out_edges(const BoostVertex& initial,
const IndexMap *index,
const VerticesSizeType *cost,
const BoostGraph& G)
{
int value, min;
BoostOutEdgeIt one, two;
bool first_iteration = true;
for (boost::tie(one, two) = boost::out_edges(initial, G); one != two; ++one) {
value = cost[index[boost::target(*one)]];
if (first_iteration) {
min = value;
first_iteration = false;
} else {
if (value < min)
min = value;
}
}
return min;
}
/*
* Tracing the path back to the source and finding the minimux residue capacity
*/
static int min_res_on_path(BoostGraph& BG, VerticesSizeType *parent, int f)
{
int cap;
int delta = 1000; /* something big so we can find smaller values */
BoostVertex u, v;
while (parent[f] != NULL) {
/* getting the capacity */
u = boost::vertex(f, BG);
v = boost::vertex(parent[f], BG);
cap = BG[boost::edge(u, v, BG).first];
/* trying to find min */
if (delta > cap)
delta = cap;
/* next... */
f = parent[f];
}
return delta;
}
/*
* this file's core function
*/
int shortest_aug_path(BoostGraph& BG, BoostVertex& source, BoostVertex& target)
{
int i, j, s, t, delta;
unsigned int n = boost::num_vertices(BG);
unsigned int m = boost::num_edges(BG);
BoostOutEdgeIt current, next;
std::vector<BoostVertex> avail;
/* We use an "index map" in order to easily assign IDs to vertices, and be able
* to use regular arrays. Boost visitors use regular arrays and they are simpler
* than using Propery Maps */
IndexMap index = boost::get(boost::vertex_index, BG);
/* We'll just use a regular array to store the distances for the sake of simplicity. */
VerticesSizeType distances[n];
std::fill_n(distances, n, 0);
/* ...and a similar one for the parent nodes */
VerticesSizeType parent[n];
std::fill_n(parent, n, NULL); // TODO: maybe null is not allowed. in that case choose an unchosen id
/* Getting the distance labels by reversed BFS. Creating the visitor inline. */
boost::breadth_first_search(boost::make_reverse_graph(BG), boost::vertex(t, BG),
boost::visitor(boost::make_bfs_visitor(boost::record_distances(&distances[0],
boost::on_tree_edge()))));
/* getting the index, since we're working we them now, and starting main loop... */
s = index[source];
t = index[target];
i = s;
while (distances[s] < n) {
/* Iterating through all out going edges of current node */
for (boost::tie(current, next) = boost::out_edges(boost::vertex(i, BG), BG); current != next; ++current) {
/* Selecting only admissible ones */
if (distances[i] == distances[boost::target(*current)] + 1)
avail.push_back(boost::target(*current, BG));
}
if (avail.size() != 0) {
/* Get the requirements */
j = index[avail[0]]; // TODO: (maybe) we need a way to go to the second
/* ADVANCE operation */
parent[j] = i;
i = j;
if (i == t) {
/* We're there. AUGMENT operation.
* We need to find the minimum residual capacity and use it to augment */
// TODO: we need to augment and edit the graph
delta = min_res_on_path(BG, parent, i);
/* Let's go again */
i = s;
}
} else {
/* RETREAT operation. Relabel first. */
distances[i] = 1 + find_min_out_edges(boost::vertex(i, BG), index, distances, BG);
/* ...and then backtrack. */
if (i != s)
i = parent[i];
}
}
}
<commit_msg>altering the new function to actually perform the augmentation<commit_after>/*
* George Papanikolaou CEID 2014
* Shortest Augmenting Path Maximum Flow algorithm implementation
* aka "Edmonds–Karp algorithm"
*/
#include <cstdlib>
#include <ctime>
#include <vector>
#include <utility>
#include <algorithm>
#include "boost-types.h"
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/property_map.hpp>
/*
* Find minimum value from the target of outgoing edges of a vertex in a graph. Yeah.
*/
static inline int find_min_out_edges(const BoostVertex& initial,
const IndexMap *index,
const VerticesSizeType *cost,
const BoostGraph& G)
{
int value, min;
BoostOutEdgeIt one, two;
bool first_iteration = true;
for (boost::tie(one, two) = boost::out_edges(initial, G); one != two; ++one) {
value = cost[index[boost::target(*one)]];
if (first_iteration) {
min = value;
first_iteration = false;
} else {
if (value < min)
min = value;
}
}
return min;
}
/*
* Tracing the path back to the source, finding min residual capacity and augmenting it.
*/
static void augment_path(BoostGraph& BG, VerticesSizeType *parent, int f)
{
int cap;
int delta = 1000; /* something big so we can find smaller values */
BoostEdge e;
BoostVertex u, v;
std::vector<BoostEdge> path;
/* Finding the smaller capacity in the path */
while (parent[f] != NULL) {
/* finding the next edge, saving it and getting the capacity */
u = boost::vertex(f, BG);
v = boost::vertex(parent[f], BG);
e = boost::edge(u, v, BG).first;
path.push_back(e);
cap = BG[e];
/* trying to find min */
if (delta > cap)
delta = cap;
/* next... */
f = parent[f];
}
if (delta == 1000)
std::cerr << "ERROR: There should have been a aug path there." << std::endl;
/* Iterating over the path to saturate the edges (using delta).
* This is where the actual graph gets altered. */
for (std::vector<BoostEdge>::iterator it = path.begin(); it != path.end(); ++it) {
BG[*it] -= delta;
if (BG[*it] <= 0)
boost::remove_edge(*it);
boost::add_edge(boost::target(*it, BG), boost::source(*it, BG), delta, BG);
}
}
/*
* this file's core function
*/
int shortest_aug_path(BoostGraph& BG, BoostVertex& source, BoostVertex& target)
{
int i, j, s, t, delta;
unsigned int n = boost::num_vertices(BG);
unsigned int m = boost::num_edges(BG);
BoostOutEdgeIt current, next;
std::vector<BoostVertex> avail;
/* We use an "index map" in order to easily assign IDs to vertices, and be able
* to use regular arrays. Boost visitors use regular arrays and they are simpler
* than using Propery Maps */
IndexMap index = boost::get(boost::vertex_index, BG);
/* We'll just use a regular array to store the distances for the sake of simplicity. */
VerticesSizeType distances[n];
std::fill_n(distances, n, 0);
/* ...and a similar one for the parent nodes */
VerticesSizeType parent[n];
std::fill_n(parent, n, NULL); // TODO: maybe null is not allowed. in that case choose an unchosen id
/* Getting the distance labels by reversed BFS. Creating the visitor inline. */
boost::breadth_first_search(boost::make_reverse_graph(BG), boost::vertex(t, BG),
boost::visitor(boost::make_bfs_visitor(boost::record_distances(&distances[0],
boost::on_tree_edge()))));
/* getting the index, since we're working we them now, and starting main loop... */
s = index[source];
t = index[target];
i = s;
while (distances[s] < n) {
/* Iterating through all out going edges of current node */
for (boost::tie(current, next) = boost::out_edges(boost::vertex(i, BG), BG); current != next; ++current) {
/* Selecting only admissible ones */
if (distances[i] == distances[boost::target(*current)] + 1)
avail.push_back(boost::target(*current, BG));
}
if (avail.size() != 0) {
/* Get the requirements */
j = index[avail[0]];
/* ADVANCE operation */
parent[j] = i;
i = j;
if (i == t) {
/* We're there. AUGMENT operation. */
augment_path(BG, parent, i);
/* Let's go from the top again */
i = s;
}
} else {
/* RETREAT operation. Relabel first. */
distances[i] = 1 + find_min_out_edges(boost::vertex(i, BG), index, distances, BG);
/* ...and then backtrack. */
if (i != s)
i = parent[i];
}
}
}
<|endoftext|> |
<commit_before>/**
* Non-metric Space Library
*
* Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
* With contributions from Lawrence Cayton (http://lcayton.com/) and others.
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2016
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <string>
#include <fstream>
#include "knnquery.h"
#include "knnqueue.h"
#include "space.h"
#include "space_sparse_jaccard.h"
#include "space_sparse_vector_inter.h"
#include "params.h"
#include "projection.h"
#include "spacefactory.h"
#include "init.h"
#include "cmd_options.h"
#include "params_def.h"
using namespace similarity;
using namespace std;
template <class dist_t>
void sampleDist(string spaceType,
string inFile, string pivotFile, unsigned maxNumPivots, string outFilePrefix,
unsigned knn,
unsigned maxNumData,
unsigned knnQueryQty) {
ToLower(spaceType);
vector<string> spaceDesc;
const string descStr = spaceType;
ParseSpaceArg(descStr, spaceType, spaceDesc);
unique_ptr<AnyParams> spaceParams =
unique_ptr<AnyParams>(new AnyParams(spaceDesc));
unique_ptr<Space<dist_t>> space(SpaceFactoryRegistry<dist_t>::Instance().CreateSpace(spaceType, *spaceParams));
SpaceSparseJaccard<dist_t>* pJaccardSpace = dynamic_cast<SpaceSparseJaccard<dist_t>*>(space.get());
SpaceSparseVectorInter<dist_t>* pInterSpace = dynamic_cast<SpaceSparseVectorInter<dist_t>*>(space.get());
if (pJaccardSpace)
LOG(LIB_INFO) << "Sparse Jaccard space detected!";
if (pInterSpace)
LOG(LIB_INFO) << "Special sparse vector space detected!";
if (NULL == space.get()) {
LOG(LIB_FATAL) << "Cannot create the space: '" << spaceType
<< "' (desc: '" << descStr << "')";
} else {
LOG(LIB_INFO) << "Created space: " << spaceType;
}
ObjectVector data;
ObjectVector pivots;
LOG(LIB_INFO) << "maxNumData=" << maxNumData;
{
vector<string> tmp;
unique_ptr<DataFileInputState> inpState(space->ReadDataset(data, tmp, inFile, maxNumData));
space->UpdateParamsFromFile(*inpState);
}
if (!pivotFile.empty()) {
vector<string> tmp;
unique_ptr<DataFileInputState> inpState(space->ReadDataset(pivots, tmp, pivotFile, maxNumPivots));
space->UpdateParamsFromFile(*inpState);
LOG(LIB_INFO) << "Read " << pivots.size() << " pivots";
}
size_t N = data.size();
vector<char> isQuery(N);
string outFilePiv = outFilePrefix + "_pivots.tsv";
ofstream outPiv(outFilePiv);
LOG(LIB_INFO) << "knnQueryQty=" << knnQueryQty;
if (knnQueryQty >= N/2) {
LOG(LIB_FATAL) << "knnQueryQty is too large: should not exceed the number of data points / 2";
}
ObjectVector queries;
for (size_t i = 0; i < knnQueryQty; ++i) {
IdType iSel=0;
do {
iSel = RandomInt() % N;
// Should terminate quickly, b/c the probability of finding a data point, which is not previously selected, is >= 1/2
} while (isQuery[iSel]);
isQuery[iSel]=1;
queries.push_back(data[iSel]);
}
size_t pivotQty = pivots.size();
vector<vector<dist_t>> outNNDistMatrix(knn);
vector<vector<unsigned>> outNNOverlapMatrix(knn);
vector<vector<dist_t>> outPivDistMatrix(pivotQty);
vector<vector<unsigned>> outPivOverlapQtyMatrix(pivotQty);
vector<vector<float>> outPivOverlapFracMatrix(pivotQty);
for (size_t qid = 0; qid < knnQueryQty; ++qid) {
LOG(LIB_INFO) << "query index : " << qid << " id: " << queries[qid]->id();
KNNQuery<dist_t> query(*space, queries[qid], knn);
vector<dist_t> pivDist(pivotQty);
for (size_t pid = 0; pid < pivotQty; ++pid) {
pivDist[pid]=space->IndexTimeDistance(pivots[pid], queries[qid]); // Pivot plays the role of an object => it's a left argument
}
sort(pivDist.begin(),pivDist.end());
for (size_t pid = 0; pid < pivotQty; ++pid) {
outPivDistMatrix[pid].push_back(pivDist[pid]);
}
if (pJaccardSpace || pInterSpace) {
vector<unsigned> pivOverlap(pivotQty);
for (size_t pid = 0; pid < pivotQty; ++pid) {
pivOverlap[pid]=pJaccardSpace ?
pJaccardSpace->ComputeOverlap(pivots[pid], queries[qid]):
pInterSpace->ComputeOverlap(pivots[pid], queries[qid]);
}
sort(pivOverlap.begin(),pivOverlap.end(), [](unsigned qty1, unsigned qty2)->bool{ return qty1 > qty2;});
float elemQty = pJaccardSpace ? pJaccardSpace->GetElemQty(queries[qid]) :
pInterSpace->GetElemQty(queries[qid]);
float elemQtyInv = 1.0f/elemQty;
for (size_t pid = 0; pid < pivotQty; ++pid) {
outPivOverlapQtyMatrix[pid].push_back(pivOverlap[pid]);
outPivOverlapFracMatrix[pid].push_back(pivOverlap[pid]*elemQtyInv);
}
}
// Brute force search
for (size_t k = 0; k < N; ++k)
if (!isQuery[k]) {
query.CheckAndAddToResult(data[k]);
}
unique_ptr<KNNQueue<dist_t>> knnQ(query.Result()->Clone());
vector<pair<dist_t,unsigned>> dists_overlaps;
dists_overlaps.reserve(knn);
// Extracting results
while (!knnQ->Empty()) {
unsigned overlap = 0;
if (pJaccardSpace || pInterSpace) {
overlap = pJaccardSpace ?
pJaccardSpace->ComputeOverlap(knnQ->TopObject(), queries[qid]):
pInterSpace->ComputeOverlap(knnQ->TopObject(), queries[qid]);
}
dists_overlaps.insert(dists_overlaps.begin(),make_pair(knnQ->TopDistance(),overlap));
knnQ->Pop();
}
for (size_t k = 0; k < min<size_t>(dists_overlaps.size(), knn); ++k) {
outNNDistMatrix[k].push_back(dists_overlaps[k].first);
outNNOverlapMatrix[k].push_back(dists_overlaps[k].second);
}
}
string outFileDistNN = outFilePrefix + "_dist_NN.tsv";
ofstream outDistNN(outFileDistNN);
for (size_t i = 0; i < outNNDistMatrix.size(); ++i) {
const vector<dist_t>& dists2 = outNNDistMatrix[i];
if (!dists2.empty()) outDistNN << dists2[0];
for (size_t k = 1; k < dists2.size(); ++k) {
outDistNN << "\t" << dists2[k];
}
outDistNN << endl;
}
outDistNN.close();
if (pJaccardSpace || pInterSpace) {
string outFileOverlapNN = outFilePrefix + "_overlap_qty_NN.tsv";
ofstream outOverlapNN(outFileOverlapNN);
for (size_t i = 0; i < outNNOverlapMatrix.size(); ++i) {
const vector<unsigned>& overlaps = outNNOverlapMatrix[i];
if (!overlaps.empty()) outOverlapNN << overlaps[0];
for (size_t k = 1; k < overlaps.size(); ++k) {
outOverlapNN << "\t" << overlaps[k];
}
outOverlapNN << endl;
}
outOverlapNN.close();
}
for (size_t i = 0; i < pivotQty; ++i) {
const vector<dist_t>& dists3= outPivDistMatrix[i];
if (!dists3.empty()) outPiv << dists3[0];
for (size_t k = 1; k < dists3.size(); ++k) {
outPiv << "\t" << dists3[k];
}
outPiv << endl;
}
outPiv.close();
if (pJaccardSpace || pInterSpace) {
string outFileOverlapQty = outFilePrefix + "_overlap_qty.tsv";
string outFileOverlapFrac = outFilePrefix + "_overlap_frac.tsv";
ofstream outOverlapQty(outFileOverlapQty);
ofstream outOverlapFrac(outFileOverlapFrac);
for (size_t i = 0; i < pivotQty; ++i) {
const vector<unsigned>& qtys = outPivOverlapQtyMatrix[i];
if (!qtys.empty()) outOverlapQty << qtys[0];
for (size_t k = 1; k < qtys.size(); ++k) {
outOverlapQty << "\t" << qtys[k];
}
outOverlapQty << endl;
const vector<float>& fracs = outPivOverlapFracMatrix[i];
if (!fracs.empty()) outOverlapFrac << fracs[0];
for (size_t k = 1; k < fracs.size(); ++k) {
outOverlapFrac << "\t" << fracs[k];
}
outOverlapFrac << endl;
}
outOverlapQty.close();
outOverlapFrac.close();
}
}
int main(int argc, char *argv[]) {
string spaceType, distType, projSpaceType;
string inFile, pivotFile, outFilePrefix;
string projType;
string logFile;
unsigned maxNumData = 0;
unsigned maxNumPivots = 0;
unsigned knnQueryQty = 0;
unsigned knn = 0;
CmdOptions cmd_options;
cmd_options.Add(new CmdParam(SPACE_TYPE_PARAM_OPT, SPACE_TYPE_PARAM_MSG,
&spaceType, true));
cmd_options.Add(new CmdParam(DIST_TYPE_PARAM_OPT, DIST_TYPE_PARAM_MSG,
&distType, false, std::string(DIST_TYPE_FLOAT)));
cmd_options.Add(new CmdParam("inFile,i", "input data file",
&inFile, true));
cmd_options.Add(new CmdParam("outFilePrefix,o", "output file prefix",
&outFilePrefix, true));
cmd_options.Add(new CmdParam("pivotFile,p", "pivot file",
&pivotFile, false, ""));
cmd_options.Add(new CmdParam("maxNumPivot", "maximum number of pivots to use",
&maxNumPivots, false, 0));
cmd_options.Add(new CmdParam("knnQueryQty", "number of randomly selected queries",
&knnQueryQty, false, 0));
cmd_options.Add(new CmdParam(KNN_PARAM_OPT, "use this number of nearest neighbors",
&knn, 0));
cmd_options.Add(new CmdParam(MAX_NUM_DATA_PARAM_OPT, MAX_NUM_DATA_PARAM_MSG,
&maxNumData, false, 0));
cmd_options.Add(new CmdParam(LOG_FILE_PARAM_OPT, LOG_FILE_PARAM_MSG,
&logFile, false, ""));
try {
cmd_options.Parse(argc, argv);
} catch (const CmdParserException& e) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << e.what();
} catch (const std::exception& e) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << e.what();
} catch (...) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << "Failed to parse cmd arguments";
}
initLibrary(logFile.empty() ? LIB_LOGSTDERR:LIB_LOGFILE, logFile.c_str());
LOG(LIB_INFO) << "Program arguments are processed";
ToLower(distType);
try {
if (knnQueryQty <= 0) LOG(LIB_FATAL) << "Please, specify knnQueryQty > 0";
if (knn <= 0) LOG(LIB_FATAL) << "Please, specify knn > 0";
if (distType == DIST_TYPE_FLOAT) {
sampleDist<float>(spaceType,
inFile, pivotFile, maxNumPivots, outFilePrefix,
knn,
maxNumData,
knnQueryQty);
} else if (distType == DIST_TYPE_DOUBLE) {
sampleDist<double>(spaceType,
inFile, pivotFile, maxNumPivots, outFilePrefix,
knn,
maxNumData,
knnQueryQty);
} else {
LOG(LIB_FATAL) << "Unsupported distance type: '" << distType << "'";
}
} catch (const exception& e) {
LOG(LIB_FATAL) << "Exception: " << e.what();
}
return 0;
}
<commit_msg>changing names of some output file in sampling app<commit_after>/**
* Non-metric Space Library
*
* Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
* With contributions from Lawrence Cayton (http://lcayton.com/) and others.
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2016
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <string>
#include <fstream>
#include "knnquery.h"
#include "knnqueue.h"
#include "space.h"
#include "space_sparse_jaccard.h"
#include "space_sparse_vector_inter.h"
#include "params.h"
#include "projection.h"
#include "spacefactory.h"
#include "init.h"
#include "cmd_options.h"
#include "params_def.h"
using namespace similarity;
using namespace std;
template <class dist_t>
void sampleDist(string spaceType,
string inFile, string pivotFile, unsigned maxNumPivots, string outFilePrefix,
unsigned knn,
unsigned maxNumData,
unsigned knnQueryQty) {
ToLower(spaceType);
vector<string> spaceDesc;
const string descStr = spaceType;
ParseSpaceArg(descStr, spaceType, spaceDesc);
unique_ptr<AnyParams> spaceParams =
unique_ptr<AnyParams>(new AnyParams(spaceDesc));
unique_ptr<Space<dist_t>> space(SpaceFactoryRegistry<dist_t>::Instance().CreateSpace(spaceType, *spaceParams));
SpaceSparseJaccard<dist_t>* pJaccardSpace = dynamic_cast<SpaceSparseJaccard<dist_t>*>(space.get());
SpaceSparseVectorInter<dist_t>* pInterSpace = dynamic_cast<SpaceSparseVectorInter<dist_t>*>(space.get());
if (pJaccardSpace)
LOG(LIB_INFO) << "Sparse Jaccard space detected!";
if (pInterSpace)
LOG(LIB_INFO) << "Special sparse vector space detected!";
if (NULL == space.get()) {
LOG(LIB_FATAL) << "Cannot create the space: '" << spaceType
<< "' (desc: '" << descStr << "')";
} else {
LOG(LIB_INFO) << "Created space: " << spaceType;
}
ObjectVector data;
ObjectVector pivots;
LOG(LIB_INFO) << "maxNumData=" << maxNumData;
{
vector<string> tmp;
unique_ptr<DataFileInputState> inpState(space->ReadDataset(data, tmp, inFile, maxNumData));
space->UpdateParamsFromFile(*inpState);
}
if (!pivotFile.empty()) {
vector<string> tmp;
unique_ptr<DataFileInputState> inpState(space->ReadDataset(pivots, tmp, pivotFile, maxNumPivots));
space->UpdateParamsFromFile(*inpState);
LOG(LIB_INFO) << "Read " << pivots.size() << " pivots";
}
size_t N = data.size();
vector<char> isQuery(N);
string outFilePiv = outFilePrefix + "_pivots.tsv";
ofstream outPiv(outFilePiv);
LOG(LIB_INFO) << "knnQueryQty=" << knnQueryQty;
if (knnQueryQty >= N/2) {
LOG(LIB_FATAL) << "knnQueryQty is too large: should not exceed the number of data points / 2";
}
ObjectVector queries;
for (size_t i = 0; i < knnQueryQty; ++i) {
IdType iSel=0;
do {
iSel = RandomInt() % N;
// Should terminate quickly, b/c the probability of finding a data point, which is not previously selected, is >= 1/2
} while (isQuery[iSel]);
isQuery[iSel]=1;
queries.push_back(data[iSel]);
}
size_t pivotQty = pivots.size();
vector<vector<dist_t>> outNNDistMatrix(knn);
vector<vector<unsigned>> outNNOverlapMatrix(knn);
vector<vector<dist_t>> outPivDistMatrix(pivotQty);
vector<vector<unsigned>> outPivOverlapQtyMatrix(pivotQty);
vector<vector<float>> outPivOverlapFracMatrix(pivotQty);
for (size_t qid = 0; qid < knnQueryQty; ++qid) {
LOG(LIB_INFO) << "query index : " << qid << " id: " << queries[qid]->id();
KNNQuery<dist_t> query(*space, queries[qid], knn);
vector<dist_t> pivDist(pivotQty);
for (size_t pid = 0; pid < pivotQty; ++pid) {
pivDist[pid]=space->IndexTimeDistance(pivots[pid], queries[qid]); // Pivot plays the role of an object => it's a left argument
}
sort(pivDist.begin(),pivDist.end());
for (size_t pid = 0; pid < pivotQty; ++pid) {
outPivDistMatrix[pid].push_back(pivDist[pid]);
}
if (pJaccardSpace || pInterSpace) {
vector<unsigned> pivOverlap(pivotQty);
for (size_t pid = 0; pid < pivotQty; ++pid) {
pivOverlap[pid]=pJaccardSpace ?
pJaccardSpace->ComputeOverlap(pivots[pid], queries[qid]):
pInterSpace->ComputeOverlap(pivots[pid], queries[qid]);
}
sort(pivOverlap.begin(),pivOverlap.end(), [](unsigned qty1, unsigned qty2)->bool{ return qty1 > qty2;});
float elemQty = pJaccardSpace ? pJaccardSpace->GetElemQty(queries[qid]) :
pInterSpace->GetElemQty(queries[qid]);
float elemQtyInv = 1.0f/elemQty;
for (size_t pid = 0; pid < pivotQty; ++pid) {
outPivOverlapQtyMatrix[pid].push_back(pivOverlap[pid]);
outPivOverlapFracMatrix[pid].push_back(pivOverlap[pid]*elemQtyInv);
}
}
// Brute force search
for (size_t k = 0; k < N; ++k)
if (!isQuery[k]) {
query.CheckAndAddToResult(data[k]);
}
unique_ptr<KNNQueue<dist_t>> knnQ(query.Result()->Clone());
vector<pair<dist_t,unsigned>> dists_overlaps;
dists_overlaps.reserve(knn);
// Extracting results
while (!knnQ->Empty()) {
unsigned overlap = 0;
if (pJaccardSpace || pInterSpace) {
overlap = pJaccardSpace ?
pJaccardSpace->ComputeOverlap(knnQ->TopObject(), queries[qid]):
pInterSpace->ComputeOverlap(knnQ->TopObject(), queries[qid]);
}
dists_overlaps.insert(dists_overlaps.begin(),make_pair(knnQ->TopDistance(),overlap));
knnQ->Pop();
}
for (size_t k = 0; k < min<size_t>(dists_overlaps.size(), knn); ++k) {
outNNDistMatrix[k].push_back(dists_overlaps[k].first);
outNNOverlapMatrix[k].push_back(dists_overlaps[k].second);
}
}
string outFileDistNN = outFilePrefix + "_dist_NN.tsv";
ofstream outDistNN(outFileDistNN);
for (size_t i = 0; i < outNNDistMatrix.size(); ++i) {
const vector<dist_t>& dists2 = outNNDistMatrix[i];
if (!dists2.empty()) outDistNN << dists2[0];
for (size_t k = 1; k < dists2.size(); ++k) {
outDistNN << "\t" << dists2[k];
}
outDistNN << endl;
}
outDistNN.close();
if (pJaccardSpace || pInterSpace) {
string outFileOverlapNN = outFilePrefix + "_overlap_qty_NN.tsv";
ofstream outOverlapNN(outFileOverlapNN);
for (size_t i = 0; i < outNNOverlapMatrix.size(); ++i) {
const vector<unsigned>& overlaps = outNNOverlapMatrix[i];
if (!overlaps.empty()) outOverlapNN << overlaps[0];
for (size_t k = 1; k < overlaps.size(); ++k) {
outOverlapNN << "\t" << overlaps[k];
}
outOverlapNN << endl;
}
outOverlapNN.close();
}
for (size_t i = 0; i < pivotQty; ++i) {
const vector<dist_t>& dists3= outPivDistMatrix[i];
if (!dists3.empty()) outPiv << dists3[0];
for (size_t k = 1; k < dists3.size(); ++k) {
outPiv << "\t" << dists3[k];
}
outPiv << endl;
}
outPiv.close();
if (pJaccardSpace || pInterSpace) {
string outFileOverlapQty = outFilePrefix + "_overlap_qty_pivots.tsv";
string outFileOverlapFrac = outFilePrefix + "_overlap_frac_pivots.tsv";
ofstream outOverlapQty(outFileOverlapQty);
ofstream outOverlapFrac(outFileOverlapFrac);
for (size_t i = 0; i < pivotQty; ++i) {
const vector<unsigned>& qtys = outPivOverlapQtyMatrix[i];
if (!qtys.empty()) outOverlapQty << qtys[0];
for (size_t k = 1; k < qtys.size(); ++k) {
outOverlapQty << "\t" << qtys[k];
}
outOverlapQty << endl;
const vector<float>& fracs = outPivOverlapFracMatrix[i];
if (!fracs.empty()) outOverlapFrac << fracs[0];
for (size_t k = 1; k < fracs.size(); ++k) {
outOverlapFrac << "\t" << fracs[k];
}
outOverlapFrac << endl;
}
outOverlapQty.close();
outOverlapFrac.close();
}
}
int main(int argc, char *argv[]) {
string spaceType, distType, projSpaceType;
string inFile, pivotFile, outFilePrefix;
string projType;
string logFile;
unsigned maxNumData = 0;
unsigned maxNumPivots = 0;
unsigned knnQueryQty = 0;
unsigned knn = 0;
CmdOptions cmd_options;
cmd_options.Add(new CmdParam(SPACE_TYPE_PARAM_OPT, SPACE_TYPE_PARAM_MSG,
&spaceType, true));
cmd_options.Add(new CmdParam(DIST_TYPE_PARAM_OPT, DIST_TYPE_PARAM_MSG,
&distType, false, std::string(DIST_TYPE_FLOAT)));
cmd_options.Add(new CmdParam("inFile,i", "input data file",
&inFile, true));
cmd_options.Add(new CmdParam("outFilePrefix,o", "output file prefix",
&outFilePrefix, true));
cmd_options.Add(new CmdParam("pivotFile,p", "pivot file",
&pivotFile, false, ""));
cmd_options.Add(new CmdParam("maxNumPivot", "maximum number of pivots to use",
&maxNumPivots, false, 0));
cmd_options.Add(new CmdParam("knnQueryQty", "number of randomly selected queries",
&knnQueryQty, false, 0));
cmd_options.Add(new CmdParam(KNN_PARAM_OPT, "use this number of nearest neighbors",
&knn, 0));
cmd_options.Add(new CmdParam(MAX_NUM_DATA_PARAM_OPT, MAX_NUM_DATA_PARAM_MSG,
&maxNumData, false, 0));
cmd_options.Add(new CmdParam(LOG_FILE_PARAM_OPT, LOG_FILE_PARAM_MSG,
&logFile, false, ""));
try {
cmd_options.Parse(argc, argv);
} catch (const CmdParserException& e) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << e.what();
} catch (const std::exception& e) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << e.what();
} catch (...) {
cmd_options.ToString();
std::cout.flush();
LOG(LIB_FATAL) << "Failed to parse cmd arguments";
}
initLibrary(logFile.empty() ? LIB_LOGSTDERR:LIB_LOGFILE, logFile.c_str());
LOG(LIB_INFO) << "Program arguments are processed";
ToLower(distType);
try {
if (knnQueryQty <= 0) LOG(LIB_FATAL) << "Please, specify knnQueryQty > 0";
if (knn <= 0) LOG(LIB_FATAL) << "Please, specify knn > 0";
if (distType == DIST_TYPE_FLOAT) {
sampleDist<float>(spaceType,
inFile, pivotFile, maxNumPivots, outFilePrefix,
knn,
maxNumData,
knnQueryQty);
} else if (distType == DIST_TYPE_DOUBLE) {
sampleDist<double>(spaceType,
inFile, pivotFile, maxNumPivots, outFilePrefix,
knn,
maxNumData,
knnQueryQty);
} else {
LOG(LIB_FATAL) << "Unsupported distance type: '" << distType << "'";
}
} catch (const exception& e) {
LOG(LIB_FATAL) << "Exception: " << e.what();
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* opencog/learning/moses/moses/local_moses.cc
*
* Copyright (C) 2002-2008 Novamente LLC
* All Rights Reserved
*
* Written by Moshe Looks
*
* 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 "local_moses.h"
namespace opencog {
namespace moses {
using namespace combo;
/**
* expand_deme -- Run one deme-creation and optimization step.
*
* A single step consists of representation-building, to create
* a deme, followed by optimization, (according to the specified
* optimizer and scoring function), and finally, a merger of
* the unique (and possibly non-dominated) trees back into the
* metapopulation, for potential use as exemplars for future demes.
*
* @param max_evals the max evals
*
* @return return true if expansion has succeeded, false otherwise
*
*/
bool expand_deme(metapopulation& mp,
int max_evals, time_t max_time, moses_statistics& stats)
{
if (mp.empty())
return true;
// Attempt to create a non-empty representation, by looping
// over exemplars until we find one that expands.
// XXX When would one never expand? Wouldn't that be a bug?
while (1) {
pbscored_combo_tree_ptr_set_cit exemplar = mp.select_exemplar();
// Should have found something by now.
if (exemplar == mp.end()) {
logger().warn(
"WARNING: All exemplars in the metapopulation have "
"been visited, but it was impossible to build a "
"representation for any of them. Perhaps the reduct "
"effort for knob building is too high.");
return true;
}
// if create_deme returned true, we are good to go.
if (mp._dex.create_demes(get_tree(*exemplar))) break;
OC_ASSERT(false, "Exemplar failed to expand!\n");
}
vector<unsigned> actl_evals = mp._dex.optimize_demes(max_evals, max_time);
stats.n_evals += boost::accumulate(actl_evals, 0U);
stats.n_expansions++;
// construct deme IDs
vector<demeID_t> demeIDs;
unsigned ds = mp._dex._demes.size();
for (unsigned i = 0; i < ds; i++)
if (ds == 1)
demeIDs.emplace_back(stats.n_expansions);
else
demeIDs.emplace_back(stats.n_expansions, i);
bool done = mp.merge_demes(mp._dex._demes, mp._dex._reps, actl_evals, demeIDs);
if (logger().isInfoEnabled()) {
logger().info() << "Expansion " << stats.n_expansions << " done";
logger().info() << "Total number of evaluations so far: " << stats.n_evals;
mp.log_best_candidates();
}
mp._dex.free_demes();
// Might be empty, if the eval fails and throws an exception
return done || mp.empty();
}
/**
* The main function of MOSES, non-distributed version.
*
* This is termed "local" because it runs only on the local CPU node.
* That is, it does not assume nor make use of any distrirubted
* processing capabilities. It does assume that the local environment
* might possibly be an SMP system (i.e. generic CPU's with more-or-less
* tightly coupled memory).
*
* @param mp the metapopulation
* @param pa the parameters to run moses
*/
void local_moses(metapopulation& mp,
const moses_parameters& pa,
moses_statistics& stats)
{
logger().info("MOSES starts, max_evals=%d max_gens=%d max_time=%d",
pa.max_evals, pa.max_gens, pa.max_time);
optim_stats *os = dynamic_cast<optim_stats *> (&mp._dex._optimize);
// Print legend for the columns of the stats.
print_stats_header(os, mp.params.diversity.pressure > 0.0);
struct timeval start;
gettimeofday(&start, NULL);
stats.elapsed_secs = 0.0;
while ((stats.n_evals < pa.max_evals)
&& (pa.max_gens != stats.n_expansions)
&& (mp.best_score() < pa.max_score)
&& (stats.elapsed_secs < pa.max_time))
{
// Run a generation
bool done = expand_deme(mp,
pa.max_evals - stats.n_evals,
pa.max_time - stats.elapsed_secs,
stats);
struct timeval stop, elapsed;
gettimeofday(&stop, NULL);
timersub(&stop, &start, &elapsed);
start = stop;
stats.elapsed_secs += elapsed.tv_sec + 1.0e-6*elapsed.tv_usec;
// Print stats in a way that makes them easy to graph.
// (columns of tab-seprated numbers)
if (logger().isInfoEnabled()) {
stringstream ss;
ss << "Stats: " << stats.n_expansions
<< "\t" << stats.n_evals // number of evaluations so far
<< "\t" << ((int) stats.elapsed_secs) // wall-clock time.
<< "\t" << mp.size() // size of the metapopulation
<< "\t" << mp.best_score() // score of the highest-ranked exemplar.
<< "\t" << get_complexity(mp.best_composite_score()); // as above.
if (os) {
ss << "\t" << os->field_set_size // number of bits in the knobs
<< "\t" << os->nsteps // number of iterations of optimizer
<< "\t" << os->over_budget; // exceeded max_evals
}
if (mp.params.diversity.pressure > 0.0) {
// diversity stats over all metapopulation
auto ds = mp.gather_diversity_stats(-1);
ss << "\t" << ds.count // number of pairs of candidates
<< "\t" << ds.mean // average distance
<< "\t" << ds.std // average dst dev
<< "\t" << ds.min // min distance
<< "\t" << ds.max; // max distance
// diversity stats over all best n candidates of the metapopulation
// TODO use the option of the output
auto best_ds = mp.gather_diversity_stats(pa.max_cnd_output);
ss << "\t" << best_ds.count // number of pairs of candidates
<< "\t" << best_ds.mean // average distance
<< "\t" << best_ds.std // average dst dev
<< "\t" << best_ds.min // min distance
<< "\t" << best_ds.max; // max distance
}
logger().info(ss.str());
}
// I find this particularly useful for studying diversity but
// it could be relaxed and printed whatever
if (logger().isDebugEnabled() and mp.params.diversity.pressure > 0.0) {
stringstream ss;
ss << pa.max_cnd_output << " best candidates of the metapopulation (with scores and visited status):" << std::endl;
mp.ostream(ss, pa.max_cnd_output, true, true, true, true);
logger().debug(ss.str());
}
// In iterative hillclimbing, it is possible (but not likely)
// that the metapop gets empty and expand returns false.
// Alternately, the candidate callback may urge a premature
// termination.
if (done) break;
}
logger().info("MOSES ends");
}
} // ~namespace moses
} // ~namespace opencog
<commit_msg>add debug print to the assert<commit_after>/*
* opencog/learning/moses/moses/local_moses.cc
*
* Copyright (C) 2002-2008 Novamente LLC
* All Rights Reserved
*
* Written by Moshe Looks
*
* 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 "local_moses.h"
namespace opencog {
namespace moses {
using namespace combo;
/**
* expand_deme -- Run one deme-creation and optimization step.
*
* A single step consists of representation-building, to create
* a deme, followed by optimization, (according to the specified
* optimizer and scoring function), and finally, a merger of
* the unique (and possibly non-dominated) trees back into the
* metapopulation, for potential use as exemplars for future demes.
*
* @param max_evals the max evals
*
* @return return true if expansion has succeeded, false otherwise
*
*/
bool expand_deme(metapopulation& mp,
int max_evals, time_t max_time, moses_statistics& stats)
{
if (mp.empty())
return true;
// Attempt to create a non-empty representation, by looping
// over exemplars until we find one that expands.
// XXX When would one never expand? Wouldn't that be a bug?
while (1) {
pbscored_combo_tree_ptr_set_cit exemplar = mp.select_exemplar();
// Should have found something by now.
if (exemplar == mp.end()) {
logger().warn(
"WARNING: All exemplars in the metapopulation have "
"been visited, but it was impossible to build a "
"representation for any of them. Perhaps the reduct "
"effort for knob building is too high.");
return true;
}
// if create_deme returned true, we are good to go.
if (mp._dex.create_demes(get_tree(*exemplar))) break;
logger().error() << "Exemplar: " << get_tree(*exemplar);
OC_ASSERT(false, "Exemplar failed to expand!\n");
}
vector<unsigned> actl_evals = mp._dex.optimize_demes(max_evals, max_time);
stats.n_evals += boost::accumulate(actl_evals, 0U);
stats.n_expansions++;
// construct deme IDs
vector<demeID_t> demeIDs;
unsigned ds = mp._dex._demes.size();
for (unsigned i = 0; i < ds; i++)
if (ds == 1)
demeIDs.emplace_back(stats.n_expansions);
else
demeIDs.emplace_back(stats.n_expansions, i);
bool done = mp.merge_demes(mp._dex._demes, mp._dex._reps, actl_evals, demeIDs);
if (logger().isInfoEnabled()) {
logger().info() << "Expansion " << stats.n_expansions << " done";
logger().info() << "Total number of evaluations so far: " << stats.n_evals;
mp.log_best_candidates();
}
mp._dex.free_demes();
// Might be empty, if the eval fails and throws an exception
return done || mp.empty();
}
/**
* The main function of MOSES, non-distributed version.
*
* This is termed "local" because it runs only on the local CPU node.
* That is, it does not assume nor make use of any distrirubted
* processing capabilities. It does assume that the local environment
* might possibly be an SMP system (i.e. generic CPU's with more-or-less
* tightly coupled memory).
*
* @param mp the metapopulation
* @param pa the parameters to run moses
*/
void local_moses(metapopulation& mp,
const moses_parameters& pa,
moses_statistics& stats)
{
logger().info("MOSES starts, max_evals=%d max_gens=%d max_time=%d",
pa.max_evals, pa.max_gens, pa.max_time);
optim_stats *os = dynamic_cast<optim_stats *> (&mp._dex._optimize);
// Print legend for the columns of the stats.
print_stats_header(os, mp.params.diversity.pressure > 0.0);
struct timeval start;
gettimeofday(&start, NULL);
stats.elapsed_secs = 0.0;
while ((stats.n_evals < pa.max_evals)
&& (pa.max_gens != stats.n_expansions)
&& (mp.best_score() < pa.max_score)
&& (stats.elapsed_secs < pa.max_time))
{
// Run a generation
bool done = expand_deme(mp,
pa.max_evals - stats.n_evals,
pa.max_time - stats.elapsed_secs,
stats);
struct timeval stop, elapsed;
gettimeofday(&stop, NULL);
timersub(&stop, &start, &elapsed);
start = stop;
stats.elapsed_secs += elapsed.tv_sec + 1.0e-6*elapsed.tv_usec;
// Print stats in a way that makes them easy to graph.
// (columns of tab-seprated numbers)
if (logger().isInfoEnabled()) {
stringstream ss;
ss << "Stats: " << stats.n_expansions
<< "\t" << stats.n_evals // number of evaluations so far
<< "\t" << ((int) stats.elapsed_secs) // wall-clock time.
<< "\t" << mp.size() // size of the metapopulation
<< "\t" << mp.best_score() // score of the highest-ranked exemplar.
<< "\t" << get_complexity(mp.best_composite_score()); // as above.
if (os) {
ss << "\t" << os->field_set_size // number of bits in the knobs
<< "\t" << os->nsteps // number of iterations of optimizer
<< "\t" << os->over_budget; // exceeded max_evals
}
if (mp.params.diversity.pressure > 0.0) {
// diversity stats over all metapopulation
auto ds = mp.gather_diversity_stats(-1);
ss << "\t" << ds.count // number of pairs of candidates
<< "\t" << ds.mean // average distance
<< "\t" << ds.std // average dst dev
<< "\t" << ds.min // min distance
<< "\t" << ds.max; // max distance
// diversity stats over all best n candidates of the metapopulation
// TODO use the option of the output
auto best_ds = mp.gather_diversity_stats(pa.max_cnd_output);
ss << "\t" << best_ds.count // number of pairs of candidates
<< "\t" << best_ds.mean // average distance
<< "\t" << best_ds.std // average dst dev
<< "\t" << best_ds.min // min distance
<< "\t" << best_ds.max; // max distance
}
logger().info(ss.str());
}
// I find this particularly useful for studying diversity but
// it could be relaxed and printed whatever
if (logger().isDebugEnabled() and mp.params.diversity.pressure > 0.0) {
stringstream ss;
ss << pa.max_cnd_output << " best candidates of the metapopulation (with scores and visited status):" << std::endl;
mp.ostream(ss, pa.max_cnd_output, true, true, true, true);
logger().debug(ss.str());
}
// In iterative hillclimbing, it is possible (but not likely)
// that the metapop gets empty and expand returns false.
// Alternately, the candidate callback may urge a premature
// termination.
if (done) break;
}
logger().info("MOSES ends");
}
} // ~namespace moses
} // ~namespace opencog
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MApplication>
#include <MTheme>
#include <QPaintEngine>
#include <QPainter>
#include <QGraphicsPixmapItem>
#include "ut_plaindesktopbackgroundextension.h"
#include "plaindesktopbackgroundextension.h"
#include "plaindesktopbackgroundstyle.h"
#include "plaindesktopbackgroundpixmap.h"
#include "windowinfo_stub.h"
// PlainDesktopBackgroundPixmap stubs
QPixmap *PlainDesktopBackgroundPixmapConstructorPixmap;
QPixmap *PlainDesktopBackgroundPixmapConstructorBlurredPixmap;
QString PlainDesktopBackgroundPixmapConstructorName;
QString PlainDesktopBackgroundPixmapConstructorDefaultName;
int PlainDesktopBackgroundPixmapConstructorBlurRadius;
QString PlainDesktopBackgroundPixmapConstructorPixmapName;
PlainDesktopBackgroundPixmap::PlainDesktopBackgroundPixmap(const QString &name, const QString &defaultName, int blurRadius)
{
PlainDesktopBackgroundPixmapConstructorName = name;
PlainDesktopBackgroundPixmapConstructorDefaultName = defaultName;
PlainDesktopBackgroundPixmapConstructorBlurRadius = blurRadius;
pixmapFromFile_ = QSharedPointer<QPixmap>(PlainDesktopBackgroundPixmapConstructorPixmap);
blurredPixmap_ = QSharedPointer<QPixmap>(PlainDesktopBackgroundPixmapConstructorBlurredPixmap);
pixmapName_ = PlainDesktopBackgroundPixmapConstructorPixmapName;
}
PlainDesktopBackgroundPixmap::~PlainDesktopBackgroundPixmap()
{
PlainDesktopBackgroundPixmapConstructorPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = NULL;
}
QPixmap *PlainDesktopBackgroundPixmap::createBlurredPixmap(const QPixmap &, int)
{
return NULL;
}
const QPixmap *PlainDesktopBackgroundPixmap::pixmap() const
{
return pixmapFromFile_.data();
}
const QPixmap *PlainDesktopBackgroundPixmap::blurredPixmap() const
{
return blurredPixmap_.data();
}
QString PlainDesktopBackgroundPixmap::pixmapName() const
{
return pixmapName_;
}
// Mock Paint Engine
class MockPaintEngine : public QPaintEngine
{
bool begin(QPaintDevice *pdev) {
Q_UNUSED(pdev);
return true;
}
bool end() {
return true;
}
void updateState(const QPaintEngineState &state) {
Q_UNUSED(state);
}
void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
Type type() const {
return QPaintEngine::User;
}
};
void MockPaintEngine::drawPixmap(const QRectF &, const QPixmap &, const QRectF &)
{
}
// Mock Paint Device
class MockPaintDevice : public QPaintDevice
{
public:
MockPaintDevice() : engine(new MockPaintEngine) {}
~MockPaintDevice();
QPaintEngine *paintEngine() const {
return engine;
}
int metric(PaintDeviceMetric metric) const;
private:
QPaintEngine *engine;
};
MockPaintDevice::~MockPaintDevice()
{
delete engine;
}
int MockPaintDevice::metric(PaintDeviceMetric metric) const
{
switch (metric) {
case QPaintDevice::PdmWidth:
return 1000;
case QPaintDevice::PdmHeight:
return 1000;
case QPaintDevice::PdmDpiY:
case QPaintDevice::PdmDpiX:
return 300;
default:
return 0;
}
return 0;
}
// QPixmap stubs
QString QPixmapLoadFileName;
bool QPixmapLoadReturnValue;
bool QPixmap::load(const QString & fileName, const char *, Qt::ImageConversionFlags)
{
QPixmapLoadFileName = fileName;
return QPixmapLoadReturnValue;
}
// QTimeLine stubs
int QTimeLineDuration;
int QTimeLineUpdateInterval;
QTimeLine::Direction QTimeLineDirection;
QTimeLine::State QTimeLineState;
void QTimeLine::setDuration(int duration)
{
QTimeLineDuration = duration;
}
void QTimeLine::setUpdateInterval(int interval)
{
QTimeLineUpdateInterval = interval;
}
QTimeLine::Direction QTimeLine::direction() const
{
return QTimeLineDirection;
}
void QTimeLine::toggleDirection()
{
QTimeLineDirection = QTimeLineDirection == QTimeLine::Forward ? QTimeLine::Backward : QTimeLine::Forward;
}
void QTimeLine::resume()
{
QTimeLineState = QTimeLine::Running;
}
QTimeLine::State QTimeLine::state() const
{
return QTimeLineState;
}
// MTheme stubs
QString MThemePixmapId;
const QPixmap *MThemePixmapDefaultValue;
const QPixmap *MThemePixmapReturnValue;
const QPixmap *MTheme::pixmap(const QString &id, const QSize &)
{
MThemePixmapId = id;
return MThemePixmapReturnValue;
}
void MTheme::releasePixmap(const QPixmap *)
{
}
// QPainter stubs
qreal QPainterOpacity;
QRectF QPainterDrawPixmapTargetRect;
const QPixmap *QPainterDrawPixmapPixmap;
QRectF QPainterDrawPixmapSourceRect;
void QPainter::setOpacity(qreal opacity)
{
QPainterOpacity = opacity;
}
void QPainter::drawPixmap(const QRectF &targetRect, const QPixmap &pixmap, const QRectF &sourceRect)
{
QPainterDrawPixmapSourceRect = sourceRect;
QPainterDrawPixmapPixmap = &pixmap;
QPainterDrawPixmapTargetRect = QPainterDrawPixmapTargetRect.united(targetRect);
}
// MGConfItem stubs
QMap<QString, QVariant> MGConfItemValueForKey;
QVariant MGConfItem::value() const
{
return MGConfItemValueForKey.value(key());
}
void MGConfItem::set(const QVariant &val)
{
MGConfItemValueForKey.insert(key(), val);
}
// Helper for getting the style
PlainDesktopBackgroundStyle *modifiablePlainDesktopBackgroundStyle(M::Orientation orientation)
{
return const_cast<PlainDesktopBackgroundStyle *>(static_cast<const PlainDesktopBackgroundStyle *> (MTheme::style("PlainDesktopBackgroundStyle", "", "", "", orientation, NULL)));
}
void Ut_PlainDesktopBackgroundExtension::initTestCase()
{
static int argc = 1;
static char *app_name[1] = { (char *) "./ut_plaindesktopbackgroundextension" };
app = new MApplication(argc, app_name);
paintDevice = new MockPaintDevice;
painter = new QPainter(paintDevice);
MThemePixmapDefaultValue = new QPixmap;
}
void Ut_PlainDesktopBackgroundExtension::cleanupTestCase()
{
delete painter;
delete paintDevice;
delete app;
delete MThemePixmapDefaultValue;
}
void Ut_PlainDesktopBackgroundExtension::init()
{
updateCalled = false;
currentOrientationAngle = M::Angle0;
PlainDesktopBackgroundPixmapConstructorPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorPixmapName.clear();
MThemePixmapReturnValue = MThemePixmapDefaultValue;
MGConfItemValueForKey.clear();
QTimeLineDirection = QTimeLine::Backward;
QTimeLineState = QTimeLine::NotRunning;
QPainterDrawPixmapTargetRect = QRectF();
extension = new PlainDesktopBackgroundExtension;
connect(this, SIGNAL(setBlurFactor(qreal)), extension, SLOT(setBlurFactor(qreal)));
connect(this, SIGNAL(updateLandscapePixmap()), extension, SLOT(updateLandscapePixmap()));
connect(this, SIGNAL(updatePortraitPixmap()), extension, SLOT(updatePortraitPixmap()));
connect(this, SIGNAL(setBlurTimeLineDirection(const QList<WindowInfo> &)), extension, SLOT(setBlurTimeLineDirection(const QList<WindowInfo> &)));
}
void Ut_PlainDesktopBackgroundExtension::cleanup()
{
delete extension;
}
void Ut_PlainDesktopBackgroundExtension::testInitialize()
{
PlainDesktopBackgroundStyle *landscapeStyle = modifiablePlainDesktopBackgroundStyle(M::Landscape);
landscapeStyle->setBlurDuration(3);
landscapeStyle->setBlurUpdateInterval(4);
QCOMPARE(extension->initialize(""), true);
QCOMPARE(QTimeLineDuration, landscapeStyle->blurDuration());
QCOMPARE(QTimeLineUpdateInterval, landscapeStyle->blurUpdateInterval());
}
void Ut_PlainDesktopBackgroundExtension::testWidget()
{
QCOMPARE(extension->widget(), (MWidget *)NULL);
}
void Ut_PlainDesktopBackgroundExtension::testDrawBackground()
{
QCOMPARE(extension->initialize(""), true);
extension->setDesktopInterface(*this);
QRectF br(10, 10, 50, 30);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
const QPixmap *landscapePixmap = PlainDesktopBackgroundPixmapConstructorPixmap;
emit updateLandscapePixmap();
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
const QPixmap *portraitPixmap = PlainDesktopBackgroundPixmapConstructorPixmap;
emit updatePortraitPixmap();
// Verify that the correct pixmaps are drawn in each orientation
currentOrientationAngle = M::Angle0;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, landscapePixmap);
currentOrientationAngle = M::Angle90;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, portraitPixmap);
currentOrientationAngle = M::Angle180;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, landscapePixmap);
currentOrientationAngle = M::Angle270;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, portraitPixmap);
// Check that the extension doesn't draw outside the bounding rectangle
QVERIFY(QPainterDrawPixmapTargetRect.isEmpty() || QPainterDrawPixmapTargetRect == br || br.contains(QPainterDrawPixmapTargetRect));
}
void Ut_PlainDesktopBackgroundExtension::testUpdatePixmaps()
{
// Set up the style for default values
PlainDesktopBackgroundStyle *landscapeStyle = modifiablePlainDesktopBackgroundStyle(M::Landscape);
PlainDesktopBackgroundStyle *portraitStyle = modifiablePlainDesktopBackgroundStyle(M::Portrait);
landscapeStyle->setBlurRadius(27);
landscapeStyle->setDefaultBackgroundImage("landscapeDefault");
portraitStyle->setDefaultBackgroundImage("portraitDefault");
// Set up GConf values
QString landscapeName("landscape");
QString portraitName("landscape");
MGConfItemValueForKey.insert("/desktop/meego/background/landscape", landscapeName);
MGConfItemValueForKey.insert("/desktop/meego/background/portrait", portraitName);
QCOMPARE(extension->initialize(""), true);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
QCOMPARE(PlainDesktopBackgroundPixmapConstructorName, landscapeName);
QCOMPARE(PlainDesktopBackgroundPixmapConstructorDefaultName, landscapeStyle->defaultBackgroundImage());
QCOMPARE(PlainDesktopBackgroundPixmapConstructorBlurRadius, landscapeStyle->blurRadius());
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updatePortraitPixmap();
QCOMPARE(PlainDesktopBackgroundPixmapConstructorName, portraitName);
QCOMPARE(PlainDesktopBackgroundPixmapConstructorDefaultName, portraitStyle->defaultBackgroundImage());
QCOMPARE(PlainDesktopBackgroundPixmapConstructorBlurRadius, landscapeStyle->blurRadius());
MTheme::releaseStyle(landscapeStyle);
MTheme::releaseStyle(portraitStyle);
}
void Ut_PlainDesktopBackgroundExtension::testUpdatePixmapsFails()
{
// Set up GConf values
QCOMPARE(extension->initialize(""), true);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmapName = "testPixmap";
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Set up the pixmaps again so that they fail
PlainDesktopBackgroundPixmapConstructorPixmapName = "unexpectedPixmap";
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Check that the GConf key was set to the previous value
QCOMPARE(MGConfItemValueForKey.value("/desktop/meego/background/landscape"), QVariant("testPixmap"));
// Set up the pixmaps again using an empty name (which is valid and should use the default)
MGConfItemValueForKey.insert("/desktop/meego/background/landscape", QString());
PlainDesktopBackgroundPixmapConstructorPixmapName = QString();
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Check that the GConf key was not set to the previous value
QCOMPARE(MGConfItemValueForKey.value("/desktop/meego/background/landscape"), QVariant(QString()));
}
void Ut_PlainDesktopBackgroundExtension::testSetBlurFactor()
{
QCOMPARE(extension->initialize(""), true);
extension->setDesktopInterface(*this);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// This should call MDesktopInterface::update() and painting (called by update()) should use the blur factor
qreal blurFactor = 0.5;
emit setBlurFactor(blurFactor);
QVERIFY(updateCalled);
QCOMPARE(QPainterOpacity, blurFactor);
// Setting the same blur factor again should not result in updates
updateCalled = false;
emit setBlurFactor(blurFactor);
QVERIFY(!updateCalled);
}
void Ut_PlainDesktopBackgroundExtension::testSetBlurTimeLineDirection()
{
QList<WindowInfo> emptyWindowList;
QList<WindowInfo> fullWindowList;
QString title;
fullWindowList.append(WindowInfo(title, Window(), XWindowAttributes(), Pixmap()));
// Test that the timeline direction is set and the timeline is resumed
emit setBlurTimeLineDirection(fullWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Forward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline is resumed if it's not running even if the direction doesn't change
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(fullWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Forward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline direction is set when it changes and the timeline is resumed
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(emptyWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Backward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline is resumed if it's not running even if the direction doesn't change
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(emptyWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Backward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
}
void Ut_PlainDesktopBackgroundExtension::update()
{
updateCalled = true;
QRectF br(10, 10, 50, 30);
extension->drawBackground(painter, br);
}
M::OrientationAngle Ut_PlainDesktopBackgroundExtension::orientationAngle()
{
return currentOrientationAngle;
}
QTEST_APPLESS_MAIN(Ut_PlainDesktopBackgroundExtension)
<commit_msg>Changes: initialize a member variable in constructor<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MApplication>
#include <MTheme>
#include <QPaintEngine>
#include <QPainter>
#include <QGraphicsPixmapItem>
#include "ut_plaindesktopbackgroundextension.h"
#include "plaindesktopbackgroundextension.h"
#include "plaindesktopbackgroundstyle.h"
#include "plaindesktopbackgroundpixmap.h"
#include "windowinfo_stub.h"
// PlainDesktopBackgroundPixmap stubs
QPixmap *PlainDesktopBackgroundPixmapConstructorPixmap;
QPixmap *PlainDesktopBackgroundPixmapConstructorBlurredPixmap;
QString PlainDesktopBackgroundPixmapConstructorName;
QString PlainDesktopBackgroundPixmapConstructorDefaultName;
int PlainDesktopBackgroundPixmapConstructorBlurRadius;
QString PlainDesktopBackgroundPixmapConstructorPixmapName;
PlainDesktopBackgroundPixmap::PlainDesktopBackgroundPixmap(const QString &name, const QString &defaultName, int blurRadius) :
pixmapFromTheme_(NULL)
{
PlainDesktopBackgroundPixmapConstructorName = name;
PlainDesktopBackgroundPixmapConstructorDefaultName = defaultName;
PlainDesktopBackgroundPixmapConstructorBlurRadius = blurRadius;
pixmapFromFile_ = QSharedPointer<QPixmap>(PlainDesktopBackgroundPixmapConstructorPixmap);
blurredPixmap_ = QSharedPointer<QPixmap>(PlainDesktopBackgroundPixmapConstructorBlurredPixmap);
pixmapName_ = PlainDesktopBackgroundPixmapConstructorPixmapName;
}
PlainDesktopBackgroundPixmap::~PlainDesktopBackgroundPixmap()
{
PlainDesktopBackgroundPixmapConstructorPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = NULL;
}
QPixmap *PlainDesktopBackgroundPixmap::createBlurredPixmap(const QPixmap &, int)
{
return NULL;
}
const QPixmap *PlainDesktopBackgroundPixmap::pixmap() const
{
return pixmapFromFile_.data();
}
const QPixmap *PlainDesktopBackgroundPixmap::blurredPixmap() const
{
return blurredPixmap_.data();
}
QString PlainDesktopBackgroundPixmap::pixmapName() const
{
return pixmapName_;
}
// Mock Paint Engine
class MockPaintEngine : public QPaintEngine
{
bool begin(QPaintDevice *pdev) {
Q_UNUSED(pdev);
return true;
}
bool end() {
return true;
}
void updateState(const QPaintEngineState &state) {
Q_UNUSED(state);
}
void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
Type type() const {
return QPaintEngine::User;
}
};
void MockPaintEngine::drawPixmap(const QRectF &, const QPixmap &, const QRectF &)
{
}
// Mock Paint Device
class MockPaintDevice : public QPaintDevice
{
public:
MockPaintDevice() : engine(new MockPaintEngine) {}
~MockPaintDevice();
QPaintEngine *paintEngine() const {
return engine;
}
int metric(PaintDeviceMetric metric) const;
private:
QPaintEngine *engine;
};
MockPaintDevice::~MockPaintDevice()
{
delete engine;
}
int MockPaintDevice::metric(PaintDeviceMetric metric) const
{
switch (metric) {
case QPaintDevice::PdmWidth:
return 1000;
case QPaintDevice::PdmHeight:
return 1000;
case QPaintDevice::PdmDpiY:
case QPaintDevice::PdmDpiX:
return 300;
default:
return 0;
}
return 0;
}
// QPixmap stubs
QString QPixmapLoadFileName;
bool QPixmapLoadReturnValue;
bool QPixmap::load(const QString & fileName, const char *, Qt::ImageConversionFlags)
{
QPixmapLoadFileName = fileName;
return QPixmapLoadReturnValue;
}
// QTimeLine stubs
int QTimeLineDuration;
int QTimeLineUpdateInterval;
QTimeLine::Direction QTimeLineDirection;
QTimeLine::State QTimeLineState;
void QTimeLine::setDuration(int duration)
{
QTimeLineDuration = duration;
}
void QTimeLine::setUpdateInterval(int interval)
{
QTimeLineUpdateInterval = interval;
}
QTimeLine::Direction QTimeLine::direction() const
{
return QTimeLineDirection;
}
void QTimeLine::toggleDirection()
{
QTimeLineDirection = QTimeLineDirection == QTimeLine::Forward ? QTimeLine::Backward : QTimeLine::Forward;
}
void QTimeLine::resume()
{
QTimeLineState = QTimeLine::Running;
}
QTimeLine::State QTimeLine::state() const
{
return QTimeLineState;
}
// MTheme stubs
QString MThemePixmapId;
const QPixmap *MThemePixmapDefaultValue;
const QPixmap *MThemePixmapReturnValue;
const QPixmap *MTheme::pixmap(const QString &id, const QSize &)
{
MThemePixmapId = id;
return MThemePixmapReturnValue;
}
void MTheme::releasePixmap(const QPixmap *)
{
}
// QPainter stubs
qreal QPainterOpacity;
QRectF QPainterDrawPixmapTargetRect;
const QPixmap *QPainterDrawPixmapPixmap;
QRectF QPainterDrawPixmapSourceRect;
void QPainter::setOpacity(qreal opacity)
{
QPainterOpacity = opacity;
}
void QPainter::drawPixmap(const QRectF &targetRect, const QPixmap &pixmap, const QRectF &sourceRect)
{
QPainterDrawPixmapSourceRect = sourceRect;
QPainterDrawPixmapPixmap = &pixmap;
QPainterDrawPixmapTargetRect = QPainterDrawPixmapTargetRect.united(targetRect);
}
// MGConfItem stubs
QMap<QString, QVariant> MGConfItemValueForKey;
QVariant MGConfItem::value() const
{
return MGConfItemValueForKey.value(key());
}
void MGConfItem::set(const QVariant &val)
{
MGConfItemValueForKey.insert(key(), val);
}
// Helper for getting the style
PlainDesktopBackgroundStyle *modifiablePlainDesktopBackgroundStyle(M::Orientation orientation)
{
return const_cast<PlainDesktopBackgroundStyle *>(static_cast<const PlainDesktopBackgroundStyle *> (MTheme::style("PlainDesktopBackgroundStyle", "", "", "", orientation, NULL)));
}
void Ut_PlainDesktopBackgroundExtension::initTestCase()
{
static int argc = 1;
static char *app_name[1] = { (char *) "./ut_plaindesktopbackgroundextension" };
app = new MApplication(argc, app_name);
paintDevice = new MockPaintDevice;
painter = new QPainter(paintDevice);
MThemePixmapDefaultValue = new QPixmap;
}
void Ut_PlainDesktopBackgroundExtension::cleanupTestCase()
{
delete painter;
delete paintDevice;
delete app;
delete MThemePixmapDefaultValue;
}
void Ut_PlainDesktopBackgroundExtension::init()
{
updateCalled = false;
currentOrientationAngle = M::Angle0;
PlainDesktopBackgroundPixmapConstructorPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = NULL;
PlainDesktopBackgroundPixmapConstructorPixmapName.clear();
MThemePixmapReturnValue = MThemePixmapDefaultValue;
MGConfItemValueForKey.clear();
QTimeLineDirection = QTimeLine::Backward;
QTimeLineState = QTimeLine::NotRunning;
QPainterDrawPixmapTargetRect = QRectF();
extension = new PlainDesktopBackgroundExtension;
connect(this, SIGNAL(setBlurFactor(qreal)), extension, SLOT(setBlurFactor(qreal)));
connect(this, SIGNAL(updateLandscapePixmap()), extension, SLOT(updateLandscapePixmap()));
connect(this, SIGNAL(updatePortraitPixmap()), extension, SLOT(updatePortraitPixmap()));
connect(this, SIGNAL(setBlurTimeLineDirection(const QList<WindowInfo> &)), extension, SLOT(setBlurTimeLineDirection(const QList<WindowInfo> &)));
}
void Ut_PlainDesktopBackgroundExtension::cleanup()
{
delete extension;
}
void Ut_PlainDesktopBackgroundExtension::testInitialize()
{
PlainDesktopBackgroundStyle *landscapeStyle = modifiablePlainDesktopBackgroundStyle(M::Landscape);
landscapeStyle->setBlurDuration(3);
landscapeStyle->setBlurUpdateInterval(4);
QCOMPARE(extension->initialize(""), true);
QCOMPARE(QTimeLineDuration, landscapeStyle->blurDuration());
QCOMPARE(QTimeLineUpdateInterval, landscapeStyle->blurUpdateInterval());
}
void Ut_PlainDesktopBackgroundExtension::testWidget()
{
QCOMPARE(extension->widget(), (MWidget *)NULL);
}
void Ut_PlainDesktopBackgroundExtension::testDrawBackground()
{
QCOMPARE(extension->initialize(""), true);
extension->setDesktopInterface(*this);
QRectF br(10, 10, 50, 30);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
const QPixmap *landscapePixmap = PlainDesktopBackgroundPixmapConstructorPixmap;
emit updateLandscapePixmap();
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
const QPixmap *portraitPixmap = PlainDesktopBackgroundPixmapConstructorPixmap;
emit updatePortraitPixmap();
// Verify that the correct pixmaps are drawn in each orientation
currentOrientationAngle = M::Angle0;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, landscapePixmap);
currentOrientationAngle = M::Angle90;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, portraitPixmap);
currentOrientationAngle = M::Angle180;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, landscapePixmap);
currentOrientationAngle = M::Angle270;
extension->drawBackground(painter, br);
QCOMPARE(QPainterDrawPixmapPixmap, portraitPixmap);
// Check that the extension doesn't draw outside the bounding rectangle
QVERIFY(QPainterDrawPixmapTargetRect.isEmpty() || QPainterDrawPixmapTargetRect == br || br.contains(QPainterDrawPixmapTargetRect));
}
void Ut_PlainDesktopBackgroundExtension::testUpdatePixmaps()
{
// Set up the style for default values
PlainDesktopBackgroundStyle *landscapeStyle = modifiablePlainDesktopBackgroundStyle(M::Landscape);
PlainDesktopBackgroundStyle *portraitStyle = modifiablePlainDesktopBackgroundStyle(M::Portrait);
landscapeStyle->setBlurRadius(27);
landscapeStyle->setDefaultBackgroundImage("landscapeDefault");
portraitStyle->setDefaultBackgroundImage("portraitDefault");
// Set up GConf values
QString landscapeName("landscape");
QString portraitName("landscape");
MGConfItemValueForKey.insert("/desktop/meego/background/landscape", landscapeName);
MGConfItemValueForKey.insert("/desktop/meego/background/portrait", portraitName);
QCOMPARE(extension->initialize(""), true);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
QCOMPARE(PlainDesktopBackgroundPixmapConstructorName, landscapeName);
QCOMPARE(PlainDesktopBackgroundPixmapConstructorDefaultName, landscapeStyle->defaultBackgroundImage());
QCOMPARE(PlainDesktopBackgroundPixmapConstructorBlurRadius, landscapeStyle->blurRadius());
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updatePortraitPixmap();
QCOMPARE(PlainDesktopBackgroundPixmapConstructorName, portraitName);
QCOMPARE(PlainDesktopBackgroundPixmapConstructorDefaultName, portraitStyle->defaultBackgroundImage());
QCOMPARE(PlainDesktopBackgroundPixmapConstructorBlurRadius, landscapeStyle->blurRadius());
MTheme::releaseStyle(landscapeStyle);
MTheme::releaseStyle(portraitStyle);
}
void Ut_PlainDesktopBackgroundExtension::testUpdatePixmapsFails()
{
// Set up GConf values
QCOMPARE(extension->initialize(""), true);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmapName = "testPixmap";
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Set up the pixmaps again so that they fail
PlainDesktopBackgroundPixmapConstructorPixmapName = "unexpectedPixmap";
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Check that the GConf key was set to the previous value
QCOMPARE(MGConfItemValueForKey.value("/desktop/meego/background/landscape"), QVariant("testPixmap"));
// Set up the pixmaps again using an empty name (which is valid and should use the default)
MGConfItemValueForKey.insert("/desktop/meego/background/landscape", QString());
PlainDesktopBackgroundPixmapConstructorPixmapName = QString();
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// Check that the GConf key was not set to the previous value
QCOMPARE(MGConfItemValueForKey.value("/desktop/meego/background/landscape"), QVariant(QString()));
}
void Ut_PlainDesktopBackgroundExtension::testSetBlurFactor()
{
QCOMPARE(extension->initialize(""), true);
extension->setDesktopInterface(*this);
// Set up the pixmaps
PlainDesktopBackgroundPixmapConstructorPixmap = new QPixmap(1, 1);
PlainDesktopBackgroundPixmapConstructorBlurredPixmap = new QPixmap(1, 1);
emit updateLandscapePixmap();
// This should call MDesktopInterface::update() and painting (called by update()) should use the blur factor
qreal blurFactor = 0.5;
emit setBlurFactor(blurFactor);
QVERIFY(updateCalled);
QCOMPARE(QPainterOpacity, blurFactor);
// Setting the same blur factor again should not result in updates
updateCalled = false;
emit setBlurFactor(blurFactor);
QVERIFY(!updateCalled);
}
void Ut_PlainDesktopBackgroundExtension::testSetBlurTimeLineDirection()
{
QList<WindowInfo> emptyWindowList;
QList<WindowInfo> fullWindowList;
QString title;
fullWindowList.append(WindowInfo(title, Window(), XWindowAttributes(), Pixmap()));
// Test that the timeline direction is set and the timeline is resumed
emit setBlurTimeLineDirection(fullWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Forward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline is resumed if it's not running even if the direction doesn't change
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(fullWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Forward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline direction is set when it changes and the timeline is resumed
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(emptyWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Backward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
// Test that the timeline is resumed if it's not running even if the direction doesn't change
QTimeLineState = QTimeLine::NotRunning;
emit setBlurTimeLineDirection(emptyWindowList);
QCOMPARE(QTimeLineDirection, QTimeLine::Backward);
QCOMPARE(QTimeLineState, QTimeLine::Running);
}
void Ut_PlainDesktopBackgroundExtension::update()
{
updateCalled = true;
QRectF br(10, 10, 50, 30);
extension->drawBackground(painter, br);
}
M::OrientationAngle Ut_PlainDesktopBackgroundExtension::orientationAngle()
{
return currentOrientationAngle;
}
QTEST_APPLESS_MAIN(Ut_PlainDesktopBackgroundExtension)
<|endoftext|> |
<commit_before>
#include <gameplay/GameplayModule.hpp>
#include <gameplay/Behavior.hpp>
#include <gameplay/behaviors/positions/Goalie.hpp>
#include <gameplay/Play.hpp>
#include <Constants.hpp>
#include <protobuf/LogFrame.pb.h>
#include <Robot.hpp>
#include <stdio.h>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;
/**
* handles gameplay: choosing plays, and doing them
*/
Gameplay::GameplayModule::GameplayModule(SystemState *state):
_mutex(QMutex::Recursive)
{
_state = state;
_goalie = 0;
_currentPlayFactory = 0;
_playDone = false;
_centerMatrix = Geometry2d::TransformMatrix::translate(Geometry2d::Point(0, Field_Length / 2));
_oppMatrix = Geometry2d::TransformMatrix::translate(Geometry2d::Point(0, Field_Length)) *
Geometry2d::TransformMatrix::rotate(180);
//// Make an obstacle to cover the opponent's half of the field except for one robot diameter across the center line.
PolygonObstacle *sidePolygon = new PolygonObstacle;
_sideObstacle = ObstaclePtr(sidePolygon);
float x = Field_Width / 2 + Field_Border;
const float y1 = Field_Length / 2;
const float y2 = Field_Length + Field_Border;
const float r = Field_CenterRadius;
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-r, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(0, y1 + r));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(r, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(x, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(x, y2));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-x, y2));
float y = -Field_Border;
float deadspace = Field_Border;
x = Floor_Width/2.0f;
PolygonObstacle* floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y-1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y-1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[0] = ObstaclePtr(floorObstacle);
y = Field_Length + Field_Border;
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y+1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y+1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[1] = ObstaclePtr(floorObstacle);
y = Floor_Length;
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x-1, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x-1, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
_nonFloor[2] = ObstaclePtr(floorObstacle);
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x+1, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x+1, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[3] = ObstaclePtr(floorObstacle);
PolygonObstacle* goalArea = new PolygonObstacle;
const float halfFlat = Field_GoalFlat/2.0;
const float radius = Field_ArcRadius;
goalArea->polygon.vertices.push_back(Geometry2d::Point(-halfFlat, 0));
goalArea->polygon.vertices.push_back(Geometry2d::Point(-halfFlat, radius));
goalArea->polygon.vertices.push_back(Geometry2d::Point( halfFlat, radius));
goalArea->polygon.vertices.push_back(Geometry2d::Point( halfFlat, 0));
_goalArea.add(ObstaclePtr(goalArea));
_goalArea.add(ObstaclePtr(new CircleObstacle(Geometry2d::Point(-halfFlat, 0), radius)));
_goalArea.add(ObstaclePtr(new CircleObstacle(Geometry2d::Point(halfFlat, 0), radius)));
_ourHalf = std::make_shared<PolygonObstacle>();
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(-x, -Field_Border));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(x, y1));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(x, -Field_Border));
_opponentHalf = std::make_shared<PolygonObstacle>();
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y2));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(x, y2));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(x, y1));
_goalieID = -1;
}
Gameplay::GameplayModule::~GameplayModule()
{
removeGoalie();
}
int Gameplay::GameplayModule::manualID() const
{
return _state->logFrame->manual_id();
}
void Gameplay::GameplayModule::createGoalie()
{
if (!_goalie)
{
printf("Creating goalie behavior.\n");
_goalie = new Behaviors::Goalie(this);
}
}
void Gameplay::GameplayModule::removeGoalie()
{
if (_goalie)
{
printf("Removing goalie behavior.\n");
delete _goalie;
_goalie = 0;
}
}
void Gameplay::GameplayModule::updatePlay() {
const bool verbose = false;
/// important scenarios:
/// - no current plays - must pick a new one
/// - no available plays - must do nothing
/// - current play is fine, must be run
/// - current play has ended, must select new and run
/// - current play is not applicable/failed, must kill, select new and run
/// - new goalie, select new play (may reselect current play, which much be assigned new robots)
/// Update play scores.
/// The GUI thread needs this for the Plays tab and we will use it later
/// to determine the new play.
BOOST_FOREACH(PlayFactory *factory, PlayFactory::factories())
{
factory->lastScore = factory->score(this);
}
if ( _playDone || /// New play if old one was complete
!_currentPlay || /// There is no current play
isinf(_currentPlayFactory->lastScore) || /// Current play doesn't apply anymore
!_currentPlayFactory->enabled /// Current play was disabled
)
{
if (verbose) cout << " Selecting a new play" << endl;
_playDone = false;
/// Find the next play
PlayFactory *bestPlay = 0;
/// Pick a new play
float bestScore = 0;
/// Find the best applicable play
BOOST_FOREACH(PlayFactory *factory, PlayFactory::factories())
{
if (factory->enabled)
{
float score = factory->lastScore;
if (!isinf(score) && (!bestPlay || score < bestScore))
{
bestScore = score;
bestPlay = factory;
}
}
}
/// Start the play if it's not current.
if (bestPlay)
{
if (bestPlay != _currentPlayFactory)
{
clearAvoidBallRadii();
_currentPlayFactory = bestPlay;
_currentPlay = std::shared_ptr<Play>(_currentPlayFactory->create(this));
}
} else {
/// No usable plays
_currentPlay.reset();
_currentPlayFactory = 0;
}
}
}
void Gameplay::GameplayModule::clearAvoidBallRadii() {
BOOST_FOREACH(OurRobot* robot, _state->self)
{
if (robot) {
robot->resetAvoidBall();
}
}
}
/**
* returns the group of obstacles for the field
*/
ObstacleGroup Gameplay::GameplayModule::globalObstacles() const {
ObstacleGroup obstacles;
if (_state->gameState.stayOnSide())
{
obstacles.add(_sideObstacle);
}
if (!_state->logFrame->use_our_half())
{
obstacles.add(_ourHalf);
}
if (!_state->logFrame->use_opponent_half())
{
obstacles.add(_opponentHalf);
}
/// Add non floor obstacles
BOOST_FOREACH(const ObstaclePtr& ptr, _nonFloor)
{
obstacles.add(ptr);
}
return obstacles;
}
/**
* runs the current play
*/
void Gameplay::GameplayModule::run()
{
QMutexLocker lock(&_mutex);
bool verbose = false;
if (verbose) cout << "Starting GameplayModule::run()" << endl;
/// perform state variable updates on robots
/// Currently - only the timer for the kicker charger
BOOST_FOREACH(OurRobot* robot, _state->self)
{
if (robot) {
robot->update();
robot->resetMotionCommand();
}
}
/// Build a list of visible robots
_playRobots.clear();
BOOST_FOREACH(OurRobot *r, _state->self)
{
if (r->visible && !r->exclude)
{
_playRobots.insert(r);
}
}
/// Assign the goalie and remove it from _playRobots
if (_goalie)
{
/// The Goalie behavior is responsible for only selecting a robot which is allowed by the rules
/// (no changing goalies at random times).
/// The goalie behavior has priority for choosing robots because it must obey this rule,
/// so the current play will be restarted in case the goalie stole one of its robots.
_goalie->assign(_playRobots, _goalieID);
}
#if 0
if (_playRobots.size() == 5)
{
printf("Too many robots on field: goalie %p\n", _goalie);
if (_goalie)
{
printf(" robot %p\n", _goalie->robot);
if (_goalie->robot)
{
printf(" shell %d\n", _goalie->robot->shell());
}
}
/// Make a new goalie
if (_goalie)
{
delete _goalie;
}
/// _goalie = new Behaviors::Goalie(this);
}
#endif
_ballMatrix = Geometry2d::TransformMatrix::translate(_state->ball.pos);
if (verbose) cout << " Updating play" << endl;
updatePlay();
/// Run the goalie
if (_goalie)
{
if (verbose) cout << " Running goalie" << endl;
if (_goalie->robot && _goalie->robot->visible)
{
_goalie->run();
}
}
/// Run the current play
if (_currentPlay)
{
if (verbose) cout << " Running play" << endl;
_playDone = !_currentPlay->run();
}
/// determine global obstacles - field requirements
/// Two versions - one set with goal area, another without for goalie
ObstacleGroup global_obstacles = globalObstacles();
ObstacleGroup obstacles_with_goal = global_obstacles;
obstacles_with_goal.add(_goalArea);
/// execute motion planning for each robot
BOOST_FOREACH(OurRobot* r, _state->self) {
if (r && r->visible) {
/// set obstacles for the robots
if (_goalie && _goalie->robot && r->shell() == _goalie->robot->shell())
r->execute(global_obstacles); /// just for goalie
else
r->execute(obstacles_with_goal); /// all other robots
}
}
/// visualize
if (_state->gameState.stayAwayFromBall() && _state->ball.valid)
{
_state->drawCircle(_state->ball.pos, Field_CenterRadius, Qt::black, "Rules");
}
if (_currentPlay)
{
_playName = _currentPlay->name();
} else {
_playName = QString();
}
if (verbose) cout << "Finishing GameplayModule::run()" << endl;
if(_state->gameState.ourScore > _our_score_last_frame)
{
BOOST_FOREACH(OurRobot* r, _state->self)
{
r->sing();
}
}
_our_score_last_frame = _state->gameState.ourScore;
}
<commit_msg>Improved robot selection for plays. Fixes #3<commit_after>
#include <gameplay/GameplayModule.hpp>
#include <gameplay/Behavior.hpp>
#include <gameplay/behaviors/positions/Goalie.hpp>
#include <gameplay/Play.hpp>
#include <Constants.hpp>
#include <protobuf/LogFrame.pb.h>
#include <Robot.hpp>
#include <stdio.h>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;
/**
* handles gameplay: choosing plays, and doing them
*/
Gameplay::GameplayModule::GameplayModule(SystemState *state):
_mutex(QMutex::Recursive)
{
_state = state;
_goalie = 0;
_currentPlayFactory = 0;
_playDone = false;
_centerMatrix = Geometry2d::TransformMatrix::translate(Geometry2d::Point(0, Field_Length / 2));
_oppMatrix = Geometry2d::TransformMatrix::translate(Geometry2d::Point(0, Field_Length)) *
Geometry2d::TransformMatrix::rotate(180);
//// Make an obstacle to cover the opponent's half of the field except for one robot diameter across the center line.
PolygonObstacle *sidePolygon = new PolygonObstacle;
_sideObstacle = ObstaclePtr(sidePolygon);
float x = Field_Width / 2 + Field_Border;
const float y1 = Field_Length / 2;
const float y2 = Field_Length + Field_Border;
const float r = Field_CenterRadius;
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-r, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(0, y1 + r));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(r, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(x, y1));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(x, y2));
sidePolygon->polygon.vertices.push_back(Geometry2d::Point(-x, y2));
float y = -Field_Border;
float deadspace = Field_Border;
x = Floor_Width/2.0f;
PolygonObstacle* floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y-1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y-1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[0] = ObstaclePtr(floorObstacle);
y = Field_Length + Field_Border;
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y+1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y+1));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[1] = ObstaclePtr(floorObstacle);
y = Floor_Length;
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x-1, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x-1, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(-x, y));
_nonFloor[2] = ObstaclePtr(floorObstacle);
floorObstacle = new PolygonObstacle;
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x+1, -deadspace));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x+1, y));
floorObstacle->polygon.vertices.push_back(Geometry2d::Point(x, y));
_nonFloor[3] = ObstaclePtr(floorObstacle);
PolygonObstacle* goalArea = new PolygonObstacle;
const float halfFlat = Field_GoalFlat/2.0;
const float radius = Field_ArcRadius;
goalArea->polygon.vertices.push_back(Geometry2d::Point(-halfFlat, 0));
goalArea->polygon.vertices.push_back(Geometry2d::Point(-halfFlat, radius));
goalArea->polygon.vertices.push_back(Geometry2d::Point( halfFlat, radius));
goalArea->polygon.vertices.push_back(Geometry2d::Point( halfFlat, 0));
_goalArea.add(ObstaclePtr(goalArea));
_goalArea.add(ObstaclePtr(new CircleObstacle(Geometry2d::Point(-halfFlat, 0), radius)));
_goalArea.add(ObstaclePtr(new CircleObstacle(Geometry2d::Point(halfFlat, 0), radius)));
_ourHalf = std::make_shared<PolygonObstacle>();
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(-x, -Field_Border));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(x, y1));
_ourHalf->polygon.vertices.push_back(Geometry2d::Point(x, -Field_Border));
_opponentHalf = std::make_shared<PolygonObstacle>();
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y1));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(-x, y2));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(x, y2));
_opponentHalf->polygon.vertices.push_back(Geometry2d::Point(x, y1));
_goalieID = -1;
}
Gameplay::GameplayModule::~GameplayModule()
{
removeGoalie();
}
int Gameplay::GameplayModule::manualID() const
{
return _state->logFrame->manual_id();
}
void Gameplay::GameplayModule::createGoalie()
{
if (!_goalie)
{
printf("Creating goalie behavior.\n");
_goalie = new Behaviors::Goalie(this);
}
}
void Gameplay::GameplayModule::removeGoalie()
{
if (_goalie)
{
printf("Removing goalie behavior.\n");
delete _goalie;
_goalie = 0;
}
}
void Gameplay::GameplayModule::updatePlay() {
const bool verbose = false;
/// important scenarios:
/// - no current plays - must pick a new one
/// - no available plays - must do nothing
/// - current play is fine, must be run
/// - current play has ended, must select new and run
/// - current play is not applicable/failed, must kill, select new and run
/// - new goalie, select new play (may reselect current play, which much be assigned new robots)
/// Update play scores.
/// The GUI thread needs this for the Plays tab and we will use it later
/// to determine the new play.
BOOST_FOREACH(PlayFactory *factory, PlayFactory::factories())
{
factory->lastScore = factory->score(this);
}
if ( _playDone || /// New play if old one was complete
!_currentPlay || /// There is no current play
isinf(_currentPlayFactory->lastScore) || /// Current play doesn't apply anymore
!_currentPlayFactory->enabled /// Current play was disabled
)
{
if (verbose) cout << " Selecting a new play" << endl;
_playDone = false;
/// Find the next play
PlayFactory *bestPlay = 0;
/// Pick a new play
float bestScore = 0;
/// Find the best applicable play
BOOST_FOREACH(PlayFactory *factory, PlayFactory::factories())
{
if (factory->enabled)
{
float score = factory->lastScore;
if (!isinf(score) && (!bestPlay || score < bestScore))
{
bestScore = score;
bestPlay = factory;
}
}
}
/// Start the play if it's not current.
if (bestPlay)
{
if (bestPlay != _currentPlayFactory)
{
clearAvoidBallRadii();
_currentPlayFactory = bestPlay;
_currentPlay = std::shared_ptr<Play>(_currentPlayFactory->create(this));
}
} else {
/// No usable plays
_currentPlay.reset();
_currentPlayFactory = 0;
}
}
}
void Gameplay::GameplayModule::clearAvoidBallRadii() {
BOOST_FOREACH(OurRobot* robot, _state->self)
{
if (robot) {
robot->resetAvoidBall();
}
}
}
/**
* returns the group of obstacles for the field
*/
ObstacleGroup Gameplay::GameplayModule::globalObstacles() const {
ObstacleGroup obstacles;
if (_state->gameState.stayOnSide())
{
obstacles.add(_sideObstacle);
}
if (!_state->logFrame->use_our_half())
{
obstacles.add(_ourHalf);
}
if (!_state->logFrame->use_opponent_half())
{
obstacles.add(_opponentHalf);
}
/// Add non floor obstacles
BOOST_FOREACH(const ObstaclePtr& ptr, _nonFloor)
{
obstacles.add(ptr);
}
return obstacles;
}
/**
* runs the current play
*/
void Gameplay::GameplayModule::run()
{
QMutexLocker lock(&_mutex);
bool verbose = false;
if (verbose) cout << "Starting GameplayModule::run()" << endl;
/// perform state variable updates on robots
/// Currently - only the timer for the kicker charger
BOOST_FOREACH(OurRobot* robot, _state->self)
{
if (robot) {
robot->update();
robot->resetMotionCommand();
}
}
/// Build a list of visible robots
_playRobots.clear();
BOOST_FOREACH(OurRobot *r, _state->self)
{
if (r->visible && !r->exclude && r->rxIsFresh())
{
_playRobots.insert(r);
}
}
/// Assign the goalie and remove it from _playRobots
if (_goalie)
{
/// The Goalie behavior is responsible for only selecting a robot which is allowed by the rules
/// (no changing goalies at random times).
/// The goalie behavior has priority for choosing robots because it must obey this rule,
/// so the current play will be restarted in case the goalie stole one of its robots.
_goalie->assign(_playRobots, _goalieID);
}
#if 0
if (_playRobots.size() == 5)
{
printf("Too many robots on field: goalie %p\n", _goalie);
if (_goalie)
{
printf(" robot %p\n", _goalie->robot);
if (_goalie->robot)
{
printf(" shell %d\n", _goalie->robot->shell());
}
}
/// Make a new goalie
if (_goalie)
{
delete _goalie;
}
/// _goalie = new Behaviors::Goalie(this);
}
#endif
_ballMatrix = Geometry2d::TransformMatrix::translate(_state->ball.pos);
if (verbose) cout << " Updating play" << endl;
updatePlay();
/// Run the goalie
if (_goalie)
{
if (verbose) cout << " Running goalie" << endl;
if (_goalie->robot && _goalie->robot->visible)
{
_goalie->run();
}
}
/// Run the current play
if (_currentPlay)
{
if (verbose) cout << " Running play" << endl;
_playDone = !_currentPlay->run();
}
/// determine global obstacles - field requirements
/// Two versions - one set with goal area, another without for goalie
ObstacleGroup global_obstacles = globalObstacles();
ObstacleGroup obstacles_with_goal = global_obstacles;
obstacles_with_goal.add(_goalArea);
/// execute motion planning for each robot
BOOST_FOREACH(OurRobot* r, _state->self) {
if (r && r->visible) {
/// set obstacles for the robots
if (_goalie && _goalie->robot && r->shell() == _goalie->robot->shell())
r->execute(global_obstacles); /// just for goalie
else
r->execute(obstacles_with_goal); /// all other robots
}
}
/// visualize
if (_state->gameState.stayAwayFromBall() && _state->ball.valid)
{
_state->drawCircle(_state->ball.pos, Field_CenterRadius, Qt::black, "Rules");
}
if (_currentPlay)
{
_playName = _currentPlay->name();
} else {
_playName = QString();
}
if (verbose) cout << "Finishing GameplayModule::run()" << endl;
if(_state->gameState.ourScore > _our_score_last_frame)
{
BOOST_FOREACH(OurRobot* r, _state->self)
{
r->sing();
}
}
_our_score_last_frame = _state->gameState.ourScore;
}
<|endoftext|> |
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
enum NPBClass { S, W, A, B, C, D };
static const int NKEY_LOG2[] = { 16, 20, 23, 25, 27, 31 };
static const int MAX_KEY_LOG2[] = { 11, 16, 19, 21, 23, 27 };
static const int NBUCKET_LOG2[] = { 10, 10, 10, 10, 10, 10 };
inline NPBClass get_npb_class(char c) {
switch (c) {
case 'S': return NPBClass::S;
case 'W': return NPBClass::W;
case 'A': return NPBClass::A;
case 'B': return NPBClass::B;
case 'C': return NPBClass::C;
case 'D': return NPBClass::D;
}
}
inline char npb_class_char(NPBClass c) {
switch (c) {
case NPBClass::S: return 'S';
case NPBClass::W: return 'W';
case NPBClass::A: return 'A';
case NPBClass::B: return 'B';
case NPBClass::C: return 'C';
case NPBClass::D: return 'D';
}
}
<commit_msg>Add 'E' size, change 'D' to be back at its old value (29).<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
enum NPBClass { S, W, A, B, C, D, E };
static const int NKEY_LOG2[] = { 16, 20, 23, 25, 27, 29, 31 };
static const int MAX_KEY_LOG2[] = { 11, 16, 19, 21, 23, 27, 27 };
static const int NBUCKET_LOG2[] = { 10, 10, 10, 10, 10, 10, 10 };
inline NPBClass get_npb_class(char c) {
switch (c) {
case 'S': return NPBClass::S;
case 'W': return NPBClass::W;
case 'A': return NPBClass::A;
case 'B': return NPBClass::B;
case 'C': return NPBClass::C;
case 'D': return NPBClass::D;
case 'E': return NPBClass::E;
}
}
inline char npb_class_char(NPBClass c) {
switch (c) {
case NPBClass::S: return 'S';
case NPBClass::W: return 'W';
case NPBClass::A: return 'A';
case NPBClass::B: return 'B';
case NPBClass::C: return 'C';
case NPBClass::D: return 'D';
case NPBClass::E: return 'E';
}
}
<|endoftext|> |
<commit_before>#include <BALL/VIEW/DIALOGS/pluginDialog.h>
#include <BALL/PLUGIN/pluginManager.h>
#include <BALL/PLUGIN/BALLPlugin.h>
#include <BALL/VIEW/PLUGIN/VIEWPlugin.h>
#include <BALL/COMMON/logStream.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/PLUGIN/inputDevPluginHandler.h>
Q_DECLARE_METATYPE(BALL::VIEW::VIEWPlugin*)
#include <QtGui/QFileDialog>
#include <QtCore/QObject>
#include <QtCore/QDebug>
namespace BALL
{
namespace VIEW
{
/* PluginItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
}
void PluginItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
option.decorationSize = QSize(64, 64);
drawBackground(painter, option, index);
drawDecoration(painter, option, index);
painter->drawText(option.decorationSize().width() + )
}
*/
PluginModel::PluginModel()
: num_rows_(0)
{
PluginManager& man = PluginManager::instance();
man.registerHandler(new InputDevPluginHandler());
}
int PluginModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return num_rows_;
}
void PluginModel::pluginsLoaded()
{
int nrow = num_rows_;
num_rows_ = PluginManager::instance().getPluginCount();
beginInsertRows(QModelIndex(), nrow, num_rows_);
endInsertRows();
}
QVariant PluginModel::data(const QModelIndex& i, int role) const
{
if(!i.isValid()) {
return QVariant();
}
PluginManager& man = PluginManager::instance();
if(i.row() >= num_rows_) {
return QVariant();
}
switch(role) {
case Qt::UserRole:
return qVariantFromValue(man.getPluginInstance(i.row()));
case Qt::DisplayRole:
{
BALLPlugin* ptr = qobject_cast<BALLPlugin*>(man.getPluginInstance(i.row()));
// we *know* that this is a BALLPlugin (the loader takes care of that), so we don't need
// to test if the cast succeeded
return ptr->getName();
}
case Qt::DecorationRole:
{
VIEWPlugin* ptr = qobject_cast<VIEWPlugin*>(man.getPluginInstance(i.row()));
if (ptr)
return QIcon(*(ptr->getIcon()));
else
return QVariant();
}
default:
return QVariant();
}
}
PluginDialog::PluginDialog(QWidget* parent, const char* name)
: QDialog(parent),
ModularWidget(name)
{
setupUi(this);
pluginView->setModel(&model_);
QString plugin_path(BALL_PATH);
plugin_path += "/plugins";
PluginManager& man = PluginManager::instance();
man.setPluginDirectory(plugin_path);
model_.pluginsLoaded();
setObjectName(name);
ModularWidget::registerWidget(this);
hide();
}
void PluginDialog::initializeWidget(MainControl&)
throw()
{
insertMenuEntry(MainControl::TOOLS, "Load Plugin", this, SLOT(show()), "Shortcut|Tools|Load_Plugin");
}
void PluginDialog::applyChanges()
{
}
void PluginDialog::revertChanges()
{
}
void PluginDialog::pluginChanged(QModelIndex i)
{
active_index_ = i;
QObject* active_object = qvariant_cast<QObject*>(model_.data(i, Qt::UserRole));
BALLPlugin* active_plugin;
if(!(active_plugin = qobject_cast<BALLPlugin*>(active_object))) {
return;
}
togglePluginButton->setEnabled(true);
if(active_plugin->isActive()) {
togglePluginButton->setText("Deactivate");
} else {
togglePluginButton->setText("Activate");
}
VIEWPlugin* active_view_plugin = qvariant_cast<VIEWPlugin*>(active_object);
if (active_view_plugin)
{
QWidget* cfg_dialog = active_view_plugin->getConfigDialog();
if(cfg_dialog) {
settingsButton->setEnabled(true);
connect(settingsButton, SIGNAL(clicked()), cfg_dialog, SLOT(show()));
} else {
settingsButton->setEnabled(false);
}
}
else
settingsButton->setEnabled(false);
}
void PluginDialog::addPluginDirectory()
{
QString plugin_path(BALL_PATH);
plugin_path += "/plugins";
QString dir = QFileDialog::getExistingDirectory(0, "Select a plugin directory", plugin_path);
PluginManager& man = PluginManager::instance();
man.setPluginDirectory(dir);
model_.pluginsLoaded();
}
void PluginDialog::togglePluginState()
{
if(!active_index_.isValid()) {
return;
}
QObject* active_object = qvariant_cast<QObject*>(model_.data(active_index_, Qt::UserRole));
BALLPlugin* active_plugin = qobject_cast<BALLPlugin*>(active_object);
if(active_plugin->isActive()) {
PluginManager::instance().stopPlugin(active_plugin);
togglePluginButton->setText("Activate");
} else {
PluginManager::instance().startPlugin(active_plugin);
togglePluginButton->setText("Deactivate");
}
}
}
}
<commit_msg>Repair a wrong qvariant_cast in PluginDialog<commit_after>#include <BALL/VIEW/DIALOGS/pluginDialog.h>
#include <BALL/PLUGIN/pluginManager.h>
#include <BALL/PLUGIN/BALLPlugin.h>
#include <BALL/VIEW/PLUGIN/VIEWPlugin.h>
#include <BALL/COMMON/logStream.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/PLUGIN/inputDevPluginHandler.h>
Q_DECLARE_METATYPE(BALL::VIEW::VIEWPlugin*)
#include <QtGui/QFileDialog>
#include <QtCore/QObject>
#include <QtCore/QDebug>
namespace BALL
{
namespace VIEW
{
/* PluginItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
}
void PluginItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
option.decorationSize = QSize(64, 64);
drawBackground(painter, option, index);
drawDecoration(painter, option, index);
painter->drawText(option.decorationSize().width() + )
}
*/
PluginModel::PluginModel()
: num_rows_(0)
{
PluginManager& man = PluginManager::instance();
man.registerHandler(new InputDevPluginHandler());
}
int PluginModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return num_rows_;
}
void PluginModel::pluginsLoaded()
{
int nrow = num_rows_;
num_rows_ = PluginManager::instance().getPluginCount();
beginInsertRows(QModelIndex(), nrow, num_rows_);
endInsertRows();
}
QVariant PluginModel::data(const QModelIndex& i, int role) const
{
if(!i.isValid()) {
return QVariant();
}
PluginManager& man = PluginManager::instance();
if(i.row() >= num_rows_) {
return QVariant();
}
switch(role) {
case Qt::UserRole:
return qVariantFromValue(man.getPluginInstance(i.row()));
case Qt::DisplayRole:
{
BALLPlugin* ptr = qobject_cast<BALLPlugin*>(man.getPluginInstance(i.row()));
// we *know* that this is a BALLPlugin (the loader takes care of that), so we don't need
// to test if the cast succeeded
return ptr->getName();
}
case Qt::DecorationRole:
{
VIEWPlugin* ptr = qobject_cast<VIEWPlugin*>(man.getPluginInstance(i.row()));
if (ptr)
return QIcon(*(ptr->getIcon()));
else
return QVariant();
}
default:
return QVariant();
}
}
PluginDialog::PluginDialog(QWidget* parent, const char* name)
: QDialog(parent),
ModularWidget(name)
{
setupUi(this);
pluginView->setModel(&model_);
QString plugin_path(BALL_PATH);
plugin_path += "/plugins";
PluginManager& man = PluginManager::instance();
man.setPluginDirectory(plugin_path);
model_.pluginsLoaded();
setObjectName(name);
ModularWidget::registerWidget(this);
hide();
}
void PluginDialog::initializeWidget(MainControl&)
throw()
{
insertMenuEntry(MainControl::TOOLS, "Load Plugin", this, SLOT(show()), "Shortcut|Tools|Load_Plugin");
}
void PluginDialog::applyChanges()
{
}
void PluginDialog::revertChanges()
{
}
void PluginDialog::pluginChanged(QModelIndex i)
{
active_index_ = i;
QObject* active_object = qvariant_cast<QObject*>(model_.data(i, Qt::UserRole));
BALLPlugin* active_plugin;
if(!(active_plugin = qobject_cast<BALLPlugin*>(active_object))) {
return;
}
togglePluginButton->setEnabled(true);
if(active_plugin->isActive()) {
togglePluginButton->setText("Deactivate");
} else {
togglePluginButton->setText("Activate");
}
VIEWPlugin* active_view_plugin = qobject_cast<VIEWPlugin*>(active_object);
if (active_view_plugin)
{
QWidget* cfg_dialog = active_view_plugin->getConfigDialog();
if(cfg_dialog) {
settingsButton->setEnabled(true);
connect(settingsButton, SIGNAL(clicked()), cfg_dialog, SLOT(show()));
} else {
settingsButton->setEnabled(false);
}
}
else
settingsButton->setEnabled(false);
}
void PluginDialog::addPluginDirectory()
{
QString plugin_path(BALL_PATH);
plugin_path += "/plugins";
QString dir = QFileDialog::getExistingDirectory(0, "Select a plugin directory", plugin_path);
PluginManager& man = PluginManager::instance();
man.setPluginDirectory(dir);
model_.pluginsLoaded();
}
void PluginDialog::togglePluginState()
{
if(!active_index_.isValid()) {
return;
}
QObject* active_object = qvariant_cast<QObject*>(model_.data(active_index_, Qt::UserRole));
BALLPlugin* active_plugin = qobject_cast<BALLPlugin*>(active_object);
if(active_plugin->isActive()) {
PluginManager::instance().stopPlugin(active_plugin);
togglePluginButton->setText("Activate");
} else {
PluginManager::instance().startPlugin(active_plugin);
togglePluginButton->setText("Deactivate");
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef ATTRIBUTE_HPP
#define ATTRIBUTE_HPP
#include <set>
#include <vector>
#include <chrono>
#include <memory>
#include <boost/optional.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/local_time/local_time.hpp>
/**
* @brief The VR enum defines the value representations of an attribute
* a Value Representation can be described as a data type.
*/
enum class VR
{
AE, AS, AT, CS, DA, DS, DT, FL, FD, IS,
LO, LT, OB, OF, OW, PN, SH, SL, SQ, SS,
ST, TM, UI, UL, UN, US, UT
};
struct elementfield_base;
template <VR vr>
struct element_field;
/**
* @brief The attribute_visitor class is the base class for the visitors that
* operate on the VR dependent types.
*/
template <VR vr>
class attribute_visitor
{
public:
virtual void accept(element_field<vr>* ef)
{
this->apply(ef);
}
virtual void apply(element_field<vr>*) { assert(false); }
};
/**
* @brief The elementfield_base struct is the base type for the element fields
* with their different types.
* This struct may not be dependent on any template parameters, as it is used
* by the elementfield struct which holds a "type-dependency-free" pointer to
* it.
*/
struct elementfield_base
{
/**
* @brief accept
* @param op
*/
template <VR vr>
void accept(attribute_visitor<vr>& op) {
element_field<vr>* ef = dynamic_cast<element_field<vr>*>(this);
assert(ef); // this class is abstract; the dynamic type of this must be
// a pointer to a subclass, therefore ef cannot be nullptr.
op.accept(ef);
}
virtual ~elementfield_base() = 0;
};
/**
* @brief The elementfield_base struct defines all information contained in an
* attribute of an iod
* @see DICOM standard 3.5, chapter 7
*/
struct elementfield
{
struct tag_type
{
short group_id;
short element_id;
};
tag_type tag;
boost::optional<VR> value_rep;
std::size_t value_len;
std::shared_ptr<elementfield_base> value_field;
};
/**
* construct a type mapping VR -> T using specialized templates
*/
template<VR>
struct type_of {};
template<>
struct type_of<VR::AE> { using type = std::string; };
template<>
struct type_of<VR::AS> { using type = std::string; };
template<>
struct type_of<VR::AT> { using type = elementfield::tag_type; };
template<>
struct type_of<VR::CS> { using type = std::string; };
template<>
struct type_of<VR::DA> { using type = boost::gregorian::date; };
template<>
struct type_of<VR::DS> { using type = std::string; };
template<>
struct type_of<VR::DT> { using type = boost::local_time::local_date_time; };
template<>
struct type_of<VR::FL> { using type = float; };
template<>
struct type_of<VR::FD> { using type = double; };
template<>
struct type_of<VR::IS> { using type = std::string; };
template<>
struct type_of<VR::LO> { using type = std::string; };
template<>
struct type_of<VR::LT> { using type = std::string; };
template<>
struct type_of<VR::OB> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::OF> { using type = std::string; };
template<>
struct type_of<VR::OW> { using type = std::string; };
template<>
struct type_of<VR::PN> { using type = std::string; };
template<>
struct type_of<VR::SH> { using type = std::string; };
template<>
struct type_of<VR::SL> { using type = long; };
template<>
struct type_of<VR::SQ> { using type = std::vector<std::set<elementfield_base>>; };
template<>
struct type_of<VR::SS> { using type = short; };
template<>
struct type_of<VR::ST> { using type = std::string; };
template<>
struct type_of<VR::TM> { using type = boost::local_time::local_date_time; };
template<>
struct type_of<VR::UI> { using type = std::string; };
template<>
struct type_of<VR::UN> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::US> { using type = unsigned short; };
template<>
struct type_of<VR::UT> { using type = std::string; };
/**
* @brief The element_field struct contains the type-specific data and methods
* for setting / receiving those
*/
template <VR vr>
struct element_field: elementfield_base
{
using vrtype = typename type_of<vr>::type;
vrtype value_field;
virtual ~element_field() {}
};
/**
* @brief The get_visitor class is used to retrieve the value of the value field
* of an attribute.
*/
template <VR vr>
class get_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type& getdata;
public:
get_visitor(typename type_of<vr>::type& data): getdata(data) {
}
virtual void apply(element_field<vr>* ef) override {
getdata = ef->value_field;
}
};
/**
* @brief get_value_field is used to retrieve the value of the value field
* of an attribute.
* @param e element field / attribute operated upon
* @param out_data reference where the value will be stored
*/
template <VR vr>
void get_value_field(elementfield& e, typename type_of<vr>::type& out_data)
{
get_visitor<vr> getter(out_data);
e.value_field->accept<vr>(getter);
}
/**
* @brief The set_visitor class is used to set a specified value into the
* value field.
*/
template <VR vr>
class set_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type setdata;
public:
set_visitor(typename type_of<vr>::type data) {
setdata = data;
}
virtual void apply(element_field<vr>* ef) override {
ef->value_field = setdata;
}
};
/**
* @brief make_elementfield is a factory function to return a prepared attribute
* / element field.
* @param gid group id
* @param eid element id
* @param data data for the value field
* @return prepared instance of elementfield
*/
template <VR vr>
elementfield make_elementfield(short gid, short eid, std::size_t data_len, typename type_of<vr>::type data)
{
elementfield el;
el.tag.group_id = gid; el.tag.element_id = eid;
el.value_rep = vr;
el.value_len = data_len;
el.value_field = std::shared_ptr<elementfield_base> {new element_field<vr>};
set_visitor<vr> setter(data);
el.value_field->accept<vr>(setter);
return el;
}
/**
* @brief operator < is necessary for the storage in the set
* @param lhs
* @param rhs
* @return
* The order is defined by the attribute group and element ids. a < b is true
* iff the group id of a is lesser than b, or if they are equal, iff the
* element id of a is lesser than b.
*/
bool operator<(const elementfield& lhs, const elementfield& rhs);
bool operator<(const elementfield::tag_type& lhs, const elementfield::tag_type& rhs);
#endif // IOD_HPP
<commit_msg>provide static value size data<commit_after>#ifndef ATTRIBUTE_HPP
#define ATTRIBUTE_HPP
#include <set>
#include <vector>
#include <chrono>
#include <memory>
#include <boost/optional.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/local_time/local_time.hpp>
/**
* @brief The VR enum defines the value representations of an attribute
* a Value Representation can be described as a data type.
*/
enum class VR
{
AE, AS, AT, CS, DA, DS, DT, FL, FD, IS,
LO, LT, OB, OD, OF, OW, PN, SH, SL, SQ,
SS, ST, TM, UI, UL, UN, US, UT
};
struct elementfield_base;
template <VR vr>
struct element_field;
/**
* @brief The attribute_visitor class is the base class for the visitors that
* operate on the VR dependent types.
*/
template <VR vr>
class attribute_visitor
{
public:
virtual void accept(element_field<vr>* ef)
{
this->apply(ef);
}
virtual void apply(element_field<vr>*) { assert(false); }
};
/**
* @brief The elementfield_base struct is the base type for the element fields
* with their different types.
* This struct may not be dependent on any template parameters, as it is used
* by the elementfield struct which holds a "type-dependency-free" pointer to
* it.
*/
struct elementfield_base
{
/**
* @brief accept
* @param op
*/
template <VR vr>
void accept(attribute_visitor<vr>& op) {
element_field<vr>* ef = dynamic_cast<element_field<vr>*>(this);
assert(ef); // this class is abstract; the dynamic type of this must be
// a pointer to a subclass, therefore ef cannot be nullptr.
op.accept(ef);
}
virtual ~elementfield_base() = 0;
};
/**
* @brief The elementfield_base struct defines all information contained in an
* attribute of an iod
* @see DICOM standard 3.5, chapter 7
*/
struct elementfield
{
struct tag_type
{
short group_id;
short element_id;
};
tag_type tag;
boost::optional<VR> value_rep;
std::size_t value_len;
std::shared_ptr<elementfield_base> value_field;
};
/**
* construct a type mapping VR -> T using specialized templates
*/
template<VR>
struct type_of {};
template<>
struct type_of<VR::AE>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::AS>
{
using type = std::string;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::AT>
{
using type = elementfield::tag_type;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::CS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DA>
{
using type = boost::gregorian::date;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::DS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DT>
{
using type = boost::local_time::local_date_time;
static const std::size_t max_len = 26;
};
template<>
struct type_of<VR::FL>
{
using type = float;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::FD>
{
using type = double;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::IS>
{
using type = std::string;
static const std::size_t max_len = 12;
};
template<>
struct type_of<VR::LO>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::LT>
{
using type = std::string;
static const std::size_t max_len = 10240;
};
template<>
struct type_of<VR::OB> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::OD>
{
using type = std::vector<unsigned char>;
static constexpr std::size_t max_len = std::pow(2, 32)-8;
};
template<>
struct type_of<VR::OF>
{
using type = std::string;
static constexpr std::size_t max_len = std::pow(2, 32)-4;
};
template<>
struct type_of<VR::OW> { using type = std::string; };
template<>
struct type_of<VR::PN>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::SH>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::SL>
{
using type = long;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::SQ> { using type = std::vector<std::set<elementfield_base>>; };
template<>
struct type_of<VR::SS>
{
using type = short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::ST>
{
using type = std::string;
static const std::size_t max_len = 1024;
};
template<>
struct type_of<VR::TM>
{
using type = boost::local_time::local_date_time;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UI>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UN> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::US>
{
using type = unsigned short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::UT>
{
using type = std::string;
static constexpr std::size_t max_len = std::pow(2, 32)-2;
};
/**
* @brief The element_field struct contains the type-specific data and methods
* for setting / receiving those
*/
template <VR vr>
struct element_field: elementfield_base
{
using vrtype = typename type_of<vr>::type;
vrtype value_field;
virtual ~element_field() {}
};
/**
* @brief The get_visitor class is used to retrieve the value of the value field
* of an attribute.
*/
template <VR vr>
class get_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type& getdata;
public:
get_visitor(typename type_of<vr>::type& data): getdata(data) {
}
virtual void apply(element_field<vr>* ef) override {
getdata = ef->value_field;
}
};
/**
* @brief get_value_field is used to retrieve the value of the value field
* of an attribute.
* @param e element field / attribute operated upon
* @param out_data reference where the value will be stored
*/
template <VR vr>
void get_value_field(elementfield& e, typename type_of<vr>::type& out_data)
{
get_visitor<vr> getter(out_data);
e.value_field->accept<vr>(getter);
}
/**
* @brief The set_visitor class is used to set a specified value into the
* value field.
*/
template <VR vr>
class set_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type setdata;
public:
set_visitor(typename type_of<vr>::type data) {
setdata = data;
}
virtual void apply(element_field<vr>* ef) override {
ef->value_field = setdata;
}
};
/**
* @brief make_elementfield is a factory function to return a prepared attribute
* / element field.
* @param gid group id
* @param eid element id
* @param data data for the value field
* @return prepared instance of elementfield
*/
template <VR vr>
elementfield make_elementfield(short gid, short eid, std::size_t data_len, typename type_of<vr>::type data)
{
elementfield el;
el.tag.group_id = gid; el.tag.element_id = eid;
el.value_rep = vr;
el.value_len = data_len;
el.value_field = std::shared_ptr<elementfield_base> {new element_field<vr>};
set_visitor<vr> setter(data);
el.value_field->accept<vr>(setter);
return el;
}
/**
* @brief operator < is necessary for the storage in the set
* @param lhs
* @param rhs
* @return
* The order is defined by the attribute group and element ids. a < b is true
* iff the group id of a is lesser than b, or if they are equal, iff the
* element id of a is lesser than b.
*/
bool operator<(const elementfield& lhs, const elementfield& rhs);
bool operator<(const elementfield::tag_type& lhs, const elementfield::tag_type& rhs);
#endif // IOD_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: b3dpolygontools.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-08-03 13:31:03 $
*
* 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 _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _BGFX_POLYGON_B3DPOLYGONTOOLS_HXX
#include <basegfx/polygon/b3dpolygontools.hxx>
#endif
#ifndef _BGFX_POLYGON_B3DPOLYGON_HXX
#include <basegfx/polygon/b3dpolygon.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef _BGFX_RANGE_B3DRANGE_HXX
#include <basegfx/range/b3drange.hxx>
#endif
#include <numeric>
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
namespace tools
{
// B3DPolygon tools
void checkClosed(B3DPolygon& rCandidate)
{
while(rCandidate.count() > 1L
&& rCandidate.getB3DPoint(0L).equal(rCandidate.getB3DPoint(rCandidate.count() - 1L)))
{
rCandidate.setClosed(true);
rCandidate.remove(rCandidate.count() - 1L);
}
}
// Get successor and predecessor indices. Returning the same index means there
// is none. Same for successor.
sal_uInt32 getIndexOfPredecessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(nIndex)
{
return nIndex - 1L;
}
else if(rCandidate.count())
{
return rCandidate.count() - 1L;
}
else
{
return nIndex;
}
}
sal_uInt32 getIndexOfSuccessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(nIndex + 1L < rCandidate.count())
{
return nIndex + 1L;
}
else
{
return 0L;
}
}
sal_uInt32 getIndexOfDifferentPredecessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
sal_uInt32 nNewIndex(nIndex);
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(rCandidate.count() > 1)
{
nNewIndex = getIndexOfPredecessor(nIndex, rCandidate);
::basegfx::B3DPoint aPoint(rCandidate.getB3DPoint(nIndex));
while(nNewIndex != nIndex
&& aPoint.equal(rCandidate.getB3DPoint(nNewIndex)))
{
nNewIndex = getIndexOfPredecessor(nNewIndex, rCandidate);
}
}
return nNewIndex;
}
sal_uInt32 getIndexOfDifferentSuccessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
sal_uInt32 nNewIndex(nIndex);
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(rCandidate.count() > 1)
{
nNewIndex = getIndexOfSuccessor(nIndex, rCandidate);
::basegfx::B3DPoint aPoint(rCandidate.getB3DPoint(nIndex));
while(nNewIndex != nIndex
&& aPoint.equal(rCandidate.getB3DPoint(nNewIndex)))
{
nNewIndex = getIndexOfSuccessor(nNewIndex, rCandidate);
}
}
return nNewIndex;
}
::basegfx::B3DRange getRange(const ::basegfx::B3DPolygon& rCandidate)
{
::basegfx::B3DRange aRetval;
const sal_uInt32 nPointCount(rCandidate.count());
for(sal_uInt32 a(0L); a < nPointCount; a++)
{
const ::basegfx::B3DPoint aTestPoint(rCandidate.getB3DPoint(a));
aRetval.expand(aTestPoint);
}
return aRetval;
}
double getEdgeLength(const ::basegfx::B3DPolygon& rCandidate, sal_uInt32 nIndex)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
double fRetval(0.0);
const sal_uInt32 nPointCount(rCandidate.count());
if(nIndex < nPointCount)
{
if(rCandidate.isClosed() || nIndex + 1 != nPointCount)
{
const sal_uInt32 nNextIndex(nIndex + 1 == nPointCount ? 0L : nIndex + 1L);
const ::basegfx::B3DPoint aCurrentPoint(rCandidate.getB3DPoint(nIndex));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
const ::basegfx::B3DVector aVector(aNextPoint - aCurrentPoint);
fRetval = aVector.getLength();
}
}
return fRetval;
}
double getLength(const ::basegfx::B3DPolygon& rCandidate)
{
// This method may also be implemented using a loop over getEdgeLength, but
// since this would cause a lot of sqare roots to be solved it is much better
// to sum up the quadrats first and then use a singe suare root (if necessary)
double fRetval(0.0);
const sal_uInt32 nPointCount(rCandidate.count());
const sal_uInt32 nLoopCount(rCandidate.isClosed() ? nPointCount : nPointCount - 1L);
for(sal_uInt32 a(0L); a < nLoopCount; a++)
{
const sal_uInt32 nNextIndex(a + 1 == nPointCount ? 0L : a + 1L);
const ::basegfx::B3DPoint aCurrentPoint(rCandidate.getB3DPoint(a));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
const ::basegfx::B3DVector aVector(aNextPoint - aCurrentPoint);
fRetval += aVector.scalar(aVector);
}
if(!::basegfx::fTools::equalZero(fRetval))
{
const double fOne(1.0);
if(!::basegfx::fTools::equal(fOne, fRetval))
{
fRetval = sqrt(fRetval);
}
}
return fRetval;
}
::basegfx::B3DPoint getPositionAbsolute(const ::basegfx::B3DPolygon& rCandidate, double fDistance, double fLength)
{
::basegfx::B3DPoint aRetval;
const sal_uInt32 nPointCount(rCandidate.count());
if(nPointCount > 1L)
{
sal_uInt32 nIndex(0L);
bool bIndexDone(false);
const double fZero(0.0);
double fEdgeLength(fZero);
// get length if not given
if(::basegfx::fTools::equalZero(fLength))
{
fLength = getLength(rCandidate);
}
// handle fDistance < 0.0
if(::basegfx::fTools::less(fDistance, fZero))
{
if(rCandidate.isClosed())
{
// if fDistance < 0.0 increment with multiple of fLength
sal_uInt32 nCount(sal_uInt32(-fDistance / fLength));
fDistance += double(nCount + 1L) * fLength;
}
else
{
// crop to polygon start
fDistance = fZero;
bIndexDone = true;
}
}
// handle fDistance >= fLength
if(::basegfx::fTools::moreOrEqual(fDistance, fLength))
{
if(rCandidate.isClosed())
{
// if fDistance >= fLength decrement with multiple of fLength
sal_uInt32 nCount(sal_uInt32(fDistance / fLength));
fDistance -= (double)(nCount) * fLength;
}
else
{
// crop to polygon end
fDistance = fZero;
nIndex = nPointCount - 1L;
bIndexDone = true;
}
}
// look for correct index. fDistance is now [0.0 .. fLength[
if(!bIndexDone)
{
do
{
// get length of next edge
fEdgeLength = getEdgeLength(rCandidate, nIndex);
if(::basegfx::fTools::moreOrEqual(fDistance, fEdgeLength))
{
// go to next edge
fDistance -= fEdgeLength;
nIndex++;
}
else
{
// it's on this edge, stop
bIndexDone = true;
}
} while (!bIndexDone);
}
// get the point using nIndex
aRetval = rCandidate.getB3DPoint(nIndex);
// if fDistance != 0.0, move that length on the edge. The edge
// length is in fEdgeLength.
if(!::basegfx::fTools::equalZero(fDistance))
{
sal_uInt32 nNextIndex(getIndexOfSuccessor(nIndex, rCandidate));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
double fRelative(fZero);
if(!::basegfx::fTools::equalZero(fEdgeLength))
{
fRelative = fDistance / fEdgeLength;
}
// add calculated average value to the return value
aRetval += ::basegfx::interpolate(aRetval, aNextPoint, fRelative);
}
}
return aRetval;
}
::basegfx::B3DPoint getPositionRelative(const ::basegfx::B3DPolygon& rCandidate, double fDistance, double fLength)
{
// get length if not given
if(::basegfx::fTools::equalZero(fLength))
{
fLength = getLength(rCandidate);
}
// multiply fDistance with real length to get absolute position and
// use getPositionAbsolute
return getPositionAbsolute(rCandidate, fDistance * fLength, fLength);
}
::basegfx::B3DPolyPolygon applyLineDashing(const ::basegfx::B3DPolygon& rCandidate, const ::std::vector<double>& raDashDotArray, double fFullDashDotLen)
{
::basegfx::B3DPolyPolygon aRetval;
if(0.0 == fFullDashDotLen && raDashDotArray.size())
{
// calculate fFullDashDotLen from raDashDotArray
fFullDashDotLen = ::std::accumulate(raDashDotArray.begin(), raDashDotArray.end(), 0.0);
}
if(rCandidate.count() && fFullDashDotLen > 0.0)
{
const sal_uInt32 nCount(rCandidate.isClosed() ? rCandidate.count() : rCandidate.count() - 1L);
sal_uInt32 nDashDotIndex(0L);
double fDashDotLength(raDashDotArray[nDashDotIndex]);
for(sal_uInt32 a(0L); a < nCount; a++)
{
const sal_uInt32 nNextIndex(getIndexOfSuccessor(a, rCandidate));
const ::basegfx::B3DPoint aStart(rCandidate.getB3DPoint(a));
const ::basegfx::B3DPoint aEnd(rCandidate.getB3DPoint(nNextIndex));
::basegfx::B3DVector aVector(aEnd - aStart);
double fLength(aVector.getLength());
double fPosOnVector(0.0);
aVector.normalize();
while(fLength >= fDashDotLength)
{
// handle [fPosOnVector .. fPosOnVector+fDashDotLength]
if(nDashDotIndex % 2)
{
::basegfx::B3DPolygon aResult;
// add start point
if(fPosOnVector == 0.0)
{
aResult.append(aStart);
}
else
{
aResult.append( B3DPoint(aStart + (aVector * fPosOnVector)) );
}
// add end point
aResult.append( B3DPoint(aStart + (aVector * (fPosOnVector + fDashDotLength))) );
// add line to PolyPolygon
aRetval.append(aResult);
}
// consume from fDashDotLength
fPosOnVector += fDashDotLength;
fLength -= fDashDotLength;
nDashDotIndex = (nDashDotIndex + 1L) % raDashDotArray.size();
fDashDotLength = raDashDotArray[nDashDotIndex];
}
// handle [fPosOnVector .. fPosOnVector+fLength (bzw. end)]
if((fLength > 0.0) && (nDashDotIndex % 2))
{
::basegfx::B3DPolygon aResult;
// add start and end point
const ::basegfx::B3DPoint aPosA(aStart + (aVector * fPosOnVector));
aResult.append(aPosA);
aResult.append(aEnd);
// add line to PolyPolygon
aRetval.append(aResult);
}
// consume from fDashDotLength
fDashDotLength -= fLength;
}
}
return aRetval;
}
} // end of namespace tools
} // end of namespace basegfx
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS aw019 (1.4.8); FILE MERGED 2004/10/13 08:30:45 aw 1.4.8.1: #i34831#<commit_after>/*************************************************************************
*
* $RCSfile: b3dpolygontools.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 08:38:29 $
*
* 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 _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _BGFX_POLYGON_B3DPOLYGONTOOLS_HXX
#include <basegfx/polygon/b3dpolygontools.hxx>
#endif
#ifndef _BGFX_POLYGON_B3DPOLYGON_HXX
#include <basegfx/polygon/b3dpolygon.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef _BGFX_RANGE_B3DRANGE_HXX
#include <basegfx/range/b3drange.hxx>
#endif
#include <numeric>
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
namespace tools
{
// B3DPolygon tools
void checkClosed(B3DPolygon& rCandidate)
{
while(rCandidate.count() > 1L
&& rCandidate.getB3DPoint(0L).equal(rCandidate.getB3DPoint(rCandidate.count() - 1L)))
{
rCandidate.setClosed(true);
rCandidate.remove(rCandidate.count() - 1L);
}
}
// Get successor and predecessor indices. Returning the same index means there
// is none. Same for successor.
sal_uInt32 getIndexOfPredecessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(nIndex)
{
return nIndex - 1L;
}
else if(rCandidate.count())
{
return rCandidate.count() - 1L;
}
else
{
return nIndex;
}
}
sal_uInt32 getIndexOfSuccessor(sal_uInt32 nIndex, const ::basegfx::B3DPolygon& rCandidate)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
if(nIndex + 1L < rCandidate.count())
{
return nIndex + 1L;
}
else
{
return 0L;
}
}
::basegfx::B3DRange getRange(const ::basegfx::B3DPolygon& rCandidate)
{
::basegfx::B3DRange aRetval;
const sal_uInt32 nPointCount(rCandidate.count());
for(sal_uInt32 a(0L); a < nPointCount; a++)
{
const ::basegfx::B3DPoint aTestPoint(rCandidate.getB3DPoint(a));
aRetval.expand(aTestPoint);
}
return aRetval;
}
double getEdgeLength(const ::basegfx::B3DPolygon& rCandidate, sal_uInt32 nIndex)
{
OSL_ENSURE(nIndex < rCandidate.count(), "getIndexOfPredecessor: Access to polygon out of range (!)");
double fRetval(0.0);
const sal_uInt32 nPointCount(rCandidate.count());
if(nIndex < nPointCount)
{
if(rCandidate.isClosed() || nIndex + 1 != nPointCount)
{
const sal_uInt32 nNextIndex(nIndex + 1 == nPointCount ? 0L : nIndex + 1L);
const ::basegfx::B3DPoint aCurrentPoint(rCandidate.getB3DPoint(nIndex));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
const ::basegfx::B3DVector aVector(aNextPoint - aCurrentPoint);
fRetval = aVector.getLength();
}
}
return fRetval;
}
double getLength(const ::basegfx::B3DPolygon& rCandidate)
{
// This method may also be implemented using a loop over getEdgeLength, but
// since this would cause a lot of sqare roots to be solved it is much better
// to sum up the quadrats first and then use a singe suare root (if necessary)
double fRetval(0.0);
const sal_uInt32 nPointCount(rCandidate.count());
const sal_uInt32 nLoopCount(rCandidate.isClosed() ? nPointCount : nPointCount - 1L);
for(sal_uInt32 a(0L); a < nLoopCount; a++)
{
const sal_uInt32 nNextIndex(a + 1 == nPointCount ? 0L : a + 1L);
const ::basegfx::B3DPoint aCurrentPoint(rCandidate.getB3DPoint(a));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
const ::basegfx::B3DVector aVector(aNextPoint - aCurrentPoint);
fRetval += aVector.scalar(aVector);
}
if(!::basegfx::fTools::equalZero(fRetval))
{
const double fOne(1.0);
if(!::basegfx::fTools::equal(fOne, fRetval))
{
fRetval = sqrt(fRetval);
}
}
return fRetval;
}
::basegfx::B3DPoint getPositionAbsolute(const ::basegfx::B3DPolygon& rCandidate, double fDistance, double fLength)
{
::basegfx::B3DPoint aRetval;
const sal_uInt32 nPointCount(rCandidate.count());
if(nPointCount > 1L)
{
sal_uInt32 nIndex(0L);
bool bIndexDone(false);
const double fZero(0.0);
double fEdgeLength(fZero);
// get length if not given
if(::basegfx::fTools::equalZero(fLength))
{
fLength = getLength(rCandidate);
}
// handle fDistance < 0.0
if(::basegfx::fTools::less(fDistance, fZero))
{
if(rCandidate.isClosed())
{
// if fDistance < 0.0 increment with multiple of fLength
sal_uInt32 nCount(sal_uInt32(-fDistance / fLength));
fDistance += double(nCount + 1L) * fLength;
}
else
{
// crop to polygon start
fDistance = fZero;
bIndexDone = true;
}
}
// handle fDistance >= fLength
if(::basegfx::fTools::moreOrEqual(fDistance, fLength))
{
if(rCandidate.isClosed())
{
// if fDistance >= fLength decrement with multiple of fLength
sal_uInt32 nCount(sal_uInt32(fDistance / fLength));
fDistance -= (double)(nCount) * fLength;
}
else
{
// crop to polygon end
fDistance = fZero;
nIndex = nPointCount - 1L;
bIndexDone = true;
}
}
// look for correct index. fDistance is now [0.0 .. fLength[
if(!bIndexDone)
{
do
{
// get length of next edge
fEdgeLength = getEdgeLength(rCandidate, nIndex);
if(::basegfx::fTools::moreOrEqual(fDistance, fEdgeLength))
{
// go to next edge
fDistance -= fEdgeLength;
nIndex++;
}
else
{
// it's on this edge, stop
bIndexDone = true;
}
} while (!bIndexDone);
}
// get the point using nIndex
aRetval = rCandidate.getB3DPoint(nIndex);
// if fDistance != 0.0, move that length on the edge. The edge
// length is in fEdgeLength.
if(!::basegfx::fTools::equalZero(fDistance))
{
sal_uInt32 nNextIndex(getIndexOfSuccessor(nIndex, rCandidate));
const ::basegfx::B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex));
double fRelative(fZero);
if(!::basegfx::fTools::equalZero(fEdgeLength))
{
fRelative = fDistance / fEdgeLength;
}
// add calculated average value to the return value
aRetval += ::basegfx::interpolate(aRetval, aNextPoint, fRelative);
}
}
return aRetval;
}
::basegfx::B3DPoint getPositionRelative(const ::basegfx::B3DPolygon& rCandidate, double fDistance, double fLength)
{
// get length if not given
if(::basegfx::fTools::equalZero(fLength))
{
fLength = getLength(rCandidate);
}
// multiply fDistance with real length to get absolute position and
// use getPositionAbsolute
return getPositionAbsolute(rCandidate, fDistance * fLength, fLength);
}
::basegfx::B3DPolyPolygon applyLineDashing(const ::basegfx::B3DPolygon& rCandidate, const ::std::vector<double>& raDashDotArray, double fFullDashDotLen)
{
::basegfx::B3DPolyPolygon aRetval;
if(0.0 == fFullDashDotLen && raDashDotArray.size())
{
// calculate fFullDashDotLen from raDashDotArray
fFullDashDotLen = ::std::accumulate(raDashDotArray.begin(), raDashDotArray.end(), 0.0);
}
if(rCandidate.count() && fFullDashDotLen > 0.0)
{
const sal_uInt32 nCount(rCandidate.isClosed() ? rCandidate.count() : rCandidate.count() - 1L);
sal_uInt32 nDashDotIndex(0L);
double fDashDotLength(raDashDotArray[nDashDotIndex]);
for(sal_uInt32 a(0L); a < nCount; a++)
{
const sal_uInt32 nNextIndex(getIndexOfSuccessor(a, rCandidate));
const ::basegfx::B3DPoint aStart(rCandidate.getB3DPoint(a));
const ::basegfx::B3DPoint aEnd(rCandidate.getB3DPoint(nNextIndex));
::basegfx::B3DVector aVector(aEnd - aStart);
double fLength(aVector.getLength());
double fPosOnVector(0.0);
aVector.normalize();
while(fLength >= fDashDotLength)
{
// handle [fPosOnVector .. fPosOnVector+fDashDotLength]
if(nDashDotIndex % 2)
{
::basegfx::B3DPolygon aResult;
// add start point
if(fPosOnVector == 0.0)
{
aResult.append(aStart);
}
else
{
aResult.append( B3DPoint(aStart + (aVector * fPosOnVector)) );
}
// add end point
aResult.append( B3DPoint(aStart + (aVector * (fPosOnVector + fDashDotLength))) );
// add line to PolyPolygon
aRetval.append(aResult);
}
// consume from fDashDotLength
fPosOnVector += fDashDotLength;
fLength -= fDashDotLength;
nDashDotIndex = (nDashDotIndex + 1L) % raDashDotArray.size();
fDashDotLength = raDashDotArray[nDashDotIndex];
}
// handle [fPosOnVector .. fPosOnVector+fLength (bzw. end)]
if((fLength > 0.0) && (nDashDotIndex % 2))
{
::basegfx::B3DPolygon aResult;
// add start and end point
const ::basegfx::B3DPoint aPosA(aStart + (aVector * fPosOnVector));
aResult.append(aPosA);
aResult.append(aEnd);
// add line to PolyPolygon
aRetval.append(aResult);
}
// consume from fDashDotLength
fDashDotLength -= fLength;
}
}
return aRetval;
}
} // end of namespace tools
} // end of namespace basegfx
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/profiler.h>
#include <geos/geom/CoordinateSequence.h>
// FIXME: we should probably not be using CoordinateArraySequenceFactory
#include <geos/geom/CoordinateArraySequenceFactory.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Envelope.h>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
namespace geos {
namespace geom { // geos::geom
#if PROFILE
static Profiler *profiler = Profiler::instance();
#endif
bool
CoordinateSequence::hasRepeatedPoints() const
{
const std::size_t size=getSize();
for(std::size_t i=1; i<size; i++) {
if (getAt(i-1)==getAt(i)) {
return true;
}
}
return false;
}
/*
* Returns either the given coordinate array if its length is greater than the
* given amount, or an empty coordinate array.
*/
CoordinateSequence *
CoordinateSequence::atLeastNCoordinatesOrNothing(size_t n,
CoordinateSequence *c)
{
if ( c->getSize() >= n )
{
return c;
}
else
{
// FIXME: return NULL rather then empty coordinate array
return CoordinateArraySequenceFactory::instance()->create(NULL);
}
}
bool
CoordinateSequence::hasRepeatedPoints(const CoordinateSequence *cl)
{
const std::size_t size=cl->getSize();
for(std::size_t i=1;i<size; i++) {
if (cl->getAt(i-1)==cl->getAt(i)) {
return true;
}
}
return false;
}
const Coordinate*
CoordinateSequence::minCoordinate() const
{
const Coordinate* minCoord=NULL;
const std::size_t size=getSize();
for(std::size_t i=0; i<size; i++) {
if(minCoord==NULL || minCoord->compareTo(getAt(i))>0) {
minCoord=&getAt(i);
}
}
return minCoord;
}
const Coordinate*
CoordinateSequence::minCoordinate(CoordinateSequence *cl)
{
const Coordinate* minCoord=NULL;
const std::size_t size=cl->getSize();
for(std::size_t i=0;i<size; i++) {
if(minCoord==NULL || minCoord->compareTo(cl->getAt(i))>0) {
minCoord=&(cl->getAt(i));
}
}
return minCoord;
}
int
CoordinateSequence::indexOf(const Coordinate *coordinate,
const CoordinateSequence *cl)
{
size_t size=cl->getSize();
for (size_t i=0; i<size; ++i)
{
if ((*coordinate)==cl->getAt(i))
{
return static_cast<int>(i); // FIXME: what if we overflow the int ?
}
}
return -1;
}
void
CoordinateSequence::scroll(CoordinateSequence* cl,
const Coordinate* firstCoordinate)
{
// FIXME: use a standard algorithm instead
std::size_t i, j=0;
std::size_t ind=indexOf(firstCoordinate,cl);
if (ind<1)
return; // not found or already first
const std::size_t length=cl->getSize();
vector<Coordinate> v(length);
for (i=ind; i<length; i++) {
v[j++]=cl->getAt(i);
}
for (i=0; i<ind; i++) {
v[j++]=cl->getAt(i);
}
cl->setPoints(v);
}
int
CoordinateSequence::increasingDirection(const CoordinateSequence& pts)
{
size_t ptsize = pts.size();
for (size_t i=0, n=ptsize/2; i<n; ++i)
{
size_t j = ptsize - 1 - i;
// skip equal points on both ends
int comp = pts[i].compareTo(pts[j]);
if (comp != 0) return comp;
}
// array must be a palindrome - defined to be in positive direction
return 1;
}
void
CoordinateSequence::reverse(CoordinateSequence *cl)
{
// FIXME: use a standard algorithm
int last = static_cast<int>(cl->getSize()) - 1;
int mid=last/2;
for(int i=0;i<=mid;i++) {
const Coordinate tmp=cl->getAt(i);
cl->setAt(cl->getAt(last-i),i);
cl->setAt(tmp,last-i);
}
}
bool
CoordinateSequence::equals(const CoordinateSequence *cl1,
const CoordinateSequence *cl2)
{
// FIXME: use std::equals()
if (cl1==cl2) return true;
if (cl1==NULL||cl2==NULL) return false;
size_t npts1=cl1->getSize();
if (npts1!=cl2->getSize()) return false;
for (size_t i=0; i<npts1; i++) {
if (!(cl1->getAt(i)==cl2->getAt(i))) return false;
}
return true;
}
/*public*/
void
CoordinateSequence::add(const vector<Coordinate>* vc, bool allowRepeated)
{
assert(vc);
for(size_t i=0; i<vc->size(); ++i)
{
add((*vc)[i], allowRepeated);
}
}
/*public*/
void
CoordinateSequence::add(const Coordinate& c, bool allowRepeated)
{
if (!allowRepeated) {
std::size_t npts=getSize();
if (npts>=1) {
const Coordinate& last=getAt(npts-1);
if (last.equals2D(c))
return;
}
}
add(c);
}
/* Here for backward compatibility */
//void
//CoordinateSequence::add(CoordinateSequence *cl, bool allowRepeated,
// bool direction)
//{
// add(cl, allowRepeated, direction);
//}
/*public*/
void
CoordinateSequence::add(const CoordinateSequence *cl,
bool allowRepeated, bool direction)
{
// FIXME: don't rely on negative values for 'j' (the reverse case)
const int npts = static_cast<int>(cl->getSize());
if (direction) {
for (int i=0; i<npts; i++) {
add(cl->getAt(i), allowRepeated);
}
} else {
for (int j=npts-1; j>=0; j--) {
add(cl->getAt(j), allowRepeated);
}
}
}
/*public static*/
CoordinateSequence*
CoordinateSequence::removeRepeatedPoints(const CoordinateSequence *cl)
{
#if PROFILE
static Profile *prof= profiler->get("CoordinateSequence::removeRepeatedPoints()");
prof->start();
#endif
const vector<Coordinate> *v=cl->toVector();
vector<Coordinate> *nv=new vector<Coordinate>;
nv->reserve(v->size());
unique_copy(v->begin(), v->end(), back_inserter(*nv));
CoordinateSequence* ret=CoordinateArraySequenceFactory::instance()->create(nv);
#if PROFILE
prof->stop();
#endif
return ret;
}
void
CoordinateSequence::expandEnvelope(Envelope &env) const
{
const std::size_t size = getSize();
for (std::size_t i=0; i<size; i++)
env.expandToInclude(getAt(i));
}
std::ostream& operator<< (std::ostream& os, const CoordinateSequence& cs)
{
os << "(";
for (size_t i=0, n=cs.size(); i<n; ++i)
{
const Coordinate& c = cs[i];
if ( i ) os << ", ";
os << c;
}
os << ")";
return os;
}
bool operator== ( const CoordinateSequence& s1, const CoordinateSequence& s2)
{
return CoordinateSequence::equals(&s1, &s2);
}
bool operator!= ( const CoordinateSequence& s1, const CoordinateSequence& s2)
{
return ! CoordinateSequence::equals(&s1, &s2);
}
} // namespace geos::geom
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.21 2006/06/12 16:51:23 strk
* Added equality and inequality operators and tests
*
* Revision 1.20 2006/06/12 16:36:22 strk
* indentation, notes about things to be fixed.
*
* Revision 1.19 2006/06/12 10:10:39 strk
* Fixed getGeometryN() to take size_t rather then int, changed unsigned int parameters to size_t.
*
* Revision 1.18 2006/05/03 19:47:27 strk
* added operator<< for CoordinateSequence
*
**********************************************************************/
<commit_msg>std::back_inserter requires <iterator> in geom/CoordinateSequence.cpp<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/profiler.h>
#include <geos/geom/CoordinateSequence.h>
// FIXME: we should probably not be using CoordinateArraySequenceFactory
#include <geos/geom/CoordinateArraySequenceFactory.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Envelope.h>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cassert>
#include <iterator>
using namespace std;
namespace geos {
namespace geom { // geos::geom
#if PROFILE
static Profiler *profiler = Profiler::instance();
#endif
bool
CoordinateSequence::hasRepeatedPoints() const
{
const std::size_t size=getSize();
for(std::size_t i=1; i<size; i++) {
if (getAt(i-1)==getAt(i)) {
return true;
}
}
return false;
}
/*
* Returns either the given coordinate array if its length is greater than the
* given amount, or an empty coordinate array.
*/
CoordinateSequence *
CoordinateSequence::atLeastNCoordinatesOrNothing(size_t n,
CoordinateSequence *c)
{
if ( c->getSize() >= n )
{
return c;
}
else
{
// FIXME: return NULL rather then empty coordinate array
return CoordinateArraySequenceFactory::instance()->create(NULL);
}
}
bool
CoordinateSequence::hasRepeatedPoints(const CoordinateSequence *cl)
{
const std::size_t size=cl->getSize();
for(std::size_t i=1;i<size; i++) {
if (cl->getAt(i-1)==cl->getAt(i)) {
return true;
}
}
return false;
}
const Coordinate*
CoordinateSequence::minCoordinate() const
{
const Coordinate* minCoord=NULL;
const std::size_t size=getSize();
for(std::size_t i=0; i<size; i++) {
if(minCoord==NULL || minCoord->compareTo(getAt(i))>0) {
minCoord=&getAt(i);
}
}
return minCoord;
}
const Coordinate*
CoordinateSequence::minCoordinate(CoordinateSequence *cl)
{
const Coordinate* minCoord=NULL;
const std::size_t size=cl->getSize();
for(std::size_t i=0;i<size; i++) {
if(minCoord==NULL || minCoord->compareTo(cl->getAt(i))>0) {
minCoord=&(cl->getAt(i));
}
}
return minCoord;
}
int
CoordinateSequence::indexOf(const Coordinate *coordinate,
const CoordinateSequence *cl)
{
size_t size=cl->getSize();
for (size_t i=0; i<size; ++i)
{
if ((*coordinate)==cl->getAt(i))
{
return static_cast<int>(i); // FIXME: what if we overflow the int ?
}
}
return -1;
}
void
CoordinateSequence::scroll(CoordinateSequence* cl,
const Coordinate* firstCoordinate)
{
// FIXME: use a standard algorithm instead
std::size_t i, j=0;
std::size_t ind=indexOf(firstCoordinate,cl);
if (ind<1)
return; // not found or already first
const std::size_t length=cl->getSize();
vector<Coordinate> v(length);
for (i=ind; i<length; i++) {
v[j++]=cl->getAt(i);
}
for (i=0; i<ind; i++) {
v[j++]=cl->getAt(i);
}
cl->setPoints(v);
}
int
CoordinateSequence::increasingDirection(const CoordinateSequence& pts)
{
size_t ptsize = pts.size();
for (size_t i=0, n=ptsize/2; i<n; ++i)
{
size_t j = ptsize - 1 - i;
// skip equal points on both ends
int comp = pts[i].compareTo(pts[j]);
if (comp != 0) return comp;
}
// array must be a palindrome - defined to be in positive direction
return 1;
}
void
CoordinateSequence::reverse(CoordinateSequence *cl)
{
// FIXME: use a standard algorithm
int last = static_cast<int>(cl->getSize()) - 1;
int mid=last/2;
for(int i=0;i<=mid;i++) {
const Coordinate tmp=cl->getAt(i);
cl->setAt(cl->getAt(last-i),i);
cl->setAt(tmp,last-i);
}
}
bool
CoordinateSequence::equals(const CoordinateSequence *cl1,
const CoordinateSequence *cl2)
{
// FIXME: use std::equals()
if (cl1==cl2) return true;
if (cl1==NULL||cl2==NULL) return false;
size_t npts1=cl1->getSize();
if (npts1!=cl2->getSize()) return false;
for (size_t i=0; i<npts1; i++) {
if (!(cl1->getAt(i)==cl2->getAt(i))) return false;
}
return true;
}
/*public*/
void
CoordinateSequence::add(const vector<Coordinate>* vc, bool allowRepeated)
{
assert(vc);
for(size_t i=0; i<vc->size(); ++i)
{
add((*vc)[i], allowRepeated);
}
}
/*public*/
void
CoordinateSequence::add(const Coordinate& c, bool allowRepeated)
{
if (!allowRepeated) {
std::size_t npts=getSize();
if (npts>=1) {
const Coordinate& last=getAt(npts-1);
if (last.equals2D(c))
return;
}
}
add(c);
}
/* Here for backward compatibility */
//void
//CoordinateSequence::add(CoordinateSequence *cl, bool allowRepeated,
// bool direction)
//{
// add(cl, allowRepeated, direction);
//}
/*public*/
void
CoordinateSequence::add(const CoordinateSequence *cl,
bool allowRepeated, bool direction)
{
// FIXME: don't rely on negative values for 'j' (the reverse case)
const int npts = static_cast<int>(cl->getSize());
if (direction) {
for (int i=0; i<npts; i++) {
add(cl->getAt(i), allowRepeated);
}
} else {
for (int j=npts-1; j>=0; j--) {
add(cl->getAt(j), allowRepeated);
}
}
}
/*public static*/
CoordinateSequence*
CoordinateSequence::removeRepeatedPoints(const CoordinateSequence *cl)
{
#if PROFILE
static Profile *prof= profiler->get("CoordinateSequence::removeRepeatedPoints()");
prof->start();
#endif
const vector<Coordinate> *v=cl->toVector();
vector<Coordinate> *nv=new vector<Coordinate>;
nv->reserve(v->size());
unique_copy(v->begin(), v->end(), back_inserter(*nv));
CoordinateSequence* ret=CoordinateArraySequenceFactory::instance()->create(nv);
#if PROFILE
prof->stop();
#endif
return ret;
}
void
CoordinateSequence::expandEnvelope(Envelope &env) const
{
const std::size_t size = getSize();
for (std::size_t i=0; i<size; i++)
env.expandToInclude(getAt(i));
}
std::ostream& operator<< (std::ostream& os, const CoordinateSequence& cs)
{
os << "(";
for (size_t i=0, n=cs.size(); i<n; ++i)
{
const Coordinate& c = cs[i];
if ( i ) os << ", ";
os << c;
}
os << ")";
return os;
}
bool operator== ( const CoordinateSequence& s1, const CoordinateSequence& s2)
{
return CoordinateSequence::equals(&s1, &s2);
}
bool operator!= ( const CoordinateSequence& s1, const CoordinateSequence& s2)
{
return ! CoordinateSequence::equals(&s1, &s2);
}
} // namespace geos::geom
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.21 2006/06/12 16:51:23 strk
* Added equality and inequality operators and tests
*
* Revision 1.20 2006/06/12 16:36:22 strk
* indentation, notes about things to be fixed.
*
* Revision 1.19 2006/06/12 10:10:39 strk
* Fixed getGeometryN() to take size_t rather then int, changed unsigned int parameters to size_t.
*
* Revision 1.18 2006/05/03 19:47:27 strk
* added operator<< for CoordinateSequence
*
**********************************************************************/
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <mapnik/line_symbolizer.hpp>
using mapnik::line_symbolizer;
using mapnik::stroke;
using mapnik::color;
void export_line_symbolizer()
{
using namespace boost::python;
class_<line_symbolizer>("LineSymbolizer",
init<>("Default LineSymbolizer - 1px solid black"))
.def(init<stroke const&>("TODO"))
.def(init<color const& ,float>())
.add_property("stroke",make_function
(&line_symbolizer::get_stroke,
return_value_policy<copy_const_reference>()),
&line_symbolizer::set_stroke)
;
}
<commit_msg>+add pickle support to line_symbolizer - see #345<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <mapnik/line_symbolizer.hpp>
using mapnik::line_symbolizer;
using mapnik::stroke;
using mapnik::color;
struct line_symbolizer_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const line_symbolizer& l)
{
return boost::python::make_tuple(l.get_stroke());
}
};
void export_line_symbolizer()
{
using namespace boost::python;
class_<line_symbolizer>("LineSymbolizer",
init<>("Default LineSymbolizer - 1px solid black"))
.def(init<stroke const&>("TODO"))
.def(init<color const& ,float>())
.def_pickle(line_symbolizer_pickle_suite())
.add_property("stroke",make_function
(&line_symbolizer::get_stroke,
return_value_policy<copy_const_reference>()),
&line_symbolizer::set_stroke)
;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: urp_dispatch.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2003-04-28 16:30:10 $
*
* 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 <sal/alloca.h>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>
#include <uno/mapping.hxx>
#include <uno/threadpool.h>
#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
namespace bridges_urp
{
void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
{
MutexGuard guard( pImpl->m_marshalingMutex );
sal_uInt8 nBitfield = 0;
// send immeadiatly
if( ! pImpl->m_blockMarshaler.empty() )
{
pImpl->m_pWriter->touch( sal_True );
}
pImpl->m_pWriter->sendEmptyMessage();
// no more data via this connection !
pImpl->m_pWriter->abort();
}
}
void SAL_CALL urp_sendRequest(
uno_Environment *pEnvRemote,
typelib_TypeDescription * pMemberType,
rtl_uString *pOid,
typelib_InterfaceTypeDescription *pInterfaceType,
void *pReturn,
void *ppArgs[],
uno_Any **ppException )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
ClientJob job(pEnvRemote, pImpl, pOid, pMemberType, pInterfaceType, pReturn, ppArgs, ppException);
if( job.pack() && ! job.isOneway() )
{
job.wait();
}
}
}
<commit_msg>INTEGRATION: CWS ooo20040329 (1.11.90); FILE MERGED 2004/03/17 11:18:54 waratah 1.11.90.1: #i1858# remove unused variable Correct spelling mistake in a comment<commit_after>/*************************************************************************
*
* $RCSfile: urp_dispatch.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 13:44:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <sal/alloca.h>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>
#include <uno/mapping.hxx>
#include <uno/threadpool.h>
#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
namespace bridges_urp
{
void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
{
MutexGuard guard( pImpl->m_marshalingMutex );
// send immediately
if( ! pImpl->m_blockMarshaler.empty() )
{
pImpl->m_pWriter->touch( sal_True );
}
pImpl->m_pWriter->sendEmptyMessage();
// no more data via this connection !
pImpl->m_pWriter->abort();
}
}
void SAL_CALL urp_sendRequest(
uno_Environment *pEnvRemote,
typelib_TypeDescription * pMemberType,
rtl_uString *pOid,
typelib_InterfaceTypeDescription *pInterfaceType,
void *pReturn,
void *ppArgs[],
uno_Any **ppException )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
ClientJob job(pEnvRemote, pImpl, pOid, pMemberType, pInterfaceType, pReturn, ppArgs, ppException);
if( job.pack() && ! job.isOneway() )
{
job.wait();
}
}
}
<|endoftext|> |
<commit_before>#ifndef __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__
#define __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <istream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <stdexcept>
#include <boost/spirit/include/qi.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/spirit/include/version.hpp>
#include <boost/spirit/home/support/iterators/line_pos_iterator.hpp>
#include <stan/gm/ast.hpp>
#include <stan/gm/grammars/whitespace_grammar.hpp>
#include <stan/gm/grammars/expression_grammar.hpp>
#include <stan/gm/grammars/var_decls_grammar.hpp>
#include <stan/gm/grammars/statement_grammar.hpp>
#include <stan/gm/grammars/program_grammar.hpp>
namespace {
// hack to pass pair into macro below to adapt; in namespace to hide
struct DUMMY_STRUCT {
typedef std::pair<std::vector<stan::gm::var_decl>,
std::vector<stan::gm::statement> > type;
};
}
BOOST_FUSION_ADAPT_STRUCT(stan::gm::program,
(std::vector<stan::gm::var_decl>, data_decl_)
(DUMMY_STRUCT::type, derived_data_decl_)
(std::vector<stan::gm::var_decl>, parameter_decl_)
(DUMMY_STRUCT::type, derived_decl_)
(stan::gm::statement, statement_)
(DUMMY_STRUCT::type, generated_decl_) )
namespace stan {
namespace gm {
struct add_lp_var {
template <typename T>
struct result { typedef void type; };
void operator()(variable_map& vm) const {
vm.add("lp__",
base_var_decl("lp__",std::vector<expression>(),DOUBLE_T),
local_origin); // lp acts as a local where defined
}
};
boost::phoenix::function<add_lp_var> add_lp_var_f;
struct remove_lp_var {
template <typename T>
struct result { typedef void type; };
void operator()(variable_map& vm) const {
vm.remove("lp__");
}
};
boost::phoenix::function<remove_lp_var> remove_lp_var_f;
struct program_error {
template <typename T1, typename T2, typename ,
typename T4, typename T5, typename T6, typename T7>
struct result { typedef void type; };
template <class Iterator, class I>
void operator()(
Iterator _begin,
Iterator _end,
Iterator _where,
I const& _info,
std::string msg,
variable_map& vm,
std::stringstream& error_msgs) const {
error_msgs << msg
<< std::endl;
using boost::phoenix::construct;
using boost::phoenix::val;
std::basic_stringstream<char> pre_error_section;
pre_error_section << boost::make_iterator_range (_begin, _where);
char last_char;
std::string correct_section = "";
while (!pre_error_section.eof()) {
last_char = (char)pre_error_section.get();
correct_section += last_char;
}
size_t indx = correct_section.size();
correct_section = correct_section.erase(indx-1, indx);
//
// Clean up whatever is before the error occurred
//
// Would be better to use the parser to select which
// section in the stan file contains the parsing error.
//
std::vector<std::string> sections;
sections.push_back("generated");
sections.push_back("model");
sections.push_back("transformed");
sections.push_back("parameter");
sections.push_back("data");
//bool found_section = false; // FIXME: do something with found_section
indx = 0;
for (size_t i = 0; i < sections.size(); ++i) {
std::string section = sections[i];
indx = correct_section.find(section);
if (!(indx == std::string::npos)) {
if (i == 2) {
// Check which transformed block we're dealing with.
// If there is another transformed section, it must be
// a 'transformed parameters' section
int indx2 = correct_section.find("transformed", indx + 5);
if (!(indx2 == std::string::npos)) {
indx = indx2;
} else {
// No second transformed section, but maybe there
// is a parameter block?
indx2 = correct_section.find("parameters", indx2);
if (!(indx2 == std::string::npos)) {
indx = indx2;
}
// Ok, we found a 'transformed data' block.
// indx is pointing at it.
}
}
//found_section = true;
correct_section = correct_section.erase(0, indx);
break;
}
}
//
// Clean up whatever comes after the error occurred
//
std::basic_stringstream<char> error_section;
error_section << boost::make_iterator_range (_where, _end);
last_char = ' ';
std::string rest_of_section = "";
while (!error_section.eof() && !(last_char == '}')) {
last_char = (char)error_section.get();
rest_of_section += last_char;
//std::cout << rest_of_section.size() << std::endl;
if (error_section.eof() && rest_of_section.size() == 1) {
rest_of_section = "'end of file'";
}
}
if (!(get_line(_where) == std::string::npos)) {
error_msgs
<< std::endl
<< "LOCATION OF PARSING ERROR (line = "
<< get_line(_where)
<< ", position = "
<< get_column(_begin, _where) - 1
<< "):"
<< std::endl
<< std::endl
<< "PARSED:"
<< std::endl
<< std::endl
<< correct_section
<< std::endl
<< std::endl
<< "EXPECTED: " << _info
<< " BUT FOUND: "
<< std::endl
<< std::endl
<< rest_of_section
<< std::endl;
}
}
};
boost::phoenix::function<program_error> program_error_f;
template <typename Iterator>
program_grammar<Iterator>::program_grammar(const std::string& model_name)
: program_grammar::base_type(program_r),
model_name_(model_name),
var_map_(),
error_msgs_(),
expression_g(var_map_,error_msgs_),
var_decls_g(var_map_,error_msgs_),
statement_g(var_map_,error_msgs_) {
using boost::spirit::qi::eps;
using boost::spirit::qi::lit;
// add model_name to var_map with special origin and no
var_map_.add(model_name,
base_var_decl(),
model_name_origin);
program_r.name("program");
program_r
%= -data_var_decls_r
> -derived_data_var_decls_r
> -param_var_decls_r
// scope lp__ to "transformed params" and "model" only
> eps[add_lp_var_f(boost::phoenix::ref(var_map_))]
> -derived_var_decls_r
> model_r
> eps[remove_lp_var_f(boost::phoenix::ref(var_map_))]
> -generated_var_decls_r
;
model_r.name("model declaration");
model_r
%= lit("model")
> statement_g(true,local_origin) // assign only to locals
;
data_var_decls_r.name("data variable declarations");
data_var_decls_r
%= lit("data")
> lit('{')
> var_decls_g(true,data_origin) // +constraints
> lit('}');
derived_data_var_decls_r.name("transformed data block");
derived_data_var_decls_r
%= ( lit("transformed")
>> lit("data") )
> lit('{')
> var_decls_g(true,transformed_data_origin) // -constraints
> *statement_g(false,transformed_data_origin) // -sampling
> lit('}');
param_var_decls_r.name("parameter variable declarations");
param_var_decls_r
%= lit("parameters")
> lit('{')
> var_decls_g(true,parameter_origin) // +constraints
> lit('}');
derived_var_decls_r.name("derived variable declarations");
derived_var_decls_r
%= ( lit("transformed")
>> lit("parameters") )
> lit('{')
> var_decls_g(true,transformed_parameter_origin) // -constraints
> *statement_g(false,transformed_parameter_origin) // -sampling
> lit('}');
generated_var_decls_r.name("generated variable declarations");
generated_var_decls_r
%= lit("generated")
> lit("quantities")
> lit('{')
> var_decls_g(true,derived_origin) // -constraints
> *statement_g(false,derived_origin) // -sampling
> lit('}');
using boost::spirit::qi::on_error;
using boost::spirit::qi::rethrow;
using namespace boost::spirit::qi::labels;
on_error<rethrow>(
program_r,
program_error_f(
_1, _2, _3, _4 ,
"",
boost::phoenix::ref(var_map_),
boost::phoenix::ref(error_msgs_)
)
);
}
}
}
#endif
<commit_msg>Fixing unsigned warning.<commit_after>#ifndef __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__
#define __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <istream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <stdexcept>
#include <boost/spirit/include/qi.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/spirit/include/version.hpp>
#include <boost/spirit/home/support/iterators/line_pos_iterator.hpp>
#include <stan/gm/ast.hpp>
#include <stan/gm/grammars/whitespace_grammar.hpp>
#include <stan/gm/grammars/expression_grammar.hpp>
#include <stan/gm/grammars/var_decls_grammar.hpp>
#include <stan/gm/grammars/statement_grammar.hpp>
#include <stan/gm/grammars/program_grammar.hpp>
namespace {
// hack to pass pair into macro below to adapt; in namespace to hide
struct DUMMY_STRUCT {
typedef std::pair<std::vector<stan::gm::var_decl>,
std::vector<stan::gm::statement> > type;
};
}
BOOST_FUSION_ADAPT_STRUCT(stan::gm::program,
(std::vector<stan::gm::var_decl>, data_decl_)
(DUMMY_STRUCT::type, derived_data_decl_)
(std::vector<stan::gm::var_decl>, parameter_decl_)
(DUMMY_STRUCT::type, derived_decl_)
(stan::gm::statement, statement_)
(DUMMY_STRUCT::type, generated_decl_) )
namespace stan {
namespace gm {
struct add_lp_var {
template <typename T>
struct result { typedef void type; };
void operator()(variable_map& vm) const {
vm.add("lp__",
base_var_decl("lp__",std::vector<expression>(),DOUBLE_T),
local_origin); // lp acts as a local where defined
}
};
boost::phoenix::function<add_lp_var> add_lp_var_f;
struct remove_lp_var {
template <typename T>
struct result { typedef void type; };
void operator()(variable_map& vm) const {
vm.remove("lp__");
}
};
boost::phoenix::function<remove_lp_var> remove_lp_var_f;
struct program_error {
template <typename T1, typename T2, typename ,
typename T4, typename T5, typename T6, typename T7>
struct result { typedef void type; };
template <class Iterator, class I>
void operator()(
Iterator _begin,
Iterator _end,
Iterator _where,
I const& _info,
std::string msg,
variable_map& vm,
std::stringstream& error_msgs) const {
error_msgs << msg
<< std::endl;
using boost::phoenix::construct;
using boost::phoenix::val;
std::basic_stringstream<char> pre_error_section;
pre_error_section << boost::make_iterator_range (_begin, _where);
char last_char;
std::string correct_section = "";
while (!pre_error_section.eof()) {
last_char = (char)pre_error_section.get();
correct_section += last_char;
}
size_t indx = correct_section.size();
correct_section = correct_section.erase(indx-1, indx);
//
// Clean up whatever is before the error occurred
//
// Would be better to use the parser to select which
// section in the stan file contains the parsing error.
//
std::vector<std::string> sections;
sections.push_back("generated");
sections.push_back("model");
sections.push_back("transformed");
sections.push_back("parameter");
sections.push_back("data");
//bool found_section = false; // FIXME: do something with found_section
indx = 0;
for (size_t i = 0; i < sections.size(); ++i) {
std::string section = sections[i];
indx = correct_section.find(section);
if (!(indx == std::string::npos)) {
if (i == 2) {
// Check which transformed block we're dealing with.
// If there is another transformed section, it must be
// a 'transformed parameters' section
size_t indx2 = correct_section.find("transformed", indx + 5);
if (!(indx2 == std::string::npos)) {
indx = indx2;
} else {
// No second transformed section, but maybe there
// is a parameter block?
indx2 = correct_section.find("parameters", indx2);
if (!(indx2 == std::string::npos)) {
indx = indx2;
}
// Ok, we found a 'transformed data' block.
// indx is pointing at it.
}
}
//found_section = true;
correct_section = correct_section.erase(0, indx);
break;
}
}
//
// Clean up whatever comes after the error occurred
//
std::basic_stringstream<char> error_section;
error_section << boost::make_iterator_range (_where, _end);
last_char = ' ';
std::string rest_of_section = "";
while (!error_section.eof() && !(last_char == '}')) {
last_char = (char)error_section.get();
rest_of_section += last_char;
//std::cout << rest_of_section.size() << std::endl;
if (error_section.eof() && rest_of_section.size() == 1) {
rest_of_section = "'end of file'";
}
}
if (!(get_line(_where) == std::string::npos)) {
error_msgs
<< std::endl
<< "LOCATION OF PARSING ERROR (line = "
<< get_line(_where)
<< ", position = "
<< get_column(_begin, _where) - 1
<< "):"
<< std::endl
<< std::endl
<< "PARSED:"
<< std::endl
<< std::endl
<< correct_section
<< std::endl
<< std::endl
<< "EXPECTED: " << _info
<< " BUT FOUND: "
<< std::endl
<< std::endl
<< rest_of_section
<< std::endl;
}
}
};
boost::phoenix::function<program_error> program_error_f;
template <typename Iterator>
program_grammar<Iterator>::program_grammar(const std::string& model_name)
: program_grammar::base_type(program_r),
model_name_(model_name),
var_map_(),
error_msgs_(),
expression_g(var_map_,error_msgs_),
var_decls_g(var_map_,error_msgs_),
statement_g(var_map_,error_msgs_) {
using boost::spirit::qi::eps;
using boost::spirit::qi::lit;
// add model_name to var_map with special origin and no
var_map_.add(model_name,
base_var_decl(),
model_name_origin);
program_r.name("program");
program_r
%= -data_var_decls_r
> -derived_data_var_decls_r
> -param_var_decls_r
// scope lp__ to "transformed params" and "model" only
> eps[add_lp_var_f(boost::phoenix::ref(var_map_))]
> -derived_var_decls_r
> model_r
> eps[remove_lp_var_f(boost::phoenix::ref(var_map_))]
> -generated_var_decls_r
;
model_r.name("model declaration");
model_r
%= lit("model")
> statement_g(true,local_origin) // assign only to locals
;
data_var_decls_r.name("data variable declarations");
data_var_decls_r
%= lit("data")
> lit('{')
> var_decls_g(true,data_origin) // +constraints
> lit('}');
derived_data_var_decls_r.name("transformed data block");
derived_data_var_decls_r
%= ( lit("transformed")
>> lit("data") )
> lit('{')
> var_decls_g(true,transformed_data_origin) // -constraints
> *statement_g(false,transformed_data_origin) // -sampling
> lit('}');
param_var_decls_r.name("parameter variable declarations");
param_var_decls_r
%= lit("parameters")
> lit('{')
> var_decls_g(true,parameter_origin) // +constraints
> lit('}');
derived_var_decls_r.name("derived variable declarations");
derived_var_decls_r
%= ( lit("transformed")
>> lit("parameters") )
> lit('{')
> var_decls_g(true,transformed_parameter_origin) // -constraints
> *statement_g(false,transformed_parameter_origin) // -sampling
> lit('}');
generated_var_decls_r.name("generated variable declarations");
generated_var_decls_r
%= lit("generated")
> lit("quantities")
> lit('{')
> var_decls_g(true,derived_origin) // -constraints
> *statement_g(false,derived_origin) // -sampling
> lit('}');
using boost::spirit::qi::on_error;
using boost::spirit::qi::rethrow;
using namespace boost::spirit::qi::labels;
on_error<rethrow>(
program_r,
program_error_f(
_1, _2, _3, _4 ,
"",
boost::phoenix::ref(var_map_),
boost::phoenix::ref(error_msgs_)
)
);
}
}
}
#endif
<|endoftext|> |
<commit_before>/* ****************************************************************************
*
* FILE SamsonSupervisor.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Dec 15 2010
*
*/
#include "logMsg.h" // LM_*
#include "traceLevels.h" // LMT_*
#include "baTerm.h" // baTermSetup
#include "globals.h" // tabManager, ...
#include "ports.h" // WORKER_PORT, ...
#include "NetworkInterface.h" // DataReceiverInterface, EndpointUpdateInterface
#include "Endpoint.h" // Endpoint
#include "Network.h" // Network
#include "iomConnect.h" // iomConnect
#include "Message.h" // ss::Message::Header
#include "qt.h" // qtRun, ...
#include "actions.h" // help, list, start, ...
#include "Starter.h" // Starter
#include "Spawner.h" // Spawner
#include "Process.h" // Process
#include "starterList.h" // starterLookup
#include "spawnerList.h" // spawnerListGet, ...
#include "processList.h" // processListGet, ...
#include "SamsonSupervisor.h" // Own interface
/* ****************************************************************************
*
* SamsonSupervisor::receive -
*/
int SamsonSupervisor::receive(int fromId, int nb, ss::Message::Header* headerP, void* dataP)
{
ss::Endpoint* ep = networkP->endpointLookup(fromId);
if (ep == NULL)
LM_RE(0, ("Cannot find endpoint with id %d", fromId));
if (ep->type == ss::Endpoint::Fd)
{
char* msg = (char*) dataP;
printf("\n");
switch (*msg)
{
case 'h':
help();
break;
case 'c':
connectToAllSpawners();
break;
case 'p':
startAllProcesses();
break;
case 's':
start();
break;
case 'l':
list();
break;
case 3:
LM_X(0, ("'Ctrl-C' pressed - I quit!"));
case 'q':
LM_X(0, ("'q' pressed - I quit!"));
case ' ':
case '\n':
printf("\n");
break;
default:
LM_E(("Key '%c' has no function", *msg));
help();
}
printf("\n");
return 0;
}
switch (headerP->code)
{
case ss::Message::WorkerSpawn:
case ss::Message::ControllerSpawn:
default:
LM_X(1, ("Don't know how to treat '%s' message", ss::Message::messageCode(headerP->code)));
}
return 0;
}
/* ****************************************************************************
*
* disconnectAllWorkers -
*/
void disconnectAllWorkers(void)
{
unsigned int ix;
std::vector<ss::Endpoint*> epV;
epV = networkP->samsonWorkerEndpoints();
LM_M(("Got %d endpoints", epV.size()));
for (ix = 0; ix < epV.size(); ix++)
{
ss::Endpoint* ep;
ep = epV[ix];
if (ep->type == ss::Endpoint::Worker)
{
LM_W(("Closing connection to Worker %02d: %-20s %-20s %s", ix, ep->name.c_str(), ep->ip.c_str(), ep->stateName()));
close(ep->wFd);
networkP->endpointRemove(ep, "Disconnecting all workers");
}
}
}
/* ****************************************************************************
*
* SamsonSupervisor::endpointUpdate -
*/
int SamsonSupervisor::endpointUpdate(ss::Endpoint* ep, ss::Endpoint::UpdateReason reason, const char* reasonText, void* info)
{
Starter* starter;
ss::Endpoint* newEp = (ss::Endpoint*) info;
if (reason == ss::Endpoint::SelectToBeCalled)
{
starterListShow("periodic");
return 0;
}
if (ep != NULL)
LM_M(("********************* Got an Update Notification ('%s') for endpoint %p '%s' at '%s'", reasonText, ep, ep->name.c_str(), ep->ip.c_str()));
else
LM_M(("********************* Got an Update Notification ('%s') for NULL endpoint", reasonText));
LM_M(("looking for starter with endpoint %p", ep));
starterListShow("Before starterLookup");
starter = starterLookup(ep);
starterListShow("After starterLookup");
LM_M(("starterLookup(%p) returned %p", ep, starter));
if (starter != NULL)
LM_M(("found %s-starter '%s'", starter->typeName(), starter->name));
switch (reason)
{
case ss::Endpoint::NoLongerTemporal:
if (ep->type != ss::Endpoint::Temporal)
LM_X(1, ("BUG - endpoint not temporal"));
if ((newEp->type != ss::Endpoint::Worker) && (newEp->type != ss::Endpoint::Spawner))
LM_X(1, ("BUG - new endpoint should be either Worker or Spawner - is '%s'", newEp->typeName()));
if (starter != NULL)
{
LM_M(("fds for temporal endpoint: r:%d w:%d", ep->rFd, ep->wFd));
LM_M(("fds for new endpoint: r:%d w:%d", newEp->rFd, newEp->wFd));
LM_M(("Changing temporal endpoint %p for '%s' endpoint %p", ep, newEp->typeName(), newEp));
starter->endpoint = newEp;
starter->check();
return 0;
}
else
{
Process* processP = NULL;
Spawner* spawnerP = NULL;
LM_W(("%s: starter not found for '%s' endpoint '%s' at '%s'", reasonText, ep->typeName(), ep->name.c_str(), ep->ip.c_str()));
LM_W(("Lookup spawner/process instead!"));
processP = processLookup((char*) ep->name.c_str(), (char*) ep->ip.c_str());
if (processP != NULL)
LM_M(("Found process! Setting its endpoint to this one ..."));
else
{
LM_W(("Cannot find process '%s' at '%s' - trying spawner", ep->name.c_str(), ep->ip.c_str()));
spawnerP = spawnerLookup((char*) ep->ip.c_str());
if (spawnerP != NULL)
LM_M(("Found spawner! Setting its endpoint to this one ..."));
else
LM_W(("Nothing found ..."));
}
}
break;
case ss::Endpoint::WorkerDisconnected:
if (starter == NULL)
LM_RE(-1, ("NULL starter for '%s'", reasonText));
starter->check();
break;
case ss::Endpoint::ControllerDisconnected:
LM_W(("Controller disconnected - I should now disconnect from all workers ..."));
LM_W(("... to reconnect to workers when controller is back"));
break;
case ss::Endpoint::ControllerRemoved:
case ss::Endpoint::WorkerRemoved:
case ss::Endpoint::EndpointRemoved:
LM_M(("Endpoint removed"));
if (starter == NULL)
LM_RE(-1, ("NULL starter for '%s'", reasonText));
starter->check();
break;
case ss::Endpoint::ControllerAdded:
case ss::Endpoint::ControllerReconnected:
case ss::Endpoint::HelloReceived:
case ss::Endpoint::WorkerAdded:
LM_W(("Got a '%s' endpoint-update-reason and I take no action ...", reasonText));
break;
case ss::Endpoint::SelectToBeCalled:
starterListShow("periodic");
break;
}
#if 0
if ((networkP->controller != NULL) && (networkP->controller->state != ss::Endpoint::Connected))
{
if (networkP->controller->state != ss::Endpoint::Unconnected)
{
LM_W(("Seems like the controller died (controller in state '%s') - disconnecting all workers", networkP->controller->stateName()));
disconnectAllWorkers();
return 0;
}
else
LM_M(("controller is unconnected - no action"));
}
if (strcmp(reason, "no longer temporal") == 0)
{
ss::Endpoint* newEp = (ss::Endpoint*) info;
if (ep->type != ss::Endpoint::Temporal)
LM_X(1, ("BUG - endpoint not temporal"));
if ((newEp->type != ss::Endpoint::Worker) && (newEp->type != ss::Endpoint::Spawner))
LM_X(1, ("BUG - new endpoint not ss::Endpoint::Worker nor ss::Endpoint::Spawner"));
}
if ((starter != NULL) && (info != NULL))
{
ss::Endpoint* newEp = (ss::Endpoint*) info;
if ((newEp->type == ss::Endpoint::Worker) && (ep->type == ss::Endpoint::Temporal))
{
LM_M(("Probably a 'Worker No longer temporal' - changing endpoint pointer for starter '%s' type '%s'", starter->name, starter->type));
starter->endpoint = newEp;
starter->check();
return 0;
}
LM_RE(-1, ("Don't know how I got here ... (starter: %s, type: %s", starter->name, starter->type));
}
if ((starter == NULL) && (info != NULL))
{
starter = starterLookup((ss::Endpoint*) info);
ep = (ss::Endpoint*) info;
}
if (starter == NULL)
{
LM_M(("********************* Cannot find starter for endpoint at %p (%p)", ep, info));
return -1;
}
LM_T(LMT_STARTER, ("Found starter '%s'", starter->name));
starter->endpoint = ep;
starter->check();
#endif
return 0;
}
/* ****************************************************************************
*
* runQtAsThread -
*/
void* runQtAsThread(void* nP)
{
int argC = 1;
const char* argV[2] = { "samsonSupervisor", NULL };
qtRun(argC, argV);
LM_X(1, ("Back from qtRun !"));
return NULL;
}
/* ****************************************************************************
*
* SamsonSupervisor::ready -
*/
int SamsonSupervisor::ready(const char* info)
{
unsigned int ix;
std::vector<ss::Endpoint*> epV;
static bool firstTime = true;
LM_M(("---- Network READY - %s --------------------------", info));
epV = networkP->samsonWorkerEndpoints();
LM_M(("Got %d endpoints", epV.size()));
for (ix = 0; ix < epV.size(); ix++)
{
ss::Endpoint* ep;
ep = epV[ix];
LM_M(("%02d: %-20s %-20s %s", ix, ep->name.c_str(), ep->ip.c_str(), ep->stateName()));
}
if (firstTime == true)
{
// Connecting to all spawners
Spawner** spawnerV;
unsigned int spawners;
spawners = spawnerMaxGet();
spawnerV = spawnerListGet();
LM_M(("Connecting to all %d spawners", spawners));
for (ix = 0; ix < spawners; ix++)
{
int s;
if (spawnerV[ix] == NULL)
continue;
LM_M(("Connecting to spawner in host '%s'", spawnerV[ix]->host));
s = iomConnect(spawnerV[ix]->host, SPAWNER_PORT);
spawnerV[ix]->fd = s;
if (s == -1)
LM_E(("Error connecting to spawner in %s (port %d)", spawnerV[ix]->host, SPAWNER_PORT));
else
networkP->endpointAdd(s, s, (char*) "Spawner", "Spawner", 0, ss::Endpoint::Temporal, spawnerV[ix]->host, SPAWNER_PORT);
}
}
networkReady = true; // Is this true if Controller not running ?
firstTime = false;
return 0;
}
<commit_msg>workers ok when reconnecting to controller<commit_after>/* ****************************************************************************
*
* FILE SamsonSupervisor.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Dec 15 2010
*
*/
#include "logMsg.h" // LM_*
#include "traceLevels.h" // LMT_*
#include "baTerm.h" // baTermSetup
#include "globals.h" // tabManager, ...
#include "ports.h" // WORKER_PORT, ...
#include "NetworkInterface.h" // DataReceiverInterface, EndpointUpdateInterface
#include "Endpoint.h" // Endpoint
#include "Network.h" // Network
#include "iomConnect.h" // iomConnect
#include "Message.h" // ss::Message::Header
#include "qt.h" // qtRun, ...
#include "actions.h" // help, list, start, ...
#include "Starter.h" // Starter
#include "Spawner.h" // Spawner
#include "Process.h" // Process
#include "starterList.h" // starterLookup
#include "spawnerList.h" // spawnerListGet, ...
#include "processList.h" // processListGet, ...
#include "SamsonSupervisor.h" // Own interface
/* ****************************************************************************
*
* SamsonSupervisor::receive -
*/
int SamsonSupervisor::receive(int fromId, int nb, ss::Message::Header* headerP, void* dataP)
{
ss::Endpoint* ep = networkP->endpointLookup(fromId);
if (ep == NULL)
LM_RE(0, ("Cannot find endpoint with id %d", fromId));
if (ep->type == ss::Endpoint::Fd)
{
char* msg = (char*) dataP;
printf("\n");
switch (*msg)
{
case 'h':
help();
break;
case 'c':
connectToAllSpawners();
break;
case 'p':
startAllProcesses();
break;
case 's':
start();
break;
case 'l':
list();
break;
case 3:
LM_X(0, ("'Ctrl-C' pressed - I quit!"));
case 'q':
LM_X(0, ("'q' pressed - I quit!"));
case ' ':
case '\n':
printf("\n");
break;
default:
LM_E(("Key '%c' has no function", *msg));
help();
}
printf("\n");
return 0;
}
switch (headerP->code)
{
case ss::Message::WorkerSpawn:
case ss::Message::ControllerSpawn:
default:
LM_X(1, ("Don't know how to treat '%s' message", ss::Message::messageCode(headerP->code)));
}
return 0;
}
/* ****************************************************************************
*
* disconnectAllWorkers -
*/
void disconnectAllWorkers(void)
{
unsigned int ix;
std::vector<ss::Endpoint*> epV;
epV = networkP->samsonWorkerEndpoints();
LM_M(("Got %d endpoints", epV.size()));
for (ix = 0; ix < epV.size(); ix++)
{
ss::Endpoint* ep;
ep = epV[ix];
if (ep->type == ss::Endpoint::Worker)
{
LM_W(("Closing connection to Worker %02d: %-20s %-20s %s", ix, ep->name.c_str(), ep->ip.c_str(), ep->stateName()));
close(ep->wFd);
networkP->endpointRemove(ep, "Disconnecting all workers");
}
}
}
/* ****************************************************************************
*
* noLongerTemporal -
*/
static void noLongerTemporal(ss::Endpoint* ep, ss::Endpoint* newEp, Starter* starter)
{
Process* processP = NULL;
Spawner* spawnerP = NULL;
if (ep->type != ss::Endpoint::Temporal)
LM_X(1, ("BUG - endpoint not temporal"));
if ((newEp->type != ss::Endpoint::Worker) && (newEp->type != ss::Endpoint::Spawner))
LM_X(1, ("BUG - new endpoint should be either Worker or Spawner - is '%s'", newEp->typeName()));
if (starter != NULL)
{
LM_M(("Changing temporal endpoint %p for '%s' endpoint %p", ep, newEp->typeName(), newEp));
starter->endpoint = newEp;
starter->check();
return;
}
LM_W(("starter not found for '%s' endpoint '%s' at '%s'", ep->typeName(), ep->name.c_str(), ep->ip.c_str()));
LM_W(("Lookup spawner/process instead!"));
processP = processLookup((char*) ep->name.c_str(), (char*) ep->ip.c_str());
if (processP != NULL)
LM_M(("Found process! Setting its endpoint to this one ..."));
else
{
LM_W(("Cannot find process '%s' at '%s' - trying spawner", ep->name.c_str(), ep->ip.c_str()));
spawnerP = spawnerLookup((char*) ep->ip.c_str());
if (spawnerP != NULL)
LM_M(("Found spawner! Setting its endpoint to this one ... ?"));
else
LM_W(("Nothing found ..."));
}
}
/* ****************************************************************************
*
* disconnectWorkers -
*/
static void disconnectWorkers(void)
{
Starter** starterV;
unsigned int starterMax;
unsigned int ix;
LM_W(("Controller disconnected - I should now disconnect from all workers ..."));
LM_W(("... to reconnect to workers when controller is back"));
starterV = starterListGet();
starterMax = starterMaxGet();
for (ix = 0; ix < starterMax; ix++)
{
if (starterV[ix] == NULL)
continue;
if (starterV[ix]->endpoint == NULL)
continue;
if (starterV[ix]->endpoint->type != ss::Endpoint::Worker)
continue;
LM_W(("Removing endpoint for worker in %s", starterV[ix]->endpoint->ip.c_str()));
networkP->endpointRemove(starterV[ix]->endpoint, "Controller disconnected");
}
}
/* ****************************************************************************
*
* SamsonSupervisor::endpointUpdate -
*/
int SamsonSupervisor::endpointUpdate(ss::Endpoint* ep, ss::Endpoint::UpdateReason reason, const char* reasonText, void* info)
{
Starter* starter;
ss::Endpoint* newEp = (ss::Endpoint*) info;
if (reason == ss::Endpoint::SelectToBeCalled)
{
starterListShow("periodic");
return 0;
}
if (ep != NULL)
LM_M(("********************* Got an Update Notification ('%s') for endpoint %p '%s' at '%s'", reasonText, ep, ep->name.c_str(), ep->ip.c_str()));
else
LM_M(("********************* Got an Update Notification ('%s') for NULL endpoint", reasonText));
LM_M(("looking for starter with endpoint %p", ep));
starterListShow("Before starterLookup");
starter = starterLookup(ep);
starterListShow("After starterLookup");
LM_M(("starterLookup(%p) returned %p", ep, starter));
if (starter != NULL)
LM_M(("found %s-starter '%s'", starter->typeName(), starter->name));
switch (reason)
{
case ss::Endpoint::NoLongerTemporal:
noLongerTemporal(ep, newEp, starter);
break;
case ss::Endpoint::WorkerDisconnected:
case ss::Endpoint::WorkerAdded:
if (starter == NULL)
LM_RE(-1, ("NULL starter for '%s'", reasonText));
starter->check();
break;
case ss::Endpoint::ControllerDisconnected:
disconnectWorkers();
break;
case ss::Endpoint::ControllerRemoved:
case ss::Endpoint::WorkerRemoved:
case ss::Endpoint::EndpointRemoved:
LM_M(("Endpoint removed"));
if (starter == NULL)
LM_RE(-1, ("NULL starter for '%s'", reasonText));
starter->check();
break;
case ss::Endpoint::ControllerAdded:
case ss::Endpoint::ControllerReconnected:
case ss::Endpoint::HelloReceived:
LM_W(("Got a '%s' endpoint-update-reason and I take no action ...", reasonText));
break;
case ss::Endpoint::SelectToBeCalled:
starterListShow("periodic");
break;
}
return 0;
}
/* ****************************************************************************
*
* runQtAsThread -
*/
void* runQtAsThread(void* nP)
{
int argC = 1;
const char* argV[2] = { "samsonSupervisor", NULL };
qtRun(argC, argV);
LM_X(1, ("Back from qtRun !"));
return NULL;
}
/* ****************************************************************************
*
* SamsonSupervisor::ready -
*/
int SamsonSupervisor::ready(const char* info)
{
unsigned int ix;
std::vector<ss::Endpoint*> epV;
static bool firstTime = true;
LM_M(("---- Network READY - %s --------------------------", info));
epV = networkP->samsonWorkerEndpoints();
LM_M(("Got %d endpoints", epV.size()));
for (ix = 0; ix < epV.size(); ix++)
{
ss::Endpoint* ep;
ep = epV[ix];
LM_M(("%02d: %-20s %-20s %s", ix, ep->name.c_str(), ep->ip.c_str(), ep->stateName()));
}
if (firstTime == true)
{
// Connecting to all spawners
Spawner** spawnerV;
unsigned int spawners;
spawners = spawnerMaxGet();
spawnerV = spawnerListGet();
LM_M(("Connecting to all %d spawners", spawners));
for (ix = 0; ix < spawners; ix++)
{
int s;
if (spawnerV[ix] == NULL)
continue;
LM_M(("Connecting to spawner in host '%s'", spawnerV[ix]->host));
s = iomConnect(spawnerV[ix]->host, SPAWNER_PORT);
spawnerV[ix]->fd = s;
if (s == -1)
LM_E(("Error connecting to spawner in %s (port %d)", spawnerV[ix]->host, SPAWNER_PORT));
else
networkP->endpointAdd(s, s, (char*) "Spawner", "Spawner", 0, ss::Endpoint::Temporal, spawnerV[ix]->host, SPAWNER_PORT);
}
}
networkReady = true; // Is this true if Controller not running ?
firstTime = false;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/systrace_trace_parser.h"
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/string_utils.h"
#include "src/trace_processor/args_tracker.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/systrace_parser.h"
#include <inttypes.h>
#include <string>
#include <unordered_map>
namespace perfetto {
namespace trace_processor {
namespace {
std::string SubstrTrim(const std::string& input, size_t start, size_t end) {
auto s = input.substr(start, end - start);
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
[](int ch) { return !std::isspace(ch); }));
s.erase(std::find_if(s.rbegin(), s.rend(),
[](int ch) { return !std::isspace(ch); })
.base(),
s.end());
return s;
}
} // namespace
SystraceTraceParser::SystraceTraceParser(TraceProcessorContext* ctx)
: context_(ctx),
sched_wakeup_name_id_(ctx->storage->InternString("sched_wakeup")),
cpu_idle_name_id_(ctx->storage->InternString("cpuidle")) {}
SystraceTraceParser::~SystraceTraceParser() = default;
util::Status SystraceTraceParser::Parse(std::unique_ptr<uint8_t[]> owned_buf,
size_t size) {
if (state_ == ParseState::kEndOfSystrace)
return util::OkStatus();
partial_buf_.insert(partial_buf_.end(), &owned_buf[0], &owned_buf[size]);
if (state_ == ParseState::kBeforeParse) {
state_ = partial_buf_[0] == '<' ? ParseState::kHtmlBeforeSystrace
: ParseState::kSystrace;
}
const char kSystraceStart[] =
R"(<script class="trace-data" type="application/text">)";
auto start_it = partial_buf_.begin();
for (;;) {
auto line_it = std::find(start_it, partial_buf_.end(), '\n');
if (line_it == partial_buf_.end())
break;
std::string buffer(start_it, line_it);
if (state_ == ParseState::kHtmlBeforeSystrace) {
if (base::Contains(buffer, kSystraceStart)) {
state_ = ParseState::kSystrace;
}
} else if (state_ == ParseState::kSystrace) {
if (base::Contains(buffer, R"(</script>)")) {
state_ = kEndOfSystrace;
break;
} else if (!base::StartsWith(buffer, "#")) {
ParseSingleSystraceEvent(buffer);
}
}
start_it = line_it + 1;
}
if (state_ == ParseState::kEndOfSystrace) {
partial_buf_.clear();
} else {
partial_buf_.erase(partial_buf_.begin(), start_it);
}
return util::OkStatus();
}
util::Status SystraceTraceParser::ParseSingleSystraceEvent(
const std::string& buffer) {
// An example line from buffer looks something like the following:
// <idle>-0 (-----) [000] d..1 16500.715638: cpu_idle: state=0 cpu_id=0
auto task_idx = 16u;
std::string task = SubstrTrim(buffer, 0, task_idx);
auto tgid_idx = buffer.find('(', task_idx + 1);
std::string pid_str = SubstrTrim(buffer, task_idx + 1, tgid_idx);
auto pid = static_cast<uint32_t>(std::stoi(pid_str));
context_->process_tracker->GetOrCreateThread(pid);
auto tgid_end = buffer.find(')', tgid_idx + 1);
std::string tgid_str = SubstrTrim(buffer, tgid_idx + 1, tgid_end);
auto tgid = tgid_str == "-----"
? base::nullopt
: base::Optional<uint32_t>(
static_cast<uint32_t>(std::stoi(tgid_str)));
if (tgid.has_value()) {
context_->process_tracker->UpdateThread(pid, tgid.value());
}
auto cpu_idx = buffer.find('[', tgid_end + 1);
auto cpu_end = buffer.find(']', cpu_idx + 1);
std::string cpu_str = SubstrTrim(buffer, cpu_idx + 1, cpu_end);
auto cpu = static_cast<uint32_t>(std::stoi(cpu_str));
auto ts_idx = buffer.find(' ', cpu_end + 2);
auto ts_end = buffer.find(':', ts_idx + 1);
std::string ts_str = SubstrTrim(buffer, ts_idx + 1, ts_end);
auto ts_float = std::stod(ts_str) * 1e9;
auto ts = static_cast<int64_t>(ts_float);
auto fn_idx = buffer.find(':', ts_end + 2);
std::string fn = SubstrTrim(buffer, ts_end + 2, fn_idx);
std::string args_str = SubstrTrim(buffer, fn_idx + 2, buffer.size());
std::unordered_map<std::string, std::string> args;
for (base::StringSplitter ss(args_str.c_str(), ' '); ss.Next();) {
std::string key;
std::string value;
for (base::StringSplitter inner(ss.cur_token(), '='); inner.Next();) {
if (key.empty()) {
key = inner.cur_token();
} else {
value = inner.cur_token();
}
}
args.emplace(std::move(key), std::move(value));
}
if (fn == "sched_switch") {
auto prev_state_str = args["prev_state"];
int64_t prev_state =
ftrace_utils::TaskState(prev_state_str.c_str()).raw_state();
auto prev_pid = std::stoi(args["prev_pid"]);
auto prev_comm = base::StringView(args["prev_comm"]);
auto prev_prio = std::stoi(args["prev_prio"]);
auto next_pid = std::stoi(args["next_pid"]);
auto next_comm = base::StringView(args["next_comm"]);
auto next_prio = std::stoi(args["next_prio"]);
context_->event_tracker->PushSchedSwitch(
static_cast<uint32_t>(cpu), ts, static_cast<uint32_t>(prev_pid),
prev_comm, prev_prio, prev_state, static_cast<uint32_t>(next_pid),
next_comm, next_prio);
} else if (fn == "tracing_mark_write" || fn == "0" || fn == "print") {
context_->systrace_parser->ParsePrintEvent(ts, pid, args_str.c_str());
} else if (fn == "sched_wakeup") {
auto comm = args["comm"];
uint32_t wakee_pid = static_cast<uint32_t>(std::stoi(args["pid"]));
StringId name_id = context_->storage->InternString(base::StringView(comm));
auto wakee_utid =
context_->process_tracker->UpdateThreadName(wakee_pid, name_id);
context_->event_tracker->PushInstant(ts, sched_wakeup_name_id_,
0 /* value */, wakee_utid,
RefType::kRefUtid);
} else if (fn == "cpu_idle") {
auto new_state = static_cast<double>(std::stoul(args["state"]));
uint32_t event_cpu = static_cast<uint32_t>(std::stoi(args["cpu_id"]));
context_->event_tracker->PushCounter(ts, new_state, cpu_idle_name_id_,
event_cpu, RefType::kRefCpuId);
}
return util::OkStatus();
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>trace_processor: fix systrace trace parsing when there is no tgid<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/systrace_trace_parser.h"
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/string_utils.h"
#include "src/trace_processor/args_tracker.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/systrace_parser.h"
#include <inttypes.h>
#include <string>
#include <unordered_map>
namespace perfetto {
namespace trace_processor {
namespace {
std::string SubstrTrim(const std::string& input, size_t start, size_t end) {
auto s = input.substr(start, end - start);
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
[](int ch) { return !std::isspace(ch); }));
s.erase(std::find_if(s.rbegin(), s.rend(),
[](int ch) { return !std::isspace(ch); })
.base(),
s.end());
return s;
}
} // namespace
SystraceTraceParser::SystraceTraceParser(TraceProcessorContext* ctx)
: context_(ctx),
sched_wakeup_name_id_(ctx->storage->InternString("sched_wakeup")),
cpu_idle_name_id_(ctx->storage->InternString("cpuidle")) {}
SystraceTraceParser::~SystraceTraceParser() = default;
util::Status SystraceTraceParser::Parse(std::unique_ptr<uint8_t[]> owned_buf,
size_t size) {
if (state_ == ParseState::kEndOfSystrace)
return util::OkStatus();
partial_buf_.insert(partial_buf_.end(), &owned_buf[0], &owned_buf[size]);
if (state_ == ParseState::kBeforeParse) {
state_ = partial_buf_[0] == '<' ? ParseState::kHtmlBeforeSystrace
: ParseState::kSystrace;
}
const char kSystraceStart[] =
R"(<script class="trace-data" type="application/text">)";
auto start_it = partial_buf_.begin();
for (;;) {
auto line_it = std::find(start_it, partial_buf_.end(), '\n');
if (line_it == partial_buf_.end())
break;
std::string buffer(start_it, line_it);
if (state_ == ParseState::kHtmlBeforeSystrace) {
if (base::Contains(buffer, kSystraceStart)) {
state_ = ParseState::kSystrace;
}
} else if (state_ == ParseState::kSystrace) {
if (base::Contains(buffer, R"(</script>)")) {
state_ = kEndOfSystrace;
break;
} else if (!base::StartsWith(buffer, "#")) {
ParseSingleSystraceEvent(buffer);
}
}
start_it = line_it + 1;
}
if (state_ == ParseState::kEndOfSystrace) {
partial_buf_.clear();
} else {
partial_buf_.erase(partial_buf_.begin(), start_it);
}
return util::OkStatus();
}
util::Status SystraceTraceParser::ParseSingleSystraceEvent(
const std::string& buffer) {
// An example line from buffer looks something like the following:
// <idle>-0 (-----) [000] d..1 16500.715638: cpu_idle: state=0 cpu_id=0
//
// However, sometimes the tgid can be missing and buffer looks like this:
// <idle>-0 [000] ...2 0.002188: task_newtask: pid=1 ...
auto task_idx = 16u;
std::string task = SubstrTrim(buffer, 0, task_idx);
// Try and figure out whether tgid is present by searching for '(' but only
// if it occurs before the start of cpu (indiciated by '[') - this is because
// '(' can also occur in the args of an event.
auto tgid_idx = buffer.find('(', task_idx + 1);
auto cpu_idx = buffer.find('[', task_idx + 1);
bool has_tgid = tgid_idx != std::string::npos && tgid_idx < cpu_idx;
auto pid_end = has_tgid ? cpu_idx : tgid_idx;
std::string pid_str = SubstrTrim(buffer, task_idx + 1, pid_end);
auto pid = static_cast<uint32_t>(std::stoi(pid_str));
context_->process_tracker->GetOrCreateThread(pid);
if (has_tgid) {
auto tgid_end = buffer.find(')', tgid_idx + 1);
std::string tgid_str = SubstrTrim(buffer, tgid_idx + 1, tgid_end);
if (tgid_str != "-----") {
context_->process_tracker->UpdateThread(
pid, static_cast<uint32_t>(std::stoi(tgid_str)));
}
}
auto cpu_end = buffer.find(']', cpu_idx + 1);
std::string cpu_str = SubstrTrim(buffer, cpu_idx + 1, cpu_end);
auto cpu = static_cast<uint32_t>(std::stoi(cpu_str));
auto ts_idx = buffer.find(' ', cpu_end + 2);
auto ts_end = buffer.find(':', ts_idx + 1);
std::string ts_str = SubstrTrim(buffer, ts_idx + 1, ts_end);
auto ts_float = std::stod(ts_str) * 1e9;
auto ts = static_cast<int64_t>(ts_float);
auto fn_idx = buffer.find(':', ts_end + 2);
std::string fn = SubstrTrim(buffer, ts_end + 2, fn_idx);
std::string args_str = SubstrTrim(buffer, fn_idx + 2, buffer.size());
std::unordered_map<std::string, std::string> args;
for (base::StringSplitter ss(args_str.c_str(), ' '); ss.Next();) {
std::string key;
std::string value;
for (base::StringSplitter inner(ss.cur_token(), '='); inner.Next();) {
if (key.empty()) {
key = inner.cur_token();
} else {
value = inner.cur_token();
}
}
args.emplace(std::move(key), std::move(value));
}
if (fn == "sched_switch") {
auto prev_state_str = args["prev_state"];
int64_t prev_state =
ftrace_utils::TaskState(prev_state_str.c_str()).raw_state();
auto prev_pid = std::stoi(args["prev_pid"]);
auto prev_comm = base::StringView(args["prev_comm"]);
auto prev_prio = std::stoi(args["prev_prio"]);
auto next_pid = std::stoi(args["next_pid"]);
auto next_comm = base::StringView(args["next_comm"]);
auto next_prio = std::stoi(args["next_prio"]);
context_->event_tracker->PushSchedSwitch(
static_cast<uint32_t>(cpu), ts, static_cast<uint32_t>(prev_pid),
prev_comm, prev_prio, prev_state, static_cast<uint32_t>(next_pid),
next_comm, next_prio);
} else if (fn == "tracing_mark_write" || fn == "0" || fn == "print") {
context_->systrace_parser->ParsePrintEvent(ts, pid, args_str.c_str());
} else if (fn == "sched_wakeup") {
auto comm = args["comm"];
uint32_t wakee_pid = static_cast<uint32_t>(std::stoi(args["pid"]));
StringId name_id = context_->storage->InternString(base::StringView(comm));
auto wakee_utid =
context_->process_tracker->UpdateThreadName(wakee_pid, name_id);
context_->event_tracker->PushInstant(ts, sched_wakeup_name_id_,
0 /* value */, wakee_utid,
RefType::kRefUtid);
} else if (fn == "cpu_idle") {
auto new_state = static_cast<double>(std::stoul(args["state"]));
uint32_t event_cpu = static_cast<uint32_t>(std::stoi(args["cpu_id"]));
context_->event_tracker->PushCounter(ts, new_state, cpu_idle_name_id_,
event_cpu, RefType::kRefCpuId);
}
return util::OkStatus();
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|> |
<commit_before>/*=====================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2013, Bill Bonney <billbonney@communistech.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Serial Settings View.
*
* @author Bill Bonney <billbonney@communistech.com>
*
* Influenced from Qt examples by :-
* Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
* Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
*
*/
#include "QsLog.h"
#include "SerialSettingsDialog.h"
#include "TerminalConsole.h"
#include "ui_SerialSettingsDialog.h"
#include <QtSerialPort/qserialport.h>
#include <QtSerialPort/qserialportinfo.h>
#include <QIntValidator>
#include <QLineEdit>
#include <QPointer>
#include <QTimer>
QT_USE_NAMESPACE
SettingsDialog::SettingsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SettingsDialog)
{
ui->setupUi(this);
m_intValidator = new QIntValidator(0, 4000000, this);
ui->baudRateBox->setInsertPolicy(QComboBox::NoInsert);
connect(ui->applyButton, SIGNAL(clicked()),
this, SLOT(apply()));
connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(showPortInfo(int)));
connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(checkCustomBaudRatePolicy(int)));
fillPortsParameters();
fillPortsInfo(*ui->serialPortInfoListBox);
updateSettings();
//Keep refreshing the serial port list
m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this,SLOT(populateSerialPorts()));
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
const SerialSettings& SettingsDialog::settings() const
{
return m_currentSettings;
}
void SettingsDialog::showPortInfo(int idx)
{
if (idx != -1) {
QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList();
ui->descriptionLabel->setText(tr("Description: %1").arg(list.at(1)));
ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.at(2)));
ui->locationLabel->setText(tr("Location: %1").arg(list.at(3)));
ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.at(4)));
ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.at(5)));
}
}
void SettingsDialog::apply()
{
updateSettings();
hide();
}
void SettingsDialog::checkCustomBaudRatePolicy(int idx)
{
bool isCustomBaudRate = !ui->baudRateBox->itemData(idx).isValid();
ui->baudRateBox->setEditable(isCustomBaudRate);
if (isCustomBaudRate) {
ui->baudRateBox->clearEditText();
QLineEdit *edit = ui->baudRateBox->lineEdit();
edit->setValidator(m_intValidator);
}
}
void SettingsDialog::fillPortsParameters()
{
// fill baud rate (is not the entire list of available values,
// desired values??, add your independently)
ui->baudRateBox->addItem(QLatin1String("115200"), QSerialPort::Baud115200);
ui->baudRateBox->addItem(QLatin1String("57600"), QSerialPort::Baud57600);
ui->baudRateBox->addItem(QLatin1String("38400"), QSerialPort::Baud38400);
ui->baudRateBox->addItem(QLatin1String("19200"), QSerialPort::Baud19200);
ui->baudRateBox->addItem(QLatin1String("9600"), QSerialPort::Baud9600);
ui->baudRateBox->addItem(QLatin1String("Custom"));
// fill data bits
ui->dataBitsBox->addItem(QLatin1String("5"), QSerialPort::Data5);
ui->dataBitsBox->addItem(QLatin1String("6"), QSerialPort::Data6);
ui->dataBitsBox->addItem(QLatin1String("7"), QSerialPort::Data7);
ui->dataBitsBox->addItem(QLatin1String("8"), QSerialPort::Data8);
ui->dataBitsBox->setCurrentIndex(3);
// fill parity
ui->parityBox->addItem(QLatin1String("None"), QSerialPort::NoParity);
ui->parityBox->addItem(QLatin1String("Even"), QSerialPort::EvenParity);
ui->parityBox->addItem(QLatin1String("Odd"), QSerialPort::OddParity);
ui->parityBox->addItem(QLatin1String("Mark"), QSerialPort::MarkParity);
ui->parityBox->addItem(QLatin1String("Space"), QSerialPort::SpaceParity);
// fill stop bits
ui->stopBitsBox->addItem(QLatin1String("1"), QSerialPort::OneStop);
#ifdef Q_OS_WIN
ui->stopBitsBox->addItem(QLatin1String("1.5"), QSerialPort::OneAndHalfStop);
#endif
ui->stopBitsBox->addItem(QLatin1String("2"), QSerialPort::TwoStop);
// fill flow control
ui->flowControlBox->addItem(QLatin1String("None"), QSerialPort::NoFlowControl);
ui->flowControlBox->addItem(QLatin1String("RTS/CTS"), QSerialPort::HardwareControl);
ui->flowControlBox->addItem(QLatin1String("XON/XOFF"), QSerialPort::SoftwareControl);
}
void SettingsDialog::populateSerialPorts()
{
QLOG_TRACE() << "SettingsDialog::populateSerialPorts";
fillPortsInfo(*ui->serialPortInfoListBox);
}
void SettingsDialog::fillPortsInfo(QComboBox &comboBox)
{
QLOG_DEBUG() << "fillPortsInfo ";
QString current = comboBox.itemText(comboBox.currentIndex());
disconnect(&comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setLink(int)));
comboBox.clear();
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
QStringList list;
list << info.portName()
<< info.description()
<< info.manufacturer()
<< info.systemLocation()
<< (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString())
<< (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : QString());
int found = comboBox.findData(list);
if (found == -1) {
QLOG_INFO() << "Inserting " << list.first();
comboBox.insertItem(0,list[0], list);
} else {
// Do nothing as the port is already listed
}
}
for (int i=0;i<comboBox.count();i++)
{
if (comboBox.itemText(i) == current)
{
comboBox.setCurrentIndex(i);
setLink(comboBox.currentIndex());
connect(&comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setLink(int)));
return;
}
}
connect(&comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setLink(int)));
setLink(comboBox.currentIndex());
}
void SettingsDialog::setLink(int index)
{
if (index == -1)
{
return;
}
m_currentSettings.name = ui->serialPortInfoListBox->itemData(index).toStringList()[0];
QLOG_INFO() << "Changed Link to:" << m_currentSettings.name;
}
void SettingsDialog::showEvent(QShowEvent *event)
{
Q_UNUSED(event);
// Start refresh Timer
m_timer->start(2000);
}
void SettingsDialog::hideEvent(QHideEvent *event)
{
Q_UNUSED(event);
// Stop the port list refeshing
m_timer->stop();
}
void SettingsDialog::updateSettings()
{
m_currentSettings.name = ui->serialPortInfoListBox->currentText();
// Baud Rate
if (ui->baudRateBox->currentIndex() == 4) {
// custom baud rate
m_currentSettings.baudRate = ui->baudRateBox->currentText().toInt();
} else {
// standard baud rate
m_currentSettings.baudRate = static_cast<QSerialPort::BaudRate>(
ui->baudRateBox->itemData(ui->baudRateBox->currentIndex()).toInt());
}
// Data bits
m_currentSettings.dataBits = static_cast<QSerialPort::DataBits>(
ui->dataBitsBox->itemData(ui->dataBitsBox->currentIndex()).toInt());
// Parity
m_currentSettings.parity = static_cast<QSerialPort::Parity>(
ui->parityBox->itemData(ui->parityBox->currentIndex()).toInt());
// Stop bits
m_currentSettings.stopBits = static_cast<QSerialPort::StopBits>(
ui->stopBitsBox->itemData(ui->stopBitsBox->currentIndex()).toInt());
// Flow control
m_currentSettings.flowControl = static_cast<QSerialPort::FlowControl>(
ui->flowControlBox->itemData(ui->flowControlBox->currentIndex()).toInt());
}
<commit_msg>Serial Configuration: Update Serial Ports Dynamically<commit_after>/*=====================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2013, Bill Bonney <billbonney@communistech.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Serial Settings View.
*
* @author Bill Bonney <billbonney@communistech.com>
*
* Influenced from Qt examples by :-
* Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
* Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
*
*/
#include "QsLog.h"
#include "SerialSettingsDialog.h"
#include "TerminalConsole.h"
#include "ui_SerialSettingsDialog.h"
#include <QtSerialPort/qserialport.h>
#include <QtSerialPort/qserialportinfo.h>
#include <QIntValidator>
#include <QLineEdit>
#include <QPointer>
#include <QTimer>
QT_USE_NAMESPACE
SettingsDialog::SettingsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SettingsDialog)
{
ui->setupUi(this);
m_intValidator = new QIntValidator(0, 4000000, this);
ui->baudRateBox->setInsertPolicy(QComboBox::NoInsert);
connect(ui->applyButton, SIGNAL(clicked()),
this, SLOT(apply()));
connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(showPortInfo(int)));
connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(checkCustomBaudRatePolicy(int)));
fillPortsParameters();
fillPortsInfo(*ui->serialPortInfoListBox);
updateSettings();
//Keep refreshing the serial port list
m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this,SLOT(populateSerialPorts()));
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
const SerialSettings& SettingsDialog::settings() const
{
return m_currentSettings;
}
void SettingsDialog::showPortInfo(int idx)
{
if (idx != -1) {
QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList();
ui->descriptionLabel->setText(tr("Description: %1").arg(list.at(1)));
ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.at(2)));
ui->locationLabel->setText(tr("Location: %1").arg(list.at(3)));
ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.at(4)));
ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.at(5)));
}
}
void SettingsDialog::apply()
{
updateSettings();
hide();
}
void SettingsDialog::checkCustomBaudRatePolicy(int idx)
{
bool isCustomBaudRate = !ui->baudRateBox->itemData(idx).isValid();
ui->baudRateBox->setEditable(isCustomBaudRate);
if (isCustomBaudRate) {
ui->baudRateBox->clearEditText();
QLineEdit *edit = ui->baudRateBox->lineEdit();
edit->setValidator(m_intValidator);
}
}
void SettingsDialog::fillPortsParameters()
{
// fill baud rate (is not the entire list of available values,
// desired values??, add your independently)
ui->baudRateBox->addItem(QLatin1String("115200"), QSerialPort::Baud115200);
ui->baudRateBox->addItem(QLatin1String("57600"), QSerialPort::Baud57600);
ui->baudRateBox->addItem(QLatin1String("38400"), QSerialPort::Baud38400);
ui->baudRateBox->addItem(QLatin1String("19200"), QSerialPort::Baud19200);
ui->baudRateBox->addItem(QLatin1String("9600"), QSerialPort::Baud9600);
ui->baudRateBox->addItem(QLatin1String("Custom"));
// fill data bits
ui->dataBitsBox->addItem(QLatin1String("5"), QSerialPort::Data5);
ui->dataBitsBox->addItem(QLatin1String("6"), QSerialPort::Data6);
ui->dataBitsBox->addItem(QLatin1String("7"), QSerialPort::Data7);
ui->dataBitsBox->addItem(QLatin1String("8"), QSerialPort::Data8);
ui->dataBitsBox->setCurrentIndex(3);
// fill parity
ui->parityBox->addItem(QLatin1String("None"), QSerialPort::NoParity);
ui->parityBox->addItem(QLatin1String("Even"), QSerialPort::EvenParity);
ui->parityBox->addItem(QLatin1String("Odd"), QSerialPort::OddParity);
ui->parityBox->addItem(QLatin1String("Mark"), QSerialPort::MarkParity);
ui->parityBox->addItem(QLatin1String("Space"), QSerialPort::SpaceParity);
// fill stop bits
ui->stopBitsBox->addItem(QLatin1String("1"), QSerialPort::OneStop);
#ifdef Q_OS_WIN
ui->stopBitsBox->addItem(QLatin1String("1.5"), QSerialPort::OneAndHalfStop);
#endif
ui->stopBitsBox->addItem(QLatin1String("2"), QSerialPort::TwoStop);
// fill flow control
ui->flowControlBox->addItem(QLatin1String("None"), QSerialPort::NoFlowControl);
ui->flowControlBox->addItem(QLatin1String("RTS/CTS"), QSerialPort::HardwareControl);
ui->flowControlBox->addItem(QLatin1String("XON/XOFF"), QSerialPort::SoftwareControl);
}
void SettingsDialog::populateSerialPorts()
{
QLOG_TRACE() << "SettingsDialog::populateSerialPorts";
fillPortsInfo(*ui->serialPortInfoListBox);
}
void SettingsDialog::fillPortsInfo(QComboBox &comboBox)
{
QLOG_DEBUG() << "fillPortsInfo ";
QString current = comboBox.itemText(comboBox.currentIndex());
disconnect(&comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setLink(int)));
comboBox.clear();
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
QStringList list;
list << info.portName()
<< info.description()
<< info.manufacturer()
<< info.systemLocation()
<< (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString())
<< (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : QString());
int found = comboBox.findData(list);
if (found == -1) {
QLOG_INFO() << "Inserting " << list.first();
comboBox.insertItem(0,list[0], list);
} else {
// Do nothing as the port is already listed
}
}
for (int i=0;i<comboBox.count();i++)
{
if (comboBox.itemText(i) == current)
{
comboBox.setCurrentIndex(i);
break;
}
}
connect(&comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setLink(int)));
setLink(comboBox.currentIndex());
}
void SettingsDialog::setLink(int index)
{
if (index == -1)
{
return;
}
m_currentSettings.name = ui->serialPortInfoListBox->itemData(index).toStringList()[0];
QLOG_INFO() << "Changed Link to:" << m_currentSettings.name;
}
void SettingsDialog::showEvent(QShowEvent *event)
{
Q_UNUSED(event);
// Start refresh Timer
m_timer->start(2000);
}
void SettingsDialog::hideEvent(QHideEvent *event)
{
Q_UNUSED(event);
// Stop the port list refeshing
m_timer->stop();
}
void SettingsDialog::updateSettings()
{
m_currentSettings.name = ui->serialPortInfoListBox->currentText();
// Baud Rate
if (ui->baudRateBox->currentIndex() == 4) {
// custom baud rate
m_currentSettings.baudRate = ui->baudRateBox->currentText().toInt();
} else {
// standard baud rate
m_currentSettings.baudRate = static_cast<QSerialPort::BaudRate>(
ui->baudRateBox->itemData(ui->baudRateBox->currentIndex()).toInt());
}
// Data bits
m_currentSettings.dataBits = static_cast<QSerialPort::DataBits>(
ui->dataBitsBox->itemData(ui->dataBitsBox->currentIndex()).toInt());
// Parity
m_currentSettings.parity = static_cast<QSerialPort::Parity>(
ui->parityBox->itemData(ui->parityBox->currentIndex()).toInt());
// Stop bits
m_currentSettings.stopBits = static_cast<QSerialPort::StopBits>(
ui->stopBitsBox->itemData(ui->stopBitsBox->currentIndex()).toInt());
// Flow control
m_currentSettings.flowControl = static_cast<QSerialPort::FlowControl>(
ui->flowControlBox->itemData(ui->flowControlBox->currentIndex()).toInt());
}
<|endoftext|> |
<commit_before><commit_msg>catch by reference<commit_after><|endoftext|> |
<commit_before>// Author: Wim Lavrijsen, February 2006
// Bindings
#include "PyROOT.h"
#include "TPyROOTApplication.h"
#include "Utility.h"
// ROOT
#include "TROOT.h"
#include "TInterpreter.h"
#include "TSystem.h"
#include "TBenchmark.h"
#include "TStyle.h"
#include "TError.h"
#include "Getline.h"
//#include "TVirtualX.h"
// Standard
#include <string.h>
//______________________________________________________________________________
// Setup interactive application for python
// ========================================
//
// The TPyROOTApplication sets up the nuts and bolts for interactive ROOT use
// from python, closely following TRint. Note that not everything is done here,
// some bits (such as e.g. the use of exception hook for shell escapes) are more
// easily done in python and you'll thus find them ROOT.py
//
// The intended use of this class is from python only. It is used by default in
// ROOT.py, so if you do not want to have a TApplication derived object created
// for you, you'll need to load libPyROOT.so instead.
//
// The static InitXYZ functions are used in conjunction with TPyROOTApplication
// in ROOT.py, but they can be used independently.
//
// NOTE: This class will receive the command line arguments from sys.argv. A
// distinction between arguments for TApplication and user arguments can be
// made by using "-" or "--" as a separator on the command line.
//- data ---------------------------------------------------------------------
ClassImp(PyROOT::TPyROOTApplication)
//- constructors/destructor --------------------------------------------------
PyROOT::TPyROOTApplication::TPyROOTApplication(
const char* acn, int* argc, char** argv, Bool_t bLoadLibs ) :
TApplication( acn, argc, argv )
{
// Create a TApplication derived for use with interactive ROOT from python. A
// set of standard, often used libs is loaded if bLoadLibs is true (default).
if ( bLoadLibs ) // note that this section could be programmed in python
{
// follow TRint to minimize differences with root.exe (note: changed <pair>
// to <utility> for Cling, which is correct)
ProcessLine( "#include <iostream>", kTRUE );
ProcessLine( "#include <string>", kTRUE ); // for std::string iostream.
ProcessLine( "#include <vector>", kTRUE ); // needed because they're used within the
ProcessLine( "#include <utility>", kTRUE ); // core ROOT dicts and CINT won't be able
// to properly unload these files
}
#ifdef WIN32
// switch win32 proxy main thread id
if (gVirtualX)
ProcessLine("((TGWin32 *)gVirtualX)->SetUserThreadId(0);", kTRUE);
#endif
// save current interpreter context
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// prevent crashes on accessing history
Gl_histinit( (char*)"-" );
// prevent ROOT from exiting python
SetReturnFromRun( kTRUE );
}
//- static public members ----------------------------------------------------
Bool_t PyROOT::TPyROOTApplication::CreatePyROOTApplication( Bool_t bLoadLibs )
{
// Create a TPyROOTApplication. Returns false if gApplication is not null.
if ( ! gApplication ) {
// retrieve arg list from python, translate to raw C, pass on
PyObject* argl = PySys_GetObject( const_cast< char* >( "argv" ) );
int argc = 1;
if ( argl && 0 < PyList_Size( argl ) ) argc = (int)PyList_GET_SIZE( argl );
char** argv = new char*[ argc ];
for ( int i = 1; i < argc; ++i ) {
char* argi = PyROOT_PyUnicode_AsString( PyList_GET_ITEM( argl, i ) );
if ( strcmp( argi, "-" ) == 0 || strcmp( argi, "--" ) == 0 ) {
// stop collecting options, the remaining are for the python script
argc = i; // includes program name
break;
}
argv[ i ] = argi;
}
#if PY_VERSION_HEX < 0x03000000
if ( Py_GetProgramName() && strlen( Py_GetProgramName() ) != 0 )
argv[ 0 ] = Py_GetProgramName();
else
argv[ 0 ] = (char*)"python";
#else
// TODO: convert the wchar_t*
argv[ 0 ] = (char*)"python";
#endif
gApplication = new TPyROOTApplication( "PyROOT", &argc, argv, bLoadLibs );
delete[] argv; // TApplication ctor has copied argv, so done with it
return kTRUE;
}
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TPyROOTApplication::InitROOTGlobals()
{
// Setup the basic ROOT globals gBenchmark, gStyle, gProgname, if not already
// set. Always returns true.
if ( ! gBenchmark ) gBenchmark = new TBenchmark();
if ( ! gStyle ) gStyle = new TStyle();
if ( ! gProgName ) // should have been set by TApplication
#if PY_VERSION_HEX < 0x03000000
gSystem->SetProgname( Py_GetProgramName() );
#else
// TODO: convert the wchar_t*
gSystem->SetProgname( "python" );
#endif
return kTRUE;
}
//____________________________________________________________________________
Bool_t PyROOT::TPyROOTApplication::InitROOTMessageCallback()
{
// Install ROOT message handler which will turn ROOT error message into
// python exceptions. Always returns true.
SetErrorHandler( (ErrorHandlerFunc_t)&Utility::ErrMsgHandler );
return kTRUE;
}
<commit_msg>Avoid a call to the interpreter in ctor of TPyROOTApplication<commit_after>// Author: Wim Lavrijsen, February 2006
// Bindings
#include "PyROOT.h"
#include "TPyROOTApplication.h"
#include "Utility.h"
// ROOT
#include "TROOT.h"
#include "TInterpreter.h"
#include "TSystem.h"
#include "TBenchmark.h"
#include "TStyle.h"
#include "TError.h"
#include "Getline.h"
//#include "TVirtualX.h"
// Standard
#include <string.h>
//______________________________________________________________________________
// Setup interactive application for python
// ========================================
//
// The TPyROOTApplication sets up the nuts and bolts for interactive ROOT use
// from python, closely following TRint. Note that not everything is done here,
// some bits (such as e.g. the use of exception hook for shell escapes) are more
// easily done in python and you'll thus find them ROOT.py
//
// The intended use of this class is from python only. It is used by default in
// ROOT.py, so if you do not want to have a TApplication derived object created
// for you, you'll need to load libPyROOT.so instead.
//
// The static InitXYZ functions are used in conjunction with TPyROOTApplication
// in ROOT.py, but they can be used independently.
//
// NOTE: This class will receive the command line arguments from sys.argv. A
// distinction between arguments for TApplication and user arguments can be
// made by using "-" or "--" as a separator on the command line.
//- data ---------------------------------------------------------------------
ClassImp(PyROOT::TPyROOTApplication)
//- constructors/destructor --------------------------------------------------
PyROOT::TPyROOTApplication::TPyROOTApplication(
const char* acn, int* argc, char** argv, Bool_t /*bLoadLibs*/ ) :
TApplication( acn, argc, argv )
{
// The following code is redundant with ROOT6 and the PCH: the headers are
// available to the interpreter.
// // Create a TApplication derived for use with interactive ROOT from python. A
// // set of standard, often used libs is loaded if bLoadLibs is true (default).
//
// if ( bLoadLibs ) // note that this section could be programmed in python
// {
// // follow TRint to minimize differences with root.exe (note: changed <pair>
// // to <utility> for Cling, which is correct)
// ProcessLine( "#include <iostream>", kTRUE );
// ProcessLine( "#include <string>", kTRUE ); // for std::string iostream.
// ProcessLine( "#include <vector>", kTRUE ); // needed because they're used within the
// ProcessLine( "#include <utility>", kTRUE ); // core ROOT dicts and CINT won't be able
// // to properly unload these files
// }
#ifdef WIN32
// switch win32 proxy main thread id
if (gVirtualX)
ProcessLine("((TGWin32 *)gVirtualX)->SetUserThreadId(0);", kTRUE);
#endif
// save current interpreter context
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// prevent crashes on accessing history
Gl_histinit( (char*)"-" );
// prevent ROOT from exiting python
SetReturnFromRun( kTRUE );
}
//- static public members ----------------------------------------------------
Bool_t PyROOT::TPyROOTApplication::CreatePyROOTApplication( Bool_t bLoadLibs )
{
// Create a TPyROOTApplication. Returns false if gApplication is not null.
if ( ! gApplication ) {
// retrieve arg list from python, translate to raw C, pass on
PyObject* argl = PySys_GetObject( const_cast< char* >( "argv" ) );
int argc = 1;
if ( argl && 0 < PyList_Size( argl ) ) argc = (int)PyList_GET_SIZE( argl );
char** argv = new char*[ argc ];
for ( int i = 1; i < argc; ++i ) {
char* argi = PyROOT_PyUnicode_AsString( PyList_GET_ITEM( argl, i ) );
if ( strcmp( argi, "-" ) == 0 || strcmp( argi, "--" ) == 0 ) {
// stop collecting options, the remaining are for the python script
argc = i; // includes program name
break;
}
argv[ i ] = argi;
}
#if PY_VERSION_HEX < 0x03000000
if ( Py_GetProgramName() && strlen( Py_GetProgramName() ) != 0 )
argv[ 0 ] = Py_GetProgramName();
else
argv[ 0 ] = (char*)"python";
#else
// TODO: convert the wchar_t*
argv[ 0 ] = (char*)"python";
#endif
gApplication = new TPyROOTApplication( "PyROOT", &argc, argv, bLoadLibs );
delete[] argv; // TApplication ctor has copied argv, so done with it
return kTRUE;
}
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TPyROOTApplication::InitROOTGlobals()
{
// Setup the basic ROOT globals gBenchmark, gStyle, gProgname, if not already
// set. Always returns true.
if ( ! gBenchmark ) gBenchmark = new TBenchmark();
if ( ! gStyle ) gStyle = new TStyle();
if ( ! gProgName ) // should have been set by TApplication
#if PY_VERSION_HEX < 0x03000000
gSystem->SetProgname( Py_GetProgramName() );
#else
// TODO: convert the wchar_t*
gSystem->SetProgname( "python" );
#endif
return kTRUE;
}
//____________________________________________________________________________
Bool_t PyROOT::TPyROOTApplication::InitROOTMessageCallback()
{
// Install ROOT message handler which will turn ROOT error message into
// python exceptions. Always returns true.
SetErrorHandler( (ErrorHandlerFunc_t)&Utility::ErrMsgHandler );
return kTRUE;
}
<|endoftext|> |
<commit_before>#include "StateSpace.h"
// NOTE: cannot initialise angle_bins or velocity_bins here as they are static. Also space is not a field of StateSpace and
// _angle_max and _velocity_max are not declared.
StateSpace::StateSpace(int _angle_bins, int _velocity_bins, const PriorityQueue<int,double>& queue ):
space1(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue)))
space2(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue)))
{}
StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
//throw if the the index is out of bounds
if(robot_state>1)throw std::domain_error("action index exceeded");
//return proxy object to accept second [] operator
return SubscriptProxy1( robot_state ? space1 : space2 );
}
//searches state space by state object
PriorityQueue<int, double>& StateSpace::operator[](const State & state)
{
//call the subscript operators with the members of the state object
return (*this)[state.robot_state][state.theta][state.theta_dot];
}
void StateSpace::setAngleBins(const double val)
{
angle_bins=val;
}
void StateSpace::setVelocityBins(const double val)
{
velocity_bins=val;
}
<commit_msg>Update StateSpace.cpp<commit_after>#include "StateSpace.h"
// NOTE: cannot initialise angle_bins or velocity_bins here as they are static. Also space is not a field of StateSpace and
// _angle_max and _velocity_max are not declared.
StateSpace::StateSpace(int _angle_bins, int _velocity_bins, const PriorityQueue<int,double>& queue):
space1(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue))),
space2(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue)))
{}
StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
//throw if the the index is out of bounds
if(robot_state>1)throw std::domain_error("action index exceeded");
//return proxy object to accept second [] operator
return SubscriptProxy1( robot_state ? space1 : space2 );
}
//searches state space by state object
PriorityQueue<int, double>& StateSpace::operator[](const State & state)
{
//call the subscript operators with the members of the state object
return (*this)[state.robot_state][state.theta][state.theta_dot];
}
void StateSpace::setAngleBins(const double val)
{
angle_bins=val;
}
void StateSpace::setVelocityBins(const double val)
{
velocity_bins=val;
}
<|endoftext|> |
<commit_before>
#include "std_incl.h"
#include "utils.h"
#include "tinydir.h"
typedef void (*process_image_cb)(ImageData *img, int bead, int frame);
std::string file_ext(const char *f){
int l=strlen(f)-1;
while (l > 0) {
if (f[l] == '.')
return &f[l+1];
l--;
}
return "";
}
struct BeadPos{ int x,y; };
std::vector<BeadPos> read_beadlist(std::string fn)
{
FILE *f = fopen(fn.c_str(), "r");
std::vector<BeadPos> beads;
while (!feof(f)) {
BeadPos bp;
fscanf(f, "%d\t%d\n", &bp.x,&bp.y);
beads.push_back(bp);
}
fclose(f);
return beads;
}
void extract_regions(std::vector<BeadPos> beads, int size, int frame, ImageData* img, process_image_cb cb)
{
ImageData roi = ImageData::alloc(size,size);
for (int i=0;i<beads.size();i++)
{
int xs = beads[i].x - size/2;
int ys = beads[i].y - size/2;
for (int y=0;y<size;y++) {
for(int x=0;x<size;x++)
roi.at(x,y) = img->at(xs+x, ys+y);
}
if(cb) cb(&roi, i, frame);
}
roi.free();
}
void process_beads(const char *path, int size, process_image_cb cb)
{
tinydir_dir d;
if (tinydir_open(&d, path) == -1)
throw std::runtime_error("can't open given path");
auto beadlist = read_beadlist(std::string(path) + "/beadlist.txt");
dbgprintf("%d beads.\n", beadlist.size());
int frame=0;
while(d.has_next) {
tinydir_file f;
tinydir_readfile(&d, &f);
if (!f.is_dir && file_ext(f.name) == "jpg") {
dbgprintf("File: %s\n", f.name);
ImageData img = ReadJPEGFile(f.path);
extract_regions(beadlist, size, frame++, &img, cb);
img.free();
}
tinydir_next(&d);
}
}
void build_tree(ImageData* img, int bead, int frame)
{
}
int main(int argc, char* argv[])
{
process_beads("../../datasets/1/tmp_001", 80, build_tree);
return 0;
}
<commit_msg>* RPTree class<commit_after>
#include "std_incl.h"
#include "utils.h"
#include "tinydir.h"
#include <list>
typedef void (*process_image_cb)(ImageData *img, int bead, int frame);
std::string file_ext(const char *f){
int l=strlen(f)-1;
while (l > 0) {
if (f[l] == '.')
return &f[l+1];
l--;
}
return "";
}
struct BeadPos{ int x,y; };
std::vector<BeadPos> read_beadlist(std::string fn)
{
FILE *f = fopen(fn.c_str(), "r");
std::vector<BeadPos> beads;
while (!feof(f)) {
BeadPos bp;
fscanf(f, "%d\t%d\n", &bp.x,&bp.y);
beads.push_back(bp);
}
fclose(f);
return beads;
}
void extract_regions(std::vector<BeadPos> beads, int size, int frame, ImageData* img, process_image_cb cb)
{
ImageData roi = ImageData::alloc(size,size);
for (int i=0;i<beads.size();i++)
{
int xs = beads[i].x - size/2;
int ys = beads[i].y - size/2;
for (int y=0;y<size;y++) {
for(int x=0;x<size;x++)
roi.at(x,y) = img->at(xs+x, ys+y);
}
if(cb) cb(&roi, i, frame);
}
roi.free();
}
void process_beads(const char *path, int size, std::vector<BeadPos> beadlist, process_image_cb cb, int framelimit)
{
tinydir_dir d;
if (tinydir_open(&d, path) == -1)
throw std::runtime_error("can't open given path");
int frame=0;
while(d.has_next) {
tinydir_file f;
tinydir_readfile(&d, &f);
if (!f.is_dir && file_ext(f.name) == "jpg") {
dbgprintf("File: %s\n", f.name);
ImageData img = ReadJPEGFile(f.path);
extract_regions(beadlist, size, frame++, &img, cb);
img.free();
}
if (frame==framelimit)
break;
tinydir_next(&d);
}
}
struct RPTree {
int D;
std::list<float*> points;
int memuse() { return points.size()*D*sizeof(float); }
RPTree(int D) : D(D) {}
~RPTree() { DeleteAllElems(points); }
void add(float* pt) {
float* cp = new float[D];
for (int i=0;i<D;i++) cp[i]=pt[i];
points.push_back(cp);
}
};
std::vector<RPTree*> trees;
void build_tree(ImageData* img, int bead, int frame)
{
trees[bead]->add(img->data);
}
void print_memuse()
{
int memuse=0;
for (int i=0;i<trees.size();i++)
memuse+=trees[i]->memuse();
dbgprintf("Memuse: %d\n", memuse);
}
int main(int argc, char* argv[])
{
const char *path = "../../datasets/1/tmp_001";
auto beadlist = read_beadlist(std::string(path) + "/beadlist.txt");
dbgprintf("%d beads.\n", beadlist.size());
int W=80;
for (int i=0;i<beadlist.size();i++)
trees.push_back(new RPTree(W*W));
process_beads(path, W, beadlist, build_tree, 40);
print_memuse();
DeleteAllElems(trees);
return 0;
}
<|endoftext|> |
<commit_before>
#include <map>
#include <set>
#include <ocelot/ir/interface/HammockGraph.h>
#include <ocelot/ir/interface/Instruction.h>
#include <hydrazine/implementation/string.h>
#include <hydrazine/implementation/debug.h>
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif
#define REPORT_BASE 1
/////////////////////////////////////////////////////////////////////////////////////////////////
ir::HammockGraph::~HammockGraph() {
}
ir::HammockGraph::HammockGraph(ir::ControlFlowGraph * _cfg): type(Subgraph), cfg(_cfg), domTree(_cfg), pdomTree(_cfg) {
// compute dominance relations
typedef std::vector< std::vector<int> > BasicBlockTree;
typedef std::multimap< int, int > DomTreeEdges;
std::map< int, int > DomToIDomMap;
DomTreeEdges idom;
DomTreeEdges ipdom;
// enumerate immediate dominator edges
int n = 0;
for (BasicBlockTree::iterator dom_it = domTree.dominated.begin();
dom_it != domTree.dominated.end(); ++dom_it, n++ ) {
for (std::vector< int >::iterator dom_it_it = dom_it->begin(); dom_it_it != dom_it->end(); ++dom_it_it) {
idom.insert(std::make_pair<int,int>(n, *dom_it_it));
}
}
// enumerage immediate post-dominator edges
int p = 0;
for (BasicBlockTree::iterator pdom_it = pdomTree.dominated.begin();
pdom_it != pdomTree.dominated.end(); ++pdom_it, p++ ) {
for (std::vector< int >::iterator pdom_it_it = pdom_it->begin(); pdom_it_it != pdom_it->end(); ++pdom_it_it) {
ipdom.insert(std::make_pair<int,int>((int)pdomTree.dominated.size() - 1 - p, (int)pdomTree.dominated.size() - 1 - *pdom_it_it));
}
}
// duplicates indicate hammocks
for (DomTreeEdges::iterator idom_it = idom.begin(); idom_it != idom.end(); ++idom_it) {
std::pair<DomTreeEdges::iterator, DomTreeEdges::iterator> ipdom_it = ipdom.equal_range(idom_it->second);
for (; ipdom_it.first != ipdom_it.second; ++(ipdom_it.first)) {
if ((ipdom_it.first)->first == idom_it->second) {
//
// found a hammock graph
//
// (idom_it->first, idom_it->second) is a hammock
int u = idom_it->first, v = idom_it->second;
// TODO - ignore 2-node hammocks (i.e. u has exactly one out-edge [to v])
if (domTree.blocks[u]->successors.size() > 1) {
hammocks.insert(std::make_pair<int,int>(u,v));
}
}
}
}
#if REPORT_BASE
report(hammocks.size() << " hammocks");
for (std::map< int, int >::iterator h_it = hammocks.begin(); h_it != hammocks.end(); ++h_it) {
report("subgraph (" << domTree.blocks[h_it->first]->label << ", " << domTree.blocks[h_it->second]->label
<< ") is a hammock - {" << h_it->first << ", " << h_it->second << "}");
}
#endif
// now recursively partition - this part could be challenging
topological_sequence();
}
/*!
\brief
*/
void ir::HammockGraph::schedule_hammock(ir::ControlFlowGraph::BlockPointerVector & sequence,
std::set<int> & scheduled, int entry, int exit) {
typedef std::vector< std::vector<int> > BasicBlockTree;
typedef ir::ControlFlowGraph::BlockPointerVector BlockPointerVector;
/*
Algorithm for scheduling a hammock
1.) reverse post-order DFS traversal of the graph
2.) if the current node has already been scheduled, skip it
3.) pop the current node from the front of the sequence and schedule it.
4.) If it is the entry to a hammock, schedule the hammock.
*/
report(" schedule_hammock(" << domTree.blocks[entry]->label << ", " << domTree.blocks[exit]->label << ")");
report(" scheduling " << domTree.blocks[entry]->label);
sequence.push_back(domTree.blocks[entry]);
scheduled.insert(entry);
std::deque< int > worklist;
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
for (BlockPointerVector::const_iterator succ_it = domTree.blocks[entry]->successors.begin();
succ_it != domTree.blocks[entry]->successors.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
while (worklist.size()) {
int node = worklist.front(); worklist.pop_front();
std::map< int, int >::iterator h_it = hammocks.find(node);
if (h_it != hammocks.end()) {
schedule_hammock(sequence, scheduled, h_it->first, h_it->second);
if (scheduled.find(h_it->second) == scheduled.end()) {
report(" scheduling " << domTree.blocks[h_it->second]->label);
sequence.push_back(domTree.blocks[h_it->second]);
scheduled.insert(h_it->second);
}
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
BlockPointerVector & succ = domTree.blocks[h_it->second]->successors;
for (BlockPointerVector::const_iterator succ_it = succ.begin(); succ_it != succ.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
}
else {
if (scheduled.find(node) == scheduled.end()) {
report(" scheduling " << domTree.blocks[node]->label);
sequence.push_back(domTree.blocks[node]);
scheduled.insert(node);
}
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
BlockPointerVector & succ = domTree.blocks[node]->successors;
for (BlockPointerVector::const_iterator succ_it = succ.begin(); succ_it != succ.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
}
}
report(" end schedule_hammock(" << domTree.blocks[entry]->label << ", " << domTree.blocks[exit]->label << ")");
}
/*!
\brief performs a topological sort to maximize reconvergence opportunities and ensure forward progress
*/
ir::ControlFlowGraph::BlockPointerVector ir::HammockGraph::topological_sequence() {
typedef ir::ControlFlowGraph::BlockPointerVector BlockPointerVector;
std::set< int > scheduled;
BlockPointerVector sequence;
schedule_hammock(sequence, scheduled, domTree.blocksToIndex[ domTree.blocks[0] ],
domTree.blocksToIndex[ pdomTree.blocks[0] ]);
// tests:
// are all blocks scheduled exactly once?
// is the entry node the first block?
// are hammocks scheduled correctly?
report("schedule:");
for (BlockPointerVector::iterator bb_it = sequence.begin(); bb_it != sequence.end(); ++bb_it) {
report(" " << (*bb_it)->label);
}
return sequence;
}
/*
1) Do no consider any edges that leave or entry the hammock.
2) Attempt a topological sort. This is done by starting with the entry
node, adding all successors to a set, then picking the next node to
schedule from the successor set such that all of it's predecessors are
either not contained in the hammock, or are already scheduled.
3) If the sort fails, there is a cycle that ends with at least one node
in the successor set. Discover the cycle and remove all edges that
cycle exit the cycle. This can be accomplished by performing a
traversal starting from each node in the successor list. If the
traversal ever ends with the starting node, then there is a cycle ending
in that node. Ignore the edge that completes the cycle. Resume the
topological sort.
Consider the following example:
A -> B
A -> C
B -> D
C -> D
C -> E
D -> F
E -> C
E -> F
This algorithm could produce the following schedules:
1) A, B, C, D, E, F
2) A, B, C, E, D, F
In these cases, 2) has the potential to be faster than 1) because the
node E that is part of the cycle C -> E -> C is given priority over D.
So if threads iterate over the cycle multiple times then some threads
could be peeled off on every iteration and branch to D. Schedule 1)
would push these one at a time to F, while schedule 2) would accumulate
them at D and then push them to F all at once. This leads me to another
rule of thumb: during scheduling, nodes that are part of a cycle should
be given scheduling priority over nodes that are not.
So let me modify the algorithm as follows:
1) Do no consider any edges that leave or entry the hammock.
2) Attempt a topological sort. Stop if the sort fails.
3) Detect a cycle as follows. For ever node in the successor set,
compute the set of predecessor nodes that are reachable from in-edges
that have not been scheduled as well as the set of successor nodes that
are reachable through out-edges and have not been scheduled. The
intersection of these two sets is a new set of nodes that form a cycle.
Set a cycle bit for these nodes and remove edges from this set of
nodes that end in the node being considered. Resume the topological
sort, giving priority to nodes with the cycle bit set if there is a choice.
This forces the algorithm to always select:
1) A, B, C, E, D, F
Note that it is still not optimal in cases where there are multiple
interacting loops because the iteration count for each loop is not
known. If we had profiling information, we could give priority to nodes
that are part of loops that exit the loop frequently.
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>BUG: make_pair should not take any template arguments.<commit_after>
#include <map>
#include <set>
#include <ocelot/ir/interface/HammockGraph.h>
#include <ocelot/ir/interface/Instruction.h>
#include <hydrazine/implementation/string.h>
#include <hydrazine/implementation/debug.h>
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif
#define REPORT_BASE 1
/////////////////////////////////////////////////////////////////////////////////////////////////
ir::HammockGraph::~HammockGraph() {
}
ir::HammockGraph::HammockGraph(ir::ControlFlowGraph * _cfg): type(Subgraph), cfg(_cfg), domTree(_cfg), pdomTree(_cfg) {
// compute dominance relations
typedef std::vector< std::vector<int> > BasicBlockTree;
typedef std::multimap< int, int > DomTreeEdges;
std::map< int, int > DomToIDomMap;
DomTreeEdges idom;
DomTreeEdges ipdom;
// enumerate immediate dominator edges
int n = 0;
for (BasicBlockTree::iterator dom_it = domTree.dominated.begin();
dom_it != domTree.dominated.end(); ++dom_it, n++ ) {
for (std::vector< int >::iterator dom_it_it = dom_it->begin(); dom_it_it != dom_it->end(); ++dom_it_it) {
idom.insert(std::make_pair(n, *dom_it_it));
}
}
// enumerage immediate post-dominator edges
int p = 0;
for (BasicBlockTree::iterator pdom_it = pdomTree.dominated.begin();
pdom_it != pdomTree.dominated.end(); ++pdom_it, p++ ) {
for (std::vector< int >::iterator pdom_it_it = pdom_it->begin(); pdom_it_it != pdom_it->end(); ++pdom_it_it) {
ipdom.insert(std::make_pair((int)pdomTree.dominated.size() - 1 - p, (int)pdomTree.dominated.size() - 1 - *pdom_it_it));
}
}
// duplicates indicate hammocks
for (DomTreeEdges::iterator idom_it = idom.begin(); idom_it != idom.end(); ++idom_it) {
std::pair<DomTreeEdges::iterator, DomTreeEdges::iterator> ipdom_it = ipdom.equal_range(idom_it->second);
for (; ipdom_it.first != ipdom_it.second; ++(ipdom_it.first)) {
if ((ipdom_it.first)->first == idom_it->second) {
//
// found a hammock graph
//
// (idom_it->first, idom_it->second) is a hammock
int u = idom_it->first, v = idom_it->second;
// TODO - ignore 2-node hammocks (i.e. u has exactly one out-edge [to v])
if (domTree.blocks[u]->successors.size() > 1) {
hammocks.insert(std::make_pair(u,v));
}
}
}
}
#if REPORT_BASE
report(hammocks.size() << " hammocks");
for (std::map< int, int >::iterator h_it = hammocks.begin(); h_it != hammocks.end(); ++h_it) {
report("subgraph (" << domTree.blocks[h_it->first]->label << ", " << domTree.blocks[h_it->second]->label
<< ") is a hammock - {" << h_it->first << ", " << h_it->second << "}");
}
#endif
// now recursively partition - this part could be challenging
topological_sequence();
}
/*!
\brief
*/
void ir::HammockGraph::schedule_hammock(ir::ControlFlowGraph::BlockPointerVector & sequence,
std::set<int> & scheduled, int entry, int exit) {
typedef std::vector< std::vector<int> > BasicBlockTree;
typedef ir::ControlFlowGraph::BlockPointerVector BlockPointerVector;
/*
Algorithm for scheduling a hammock
1.) reverse post-order DFS traversal of the graph
2.) if the current node has already been scheduled, skip it
3.) pop the current node from the front of the sequence and schedule it.
4.) If it is the entry to a hammock, schedule the hammock.
*/
report(" schedule_hammock(" << domTree.blocks[entry]->label << ", " << domTree.blocks[exit]->label << ")");
report(" scheduling " << domTree.blocks[entry]->label);
sequence.push_back(domTree.blocks[entry]);
scheduled.insert(entry);
std::deque< int > worklist;
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
for (BlockPointerVector::const_iterator succ_it = domTree.blocks[entry]->successors.begin();
succ_it != domTree.blocks[entry]->successors.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
while (worklist.size()) {
int node = worklist.front(); worklist.pop_front();
std::map< int, int >::iterator h_it = hammocks.find(node);
if (h_it != hammocks.end()) {
schedule_hammock(sequence, scheduled, h_it->first, h_it->second);
if (scheduled.find(h_it->second) == scheduled.end()) {
report(" scheduling " << domTree.blocks[h_it->second]->label);
sequence.push_back(domTree.blocks[h_it->second]);
scheduled.insert(h_it->second);
}
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
BlockPointerVector & succ = domTree.blocks[h_it->second]->successors;
for (BlockPointerVector::const_iterator succ_it = succ.begin(); succ_it != succ.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
}
else {
if (scheduled.find(node) == scheduled.end()) {
report(" scheduling " << domTree.blocks[node]->label);
sequence.push_back(domTree.blocks[node]);
scheduled.insert(node);
}
//
// visit successors and push onto work-list [checking to avoid re-scheduling]
//
BlockPointerVector & succ = domTree.blocks[node]->successors;
for (BlockPointerVector::const_iterator succ_it = succ.begin(); succ_it != succ.end(); ++succ_it) {
int p = (int)domTree.blocksToIndex[*succ_it];
if (scheduled.find(p) == scheduled.end()) {
worklist.push_back(p);
}
}
}
}
report(" end schedule_hammock(" << domTree.blocks[entry]->label << ", " << domTree.blocks[exit]->label << ")");
}
/*!
\brief performs a topological sort to maximize reconvergence opportunities and ensure forward progress
*/
ir::ControlFlowGraph::BlockPointerVector ir::HammockGraph::topological_sequence() {
typedef ir::ControlFlowGraph::BlockPointerVector BlockPointerVector;
std::set< int > scheduled;
BlockPointerVector sequence;
schedule_hammock(sequence, scheduled, domTree.blocksToIndex[ domTree.blocks[0] ],
domTree.blocksToIndex[ pdomTree.blocks[0] ]);
// tests:
// are all blocks scheduled exactly once?
// is the entry node the first block?
// are hammocks scheduled correctly?
report("schedule:");
for (BlockPointerVector::iterator bb_it = sequence.begin(); bb_it != sequence.end(); ++bb_it) {
report(" " << (*bb_it)->label);
}
return sequence;
}
/*
1) Do no consider any edges that leave or entry the hammock.
2) Attempt a topological sort. This is done by starting with the entry
node, adding all successors to a set, then picking the next node to
schedule from the successor set such that all of it's predecessors are
either not contained in the hammock, or are already scheduled.
3) If the sort fails, there is a cycle that ends with at least one node
in the successor set. Discover the cycle and remove all edges that
cycle exit the cycle. This can be accomplished by performing a
traversal starting from each node in the successor list. If the
traversal ever ends with the starting node, then there is a cycle ending
in that node. Ignore the edge that completes the cycle. Resume the
topological sort.
Consider the following example:
A -> B
A -> C
B -> D
C -> D
C -> E
D -> F
E -> C
E -> F
This algorithm could produce the following schedules:
1) A, B, C, D, E, F
2) A, B, C, E, D, F
In these cases, 2) has the potential to be faster than 1) because the
node E that is part of the cycle C -> E -> C is given priority over D.
So if threads iterate over the cycle multiple times then some threads
could be peeled off on every iteration and branch to D. Schedule 1)
would push these one at a time to F, while schedule 2) would accumulate
them at D and then push them to F all at once. This leads me to another
rule of thumb: during scheduling, nodes that are part of a cycle should
be given scheduling priority over nodes that are not.
So let me modify the algorithm as follows:
1) Do no consider any edges that leave or entry the hammock.
2) Attempt a topological sort. Stop if the sort fails.
3) Detect a cycle as follows. For ever node in the successor set,
compute the set of predecessor nodes that are reachable from in-edges
that have not been scheduled as well as the set of successor nodes that
are reachable through out-edges and have not been scheduled. The
intersection of these two sets is a new set of nodes that form a cycle.
Set a cycle bit for these nodes and remove edges from this set of
nodes that end in the node being considered. Resume the topological
sort, giving priority to nodes with the cycle bit set if there is a choice.
This forces the algorithm to always select:
1) A, B, C, E, D, F
Note that it is still not optimal in cases where there are multiple
interacting loops because the iteration count for each loop is not
known. If we had profiling information, we could give priority to nodes
that are part of loops that exit the loop frequently.
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "csgfxldr/gifimage.h"
//---------------------------------------------------------------------------
bool RegisterGIF ()
{
static csGIFImageLoader loader;
return csImageLoader::Register (&loader);
}
csImageFile* csGIFImageLoader::LoadImage (UByte* iBuffer, ULong iSize, int iFormat)
{
ImageGifFile* i = new ImageGifFile (iFormat);
if (i && !i->Load (iBuffer, iSize))
{
delete i;
return NULL;
}
return i;
}
//---------------------------------------------------------------------------
#define IMAGESEP 0x2c
#define GRAPHIC_EXT 0xf9
#define PLAINTEXT_EXT 0x01
#define APPLICATION_EXT 0xff
#define COMMENT_EXT 0xfe
#define START_EXTENSION 0x21
#define INTERLACEMASK 0x40
#define COLORMAPMASK 0x80
#define GIF_BadExtension 1
#define GIF_OutCount 2
#define GIF_CodeSize 3
#define GIF_BadFormat 4
//---------------------------------------------------------------------------
class GIFStream
{
private:
UByte *buf, *ptr, *bmark;
long size, remaining;
UByte bitoffs;
bool EOFcode;
public:
GIFStream(UByte* b, long fsize, int offs=0) :
buf(b), ptr(b+offs), bmark(NULL), size(fsize), remaining(fsize-offs),
bitoffs(0), EOFcode( fsize <= offs ) {}
UByte operator* () const
{ if (EOFcode) return 0; else return *ptr; }
UByte operator[] (int i) const
{ if (i >= remaining) return 0; else return ptr[i]; }
GIFStream& operator++ ()
{ ptr++; remaining--; EOFcode = remaining<=0; return *this; }
GIFStream operator++ (int)
{ GIFStream t = *this; ++(*this); return t; }
GIFStream& operator+= (int i)
{ ptr += i; remaining -= i; EOFcode = remaining<=0; return *this; }
bool isEOF() const { return EOFcode; }
UByte nextbyte() { return *(*this)++; }
int nextword() { int r = nextbyte(); return ( nextbyte() << 8 ) + r; }
int nextcode(UByte codesize);
private:
int getunblock();
};
int GIFStream::getunblock()
{
if (!bmark) bmark = ptr;
while ( (bmark <= ptr) && (bmark < buf+size) )
{
++(*this);
bmark += *bmark+1;
}
int r = *(*this);
if (bmark > ptr+1) r += (*this)[1] << 8;
else r += (*this)[2] << 8;
if (bmark > ptr+2) r += (*this)[2] << 16;
else r += (*this)[3] << 16;
return r;
}
int GIFStream::nextcode(UByte codesize)
{
int code = getunblock();
code = (code >> bitoffs) & ( (1<<codesize) - 1 );
bitoffs += codesize;
(*this) += bitoffs >> 3;
bitoffs &= 7;
return code;
}
//---------------------------------------------------------------------------
class GIFOutput
{
private:
UByte *img;
int w, h, x, y;
bool interlaced;
int pass;
public:
GIFOutput (int width, int height, bool ilace = false) : w (width), h (height),
x (0), y (0), interlaced (ilace), pass (0)
{
img = new UByte [width * height];
}
UByte& operator* () const
{ return *(img + y * w + x); }
GIFOutput& operator++ ()
{
if (++x == w)
{
x = 0;
if (!interlaced)
y++;
else
{
if (pass > 0 && pass < 4)
y += 16 >> pass;
else if (pass == 0)
y += 8;
if (y >= h && pass < 3)
y = 1 << (2 - pass++);
}
if (y >= h)
y = 0;
} /* if (++x == w) */
return *this;
}
UByte *get_image () { return img; }
};
//---------------------------------------------------------------------------
class GIFPalette
{
private:
csRGBcolor palette[256];
int pal_size;
int bitmask;
public:
GIFPalette () : pal_size (0), bitmask (0) {}
void Load (GIFStream& gptr, int size)
{
pal_size = (size < 0) ? 0 : (size > 256) ? 256 : size;
bitmask = pal_size - 1;
for (int i = 0; i < pal_size; i++)
{
palette[i].red = gptr.nextbyte ();
palette[i].green = gptr.nextbyte ();
palette[i].blue = gptr.nextbyte ();
}
}
csRGBcolor operator () (int i)
{ return palette [i & bitmask]; }
int get_size () const { return pal_size; }
int get_mask () const { return bitmask; }
csRGBcolor *get_palette () { return palette; }
};
//---------------------------------------------------------------------------
int ImageGifFile::decode_gif (UByte* iBuffer, long iSize, int* Prefix,
int* Suffix, int* OutCode)
{
GIFStream gptr (iBuffer,iSize);
GIFPalette palette;
UByte ch;
if (strncmp( (char*)iBuffer, "GIF87a", 6) && strncmp( (char*)iBuffer, "GIF89a", 6))
return GIF_BadFormat;
gptr += 6;
// Get variables from the GIF screen descriptor
gptr += 4; // skip screen width, screen height (unused)
ch = gptr.nextbyte();
bool has_cmap = ch & COLORMAPMASK;
int cmap_size = 1 << ( (ch & 7) + 1 );
gptr += 2; // skip 2 bytes : background color and '0'
if (has_cmap) palette.Load (gptr, cmap_size);
// look for image separator
for (UByte i = gptr.nextbyte() ; i != IMAGESEP ; i = gptr.nextbyte())
{
if (i != START_EXTENSION)
return GIF_BadFormat;
// handle image extensions
switch (ch = gptr.nextbyte())
{
case GRAPHIC_EXT:
ch = gptr.nextbyte();
if (*gptr & 0x1) (void)gptr; // image is transparent
gptr += ch;
break;
case PLAINTEXT_EXT:
break;
case APPLICATION_EXT:
break;
case COMMENT_EXT:
break;
default:
return GIF_BadExtension;
}
while ((ch = gptr.nextbyte()) != 0) gptr += ch;
}
// Now read in values from the image descriptor
gptr += 4; // skipping Left Offset, Top Offset
int width = gptr.nextword();
int height = gptr.nextword();
set_dimensions (width, height);
GIFOutput optr(width, height, (gptr.nextbyte() & INTERLACEMASK));
// Note that I ignore the possible existence of a local color map.
// I'm told there aren't many files around that use them, and the spec
// says it's defined for future use. This could lead to an error
// reading some files.
// Start reading the raster data. First we get the intial code size
// and compute decompressor constant values, based on this code size.
// The GIF spec has it that the code size is the code size used to
// compute the above values is the code size given in the file, but the
// code size used in compression/decompression is the code size given in
// the file plus one. (thus the ++).
int code_size = gptr.nextbyte(); // bits per code
int val_clear = 1 << code_size; // code representing 'clear'
int val_EOF = val_clear + 1; // code representing 'EOF'
int code_free = val_clear + 2; //
int first_free = code_free; // initial value of code_free
int first_size = ++code_size; // initial value of code_size
int code_max = val_clear << 1; // upper bound for each code
int OutCount = 0;
if (code_size > 12)
return GIF_CodeSize;
// Decompress the file, continuing until you see the GIF EOF code.
// One obvious enhancement is to add checking for corrupt files here.
int code = gptr.nextcode(code_size);
int code_write = 0, code_old = 0;
while (code != val_EOF && !gptr.isEOF ())
{
if (code == val_clear)
{
// The Clear code sets everything back to its initial value,
// then reads the subsequent code as uncompressed data.
code_size = first_size;
code_max = 1 << code_size;
code_free = first_free;
code_write = code_old = code = gptr.nextcode(code_size);
*optr = code_write;
++optr;
}
else
{
// If it's not a Clear, then it must be data.
int code_in = code;
// If it's >= code_free, then it's not in the hash table yet;
// repeat the last character decoded.
if (OutCount > 1024)
return GIF_OutCount;
if (code >= code_free)
{
code = code_old;
OutCode[OutCount++] = code_write;
}
// Unless this code is raw data, pursue the chain pointed to by
// code_cur through the hash table to its end; each code in the
// chain puts its associated output code on the output queue.
while (code > palette.get_mask())
{
if (OutCount > 1024)
return GIF_OutCount;
OutCode[OutCount++] = Suffix[code];
code = Prefix[code];
}
// The last code in the chain is treated as raw data.
if (OutCount > 1024)
return GIF_OutCount;
OutCode[OutCount++] = code;
// Now we put the data out to the image buffer.
// It's been stacked LIFO, so deal with it that way...
for (int j = OutCount - 1; j >= 0; j--)
{
*optr = OutCode [j];
++optr;
}
OutCount = 0;
// Build the hash table on-the-fly. No table is stored in the file.
Prefix[code_free] = code_old;
Suffix[code_free] = code_write = code;
code_old = code_in;
// Point to the next slot in the table. If we exceed the current
// max code value, increment the code size unless it's already 12.
// If the size is already 12, do nothing: the next code better be
// CLEAR.
if (++code_free >= code_max)
{
if (code_size < 12) { code_size++; code_max <<= 1; }
}
}
code = gptr.nextcode(code_size);
}
Format &= ~CS_IMGFMT_ALPHA;
convert_pal8 (optr.get_image (), palette.get_palette ());
return 0;
}
bool ImageGifFile::Load (UByte* iBuffer, ULong iSize)
{
int* Prefix = new int [4096]; // Hash table used by decompressor.
int* Suffix = new int [4096]; // Hash table used by decompressor.
int* OutCode = new int [1025]; // Output array used by decompressor.
int rc = decode_gif (iBuffer, iSize, Prefix, Suffix, OutCode);
delete [] Prefix;
delete [] Suffix;
delete [] OutCode;
return (rc == 0);
}
<commit_msg><commit_after>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "csgfxldr/gifimage.h"
//---------------------------------------------------------------------------
bool RegisterGIF ()
{
static csGIFImageLoader loader;
return csImageLoader::Register (&loader);
}
csImageFile* csGIFImageLoader::LoadImage (UByte* iBuffer, ULong iSize, int iFormat)
{
ImageGifFile* i = new ImageGifFile (iFormat);
if (i && !i->Load (iBuffer, iSize))
{
delete i;
return NULL;
}
return i;
}
//---------------------------------------------------------------------------
#define IMAGESEP 0x2c
#define GRAPHIC_EXT 0xf9
#define PLAINTEXT_EXT 0x01
#define APPLICATION_EXT 0xff
#define COMMENT_EXT 0xfe
#define START_EXTENSION 0x21
#define INTERLACEMASK 0x40
#define COLORMAPMASK 0x80
#define GIF_BadExtension 1
#define GIF_OutCount 2
#define GIF_CodeSize 3
#define GIF_BadFormat 4
//---------------------------------------------------------------------------
class GIFStream
{
private:
UByte *buf, *ptr, *bmark;
long size, remaining;
UByte bitoffs;
bool EOFcode;
public:
GIFStream(UByte* b, long fsize, int offs=0) :
buf(b), ptr(b+offs), bmark(NULL), size(fsize), remaining(fsize-offs),
bitoffs(0), EOFcode( fsize <= offs ) {}
UByte operator* () const
{ if (EOFcode) return 0; else return *ptr; }
UByte operator[] (int i) const
{ if (i >= remaining) return 0; else return ptr[i]; }
GIFStream& operator++ ()
{ ptr++; remaining--; EOFcode = remaining<=0; return *this; }
GIFStream operator++ (int)
{ GIFStream t = *this; ++(*this); return t; }
GIFStream& operator+= (int i)
{ ptr += i; remaining -= i; EOFcode = remaining<=0; return *this; }
bool isEOF() const { return EOFcode; }
UByte nextbyte() { return *(*this)++; }
int nextword() { int r = nextbyte(); return ( nextbyte() << 8 ) + r; }
int nextcode(UByte codesize);
private:
int getunblock();
};
int GIFStream::getunblock()
{
if (!bmark) bmark = ptr;
while ( (bmark <= ptr) && (bmark < buf+size) )
{
++(*this);
bmark += *bmark+1;
}
int r = *(*this);
if (bmark > ptr+1) r += (*this)[1] << 8;
else r += (*this)[2] << 8;
if (bmark > ptr+2) r += (*this)[2] << 16;
else r += (*this)[3] << 16;
return r;
}
int GIFStream::nextcode(UByte codesize)
{
int code = getunblock();
code = (code >> bitoffs) & ( (1<<codesize) - 1 );
bitoffs += codesize;
(*this) += bitoffs >> 3;
bitoffs &= 7;
return code;
}
//---------------------------------------------------------------------------
class GIFOutput
{
private:
UByte *img;
int w, h, x, y;
bool interlaced;
int pass;
public:
GIFOutput (int width, int height, bool ilace = false) : w (width), h (height),
x (0), y (0), interlaced (ilace), pass (0)
{
img = new UByte [width * height];
}
UByte& operator* () const
{ return *(img + y * w + x); }
GIFOutput& operator++ ()
{
if (++x == w)
{
x = 0;
if (!interlaced)
y++;
else
{
if (pass > 0 && pass < 4)
y += 16 >> pass;
else if (pass == 0)
y += 8;
if (y >= h && pass < 3)
y = 1 << (2 - pass++);
}
if (y >= h)
y = 0;
} /* if (++x == w) */
return *this;
}
UByte *get_image () { return img; }
};
//---------------------------------------------------------------------------
class GIFPalette
{
private:
csRGBcolor palette[256];
int pal_size;
int bitmask;
public:
GIFPalette () : pal_size (0), bitmask (0) {}
void Load (GIFStream& gptr, int size)
{
pal_size = (size < 0) ? 0 : (size > 256) ? 256 : size;
bitmask = pal_size - 1;
for (int i = 0; i < pal_size; i++)
{
palette[i].red = gptr.nextbyte ();
palette[i].green = gptr.nextbyte ();
palette[i].blue = gptr.nextbyte ();
}
}
csRGBcolor operator () (int i)
{ return palette [i & bitmask]; }
int get_size () const { return pal_size; }
int get_mask () const { return bitmask; }
csRGBcolor *get_palette () { return palette; }
};
//---------------------------------------------------------------------------
int ImageGifFile::decode_gif (UByte* iBuffer, long iSize, int* Prefix,
int* Suffix, int* OutCode)
{
GIFStream gptr (iBuffer,iSize);
GIFPalette palette;
UByte ch;
int is_transparent = 0;
UByte transp_index = 0;
if (strncmp( (char*)iBuffer, "GIF87a", 6) && strncmp( (char*)iBuffer, "GIF89a", 6))
return GIF_BadFormat;
gptr += 6;
// Get variables from the GIF screen descriptor
gptr += 4; // skip screen width, screen height (unused)
ch = gptr.nextbyte();
bool has_cmap = ch & COLORMAPMASK;
int cmap_size = 1 << ( (ch & 7) + 1 );
gptr += 2; // skip 2 bytes : background color and '0'
if (has_cmap) palette.Load (gptr, cmap_size);
// look for image separator
for (UByte i = gptr.nextbyte() ; i != IMAGESEP ; i = gptr.nextbyte())
{
if (i != START_EXTENSION)
return GIF_BadFormat;
// handle image extensions
switch (ch = gptr.nextbyte())
{
case GRAPHIC_EXT:
ch = gptr.nextbyte();
if (*gptr & 0x1)
{
// image is transparent
is_transparent = 1;
// get transparent color index - (ch==4), so the 3'th byte
transp_index = gptr[3];
csRGBcolor tcol = palette(transp_index);
#ifdef CS_DEBUG
printf("Transparent colour index is %d (%d,%d,%d).\n",
transp_index, tcol.red, tcol.green, tcol.blue);
#endif // CS_DEBUG
}
gptr += ch;
break;
case PLAINTEXT_EXT:
break;
case APPLICATION_EXT:
break;
case COMMENT_EXT:
break;
default:
return GIF_BadExtension;
}
while ((ch = gptr.nextbyte()) != 0) gptr += ch;
}
// Now read in values from the image descriptor
gptr += 4; // skipping Left Offset, Top Offset
int width = gptr.nextword();
int height = gptr.nextword();
set_dimensions (width, height);
GIFOutput optr(width, height, (gptr.nextbyte() & INTERLACEMASK));
// Note that I ignore the possible existence of a local color map.
// I'm told there aren't many files around that use them, and the spec
// says it's defined for future use. This could lead to an error
// reading some files.
// Start reading the raster data. First we get the intial code size
// and compute decompressor constant values, based on this code size.
// The GIF spec has it that the code size is the code size used to
// compute the above values is the code size given in the file, but the
// code size used in compression/decompression is the code size given in
// the file plus one. (thus the ++).
int code_size = gptr.nextbyte(); // bits per code
int val_clear = 1 << code_size; // code representing 'clear'
int val_EOF = val_clear + 1; // code representing 'EOF'
int code_free = val_clear + 2; //
int first_free = code_free; // initial value of code_free
int first_size = ++code_size; // initial value of code_size
int code_max = val_clear << 1; // upper bound for each code
int OutCount = 0;
if (code_size > 12)
return GIF_CodeSize;
// Decompress the file, continuing until you see the GIF EOF code.
// One obvious enhancement is to add checking for corrupt files here.
int code = gptr.nextcode(code_size);
int code_write = 0, code_old = 0;
while (code != val_EOF && !gptr.isEOF ())
{
if (code == val_clear)
{
// The Clear code sets everything back to its initial value,
// then reads the subsequent code as uncompressed data.
code_size = first_size;
code_max = 1 << code_size;
code_free = first_free;
code_write = code_old = code = gptr.nextcode(code_size);
*optr = code_write;
++optr;
}
else
{
// If it's not a Clear, then it must be data.
int code_in = code;
// If it's >= code_free, then it's not in the hash table yet;
// repeat the last character decoded.
if (OutCount > 1024)
return GIF_OutCount;
if (code >= code_free)
{
code = code_old;
OutCode[OutCount++] = code_write;
}
// Unless this code is raw data, pursue the chain pointed to by
// code_cur through the hash table to its end; each code in the
// chain puts its associated output code on the output queue.
while (code > palette.get_mask())
{
if (OutCount > 1024)
return GIF_OutCount;
OutCode[OutCount++] = Suffix[code];
code = Prefix[code];
}
// The last code in the chain is treated as raw data.
if (OutCount > 1024)
return GIF_OutCount;
OutCode[OutCount++] = code;
// Now we put the data out to the image buffer.
// It's been stacked LIFO, so deal with it that way...
for (int j = OutCount - 1; j >= 0; j--)
{
*optr = OutCode [j];
++optr;
}
OutCount = 0;
// Build the hash table on-the-fly. No table is stored in the file.
Prefix[code_free] = code_old;
Suffix[code_free] = code_write = code;
code_old = code_in;
// Point to the next slot in the table. If we exceed the current
// max code value, increment the code size unless it's already 12.
// If the size is already 12, do nothing: the next code better be
// CLEAR.
if (++code_free >= code_max)
{
if (code_size < 12) { code_size++; code_max <<= 1; }
}
}
code = gptr.nextcode(code_size);
}
Format &= ~CS_IMGFMT_ALPHA;
convert_pal8 (optr.get_image (), palette.get_palette ());
return 0;
}
bool ImageGifFile::Load (UByte* iBuffer, ULong iSize)
{
int* Prefix = new int [4096]; // Hash table used by decompressor.
int* Suffix = new int [4096]; // Hash table used by decompressor.
int* OutCode = new int [1025]; // Output array used by decompressor.
int rc = decode_gif (iBuffer, iSize, Prefix, Suffix, OutCode);
delete [] Prefix;
delete [] Suffix;
delete [] OutCode;
return (rc == 0);
}
<|endoftext|> |
<commit_before>/*
Dynamics/Kinematics modeling and simulation library.
Copyright (C) 1999 by Michael Alexander Ewert
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// bleh, bleh, I am articula; I don't drink.... wine.....
//!me stuff todo
// uhhhh R_fg, I suspect this could just be selected local vars
#include "csphyzik/articula.h"
#include "csphyzik/joint.h"
#include "csphyzik/debug.h"
#include "csphyzik/feathers.h"
#include "csphyzik/ik.h"
// set friction for this handles inboard joint
void ctArticulatedBody::set_joint_friction( double pfrict )
{
ctJoint::joint_friction = pfrict;
}
// constructor
ctArticulatedBody::ctArticulatedBody()
{
handle = NULL; inboard_joint = NULL;
is_grounded = false;
solver = new ctFeatherstoneAlgorithm( *this );
// solver = new ctInverseKinematics( *this );
}
// construct with a handle
ctArticulatedBody::ctArticulatedBody( ctRigidBody *phandle )
{
handle = phandle; inboard_joint = NULL;
is_grounded = false;
solver = new ctFeatherstoneAlgorithm( *this );
// solver = new ctInverseKinematics( *this );
}
// clean up
ctArticulatedBody::~ctArticulatedBody()
{
ctArticulatedBody *out_link;
if( solver )
delete solver;
if( handle )
delete handle;
if( inboard_joint )
delete inboard_joint;
out_link = outboard_links.get_first();
while( out_link ){
delete out_link;
out_link = outboard_links.get_next();
}
}
//!me I don't really like the way this works....
// change the solver to featherstone
ctFeatherstoneAlgorithm *ctArticulatedBody::install_featherstone_solver()
{
ctArticulatedBody *out_link;
ctFeatherstoneAlgorithm *feather_solve;
if( solver ){
delete solver;
}
solver = feather_solve = new ctFeatherstoneAlgorithm( *this );
out_link = outboard_links.get_first();
while( out_link ){
out_link->install_featherstone_solver();
out_link = outboard_links.get_next();
}
return feather_solve;
}
// change the solver to IK. Set the goal for the returned solver
ctInverseKinematics *ctArticulatedBody::install_IK_solver()
{
ctArticulatedBody *out_link;
ctInverseKinematics *ik_solve;
if( solver ){
delete solver;
}
solver = ik_solve = new ctInverseKinematics( *this );
out_link = outboard_links.get_first();
while( out_link ){
out_link->install_IK_solver();
out_link = outboard_links.get_next();
}
return ik_solve;
}
int ctArticulatedBody::get_state_size()
{
ctArticulatedBody *out_link;
int sze = 0;
if( !is_grounded && handle ){
sze += handle->get_state_size();
}
out_link = outboard_links.get_first();
while( out_link ){
sze += JOINT_STATESIZE;
sze += out_link->get_state_size();
out_link = outboard_links.get_next();
}
return sze;
}
void ctArticulatedBody::init_state()
{
ctArticulatedBody *out_link;
if(handle) handle->init_state();
out_link = outboard_links.get_first();
while( out_link ){
out_link->init_state();
out_link = outboard_links.get_next();
}
} //!me init joint as well???}//F.x = 0; F.y = 0; F.z = 0; T.x = 0; T.y = 0; T.z = 0; }
//!me would be better OOD to call joint->solve() and do all calculations there
// compute absolute velocities of all links from joint velocities of parents
void ctArticulatedBody::compute_link_velocities()
{
ctArticulatedBody *out_link;
ctJoint *jnt; // this bodies inboard joint
ctPhysicalEntity *pe_f; // parent ( inboard ) handle
ctRigidBody *pe_g; // this handle
jnt = inboard_joint;
pe_g = handle;
//!me add error log
if( pe_g == NULL ){
return;
}
//!me add error log
// ack something is wrong so try to limit the damage
if( jnt == NULL || jnt->inboard == NULL ){
ctVector3 vzero( 0.0,0.0,0.0 );
pe_g->set_angular_v( vzero );
pe_g->set_v( vzero );
}
pe_f = jnt->inboard->handle;
if( !pe_f ){
return;
}
// R_fg = R_world_g * R_f_world
// R is coord transfrom matrix, not rotation
R_fg = pe_g->get_world_to_this()*pe_f->get_this_to_world();
// vector from C.O.M. of F to G in G's ref frame.
r_fg = pe_g->get_T()*( pe_g->get_org_world() - pe_f->get_org_world() );
// calc contribution to v and w from parent link.
pe_g->w = R_fg*pe_f->get_angular_v();
pe_g->v = R_fg*pe_f->get_v() + pe_g->get_angular_v() % r_fg;
// get joint to calculate final result for v and angular v ( w )
jnt->calc_vw( pe_g->v, pe_g->w );
// iterate to next links
out_link = outboard_links.get_first();
while( out_link ){
out_link->compute_link_velocities();
out_link = outboard_links.get_next();
}
}
// apply a force to all links of this articulated body
void ctArticulatedBody::apply_given_F( ctForce &frc )
{
ctPhysicalEntity *pe;
ctArticulatedBody *out_link;
pe = handle;
if( pe ){
pe->apply_given_F( frc );
out_link = outboard_links.get_first();
while( out_link ){
out_link->apply_given_F( frc );
out_link = outboard_links.get_next();
}
}
}
// calc F and torque from all applied forces
void ctArticulatedBody::apply_forces( real t )
{
ctPhysicalEntity *pe;
ctArticulatedBody *out_link;
pe = handle;
if( pe ){
pe->solve( t );
out_link = outboard_links.get_first();
while( out_link ){
out_link->apply_forces( t );
out_link = outboard_links.get_next();
}
}
}
int ctArticulatedBody::set_state( real *state_array )
{
int ret = 0;
if( !is_grounded && handle ){
ret += handle->set_state( state_array );
state_array += ret;
}
ret += set_state_links( state_array );
return ret;
}
int ctArticulatedBody::set_state_links( real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->set_state( state_array );
state_array += ret;
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->set_state_links( state_array );
state_array += one_size;
ret += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
int ctArticulatedBody::get_state( const real *state_array )
{
int ret = 0;
if( !is_grounded && handle ){
ret += handle->get_state( state_array );
state_array += ret;
}
ret += get_state_links( state_array );
return ret;
}
int ctArticulatedBody::get_state_links( const real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->get_state( state_array );
state_array += ret;
// calc postion and orientation
inboard_joint->update_link_RF( R_fg );
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->get_state_links( state_array );
ret += one_size;
state_array += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
int ctArticulatedBody::set_delta_state( real *state_array )
{
int ret = 0;
if( !is_grounded && handle && solver ){
// calc F and T from spatial acceleration
// F = ma
// HAHA!!!!! a^ is relative to body frame!!!!
const ctMatrix3 &R = handle->get_R();
ctVector3 lin_a = R * (((ctArticulatedSolver *)solver)->get_linear_a());
lin_a *= handle->get_m();
handle->set_F( lin_a );
// T = I*alpha I is in world coords
ctMatrix3 I_world = R * handle->get_I() * (R.get_transpose());
ctVector3 alpha = R * (((ctArticulatedSolver *)solver)->get_angular_a());
handle->set_torque( I_world*alpha );
ret += handle->set_delta_state( state_array );
state_array += ret;
}
ret += set_delta_state_links( state_array );
return ret;
}
int ctArticulatedBody::set_delta_state_links( real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->set_delta_state( state_array );
state_array += ret;
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->set_delta_state_links( state_array );
ret += one_size;
state_array += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
// update position and orientation of all links according to joint angles
void ctArticulatedBody::update_links()
{
ctArticulatedBody *out_link;
if( inboard_joint ){
// calc postion and orientation
inboard_joint->update_link_RF( R_fg );
}
out_link = outboard_links.get_first();
while( out_link ){
out_link->update_links();
out_link = outboard_links.get_next();
}
}
// calc transform frame from parent to this
void ctArticulatedBody::calc_relative_frame()
{
ctJoint *jnt; // this bodies inboard joint
ctPhysicalEntity *pe_f; // parent ( inboard ) handle
ctRigidBody *pe_g; // this handle
jnt = inboard_joint;
pe_g = handle;
//!me add error log
if( pe_g == NULL ){
return;
}
// if root
if( jnt == NULL || jnt->inboard == NULL ){
r_fg = pe_g->get_pos();
R_fg = pe_g->get_world_to_this();
return;
}
pe_f = jnt->inboard->handle;
if( !pe_f ){
return;
}
// R_fg = R_world_g * R_f_world
// R is coord transfrom matrix, not rotation
R_fg = pe_g->get_world_to_this()*pe_f->get_this_to_world();
// vector from C.O.M. of F to G in G's ref frame.
r_fg = pe_g->get_T()*( pe_g->get_org_world() - pe_f->get_org_world() );
}
// link together two articulated bodies via a hing joint that hinges along given axis
void ctArticulatedBody::link_revolute( ctArticulatedBody *child, ctVector3 &pin_joint_offset, ctVector3 &pout_joint_offset, ctVector3 &pjoint_axis )
{
ctJoint *jnt = new ctRevoluteJoint( this, pin_joint_offset, child, pout_joint_offset, pjoint_axis );
child->inboard_joint = jnt;
child->calc_relative_frame();
outboard_links.add_link( child );
}
// explicit rotation
void ctArticulatedBody::rotate_around_axis( real ptheta )
{
if( inboard_joint ){
inboard_joint->q += ptheta;
calc_relative_frame();
}
}
<commit_msg>use set_v instead of v and w<commit_after>/*
Dynamics/Kinematics modeling and simulation library.
Copyright (C) 1999 by Michael Alexander Ewert
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// bleh, bleh, I am articula; I don't drink.... wine.....
//!me stuff todo
// uhhhh R_fg, I suspect this could just be selected local vars
#include "csphyzik/articula.h"
#include "csphyzik/joint.h"
#include "csphyzik/debug.h"
#include "csphyzik/feathers.h"
#include "csphyzik/ik.h"
// set friction for this handles inboard joint
void ctArticulatedBody::set_joint_friction( double pfrict )
{
ctJoint::joint_friction = pfrict;
}
// constructor
ctArticulatedBody::ctArticulatedBody()
{
handle = NULL; inboard_joint = NULL;
is_grounded = false;
solver = new ctFeatherstoneAlgorithm( *this );
// solver = new ctInverseKinematics( *this );
}
// construct with a handle
ctArticulatedBody::ctArticulatedBody( ctRigidBody *phandle )
{
handle = phandle; inboard_joint = NULL;
is_grounded = false;
solver = new ctFeatherstoneAlgorithm( *this );
// solver = new ctInverseKinematics( *this );
}
// clean up
ctArticulatedBody::~ctArticulatedBody()
{
ctArticulatedBody *out_link;
if( solver )
delete solver;
if( handle )
delete handle;
if( inboard_joint )
delete inboard_joint;
out_link = outboard_links.get_first();
while( out_link ){
delete out_link;
out_link = outboard_links.get_next();
}
}
//!me I don't really like the way this works....
// change the solver to featherstone
ctFeatherstoneAlgorithm *ctArticulatedBody::install_featherstone_solver()
{
ctArticulatedBody *out_link;
ctFeatherstoneAlgorithm *feather_solve;
if( solver ){
delete solver;
}
solver = feather_solve = new ctFeatherstoneAlgorithm( *this );
out_link = outboard_links.get_first();
while( out_link ){
out_link->install_featherstone_solver();
out_link = outboard_links.get_next();
}
return feather_solve;
}
// change the solver to IK. Set the goal for the returned solver
ctInverseKinematics *ctArticulatedBody::install_IK_solver()
{
ctArticulatedBody *out_link;
ctInverseKinematics *ik_solve;
if( solver ){
delete solver;
}
solver = ik_solve = new ctInverseKinematics( *this );
out_link = outboard_links.get_first();
while( out_link ){
out_link->install_IK_solver();
out_link = outboard_links.get_next();
}
return ik_solve;
}
int ctArticulatedBody::get_state_size()
{
ctArticulatedBody *out_link;
int sze = 0;
if( !is_grounded && handle ){
sze += handle->get_state_size();
}
out_link = outboard_links.get_first();
while( out_link ){
sze += JOINT_STATESIZE;
sze += out_link->get_state_size();
out_link = outboard_links.get_next();
}
return sze;
}
void ctArticulatedBody::init_state()
{
ctArticulatedBody *out_link;
if(handle) handle->init_state();
out_link = outboard_links.get_first();
while( out_link ){
out_link->init_state();
out_link = outboard_links.get_next();
}
} //!me init joint as well???}//F.x = 0; F.y = 0; F.z = 0; T.x = 0; T.y = 0; T.z = 0; }
//!me would be better OOD to call joint->solve() and do all calculations there
// compute absolute velocities of all links from joint velocities of parents
void ctArticulatedBody::compute_link_velocities()
{
ctArticulatedBody *out_link;
ctJoint *jnt; // this bodies inboard joint
ctPhysicalEntity *pe_f; // parent ( inboard ) handle
ctRigidBody *pe_g; // this handle
jnt = inboard_joint;
pe_g = handle;
//!me add error log
if( pe_g == NULL ){
return;
}
//!me add error log
// ack something is wrong so try to limit the damage
if( jnt == NULL || jnt->inboard == NULL ){
ctVector3 vzero( 0.0,0.0,0.0 );
pe_g->set_angular_v( vzero );
pe_g->set_v( vzero );
}
pe_f = jnt->inboard->handle;
if( !pe_f ){
return;
}
// R_fg = R_world_g * R_f_world
// R is coord transfrom matrix, not rotation
R_fg = pe_g->get_world_to_this()*pe_f->get_this_to_world();
// vector from C.O.M. of F to G in G's ref frame.
r_fg = pe_g->get_T()*( pe_g->get_org_world() - pe_f->get_org_world() );
// calc contribution to v and w from parent link.
//!me 1Dec99 pe_g->w = R_fg*pe_f->get_angular_v();
//!me 1Dec99 pe_g->v = R_fg*pe_f->get_v() + pe_g->get_angular_v() % r_fg;
ctVector3 w_prime = R_fg*pe_f->get_angular_v();
ctVector3 v_prime = R_fg*pe_f->get_v() + pe_g->get_angular_v() % r_fg;
// get joint to calculate final result for v and angular v ( w )
jnt->calc_vw( v_prime, w_prime );
pe_g->set_angular_v( w_prime );
pe_g->set_v( v_prime );
// iterate to next links
out_link = outboard_links.get_first();
while( out_link ){
out_link->compute_link_velocities();
out_link = outboard_links.get_next();
}
}
// apply a force to all links of this articulated body
void ctArticulatedBody::apply_given_F( ctForce &frc )
{
ctPhysicalEntity *pe;
ctArticulatedBody *out_link;
pe = handle;
if( pe ){
pe->apply_given_F( frc );
out_link = outboard_links.get_first();
while( out_link ){
out_link->apply_given_F( frc );
out_link = outboard_links.get_next();
}
}
}
// calc F and torque from all applied forces
void ctArticulatedBody::apply_forces( real t )
{
ctPhysicalEntity *pe;
ctArticulatedBody *out_link;
pe = handle;
if( pe ){
pe->solve( t );
out_link = outboard_links.get_first();
while( out_link ){
out_link->apply_forces( t );
out_link = outboard_links.get_next();
}
}
}
int ctArticulatedBody::set_state( real *state_array )
{
int ret = 0;
if( !is_grounded && handle ){
ret += handle->set_state( state_array );
state_array += ret;
}
ret += set_state_links( state_array );
return ret;
}
int ctArticulatedBody::set_state_links( real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->set_state( state_array );
state_array += ret;
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->set_state_links( state_array );
state_array += one_size;
ret += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
int ctArticulatedBody::get_state( const real *state_array )
{
int ret = 0;
if( !is_grounded && handle ){
ret += handle->get_state( state_array );
state_array += ret;
}
ret += get_state_links( state_array );
return ret;
}
int ctArticulatedBody::get_state_links( const real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->get_state( state_array );
state_array += ret;
// calc postion and orientation
inboard_joint->update_link_RF( R_fg );
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->get_state_links( state_array );
ret += one_size;
state_array += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
int ctArticulatedBody::set_delta_state( real *state_array )
{
int ret = 0;
if( !is_grounded && handle && solver ){
// calc F and T from spatial acceleration
// F = ma
// HAHA!!!!! a^ is relative to body frame!!!!
const ctMatrix3 &R = handle->get_R();
ctVector3 lin_a = R * (((ctArticulatedSolver *)solver)->get_linear_a());
lin_a *= handle->get_m();
handle->set_F( lin_a );
// T = I*alpha I is in world coords
ctMatrix3 I_world = R * handle->get_I() * (R.get_transpose());
ctVector3 alpha = R * (((ctArticulatedSolver *)solver)->get_angular_a());
handle->set_torque( I_world*alpha );
ret += handle->set_delta_state( state_array );
state_array += ret;
}
ret += set_delta_state_links( state_array );
return ret;
}
int ctArticulatedBody::set_delta_state_links( real *state_array )
{
int ret = 0;
int one_size;
ctArticulatedBody *out_link;
if( inboard_joint ){
ret = inboard_joint->set_delta_state( state_array );
state_array += ret;
}
out_link = outboard_links.get_first();
while( out_link ){
one_size = out_link->set_delta_state_links( state_array );
ret += one_size;
state_array += one_size;
out_link = outboard_links.get_next();
}
return ret;
}
// update position and orientation of all links according to joint angles
void ctArticulatedBody::update_links()
{
ctArticulatedBody *out_link;
if( inboard_joint ){
// calc postion and orientation
inboard_joint->update_link_RF( R_fg );
}
out_link = outboard_links.get_first();
while( out_link ){
out_link->update_links();
out_link = outboard_links.get_next();
}
}
// calc transform frame from parent to this
void ctArticulatedBody::calc_relative_frame()
{
ctJoint *jnt; // this bodies inboard joint
ctPhysicalEntity *pe_f; // parent ( inboard ) handle
ctRigidBody *pe_g; // this handle
jnt = inboard_joint;
pe_g = handle;
//!me add error log
if( pe_g == NULL ){
return;
}
// if root
if( jnt == NULL || jnt->inboard == NULL ){
r_fg = pe_g->get_pos();
R_fg = pe_g->get_world_to_this();
return;
}
pe_f = jnt->inboard->handle;
if( !pe_f ){
return;
}
// R_fg = R_world_g * R_f_world
// R is coord transfrom matrix, not rotation
R_fg = pe_g->get_world_to_this()*pe_f->get_this_to_world();
// vector from C.O.M. of F to G in G's ref frame.
r_fg = pe_g->get_T()*( pe_g->get_org_world() - pe_f->get_org_world() );
}
// link together two articulated bodies via a hing joint that hinges along given axis
void ctArticulatedBody::link_revolute( ctArticulatedBody *child, ctVector3 &pin_joint_offset, ctVector3 &pout_joint_offset, ctVector3 &pjoint_axis )
{
ctJoint *jnt = new ctRevoluteJoint( this, pin_joint_offset, child, pout_joint_offset, pjoint_axis );
child->inboard_joint = jnt;
child->calc_relative_frame();
outboard_links.add_link( child );
}
// explicit rotation
void ctArticulatedBody::rotate_around_axis( real ptheta )
{
if( inboard_joint ){
inboard_joint->q += ptheta;
calc_relative_frame();
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#include "ReQL-new.hpp"
#include <limits>
namespace ReQL {
static ReQL_Obj_t **
reql_alloc_arr(uint32_t size) {
return new ReQL_Obj_t *[size];
}
static ReQL_Pair_t *
reql_alloc_pair(uint32_t size) {
return new ReQL_Pair_t[size];
}
static ReQL_Obj_t *
reql_alloc_term() {
return new ReQL_Obj_t;
}
static ReQL_Obj_t *
reql_new_array(uint32_t size) {
ReQL_Obj_t *obj = reql_alloc_term();
ReQL_Obj_t **arr = reql_alloc_arr(size);
reql_array_init(obj, arr, size);
return obj;
}
static ReQL_Obj_t *
reql_new(bool val) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_bool_init(obj, val);
return obj;
}
static ReQL_Obj_t *
reql_new_make_array(ReQL_Obj_t *arg) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_ast_make_array(obj, arg, NULL);
return obj;
}
static ReQL_Obj_t *
reql_new_make_obj(ReQL_Obj_t *arg) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_ast_make_obj(obj, NULL, arg);
return obj;
}
static ReQL_Obj_t *
reql_new() {
ReQL_Obj_t *obj = reql_alloc_term();
reql_null_init(obj);
return obj;
}
static ReQL_Obj_t *
reql_new(double val) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_number_init(obj, val);
return obj;
}
static ReQL_Obj_t *
reql_new_object(uint32_t size) {
ReQL_Obj_t *obj = reql_alloc_term();
ReQL_Pair_t *pair = reql_alloc_pair(size);
reql_object_init(obj, pair, size);
return obj;
}
static ReQL_Obj_t *
reql_new(std::string val) {
size_t size = val.size();
if (size > UINT32_MAX) {
return NULL;
}
uint8_t *str = new uint8_t[size]();
val.copy((char *)str, size);
ReQL_Obj_t *obj = reql_alloc_term();
reql_string_init(obj, str, (uint32_t)size);
return obj;
}
ReQL::ReQL() : query(reql_new()), array(nullptr), object(nullptr) {
}
ReQL::ReQL(ReQL_AST_Function f, std::vector<ReQL> args, std::map<ReQL, ReQL> kwargs) {
const std::size_t args_size = args.size();
if (args_size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
const std::size_t kwargs_size = kwargs.size();
if (kwargs_size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
array = reql_new_array(static_cast<std::uint32_t>(args_size));
for (auto q : args) {
reql_array_append(array, q.query);
}
object = reql_new_object(static_cast<std::uint32_t>(kwargs_size));
for (auto q : kwargs) {
reql_object_add(object, q.first.query, q.second.query);
}
query = reql_alloc_term();
f(query, array, object);
}
ReQL::ReQL(std::string val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(double val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(bool val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(std::vector<ReQL> val) {
const std::size_t size = val.size();
if (size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
array = reql_new_array(static_cast<std::uint32_t>(size));
query = reql_new_make_array(array);
for (auto q : val) {
reql_array_append(query, q.query);
}
}
ReQL::ReQL(std::map<ReQL, ReQL> val) {
std::size_t size = val.size();
if (size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
object = reql_new_object(static_cast<std::uint32_t>(size));
query = reql_new_make_obj(object);
for (auto q : val) {
reql_object_add(query, q.first.query, q.second.query);
}
}
ReQL::ReQL(const ReQL &other)
:
query(reql_alloc_term()),
array(reql_new_array(reql_array_size(other.array))),
object(reql_new_object(reql_array_size(other.object))) {
std::memcpy(query, other.query, sizeof(ReQL_Obj_t));
ReQL_Iter_t it = reql_new_iter(other.array);
ReQL_Obj_t *elem;
while ((elem = reql_iter_next(&it)) != NULL) {
reql_array_append(array, elem);
}
it = reql_new_iter(other.object);
ReQL_Obj_t *key;
while ((key = reql_iter_next(&it)) != NULL) {
reql_object_add(object, key, reql_object_get(other.object, key));
}
}
ReQL::ReQL(ReQL &&other) {
query = other.query; other.query = nullptr;
array = other.array; other.array = nullptr;
object = other.object; other.object = nullptr;
}
ReQL &
ReQL::operator=(const ReQL &other) {
if (this != &other) {
std::memcpy(query, other.query, sizeof(ReQL_Obj_t));
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
array = reql_new_array(reql_array_size(other.array));
ReQL_Iter_t it = reql_new_iter(other.array);
ReQL_Obj_t *elem;
while ((elem = reql_iter_next(&it)) != NULL) {
reql_array_append(array, elem);
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
object = reql_new_object(reql_array_size(other.object));
it = reql_new_iter(other.object);
ReQL_Obj_t *key;
while ((key = reql_iter_next(&it)) != NULL) {
reql_object_add(object, key, reql_object_get(other.object, key));
}
}
return *this;
}
ReQL &
ReQL::operator=(ReQL &&other) {
if (this != &other) {
if (query != nullptr) {
delete query;
}
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
query = other.query; other.query = nullptr;
array = other.array; other.array = nullptr;
object = other.object; other.object = nullptr;
}
return *this;
}
bool
ReQL::operator<(const ReQL &other) const {
ReQL_Datum_t ltype = reql_datum_type(query), rtype = reql_datum_type(other.query);
if (ltype == rtype) {
switch (ltype) {
case REQL_R_ARRAY:
case REQL_R_BOOL:
case REQL_R_JSON:
case REQL_R_NULL:
case REQL_R_NUM:
case REQL_R_OBJECT:
case REQL_R_REQL: {
return query < other.query;
}
case REQL_R_STR: {
std::string same((char *)reql_string_buf(query), reql_string_size(query));
std::string diff((char *)reql_string_buf(other.query), reql_string_size(other.query));
return same < diff;
}
}
}
return ltype < rtype;
}
ReQL_Obj_t *
ReQL::data() const {
return query;
}
ReQL::~ReQL() {
if (query != nullptr) {
delete query;
}
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
}
}
<commit_msg>Handle nullptr values in copy/move constructors.<commit_after>/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#include "ReQL-new.hpp"
#include <limits>
namespace ReQL {
static ReQL_Obj_t **
reql_alloc_arr(uint32_t size) {
return new ReQL_Obj_t *[size];
}
static ReQL_Pair_t *
reql_alloc_pair(uint32_t size) {
return new ReQL_Pair_t[size];
}
static ReQL_Obj_t *
reql_alloc_term() {
return new ReQL_Obj_t;
}
static ReQL_Obj_t *
reql_new_array(uint32_t size) {
ReQL_Obj_t *obj = reql_alloc_term();
ReQL_Obj_t **arr = reql_alloc_arr(size);
reql_array_init(obj, arr, size);
return obj;
}
static ReQL_Obj_t *
reql_new(bool val) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_bool_init(obj, val);
return obj;
}
static ReQL_Obj_t *
reql_new_make_array(ReQL_Obj_t *arg) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_ast_make_array(obj, arg, NULL);
return obj;
}
static ReQL_Obj_t *
reql_new_make_obj(ReQL_Obj_t *arg) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_ast_make_obj(obj, NULL, arg);
return obj;
}
static ReQL_Obj_t *
reql_new() {
ReQL_Obj_t *obj = reql_alloc_term();
reql_null_init(obj);
return obj;
}
static ReQL_Obj_t *
reql_new(double val) {
ReQL_Obj_t *obj = reql_alloc_term();
reql_number_init(obj, val);
return obj;
}
static ReQL_Obj_t *
reql_new_object(uint32_t size) {
ReQL_Obj_t *obj = reql_alloc_term();
ReQL_Pair_t *pair = reql_alloc_pair(size);
reql_object_init(obj, pair, size);
return obj;
}
static ReQL_Obj_t *
reql_new(std::string val) {
size_t size = val.size();
if (size > UINT32_MAX) {
return NULL;
}
uint8_t *str = new uint8_t[size]();
val.copy((char *)str, size);
ReQL_Obj_t *obj = reql_alloc_term();
reql_string_init(obj, str, (uint32_t)size);
return obj;
}
ReQL::ReQL() : query(reql_new()), array(nullptr), object(nullptr) {
}
ReQL::ReQL(ReQL_AST_Function f, std::vector<ReQL> args, std::map<ReQL, ReQL> kwargs) {
const std::size_t args_size = args.size();
if (args_size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
const std::size_t kwargs_size = kwargs.size();
if (kwargs_size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
array = reql_new_array(static_cast<std::uint32_t>(args_size));
for (auto q : args) {
reql_array_append(array, q.query);
}
object = reql_new_object(static_cast<std::uint32_t>(kwargs_size));
for (auto q : kwargs) {
reql_object_add(object, q.first.query, q.second.query);
}
query = reql_alloc_term();
f(query, array, object);
}
ReQL::ReQL(std::string val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(double val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(bool val) : query(reql_new(val)), array(nullptr), object(nullptr) {
}
ReQL::ReQL(std::vector<ReQL> val) {
const std::size_t size = val.size();
if (size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
array = reql_new_array(static_cast<std::uint32_t>(size));
query = reql_new_make_array(array);
for (auto q : val) {
reql_array_append(query, q.query);
}
}
ReQL::ReQL(std::map<ReQL, ReQL> val) {
std::size_t size = val.size();
if (size > std::numeric_limits<std::uint32_t>::max()) {
return;
}
object = reql_new_object(static_cast<std::uint32_t>(size));
query = reql_new_make_obj(object);
for (auto q : val) {
reql_object_add(query, q.first.query, q.second.query);
}
}
ReQL::ReQL(const ReQL &other) : query(reql_alloc_term()) {
query->tt = other.query->tt;
query->obj = other.query->obj;
if (other.array == nullptr) {
array = nullptr;
} else {
array = reql_new_array(reql_array_size(other.array));
ReQL_Iter_t it = reql_new_iter(other.array);
ReQL_Obj_t *elem;
while ((elem = reql_iter_next(&it)) != NULL) {
reql_array_append(array, elem);
}
}
if (other.object == nullptr) {
object = nullptr;
} else {
object = (reql_new_object(reql_array_size(other.object)));
ReQL_Iter_t it = reql_new_iter(other.object);
ReQL_Obj_t *key;
while ((key = reql_iter_next(&it)) != NULL) {
reql_object_add(object, key, reql_object_get(other.object, key));
}
}
}
ReQL::ReQL(ReQL &&other) {
query = other.query; other.query = nullptr;
array = other.array; other.array = nullptr;
object = other.object; other.object = nullptr;
}
ReQL &
ReQL::operator=(const ReQL &other) {
if (this != &other) {
query->tt = other.query->tt;
query->obj = other.query->obj;
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
if (other.array != nullptr) {
array = reql_new_array(reql_array_size(other.array));
ReQL_Iter_t it = reql_new_iter(other.array);
ReQL_Obj_t *elem;
while ((elem = reql_iter_next(&it)) != NULL) {
reql_array_append(array, elem);
}
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
if (other.object != nullptr) {
object = reql_new_object(reql_array_size(other.object));
ReQL_Iter_t it = reql_new_iter(other.object);
ReQL_Obj_t *key;
while ((key = reql_iter_next(&it)) != NULL) {
reql_object_add(object, key, reql_object_get(other.object, key));
}
}
}
return *this;
}
ReQL &
ReQL::operator=(ReQL &&other) {
if (this != &other) {
if (query != nullptr) {
delete query;
}
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
query = other.query; other.query = nullptr;
array = other.array; other.array = nullptr;
object = other.object; other.object = nullptr;
}
return *this;
}
bool
ReQL::operator<(const ReQL &other) const {
ReQL_Datum_t ltype = reql_datum_type(query), rtype = reql_datum_type(other.query);
if (ltype == rtype) {
switch (ltype) {
case REQL_R_ARRAY:
case REQL_R_BOOL:
case REQL_R_JSON:
case REQL_R_NULL:
case REQL_R_NUM:
case REQL_R_OBJECT:
case REQL_R_REQL: {
return query < other.query;
}
case REQL_R_STR: {
std::string same((char *)reql_string_buf(query), reql_string_size(query));
std::string diff((char *)reql_string_buf(other.query), reql_string_size(other.query));
return same < diff;
}
}
}
return ltype < rtype;
}
ReQL_Obj_t *
ReQL::data() const {
return query;
}
ReQL::~ReQL() {
if (query != nullptr) {
delete query;
}
if (array != nullptr) {
delete [] array->obj.datum.json.var.data.array;
delete array;
}
if (object != nullptr) {
delete object->obj.datum.json.var.data.pair;
delete object;
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "switcherconfig.h"
#include <QDir>
#include <QJsonValue>
#include "apimanager.h"
#include "../Common/defines.h"
namespace Connectivity {
#if defined(QT_DEBUG)
#define LOCAL_SWITCHER_CONFIG "debug_switches.json"
#elif defined(INTEGRATION_TESTS)
#define LOCAL_SWITCHER_CONFIG "tests_switches.json"
#else
#define LOCAL_SWITCHER_CONFIG "switches.json"
#endif
#define VALUE_KEY QLatin1String("v")
#define THRESHOLD_KEY QLatin1String("t")
#define WIN_THRESHOLD_KEY QLatin1String("wt")
#define MAC_THRESHOLD_KEY QLatin1String("mt")
#define LIN_THRESHOLD_KEY QLatin1String("lt")
#define OVERWRITE_KEY QLatin1String("overwrite")
#define OVERWRITE_SWITCHER_CONFIG true
#define DONATE_CAMPAIGN_1_KEY QLatin1String("donateCampaign1")
#define DONATE_CAMPAIGN_1_STAGE_2 QLatin1String("donateCampaign1Stage2")
#define PROGRESSIVE_SUGGESTION_PREVIEWS QLatin1String("progressiveSuggestionPreviews")
#define DIRECT_METADATA_EXPORT QLatin1String("directExport")
#define GOOD_QUALITY_VIDEO_PREVIEWS QLatin1String("qualityVideoPreviews")
QDebug operator << (QDebug d, const SwitcherConfig::SwitchValue &value) {
d << "{" << value.m_IsOn << "*" << value.m_Threshold << "}";
return d;
}
SwitcherConfig::SwitcherConfig(QObject *parent):
Models::AbstractConfigUpdaterModel(OVERWRITE_SWITCHER_CONFIG, parent)
{
}
void SwitcherConfig::initializeConfigs() {
QString localConfigPath;
QString appDataPath = XPIKS_USERDATA_PATH;
if (!appDataPath.isEmpty()) {
QDir appDataDir(appDataPath);
localConfigPath = appDataDir.filePath(LOCAL_SWITCHER_CONFIG);
} else {
localConfigPath = LOCAL_SWITCHER_CONFIG;
}
auto &apiManager = Connectivity::ApiManager::getInstance();
QString remoteAddress = apiManager.getSwitcherAddr();
AbstractConfigUpdaterModel::initializeConfigs(remoteAddress, localConfigPath);
}
bool SwitcherConfig::isSwitchOn(int switchKey, int minThreshold) {
QReadLocker locker(&m_RwLock);
Q_UNUSED(locker);
bool isOn = false;
if (m_SwitchesHash.contains(switchKey)) {
SwitchValue &value = m_SwitchesHash[switchKey];
if (value.m_Threshold >= minThreshold) {
isOn = value.m_IsOn;
}
}
return isOn;
}
bool SwitcherConfig::processLocalConfig(const QJsonDocument &document) {
LOG_INTEGR_TESTS_OR_DEBUG << document;
bool anyError = false;
do {
if (!document.isObject()) {
LOG_WARNING << "Json document is not an object";
anyError = true;
break;
}
QJsonObject rootObject = document.object();
parseSwitches(rootObject);
} while (false);
return anyError;
}
void SwitcherConfig::processRemoteConfig(const QJsonDocument &remoteDocument, bool overwriteLocal) {
bool overwrite = false;
if (!overwriteLocal && remoteDocument.isObject()) {
QJsonObject rootObject = remoteDocument.object();
if (rootObject.contains(OVERWRITE_KEY)) {
QJsonValue overwriteValue = rootObject[OVERWRITE_KEY];
if (overwriteValue.isBool()) {
overwrite = overwriteValue.toBool();
LOG_DEBUG << "Overwrite flag present in the config:" << overwrite;
} else {
LOG_WARNING << "Overwrite flag is not boolean";
}
}
} else {
overwrite = overwriteLocal;
}
Models::AbstractConfigUpdaterModel::processRemoteConfig(remoteDocument, overwrite);
if (remoteDocument.isObject()) {
parseSwitches(remoteDocument.object());
} else {
LOG_WARNING << "Remote document is not an object";
}
}
int SwitcherConfig::operator ()(const QJsonObject &val1, const QJsonObject &val2) {
// values are always considered equal. This may lead to loss of local changes.
Q_UNUSED(val1);
Q_UNUSED(val2);
return 0;
}
bool tryGetDouble(const QJsonObject &object, const QString &key, double &value) {
bool hasValue = false;
if (object.contains(key)) {
QJsonValue valueObject = object[key];
if (valueObject.isDouble()) {
value = valueObject.toDouble();
hasValue = true;
}
}
return hasValue;
}
bool tryGetThresholdValue(const QJsonObject &object, double &threshold) {
#if defined(Q_OS_WIN)
if (tryGetDouble(object, WIN_THRESHOLD_KEY, threshold)) {
return true;
}
#elif defined(Q_OS_MAC)
if (tryGetDouble(object, MAC_THRESHOLD_KEY, threshold)) {
return true;
}
#elif defined(Q_OS_LINUX)
if (tryGetDouble(object, LIN_THRESHOLD_KEY, threshold)) {
return true;
}
#endif
if (tryGetDouble(object, THRESHOLD_KEY, threshold)) {
return true;
}
return false;
}
bool tryGetBool(const QJsonObject &object, const QString &key, bool &value) {
bool hasValue = false;
if (object.contains(key)) {
QJsonValue valueObject = object[key];
if (valueObject.isBool()) {
value = valueObject.toBool();
hasValue = true;
}
}
return hasValue;
}
void initSwitchValue(const QJsonObject &object, const QLatin1String &keyName, SwitcherConfig::SwitchValue &value) {
value.m_IsOn = false;
value.m_Threshold = 0;
QJsonValue propertiesObjectValue = object[keyName];
if (propertiesObjectValue.isObject()) {
QJsonObject propertiesObject = propertiesObjectValue.toObject();
bool switchValue = false;
if (tryGetBool(propertiesObject, VALUE_KEY, switchValue)) {
value.m_IsOn = switchValue;
}
double threshold = 0.0;
if (tryGetThresholdValue(propertiesObject, threshold)) {
int intThreshold = (int)threshold;
Q_ASSERT((0 <= intThreshold) && (intThreshold <= 100));
if ((0 <= intThreshold) && (intThreshold <= 100)) {
value.m_Threshold = intThreshold;
}
}
}
}
void SwitcherConfig::parseSwitches(const QJsonObject &object) {
LOG_DEBUG << "#";
SwitchValue donateCampaign1Active;
SwitchValue donateCampaign1Stage2;
SwitchValue progressiveSuggestionPreviews;
SwitchValue directExport;
SwitchValue qualityVideoPreviews;
initSwitchValue(object, DONATE_CAMPAIGN_1_KEY, donateCampaign1Active);
initSwitchValue(object, DONATE_CAMPAIGN_1_STAGE_2, donateCampaign1Stage2);
initSwitchValue(object, PROGRESSIVE_SUGGESTION_PREVIEWS, progressiveSuggestionPreviews);
initSwitchValue(object, DIRECT_METADATA_EXPORT, directExport);
initSwitchValue(object, GOOD_QUALITY_VIDEO_PREVIEWS, qualityVideoPreviews);
// overwrite these values
{
QWriteLocker locker(&m_RwLock);
Q_UNUSED(locker);
m_SwitchesHash.clear();
m_SwitchesHash[DonateCampaign1] = donateCampaign1Active;
m_SwitchesHash[DonateCampaign1Stage2] = donateCampaign1Stage2;
m_SwitchesHash[ProgressiveSuggestionPreviews] = progressiveSuggestionPreviews;
m_SwitchesHash[DirectMetadataExport] = directExport;
m_SwitchesHash[GoodQualityVideoPreviews] = qualityVideoPreviews;
LOG_INTEGR_TESTS_OR_DEBUG << m_SwitchesHash;
}
emit switchesUpdated();
}
}
<commit_msg>No switcher threshold by default<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "switcherconfig.h"
#include <QDir>
#include <QJsonValue>
#include "apimanager.h"
#include "../Common/defines.h"
namespace Connectivity {
#if defined(QT_DEBUG)
#define LOCAL_SWITCHER_CONFIG "debug_switches.json"
#elif defined(INTEGRATION_TESTS)
#define LOCAL_SWITCHER_CONFIG "tests_switches.json"
#else
#define LOCAL_SWITCHER_CONFIG "switches.json"
#endif
#define VALUE_KEY QLatin1String("v")
#define THRESHOLD_KEY QLatin1String("t")
#define WIN_THRESHOLD_KEY QLatin1String("wt")
#define MAC_THRESHOLD_KEY QLatin1String("mt")
#define LIN_THRESHOLD_KEY QLatin1String("lt")
#define OVERWRITE_KEY QLatin1String("overwrite")
#define OVERWRITE_SWITCHER_CONFIG true
#define DONATE_CAMPAIGN_1_KEY QLatin1String("donateCampaign1")
#define DONATE_CAMPAIGN_1_STAGE_2 QLatin1String("donateCampaign1Stage2")
#define PROGRESSIVE_SUGGESTION_PREVIEWS QLatin1String("progressiveSuggestionPreviews")
#define DIRECT_METADATA_EXPORT QLatin1String("directExport")
#define GOOD_QUALITY_VIDEO_PREVIEWS QLatin1String("qualityVideoPreviews")
QDebug operator << (QDebug d, const SwitcherConfig::SwitchValue &value) {
d << "{" << value.m_IsOn << "*" << value.m_Threshold << "}";
return d;
}
SwitcherConfig::SwitcherConfig(QObject *parent):
Models::AbstractConfigUpdaterModel(OVERWRITE_SWITCHER_CONFIG, parent)
{
}
void SwitcherConfig::initializeConfigs() {
QString localConfigPath;
QString appDataPath = XPIKS_USERDATA_PATH;
if (!appDataPath.isEmpty()) {
QDir appDataDir(appDataPath);
localConfigPath = appDataDir.filePath(LOCAL_SWITCHER_CONFIG);
} else {
localConfigPath = LOCAL_SWITCHER_CONFIG;
}
auto &apiManager = Connectivity::ApiManager::getInstance();
QString remoteAddress = apiManager.getSwitcherAddr();
AbstractConfigUpdaterModel::initializeConfigs(remoteAddress, localConfigPath);
}
bool SwitcherConfig::isSwitchOn(int switchKey, int minThreshold) {
QReadLocker locker(&m_RwLock);
Q_UNUSED(locker);
bool isOn = false;
if (m_SwitchesHash.contains(switchKey)) {
SwitchValue &value = m_SwitchesHash[switchKey];
if (value.m_Threshold >= minThreshold) {
isOn = value.m_IsOn;
}
}
return isOn;
}
bool SwitcherConfig::processLocalConfig(const QJsonDocument &document) {
LOG_INTEGR_TESTS_OR_DEBUG << document;
bool anyError = false;
do {
if (!document.isObject()) {
LOG_WARNING << "Json document is not an object";
anyError = true;
break;
}
QJsonObject rootObject = document.object();
parseSwitches(rootObject);
} while (false);
return anyError;
}
void SwitcherConfig::processRemoteConfig(const QJsonDocument &remoteDocument, bool overwriteLocal) {
bool overwrite = false;
if (!overwriteLocal && remoteDocument.isObject()) {
QJsonObject rootObject = remoteDocument.object();
if (rootObject.contains(OVERWRITE_KEY)) {
QJsonValue overwriteValue = rootObject[OVERWRITE_KEY];
if (overwriteValue.isBool()) {
overwrite = overwriteValue.toBool();
LOG_DEBUG << "Overwrite flag present in the config:" << overwrite;
} else {
LOG_WARNING << "Overwrite flag is not boolean";
}
}
} else {
overwrite = overwriteLocal;
}
Models::AbstractConfigUpdaterModel::processRemoteConfig(remoteDocument, overwrite);
if (remoteDocument.isObject()) {
parseSwitches(remoteDocument.object());
} else {
LOG_WARNING << "Remote document is not an object";
}
}
int SwitcherConfig::operator ()(const QJsonObject &val1, const QJsonObject &val2) {
// values are always considered equal. This may lead to loss of local changes.
Q_UNUSED(val1);
Q_UNUSED(val2);
return 0;
}
bool tryGetDouble(const QJsonObject &object, const QString &key, double &value) {
bool hasValue = false;
if (object.contains(key)) {
QJsonValue valueObject = object[key];
if (valueObject.isDouble()) {
value = valueObject.toDouble();
hasValue = true;
}
}
return hasValue;
}
bool tryGetThresholdValue(const QJsonObject &object, double &threshold) {
#if defined(Q_OS_WIN)
if (tryGetDouble(object, WIN_THRESHOLD_KEY, threshold)) {
return true;
}
#elif defined(Q_OS_MAC)
if (tryGetDouble(object, MAC_THRESHOLD_KEY, threshold)) {
return true;
}
#elif defined(Q_OS_LINUX)
if (tryGetDouble(object, LIN_THRESHOLD_KEY, threshold)) {
return true;
}
#endif
if (tryGetDouble(object, THRESHOLD_KEY, threshold)) {
return true;
}
return false;
}
bool tryGetBool(const QJsonObject &object, const QString &key, bool &value) {
bool hasValue = false;
if (object.contains(key)) {
QJsonValue valueObject = object[key];
if (valueObject.isBool()) {
value = valueObject.toBool();
hasValue = true;
}
}
return hasValue;
}
void initSwitchValue(const QJsonObject &object, const QLatin1String &keyName, SwitcherConfig::SwitchValue &value) {
value.m_IsOn = false;
value.m_Threshold = 0;
QJsonValue propertiesObjectValue = object[keyName];
if (propertiesObjectValue.isObject()) {
QJsonObject propertiesObject = propertiesObjectValue.toObject();
bool switchValue = false;
if (tryGetBool(propertiesObject, VALUE_KEY, switchValue)) {
value.m_IsOn = switchValue;
}
double threshold = 0.0;
if (tryGetThresholdValue(propertiesObject, threshold)) {
int intThreshold = (int)threshold;
Q_ASSERT((0 <= intThreshold) && (intThreshold <= 100));
if ((0 <= intThreshold) && (intThreshold <= 100)) {
value.m_Threshold = intThreshold;
}
} else {
// allowed by default
value.m_Threshold = 100;
}
}
}
void SwitcherConfig::parseSwitches(const QJsonObject &object) {
LOG_DEBUG << "#";
SwitchValue donateCampaign1Active;
SwitchValue donateCampaign1Stage2;
SwitchValue progressiveSuggestionPreviews;
SwitchValue directExport;
SwitchValue qualityVideoPreviews;
initSwitchValue(object, DONATE_CAMPAIGN_1_KEY, donateCampaign1Active);
initSwitchValue(object, DONATE_CAMPAIGN_1_STAGE_2, donateCampaign1Stage2);
initSwitchValue(object, PROGRESSIVE_SUGGESTION_PREVIEWS, progressiveSuggestionPreviews);
initSwitchValue(object, DIRECT_METADATA_EXPORT, directExport);
initSwitchValue(object, GOOD_QUALITY_VIDEO_PREVIEWS, qualityVideoPreviews);
// overwrite these values
{
QWriteLocker locker(&m_RwLock);
Q_UNUSED(locker);
m_SwitchesHash.clear();
m_SwitchesHash[DonateCampaign1] = donateCampaign1Active;
m_SwitchesHash[DonateCampaign1Stage2] = donateCampaign1Stage2;
m_SwitchesHash[ProgressiveSuggestionPreviews] = progressiveSuggestionPreviews;
m_SwitchesHash[DirectMetadataExport] = directExport;
m_SwitchesHash[GoodQualityVideoPreviews] = qualityVideoPreviews;
LOG_INTEGR_TESTS_OR_DEBUG << m_SwitchesHash;
}
emit switchesUpdated();
}
}
<|endoftext|> |
<commit_before>#ifndef _SDD_MEM_CACHE_HH_
#define _SDD_MEM_CACHE_HH_
#include <algorithm> // count_if, for_each, nth_element
#include <cstdint> // uint32_t
#include <forward_list>
#include <numeric> // accumulate
#include <tuple>
#include <utility> // forward
#include <vector>
#include <boost/intrusive/unordered_set.hpp>
#include "sdd/util/packed.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by cache to know if an operation should be cached or not.
///
/// A filter should always return the same result for the same operation.
template <typename T, typename... Filters>
struct apply_filters;
template <typename T>
struct apply_filters<T>
{
constexpr
bool
operator()(const T&)
const
{
return true;
}
};
template <typename T, typename Filter, typename... Filters>
struct apply_filters<T, Filter, Filters...>
{
bool
operator()(const T& op)
const
{
return Filter()(op) ? apply_filters<T, Filters...>()(op) : false;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief The statistics of a cache.
///
/// A statistic is made of several rounds: each time a cache is cleaned up, a new round is
/// created. Thus, one can have detailed statistics to see how well the cache performed.
struct cache_statistics
{
/// @internal
/// @brief Statistic between two cleanups.
struct round
{
round()
: hits(0)
, misses(0)
, filtered(0)
{
}
/// @brief The number of hits in a round.
std::size_t hits;
/// @brief The number of misses in a round.
std::size_t misses;
/// @brief The number of filtered entries in a round.
std::size_t filtered;
};
/// @brief The list of all rounds.
std::forward_list<round> rounds;
/// @brief Default constructor.
cache_statistics()
: rounds(1)
{
}
/// @brief Get the number of rounds.
std::size_t
size()
const noexcept
{
return std::count_if(rounds.begin(), rounds.end(), [](const round&){return true;});
}
/// @brief Get the number of performed cleanups.
std::size_t
cleanups()
const noexcept
{
return size() - 1;
}
round
total()
const noexcept
{
return std::accumulate( rounds.begin(), rounds.end(), round()
, [&](const round& acc, const round& r) -> round
{
round res;
res.hits = acc.hits + r.hits;
res.misses = acc.misses + r.misses;
res.filtered = acc.filtered + r.filtered;
return res;
}
);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A generic cache.
/// @tparam Operation is the operation type.
/// @tparam EvaluationError is the exception that the evaluation of an Operation can throw.
/// @tparam Filters is a list of filters that reject some operations.
///
/// It uses the LFU strategy to cleanup old entries.
template <typename Context, typename Operation, typename EvaluationError, typename... Filters>
class cache
{
// Can't copy a cache.
cache(const cache&) = delete;
cache* operator=(const cache&) = delete;
private:
/// @brief The type of the context of this cache.
typedef Context context_type;
/// @brief The type of the result of an operation stored in the cache.
typedef typename Operation::result_type result_type;
/// @brief Faster, unsafe mode for Boost.Intrusive.
typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;
/// @brief Associate an operation to its result into the cache.
///
/// The operation acts as a key and the associated result is the value counterpart.
struct
#if defined __clang__
LIBSDD_ATTRIBUTE_PACKED
#endif
cache_entry
: public boost::intrusive::unordered_set_base_hook<link_mode>
{
// Can't copy a cache_entry.
cache_entry(const cache_entry&) = delete;
cache_entry& operator=(const cache_entry&) = delete;
/// @brief The cached operation.
const Operation operation;
/// @brief The result of the evaluation of operation.
const result_type result;
/// @brief Count the number of times this entry has been accessed.
///
/// Used by the LFU cache cleanup strategy.
std::uint32_t nb_hits_;
/// brief The 'in use' bit position in nb_hits_.
static constexpr std::uint32_t in_use_bit = (1u << 31);
/// @brief Constructor.
template <typename... Args>
cache_entry(Operation&& op, Args&&... args)
: operation(std::move(op))
, result(std::forward<Args>(args)...)
, nb_hits_(in_use_bit) // initially in use
{
}
/// @brief Cache entries are only compared using their operations.
bool
operator==(const cache_entry& other)
const noexcept
{
return operation == other.operation;
}
/// @brief Get the number of hits, with the 'in use' bit set or not.
unsigned int
raw_nb_hits()
const noexcept
{
return nb_hits_;
}
/// @brief Set this cache entry to a 'not in use' and 'never used' state.
void
reset()
noexcept
{
nb_hits_ = 0;
}
/// @brief Increment the number of hits.
void
increment_nb_hits()
noexcept
{
++nb_hits_;
}
/// @brief Set this cache entry to a 'not in use' state.
void
reset_in_use()
noexcept
{
nb_hits_ &= ~in_use_bit;
}
/// @brief Set this cache entry to an 'in use' state.
bool
in_use()
const noexcept
{
return nb_hits_ & in_use_bit;
}
};
/// @brief Hash a cache_entry.
///
/// We only use the Operation part of a cache_entry to find it in the cache, in order
/// to manage the set that stores cache entries as a map.
struct hash_key
{
std::size_t
operator()(const cache_entry& x)
const noexcept
{
return std::hash<Operation>()(x.operation);
}
};
/// @brief This cache's context.
context_type& cxt_;
/// @brief The cache name.
const std::string name_;
/// @brief The maximum size this cache is authorized to grow to.
const std::size_t max_size_;
/// @brief We use Boost.Intrusive to store the cache entries.
typedef typename boost::intrusive::make_unordered_set< cache_entry
, boost::intrusive::hash<hash_key>
>::type
set_type;
/// @brief Needed to use Boost.Intrusive.
typedef typename set_type::bucket_type bucket_type;
/// @brief Needed to use Boost.Intrusive.
typedef typename set_type::bucket_traits bucket_traits;
/// @brief Boost.Intrusive requires us to manage ourselves its buckets.
bucket_type* buckets_;
/// @brief The actual storage of caches entries.
set_type* set_;
/// @brief The statistics of this cache.
cache_statistics stats_;
public:
/// @brief Construct a cache.
/// @param context This cache's context.
/// @param name Give a name to this cache.
/// @param size tells how many cache entries are keeped in the cache.
///
/// When the maximal size is reached, a cleanup is launched: half of the cache is removed,
/// using an LFU strategy. This cache will never perform a rehash, therefore it allocates
/// all the memory it needs at its construction.
cache(context_type& context, const std::string& name, std::size_t size)
: cxt_(context)
, name_(name)
, max_size_(set_type::suggested_upper_bucket_count(size))
, buckets_(new bucket_type[max_size_])
, set_(new set_type(bucket_traits(buckets_, max_size_)))
, stats_()
{
}
/// @brief Destructor.
~cache()
{
clear();
delete set_;
delete[] buckets_;
}
/// @brief Cache lookup.
result_type
operator()(Operation&& op)
{
// Check if the current operation should not be cached.
if (not apply_filters<Operation, Filters...>()(op))
{
++stats_.rounds.front().filtered;
try
{
return op(cxt_);
}
catch (EvaluationError& e)
{
--stats_.rounds.front().filtered;
e.add_step(std::move(op));
throw;
}
}
// Lookup for op.
typename set_type::insert_commit_data commit_data;
auto insertion = set_->insert_check( op
, std::hash<Operation>()
, [](const Operation& lhs, const cache_entry& rhs)
{return lhs == rhs.operation;}
, commit_data);
// Check if op has already been computed.
if (not insertion.second)
{
++stats_.rounds.front().hits;
insertion.first->increment_nb_hits();
return insertion.first->result;
}
++stats_.rounds.front().misses;
// Remove half of the cache if it's full.
if (set_->size() >= max_size_)
{
cleanup();
}
try
{
cache_entry* entry = new cache_entry(std::move(op), op(cxt_));
// A cache entry is constructed with the 'in use' bit set.
entry->reset_in_use();
set_->insert_commit(*entry, commit_data); // doesn't throw
return entry->result;
}
catch (EvaluationError& e)
{
--stats_.rounds.front().misses;
e.add_step(std::move(op));
throw;
}
}
/// @brief Remove half of the cache (LFU strategy).
void
cleanup()
{
typedef typename set_type::iterator iterator;
stats_.rounds.emplace_front(cache_statistics::round());
std::vector<iterator> vec;
vec.reserve(set_->size());
for (auto cit = set_->begin(); cit != set_->end(); ++cit)
{
vec.push_back(cit);
}
// We remove an half of the cache.
const std::size_t cut_size = vec.size() / 2;
// Find the median of the number of hits.
std::nth_element( vec.begin(), vec.begin() + cut_size, vec.end()
, [](iterator lhs, iterator rhs)
{
// We sort using the raw nb_hits counter, with the 'in use' possibily bit
// set. As this is the higher bit, the value of nb_hits may be large.
// Thus, it's very unlikely that cache entries currently in use will be
// put below the median.
return lhs->raw_nb_hits() < rhs->raw_nb_hits();
});
// Delete all cache entries with a number of entries smaller than the median.
std::for_each( vec.begin(), vec.begin() + cut_size
, [&](iterator cit)
{
if (not cit->in_use())
{
const cache_entry* x = &*cit;
set_->erase(cit);
delete x;
}
});
// Reset the number of hits of all remaining cache entries.
std::for_each(vec.begin() + cut_size, vec.end(), [](iterator it){it->reset();});
}
/// @brief Remove all entries of the cache.
void
clear()
noexcept
{
set_->clear_and_dispose([](cache_entry* x){delete x;});
}
/// @brief Get the number of cached operations.
std::size_t
size()
const noexcept
{
return set_->size();
}
/// @brief Get the statistics of this cache.
const cache_statistics&
statistics()
const noexcept
{
return stats_;
}
/// @brief Get this cache's name
const std::string&
name()
const noexcept
{
return name_;
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
#endif // _SDD_MEM_CACHE_HH_
<commit_msg>Don't reset the 'in use' bit when resetting the number of hits.<commit_after>#ifndef _SDD_MEM_CACHE_HH_
#define _SDD_MEM_CACHE_HH_
#include <algorithm> // count_if, for_each, nth_element
#include <cstdint> // uint32_t
#include <forward_list>
#include <numeric> // accumulate
#include <tuple>
#include <utility> // forward
#include <vector>
#include <boost/intrusive/unordered_set.hpp>
#include "sdd/util/packed.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by cache to know if an operation should be cached or not.
///
/// A filter should always return the same result for the same operation.
template <typename T, typename... Filters>
struct apply_filters;
template <typename T>
struct apply_filters<T>
{
constexpr
bool
operator()(const T&)
const
{
return true;
}
};
template <typename T, typename Filter, typename... Filters>
struct apply_filters<T, Filter, Filters...>
{
bool
operator()(const T& op)
const
{
return Filter()(op) ? apply_filters<T, Filters...>()(op) : false;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief The statistics of a cache.
///
/// A statistic is made of several rounds: each time a cache is cleaned up, a new round is
/// created. Thus, one can have detailed statistics to see how well the cache performed.
struct cache_statistics
{
/// @internal
/// @brief Statistic between two cleanups.
struct round
{
round()
: hits(0)
, misses(0)
, filtered(0)
{
}
/// @brief The number of hits in a round.
std::size_t hits;
/// @brief The number of misses in a round.
std::size_t misses;
/// @brief The number of filtered entries in a round.
std::size_t filtered;
};
/// @brief The list of all rounds.
std::forward_list<round> rounds;
/// @brief Default constructor.
cache_statistics()
: rounds(1)
{
}
/// @brief Get the number of rounds.
std::size_t
size()
const noexcept
{
return std::count_if(rounds.begin(), rounds.end(), [](const round&){return true;});
}
/// @brief Get the number of performed cleanups.
std::size_t
cleanups()
const noexcept
{
return size() - 1;
}
round
total()
const noexcept
{
return std::accumulate( rounds.begin(), rounds.end(), round()
, [&](const round& acc, const round& r) -> round
{
round res;
res.hits = acc.hits + r.hits;
res.misses = acc.misses + r.misses;
res.filtered = acc.filtered + r.filtered;
return res;
}
);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A generic cache.
/// @tparam Operation is the operation type.
/// @tparam EvaluationError is the exception that the evaluation of an Operation can throw.
/// @tparam Filters is a list of filters that reject some operations.
///
/// It uses the LFU strategy to cleanup old entries.
template <typename Context, typename Operation, typename EvaluationError, typename... Filters>
class cache
{
// Can't copy a cache.
cache(const cache&) = delete;
cache* operator=(const cache&) = delete;
private:
/// @brief The type of the context of this cache.
typedef Context context_type;
/// @brief The type of the result of an operation stored in the cache.
typedef typename Operation::result_type result_type;
/// @brief Faster, unsafe mode for Boost.Intrusive.
typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;
/// @brief Associate an operation to its result into the cache.
///
/// The operation acts as a key and the associated result is the value counterpart.
struct
#if defined __clang__
LIBSDD_ATTRIBUTE_PACKED
#endif
cache_entry
: public boost::intrusive::unordered_set_base_hook<link_mode>
{
// Can't copy a cache_entry.
cache_entry(const cache_entry&) = delete;
cache_entry& operator=(const cache_entry&) = delete;
/// @brief The cached operation.
const Operation operation;
/// @brief The result of the evaluation of operation.
const result_type result;
/// @brief Count the number of times this entry has been accessed.
///
/// Used by the LFU cache cleanup strategy.
std::uint32_t nb_hits_;
/// brief The 'in use' bit position in nb_hits_.
static constexpr std::uint32_t in_use_mask = (1u << 31);
/// @brief Constructor.
template <typename... Args>
cache_entry(Operation&& op, Args&&... args)
: operation(std::move(op))
, result(std::forward<Args>(args)...)
, nb_hits_(in_use_mask) // initially in use
{
}
/// @brief Cache entries are only compared using their operations.
bool
operator==(const cache_entry& other)
const noexcept
{
return operation == other.operation;
}
/// @brief Get the number of hits, with the 'in use' bit set or not.
unsigned int
raw_nb_hits()
const noexcept
{
return nb_hits_;
}
/// @brief Set this cache entry to a 'never used' state.
void
reset_nb_hits()
noexcept
{
nb_hits_ &= in_use_mask;
}
/// @brief Increment the number of hits.
void
increment_nb_hits()
noexcept
{
++nb_hits_;
}
/// @brief Set this cache entry to a 'not in use' state.
void
reset_in_use()
noexcept
{
nb_hits_ &= ~in_use_mask;
}
/// @brief Set this cache entry to an 'in use' state.
bool
in_use()
const noexcept
{
return nb_hits_ & in_use_mask;
}
};
/// @brief Hash a cache_entry.
///
/// We only use the Operation part of a cache_entry to find it in the cache, in order
/// to manage the set that stores cache entries as a map.
struct hash_key
{
std::size_t
operator()(const cache_entry& x)
const noexcept
{
return std::hash<Operation>()(x.operation);
}
};
/// @brief This cache's context.
context_type& cxt_;
/// @brief The cache name.
const std::string name_;
/// @brief The maximum size this cache is authorized to grow to.
const std::size_t max_size_;
/// @brief We use Boost.Intrusive to store the cache entries.
typedef typename boost::intrusive::make_unordered_set< cache_entry
, boost::intrusive::hash<hash_key>
>::type
set_type;
/// @brief Needed to use Boost.Intrusive.
typedef typename set_type::bucket_type bucket_type;
/// @brief Needed to use Boost.Intrusive.
typedef typename set_type::bucket_traits bucket_traits;
/// @brief Boost.Intrusive requires us to manage ourselves its buckets.
bucket_type* buckets_;
/// @brief The actual storage of caches entries.
set_type* set_;
/// @brief The statistics of this cache.
cache_statistics stats_;
public:
/// @brief Construct a cache.
/// @param context This cache's context.
/// @param name Give a name to this cache.
/// @param size tells how many cache entries are keeped in the cache.
///
/// When the maximal size is reached, a cleanup is launched: half of the cache is removed,
/// using an LFU strategy. This cache will never perform a rehash, therefore it allocates
/// all the memory it needs at its construction.
cache(context_type& context, const std::string& name, std::size_t size)
: cxt_(context)
, name_(name)
, max_size_(set_type::suggested_upper_bucket_count(size))
, buckets_(new bucket_type[max_size_])
, set_(new set_type(bucket_traits(buckets_, max_size_)))
, stats_()
{
}
/// @brief Destructor.
~cache()
{
clear();
delete set_;
delete[] buckets_;
}
/// @brief Cache lookup.
result_type
operator()(Operation&& op)
{
// Check if the current operation should not be cached.
if (not apply_filters<Operation, Filters...>()(op))
{
++stats_.rounds.front().filtered;
try
{
return op(cxt_);
}
catch (EvaluationError& e)
{
--stats_.rounds.front().filtered;
e.add_step(std::move(op));
throw;
}
}
// Lookup for op.
typename set_type::insert_commit_data commit_data;
auto insertion = set_->insert_check( op
, std::hash<Operation>()
, [](const Operation& lhs, const cache_entry& rhs)
{return lhs == rhs.operation;}
, commit_data);
// Check if op has already been computed.
if (not insertion.second)
{
++stats_.rounds.front().hits;
insertion.first->increment_nb_hits();
return insertion.first->result;
}
++stats_.rounds.front().misses;
// Remove half of the cache if it's full.
if (set_->size() >= max_size_)
{
cleanup();
}
try
{
cache_entry* entry = new cache_entry(std::move(op), op(cxt_));
// A cache entry is constructed with the 'in use' bit set.
entry->reset_in_use();
set_->insert_commit(*entry, commit_data); // doesn't throw
return entry->result;
}
catch (EvaluationError& e)
{
--stats_.rounds.front().misses;
e.add_step(std::move(op));
throw;
}
}
/// @brief Remove half of the cache (LFU strategy).
void
cleanup()
{
typedef typename set_type::iterator iterator;
stats_.rounds.emplace_front(cache_statistics::round());
std::vector<iterator> vec;
vec.reserve(set_->size());
for (auto cit = set_->begin(); cit != set_->end(); ++cit)
{
vec.push_back(cit);
}
// We remove an half of the cache.
const std::size_t cut_size = vec.size() / 2;
// Find the median of the number of hits.
std::nth_element( vec.begin(), vec.begin() + cut_size, vec.end()
, [](iterator lhs, iterator rhs)
{
// We sort using the raw nb_hits counter, with the 'in use' possibily bit
// set. As this is the higher bit, the value of nb_hits may be large.
// Thus, it's very unlikely that cache entries currently in use will be
// put below the median.
return lhs->raw_nb_hits() < rhs->raw_nb_hits();
});
// Delete all cache entries with a number of entries smaller than the median.
std::for_each( vec.begin(), vec.begin() + cut_size
, [&](iterator cit)
{
if (not cit->in_use())
{
const cache_entry* x = &*cit;
set_->erase(cit);
delete x;
}
});
// Reset the number of hits of all remaining cache entries.
std::for_each(vec.begin() + cut_size, vec.end(), [](iterator it){it->reset_nb_hits();});
}
/// @brief Remove all entries of the cache.
void
clear()
noexcept
{
set_->clear_and_dispose([](cache_entry* x){delete x;});
}
/// @brief Get the number of cached operations.
std::size_t
size()
const noexcept
{
return set_->size();
}
/// @brief Get the statistics of this cache.
const cache_statistics&
statistics()
const noexcept
{
return stats_;
}
/// @brief Get this cache's name
const std::string&
name()
const noexcept
{
return name_;
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
#endif // _SDD_MEM_CACHE_HH_
<|endoftext|> |
<commit_before>#include "query.hpp"
#include "delimiters.hpp"
#include "keyword_matcher.hpp"
#include "string_match.hpp"
namespace search
{
namespace impl
{
uint32_t KeywordMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, false);
}
uint32_t PrefixMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, true);
}
Query::Query(string const & query, m2::RectD const & rect, IndexType const * pIndex)
: m_queryText(query), m_rect(rect), m_pIndex(pIndex)
{
search::Delimiters delims;
for (strings::TokenizeIterator<search::Delimiters> iter(query, delims); iter; ++iter)
{
if (iter.IsLast() && !delims(strings::LastUniChar(query)))
m_prefix = strings::MakeLowerCase(iter.GetUniString());
else
m_keywords.push_back(strings::MakeLowerCase(iter.GetUniString()));
}
}
struct FeatureProcessor
{
Query & m_query;
explicit FeatureProcessor(Query & query) : m_query(query) {}
void operator () (FeatureType const & feature) const
{
KeywordMatcher matcher(&m_query.m_keywords[0], m_query.m_keywords.size(), m_query.m_prefix,
512, 256 * max(0, int(m_query.m_prefix.size()) - 1),
&KeywordMatch, &PrefixMatch);
feature.ForEachNameRef(matcher);
m_query.AddResult(IntermediateResult(
feature, matcher.GetBestPrefixMatch(), matcher.GetMatchScore()));
}
};
void Query::Search(function<void (Result const &)> const & f)
{
FeatureProcessor featureProcessor(*this);
m_pIndex->ForEachInRect(featureProcessor, m_rect,
min(scales::GetUpperScale(), scales::GetScaleLevel(m_rect) + 1));
vector<Result> results;
results.reserve(m_resuts.size());
while (!m_resuts.empty())
{
results.push_back(m_resuts.top().GenerateFinalResult());
m_resuts.pop();
}
for (vector<Result>::const_reverse_iterator it = results.rbegin(); it != results.rend(); ++it)
f(*it);
}
void Query::AddResult(IntermediateResult const & result)
{
m_resuts.push(result);
while (m_resuts.size() > 10)
m_resuts.pop();
}
} // namespace search::impl
} // namespace search
<commit_msg>[search] Optimization: don't push IntermediateResult into priority queue if it isn't good enough.<commit_after>#include "query.hpp"
#include "delimiters.hpp"
#include "keyword_matcher.hpp"
#include "string_match.hpp"
namespace search
{
namespace impl
{
uint32_t KeywordMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, false);
}
uint32_t PrefixMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, true);
}
Query::Query(string const & query, m2::RectD const & rect, IndexType const * pIndex)
: m_queryText(query), m_rect(rect), m_pIndex(pIndex)
{
search::Delimiters delims;
for (strings::TokenizeIterator<search::Delimiters> iter(query, delims); iter; ++iter)
{
if (iter.IsLast() && !delims(strings::LastUniChar(query)))
m_prefix = strings::MakeLowerCase(iter.GetUniString());
else
m_keywords.push_back(strings::MakeLowerCase(iter.GetUniString()));
}
}
struct FeatureProcessor
{
Query & m_query;
explicit FeatureProcessor(Query & query) : m_query(query) {}
void operator () (FeatureType const & feature) const
{
KeywordMatcher matcher(&m_query.m_keywords[0], m_query.m_keywords.size(), m_query.m_prefix,
512, 256 * max(0, int(m_query.m_prefix.size()) - 1),
&KeywordMatch, &PrefixMatch);
feature.ForEachNameRef(matcher);
m_query.AddResult(IntermediateResult(
feature, matcher.GetBestPrefixMatch(), matcher.GetMatchScore()));
}
};
void Query::Search(function<void (Result const &)> const & f)
{
FeatureProcessor featureProcessor(*this);
m_pIndex->ForEachInRect(featureProcessor, m_rect,
min(scales::GetUpperScale(), scales::GetScaleLevel(m_rect) + 1));
vector<Result> results;
results.reserve(m_resuts.size());
while (!m_resuts.empty())
{
results.push_back(m_resuts.top().GenerateFinalResult());
m_resuts.pop();
}
for (vector<Result>::const_reverse_iterator it = results.rbegin(); it != results.rend(); ++it)
f(*it);
}
void Query::AddResult(IntermediateResult const & result)
{
if (m_resuts.size() < 10)
m_resuts.push(result);
else if (result < m_resuts.top())
{
m_resuts.pop();
m_resuts.push(result);
}
}
} // namespace search::impl
} // namespace search
<|endoftext|> |
<commit_before>//===- InheritViz.cpp - Graphviz visualization for inheritance --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements CXXRecordDecl::viewInheritance, which
// generates a GraphViz DOT file that depicts the class inheritance
// diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include <fstream>
#include <map>
using namespace llvm;
namespace clang {
#ifndef NDEBUG
/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
ASTContext& Context;
std::ostream &Out;
std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
std::set<QualType, QualTypeOrdering> KnownVirtualBases;
public:
InheritanceHierarchyWriter(ASTContext& Context, std::ostream& Out)
: Context(Context), Out(Out) { }
void WriteGraph(QualType Type) {
Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
WriteNode(Type, false);
Out << "}\n";
}
protected:
/// WriteNode - Write out the description of node in the inheritance
/// diagram, which may be a base class or it may be the root node.
void WriteNode(QualType Type, bool FromVirtual);
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
std::ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};
void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
if (FromVirtual) {
if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
return;
// We haven't seen this virtual base before, so display it and
// its bases.
KnownVirtualBases.insert(CanonType);
}
// Declare the node itself.
Out << " ";
WriteNodeReference(Type, FromVirtual);
// Give the node a label based on the name of the class.
std::string TypeName = Type.getAsString();
Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);
// If the name of the class was a typedef or something different
// from the "real" class name, show the real class name in
// parentheses so we don't confuse ourselves.
if (TypeName != CanonType.getAsString()) {
Out << "\\n(" << CanonType.getAsString() << ")";
}
// Finished describing the node.
Out << " \"];\n";
// Display the base classes.
const CXXRecordDecl *Decl
= static_cast<const CXXRecordDecl *>(Type->getAsRecordType()->getDecl());
for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin();
Base != Decl->bases_end(); ++Base) {
QualType CanonBaseType = Context.getCanonicalType(Base->getType());
// If this is not virtual inheritance, bump the direct base
// count for the type.
if (!Base->isVirtual())
++DirectBaseCount[CanonBaseType];
// Write out the node (if we need to).
WriteNode(Base->getType(), Base->isVirtual());
// Write out the edge.
Out << " ";
WriteNodeReference(Type, FromVirtual);
Out << " -> ";
WriteNodeReference(Base->getType(), Base->isVirtual());
// Write out edge attributes to show the kind of inheritance.
if (Base->isVirtual()) {
Out << " [ style=\"dashed\" ]";
}
Out << ";";
}
}
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
std::ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
Out << "Class_" << CanonType.getAsOpaquePtr();
if (!FromVirtual)
Out << "_" << DirectBaseCount[CanonType];
return Out;
}
#endif
/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void QualType::viewInheritance(ASTContext& Context) {
if (!(*this)->getAsRecordType()) {
cerr << "Type " << getAsString() << " is not a C++ class type.\n";
return;
}
#ifndef NDEBUG
std::string ErrMsg;
sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
if (Filename.isEmpty()) {
cerr << "Error: " << ErrMsg << "\n";
return;
}
Filename.appendComponent(getAsString() + ".dot");
if (Filename.makeUnique(true,&ErrMsg)) {
cerr << "Error: " << ErrMsg << "\n";
return;
}
cerr << "Writing '" << Filename << "'... ";
std::ofstream O(Filename.c_str());
if (O.good()) {
InheritanceHierarchyWriter Writer(Context, O);
Writer.WriteGraph(*this);
cerr << " done. \n";
O.close();
// Display the graph
DisplayGraph(Filename);
} else {
cerr << "error opening file for writing!\n";
Filename.clear();
}
#else
cerr << "QualType::viewInheritance is only available in debug "
<< "builds on systems with Graphviz or gv!\n";
#endif
}
}
<commit_msg>Convert InheritanceHierarchyWriter to use llvm::raw_ostream instead of std::ostream.<commit_after>//===- InheritViz.cpp - Graphviz visualization for inheritance --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements CXXRecordDecl::viewInheritance, which
// generates a GraphViz DOT file that depicts the class inheritance
// diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
namespace clang {
#ifndef NDEBUG
/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
ASTContext& Context;
llvm::raw_ostream &Out;
std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
std::set<QualType, QualTypeOrdering> KnownVirtualBases;
public:
InheritanceHierarchyWriter(ASTContext& Context, llvm::raw_ostream& Out)
: Context(Context), Out(Out) { }
void WriteGraph(QualType Type) {
Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
WriteNode(Type, false);
Out << "}\n";
}
protected:
/// WriteNode - Write out the description of node in the inheritance
/// diagram, which may be a base class or it may be the root node.
void WriteNode(QualType Type, bool FromVirtual);
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
llvm::raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};
void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
if (FromVirtual) {
if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
return;
// We haven't seen this virtual base before, so display it and
// its bases.
KnownVirtualBases.insert(CanonType);
}
// Declare the node itself.
Out << " ";
WriteNodeReference(Type, FromVirtual);
// Give the node a label based on the name of the class.
std::string TypeName = Type.getAsString();
Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);
// If the name of the class was a typedef or something different
// from the "real" class name, show the real class name in
// parentheses so we don't confuse ourselves.
if (TypeName != CanonType.getAsString()) {
Out << "\\n(" << CanonType.getAsString() << ")";
}
// Finished describing the node.
Out << " \"];\n";
// Display the base classes.
const CXXRecordDecl *Decl
= static_cast<const CXXRecordDecl *>(Type->getAsRecordType()->getDecl());
for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin();
Base != Decl->bases_end(); ++Base) {
QualType CanonBaseType = Context.getCanonicalType(Base->getType());
// If this is not virtual inheritance, bump the direct base
// count for the type.
if (!Base->isVirtual())
++DirectBaseCount[CanonBaseType];
// Write out the node (if we need to).
WriteNode(Base->getType(), Base->isVirtual());
// Write out the edge.
Out << " ";
WriteNodeReference(Type, FromVirtual);
Out << " -> ";
WriteNodeReference(Base->getType(), Base->isVirtual());
// Write out edge attributes to show the kind of inheritance.
if (Base->isVirtual()) {
Out << " [ style=\"dashed\" ]";
}
Out << ";";
}
}
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
llvm::raw_ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
Out << "Class_" << CanonType.getAsOpaquePtr();
if (!FromVirtual)
Out << "_" << DirectBaseCount[CanonType];
return Out;
}
#endif
/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void QualType::viewInheritance(ASTContext& Context) {
if (!(*this)->getAsRecordType()) {
cerr << "Type " << getAsString() << " is not a C++ class type.\n";
return;
}
#ifndef NDEBUG
std::string ErrMsg;
sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
if (Filename.isEmpty()) {
cerr << "Error: " << ErrMsg << "\n";
return;
}
Filename.appendComponent(getAsString() + ".dot");
if (Filename.makeUnique(true,&ErrMsg)) {
cerr << "Error: " << ErrMsg << "\n";
return;
}
cerr << "Writing '" << Filename << "'... ";
llvm::raw_fd_ostream O(Filename.c_str(), ErrMsg);
if (ErrMsg.empty()) {
InheritanceHierarchyWriter Writer(Context, O);
Writer.WriteGraph(*this);
cerr << " done. \n";
O.close();
// Display the graph
DisplayGraph(Filename);
} else {
llvm::errs() << "error opening file for writing!\n";
}
#else
llvm::errs() << "QualType::viewInheritance is only available in debug "
<< "builds on systems with Graphviz or gv!\n";
#endif
}
}
<|endoftext|> |
<commit_before>#include "PlatformEntity.h"
PlatformEntity::PlatformEntity(){}
PlatformEntity::~PlatformEntity()
{
this->Shutdown();
}
int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp);
return result;
}
int PlatformEntity::Shutdown()
{
int result = 0;
if (this->m_ActiveSound != nullptr)
this->m_ActiveSound->drop();
return result;
}
int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler)
{
int result = 0;
this->SyncComponents();
// Adjust misplaced graphics component - hack...
this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort,
DirectX::XMMatrixTranslationFromVector(
DirectX::XMVectorSubtract(this->m_pComp->PC_pos,
DirectX::XMVECTOR{
m_gComp->modelPtr->GetOBBData().position.x,
m_gComp->modelPtr->GetOBBData().position.y,
m_gComp->modelPtr->GetOBBData().position.z, 0})));
if (this->GetAIComponent()->AC_triggered)
{
if (this->m_ActiveSound == nullptr)
{
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true);
}
else
{
if (this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setIsPaused(false);
}
}
}
else
{
if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setPlayPosition(0);
this->m_ActiveSound->setIsPaused(true); //Pause the walking sound
}
}
return result;
}
int PlatformEntity::React(int entityID, EVENT reactEvent)
{
switch (reactEvent)
{
//case FIELD_CONTAINS:
// break;
//case FIELD_ENTERED:
// break;
//case FIELD_EXITED:
// break;
//case FIELD_CONDITIONS_MET:
// break;
//case FIELD_ENABLED:
// break;
//case FIELD_DISABLED:
// break;
case BUTTON_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case BUTTON_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
//case LEVER_DEACTIVE:
// break;
//case LEVER_ACTIVE:
// break;
//case LEVER_ENABLED:
// break;
//case LEVER_DISABLED:
// break;
default:
break;
}
return 1;
}<commit_msg>ADD Reaction to Levers to trigger AIComponent<commit_after>#include "PlatformEntity.h"
PlatformEntity::PlatformEntity(){}
PlatformEntity::~PlatformEntity()
{
this->Shutdown();
}
int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp);
return result;
}
int PlatformEntity::Shutdown()
{
int result = 0;
if (this->m_ActiveSound != nullptr)
this->m_ActiveSound->drop();
return result;
}
int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler)
{
int result = 0;
this->SyncComponents();
// Adjust misplaced graphics component - hack...
this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort,
DirectX::XMMatrixTranslationFromVector(
DirectX::XMVectorSubtract(this->m_pComp->PC_pos,
DirectX::XMVECTOR{
m_gComp->modelPtr->GetOBBData().position.x,
m_gComp->modelPtr->GetOBBData().position.y,
m_gComp->modelPtr->GetOBBData().position.z, 0})));
if (this->GetAIComponent()->AC_triggered)
{
if (this->m_ActiveSound == nullptr)
{
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true);
}
else
{
if (this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setIsPaused(false);
}
}
}
else
{
if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setPlayPosition(0);
this->m_ActiveSound->setIsPaused(true); //Pause the walking sound
}
}
return result;
}
int PlatformEntity::React(int entityID, EVENT reactEvent)
{
switch (reactEvent)
{
//case FIELD_CONTAINS:
// break;
//case FIELD_ENTERED:
// break;
//case FIELD_EXITED:
// break;
//case FIELD_CONDITIONS_MET:
// break;
//case FIELD_ENABLED:
// break;
//case FIELD_DISABLED:
// break;
case BUTTON_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case BUTTON_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
case LEVER_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case LEVER_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
//case LEVER_ENABLED:
// break;
//case LEVER_DISABLED:
// break;
default:
break;
}
return 1;
}<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.