<commit_before>#include "physicsEntity.h"

//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//

PhysicsEntity::PhysicsEntity( QString pathToModel, QString pathToTexture,
    btScalar mass, btTransform startingState )
    :   m_pathToModel( pathToModel ), m_pathToTexture( pathToTexture ),
        m_mass( mass )
{
    ModelLoader::loadModel( pathToModel, m_model, m_numVertices );
    ModelLoader::loadTriMesh( pathToModel, m_triMesh );

    // Initialize Bullet
    m_collisionShape = new btBvhTriangleMeshShape( m_triMesh, true );

    m_motionState = new btDefaultMotionState( startingState );

    Inertia = btVector3( 0, 0, 0 );

    m_collisionShape->calculateLocalInertia( m_mass, Inertia );
    m_rigidBodyCI = new btRigidBody::btRigidBodyConstructionInfo(
        m_mass, m_motionState, m_collisionShape, Inertia );

    RigidBody = new btRigidBody( *m_rigidBodyCI );

    // make static objects kinematic
    // see http://www.cse.unr.edu/~fredh/class/480/F2015/proj/PA08/PA8.php
    if( mass == 0 )
    {
        RigidBody->setCollisionFlags(RigidBody->getCollisionFlags() |
            btCollisionObject::CF_KINEMATIC_OBJECT);
        RigidBody->setActivationState(DISABLE_DEACTIVATION);
    }
}

PhysicsEntity::~PhysicsEntity()
{
    teardownGL();

    delete m_triMesh;
    delete m_collisionShape;
    delete m_motionState;
    delete m_rigidBodyCI;
    delete RigidBody;
}

//
// RENDERABLE FUNCTINOS ////////////////////////////////////////////////////////
//

void PhysicsEntity::initializeGL()
{
    initializeOpenGLFunctions();

    // Create the shader this entity will use
    m_program = new QOpenGLShaderProgram();
    m_program->addShaderFromSourceFile( QOpenGLShader::Vertex,
        PATH_TO_V_SHADER );
    m_program->addShaderFromSourceFile( QOpenGLShader::Fragment,
        PATH_TO_F_SHADER );
    m_program->link();
    m_program->bind();

    // Cache the Uniform Locations
    m_modelWorld = m_program->uniformLocation( "model_to_world" );
    m_worldEye = m_program->uniformLocation( "world_to_eye" );
    m_eyeClip = m_program->uniformLocation( "eye_to_clip" );

    // Create the Texture Buffer Object
    m_texture = new QOpenGLTexture( QImage( m_pathToTexture ).mirrored() );
    m_texture->setMinificationFilter( QOpenGLTexture::LinearMipMapLinear );
    m_texture->setMagnificationFilter( QOpenGLTexture::Linear );

    // Create the Vertex Buffer Object
    m_vbo = new QOpenGLBuffer();
    m_vbo->create();
    m_vbo->bind();
    m_vbo->setUsagePattern( QOpenGLBuffer::StaticDraw );
    m_vbo->allocate( m_model, m_numVertices * sizeof( m_model[0] ) );

    // Create the Vertex Array Object
    m_vao = new QOpenGLVertexArrayObject();
    m_vao->create();
    m_vao->bind();
    m_program->enableAttributeArray( 0 );
    m_program->enableAttributeArray( 1 );
    m_program->setAttributeBuffer(  0,
                                    GL_FLOAT,
                                    Vertex::positionOffset(),
                                    Vertex::PositionTupleSize,
                                    Vertex::stride() );
    m_program->setAttributeBuffer(  1,
                                    GL_FLOAT,
                                    Vertex::uvOffset(),
                                    Vertex::UVTupleSize,
                                    Vertex::stride() );

    // Release all in order
    m_vao->release();
    m_vbo->release();
    m_texture->release();
    m_program->release();
}

void PhysicsEntity::paintGL( Camera3D& camera, QMatrix4x4& projection )
{
    m_program->bind();

    m_program->setUniformValue( m_worldEye, camera.toMatrix() );
    m_program->setUniformValue( m_eyeClip, projection );

    m_vao->bind();
    m_texture->bind();

    m_program->setUniformValue( m_modelWorld, Transform );

    glDrawArrays( GL_TRIANGLES, 0, m_numVertices );

    m_texture->release();
    m_vao->release();
    m_program->release();
}

void PhysicsEntity::update()
{
}

void PhysicsEntity::teardownGL()
{
    delete m_vbo;
    delete m_vao;
    delete m_program;
    delete m_model;
    delete m_texture;
}<commit_msg>COLLISION WORKS.<commit_after>#include "physicsEntity.h"

//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//

PhysicsEntity::PhysicsEntity( QString pathToModel, QString pathToTexture,
    btScalar mass, btTransform startingState )
    :   m_pathToModel( pathToModel ), m_pathToTexture( pathToTexture ),
        m_mass( mass )
{
    ModelLoader::loadModel( pathToModel, m_model, m_numVertices );
    ModelLoader::loadTriMesh( pathToModel, m_triMesh );

    // Initialize Bullet
    if( mass == 0 )
        m_collisionShape = new btBvhTriangleMeshShape( m_triMesh, true );
    else
        m_collisionShape = new btConvexTriangleMeshShape( m_triMesh );

    m_motionState = new btDefaultMotionState( startingState );

    Inertia = btVector3( 0, 0, 0 );

    m_collisionShape->calculateLocalInertia( m_mass, Inertia );
    m_rigidBodyCI = new btRigidBody::btRigidBodyConstructionInfo(
        m_mass, m_motionState, m_collisionShape, Inertia );

    RigidBody = new btRigidBody( *m_rigidBodyCI );

    // make static objects kinematic
    // see http://www.cse.unr.edu/~fredh/class/480/F2015/proj/PA08/PA8.php
    if( mass == 0 )
    {
        RigidBody->setCollisionFlags(RigidBody->getCollisionFlags() |
            btCollisionObject::CF_KINEMATIC_OBJECT);
        RigidBody->setActivationState(DISABLE_DEACTIVATION);
    }
}

PhysicsEntity::~PhysicsEntity()
{
    teardownGL();

    delete m_triMesh;
    delete m_collisionShape;
    delete m_motionState;
    delete m_rigidBodyCI;
    delete RigidBody;
}

//
// RENDERABLE FUNCTINOS ////////////////////////////////////////////////////////
//

void PhysicsEntity::initializeGL()
{
    initializeOpenGLFunctions();

    // Create the shader this entity will use
    m_program = new QOpenGLShaderProgram();
    m_program->addShaderFromSourceFile( QOpenGLShader::Vertex,
        PATH_TO_V_SHADER );
    m_program->addShaderFromSourceFile( QOpenGLShader::Fragment,
        PATH_TO_F_SHADER );
    m_program->link();
    m_program->bind();

    // Cache the Uniform Locations
    m_modelWorld = m_program->uniformLocation( "model_to_world" );
    m_worldEye = m_program->uniformLocation( "world_to_eye" );
    m_eyeClip = m_program->uniformLocation( "eye_to_clip" );

    // Create the Texture Buffer Object
    m_texture = new QOpenGLTexture( QImage( m_pathToTexture ).mirrored() );
    m_texture->setMinificationFilter( QOpenGLTexture::LinearMipMapLinear );
    m_texture->setMagnificationFilter( QOpenGLTexture::Linear );

    // Create the Vertex Buffer Object
    m_vbo = new QOpenGLBuffer();
    m_vbo->create();
    m_vbo->bind();
    m_vbo->setUsagePattern( QOpenGLBuffer::StaticDraw );
    m_vbo->allocate( m_model, m_numVertices * sizeof( m_model[0] ) );

    // Create the Vertex Array Object
    m_vao = new QOpenGLVertexArrayObject();
    m_vao->create();
    m_vao->bind();
    m_program->enableAttributeArray( 0 );
    m_program->enableAttributeArray( 1 );
    m_program->setAttributeBuffer(  0,
                                    GL_FLOAT,
                                    Vertex::positionOffset(),
                                    Vertex::PositionTupleSize,
                                    Vertex::stride() );
    m_program->setAttributeBuffer(  1,
                                    GL_FLOAT,
                                    Vertex::uvOffset(),
                                    Vertex::UVTupleSize,
                                    Vertex::stride() );

    // Release all in order
    m_vao->release();
    m_vbo->release();
    m_texture->release();
    m_program->release();
}

void PhysicsEntity::paintGL( Camera3D& camera, QMatrix4x4& projection )
{
    m_program->bind();

    m_program->setUniformValue( m_worldEye, camera.toMatrix() );
    m_program->setUniformValue( m_eyeClip, projection );

    m_vao->bind();
    m_texture->bind();

    m_program->setUniformValue( m_modelWorld, Transform );

    glDrawArrays( GL_TRIANGLES, 0, m_numVertices );

    m_texture->release();
    m_vao->release();
    m_program->release();
}

void PhysicsEntity::update()
{
}

void PhysicsEntity::teardownGL()
{
    delete m_vbo;
    delete m_vao;
    delete m_program;
    delete m_model;
    delete m_texture;
}<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"

#include <memory>

#include "mlir/IR/Module.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"

namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
  // Print the whole module after each pass, which requires disabling
  // multi-threading as well.
  pm->getContext()->disableMultithreading();
  pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
      /*print_module_scope=*/true));
  pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
}  // namespace

namespace TFTPU {
namespace {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
  auto add_pass = [&](std::unique_ptr<Pass> pass) {
    pm.addNestedPass<FuncOp>(std::move(pass));
    pm.addPass(CreateBreakUpIslandsPass());
  };

  pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass());
  add_pass(TFDevice::CreateParallelizeEmbeddingParamsOpsPass());
  pm.addPass(TFDevice::CreateReplicateToIslandPass());
  pm.addPass(CreateBreakUpIslandsPass());
  add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
  add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
}

tensorflow::Status RunTPUBridge(
    ModuleOp module, bool enable_logging,
    llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
  PassManager bridge(module.getContext());
  ::tensorflow::applyTensorflowAndCLOptions(bridge);
  if (enable_logging) EnableLogging(&bridge);

  // Populate a passmanager with the list of passes that implement the bridge.
  pipeline_builder(bridge);

  // Add set of passes to lower back to graph (from tf_executor).
  AddGraphExportLoweringPasses(bridge);

  // Run the bridge on the module, in case of failure, the `diag_handler`
  // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  return diag_handler.ConsumeStatus();
}
}  // namespace

void CreateTPUBridgePipeline(OpPassManager &pm) {
  pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorGraphPruningPass());
  // It is assumed at this stage there are no V1 control flow ops as Graph
  // functionalization is ran before import. Ops can be lifted out of
  // tf_executor dialect islands/graphs.
  pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
  // Run shape inference so that tf_executor/tf_device ops created later will
  // likely to inherit more concrete types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  // Encode this in its own scope so that func_pm is not mistakenly used
  // later on.
  {
    pm.addPass(CreateTPUClusterFormationPass());
    OpPassManager &func_pm = pm.nest<FuncOp>();
    // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
    // because DecomposeResourceOpsPass uses pattern rewriter which hoists
    // changed constants out of tf_device.Launch.
    func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
    func_pm.addPass(CreateTPUHostComputationExpansionPass());
    func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
  }
  // Run another shape inference pass because resource decomposition might have
  // created new partial types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
  pm.addPass(mlir::createInlinerPass());
  pm.addPass(CreateTPUClusterCleanupAttributesPass());
  pm.addPass(TFDevice::CreateResourceOpLiftingPass());
  pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
  pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
  pm.addPass(CreateTPUOutsideCompilationClusterPass());
  pm.addPass(CreateTPUExtractOutsideCompilationPass());

  pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorConstantSinkingPass());
  pm.addPass(TF::CreateResourceDeviceInferencePass());
  pm.addPass(TFDevice::CreateClusterOutliningPass());
  pm.addPass(CreateTPUDynamicPaddingMapperPass());
  pm.addPass(CreateTPUResourceReadForWritePass());
  pm.addPass(CreateTPUShardingIdentificationPass());
  pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
  pm.addPass(CreateTPURewritePass());
  pm.addPass(createSymbolDCEPass());
  pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
  pm.addNestedPass<FuncOp>(CreateTPUDynamicLayoutPass());
  pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
  pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
  pm.addPass(CreateTPUVariableReformattingPass());
  pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}

void CreateTPUBridgePipelineV1(OpPassManager &pm) {
  pm.addPass(TF::CreateTFShapeInferencePass());
  // For V1 compatibility, we process a module where the graph does not have
  // feeds and fetched. We extract first the TPU computation in a submodule,
  // where it'll be in a function with args and returned values, much more like
  // a TF v2 module. We can then run the usual pipeline on this nested module.
  // Afterward we inline back in the parent module and delete the nested one.
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
  OpPassManager &nested_module = pm.nest<ModuleOp>();
  CreateTPUBridgePipeline(nested_module);
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}

tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}

}  // namespace TFTPU

namespace TF {

tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
                                                 bool enable_logging,
                                                 bool enable_inliner) {
  PassManager bridge(module.getContext());
  if (enable_logging) EnableLogging(&bridge);

  StandardPipelineOptions pipeline_options;
  pipeline_options.enable_inliner.setValue(enable_inliner);
  CreateTFStandardPipeline(bridge, pipeline_options);
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  return diag_handler.ConsumeStatus();
}

}  // namespace TF
}  // namespace mlir
<commit_msg>Add TPUDevicePropagation pass to TPU bridge pipeline.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"

#include <memory>

#include "mlir/IR/Module.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"

namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
  // Print the whole module after each pass, which requires disabling
  // multi-threading as well.
  pm->getContext()->disableMultithreading();
  pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
      /*print_module_scope=*/true));
  pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
}  // namespace

namespace TFTPU {
namespace {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
  auto add_pass = [&](std::unique_ptr<Pass> pass) {
    pm.addNestedPass<FuncOp>(std::move(pass));
    pm.addPass(CreateBreakUpIslandsPass());
  };

  pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass());
  add_pass(TFDevice::CreateParallelizeEmbeddingParamsOpsPass());
  pm.addPass(TFDevice::CreateReplicateToIslandPass());
  pm.addPass(CreateBreakUpIslandsPass());
  add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
  add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
  pm.addNestedPass<FuncOp>(CreateTPUDevicePropagationPass());
}

tensorflow::Status RunTPUBridge(
    ModuleOp module, bool enable_logging,
    llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
  PassManager bridge(module.getContext());
  ::tensorflow::applyTensorflowAndCLOptions(bridge);
  if (enable_logging) EnableLogging(&bridge);

  // Populate a passmanager with the list of passes that implement the bridge.
  pipeline_builder(bridge);

  // Add set of passes to lower back to graph (from tf_executor).
  AddGraphExportLoweringPasses(bridge);

  // Run the bridge on the module, in case of failure, the `diag_handler`
  // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  return diag_handler.ConsumeStatus();
}
}  // namespace

void CreateTPUBridgePipeline(OpPassManager &pm) {
  pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorGraphPruningPass());
  // It is assumed at this stage there are no V1 control flow ops as Graph
  // functionalization is ran before import. Ops can be lifted out of
  // tf_executor dialect islands/graphs.
  pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
  // Run shape inference so that tf_executor/tf_device ops created later will
  // likely to inherit more concrete types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  // Encode this in its own scope so that func_pm is not mistakenly used
  // later on.
  {
    pm.addPass(CreateTPUClusterFormationPass());
    OpPassManager &func_pm = pm.nest<FuncOp>();
    // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
    // because DecomposeResourceOpsPass uses pattern rewriter which hoists
    // changed constants out of tf_device.Launch.
    func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
    func_pm.addPass(CreateTPUHostComputationExpansionPass());
    func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
  }
  // Run another shape inference pass because resource decomposition might have
  // created new partial types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
  pm.addPass(mlir::createInlinerPass());
  pm.addPass(CreateTPUClusterCleanupAttributesPass());
  pm.addPass(TFDevice::CreateResourceOpLiftingPass());
  pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
  pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
  pm.addPass(CreateTPUOutsideCompilationClusterPass());
  pm.addPass(CreateTPUExtractOutsideCompilationPass());

  pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorConstantSinkingPass());
  pm.addPass(TF::CreateResourceDeviceInferencePass());
  pm.addPass(TFDevice::CreateClusterOutliningPass());
  pm.addPass(CreateTPUDynamicPaddingMapperPass());
  pm.addPass(CreateTPUResourceReadForWritePass());
  pm.addPass(CreateTPUShardingIdentificationPass());
  pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
  pm.addPass(CreateTPURewritePass());
  pm.addPass(createSymbolDCEPass());
  pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
  pm.addNestedPass<FuncOp>(CreateTPUDynamicLayoutPass());
  pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
  pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
  pm.addPass(CreateTPUVariableReformattingPass());
  pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}

void CreateTPUBridgePipelineV1(OpPassManager &pm) {
  pm.addPass(TF::CreateTFShapeInferencePass());
  // For V1 compatibility, we process a module where the graph does not have
  // feeds and fetched. We extract first the TPU computation in a submodule,
  // where it'll be in a function with args and returned values, much more like
  // a TF v2 module. We can then run the usual pipeline on this nested module.
  // Afterward we inline back in the parent module and delete the nested one.
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
  OpPassManager &nested_module = pm.nest<ModuleOp>();
  CreateTPUBridgePipeline(nested_module);
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}

tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}

}  // namespace TFTPU

namespace TF {

tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
                                                 bool enable_logging,
                                                 bool enable_inliner) {
  PassManager bridge(module.getContext());
  if (enable_logging) EnableLogging(&bridge);

  StandardPipelineOptions pipeline_options;
  pipeline_options.enable_inliner.setValue(enable_inliner);
  CreateTFStandardPipeline(bridge, pipeline_options);
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  return diag_handler.ConsumeStatus();
}

}  // namespace TF
}  // namespace mlir
<|endoftext|>


<commit_before>// ConClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <thread>
#include "Console.h"
#include "cxxopts.hpp"

#ifdef _WIN32
int _tmain(int argc, _TCHAR* argv[]) {
#else /* _WIN32 */
int main(int argc, char* argv[]) {
#endif /* _WIN32 */
    using std::cout;
    using std::endl;

    std::string host;
    std::string file;
    bool keepOpen = false;

    cxxopts::Options options("remoteconsole.exe", "MegaMol Remote Lua Console Client");
    options.add_options()
        ("open", "open host", cxxopts::value<std::string>())
        ("source", "source file", cxxopts::value<std::string>())
        ("keep-open", "keep open")
        ("help", "print help")
        ;

    try {
        options.parse(argc, argv);
    } catch (...) {
        std::cout << options.help({ "" }) << std::endl;
        exit(0);
    }

    if (options.count("help")) {
        std::cout << options.help({ "" }) << std::endl;
        exit(0);
    }

    // greeting text
    printGreeting();

    host = options["open"].as<std::string>();
    file = options["source"].as<std::string>();
    keepOpen = options["keep-open"].as<bool>();

    //  Prepare our context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_REQ);
    Connection conn(socket);

    if (!host.empty()) {
        cout << "Connecting \"" << host << "\" ... ";
        try {
            conn.Connect(host);
            cout << endl
                << "\tConnected" << endl
                << endl;

        } catch (std::exception& ex) {
            cout << endl
                << "ERR Socket connection failed: " << ex.what() << endl
                << endl;
        } catch (...) {
            cout << endl
                << "ERR Socket connection failed: unknown exception" << endl
                << endl;
        }
    }

    if (!file.empty()) {
        runScript(conn, file);

    } else {
        keepOpen = true;
    }

    if (keepOpen) {
        interactiveConsole(conn);
    }

    return 0;
}

<commit_msg>fix for new cxxopts interface<commit_after>// ConClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <thread>
#include "Console.h"
#include "cxxopts.hpp"

#ifdef _WIN32
int _tmain(int argc, _TCHAR* argv[]) {
#else /* _WIN32 */
int main(int argc, char* argv[]) {
#endif /* _WIN32 */
    using std::cout;
    using std::endl;

    std::string host;
    std::string file;
    bool keepOpen = false;

    cxxopts::Options options("remoteconsole.exe", "MegaMol Remote Lua Console Client");
    options.add_options()
        ("open", "open host", cxxopts::value<std::string>())
        ("source", "source file", cxxopts::value<std::string>())
        ("keep-open", "keep open")
        ("help", "print help")
        ;

    try {

        auto parseRes = options.parse(argc, argv);

        if (parseRes.count("help")) {
            std::cout << options.help({ "" }) << std::endl;
            exit(0);
        }

        // greeting text
        printGreeting();

        if (parseRes.count("open")) host = parseRes["open"].as<std::string>();
        if (parseRes.count("source")) file = parseRes["source"].as<std::string>();
        if (parseRes.count("keep-open")) keepOpen = parseRes["keep-open"].as<bool>();

        //  Prepare our context and socket
        zmq::context_t context(1);
        zmq::socket_t socket(context, ZMQ_REQ);
        Connection conn(socket);

        if (!host.empty()) {
            cout << "Connecting \"" << host << "\" ... ";
            try {
                conn.Connect(host);
                cout << endl
                    << "\tConnected" << endl
                    << endl;

            } catch (std::exception& ex) {
                cout << endl
                    << "ERR Socket connection failed: " << ex.what() << endl
                    << endl;
            } catch (...) {
                cout << endl
                    << "ERR Socket connection failed: unknown exception" << endl
                    << endl;
            }
        }

        if (!file.empty()) {
            runScript(conn, file);

        } else {
            keepOpen = true;
        }

        if (keepOpen) {
            interactiveConsole(conn);
        }

    } catch (...) {
        std::cout << options.help({ "" }) << std::endl;
        exit(0);
    }

    return 0;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/*
  Produces the data needed to calculate the quality assurance.
  All data must be mergeable objects.
  Y. Schutz CERN July 2007
*/

// --- ROOT system ---
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TH2F.h>

// --- Standard library ---

// --- AliRoot header files ---
#include "AliESDCaloCluster.h"
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliPHOSDigit.h"
#include "AliPHOSHit.h"
#include "AliPHOSQualAssDataMaker.h"
#include "AliPHOSCpvRecPoint.h"
#include "AliPHOSEmcRecPoint.h"
#include "AliPHOSRecParticle.h"
#include "AliPHOSTrackSegment.h"
#include "AliPHOSRawDecoder.h"

ClassImp(AliPHOSQualAssDataMaker)

//____________________________________________________________________________
  AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker() :
  AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kPHOS), "PHOS Quality Assurance Data Maker")
{
  // ctor
}

//____________________________________________________________________________
AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker(const AliPHOSQualAssDataMaker& qadm) :
  AliQualAssDataMaker()
{
  //copy ctor
  SetName((const char*)qadm.GetName()) ;
  SetTitle((const char*)qadm.GetTitle());
}

//__________________________________________________________________
AliPHOSQualAssDataMaker& AliPHOSQualAssDataMaker::operator = (const AliPHOSQualAssDataMaker& qadm )
{
  // Equal operator.
  this->~AliPHOSQualAssDataMaker();
  new(this) AliPHOSQualAssDataMaker(qadm);
  return *this;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::EndOfDetectorCycle()
{
  //Detector specific actions at end of cycle
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitESDs()
{
  //create ESDs histograms in ESDs subdir
  TH1F * h0 = new TH1F("hPhosESDs",    "ESDs energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2ESDsList(h0, 0) ;
  TH1I * h1  = new TH1I("hPhosESDsMul", "ESDs multiplicity distribution in PHOS", 100, 0., 100) ;
  h1->Sumw2() ;
  Add2ESDsList(h1, 1) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitHits()
{
  // create Hits histograms in Hits subdir
  TH1F * h0 = new TH1F("hPhosHits",    "Hits energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2HitsList(h0, 0) ;
  TH1I * h1  = new TH1I("hPhosHitsMul", "Hits multiplicity distribution in PHOS", 500, 0., 10000) ;
  h1->Sumw2() ;
  Add2HitsList(h1, 1) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitDigits()
{
  // create Digits histograms in Digits subdir
  TH1I * h0 = new TH1I("hPhosDigits",    "Digits amplitude distribution in PHOS",    500, 0, 5000) ;
  h0->Sumw2() ;
  Add2DigitsList(h0, 0) ;
  TH1I * h1 = new TH1I("hPhosDigitsMul", "Digits multiplicity distribution in PHOS", 500, 0, 1000) ;
  h1->Sumw2() ;
  Add2DigitsList(h1, 0) ;
}

//____________________________________________________________________________
//void AliPHOSQualAssDataMaker::InitRecParticles()
//{
//  // create Reconstructed particles histograms in RecParticles subdir
//  fhRecParticles     = new TH1F("hPhosRecParticles",    "RecParticles energy distribution in PHOS",       100, 0., 100.) ;
//  fhRecParticles->Sumw2() ;
//  fhRecParticlesMul  = new TH1I("hPhosRecParticlesMul", "RecParticles multiplicity distribution in PHOS", 100, 0,  100) ;
//  fhRecParticlesMul->Sumw2() ;
//}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitRecPoints()
{
  // create Reconstructed Points histograms in RecPoints subdir
  TH1F * h0 = new TH1F("hEmcPhosRecPoints",    "EMCA RecPoints energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2RecPointsList(h0, 0) ;
  TH1I * h1 = new TH1I("hEmcPhosRecPointsMul", "EMCA RecPoints multiplicity distribution in PHOS", 100, 0,  100) ;
  h1->Sumw2() ;
  Add2RecPointsList(h1, 1) ;

  TH1F * h2 = new TH1F("hCpvPhosRecPoints",    "CPV RecPoints energy distribution in PHOS",       100, 0., 100.) ;
  h2->Sumw2() ;
  Add2RecPointsList(h2, 2) ;
  TH1I * h3 = new TH1I("hCpvPhosRecPointsMul", "CPV RecPoints multiplicity distribution in PHOS", 100, 0,  100) ;
  h3->Sumw2() ;
  Add2RecPointsList(h3, 3) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitRaws()
{
  // create Raws histograms in Raws subdir
  TH1I * h0 = new TH1I("hPhosModules",    "Hits in EMCA PHOS modules",       6, 0, 6) ;
  h0->Sumw2() ;
  Add2RawsList(h0, 0) ;
  const Int_t modMax = 5 ;
  TH2I * h1[modMax] ;
  for (Int_t mod = 0; mod < modMax; mod++) {
   char name[16] ;
   sprintf(name, "hPHOSMod%d", mod) ;
   char title[32] ;
   sprintf(title, "Raws x Columns for PHOS module %d", mod+1) ;
   h1[mod] = new TH2I(name, title, 64, 0, 63, 56, 0, 55) ;
   Add2RawsList(h1[mod], mod+1) ;
  }
  TH1F * h6 = new TH1F("hPhosRawtime", "Time of raw hits in PHOS", 100, 0, 100.) ;
  h6->Sumw2() ;
  Add2RawsList(h6, 6) ;
  TH1F * h7 = new TH1F("hPhosRawEnergy", "Energy of raw hits in PHOS", 1000, 0., 1200.) ;
  h7->Sumw2() ;
  Add2RawsList(h7, 7) ;

}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitSDigits()
{
  // create SDigits histograms in SDigits subdir
  TH1F * h0 = new TH1F("hPhosSDigits",    "SDigits energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2SDigitsList(h0, 0) ;
  TH1I * h1 = new TH1I("hPhosSDigitsMul", "SDigits multiplicity distribution in PHOS", 500, 0,  10000) ;
  h1->Sumw2() ;
  Add2SDigitsList(h1, 1) ;
}

//____________________________________________________________________________
//void AliPHOSQualAssDataMaker::InitTrackSegments()
//{
//  // create Track Segments histograms in TrackSegments subdir
//  fhTrackSegments     = new TH1F("hPhosTrackSegments",    "TrackSegments EMC-CPV distance in PHOS",       500, 0., 5000.) ;
//  fhTrackSegments->Sumw2() ;
//  fhTrackSegmentsMul  = new TH1I("hPhosTrackSegmentsMul", "TrackSegments multiplicity distribution in PHOS", 100, 0,  100) ;
//  fhTrackSegmentsMul->Sumw2() ;
//}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeESDs(AliESDEvent * esd)
{
  // make QA data from ESDs

  Int_t maxClu = esd->GetNumberOfPHOSClusters() ;
  Int_t index = 0, count = 0 ;
  for ( index = 0 ; index < maxClu; index++ ) {
    AliESDCaloCluster * clu = esd->GetCaloCluster(index) ;
    GetESDsData(0)->Fill(clu->E()) ;
    count++ ;
  }
  GetESDsData(1)->Fill(count) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeHits(TClonesArray * hits)
{
  //make QA data from Hits

    GetHitsData(1)->Fill(hits->GetEntriesFast()) ;
    TIter next(hits) ;
    AliPHOSHit * hit ;
    while ( (hit = dynamic_cast<AliPHOSHit *>(next())) ) {
      GetHitsData(0)->Fill( hit->GetEnergy()) ;
    }
}
//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeDigits(TClonesArray * digits)
{
  // makes data from Digits

    GetDigitsData(1)->Fill(digits->GetEntriesFast()) ;
    TIter next(digits) ;
    AliPHOSDigit * digit ;
    while ( (digit = dynamic_cast<AliPHOSDigit *>(next())) ) {
      GetDigitsData(0)->Fill( digit->GetEnergy()) ;
    }
}

//____________________________________________________________________________
// void AliPHOSQualAssDataMaker::MakeRecParticles(TTree * recpar)
// {
//   // makes data from RecParticles

//   TClonesArray * recparticles = dynamic_cast<TClonesArray*>(fData) ;
//   fhRecParticlesMul->Fill(recparticles->GetEntriesFast()) ;
//   TIter next(recparticles) ;
//   AliPHOSRecParticle * recparticle ;
//   while ( (recparticle = dynamic_cast<AliPHOSRecParticle *>(next())) ) {
//     fhRecParticles->Fill( recparticle->Energy()) ;
//   }
// }

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeRaws(AliRawReader* rawReader)
{
  rawReader->Reset() ;
  AliPHOSRawDecoder decoder(rawReader);
  decoder.SetOldRCUFormat(kTRUE);
  Int_t count = 0 ;
  while (decoder.NextDigit()) {
   Int_t module  = decoder.GetModule() ;
   Int_t row     = decoder.GetRow() ;
   Int_t col     = decoder.GetColumn() ;
   Double_t time = decoder.GetTime() ;
   Double_t energy  = decoder.GetEnergy() ;
   GetRawsData(0)->Fill(module) ;
   GetRawsData(module)->Fill(row, col) ;
   GetRawsData(6)->Fill(time) ;
   GetRawsData(7)->Fill(energy) ;
   AliInfo(Form(" %d %d %d %d %f %f\n", count, module, row, col, time, energy)) ;
   count++ ;
  }
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeRecPoints(TTree * clustersTree)
{
  {
    // makes data from RecPoints
    TBranch *emcbranch = clustersTree->GetBranch("PHOSEmcRP");
    if (!emcbranch) {
      AliError("can't get the branch with the PHOS EMC clusters !");
      return;
    }
    TObjArray * emcrecpoints = new TObjArray(100) ;
    emcbranch->SetAddress(&emcrecpoints);
    emcbranch->GetEntry(0);

    GetRecPointsData(1)->Fill(emcrecpoints->GetEntriesFast()) ;
    TIter next(emcrecpoints) ;
    AliPHOSEmcRecPoint * rp ;
    while ( (rp = dynamic_cast<AliPHOSEmcRecPoint *>(next())) ) {
      GetRecPointsData(0)->Fill( rp->GetEnergy()) ;
    }
    emcrecpoints->Delete();
    delete emcrecpoints;
  }
  {
    TBranch *cpvbranch = clustersTree->GetBranch("PHOSCpvRP");
    if (!cpvbranch) {
      AliError("can't get the branch with the PHOS CPV clusters !");
      return;
    }
    TObjArray *cpvrecpoints = new TObjArray(100) ;
    cpvbranch->SetAddress(&cpvrecpoints);
    cpvbranch->GetEntry(0);

    GetRecPointsData(1)->Fill(cpvrecpoints->GetEntriesFast()) ;
    TIter next(cpvrecpoints) ;
    AliPHOSCpvRecPoint * rp ;
    while ( (rp = dynamic_cast<AliPHOSCpvRecPoint *>(next())) ) {
      GetRecPointsData(0)->Fill( rp->GetEnergy()) ;
    }
    cpvrecpoints->Delete();
    delete cpvrecpoints;
  }
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeSDigits(TClonesArray * sdigits)
{
  // makes data from SDigits

	GetSDigitsData(1)->Fill(sdigits->GetEntriesFast()) ;
    TIter next(sdigits) ;
    AliPHOSDigit * sdigit ;
    while ( (sdigit = dynamic_cast<AliPHOSDigit *>(next())) ) {
      GetSDigitsData(0)->Fill( sdigit->GetEnergy()) ;
    }
}

//____________________________________________________________________________
// void AliPHOSQualAssDataMaker::MakeTrackSegments(TTree * ts)
// {
//   // makes data from TrackSegments

//   TClonesArray * tracksegments = dynamic_cast<TClonesArray*>(fData) ;

//   fhTrackSegmentsMul->Fill(tracksegments->GetEntriesFast()) ;
//   TIter next(tracksegments) ;
//   AliPHOSTrackSegment * ts ;
//   while ( (ts = dynamic_cast<AliPHOSTrackSegment *>(next())) ) {
//     fhTrackSegments->Fill( ts->GetCpvDistance()) ;
//   }
// }

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::StartOfDetectorCycle()
{
  //Detector specific actions at start of cycle

}
<commit_msg>Mini bug corrected<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/*
  Produces the data needed to calculate the quality assurance.
  All data must be mergeable objects.
  Y. Schutz CERN July 2007
*/

// --- ROOT system ---
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TH2F.h>

// --- Standard library ---

// --- AliRoot header files ---
#include "AliESDCaloCluster.h"
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliPHOSDigit.h"
#include "AliPHOSHit.h"
#include "AliPHOSQualAssDataMaker.h"
#include "AliPHOSCpvRecPoint.h"
#include "AliPHOSEmcRecPoint.h"
#include "AliPHOSRecParticle.h"
#include "AliPHOSTrackSegment.h"
#include "AliPHOSRawDecoder.h"

ClassImp(AliPHOSQualAssDataMaker)

//____________________________________________________________________________
  AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker() :
  AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kPHOS), "PHOS Quality Assurance Data Maker")
{
  // ctor
}

//____________________________________________________________________________
AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker(const AliPHOSQualAssDataMaker& qadm) :
  AliQualAssDataMaker()
{
  //copy ctor
  SetName((const char*)qadm.GetName()) ;
  SetTitle((const char*)qadm.GetTitle());
}

//__________________________________________________________________
AliPHOSQualAssDataMaker& AliPHOSQualAssDataMaker::operator = (const AliPHOSQualAssDataMaker& qadm )
{
  // Equal operator.
  this->~AliPHOSQualAssDataMaker();
  new(this) AliPHOSQualAssDataMaker(qadm);
  return *this;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::EndOfDetectorCycle()
{
  //Detector specific actions at end of cycle
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitESDs()
{
  //create ESDs histograms in ESDs subdir
  TH1F * h0 = new TH1F("hPhosESDs",    "ESDs energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2ESDsList(h0, 0) ;
  TH1I * h1  = new TH1I("hPhosESDsMul", "ESDs multiplicity distribution in PHOS", 100, 0., 100) ;
  h1->Sumw2() ;
  Add2ESDsList(h1, 1) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitHits()
{
  // create Hits histograms in Hits subdir
  TH1F * h0 = new TH1F("hPhosHits",    "Hits energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2HitsList(h0, 0) ;
  TH1I * h1  = new TH1I("hPhosHitsMul", "Hits multiplicity distribution in PHOS", 500, 0., 10000) ;
  h1->Sumw2() ;
  Add2HitsList(h1, 1) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitDigits()
{
  // create Digits histograms in Digits subdir
  TH1I * h0 = new TH1I("hPhosDigits",    "Digits amplitude distribution in PHOS",    500, 0, 5000) ;
  h0->Sumw2() ;
  Add2DigitsList(h0, 0) ;
  TH1I * h1 = new TH1I("hPhosDigitsMul", "Digits multiplicity distribution in PHOS", 500, 0, 1000) ;
  h1->Sumw2() ;
  Add2DigitsList(h1, 0) ;
}

//____________________________________________________________________________
//void AliPHOSQualAssDataMaker::InitRecParticles()
//{
//  // create Reconstructed particles histograms in RecParticles subdir
//  fhRecParticles     = new TH1F("hPhosRecParticles",    "RecParticles energy distribution in PHOS",       100, 0., 100.) ;
//  fhRecParticles->Sumw2() ;
//  fhRecParticlesMul  = new TH1I("hPhosRecParticlesMul", "RecParticles multiplicity distribution in PHOS", 100, 0,  100) ;
//  fhRecParticlesMul->Sumw2() ;
//}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitRecPoints()
{
  // create Reconstructed Points histograms in RecPoints subdir
  TH1F * h0 = new TH1F("hEmcPhosRecPoints",    "EMCA RecPoints energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2RecPointsList(h0, 0) ;
  TH1I * h1 = new TH1I("hEmcPhosRecPointsMul", "EMCA RecPoints multiplicity distribution in PHOS", 100, 0,  100) ;
  h1->Sumw2() ;
  Add2RecPointsList(h1, 1) ;

  TH1F * h2 = new TH1F("hCpvPhosRecPoints",    "CPV RecPoints energy distribution in PHOS",       100, 0., 100.) ;
  h2->Sumw2() ;
  Add2RecPointsList(h2, 2) ;
  TH1I * h3 = new TH1I("hCpvPhosRecPointsMul", "CPV RecPoints multiplicity distribution in PHOS", 100, 0,  100) ;
  h3->Sumw2() ;
  Add2RecPointsList(h3, 3) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitRaws()
{
  // create Raws histograms in Raws subdir
  TH1I * h0 = new TH1I("hPhosModules",    "Hits in EMCA PHOS modules",       6, 0, 6) ;
  h0->Sumw2() ;
  Add2RawsList(h0, 0) ;
  const Int_t modMax = 5 ;
  TH2I * h1[modMax] ;
  char name[32] ;
  char title[32] ;
  for (Int_t mod = 0; mod < modMax; mod++) {
   sprintf(title, "Raws x Columns for PHOS module %d", mod+1) ;
   sprintf(name, "hPHOSxyMod%d", mod+1) ;
   h1[mod] = new TH2I(name, title, 64, 0, 63, 56, 0, 55) ;
   Add2RawsList(h1[mod], mod+1) ;
  }
  TH1F * h6 = new TH1F("hPhosRawtime", "Time of raw hits in PHOS", 100, 0, 100.) ;
  h6->Sumw2() ;
  Add2RawsList(h6, 6) ;
  TH1F * h7 = new TH1F("hPhosRawEnergy", "Energy of raw hits in PHOS", 1000, 0., 1200.) ;
  h7->Sumw2() ;
  Add2RawsList(h7, 7) ;

}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::InitSDigits()
{
  // create SDigits histograms in SDigits subdir
  TH1F * h0 = new TH1F("hPhosSDigits",    "SDigits energy distribution in PHOS",       100, 0., 100.) ;
  h0->Sumw2() ;
  Add2SDigitsList(h0, 0) ;
  TH1I * h1 = new TH1I("hPhosSDigitsMul", "SDigits multiplicity distribution in PHOS", 500, 0,  10000) ;
  h1->Sumw2() ;
  Add2SDigitsList(h1, 1) ;
}

//____________________________________________________________________________
//void AliPHOSQualAssDataMaker::InitTrackSegments()
//{
//  // create Track Segments histograms in TrackSegments subdir
//  fhTrackSegments     = new TH1F("hPhosTrackSegments",    "TrackSegments EMC-CPV distance in PHOS",       500, 0., 5000.) ;
//  fhTrackSegments->Sumw2() ;
//  fhTrackSegmentsMul  = new TH1I("hPhosTrackSegmentsMul", "TrackSegments multiplicity distribution in PHOS", 100, 0,  100) ;
//  fhTrackSegmentsMul->Sumw2() ;
//}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeESDs(AliESDEvent * esd)
{
  // make QA data from ESDs

  Int_t maxClu = esd->GetNumberOfPHOSClusters() ;
  Int_t index = 0, count = 0 ;
  for ( index = 0 ; index < maxClu; index++ ) {
    AliESDCaloCluster * clu = esd->GetCaloCluster(index) ;
    GetESDsData(0)->Fill(clu->E()) ;
    count++ ;
  }
  GetESDsData(1)->Fill(count) ;
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeHits(TClonesArray * hits)
{
  //make QA data from Hits

    GetHitsData(1)->Fill(hits->GetEntriesFast()) ;
    TIter next(hits) ;
    AliPHOSHit * hit ;
    while ( (hit = dynamic_cast<AliPHOSHit *>(next())) ) {
      GetHitsData(0)->Fill( hit->GetEnergy()) ;
    }
}
//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeDigits(TClonesArray * digits)
{
  // makes data from Digits

    GetDigitsData(1)->Fill(digits->GetEntriesFast()) ;
    TIter next(digits) ;
    AliPHOSDigit * digit ;
    while ( (digit = dynamic_cast<AliPHOSDigit *>(next())) ) {
      GetDigitsData(0)->Fill( digit->GetEnergy()) ;
    }
}

//____________________________________________________________________________
// void AliPHOSQualAssDataMaker::MakeRecParticles(TTree * recpar)
// {
//   // makes data from RecParticles

//   TClonesArray * recparticles = dynamic_cast<TClonesArray*>(fData) ;
//   fhRecParticlesMul->Fill(recparticles->GetEntriesFast()) ;
//   TIter next(recparticles) ;
//   AliPHOSRecParticle * recparticle ;
//   while ( (recparticle = dynamic_cast<AliPHOSRecParticle *>(next())) ) {
//     fhRecParticles->Fill( recparticle->Energy()) ;
//   }
// }

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeRaws(AliRawReader* rawReader)
{
  rawReader->Reset() ;
  AliPHOSRawDecoder decoder(rawReader);
  decoder.SetOldRCUFormat(kTRUE);
  Int_t count = 0 ;
  while (decoder.NextDigit()) {
   Int_t module  = decoder.GetModule() ;
   Int_t row     = decoder.GetRow() ;
   Int_t col     = decoder.GetColumn() ;
   Double_t time = decoder.GetTime() ;
   Double_t energy  = decoder.GetEnergy() ;
   GetRawsData(0)->Fill(module) ;
   GetRawsData(module)->Fill(row, col) ;
   GetRawsData(6)->Fill(time) ;
   GetRawsData(7)->Fill(energy) ;
   //AliInfo(Form(" %d %d %d %d %f %f\n", count, module, row, col, time, energy)) ;
   count++ ;
  }
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeRecPoints(TTree * clustersTree)
{
  {
    // makes data from RecPoints
    TBranch *emcbranch = clustersTree->GetBranch("PHOSEmcRP");
    if (!emcbranch) {
      AliError("can't get the branch with the PHOS EMC clusters !");
      return;
    }
    TObjArray * emcrecpoints = new TObjArray(100) ;
    emcbranch->SetAddress(&emcrecpoints);
    emcbranch->GetEntry(0);

    GetRecPointsData(1)->Fill(emcrecpoints->GetEntriesFast()) ;
    TIter next(emcrecpoints) ;
    AliPHOSEmcRecPoint * rp ;
    while ( (rp = dynamic_cast<AliPHOSEmcRecPoint *>(next())) ) {
      GetRecPointsData(0)->Fill( rp->GetEnergy()) ;
    }
    emcrecpoints->Delete();
    delete emcrecpoints;
  }
  {
    TBranch *cpvbranch = clustersTree->GetBranch("PHOSCpvRP");
    if (!cpvbranch) {
      AliError("can't get the branch with the PHOS CPV clusters !");
      return;
    }
    TObjArray *cpvrecpoints = new TObjArray(100) ;
    cpvbranch->SetAddress(&cpvrecpoints);
    cpvbranch->GetEntry(0);

    GetRecPointsData(1)->Fill(cpvrecpoints->GetEntriesFast()) ;
    TIter next(cpvrecpoints) ;
    AliPHOSCpvRecPoint * rp ;
    while ( (rp = dynamic_cast<AliPHOSCpvRecPoint *>(next())) ) {
      GetRecPointsData(0)->Fill( rp->GetEnergy()) ;
    }
    cpvrecpoints->Delete();
    delete cpvrecpoints;
  }
}

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::MakeSDigits(TClonesArray * sdigits)
{
  // makes data from SDigits

	GetSDigitsData(1)->Fill(sdigits->GetEntriesFast()) ;
    TIter next(sdigits) ;
    AliPHOSDigit * sdigit ;
    while ( (sdigit = dynamic_cast<AliPHOSDigit *>(next())) ) {
      GetSDigitsData(0)->Fill( sdigit->GetEnergy()) ;
    }
}

//____________________________________________________________________________
// void AliPHOSQualAssDataMaker::MakeTrackSegments(TTree * ts)
// {
//   // makes data from TrackSegments

//   TClonesArray * tracksegments = dynamic_cast<TClonesArray*>(fData) ;

//   fhTrackSegmentsMul->Fill(tracksegments->GetEntriesFast()) ;
//   TIter next(tracksegments) ;
//   AliPHOSTrackSegment * ts ;
//   while ( (ts = dynamic_cast<AliPHOSTrackSegment *>(next())) ) {
//     fhTrackSegments->Fill( ts->GetCpvDistance()) ;
//   }
// }

//____________________________________________________________________________
void AliPHOSQualAssDataMaker::StartOfDetectorCycle()
{
  //Detector specific actions at start of cycle

}
<|endoftext|>


<commit_before>/*
 PubSubClient.cpp - A simple client for MQTT.
  Nicholas O'Leary
  http://knolleary.net
*/

#include "PubSubClient.h"
#include <string.h>

PubSubClient::PubSubClient(Client& c) :
  _callback(NULL),
  _client(&c),
  _max_retries(10)
{}

PubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :
  _callback(NULL),
  _client(&c),
  _max_retries(10),
  server_ip(ip),
  server_port(port)
{}

PubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :
  _callback(NULL),
  _client(&c),
  _max_retries(10),
  server_port(port),
  server_hostname(hostname)
{}

PubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {
  server_hostname = "";
  server_ip = ip;
  server_port = port;
  return *this;
}

PubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {
  server_hostname = hostname;
  server_port = port;
  return *this;
}

void PubSubClient::_process_message(MQTT::Message* msg) {
  switch (msg->type()) {
  case MQTT::PUBLISH:
    {
      MQTT::Publish *pub = static_cast<MQTT::Publish*>(msg);	// RTTI is disabled on embedded, so no dynamic_cast<>()

      if (_callback)
	_callback(*pub);

      if (pub->qos() == 1) {
	MQTT::PublishAck puback(pub->packet_id());
	puback.send(*_client);
	lastOutActivity = millis();

      } else if (pub->qos() == 2) {
	uint8_t retries = 0;

	{
	  MQTT::PublishRec pubrec(pub->packet_id());
	  if (!send_reliably(&pubrec))
	    return;
	}

	{
	  MQTT::PublishComp pubcomp(pub->packet_id());
	  pubcomp.send(*_client);
	  lastOutActivity = millis();
	}
      }
    }
    break;

  case MQTT::PINGREQ:
    {
      MQTT::PingResp pr;
      pr.send(*_client);
      lastOutActivity = millis();
    }
    break;

  case MQTT::PINGRESP:
    pingOutstanding = false;
  }
}

bool PubSubClient::wait_for(MQTT::message_type match_type, uint16_t match_pid) {
  while (!_client->available()) {
    if (millis() - lastInActivity > keepalive * 1000UL)
      return false;
    yield();
  }

  while (millis() < lastInActivity + (keepalive * 1000)) {
    // Read the packet and check it
    MQTT::Message *msg = MQTT::readPacket(*_client);
    if (msg != NULL) {
      lastInActivity = millis();

      if (msg->type() == match_type) {
	uint8_t pid = msg->packet_id();
	delete msg;
	if (match_pid)
	  return pid == match_pid;
	return true;
      }

      _process_message(msg);
      delete msg;
    }

    yield();
  }

  return false;
}

bool PubSubClient::send_reliably(MQTT::Message* msg) {
  MQTT::message_type r_type = msg->response_type();
  uint16_t pid = msg->packet_id();

  uint8_t retries = 0;
 send:
  msg->send(*_client);
  lastOutActivity = millis();

  if (r_type == MQTT::None)
    return true;

  if (!wait_for(r_type, pid)) {
    if (retries < _max_retries) {
      retries++;
      goto send;
    }
    return false;
  }
  return true;
}

bool PubSubClient::connect(String id) {
  if (connected())
    return false;

  return connect(id, "", 0, false, "");
}

bool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {
  if (connected())
    return false;

  MQTT::Connect conn(id);
  if (willTopic.length())
    conn.set_will(willTopic, willMessage, willQos, willRetain);
  return connect(conn);
}

bool PubSubClient::connect(MQTT::Connect &conn) {
  if (connected())
    return false;

  int result = 0;

  if (server_hostname.length() > 0)
    result = _client->connect(server_hostname.c_str(), server_port);
  else
    result = _client->connect(server_ip, server_port);

  if (!result) {
    _client->stop();
    return false;
  }

  pingOutstanding = false;
  nextMsgId = 1;		// Init the next packet id
  lastInActivity = millis();	// Init this so that wait_for() doesn't think we've already timed-out
  keepalive = conn.keepalive();	// Store the keepalive period from this connection

  bool ret = send_reliably(&conn);
  if (!ret)
    _client->stop();

  return ret;
}

bool PubSubClient::loop() {
  if (!connected())
    return false;

  unsigned long t = millis();
  if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {
    if (pingOutstanding) {
      _client->stop();
      return false;
    } else {
      MQTT::Ping ping;
      ping.send(*_client);
      lastInActivity = lastOutActivity = t;
      pingOutstanding = true;
    }
  }
  if (_client->available()) {
    // Read the packet and check it
    MQTT::Message *msg = MQTT::readPacket(*_client);
    if (msg != NULL) {
      lastInActivity = millis();
      _process_message(msg);
      delete msg;
    }
  }
  return true;
}

bool PubSubClient::publish(String topic, String payload) {
  if (!connected())
    return false;

  MQTT::Publish pub(topic, payload);
  return publish(pub);
}

bool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {
  if (!connected())
    return false;

  MQTT::Publish pub(topic, const_cast<uint8_t*>(payload), plength);
  pub.set_retain(retained);
  return publish(pub);
}

bool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {
  if (!connected())
    return false;

  MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);
  pub.set_retain(retained);
  return publish(pub);
}

bool PubSubClient::publish(MQTT::Publish &pub) {
  if (!connected())
    return false;

  switch (pub.qos()) {
  case 0:
    pub.send(*_client);
    lastOutActivity = millis();
    break;

  case 1:
    if (!send_reliably(&pub))
      return false;
    break;

  case 2:
    {
      if (!send_reliably(&pub))
	return false;

      MQTT::PublishRel pubrel(pub.packet_id());
      if (!send_reliably(&pubrel))
	return false;
    }
    break;
  }
  return true;
}

bool PubSubClient::subscribe(String topic, uint8_t qos) {
  if (!connected())
    return false;

  if (qos > 2)
    return false;

  MQTT::Subscribe sub(next_packet_id(), topic, qos);
  return subscribe(sub);
}

bool PubSubClient::subscribe(MQTT::Subscribe &sub) {
  if (!connected())
    return false;

  if (!send_reliably(&sub))
    return false;

  return true;
}

bool PubSubClient::unsubscribe(String topic) {
  if (!connected())
    return false;

  MQTT::Unsubscribe unsub(next_packet_id(), topic);
  return unsubscribe(unsub);
}

bool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {
  if (!connected())
    return false;

  if (!send_reliably(&unsub))
    return false;

  return true;
}

void PubSubClient::disconnect() {
   MQTT::Disconnect discon;
   discon.send(*_client);
   _client->stop();
   lastInActivity = lastOutActivity = millis();
}

bool PubSubClient::connected() {
   bool rc = _client->connected();
   if (!rc)
     _client->stop();

   return rc;
}
<commit_msg>Check make sure we're connected before trying to disconnect<commit_after>/*
 PubSubClient.cpp - A simple client for MQTT.
  Nicholas O'Leary
  http://knolleary.net
*/

#include "PubSubClient.h"
#include <string.h>

PubSubClient::PubSubClient(Client& c) :
  _callback(NULL),
  _client(&c),
  _max_retries(10)
{}

PubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :
  _callback(NULL),
  _client(&c),
  _max_retries(10),
  server_ip(ip),
  server_port(port)
{}

PubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :
  _callback(NULL),
  _client(&c),
  _max_retries(10),
  server_port(port),
  server_hostname(hostname)
{}

PubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {
  server_hostname = "";
  server_ip = ip;
  server_port = port;
  return *this;
}

PubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {
  server_hostname = hostname;
  server_port = port;
  return *this;
}

void PubSubClient::_process_message(MQTT::Message* msg) {
  switch (msg->type()) {
  case MQTT::PUBLISH:
    {
      MQTT::Publish *pub = static_cast<MQTT::Publish*>(msg);	// RTTI is disabled on embedded, so no dynamic_cast<>()

      if (_callback)
	_callback(*pub);

      if (pub->qos() == 1) {
	MQTT::PublishAck puback(pub->packet_id());
	puback.send(*_client);
	lastOutActivity = millis();

      } else if (pub->qos() == 2) {
	uint8_t retries = 0;

	{
	  MQTT::PublishRec pubrec(pub->packet_id());
	  if (!send_reliably(&pubrec))
	    return;
	}

	{
	  MQTT::PublishComp pubcomp(pub->packet_id());
	  pubcomp.send(*_client);
	  lastOutActivity = millis();
	}
      }
    }
    break;

  case MQTT::PINGREQ:
    {
      MQTT::PingResp pr;
      pr.send(*_client);
      lastOutActivity = millis();
    }
    break;

  case MQTT::PINGRESP:
    pingOutstanding = false;
  }
}

bool PubSubClient::wait_for(MQTT::message_type match_type, uint16_t match_pid) {
  while (!_client->available()) {
    if (millis() - lastInActivity > keepalive * 1000UL)
      return false;
    yield();
  }

  while (millis() < lastInActivity + (keepalive * 1000)) {
    // Read the packet and check it
    MQTT::Message *msg = MQTT::readPacket(*_client);
    if (msg != NULL) {
      lastInActivity = millis();

      if (msg->type() == match_type) {
	uint8_t pid = msg->packet_id();
	delete msg;
	if (match_pid)
	  return pid == match_pid;
	return true;
      }

      _process_message(msg);
      delete msg;
    }

    yield();
  }

  return false;
}

bool PubSubClient::send_reliably(MQTT::Message* msg) {
  MQTT::message_type r_type = msg->response_type();
  uint16_t pid = msg->packet_id();

  uint8_t retries = 0;
 send:
  msg->send(*_client);
  lastOutActivity = millis();

  if (r_type == MQTT::None)
    return true;

  if (!wait_for(r_type, pid)) {
    if (retries < _max_retries) {
      retries++;
      goto send;
    }
    return false;
  }
  return true;
}

bool PubSubClient::connect(String id) {
  if (connected())
    return false;

  return connect(id, "", 0, false, "");
}

bool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {
  if (connected())
    return false;

  MQTT::Connect conn(id);
  if (willTopic.length())
    conn.set_will(willTopic, willMessage, willQos, willRetain);
  return connect(conn);
}

bool PubSubClient::connect(MQTT::Connect &conn) {
  if (connected())
    return false;

  int result = 0;

  if (server_hostname.length() > 0)
    result = _client->connect(server_hostname.c_str(), server_port);
  else
    result = _client->connect(server_ip, server_port);

  if (!result) {
    _client->stop();
    return false;
  }

  pingOutstanding = false;
  nextMsgId = 1;		// Init the next packet id
  lastInActivity = millis();	// Init this so that wait_for() doesn't think we've already timed-out
  keepalive = conn.keepalive();	// Store the keepalive period from this connection

  bool ret = send_reliably(&conn);
  if (!ret)
    _client->stop();

  return ret;
}

bool PubSubClient::loop() {
  if (!connected())
    return false;

  unsigned long t = millis();
  if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {
    if (pingOutstanding) {
      _client->stop();
      return false;
    } else {
      MQTT::Ping ping;
      ping.send(*_client);
      lastInActivity = lastOutActivity = t;
      pingOutstanding = true;
    }
  }
  if (_client->available()) {
    // Read the packet and check it
    MQTT::Message *msg = MQTT::readPacket(*_client);
    if (msg != NULL) {
      lastInActivity = millis();
      _process_message(msg);
      delete msg;
    }
  }
  return true;
}

bool PubSubClient::publish(String topic, String payload) {
  if (!connected())
    return false;

  MQTT::Publish pub(topic, payload);
  return publish(pub);
}

bool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {
  if (!connected())
    return false;

  MQTT::Publish pub(topic, const_cast<uint8_t*>(payload), plength);
  pub.set_retain(retained);
  return publish(pub);
}

bool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {
  if (!connected())
    return false;

  MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);
  pub.set_retain(retained);
  return publish(pub);
}

bool PubSubClient::publish(MQTT::Publish &pub) {
  if (!connected())
    return false;

  switch (pub.qos()) {
  case 0:
    pub.send(*_client);
    lastOutActivity = millis();
    break;

  case 1:
    if (!send_reliably(&pub))
      return false;
    break;

  case 2:
    {
      if (!send_reliably(&pub))
	return false;

      MQTT::PublishRel pubrel(pub.packet_id());
      if (!send_reliably(&pubrel))
	return false;
    }
    break;
  }
  return true;
}

bool PubSubClient::subscribe(String topic, uint8_t qos) {
  if (!connected())
    return false;

  if (qos > 2)
    return false;

  MQTT::Subscribe sub(next_packet_id(), topic, qos);
  return subscribe(sub);
}

bool PubSubClient::subscribe(MQTT::Subscribe &sub) {
  if (!connected())
    return false;

  if (!send_reliably(&sub))
    return false;

  return true;
}

bool PubSubClient::unsubscribe(String topic) {
  if (!connected())
    return false;

  MQTT::Unsubscribe unsub(next_packet_id(), topic);
  return unsubscribe(unsub);
}

bool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {
  if (!connected())
    return false;

  if (!send_reliably(&unsub))
    return false;

  return true;
}

void PubSubClient::disconnect() {
   if (!connected())
     return;

   MQTT::Disconnect discon;
   discon.send(*_client);
   _client->stop();
   lastInActivity = lastOutActivity = millis();
}

bool PubSubClient::connected() {
   bool rc = _client->connected();
   if (!rc)
     _client->stop();

   return rc;
}
<|endoftext|>


<commit_before>// Test that lsan handles tls correctly for many threads
// RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -DUSE_THREAD -o %t-thread
// RUN: %clangxx_lsan %s -DUSE_PTHREAD -o %t-pthread
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=0" not %run %t-thread 2>&1 | FileCheck %s
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=1" %run %t-thread 2>&1
// RUN: %env_lsan_opts="" %run %t-thread 2>&1
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=0" not %run %t-pthread 2>&1 | FileCheck %s
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=1" %run %t-pthread 2>&1
// RUN: %env_lsan_opts="" %run %t-pthread 2>&1

#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

static const int NUM_THREADS = 10;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int finished = 0;

#if USE_THREAD
__thread void *ptr1;
__thread void *ptr2;
__thread void *ptr3;
__thread void *ptr4;
__thread void *ptr5;

void alloc() {
  ptr1 = malloc(1111);
  ptr2 = malloc(2222);
  ptr3 = malloc(3333);
  ptr4 = malloc(4444);
  ptr5 = malloc(5555);
}

#elif USE_PTHREAD
// We won't be able to create the maximum number of keys, due to other users
// of the tls, but we'll use as many keys as we can before failing to create
// a new key.
pthread_key_t keys[PTHREAD_KEYS_MAX];
static const int PTHREAD_KEY_INVALID = 0xffffffff;

void alloc() {
  for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {
    void *ptr = malloc(123);
    if ((keys[i] == PTHREAD_KEY_INVALID) || pthread_setspecific(keys[i], ptr)) {
      free(ptr);
      break;
    }
  }
}

void pthread_destructor(void *arg) {
  assert(0 && "pthread destructors shouldn't be called");
}
#endif

void *thread_start(void *arg) {
  alloc();

  pthread_mutex_lock(&mutex);
  finished++;
  pthread_mutex_unlock(&mutex);

  // don't exit, to intentionally leak tls data
  while (1)
    sleep(100);
}

int main() {
#if USE_PTHREAD
  for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {
    if (pthread_key_create(&keys[i], pthread_destructor)) {
      keys[i] = PTHREAD_KEY_INVALID;
      break;
    }
  }
#endif

  pthread_t thread[NUM_THREADS];
  for (int i = 0; i < NUM_THREADS; ++i) {
    assert(0 == pthread_create(&thread[i], 0, thread_start, 0));
  }
  // spin until all threads have finished
  while (finished < NUM_THREADS)
    sleep(1);
  exit(0);
}

// CHECK: LeakSanitizer: detected memory leaks
// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
<commit_msg>[LSAN-ARM] Marking new test unsupported on ARMHF due to bot failures<commit_after>// Test that lsan handles tls correctly for many threads
// RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -DUSE_THREAD -o %t-thread
// RUN: %clangxx_lsan %s -DUSE_PTHREAD -o %t-pthread
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=0" not %run %t-thread 2>&1 | FileCheck %s
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=1" %run %t-thread 2>&1
// RUN: %env_lsan_opts="" %run %t-thread 2>&1
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=0" not %run %t-pthread 2>&1 | FileCheck %s
// RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=1" %run %t-pthread 2>&1
// RUN: %env_lsan_opts="" %run %t-pthread 2>&1

// Patch r303906 did not fix all the problems.
// UNSUPPORTED: arm-linux,armhf-linux

#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

static const int NUM_THREADS = 10;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int finished = 0;

#if USE_THREAD
__thread void *ptr1;
__thread void *ptr2;
__thread void *ptr3;
__thread void *ptr4;
__thread void *ptr5;

void alloc() {
  ptr1 = malloc(1111);
  ptr2 = malloc(2222);
  ptr3 = malloc(3333);
  ptr4 = malloc(4444);
  ptr5 = malloc(5555);
}

#elif USE_PTHREAD
// We won't be able to create the maximum number of keys, due to other users
// of the tls, but we'll use as many keys as we can before failing to create
// a new key.
pthread_key_t keys[PTHREAD_KEYS_MAX];
static const int PTHREAD_KEY_INVALID = 0xffffffff;

void alloc() {
  for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {
    void *ptr = malloc(123);
    if ((keys[i] == PTHREAD_KEY_INVALID) || pthread_setspecific(keys[i], ptr)) {
      free(ptr);
      break;
    }
  }
}

void pthread_destructor(void *arg) {
  assert(0 && "pthread destructors shouldn't be called");
}
#endif

void *thread_start(void *arg) {
  alloc();

  pthread_mutex_lock(&mutex);
  finished++;
  pthread_mutex_unlock(&mutex);

  // don't exit, to intentionally leak tls data
  while (1)
    sleep(100);
}

int main() {
#if USE_PTHREAD
  for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {
    if (pthread_key_create(&keys[i], pthread_destructor)) {
      keys[i] = PTHREAD_KEY_INVALID;
      break;
    }
  }
#endif

  pthread_t thread[NUM_THREADS];
  for (int i = 0; i < NUM_THREADS; ++i) {
    assert(0 == pthread_create(&thread[i], 0, thread_start, 0));
  }
  // spin until all threads have finished
  while (finished < NUM_THREADS)
    sleep(1);
  exit(0);
}

// CHECK: LeakSanitizer: detected memory leaks
// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fsfactory.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 14:56:33 $
 *
 *  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_svtools.hxx"

#include "fsfactory.hxx"

#ifndef _CPPUHELPER_FACTORY_HXX_
#include "cppuhelper/factory.hxx"
#endif

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

#include <ucbhelper/fileidentifierconverter.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <ucbhelper/content.hxx>

#include <unotools/tempfile.hxx>
#include <unotools/ucbhelper.hxx>

#include "fsstorage.hxx"

using namespace ::com::sun::star;

//-------------------------------------------------------------------------
// Checks whether it is a file URL that represents a folder
sal_Bool isLocalNotFile_Impl( ::rtl::OUString aURL )
{
    sal_Bool bResult = sal_False;

    ::rtl::OUString aSystemPath;
    ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();
    if ( !pBroker )
        throw uno::RuntimeException();

    uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =
            pBroker->getContentProviderManagerInterface();
    try
    {
           aSystemPath = ::ucb::getSystemPathFromFileURL( xManager, aURL );
    }
    catch ( uno::Exception& )
    {
    }

    if ( aSystemPath.getLength() != 0 )
    {
        // it is a local file URL, check that it is not a file
        try
        {
            uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > xDummyEnv;
            ::ucb::Content aContent( aURL, xDummyEnv );
            bResult = aContent.isFolder();
        }
        catch( uno::Exception& )
        {
            bResult = sal_True;
        }
    }

    return bResult;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.FileSystemStorageFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.FileSystemStorageFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL FSStorageFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.FileSystemStorageFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new FSStorageFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstance()
    throw ( uno::Exception,
            uno::RuntimeException )
{
    ::rtl::OUString aTempURL;

    aTempURL = ::utl::TempFile( NULL, sal_True ).GetURL();

    if ( !aTempURL.getLength() )
        throw uno::RuntimeException(); // TODO: can not create tempfile

    ::ucb::Content aResultContent( aTempURL, uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

    return uno::Reference< uno::XInterface >(
                static_cast< OWeakObject* >( new FSStorage( aResultContent,
                                                            embed::ElementModes::READWRITE,
                                                            uno::Sequence< beans::PropertyValue >(),
                                                            m_xFactory ) ),
                uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstanceWithArguments(
            const uno::Sequence< uno::Any >& aArguments )
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // The request for storage can be done with up to three arguments

    // The first argument specifies a source for the storage
    // it must be URL.
    // The second value is a mode the storage should be open in.
    // And the third value is a media descriptor.

    sal_Int32 nArgNum = aArguments.getLength();
    OSL_ENSURE( nArgNum < 4, "Wrong parameter number" );

    if ( !nArgNum )
        return createInstance();

    // first try to retrieve storage open mode if any
    // by default the storage will be open in readonly mode
    sal_Int32 nStorageMode = embed::ElementModes::READ;
    if ( nArgNum >= 2 )
    {
        if( !( aArguments[1] >>= nStorageMode ) )
        {
            OSL_ENSURE( sal_False, "Wrong second argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
        // it's allways possible to read written storage in this implementation
        nStorageMode |= embed::ElementModes::READ;
    }

    // retrieve storage source URL
    ::rtl::OUString aURL;

    if ( aArguments[0] >>= aURL )
    {
        if ( !aURL.getLength() )
        {
            OSL_ENSURE( sal_False, "Empty URL is provided!\n" );
            throw uno::Exception(); // TODO: illegal argument
        }
    }
    else
    {
        OSL_ENSURE( sal_False, "Wrong first argument!\n" );
        throw uno::Exception(); // TODO: Illegal argument
    }

    // retrieve mediadescriptor and set storage properties
    uno::Sequence< beans::PropertyValue > aDescr;
    uno::Sequence< beans::PropertyValue > aPropsToSet;

    if ( nArgNum >= 3 )
    {
        if( aArguments[2] >>= aDescr )
        {
            aPropsToSet.realloc(1);
            aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( "URL" );
            aPropsToSet[0].Value <<= aURL;

            for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )
            {
                if ( aDescr[nInd].Name.equalsAscii( "InteractionHandler" ) )
                {
                    aPropsToSet.realloc( ++nNumArgs );
                    aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;
                    aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;
                    break;
                }
                else
                    OSL_ENSURE( sal_False, "Unacceptable property, will be ignored!\n" );
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "Wrong third argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
    }

    // allow to use other ucp's
    // if ( !isLocalNotFile_Impl( aURL ) )
    if ( aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.pkg", 16 )
      || aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.zip", 16 )
      || ::utl::UCBContentHelper::IsDocument( aURL ) )
    {
        OSL_ENSURE( sal_False, "File system storages can be based only on file URLs!\n" ); // ???
        throw uno::Exception(); // TODO: illegal argument
    }

    if ( ( nStorageMode & embed::ElementModes::WRITE ) && !( nStorageMode & embed::ElementModes::NOCREATE ) )
        FSStorage::MakeFolderNoUI( aURL, sal_False );
    else if ( !::utl::UCBContentHelper::IsFolder( aURL ) )
        throw io::IOException(); // there is no such folder

    ::ucb::Content aResultContent( aURL, uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

    // create storage based on source
    return uno::Reference< uno::XInterface >(
                static_cast< OWeakObject* >( new FSStorage( aResultContent, nStorageMode, aPropsToSet, m_xFactory ) ),
                uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL FSStorageFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL FSStorageFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

//-------------------------------------------------------------------------

extern "C"
{
SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment (
    const sal_Char ** ppEnvTypeName, uno_Environment ** /* ppEnv */)
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo (
    void * /* pServiceManager */, void * pRegistryKey)
{
    if (pRegistryKey)
    {
        uno::Reference< registry::XRegistryKey > xRegistryKey (
            reinterpret_cast< registry::XRegistryKey*>(pRegistryKey));

        uno::Reference< registry::XRegistryKey > xNewKey;
        xNewKey = xRegistryKey->createKey(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
            FSStorageFactory::impl_staticGetImplementationName() +
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES")));

        const uno::Sequence< ::rtl::OUString > aServices (
            FSStorageFactory::impl_staticGetSupportedServiceNames());
        for( sal_Int32 i = 0; i < aServices.getLength(); i++ )
            xNewKey->createKey( aServices.getConstArray()[i] );

        return sal_True;
    }
    return sal_False;
}

SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory (
    const sal_Char * pImplementationName, void * pServiceManager, void * /* pRegistryKey */)
{
    void * pResult = 0;
    if (pServiceManager)
    {
        uno::Reference< lang::XSingleServiceFactory > xFactory;
        if (FSStorageFactory::impl_staticGetImplementationName().compareToAscii (pImplementationName) == 0)
        {
            xFactory = cppu::createOneInstanceFactory (
                reinterpret_cast< lang::XMultiServiceFactory* >(pServiceManager),
                FSStorageFactory::impl_staticGetImplementationName(),
                FSStorageFactory::impl_staticCreateSelfInstance,
                FSStorageFactory::impl_staticGetSupportedServiceNames() );
        }
        if (xFactory.is())
        {
            xFactory->acquire();
            pResult = xFactory.get();
        }
    }
    return pResult;
}

} // extern "C"

<commit_msg>INTEGRATION: CWS bgdlremove (1.7.186); FILE MERGED 2007/05/18 11:32:07 kso 1.7.186.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fsfactory.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:26:04 $
 *
 *  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_svtools.hxx"

#include "fsfactory.hxx"

#ifndef _CPPUHELPER_FACTORY_HXX_
#include "cppuhelper/factory.hxx"
#endif

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

#include <ucbhelper/fileidentifierconverter.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <ucbhelper/content.hxx>

#include <unotools/tempfile.hxx>
#include <unotools/ucbhelper.hxx>

#include "fsstorage.hxx"

using namespace ::com::sun::star;

//-------------------------------------------------------------------------
// Checks whether it is a file URL that represents a folder
sal_Bool isLocalNotFile_Impl( ::rtl::OUString aURL )
{
    sal_Bool bResult = sal_False;

    ::rtl::OUString aSystemPath;
    ::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get();
    if ( !pBroker )
        throw uno::RuntimeException();

    uno::Reference< ucb::XContentProviderManager > xManager =
            pBroker->getContentProviderManagerInterface();
    try
    {
           aSystemPath = ::ucbhelper::getSystemPathFromFileURL( xManager, aURL );
    }
    catch ( uno::Exception& )
    {
    }

    if ( aSystemPath.getLength() != 0 )
    {
        // it is a local file URL, check that it is not a file
        try
        {
            uno::Reference< ucb::XCommandEnvironment > xDummyEnv;
            ::ucbhelper::Content aContent( aURL, xDummyEnv );
            bResult = aContent.isFolder();
        }
        catch( uno::Exception& )
        {
            bResult = sal_True;
        }
    }

    return bResult;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.FileSystemStorageFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.FileSystemStorageFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL FSStorageFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.FileSystemStorageFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new FSStorageFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstance()
    throw ( uno::Exception,
            uno::RuntimeException )
{
    ::rtl::OUString aTempURL;

    aTempURL = ::utl::TempFile( NULL, sal_True ).GetURL();

    if ( !aTempURL.getLength() )
        throw uno::RuntimeException(); // TODO: can not create tempfile

    ::ucbhelper::Content aResultContent(
        aTempURL, uno::Reference< ucb::XCommandEnvironment >() );

    return uno::Reference< uno::XInterface >(
        static_cast< OWeakObject* >(
            new FSStorage(  aResultContent,
                            embed::ElementModes::READWRITE,
                            uno::Sequence< beans::PropertyValue >(),
                            m_xFactory ) ),
        uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstanceWithArguments(
            const uno::Sequence< uno::Any >& aArguments )
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // The request for storage can be done with up to three arguments

    // The first argument specifies a source for the storage
    // it must be URL.
    // The second value is a mode the storage should be open in.
    // And the third value is a media descriptor.

    sal_Int32 nArgNum = aArguments.getLength();
    OSL_ENSURE( nArgNum < 4, "Wrong parameter number" );

    if ( !nArgNum )
        return createInstance();

    // first try to retrieve storage open mode if any
    // by default the storage will be open in readonly mode
    sal_Int32 nStorageMode = embed::ElementModes::READ;
    if ( nArgNum >= 2 )
    {
        if( !( aArguments[1] >>= nStorageMode ) )
        {
            OSL_ENSURE( sal_False, "Wrong second argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
        // it's allways possible to read written storage in this implementation
        nStorageMode |= embed::ElementModes::READ;
    }

    // retrieve storage source URL
    ::rtl::OUString aURL;

    if ( aArguments[0] >>= aURL )
    {
        if ( !aURL.getLength() )
        {
            OSL_ENSURE( sal_False, "Empty URL is provided!\n" );
            throw uno::Exception(); // TODO: illegal argument
        }
    }
    else
    {
        OSL_ENSURE( sal_False, "Wrong first argument!\n" );
        throw uno::Exception(); // TODO: Illegal argument
    }

    // retrieve mediadescriptor and set storage properties
    uno::Sequence< beans::PropertyValue > aDescr;
    uno::Sequence< beans::PropertyValue > aPropsToSet;

    if ( nArgNum >= 3 )
    {
        if( aArguments[2] >>= aDescr )
        {
            aPropsToSet.realloc(1);
            aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( "URL" );
            aPropsToSet[0].Value <<= aURL;

            for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )
            {
                if ( aDescr[nInd].Name.equalsAscii( "InteractionHandler" ) )
                {
                    aPropsToSet.realloc( ++nNumArgs );
                    aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;
                    aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;
                    break;
                }
                else
                    OSL_ENSURE( sal_False, "Unacceptable property, will be ignored!\n" );
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "Wrong third argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
    }

    // allow to use other ucp's
    // if ( !isLocalNotFile_Impl( aURL ) )
    if ( aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.pkg", 16 )
      || aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.zip", 16 )
      || ::utl::UCBContentHelper::IsDocument( aURL ) )
    {
        OSL_ENSURE( sal_False, "File system storages can be based only on file URLs!\n" ); // ???
        throw uno::Exception(); // TODO: illegal argument
    }

    if ( ( nStorageMode & embed::ElementModes::WRITE ) && !( nStorageMode & embed::ElementModes::NOCREATE ) )
        FSStorage::MakeFolderNoUI( aURL, sal_False );
    else if ( !::utl::UCBContentHelper::IsFolder( aURL ) )
        throw io::IOException(); // there is no such folder

    ::ucbhelper::Content aResultContent(
        aURL, uno::Reference< ucb::XCommandEnvironment >() );

    // create storage based on source
    return uno::Reference< uno::XInterface >(
        static_cast< OWeakObject* >( new FSStorage( aResultContent,
                                                    nStorageMode,
                                                    aPropsToSet,
                                                    m_xFactory ) ),
        uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL FSStorageFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL FSStorageFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

//-------------------------------------------------------------------------

extern "C"
{
SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment (
    const sal_Char ** ppEnvTypeName, uno_Environment ** /* ppEnv */)
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo (
    void * /* pServiceManager */, void * pRegistryKey)
{
    if (pRegistryKey)
    {
        uno::Reference< registry::XRegistryKey > xRegistryKey (
            reinterpret_cast< registry::XRegistryKey*>(pRegistryKey));

        uno::Reference< registry::XRegistryKey > xNewKey;
        xNewKey = xRegistryKey->createKey(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
            FSStorageFactory::impl_staticGetImplementationName() +
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES")));

        const uno::Sequence< ::rtl::OUString > aServices (
            FSStorageFactory::impl_staticGetSupportedServiceNames());
        for( sal_Int32 i = 0; i < aServices.getLength(); i++ )
            xNewKey->createKey( aServices.getConstArray()[i] );

        return sal_True;
    }
    return sal_False;
}

SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory (
    const sal_Char * pImplementationName, void * pServiceManager, void * /* pRegistryKey */)
{
    void * pResult = 0;
    if (pServiceManager)
    {
        uno::Reference< lang::XSingleServiceFactory > xFactory;
        if (FSStorageFactory::impl_staticGetImplementationName().compareToAscii (pImplementationName) == 0)
        {
            xFactory = cppu::createOneInstanceFactory (
                reinterpret_cast< lang::XMultiServiceFactory* >(pServiceManager),
                FSStorageFactory::impl_staticGetImplementationName(),
                FSStorageFactory::impl_staticCreateSelfInstance,
                FSStorageFactory::impl_staticGetSupportedServiceNames() );
        }
        if (xFactory.is())
        {
            xFactory->acquire();
            pResult = xFactory.get();
        }
    }
    return pResult;
}

} // extern "C"

<|endoftext|>