<commit_before>/* OpenSceneGraph example, osgtexture3D.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture3D>
#include <osg/TexGen>
#include <osg/Geode>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgViewer/Viewer>

#include <iostream>

//
// A simple demo demonstrating different texturing modes,
// including using of texture extensions.
//

typedef std::vector< osg::ref_ptr<osg::Image> > ImageList;

osg::StateSet* createState()
{
    // read 4 2d images
    osg::ref_ptr<osg::Image> image_0 = osgDB::readImageFile("Images/lz.rgb");
    osg::ref_ptr<osg::Image> image_1 = osgDB::readImageFile("Images/reflect.rgb");
    osg::ref_ptr<osg::Image> image_2 = osgDB::readImageFile("Images/tank.rgb");
    osg::ref_ptr<osg::Image> image_3 = osgDB::readImageFile("Images/skymap.jpg");

    if (!image_0 || !image_1 || !image_2 || !image_3)
    {
        std::cout << "Warning: could not open files."<<std::endl;
        return new osg::StateSet;
    }

    if (image_0->getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())
    {
        std::cout << "Warning: image pixel formats not compatible."<<std::endl;
        return new osg::StateSet;
    }

    GLint textureSize = 256;

    // scale them all to the same size.
    image_0->scaleImage(textureSize,textureSize,1);
    image_1->scaleImage(textureSize,textureSize,1);
    image_2->scaleImage(textureSize,textureSize,1);
    image_3->scaleImage(textureSize,textureSize,1);

    // then allocated a 3d image to use for texturing.
    osg::Image* image_3d = new osg::Image;
    image_3d->allocateImage(textureSize,textureSize,4,
                            image_0->getPixelFormat(),image_0->getDataType());

    // copy the 2d images into the 3d image.
    image_3d->copySubImage(0,0,0,image_0.get());
    image_3d->copySubImage(0,0,1,image_1.get());
    image_3d->copySubImage(0,0,2,image_2.get());
    image_3d->copySubImage(0,0,3,image_3.get());

    image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());

    // set up the 3d texture itself,
    // note, well set the filtering up so that mip mapping is disabled,
    // gluBuild3DMipsmaps doesn't do a very good job of handled the
    // inbalanced dimensions of the 256x256x4 texture.
    osg::Texture3D* texture3D = new osg::Texture3D;
    texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);
    texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);
    texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);
    texture3D->setImage(image_3d);

    // create a texgen to generate a R texture coordinate, the geometry
    // itself will supply the S & T texture coordinates.
    // in the animateStateSet callback well alter this R value to
    // move the texture through the 3d texture, 3d texture filtering
    // will do the blending for us.
    osg::TexGen* texgen = new osg::TexGen;
    texgen->setMode(osg::TexGen::OBJECT_LINEAR);
    texgen->setPlane(osg::TexGen::R, osg::Plane(0.0f,0.0f,0.0f,0.2f));

    // create the StateSet to store the texture data
    osg::StateSet* stateset = new osg::StateSet;
    stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
    stateset->setTextureAttribute(0,texgen);
    stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);

    return stateset;
}

class UpdateStateCallback : public osg::NodeCallback
{
    public:
        UpdateStateCallback() {}

        void animateState(osg::StateSet* stateset)
        {
            // here we simply get any existing texgen, and then increment its
            // plane, pushing the R coordinate through the texture.
            osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);
            osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(attribute);
            if (texgen)
            {
                texgen->getPlane(osg::TexGen::R)[3] += 0.001f;
            }

        }

        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {

            osg::StateSet* stateset = node->getStateSet();
            if (stateset)
            {
                // we have an exisitng stateset, so lets animate it.
                animateState(stateset);
            }

            // note, callback is repsonsible for scenegraph traversal so
            // should always include call the traverse(node,nv) to ensure
            // that the rest of cullbacks and the scene graph are traversed.
            traverse(node,nv);
        }
};

/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan */
osg::Drawable* createSquare(float textureCoordMax=1.0f)
{
    // set up the Geometry.
    osg::Geometry* geom = new osg::Geometry;

    osg::Vec3Array* coords = new osg::Vec3Array(4);
    (*coords)[0].set(-1.0f,0.0f,1.0f);
    (*coords)[1].set(-1.0f,0.0f,-1.0f);
    (*coords)[2].set(1.0f,0.0f,-1.0f);
    (*coords)[3].set(1.0f,0.0f,1.0f);
    geom->setVertexArray(coords);

    osg::Vec3Array* norms = new osg::Vec3Array(1);
    (*norms)[0].set(0.0f,-1.0f,0.0f);
    geom->setNormalArray(norms, osg::Array::BIND_OVERALL);

    osg::Vec2Array* tcoords = new osg::Vec2Array(4);
    (*tcoords)[0].set(0.0f,textureCoordMax);
    (*tcoords)[1].set(0.0f,0.0f);
    (*tcoords)[2].set(textureCoordMax,0.0f);
    (*tcoords)[3].set(textureCoordMax,textureCoordMax);
    geom->setTexCoordArray(0,tcoords);

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));

    return geom;
}

osg::Node* createModel()
{

    // create the geometry of the model, just a simple 2d quad right now.
    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(createSquare());

    // normally we'd create the stateset's to contain all the textures
    // etc here, but, the above technique uses osg::Image::scaleImage and
    // osg::Image::copySubImage() which are implemented with OpenGL utility
    // library, which unfortunately can't be used until we have a valid
    // OpenGL context, and at this point in initilialization we don't have
    // a valid OpenGL context, so we have to delay creation of state until
    // there is a valid OpenGL context.  I'll manage this by using an
    // app callback which will create the state during the first traversal.
    // A bit hacky, and my plan is to reimplement the osg::scaleImage and
    // osg::Image::copySubImage() without using GLU which will get round
    // this current limitation.
    geode->setUpdateCallback(new UpdateStateCallback());
    geode->setStateSet(createState());

    return geode;

}

int main(int , char **)
{
    // construct the viewer.
    osgViewer::Viewer viewer;

    // create a model from the images and pass it to the viewer.
    viewer.setSceneData(createModel());

    return viewer.run();
}
<commit_msg>Updated the comments to be more relevant<commit_after>/* OpenSceneGraph example, osgtexture3D.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture3D>
#include <osg/TexGen>
#include <osg/Geode>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgViewer/Viewer>

#include <iostream>

//
// A simple demo demonstrating use osg::Texture3D to create a blended animation between four seperate images packed together into a 3d texture
//

typedef std::vector< osg::ref_ptr<osg::Image> > ImageList;

osg::StateSet* createState()
{
    // read 4 2d images
    osg::ref_ptr<osg::Image> image_0 = osgDB::readImageFile("Images/lz.rgb");
    osg::ref_ptr<osg::Image> image_1 = osgDB::readImageFile("Images/reflect.rgb");
    osg::ref_ptr<osg::Image> image_2 = osgDB::readImageFile("Images/tank.rgb");
    osg::ref_ptr<osg::Image> image_3 = osgDB::readImageFile("Images/skymap.jpg");

    if (!image_0 || !image_1 || !image_2 || !image_3)
    {
        std::cout << "Warning: could not open files."<<std::endl;
        return new osg::StateSet;
    }

    if (image_0->getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())
    {
        std::cout << "Warning: image pixel formats not compatible."<<std::endl;
        return new osg::StateSet;
    }

    GLint textureSize = 256;

    // scale them all to the same size.
    image_0->scaleImage(textureSize,textureSize,1);
    image_1->scaleImage(textureSize,textureSize,1);
    image_2->scaleImage(textureSize,textureSize,1);
    image_3->scaleImage(textureSize,textureSize,1);

    // then allocated a 3d image to use for texturing.
    osg::Image* image_3d = new osg::Image;
    image_3d->allocateImage(textureSize,textureSize,4,
                            image_0->getPixelFormat(),image_0->getDataType());

    // copy the 2d images into the 3d image.
    image_3d->copySubImage(0,0,0,image_0.get());
    image_3d->copySubImage(0,0,1,image_1.get());
    image_3d->copySubImage(0,0,2,image_2.get());
    image_3d->copySubImage(0,0,3,image_3.get());

    image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());

    // set up the 3d texture itself,
    // note, well set the filtering up so that mip mapping is disabled,
    // gluBuild3DMipsmaps doesn't do a very good job of handled the
    // inbalanced dimensions of the 256x256x4 texture.
    osg::Texture3D* texture3D = new osg::Texture3D;
    texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);
    texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);
    texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);
    texture3D->setImage(image_3d);

    // create a texgen to generate a R texture coordinate, the geometry
    // itself will supply the S & T texture coordinates.
    // in the animateStateSet callback well alter this R value to
    // move the texture through the 3d texture, 3d texture filtering
    // will do the blending for us.
    osg::TexGen* texgen = new osg::TexGen;
    texgen->setMode(osg::TexGen::OBJECT_LINEAR);
    texgen->setPlane(osg::TexGen::R, osg::Plane(0.0f,0.0f,0.0f,0.2f));

    // create the StateSet to store the texture data
    osg::StateSet* stateset = new osg::StateSet;
    stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
    stateset->setTextureAttribute(0,texgen);
    stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);

    return stateset;
}

class UpdateStateCallback : public osg::NodeCallback
{
    public:
        UpdateStateCallback() {}

        void animateState(osg::StateSet* stateset)
        {
            // here we simply get any existing texgen, and then increment its
            // plane, pushing the R coordinate through the texture.
            osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);
            osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(attribute);
            if (texgen)
            {
                texgen->getPlane(osg::TexGen::R)[3] += 0.001f;
            }

        }

        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {

            osg::StateSet* stateset = node->getStateSet();
            if (stateset)
            {
                // we have an exisitng stateset, so lets animate it.
                animateState(stateset);
            }

            // note, callback is repsonsible for scenegraph traversal so
            // should always include call the traverse(node,nv) to ensure
            // that the rest of cullbacks and the scene graph are traversed.
            traverse(node,nv);
        }
};

/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan */
osg::Drawable* createSquare(float textureCoordMax=1.0f)
{
    // set up the Geometry.
    osg::Geometry* geom = new osg::Geometry;

    osg::Vec3Array* coords = new osg::Vec3Array(4);
    (*coords)[0].set(-1.0f,0.0f,1.0f);
    (*coords)[1].set(-1.0f,0.0f,-1.0f);
    (*coords)[2].set(1.0f,0.0f,-1.0f);
    (*coords)[3].set(1.0f,0.0f,1.0f);
    geom->setVertexArray(coords);

    osg::Vec3Array* norms = new osg::Vec3Array(1);
    (*norms)[0].set(0.0f,-1.0f,0.0f);
    geom->setNormalArray(norms, osg::Array::BIND_OVERALL);

    osg::Vec2Array* tcoords = new osg::Vec2Array(4);
    (*tcoords)[0].set(0.0f,textureCoordMax);
    (*tcoords)[1].set(0.0f,0.0f);
    (*tcoords)[2].set(textureCoordMax,0.0f);
    (*tcoords)[3].set(textureCoordMax,textureCoordMax);
    geom->setTexCoordArray(0,tcoords);

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));

    return geom;
}

osg::Node* createModel()
{
    // create the geometry of the model, just a simple 2d quad right now.
    osg::Geode* geode = new osg::Geode;

    geode->addDrawable(createSquare());

    geode->setUpdateCallback(new UpdateStateCallback());

    geode->setStateSet(createState());

    return geode;
}

int main(int , char **)
{
    // construct the viewer.
    osgViewer::Viewer viewer;

    // create a model from the images and pass it to the viewer.
    viewer.setSceneData(createModel());

    return viewer.run();
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 Neil Moore, Jason Stavrinaky, Micheal McGee, Robert Medina
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "sql/statements/builder.h"

#include "data/data_store.h"

#include <cstdio>

// Helper functions
static DataType getSQLType(std::string* type);

static Expression* createExpression(Token op, Token left, Token right);

void builderStartCreateTable(StatementBuilder* builder, Token table_name)
{
    CreateTableCommand* command = new CreateTableCommand;
    command->table_name = table_name->text;

    builder->started = true;
    builder->statement = command;
    builder->valid = true;
}

void builderStartDropTable(StatementBuilder* builder, Token table_name)
{
    DropTableCommand* command = new DropTableCommand;
    command->table_name = table_name->text;

    builder->started = true;
    builder->statement = command;
    builder->valid = true;
}

void builderAddColumnConstraint(StatementBuilder* builder, SQLConstraintType type,
        Token value)
{
    assert(builder != nullptr);

    SQLConstraint constraint;
    constraint.type = type;

    if(value && value->is_value)
    {
        constraint.value = value->value;
    }

    builder->temp_constraints.push_back(constraint);
}

void builderStartSelectQuery(StatementBuilder* builder)
{
    SelectQuery* query = new (std::nothrow) SelectQuery();
    if(query == nullptr)
    {
        // TODO: Error handling
    }

    builder->started = true;
    builder->statement = query;
    builder->valid = true;
}

void builderStartInsertCommand(StatementBuilder* builder)
{
    InsertCommand* cmd = new (std::nothrow) InsertCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

void builderStartUpdateCommand(StatementBuilder* builder)
{
    UpdateCommand* cmd = new (std::nothrow) UpdateCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

void builderStartDeleteCommand(StatementBuilder* builder)
{
    DeleteCommand* cmd = new (std::nothrow) DeleteCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

// SELECT helper functions ////////////////////////////////////////////////////
void builderAddSelectAllColumns(StatementBuilder* builder, Token table)
{
    // Don't want to override a currently active statement
    if(!builder->started)
    {
        builderStartSelectQuery(builder);
    }

    if(builder->statement == nullptr)
    {
        // TODO: Error handling
    }

    // TODO: Add all columns in the given table to this query
    switch(builder->statement->type)
    {
        case SQLStatement::SELECT:
            break;
        default:
            // TODO: Error handling?
            break;
    }
}

void builderAddQualifiedSelectColumn(StatementBuilder* builder,
                                     Token table, Token source_column,
                                     Token output_column)
{
    // This means the output column should be named the same as the
    // source column
    if(output_column == nullptr)
    {
        output_column = source_column;
    }

    if(!builder->started)
    {
        // Start the SELECT statement then
        builderStartSelectQuery(builder);
    }
    else
    {
        // TODO: Error handling
    }

    ColumnReference source;
    source.table = table->text;

    auto res = builder->data_store->getColumnIndex(source.table, source_column->text);
    if(res.status == ResultStatus::SUCCESS)
    {
        source.column_idx = res.result;
    }
    else
    {
        // TODO: Error handling
        printf("%s: Error encountered while finding column index! Error code = %u\n",
                __FUNCTION__, (uint16_t)res.status);
    }

    SelectQuery* query = reinterpret_cast<SelectQuery*>(builder->statement);

    // Push the previously calculated information into the query object
    query->source_columns.push_back(source);

    query->output_columns.push_back(output_column->text);
}

void builderFinishSelectQuery(StatementBuilder* builder)
{
    if(!builder->started || builder->statement->type != SQLStatement::SELECT)
    {
        return;
    }

    SelectQuery* query = reinterpret_cast<SelectQuery*>(builder->statement);

    // Push all unique tables into the tables vector in the query.
    for(auto col_ref : query->source_columns)
    {
        if(std::find(query->tables.begin(), query->tables.end(), col_ref.table) == query->tables.end())
        {
            query->tables.push_back(col_ref.table);
        }
    }
}

// Insert command helper functions ////////////////////////////////////////////

void builderAddDataItem(StatementBuilder* builder, Token data)
{
    if(data->is_value && builder->started)
    {
        InsertCommand* cmd = reinterpret_cast<InsertCommand*>(builder->statement);

        cmd->data.push_back(data->value);
    }
}

void builderFinishInsertCommand(StatementBuilder* builder)
{
    (void)builder;
}

// Update command helper functions ////////////////////////////////////////////

void builderAddUpdateExpr(StatementBuilder* builder, Token operation,
        Token left, Token right)
{
    if(!builder->started)
    {
        return;
    }

    if(!operation->is_operation ||
        operation->operation != static_cast<uint16_t>(ExpressionOperation::EQUALS))
    {
        printf("Invalid expression for UPDATE statements!\n");
        return;
    }

    UpdateCommand* update = reinterpret_cast<UpdateCommand*>(builder->statement);
    ColumnUpdate update_info;

    SchemaResult schema_res = builder->data_store->getTableSchema(update->table);
    if(schema_res.status != ResultStatus::SUCCESS)
    {
        // TODO: Table doesn't exist
        printf("%s: Unable to retrieve table schema! Handle this TODO!\n", __FUNCTION__);
    }

    update->table_schema = schema_res.result;

    auto column_idx_result = builder->data_store->getColumnIndex(update->table, left->text);
    if(column_idx_result.status == ResultStatus::SUCCESS)
    {
        update_info.column_idx = column_idx_result.result;
    }
    else
    {
        // Column doesn't exist
        // TODO: Error handling
        printf("%s: Unable to find column!\n", __FUNCTION__);
    }

    if(right->is_value)
    {
        update_info.new_data = right->value;
    }
    else
    {
        // Not a value
        // TODO: Error handling
        printf("%s: Invalid type! Handle TODO!\n", __FUNCTION__);
    }

    update->columns.push_back(update_info);
}

void builderFinishUpdateCommand(StatementBuilder* builder)
{
    if(builder->started && builder->valid)
    {
        UpdateCommand* update_cmd = reinterpret_cast<UpdateCommand*>(builder->statement);

        if(update_cmd->table_schema.columns.size() == 0)
        {
            // Attempt to get the table schema one more time
            SchemaResult schema_check = builder->data_store->getTableSchema(update_cmd->table);
            if(schema_check.status != ResultStatus::SUCCESS)
            {
                update_cmd->runnable = false;
                // No point going any further
                return;
            }
            else
            {
                update_cmd->table_schema = schema_check.result;
            }
        }

        TervelData null_data = { .value = 0 };
        null_data.data.null = 1;

        update_cmd->full_record.resize(update_cmd->table_schema.columns.size(), null_data);
        for(auto updated_col : update_cmd->columns)
        {
            update_cmd->full_record[updated_col.column_idx] = updated_col.new_data;
        }

        update_cmd->runnable = true;
    }
}

// Generic-ish helper functions ///////////////////////////////////////////////

void builderAddColumn(StatementBuilder* builder, Token column_name,
                      Token column_type, Token column_constraints)
{
    (void)column_constraints;

    //printf("Entered builderAddColumn\n");

    if(!builder->started)
    {
        printf("Builder not started, but attempting to add column?!\n");
    }

    switch(builder->statement->type)
    {
        case SQLStatement::CREATE_TABLE:
        {
            CreateTableCommand* cmd = (CreateTableCommand*)builder->statement;
            SQLColumn column;
            column.name = column_name->text;
            column.type = getSQLType(&column_type->text);

            std::swap(column.constraint, builder->temp_constraints);
            builder->temp_constraints.clear();

            cmd->columns.push_back(column);
        }
        break;
        case SQLStatement::SELECT:
        case SQLStatement::INVALID:
        default:
        {
            printf("%s: SQL statement type isn't supported in this function!\n", __FUNCTION__);
        }
        break;
    }
}

void builderAddTableName(StatementBuilder* builder, Token table_name)
{
    if(!builder->started)
    {
        printf("%s: Builder hasn't been started!\n", __FUNCTION__);
        return;
    }

    switch(builder->statement->type)
    {
        case SQLStatement::INSERT_INTO:
            {
                InsertCommand* insert = reinterpret_cast<InsertCommand*>(builder->statement);
                insert->table = table_name->text;
            }
            break;
        case SQLStatement::UPDATE:
            {
                UpdateCommand* update = reinterpret_cast<UpdateCommand*>(builder->statement);
                update->table = table_name->text;

                // Grab the table schema
                SchemaResult schema_check = builder->data_store->getTableSchema(update->table);
                if(schema_check.status == ResultStatus::SUCCESS)
                {
                    update->table_schema = schema_check.result;
                }
                else
                {
                    // TODO: Handle error here?
                }
            }
            break;
        case SQLStatement::DELETE:
            {
                DeleteCommand* del = reinterpret_cast<DeleteCommand*>(builder->statement);
                del->table = table_name->text;
            }
            break;
        default:
            printf("%s: SQL statement being built isn't supported!\n", __FUNCTION__);
            break;
    }
}

void builderStartNestedExpr(StatementBuilder* builder, Token operation)
{
    if(builder == nullptr)
    {
        printf("This shouldn't happen\n");
        // TODO: Assert?
	    return;
    }

    printf("Starting nested expression: [%s]\n", operation->text.c_str());

    if(isExprFlagContained(builder->expr->flags, ExpressionFlags::NESTED))
    {
        builder->expr->op = static_cast<ExpressionOperation>(operation->operation);
        printf("Nested operation = %u\n", (uint32_t)builder->expr->op);
        builder->expr->flags = ExpressionFlags::NESTED;
    }

    printExpressionTree(builder->expr);
}

void builderAddValueExpr(StatementBuilder* builder,
	Token operation, Token left_term, Token right_term)
{
    // printf("Adding value expression: %s %s %s\n",
    //         left_term->text.c_str(),
    //         operation->text.c_str(),
    //         right_term->text.c_str());

    if(builder->expr == nullptr)
    {
        builder->expr = createExpression(operation, left_term, right_term);
        if(builder->expr == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }
    }
    else
    {
        // printf("Non-null builder->expr\n");
        // Create nested expression and set the previous to the left child
        Expression* right = createExpression(operation, left_term, right_term);
        if(right == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }

        Expression* parent = new (std::nothrow) Expression();
        if(parent == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }

        parent->flags = ExpressionFlags::NESTED | ExpressionFlags::EMPTY;
        parent->left = builder->expr;
        parent->right = right;

        builder->expr = parent;
    }

    // printExpressionTree(builder->expr);
}

Expression* createExpression(Token op, Token left, Token right)
{
    Expression* parent = new (std::nothrow) Expression(op);
    if(parent)
    {
        Expression* left_expr = new (std::nothrow) Expression(left);
        if(left_expr)
        {
            parent->left = left_expr;
        }
        else
        {
            delete parent;
            return nullptr;
        }

        Expression* right_expr = new (std::nothrow) Expression(right);
        if(right_expr)
        {
            parent->right = right_expr;
        }
        else
        {
            delete parent;
            return nullptr;
        }
    }
    else
    {
        return nullptr;
    }

    return parent;
}

void builderClean(StatementBuilder* builder)
{
    // DEBUG
    printf("builderClean called\n");

    if(builder->started)
    {
        delete builder->statement;
    }

    builder->statement = nullptr;

    builder->started = false;
}

DataType getSQLType(std::string* type)
{
    if(type == nullptr)
    {
        printf("Null pointer in getSQLType, check your parser.\n");
        return DataType::NONE;
    }

    if((*type) == "INTEGER")
    {
        return DataType::INTEGER;
    }

    if((*type) == "SMALLINT")
    {
        return DataType::SMALL_INT;
    }

    if((*type) == "BIGINT")
    {
        return DataType::BIG_INT;
    }

    if((*type) == "BOOLEAN")
    {
        return DataType::BOOLEAN;
    }

    if((*type) == "DATE")
    {
        return DataType::DATE;
    }

    if((*type) == "TIME")
    {
        return DataType::TIME;
    }

    return DataType::NONE;
}
<commit_msg>Added ability to perform full table SELECT queries<commit_after>/* Copyright (c) 2016 Neil Moore, Jason Stavrinaky, Micheal McGee, Robert Medina
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "sql/statements/builder.h"

#include "data/data_store.h"

#include <cstdio>

// Helper functions
static DataType getSQLType(std::string* type);

static Expression* createExpression(Token op, Token left, Token right);

void builderStartCreateTable(StatementBuilder* builder, Token table_name)
{
    CreateTableCommand* command = new CreateTableCommand;
    command->table_name = table_name->text;

    builder->started = true;
    builder->statement = command;
    builder->valid = true;
}

void builderStartDropTable(StatementBuilder* builder, Token table_name)
{
    DropTableCommand* command = new DropTableCommand;
    command->table_name = table_name->text;

    builder->started = true;
    builder->statement = command;
    builder->valid = true;
}

void builderAddColumnConstraint(StatementBuilder* builder, SQLConstraintType type,
        Token value)
{
    assert(builder != nullptr);

    SQLConstraint constraint;
    constraint.type = type;

    if(value && value->is_value)
    {
        constraint.value = value->value;
    }

    builder->temp_constraints.push_back(constraint);
}

void builderStartSelectQuery(StatementBuilder* builder)
{
    SelectQuery* query = new (std::nothrow) SelectQuery();
    if(query == nullptr)
    {
        // TODO: Error handling
    }

    builder->started = true;
    builder->statement = query;
    builder->valid = true;
}

void builderStartInsertCommand(StatementBuilder* builder)
{
    InsertCommand* cmd = new (std::nothrow) InsertCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

void builderStartUpdateCommand(StatementBuilder* builder)
{
    UpdateCommand* cmd = new (std::nothrow) UpdateCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

void builderStartDeleteCommand(StatementBuilder* builder)
{
    DeleteCommand* cmd = new (std::nothrow) DeleteCommand();
    // TODO: Error handling

    builder->started = true;
    builder->statement = cmd;
    builder->valid = true;
}

// SELECT helper functions ////////////////////////////////////////////////////
void builderAddSelectAllColumns(StatementBuilder* builder, Token table)
{
    // Don't want to override a currently active statement
    if(!builder->started)
    {
        builderStartSelectQuery(builder);
    }

    if(builder->statement == nullptr)
    {
        // TODO: Error handling
    }

    switch(builder->statement->type)
    {
        case SQLStatement::SELECT:
            {
                SelectQuery* query = reinterpret_cast<SelectQuery*>(builder->statement);
                SchemaResult schema = builder->data_store->getTableSchema(table->text);
                if(schema.status != ResultStatus::SUCCESS)
                {
                    printf("Error retrieving schema for table \"%s\"\n", table->text.c_str());
                }

                size_t num_columns = schema.result.columns.size();
                for(size_t i = 0; i < num_columns; i++)
                {
                    ColumnReference col;
                    col.column_idx = i;
                    col.table = table->text;
                    query->source_columns.push_back(col);
                    query->output_columns.push_back(schema.result.columns[i].name);
                }
            }
            break;
        default:
            // TODO: Error handling?
            break;
    }
}

void builderAddQualifiedSelectColumn(StatementBuilder* builder,
                                     Token table, Token source_column,
                                     Token output_column)
{
    // This means the output column should be named the same as the
    // source column
    if(output_column == nullptr)
    {
        output_column = source_column;
    }

    if(!builder->started)
    {
        // Start the SELECT statement then
        builderStartSelectQuery(builder);
    }
    else
    {
        // TODO: Error handling
    }

    ColumnReference source;
    source.table = table->text;

    auto res = builder->data_store->getColumnIndex(source.table, source_column->text);
    if(res.status == ResultStatus::SUCCESS)
    {
        source.column_idx = res.result;
    }
    else
    {
        // TODO: Error handling
        printf("%s: Error encountered while finding column index! Error code = %u\n",
                __FUNCTION__, (uint16_t)res.status);
    }

    SelectQuery* query = reinterpret_cast<SelectQuery*>(builder->statement);

    // Push the previously calculated information into the query object
    query->source_columns.push_back(source);

    query->output_columns.push_back(output_column->text);
}

void builderFinishSelectQuery(StatementBuilder* builder)
{
    if(!builder->started || builder->statement->type != SQLStatement::SELECT)
    {
        return;
    }

    SelectQuery* query = reinterpret_cast<SelectQuery*>(builder->statement);

    // Push all unique tables into the tables vector in the query.
    for(auto col_ref : query->source_columns)
    {
        if(std::find(query->tables.begin(), query->tables.end(), col_ref.table) == query->tables.end())
        {
            query->tables.push_back(col_ref.table);
        }
    }
}

// Insert command helper functions ////////////////////////////////////////////

void builderAddDataItem(StatementBuilder* builder, Token data)
{
    if(data->is_value && builder->started)
    {
        InsertCommand* cmd = reinterpret_cast<InsertCommand*>(builder->statement);

        cmd->data.push_back(data->value);
    }
}

void builderFinishInsertCommand(StatementBuilder* builder)
{
    (void)builder;
}

// Update command helper functions ////////////////////////////////////////////

void builderAddUpdateExpr(StatementBuilder* builder, Token operation,
        Token left, Token right)
{
    if(!builder->started)
    {
        return;
    }

    if(!operation->is_operation ||
        operation->operation != static_cast<uint16_t>(ExpressionOperation::EQUALS))
    {
        printf("Invalid expression for UPDATE statements!\n");
        return;
    }

    UpdateCommand* update = reinterpret_cast<UpdateCommand*>(builder->statement);
    ColumnUpdate update_info;

    SchemaResult schema_res = builder->data_store->getTableSchema(update->table);
    if(schema_res.status != ResultStatus::SUCCESS)
    {
        // TODO: Table doesn't exist
        printf("%s: Unable to retrieve table schema! Handle this TODO!\n", __FUNCTION__);
    }

    update->table_schema = schema_res.result;

    auto column_idx_result = builder->data_store->getColumnIndex(update->table, left->text);
    if(column_idx_result.status == ResultStatus::SUCCESS)
    {
        update_info.column_idx = column_idx_result.result;
    }
    else
    {
        // Column doesn't exist
        // TODO: Error handling
        printf("%s: Unable to find column!\n", __FUNCTION__);
    }

    if(right->is_value)
    {
        update_info.new_data = right->value;
    }
    else
    {
        // Not a value
        // TODO: Error handling
        printf("%s: Invalid type! Handle TODO!\n", __FUNCTION__);
    }

    update->columns.push_back(update_info);
}

void builderFinishUpdateCommand(StatementBuilder* builder)
{
    if(builder->started && builder->valid)
    {
        UpdateCommand* update_cmd = reinterpret_cast<UpdateCommand*>(builder->statement);

        if(update_cmd->table_schema.columns.size() == 0)
        {
            // Attempt to get the table schema one more time
            SchemaResult schema_check = builder->data_store->getTableSchema(update_cmd->table);
            if(schema_check.status != ResultStatus::SUCCESS)
            {
                update_cmd->runnable = false;
                // No point going any further
                return;
            }
            else
            {
                update_cmd->table_schema = schema_check.result;
            }
        }

        TervelData null_data = { .value = 0 };
        null_data.data.null = 1;

        update_cmd->full_record.resize(update_cmd->table_schema.columns.size(), null_data);
        for(auto updated_col : update_cmd->columns)
        {
            update_cmd->full_record[updated_col.column_idx] = updated_col.new_data;
        }

        update_cmd->runnable = true;
    }
}

// Generic-ish helper functions ///////////////////////////////////////////////

void builderAddColumn(StatementBuilder* builder, Token column_name,
                      Token column_type, Token column_constraints)
{
    (void)column_constraints;

    //printf("Entered builderAddColumn\n");

    if(!builder->started)
    {
        printf("Builder not started, but attempting to add column?!\n");
    }

    switch(builder->statement->type)
    {
        case SQLStatement::CREATE_TABLE:
        {
            CreateTableCommand* cmd = (CreateTableCommand*)builder->statement;
            SQLColumn column;
            column.name = column_name->text;
            column.type = getSQLType(&column_type->text);

            std::swap(column.constraint, builder->temp_constraints);
            builder->temp_constraints.clear();

            cmd->columns.push_back(column);
        }
        break;
        case SQLStatement::SELECT:
        case SQLStatement::INVALID:
        default:
        {
            printf("%s: SQL statement type isn't supported in this function!\n", __FUNCTION__);
        }
        break;
    }
}

void builderAddTableName(StatementBuilder* builder, Token table_name)
{
    if(!builder->started)
    {
        printf("%s: Builder hasn't been started!\n", __FUNCTION__);
        return;
    }

    switch(builder->statement->type)
    {
        case SQLStatement::INSERT_INTO:
            {
                InsertCommand* insert = reinterpret_cast<InsertCommand*>(builder->statement);
                insert->table = table_name->text;
            }
            break;
        case SQLStatement::UPDATE:
            {
                UpdateCommand* update = reinterpret_cast<UpdateCommand*>(builder->statement);
                update->table = table_name->text;

                // Grab the table schema
                SchemaResult schema_check = builder->data_store->getTableSchema(update->table);
                if(schema_check.status == ResultStatus::SUCCESS)
                {
                    update->table_schema = schema_check.result;
                }
                else
                {
                    // TODO: Handle error here?
                }
            }
            break;
        case SQLStatement::DELETE:
            {
                DeleteCommand* del = reinterpret_cast<DeleteCommand*>(builder->statement);
                del->table = table_name->text;
            }
            break;
        default:
            printf("%s: SQL statement being built isn't supported!\n", __FUNCTION__);
            break;
    }
}

void builderStartNestedExpr(StatementBuilder* builder, Token operation)
{
    if(builder == nullptr)
    {
        printf("This shouldn't happen\n");
        // TODO: Assert?
	    return;
    }

    printf("Starting nested expression: [%s]\n", operation->text.c_str());

    if(isExprFlagContained(builder->expr->flags, ExpressionFlags::NESTED))
    {
        builder->expr->op = static_cast<ExpressionOperation>(operation->operation);
        printf("Nested operation = %u\n", (uint32_t)builder->expr->op);
        builder->expr->flags = ExpressionFlags::NESTED;
    }

    printExpressionTree(builder->expr);
}

void builderAddValueExpr(StatementBuilder* builder,
	Token operation, Token left_term, Token right_term)
{
    // printf("Adding value expression: %s %s %s\n",
    //         left_term->text.c_str(),
    //         operation->text.c_str(),
    //         right_term->text.c_str());

    if(builder->expr == nullptr)
    {
        builder->expr = createExpression(operation, left_term, right_term);
        if(builder->expr == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }
    }
    else
    {
        // printf("Non-null builder->expr\n");
        // Create nested expression and set the previous to the left child
        Expression* right = createExpression(operation, left_term, right_term);
        if(right == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }

        Expression* parent = new (std::nothrow) Expression();
        if(parent == nullptr)
        {
            printf("Fatal error, unable to generate value expression\n");
            return;
        }

        parent->flags = ExpressionFlags::NESTED | ExpressionFlags::EMPTY;
        parent->left = builder->expr;
        parent->right = right;

        builder->expr = parent;
    }

    // printExpressionTree(builder->expr);
}

Expression* createExpression(Token op, Token left, Token right)
{
    Expression* parent = new (std::nothrow) Expression(op);
    if(parent)
    {
        Expression* left_expr = new (std::nothrow) Expression(left);
        if(left_expr)
        {
            parent->left = left_expr;
        }
        else
        {
            delete parent;
            return nullptr;
        }

        Expression* right_expr = new (std::nothrow) Expression(right);
        if(right_expr)
        {
            parent->right = right_expr;
        }
        else
        {
            delete parent;
            return nullptr;
        }
    }
    else
    {
        return nullptr;
    }

    return parent;
}

void builderClean(StatementBuilder* builder)
{
    // DEBUG
    printf("builderClean called\n");

    if(builder->started)
    {
        delete builder->statement;
    }

    builder->statement = nullptr;

    builder->started = false;
}

DataType getSQLType(std::string* type)
{
    if(type == nullptr)
    {
        printf("Null pointer in getSQLType, check your parser.\n");
        return DataType::NONE;
    }

    if((*type) == "INTEGER")
    {
        return DataType::INTEGER;
    }

    if((*type) == "SMALLINT")
    {
        return DataType::SMALL_INT;
    }

    if((*type) == "BIGINT")
    {
        return DataType::BIG_INT;
    }

    if((*type) == "BOOLEAN")
    {
        return DataType::BOOLEAN;
    }

    if((*type) == "DATE")
    {
        return DataType::DATE;
    }

    if((*type) == "TIME")
    {
        return DataType::TIME;
    }

    return DataType::NONE;
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "workerthread.h"

// appleseed.foundation headers.
#include "foundation/platform/snprintf.h"
#include "foundation/platform/types.h"
#include "foundation/utility/job/ijob.h"
#include "foundation/utility/job/jobmanager.h"
#include "foundation/utility/job/jobqueue.h"
#include "foundation/utility/log.h"

// Standard headers.
#include <exception>

using namespace boost;
using namespace std;

namespace foundation
{

//
// WorkerThread class implementation.
//

WorkerThread::WorkerThread(
    const size_t    index,
    Logger&         logger,
    JobQueue&       job_queue,
    const int       flags)
  : m_index(index)
  , m_logger(logger)
  , m_job_queue(job_queue)
  , m_flags(flags)
  , m_thread_func(*this)
  , m_thread(0)
{
}

WorkerThread::~WorkerThread()
{
    stop();
}

void WorkerThread::start()
{
    // Don't do anything if the worker thread is already running.
    if (m_thread)
        return;

    assert(m_pause_flag.is_clear());
    assert(!m_abort_switch.is_aborted());

    // Start the thread.
    m_thread = new thread(m_thread_func);
}

void WorkerThread::stop()
{
    // Don't do anything if the worker thread is already stopped.
    if (!m_thread)
        return;

    // Resume the thread if it was paused.
    m_pause_flag.clear();
    m_pause_event.notify_all();

    // Ask the thread to stop, and wait until it has.
    m_abort_switch.abort();
    m_job_queue.signal_event();
    m_thread->join();
    m_abort_switch.clear();

    // Delete the thread object.
    delete m_thread;
    m_thread = 0;
}

void WorkerThread::pause()
{
    // Don't do anything if the worker thread is not running.
    if (!m_thread)
        return;

    mutex::scoped_lock lock(m_pause_mutex);
    m_pause_flag.set();
}

void WorkerThread::resume()
{
    // Don't do anything if the worker thread is not running.
    if (!m_thread)
        return;

    mutex::scoped_lock lock(m_pause_mutex);
    m_pause_flag.clear();
    m_pause_event.notify_all();
}

void WorkerThread::set_thread_name()
{
    char thread_name[16];
    portable_snprintf(thread_name, sizeof(thread_name), "worker_%03u", m_index);
    set_current_thread_name(thread_name);
}

void WorkerThread::run()
{
    set_thread_name();

    while (!m_abort_switch.is_aborted())
    {
        if (m_pause_flag.is_set())
        {
            // Wait until the resume event.
            mutex::scoped_lock lock(m_pause_mutex);
            while (m_pause_flag.is_set())
                m_pause_event.wait(lock);
        }

        // Acquire a job.
        const JobQueue::RunningJobInfo running_job_info =
            m_job_queue.wait_for_scheduled_job(m_abort_switch);

        // Handle the case where the job queue is empty.
        if (running_job_info.first.m_job == 0)
        {
            if (m_flags & JobManager::KeepRunningOnEmptyQueue)
            {
                // Keep the thread running and waiting for new jobs.
                continue;
            }
            else
            {
                // Terminate the thread.
                break;
            }
        }

        // Execute the job.
        const bool success = execute_job(*running_job_info.first.m_job);

        // Retire the job.
        m_job_queue.retire_running_job(running_job_info);

        // Handle job execution failures.
        if (!success && !(m_flags & JobManager::KeepRunningOnJobFailure))
        {
            m_job_queue.clear_scheduled_jobs();
            break;
        }
    }
}

bool WorkerThread::execute_job(IJob& job)
{
    try
    {
        job.execute(m_index);
    }
    catch (const bad_alloc&)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (ran out of memory).",
            m_index);

        return false;
    }
#ifdef NDEBUG
    catch (const std::exception& e)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (%s).",
            m_index,
            e.what());

        return false;
    }
    catch (...)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (unknown exception).",
            m_index);

        return false;
    }
#endif

    return true;
}

}   // namespace foundation
<commit_msg>Fixed WorkerThread::set_thread_name() for OSX 10.7.5 (GCC 4.2.1).<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "workerthread.h"

// appleseed.foundation headers.
#include "foundation/platform/snprintf.h"
#include "foundation/platform/types.h"
#include "foundation/utility/job/ijob.h"
#include "foundation/utility/job/jobmanager.h"
#include "foundation/utility/job/jobqueue.h"
#include "foundation/utility/log.h"

// Standard headers.
#include <exception>

using namespace boost;
using namespace std;

namespace foundation
{

//
// WorkerThread class implementation.
//

WorkerThread::WorkerThread(
    const size_t    index,
    Logger&         logger,
    JobQueue&       job_queue,
    const int       flags)
  : m_index(index)
  , m_logger(logger)
  , m_job_queue(job_queue)
  , m_flags(flags)
  , m_thread_func(*this)
  , m_thread(0)
{
}

WorkerThread::~WorkerThread()
{
    stop();
}

void WorkerThread::start()
{
    // Don't do anything if the worker thread is already running.
    if (m_thread)
        return;

    assert(m_pause_flag.is_clear());
    assert(!m_abort_switch.is_aborted());

    // Start the thread.
    m_thread = new thread(m_thread_func);
}

void WorkerThread::stop()
{
    // Don't do anything if the worker thread is already stopped.
    if (!m_thread)
        return;

    // Resume the thread if it was paused.
    m_pause_flag.clear();
    m_pause_event.notify_all();

    // Ask the thread to stop, and wait until it has.
    m_abort_switch.abort();
    m_job_queue.signal_event();
    m_thread->join();
    m_abort_switch.clear();

    // Delete the thread object.
    delete m_thread;
    m_thread = 0;
}

void WorkerThread::pause()
{
    // Don't do anything if the worker thread is not running.
    if (!m_thread)
        return;

    mutex::scoped_lock lock(m_pause_mutex);
    m_pause_flag.set();
}

void WorkerThread::resume()
{
    // Don't do anything if the worker thread is not running.
    if (!m_thread)
        return;

    mutex::scoped_lock lock(m_pause_mutex);
    m_pause_flag.clear();
    m_pause_event.notify_all();
}

void WorkerThread::set_thread_name()
{
    char thread_name[16];
    portable_snprintf(thread_name, sizeof(thread_name), "worker_%03lu", (long unsigned int)m_index);
    set_current_thread_name(thread_name);
}

void WorkerThread::run()
{
    set_thread_name();

    while (!m_abort_switch.is_aborted())
    {
        if (m_pause_flag.is_set())
        {
            // Wait until the resume event.
            mutex::scoped_lock lock(m_pause_mutex);
            while (m_pause_flag.is_set())
                m_pause_event.wait(lock);
        }

        // Acquire a job.
        const JobQueue::RunningJobInfo running_job_info =
            m_job_queue.wait_for_scheduled_job(m_abort_switch);

        // Handle the case where the job queue is empty.
        if (running_job_info.first.m_job == 0)
        {
            if (m_flags & JobManager::KeepRunningOnEmptyQueue)
            {
                // Keep the thread running and waiting for new jobs.
                continue;
            }
            else
            {
                // Terminate the thread.
                break;
            }
        }

        // Execute the job.
        const bool success = execute_job(*running_job_info.first.m_job);

        // Retire the job.
        m_job_queue.retire_running_job(running_job_info);

        // Handle job execution failures.
        if (!success && !(m_flags & JobManager::KeepRunningOnJobFailure))
        {
            m_job_queue.clear_scheduled_jobs();
            break;
        }
    }
}

bool WorkerThread::execute_job(IJob& job)
{
    try
    {
        job.execute(m_index);
    }
    catch (const bad_alloc&)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (ran out of memory).",
            m_index);

        return false;
    }
#ifdef NDEBUG
    catch (const std::exception& e)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (%s).",
            m_index,
            e.what());

        return false;
    }
    catch (...)
    {
        LOG_ERROR(
            m_logger,
            "worker thread " FMT_SIZE_T ": job was terminated (unknown exception).",
            m_index);

        return false;
    }
#endif

    return true;
}

}   // namespace foundation
<|endoftext|>


<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/eval/eval/simple_value.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/eval/tensor/cell_values.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/partial_update.h>
#include <vespa/eval/tensor/sparse/sparse_tensor.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <optional>

using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;

using vespalib::make_string_short::fmt;

std::vector<Layout> add_layouts = {
    {x({"a"})},                           {x({"b"})},
    {x({"a","b"})},                       {x({"a","c"})},
    float_cells({x({"a","b"})}),          {x({"a","c"})},
    {x({"a","b"})},                       float_cells({x({"a","c"})}),
    float_cells({x({"a","b"})}),          float_cells({x({"a","c"})}),
    {x({"a","b","c"}),y({"d","e"})},      {x({"b","f"}),y({"d","g"})},
    {x(3),y({"a","b"})},                  {x(3),y({"b","c"})}
};

TensorSpec reference_add(const TensorSpec &a, const TensorSpec &b) {
    TensorSpec result(a.type());
    for (const auto &cell: b.cells()) {
        result.add(cell.first, cell.second);
    }
    auto end_iter = b.cells().end();
    for (const auto &cell: a.cells()) {
        auto iter = b.cells().find(cell.first);
        if (iter == end_iter) {
            result.add(cell.first, cell.second);
        }
    }
    return result;
}

TensorSpec perform_partial_add(const TensorSpec &a, const TensorSpec &b) {
    const auto &factory = SimpleValueBuilderFactory::get();
    auto lhs = value_from_spec(a, factory);
    auto rhs = value_from_spec(b, factory);
    auto up = tensor::TensorPartialUpdate::add(*lhs, *rhs, factory);
    if (up) {
        return spec_from_value(*up);
    } else {
        return TensorSpec(a.type());
    }
}

TensorSpec perform_old_add(const TensorSpec &a, const TensorSpec &b) {
    const auto &engine = tensor::DefaultTensorEngine::ref();
    auto lhs = engine.from_spec(a);
    auto rhs = engine.from_spec(b);
    auto lhs_tensor = dynamic_cast<tensor::Tensor *>(lhs.get());
    EXPECT_TRUE(lhs_tensor);
    auto rhs_tensor = dynamic_cast<tensor::Tensor *>(rhs.get());
    EXPECT_TRUE(rhs_tensor);
    auto up = lhs_tensor->add(*rhs_tensor);
    EXPECT_TRUE(up);
    return engine.to_spec(*up);
}

TEST(PartialAddTest, partial_add_works_for_simple_values) {
    ASSERT_TRUE((add_layouts.size() % 2) == 0);
    for (size_t i = 0; i < add_layouts.size(); i += 2) {
        TensorSpec lhs = spec(add_layouts[i], N());
        TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));
        SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str()));
        auto expect = reference_add(lhs, rhs);
        auto actual = perform_partial_add(lhs, rhs);
        EXPECT_EQ(actual, expect);
    }
}

TEST(PartialAddTest, partial_add_works_like_old_add) {
    ASSERT_TRUE((add_layouts.size() % 2) == 0);
    for (size_t i = 0; i < add_layouts.size(); i += 2) {
        TensorSpec lhs = spec(add_layouts[i], N());
        TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));
        SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str()));
        auto expect = perform_old_add(lhs, rhs);
        auto actual = perform_partial_add(lhs, rhs);
        EXPECT_EQ(actual, expect);
        printf("%s add %s -> %s\n", lhs.to_string().c_str(), rhs.to_string().c_str(), actual.to_string().c_str());

    }
}

GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>add PartialAdd unit test for bad input<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/eval/eval/simple_value.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/eval/tensor/cell_values.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/partial_update.h>
#include <vespa/eval/tensor/sparse/sparse_tensor.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <optional>

using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;

using vespalib::make_string_short::fmt;

std::vector<Layout> add_layouts = {
    {x({"a"})},                           {x({"b"})},
    {x({"a","b"})},                       {x({"a","c"})},
    float_cells({x({"a","b"})}),          {x({"a","c"})},
    {x({"a","b"})},                       float_cells({x({"a","c"})}),
    float_cells({x({"a","b"})}),          float_cells({x({"a","c"})}),
    {x({"a","b","c"}),y({"d","e"})},      {x({"b","f"}),y({"d","g"})},
    {x(3),y({"a","b"})},                  {x(3),y({"b","c"})}
};

TensorSpec reference_add(const TensorSpec &a, const TensorSpec &b) {
    TensorSpec result(a.type());
    for (const auto &cell: b.cells()) {
        result.add(cell.first, cell.second);
    }
    auto end_iter = b.cells().end();
    for (const auto &cell: a.cells()) {
        auto iter = b.cells().find(cell.first);
        if (iter == end_iter) {
            result.add(cell.first, cell.second);
        }
    }
    return result;
}

Value::UP try_partial_add(const TensorSpec &a, const TensorSpec &b) {
    const auto &factory = SimpleValueBuilderFactory::get();
    auto lhs = value_from_spec(a, factory);
    auto rhs = value_from_spec(b, factory);
    return tensor::TensorPartialUpdate::add(*lhs, *rhs, factory);
}

TensorSpec perform_partial_add(const TensorSpec &a, const TensorSpec &b) {
    auto up = try_partial_add(a, b);
    EXPECT_TRUE(up);
    if (up) {
        return spec_from_value(*up);
    } else {
        return TensorSpec(a.type());
    }
}

TensorSpec perform_old_add(const TensorSpec &a, const TensorSpec &b) {
    const auto &engine = tensor::DefaultTensorEngine::ref();
    auto lhs = engine.from_spec(a);
    auto rhs = engine.from_spec(b);
    auto lhs_tensor = dynamic_cast<tensor::Tensor *>(lhs.get());
    EXPECT_TRUE(lhs_tensor);
    auto rhs_tensor = dynamic_cast<tensor::Tensor *>(rhs.get());
    EXPECT_TRUE(rhs_tensor);
    auto up = lhs_tensor->add(*rhs_tensor);
    EXPECT_TRUE(up);
    return engine.to_spec(*up);
}

TEST(PartialAddTest, partial_add_works_for_simple_values) {
    ASSERT_TRUE((add_layouts.size() % 2) == 0);
    for (size_t i = 0; i < add_layouts.size(); i += 2) {
        TensorSpec lhs = spec(add_layouts[i], N());
        TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));
        SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str()));
        auto expect = reference_add(lhs, rhs);
        auto actual = perform_partial_add(lhs, rhs);
        EXPECT_EQ(actual, expect);
    }
}

TEST(PartialAddTest, partial_add_works_like_old_add) {
    ASSERT_TRUE((add_layouts.size() % 2) == 0);
    for (size_t i = 0; i < add_layouts.size(); i += 2) {
        TensorSpec lhs = spec(add_layouts[i], N());
        TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));
        SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str()));
        auto expect = perform_old_add(lhs, rhs);
        auto actual = perform_partial_add(lhs, rhs);
        EXPECT_EQ(actual, expect);
    }
}

std::vector<Layout> bad_layouts = {
    {x(3)},                               {x(3),y(1)},
    {x(3),y(1)},                          {x(3)},
    {x(3),y(3)},                          {x(3),y({"a"})},
    {x(3),y({"a"})},                      {x(3),y(3)},
    {x({"a"})},                           {x({"a"}),y({"b"})},
    {x({"a"}),y({"b"})},                  {x({"a"})},
    {x({"a"})},                           {x({"a"}),y(1)}
};

TEST(PartialAddTest, partial_add_returns_nullptr_on_invalid_inputs) {
    ASSERT_TRUE((bad_layouts.size() % 2) == 0);
    for (size_t i = 0; i < bad_layouts.size(); i += 2) {
        TensorSpec lhs = spec(bad_layouts[i], N());
        TensorSpec rhs = spec(bad_layouts[i + 1], Div16(N()));
        SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str()));
        auto actual = try_partial_add(lhs, rhs);
        auto expect = Value::UP();
        EXPECT_EQ(actual, expect);
    }
}

GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|>


<commit_before>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "Player/Player.h"
#include "Common/config.h"
#include "PlayerProxy.h"
#include "Util/mini.h"
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Thread/AsyncTaskThread.h"

using namespace toolkit;

namespace mediakit {

static uint8_t s_mute_adts[] = {0xff, 0xf1, 0x6c, 0x40, 0x2d, 0x3f, 0xfc, 0x00, 0xe0, 0x34, 0x20, 0xad, 0xf2, 0x3f, 0xb5, 0xdd,
                                0x73, 0xac, 0xbd, 0xca, 0xd7, 0x7d, 0x4a, 0x13, 0x2d, 0x2e, 0xa2, 0x62, 0x02, 0x70, 0x3c, 0x1c,
                                0xc5, 0x63, 0x55, 0x69, 0x94, 0xb5, 0x8d, 0x70, 0xd7, 0x24, 0x6a, 0x9e, 0x2e, 0x86, 0x24, 0xea,
                                0x4f, 0xd4, 0xf8, 0x10, 0x53, 0xa5, 0x4a, 0xb2, 0x9a, 0xf0, 0xa1, 0x4f, 0x2f, 0x66, 0xf9, 0xd3,
                                0x8c, 0xa6, 0x97, 0xd5, 0x84, 0xac, 0x09, 0x25, 0x98, 0x0b, 0x1d, 0x77, 0x04, 0xb8, 0x55, 0x49,
                                0x85, 0x27, 0x06, 0x23, 0x58, 0xcb, 0x22, 0xc3, 0x20, 0x3a, 0x12, 0x09, 0x48, 0x24, 0x86, 0x76,
                                0x95, 0xe3, 0x45, 0x61, 0x43, 0x06, 0x6b, 0x4a, 0x61, 0x14, 0x24, 0xa9, 0x16, 0xe0, 0x97, 0x34,
                                0xb6, 0x58, 0xa4, 0x38, 0x34, 0x90, 0x19, 0x5d, 0x00, 0x19, 0x4a, 0xc2, 0x80, 0x4b, 0xdc, 0xb7,
                                0x00, 0x18, 0x12, 0x3d, 0xd9, 0x93, 0xee, 0x74, 0x13, 0x95, 0xad, 0x0b, 0x59, 0x51, 0x0e, 0x99,
                                0xdf, 0x49, 0x98, 0xde, 0xa9, 0x48, 0x4b, 0xa5, 0xfb, 0xe8, 0x79, 0xc9, 0xe2, 0xd9, 0x60, 0xa5,
                                0xbe, 0x74, 0xa6, 0x6b, 0x72, 0x0e, 0xe3, 0x7b, 0x28, 0xb3, 0x0e, 0x52, 0xcc, 0xf6, 0x3d, 0x39,
                                0xb7, 0x7e, 0xbb, 0xf0, 0xc8, 0xce, 0x5c, 0x72, 0xb2, 0x89, 0x60, 0x33, 0x7b, 0xc5, 0xda, 0x49,
                                0x1a, 0xda, 0x33, 0xba, 0x97, 0x9e, 0xa8, 0x1b, 0x6d, 0x5a, 0x77, 0xb6, 0xf1, 0x69, 0x5a, 0xd1,
                                0xbd, 0x84, 0xd5, 0x4e, 0x58, 0xa8, 0x5e, 0x8a, 0xa0, 0xc2, 0xc9, 0x22, 0xd9, 0xa5, 0x53, 0x11,
                                0x18, 0xc8, 0x3a, 0x39, 0xcf, 0x3f, 0x57, 0xb6, 0x45, 0x19, 0x1e, 0x8a, 0x71, 0xa4, 0x46, 0x27,
                                0x9e, 0xe9, 0xa4, 0x86, 0xdd, 0x14, 0xd9, 0x4d, 0xe3, 0x71, 0xe3, 0x26, 0xda, 0xaa, 0x17, 0xb4,
                                0xac, 0xe1, 0x09, 0xc1, 0x0d, 0x75, 0xba, 0x53, 0x0a, 0x37, 0x8b, 0xac, 0x37, 0x39, 0x41, 0x27,
                                0x6a, 0xf0, 0xe9, 0xb4, 0xc2, 0xac, 0xb0, 0x39, 0x73, 0x17, 0x64, 0x95, 0xf4, 0xdc, 0x33, 0xbb,
                                0x84, 0x94, 0x3e, 0xf8, 0x65, 0x71, 0x60, 0x7b, 0xd4, 0x5f, 0x27, 0x79, 0x95, 0x6a, 0xba, 0x76,
                                0xa6, 0xa5, 0x9a, 0xec, 0xae, 0x55, 0x3a, 0x27, 0x48, 0x23, 0xcf, 0x5c, 0x4d, 0xbc, 0x0b, 0x35,
                                0x5c, 0xa7, 0x17, 0xcf, 0x34, 0x57, 0xc9, 0x58, 0xc5, 0x20, 0x09, 0xee, 0xa5, 0xf2, 0x9c, 0x6c,
                                0x39, 0x1a, 0x77, 0x92, 0x9b, 0xff, 0xc6, 0xae, 0xf8, 0x36, 0xba, 0xa8, 0xaa, 0x6b, 0x1e, 0x8c,
                                0xc5, 0x97, 0x39, 0x6a, 0xb8, 0xa2, 0x55, 0xa8, 0xf8};
#define MUTE_ADTS_DATA s_mute_adts
#define MUTE_ADTS_DATA_LEN sizeof(s_mute_adts)
#define MUTE_ADTS_DATA_MS 130

PlayerProxy::PlayerProxy(const char *strVhost,
                         const char *strApp,
                         const char *strSrc,
                         bool bEnableHls,
                         bool bEnableMp4,
                         int iRetryCount){
	_strVhost = strVhost;
	_strApp = strApp;
	_strSrc = strSrc;
    _bEnableHls = bEnableHls;
    _bEnableMp4 = bEnableMp4;
    _iRetryCount = iRetryCount;
}
void PlayerProxy::play(const char* strUrl) {
	weak_ptr<PlayerProxy> weakSelf = shared_from_this();
	std::shared_ptr<int> piFailedCnt(new int(0)); //连续播放失败次数
	string strUrlTmp(strUrl);
	setOnPlayResult([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
		auto strongSelf = weakSelf.lock();
		if(!strongSelf) {
			return;
		}
		if(!err) {
			// 播放成功
			*piFailedCnt = 0;//连续播放失败次数清0
			strongSelf->onPlaySuccess();
		}else if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {
			// 播放失败，延时重试播放
			strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
		}
	});
	setOnShutdown([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
		auto strongSelf = weakSelf.lock();
		if(!strongSelf) {
			return;
		}
		if(strongSelf->_pChn) {
			strongSelf->_pChn.reset();
		}
		//播放异常中断，延时重试播放
		if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {
			strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
		}
	});
	MediaPlayer::play(strUrl);
}

PlayerProxy::~PlayerProxy() {
	auto iTaskId = reinterpret_cast<uint64_t>(this);
	AsyncTaskThread::Instance().CancelTask(iTaskId);
}
void PlayerProxy::rePlay(const string &strUrl,int iFailedCnt){
	auto iTaskId = reinterpret_cast<uint64_t>(this);
	auto iDelay = MAX(2 * 1000, MIN(iFailedCnt * 3000,60*1000));
	weak_ptr<PlayerProxy> weakSelf = shared_from_this();
	AsyncTaskThread::Instance().CancelTask(iTaskId);
	AsyncTaskThread::Instance().DoTaskDelay(iTaskId, iDelay, [weakSelf,strUrl,iFailedCnt]() {
		//播放失败次数越多，则延时越长
		auto strongPlayer = weakSelf.lock();
		if(!strongPlayer) {
			return false;
		}
		WarnL << "重试播放[" << iFailedCnt << "]:"  << strUrl;
		strongPlayer->MediaPlayer::play(strUrl.data());
		return false;
	});
}
bool PlayerProxy::close() {
    //通知其停止推流
    weak_ptr<PlayerProxy> weakSlef = dynamic_pointer_cast<PlayerProxy>(shared_from_this());
	auto executor = getExecutor();
	if(executor) {
		executor->async_first([weakSlef]() {
			auto stronSelf = weakSlef.lock();
			if (stronSelf) {
				stronSelf->_pChn.reset();
				stronSelf->teardown();
			}
		});
	}
    return true;
}

class MuteAudioMaker : public FrameRingInterfaceDelegate{
public:
	typedef std::shared_ptr<MuteAudioMaker> Ptr;

	MuteAudioMaker(){};
	virtual ~MuteAudioMaker(){}
	void inputFrame(const Frame::Ptr &frame) override {
		if(frame->getTrackType() == TrackVideo){
			auto iAudioIndex = frame->stamp() / MUTE_ADTS_DATA_MS;
			if(_iAudioIndex != iAudioIndex){
				_iAudioIndex = iAudioIndex;
				auto aacFrame = std::make_shared<AACFrameNoCopyAble>((char *)MUTE_ADTS_DATA,
																	 MUTE_ADTS_DATA_LEN,
																	  _iAudioIndex * MUTE_ADTS_DATA_MS);
				FrameRingInterfaceDelegate::inputFrame(aacFrame);
			}
		}
	}
private:
	int _iAudioIndex = 0;
};

void PlayerProxy::onPlaySuccess() {
	_pChn.reset(new DevChannel(_strVhost.data(),_strApp.data(),_strSrc.data(),getDuration(),_bEnableHls,_bEnableMp4));
	_pChn->setListener(shared_from_this());

	auto videoTrack = getTrack(TrackVideo);
	if(videoTrack){
		//添加视频
		_pChn->addTrack(videoTrack);
		//视频数据写入_pChn
		videoTrack->addDelegate(_pChn);
	}

	auto audioTrack = getTrack(TrackAudio);
	if(audioTrack){
		//添加音频
		_pChn->addTrack(audioTrack);
		//音频数据写入_pChn
        audioTrack->addDelegate(_pChn);
    }else if(videoTrack){
		//没有音频信息，产生一个静音音频
		MuteAudioMaker::Ptr audioMaker = std::make_shared<MuteAudioMaker>();
		//videoTrack把数据写入MuteAudioMaker
		videoTrack->addDelegate(audioMaker);
		//添加一个静音Track至_pChn
		_pChn->addTrack(std::make_shared<AACTrack>());
		//MuteAudioMaker生成静音音频然后写入_pChn；
		audioMaker->addDelegate(_pChn);
	}
}

} /* namespace mediakit */
<commit_msg>修复小bug<commit_after>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "Player/Player.h"
#include "Common/config.h"
#include "PlayerProxy.h"
#include "Util/mini.h"
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Thread/AsyncTaskThread.h"

using namespace toolkit;

namespace mediakit {

static uint8_t s_mute_adts[] = {0xff, 0xf1, 0x6c, 0x40, 0x2d, 0x3f, 0xfc, 0x00, 0xe0, 0x34, 0x20, 0xad, 0xf2, 0x3f, 0xb5, 0xdd,
                                0x73, 0xac, 0xbd, 0xca, 0xd7, 0x7d, 0x4a, 0x13, 0x2d, 0x2e, 0xa2, 0x62, 0x02, 0x70, 0x3c, 0x1c,
                                0xc5, 0x63, 0x55, 0x69, 0x94, 0xb5, 0x8d, 0x70, 0xd7, 0x24, 0x6a, 0x9e, 0x2e, 0x86, 0x24, 0xea,
                                0x4f, 0xd4, 0xf8, 0x10, 0x53, 0xa5, 0x4a, 0xb2, 0x9a, 0xf0, 0xa1, 0x4f, 0x2f, 0x66, 0xf9, 0xd3,
                                0x8c, 0xa6, 0x97, 0xd5, 0x84, 0xac, 0x09, 0x25, 0x98, 0x0b, 0x1d, 0x77, 0x04, 0xb8, 0x55, 0x49,
                                0x85, 0x27, 0x06, 0x23, 0x58, 0xcb, 0x22, 0xc3, 0x20, 0x3a, 0x12, 0x09, 0x48, 0x24, 0x86, 0x76,
                                0x95, 0xe3, 0x45, 0x61, 0x43, 0x06, 0x6b, 0x4a, 0x61, 0x14, 0x24, 0xa9, 0x16, 0xe0, 0x97, 0x34,
                                0xb6, 0x58, 0xa4, 0x38, 0x34, 0x90, 0x19, 0x5d, 0x00, 0x19, 0x4a, 0xc2, 0x80, 0x4b, 0xdc, 0xb7,
                                0x00, 0x18, 0x12, 0x3d, 0xd9, 0x93, 0xee, 0x74, 0x13, 0x95, 0xad, 0x0b, 0x59, 0x51, 0x0e, 0x99,
                                0xdf, 0x49, 0x98, 0xde, 0xa9, 0x48, 0x4b, 0xa5, 0xfb, 0xe8, 0x79, 0xc9, 0xe2, 0xd9, 0x60, 0xa5,
                                0xbe, 0x74, 0xa6, 0x6b, 0x72, 0x0e, 0xe3, 0x7b, 0x28, 0xb3, 0x0e, 0x52, 0xcc, 0xf6, 0x3d, 0x39,
                                0xb7, 0x7e, 0xbb, 0xf0, 0xc8, 0xce, 0x5c, 0x72, 0xb2, 0x89, 0x60, 0x33, 0x7b, 0xc5, 0xda, 0x49,
                                0x1a, 0xda, 0x33, 0xba, 0x97, 0x9e, 0xa8, 0x1b, 0x6d, 0x5a, 0x77, 0xb6, 0xf1, 0x69, 0x5a, 0xd1,
                                0xbd, 0x84, 0xd5, 0x4e, 0x58, 0xa8, 0x5e, 0x8a, 0xa0, 0xc2, 0xc9, 0x22, 0xd9, 0xa5, 0x53, 0x11,
                                0x18, 0xc8, 0x3a, 0x39, 0xcf, 0x3f, 0x57, 0xb6, 0x45, 0x19, 0x1e, 0x8a, 0x71, 0xa4, 0x46, 0x27,
                                0x9e, 0xe9, 0xa4, 0x86, 0xdd, 0x14, 0xd9, 0x4d, 0xe3, 0x71, 0xe3, 0x26, 0xda, 0xaa, 0x17, 0xb4,
                                0xac, 0xe1, 0x09, 0xc1, 0x0d, 0x75, 0xba, 0x53, 0x0a, 0x37, 0x8b, 0xac, 0x37, 0x39, 0x41, 0x27,
                                0x6a, 0xf0, 0xe9, 0xb4, 0xc2, 0xac, 0xb0, 0x39, 0x73, 0x17, 0x64, 0x95, 0xf4, 0xdc, 0x33, 0xbb,
                                0x84, 0x94, 0x3e, 0xf8, 0x65, 0x71, 0x60, 0x7b, 0xd4, 0x5f, 0x27, 0x79, 0x95, 0x6a, 0xba, 0x76,
                                0xa6, 0xa5, 0x9a, 0xec, 0xae, 0x55, 0x3a, 0x27, 0x48, 0x23, 0xcf, 0x5c, 0x4d, 0xbc, 0x0b, 0x35,
                                0x5c, 0xa7, 0x17, 0xcf, 0x34, 0x57, 0xc9, 0x58, 0xc5, 0x20, 0x09, 0xee, 0xa5, 0xf2, 0x9c, 0x6c,
                                0x39, 0x1a, 0x77, 0x92, 0x9b, 0xff, 0xc6, 0xae, 0xf8, 0x36, 0xba, 0xa8, 0xaa, 0x6b, 0x1e, 0x8c,
                                0xc5, 0x97, 0x39, 0x6a, 0xb8, 0xa2, 0x55, 0xa8, 0xf8};
#define MUTE_ADTS_DATA s_mute_adts
#define MUTE_ADTS_DATA_LEN sizeof(s_mute_adts)
#define MUTE_ADTS_DATA_MS 130

PlayerProxy::PlayerProxy(const char *strVhost,
                         const char *strApp,
                         const char *strSrc,
                         bool bEnableHls,
                         bool bEnableMp4,
                         int iRetryCount){
	_strVhost = strVhost;
	_strApp = strApp;
	_strSrc = strSrc;
    _bEnableHls = bEnableHls;
    _bEnableMp4 = bEnableMp4;
    _iRetryCount = iRetryCount;
}
void PlayerProxy::play(const char* strUrl) {
	weak_ptr<PlayerProxy> weakSelf = shared_from_this();
	std::shared_ptr<int> piFailedCnt(new int(0)); //连续播放失败次数
	string strUrlTmp(strUrl);
	setOnPlayResult([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
		auto strongSelf = weakSelf.lock();
		if(!strongSelf) {
			return;
		}
		if(!err) {
			// 播放成功
			*piFailedCnt = 0;//连续播放失败次数清0
			strongSelf->onPlaySuccess();
		}else if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {
			// 播放失败，延时重试播放
			strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
		}
	});
	setOnShutdown([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
		auto strongSelf = weakSelf.lock();
		if(!strongSelf) {
			return;
		}
		if(strongSelf->_pChn) {
			auto tracks = strongSelf->getTracks();
			for (auto & track : tracks){
				track->delDelegate(strongSelf->_pChn.get());
			}
			strongSelf->_pChn.reset();
		}
		//播放异常中断，延时重试播放
		if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {
			strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
		}
	});
	MediaPlayer::play(strUrl);
}

PlayerProxy::~PlayerProxy() {
	auto iTaskId = reinterpret_cast<uint64_t>(this);
	AsyncTaskThread::Instance().CancelTask(iTaskId);
}
void PlayerProxy::rePlay(const string &strUrl,int iFailedCnt){
	auto iTaskId = reinterpret_cast<uint64_t>(this);
	auto iDelay = MAX(2 * 1000, MIN(iFailedCnt * 3000,60*1000));
	weak_ptr<PlayerProxy> weakSelf = shared_from_this();
	AsyncTaskThread::Instance().CancelTask(iTaskId);
	AsyncTaskThread::Instance().DoTaskDelay(iTaskId, iDelay, [weakSelf,strUrl,iFailedCnt]() {
		//播放失败次数越多，则延时越长
		auto strongPlayer = weakSelf.lock();
		if(!strongPlayer) {
			return false;
		}
		WarnL << "重试播放[" << iFailedCnt << "]:"  << strUrl;
		strongPlayer->MediaPlayer::play(strUrl.data());
		return false;
	});
}
bool PlayerProxy::close() {
    //通知其停止推流
    weak_ptr<PlayerProxy> weakSlef = dynamic_pointer_cast<PlayerProxy>(shared_from_this());
	auto executor = getExecutor();
	if(executor) {
		executor->async_first([weakSlef]() {
			auto stronSelf = weakSlef.lock();
			if (stronSelf) {
				stronSelf->_pChn.reset();
				stronSelf->teardown();
			}
		});
	}
    return true;
}

class MuteAudioMaker : public FrameRingInterfaceDelegate{
public:
	typedef std::shared_ptr<MuteAudioMaker> Ptr;

	MuteAudioMaker(){};
	virtual ~MuteAudioMaker(){}
	void inputFrame(const Frame::Ptr &frame) override {
		if(frame->getTrackType() == TrackVideo){
			auto iAudioIndex = frame->stamp() / MUTE_ADTS_DATA_MS;
			if(_iAudioIndex != iAudioIndex){
				_iAudioIndex = iAudioIndex;
				auto aacFrame = std::make_shared<AACFrameNoCopyAble>((char *)MUTE_ADTS_DATA,
																	 MUTE_ADTS_DATA_LEN,
																	  _iAudioIndex * MUTE_ADTS_DATA_MS);
				FrameRingInterfaceDelegate::inputFrame(aacFrame);
			}
		}
	}
private:
	int _iAudioIndex = 0;
};

void PlayerProxy::onPlaySuccess() {
	_pChn.reset(new DevChannel(_strVhost.data(),_strApp.data(),_strSrc.data(),getDuration(),_bEnableHls,_bEnableMp4));
	_pChn->setListener(shared_from_this());

	auto videoTrack = getTrack(TrackVideo);
	if(videoTrack){
		//添加视频
		_pChn->addTrack(videoTrack);
		//视频数据写入_pChn
		videoTrack->addDelegate(_pChn);
	}

	auto audioTrack = getTrack(TrackAudio);
	if(audioTrack){
		//添加音频
		_pChn->addTrack(audioTrack);
		//音频数据写入_pChn
        audioTrack->addDelegate(_pChn);
    }else if(videoTrack){
		//没有音频信息，产生一个静音音频
		MuteAudioMaker::Ptr audioMaker = std::make_shared<MuteAudioMaker>();
		//videoTrack把数据写入MuteAudioMaker
		videoTrack->addDelegate(audioMaker);
		//添加一个静音Track至_pChn
		_pChn->addTrack(std::make_shared<AACTrack>());
		//MuteAudioMaker生成静音音频然后写入_pChn；
		audioMaker->addDelegate(_pChn);
	}
}

} /* namespace mediakit */
<|endoftext|>


<commit_before><commit_msg>Remove depracated limitation code in Modelica generator<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dbtreeview.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: oj $ $Date: 2002-05-02 07:14:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#include "dbaccess_helpid.hrc"

// .........................................................................
namespace dbaui
{
// .........................................................................

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

DBG_NAME(DBTreeView)
//========================================================================
// class DBTreeView
//========================================================================
DBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits)
                    :   Window( pParent, nBits )
                    , m_pTreeListBox(NULL)
{
    DBG_CTOR(DBTreeView,NULL);

    m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT);
    m_pTreeListBox->EnableCheckButton(NULL);
    m_pTreeListBox->SetDragDropMode( 0 );
    m_pTreeListBox->EnableInplaceEditing( sal_True );
    m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX);
    m_pTreeListBox->Show();
}

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

DBTreeView::~DBTreeView()
{
    if (m_pTreeListBox)
    {
        if (m_pTreeListBox->GetModel())
        {
            m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox);
            m_pTreeListBox->DisconnectFromModel();
        }
        Window* pDeleteIt = m_pTreeListBox;
        m_pTreeListBox = NULL;
        delete pDeleteIt;
    }
    DBG_DTOR(DBTreeView,NULL);
}

// -----------------------------------------------------------------------------
void DBTreeView::SetPreExpandHandler(const Link& _rHdl)
{
    m_pTreeListBox->SetPreExpandHandler(_rHdl);
}

// -----------------------------------------------------------------------------
Link DBTreeView::GetPreExpandHandler() const
{
    return m_pTreeListBox->GetPreExpandHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setCutHandler(const Link& _rHdl)
{
    m_pTreeListBox->setCutHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getCutHandler() const
{
    return m_pTreeListBox->getCutHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setCopyHandler(const Link& _rHdl)
{
    m_pTreeListBox->setCopyHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getCopyHandler() const
{
    return m_pTreeListBox->getCopyHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setPasteHandler(const Link& _rHdl)
{
    m_pTreeListBox->setPasteHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getPasteHandler() const
{
    return m_pTreeListBox->getPasteHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setDeleteHandler(const Link& _rHdl)
{
    m_pTreeListBox->setDeleteHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getDeleteHandler() const
{
    return m_pTreeListBox->getDeleteHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setEditingHandler(const Link& _rHdl)
{
    m_pTreeListBox->setEditingHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getEditingHandler() const
{
    return m_pTreeListBox->getEditingHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setEditedHandler(const Link& _rHdl)
{
    m_pTreeListBox->setEditedHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getEditedHandler() const
{
    return m_pTreeListBox->getEditedHandler();
}
// -----------------------------------------------------------------------------
void DBTreeView::Resize()
{
    Window::Resize();
    m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel());
}

// -------------------------------------------------------------------------
DBTreeListModel* DBTreeView::getModel() const
{
    return (DBTreeListModel*)m_pTreeListBox->GetModel();
}

// -------------------------------------------------------------------------
void DBTreeView::setModel(DBTreeListModel* _pTreeModel)
{
    if (_pTreeModel)
        _pTreeModel->InsertView(m_pTreeListBox);
    m_pTreeListBox->SetModel(_pTreeModel);
}

// -------------------------------------------------------------------------
DBTreeListBox* DBTreeView::getListBox() const
{
    return m_pTreeListBox;
}

// -------------------------------------------------------------------------
void DBTreeView::setSelectHdl(const Link& _rHdl)
{
    m_pTreeListBox->SetSelectHdl(_rHdl);
}
// -----------------------------------------------------------------------------
void DBTreeView::GetFocus()
{
    Window::GetFocus();
    if ( m_pTreeListBox )//&& !m_pTreeListBox->HasChildPathFocus())
        m_pTreeListBox->GrabFocus();
}

// .........................................................................
}   // namespace dbaui
// .........................................................................

<commit_msg>INTEGRATION: CWS insight01 (1.17.112); FILE MERGED 2004/07/15 10:58:37 oj 1.17.112.4: add chkthis macros 2004/05/26 08:35:45 oj 1.17.112.3: handle return key event 2003/12/18 13:54:32 oj 1.17.112.2: #111075# ongoing work 2003/11/05 11:41:02 oj 1.17.112.1: #111075# ongoing work<commit_after>/*************************************************************************
 *
 *  $RCSfile: dbtreeview.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:33:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#include "dbaccess_helpid.hrc"

// .........................................................................
namespace dbaui
{
// .........................................................................

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

DBG_NAME(DBTreeView)
//========================================================================
// class DBTreeView
//========================================================================
DBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits)
                    :   Window( pParent, nBits )
                    , m_pTreeListBox(NULL)
{
    DBG_CTOR(DBTreeView,NULL);

    m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_HASLINES | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT,sal_True);
    m_pTreeListBox->EnableCheckButton(NULL);
    m_pTreeListBox->SetDragDropMode( 0 );
    m_pTreeListBox->EnableInplaceEditing( sal_True );
    m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX);
    m_pTreeListBox->Show();
}

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

DBTreeView::~DBTreeView()
{
    DBG_DTOR(DBTreeView,NULL);
    if (m_pTreeListBox)
    {
        if (m_pTreeListBox->GetModel())
        {
            m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox);
            m_pTreeListBox->DisconnectFromModel();
        }
        ::std::auto_ptr<Window> aTemp(m_pTreeListBox);
        m_pTreeListBox = NULL;
    }
}

// -----------------------------------------------------------------------------
void DBTreeView::SetPreExpandHandler(const Link& _rHdl)
{
    m_pTreeListBox->SetPreExpandHandler(_rHdl);
}

// -----------------------------------------------------------------------------
Link DBTreeView::GetPreExpandHandler() const
{
    return m_pTreeListBox->GetPreExpandHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setCutHandler(const Link& _rHdl)
{
    m_pTreeListBox->setCutHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getCutHandler() const
{
    return m_pTreeListBox->getCutHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setCopyHandler(const Link& _rHdl)
{
    m_pTreeListBox->setCopyHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getCopyHandler() const
{
    return m_pTreeListBox->getCopyHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setPasteHandler(const Link& _rHdl)
{
    m_pTreeListBox->setPasteHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getPasteHandler() const
{
    return m_pTreeListBox->getPasteHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setDeleteHandler(const Link& _rHdl)
{
    m_pTreeListBox->setDeleteHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getDeleteHandler() const
{
    return m_pTreeListBox->getDeleteHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setEditingHandler(const Link& _rHdl)
{
    m_pTreeListBox->setEditingHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getEditingHandler() const
{
    return m_pTreeListBox->getEditingHandler();
}
// -----------------------------------------------------------------------------
void    DBTreeView::setEditedHandler(const Link& _rHdl)
{
    m_pTreeListBox->setEditedHandler(_rHdl);
}
// -----------------------------------------------------------------------------
Link    DBTreeView::getEditedHandler() const
{
    return m_pTreeListBox->getEditedHandler();
}
// -----------------------------------------------------------------------------
void DBTreeView::Resize()
{
    Window::Resize();
    m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel());
}

// -------------------------------------------------------------------------
DBTreeListModel* DBTreeView::getModel() const
{
    return (DBTreeListModel*)m_pTreeListBox->GetModel();
}

// -------------------------------------------------------------------------
void DBTreeView::setModel(DBTreeListModel* _pTreeModel)
{
    if (_pTreeModel)
        _pTreeModel->InsertView(m_pTreeListBox);
    m_pTreeListBox->SetModel(_pTreeModel);
}

// -------------------------------------------------------------------------
DBTreeListBox* DBTreeView::getListBox() const
{
    return m_pTreeListBox;
}

// -------------------------------------------------------------------------
void DBTreeView::setSelectHdl(const Link& _rHdl)
{
    m_pTreeListBox->SetSelectHdl(_rHdl);
}
// -----------------------------------------------------------------------------
void DBTreeView::GetFocus()
{
    Window::GetFocus();
    if ( m_pTreeListBox )//&& !m_pTreeListBox->HasChildPathFocus())
        m_pTreeListBox->GrabFocus();
}

// .........................................................................
}   // namespace dbaui
// .........................................................................

<|endoftext|>