<commit_before><commit_msg>No bzero in MSVC<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS sj02 (1.62.136); FILE MERGED 2003/07/28 15:32:27 sj 1.62.136.1: #i15927# PowerPoint import: added font independent linespacing<commit_after><|endoftext|>


<commit_before><commit_msg>delete unuseful operator<commit_after><|endoftext|>


<commit_before><commit_msg>Add some logic to just try and split any new dock in half<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include <dukat/fullscreeneffect2.h>
#include <dukat/animationmanager.h>
#include <dukat/game2.h>
#include <dukat/log.h>

namespace dukat
{
    FullscreenEffect2::FullscreenEffect2(Game2* game) : game(game)
    {
        static constexpr auto uniform_time = "u_time";
        static constexpr auto uniform_diffuse = "u_diffuse";

        composite_binder = [&](ShaderProgram* sp) {
            if (sp->attr(uniform_time) != -1)
                sp->set(uniform_time, this->game->get_time());
            if (sp->attr(uniform_diffuse) != -1)
                sp->set(uniform_diffuse, state.color.r, state.color.g, state.color.b, state.color.a * state.alpha);
        };
    }

    FullscreenEffect2::~FullscreenEffect2(void)
    {
        auto am = game->get<AnimationManager>();
        if (state.anim != nullptr)
            am->cancel(state.anim);
        for (auto& it : state_stash)
        {
            if (it.second.anim != nullptr)
                am->cancel(it.second.anim);
        }
    }

    void FullscreenEffect2::begin_fade_in(float duration, std::function<void(void)> callback)
    {
        log->debug("Begin fade-in: {}", duration);
        cancel_anim();

        state.alpha = 1.0f;
        auto sp = game->get_shaders()->get_program(default_vsh, solid_fsh);
        game->get_renderer()->set_composite_program(sp, composite_binder);

        begin_anim(duration, 0.0f, callback);
    }

    void FullscreenEffect2::begin_fade_out(float duration, std::function<void(void)> callback)
    {
        log->debug("Begin fade-out: {}", duration);
        cancel_anim();

        state.alpha = 0.0f;
        auto sp = game->get_shaders()->get_program(default_vsh, solid_fsh);
        game->get_renderer()->set_composite_program(sp, composite_binder);

        begin_anim(duration, 1.0f, callback);
    }

    void FullscreenEffect2::begin_anim(float duration, float target, std::function<void(void)> callback)
    {
        auto value_anim = std::make_unique<ValueAnimation<float>>(&state.alpha, duration, target);
        value_anim->set_callback([&, callback](void) {
            if (callback != nullptr)
                callback();
            state.anim = nullptr;
        });
        state.anim = game->get<AnimationManager>()->add(std::move(value_anim));
    }

    void FullscreenEffect2::cancel_anim(void)
    {
        if (state.anim != nullptr)
        {
            game->get<AnimationManager>()->cancel(state.anim);
            state.anim = nullptr;
        }
    }

    void FullscreenEffect2::stash(const std::string& id)
    {
        if (state.anim != nullptr)
            state.anim->pause();

        state_stash[id] = state;
    }

    void FullscreenEffect2::restore(const std::string& id)
    {
        if (!state_stash.count(id))
        {
            reset_composite_program(); // if no effect defined, just go to default
            return;
        }

        if (state.anim != nullptr)
            game->get<AnimationManager>()->cancel(state.anim);

        state = state_stash[id];
        state_stash.erase(id);

        game->get_renderer()->set_composite_program(state.sp, composite_binder);

        if (state.anim != nullptr)
            state.anim->resume();
    }

    void FullscreenEffect2::set_composite_program(ShaderProgram* sp, std::function<void(ShaderProgram*)> binder)
    {
        game->get_renderer()->set_composite_program(sp, binder != nullptr ? binder : composite_binder);
        state.sp = sp; // back up SP so we can restore if needed
    }

    void FullscreenEffect2::reset_composite_program(void)
    {
        state.sp = game->get_shaders()->get_program(default_vsh, default_fsh);
        game->get_renderer()->set_composite_program(state.sp);
        state.color = Color{ 1, 1, 1, 1 };
        state.alpha = 0.0f;
        state.anim = nullptr;
    }
}<commit_msg>Fix default color<commit_after>#include "stdafx.h"
#include <dukat/fullscreeneffect2.h>
#include <dukat/animationmanager.h>
#include <dukat/game2.h>
#include <dukat/log.h>

namespace dukat
{
    FullscreenEffect2::FullscreenEffect2(Game2* game) : game(game)
    {
        static constexpr auto uniform_time = "u_time";
        static constexpr auto uniform_diffuse = "u_diffuse";

        composite_binder = [&](ShaderProgram* sp) {
            if (sp->attr(uniform_time) != -1)
                sp->set(uniform_time, this->game->get_time());
            if (sp->attr(uniform_diffuse) != -1)
                sp->set(uniform_diffuse, state.color.r, state.color.g, state.color.b, state.color.a * state.alpha);
        };
    }

    FullscreenEffect2::~FullscreenEffect2(void)
    {
        auto am = game->get<AnimationManager>();
        if (state.anim != nullptr)
            am->cancel(state.anim);
        for (auto& it : state_stash)
        {
            if (it.second.anim != nullptr)
                am->cancel(it.second.anim);
        }
    }

    void FullscreenEffect2::begin_fade_in(float duration, std::function<void(void)> callback)
    {
        log->debug("Begin fade-in: {}", duration);
        cancel_anim();

        state.alpha = 1.0f;
        auto sp = game->get_shaders()->get_program(default_vsh, solid_fsh);
        game->get_renderer()->set_composite_program(sp, composite_binder);

        begin_anim(duration, 0.0f, callback);
    }

    void FullscreenEffect2::begin_fade_out(float duration, std::function<void(void)> callback)
    {
        log->debug("Begin fade-out: {}", duration);
        cancel_anim();

        state.alpha = 0.0f;
        auto sp = game->get_shaders()->get_program(default_vsh, solid_fsh);
        game->get_renderer()->set_composite_program(sp, composite_binder);

        begin_anim(duration, 1.0f, callback);
    }

    void FullscreenEffect2::begin_anim(float duration, float target, std::function<void(void)> callback)
    {
        auto value_anim = std::make_unique<ValueAnimation<float>>(&state.alpha, duration, target);
        value_anim->set_callback([&, callback](void) {
            if (callback != nullptr)
                callback();
            state.anim = nullptr;
        });
        state.anim = game->get<AnimationManager>()->add(std::move(value_anim));
    }

    void FullscreenEffect2::cancel_anim(void)
    {
        if (state.anim != nullptr)
        {
            game->get<AnimationManager>()->cancel(state.anim);
            state.anim = nullptr;
        }
    }

    void FullscreenEffect2::stash(const std::string& id)
    {
        if (state.anim != nullptr)
            state.anim->pause();

        state_stash[id] = state;
    }

    void FullscreenEffect2::restore(const std::string& id)
    {
        if (!state_stash.count(id))
        {
            reset_composite_program(); // if no effect defined, just go to default
            return;
        }

        if (state.anim != nullptr)
            game->get<AnimationManager>()->cancel(state.anim);

        state = state_stash[id];
        state_stash.erase(id);

        game->get_renderer()->set_composite_program(state.sp, composite_binder);

        if (state.anim != nullptr)
            state.anim->resume();
    }

    void FullscreenEffect2::set_composite_program(ShaderProgram* sp, std::function<void(ShaderProgram*)> binder)
    {
        game->get_renderer()->set_composite_program(sp, binder != nullptr ? binder : composite_binder);
        state.sp = sp; // back up SP so we can restore if needed
    }

    void FullscreenEffect2::reset_composite_program(void)
    {
        state.sp = game->get_shaders()->get_program(default_vsh, default_fsh);
        game->get_renderer()->set_composite_program(state.sp);
        state.color = Color{ 0, 0, 0, 1 };
        state.alpha = 0.0f;
        state.anim = nullptr;
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <stdexcept>

#include <nix/hdf5/PropertyHDF5.hpp>

using namespace std;

namespace nix {
namespace hdf5 {

PropertyHDF5::PropertyHDF5(const PropertyHDF5 &property)
    : NamedEntityHDF5(property.file(), property.group(), property.id())
{
}

PropertyHDF5::PropertyHDF5(const File &file, const Group &group, const string &id)
    : NamedEntityHDF5(file, group, id)
{
}

PropertyHDF5::PropertyHDF5(const File &file, const Group &group, const string &id, time_t time)
    : NamedEntityHDF5(file, group, id, time)
{
}

void PropertyHDF5::dataType(const string &dataType) {
    string dt = this->dataType();
    if (dt.compare(dataType) == 0) {
        return;
    } else {
        if (valueCount() > 0 && this->dataType().length() > 0) {
            throw runtime_error("Cannot change data type of a not empty property!");
            return;
        }
    }
    group().setAttr("data_type", dataType);
}

string PropertyHDF5::dataType() const {
    string dataType;
    group().getAttr("data_type", dataType);
    return dataType;
}

void PropertyHDF5::mapping(const string &mapping) {
    group().setAttr("mapping", mapping);
}

string PropertyHDF5::mapping() const {
    string mapping;
    group().getAttr("mapping", mapping);
    return mapping;
}

void PropertyHDF5::unit(const string &unit) {
    if (valueCount() > 0 && this->unit().length() > 0) {
        throw runtime_error("Cannot change unit of a not-empty property!");
        return;
    }
    group().setAttr("unit", unit);
}

string PropertyHDF5::unit() const {
    string unit;
    group().getAttr("unit", unit);
    return unit;
}

void PropertyHDF5::removeValues(){
    group().removeData("values");
}

// TODO should this be moved to Property.hpp/cpp
/*
bool PropertyHDF5::checkDataType(const H5::DataSet &dataset, H5T_class_t destType) const {
    H5::DataType type = dataset.getDataType();
    if (type.getClass() != H5T_COMPOUND) {
        return false;
    }
    H5::CompType ct(dataset);
    if (ct.getMemberDataType(ct.getMemberIndex("value")).getClass() != destType) {
        return false;
    }
    return true;
}
*/

size_t PropertyHDF5::valueCount() const {
    size_t count = 0;
    if (group().hasData("values")) {
        DataSet dataset = group().openData("values");
        NDSize size = dataset.size();
        return size[0];
    }
    return count;
}

void PropertyHDF5::setValues(const std::vector<Value> &values)
{
    DataSet dataset;

    if (values.size() < 1) {
        return; //FIXME: set_extent the dataset to 0
    }

    if (group().hasData("values")) {
        dataset = group().openData("values");
    } else {
        NDSize size = {1};
        NDSize maxsize = {H5S_UNLIMITED};
        NDSize chunks = DataSet::guessChunking(size, values[0].type());
        H5::DataType fileType = DataSet::fileTypeForValue(values[0].type());

        dataset = DataSet::create(group().h5Group(), "values", fileType, size, &maxsize, &chunks);
    }

    dataset.write(values);
}

std::vector<Value> PropertyHDF5::getValues(void) const
{
    std::vector<Value> values;
    if (!group().hasData("values")) {
        return values;
    }

    DataSet dataset = group().openData("values");
    dataset.read(values);
    return values;
}

PropertyHDF5::~PropertyHDF5() {}

} // namespace hdf5
} // namespace nix
<commit_msg>PropertyHDF5: Values::write: move size check into ds creation<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <stdexcept>

#include <nix/hdf5/PropertyHDF5.hpp>

using namespace std;

namespace nix {
namespace hdf5 {

PropertyHDF5::PropertyHDF5(const PropertyHDF5 &property)
    : NamedEntityHDF5(property.file(), property.group(), property.id())
{
}

PropertyHDF5::PropertyHDF5(const File &file, const Group &group, const string &id)
    : NamedEntityHDF5(file, group, id)
{
}

PropertyHDF5::PropertyHDF5(const File &file, const Group &group, const string &id, time_t time)
    : NamedEntityHDF5(file, group, id, time)
{
}

void PropertyHDF5::dataType(const string &dataType) {
    string dt = this->dataType();
    if (dt.compare(dataType) == 0) {
        return;
    } else {
        if (valueCount() > 0 && this->dataType().length() > 0) {
            throw runtime_error("Cannot change data type of a not empty property!");
            return;
        }
    }
    group().setAttr("data_type", dataType);
}

string PropertyHDF5::dataType() const {
    string dataType;
    group().getAttr("data_type", dataType);
    return dataType;
}

void PropertyHDF5::mapping(const string &mapping) {
    group().setAttr("mapping", mapping);
}

string PropertyHDF5::mapping() const {
    string mapping;
    group().getAttr("mapping", mapping);
    return mapping;
}

void PropertyHDF5::unit(const string &unit) {
    if (valueCount() > 0 && this->unit().length() > 0) {
        throw runtime_error("Cannot change unit of a not-empty property!");
        return;
    }
    group().setAttr("unit", unit);
}

string PropertyHDF5::unit() const {
    string unit;
    group().getAttr("unit", unit);
    return unit;
}

void PropertyHDF5::removeValues(){
    group().removeData("values");
}

// TODO should this be moved to Property.hpp/cpp
/*
bool PropertyHDF5::checkDataType(const H5::DataSet &dataset, H5T_class_t destType) const {
    H5::DataType type = dataset.getDataType();
    if (type.getClass() != H5T_COMPOUND) {
        return false;
    }
    H5::CompType ct(dataset);
    if (ct.getMemberDataType(ct.getMemberIndex("value")).getClass() != destType) {
        return false;
    }
    return true;
}
*/

size_t PropertyHDF5::valueCount() const {
    size_t count = 0;
    if (group().hasData("values")) {
        DataSet dataset = group().openData("values");
        NDSize size = dataset.size();
        return size[0];
    }
    return count;
}

void PropertyHDF5::setValues(const std::vector<Value> &values)
{
    DataSet dataset;

    if (group().hasData("values")) {
        dataset = group().openData("values");
    } else {

        if (values.size() < 1) {
            return; //Nothing to do, since we also cannot guess the correct DataType
        }

        NDSize size = {1};
        NDSize maxsize = {H5S_UNLIMITED};
        NDSize chunks = DataSet::guessChunking(size, values[0].type());
        H5::DataType fileType = DataSet::fileTypeForValue(values[0].type());

        dataset = DataSet::create(group().h5Group(), "values", fileType, size, &maxsize, &chunks);
    }

    dataset.write(values);
}

std::vector<Value> PropertyHDF5::getValues(void) const
{
    std::vector<Value> values;
    if (!group().hasData("values")) {
        return values;
    }

    DataSet dataset = group().openData("values");
    dataset.read(values);
    return values;
}

PropertyHDF5::~PropertyHDF5() {}

} // namespace hdf5
} // namespace nix
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: reposy.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 16:34:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_autodoc.hxx"

//  VERSION:            Autodoc 2.2

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/x_ary.hxx>
#include <ary/actions.hxx>
#include <idl/i_reposypart.hxx>

    // S P L I T //

#include <store/storage.hxx>
#include <store/strg_ifc.hxx>
#include <id_gener.hxx>
#include <cpp/c_gate.hxx>
#include <loc/l_gate.hxx>

namespace ary
{

namespace
{
    static Dyn<RepositoryCenter> pTheOldInstance_(0);
}

namespace n22
{

using ::ary::Command;
using ::ary::X_Ary;

//*****************     Repository          ************//

namespace
{
    static Dyn<RepositoryCenter> pTheInstance_(0);
}

Repository &
Repository::Create_()
{
    if ( pTheInstance_ )
        throw X_Ary(X_Ary::x_MultipleRepository);

    pTheInstance_ = new RepositoryCenter;

    // KORR_FUTURE
    //   Create the Cpp repository:
    ::ary::Repository::Create_(0);

    return *pTheInstance_;
}

Repository &
Repository::The_()
{
    if ( NOT pTheInstance_ )
        throw X_Ary(X_Ary::x_MissingRepository);

    return *pTheInstance_;
}

void
Repository::Destroy_()
{
    pTheInstance_ = 0;

    // KORR_FUTURE
    //   Destroythe Cpp repository:
    ::ary::Repository::Destroy_();
}

//*****************     RepositoryCenter          ************//

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
#if 0       // Version 2.2
        pCppPartition(),
#endif // Version 2.2
        pIdlPartition()
{
}

RepositoryCenter::~RepositoryCenter()
{
}

void
RepositoryCenter::RunCommand_ProduceAllSecondaries()
{
    // KORR_FUTURE
}

void
RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & )
{
    // KORR_FUTURE
}

void
RepositoryCenter::do_Perform( Command & io_rCommand )
{
    io_rCommand.Run(*this);
}

const String &
RepositoryCenter::inq_Name() const
{
    return sDisplayedName;
}

bool
RepositoryCenter::inq_HasIdl() const
{
    return bool(pIdlPartition);
}

bool
RepositoryCenter::inq_HasCpp() const
{
    return pTheOldInstance_->HasCpp();
}

const ::ary::idl::Gate &
RepositoryCenter::inq_Gate_Idl() const
{
    return const_cast< RepositoryCenter& >(*this).access_Gate_Idl();
}

const ::ary::cpp::DisplayGate &
RepositoryCenter::inq_Gate_Cpp() const
{
    return pTheOldInstance_->DisplayGate_Cpp();
}

::ary::idl::Gate &
RepositoryCenter::access_Gate_Idl()
{
    if (NOT pIdlPartition)
        pIdlPartition = new idl::RepositoryPartition(*this);

    return pIdlPartition->TheGate();
}

::ary::cpp::RwGate &
RepositoryCenter::access_Gate_Cpp()
{
    return pTheOldInstance_->RwGate_Cpp();
}

void
RepositoryCenter::do_Set_Name(const String & i_sName)
{
    sDisplayedName = i_sName;
    pTheOldInstance_->Set_Name(i_sName);
}

#if 0       // Version 2.2
/*
cpp::Gate &
RepositoryCenter::access_Gate_Cpp()
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
const cpp::Gate &
RepositoryCenter::inq_Gate_Cpp() const
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
*/
#endif    // Version 2.2

}   // namespace n22

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    info
    ----
    CodeInformation
        (IDL)          11002
*/

                        //      S P L I T           //

struct RepositoryCenter::CheshireCat
{
    //  DATA
    String              sName;
    Dyn<store::Storage> pStorage;
    Dyn<Storage_Ifc>    pStorage_Ifc;
    Dyn<IdGenerator>    pIdGenerator;

    Dyn<cpp::Gate>      pGate_Cpp;
    Dyn<loc::Gate>      pGate_Locations;
    bool                bHasCppContent;

                        CheshireCat(
                            DYN IdGenerator &   let_drIds );
                        ~CheshireCat();
};

Repository &
Repository::Create_( DYN IdGenerator *   let_dpIds )
{
    csv_assert( NOT pTheOldInstance_ );

    DYN IdGenerator * dpIds =
            let_dpIds != 0
                ?   let_dpIds
                :   new Std_IdGenerator;
    pTheOldInstance_ = new RepositoryCenter( *dpIds );
    return *pTheOldInstance_;
}

Repository &
Repository::The_()
{
    csv_assert( pTheOldInstance_ );
    return *pTheOldInstance_;
}

void
Repository::Destroy_()
{
    pTheOldInstance_ = 0;
}

RepositoryCenter::RepositoryCenter( DYN IdGenerator &   let_drIds )
    :   pi( new CheshireCat(let_drIds) )
{
}

RepositoryCenter::~RepositoryCenter()
{
}

bool
RepositoryCenter::HasCpp() const
{
    return pi->bHasCppContent;
}

void
RepositoryCenter::Set_Name( const String & i_name )
{
     pi->sName = i_name;
}

const cpp::DisplayGate &
RepositoryCenter::inq_DisplayGate_Cpp() const
{
    return *pi->pGate_Cpp;
}

const udmstri &
RepositoryCenter::inq_Name() const
{
    return pi->sName;
}

cpp::RwGate &
RepositoryCenter::access_RwGate_Cpp()
{
    pi->bHasCppContent = true;
    return *pi->pGate_Cpp;
}

RepositoryCenter::
CheshireCat::CheshireCat( DYN IdGenerator &   let_drIds )
    :   sName(),
        pStorage(0),
        pStorage_Ifc(0),
        pIdGenerator( &let_drIds ),
        pGate_Cpp(0),
        pGate_Locations(0),
        bHasCppContent(false)
{
    pStorage                = new store::Storage;
    pStorage_Ifc            = new Storage_Ifc( *pStorage );
    pGate_Locations         = new loc::Gate(
                                        pStorage_Ifc->Ifc_Locations(),
                                        *pIdGenerator );
    pGate_Cpp               = new cpp::Gate(
                                        *pStorage_Ifc,
                                        *pIdGenerator,
                                        *pGate_Locations );
}

RepositoryCenter::
CheshireCat::~CheshireCat()
{
}

}   // namespace ary

<commit_msg>INTEGRATION: CWS adc17 (1.8.18); FILE MERGED 2007/08/31 14:45:28 np 1.8.18.1: #i80569# remove wrong pchs.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: reposy.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 13:44:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/x_ary.hxx>
#include <ary/actions.hxx>
#include <idl/i_reposypart.hxx>

    // S P L I T //

#include <store/storage.hxx>
#include <store/strg_ifc.hxx>
#include <id_gener.hxx>
#include <cpp/c_gate.hxx>
#include <loc/l_gate.hxx>

namespace ary
{

namespace
{
    static Dyn<RepositoryCenter> pTheOldInstance_(0);
}

namespace n22
{

using ::ary::Command;
using ::ary::X_Ary;

//*****************     Repository          ************//

namespace
{
    static Dyn<RepositoryCenter> pTheInstance_(0);
}

Repository &
Repository::Create_()
{
    if ( pTheInstance_ )
        throw X_Ary(X_Ary::x_MultipleRepository);

    pTheInstance_ = new RepositoryCenter;

    // KORR_FUTURE
    //   Create the Cpp repository:
    ::ary::Repository::Create_(0);

    return *pTheInstance_;
}

Repository &
Repository::The_()
{
    if ( NOT pTheInstance_ )
        throw X_Ary(X_Ary::x_MissingRepository);

    return *pTheInstance_;
}

void
Repository::Destroy_()
{
    pTheInstance_ = 0;

    // KORR_FUTURE
    //   Destroythe Cpp repository:
    ::ary::Repository::Destroy_();
}

//*****************     RepositoryCenter          ************//

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
#if 0       // Version 2.2
        pCppPartition(),
#endif // Version 2.2
        pIdlPartition()
{
}

RepositoryCenter::~RepositoryCenter()
{
}

void
RepositoryCenter::RunCommand_ProduceAllSecondaries()
{
    // KORR_FUTURE
}

void
RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & )
{
    // KORR_FUTURE
}

void
RepositoryCenter::do_Perform( Command & io_rCommand )
{
    io_rCommand.Run(*this);
}

const String &
RepositoryCenter::inq_Name() const
{
    return sDisplayedName;
}

bool
RepositoryCenter::inq_HasIdl() const
{
    return bool(pIdlPartition);
}

bool
RepositoryCenter::inq_HasCpp() const
{
    return pTheOldInstance_->HasCpp();
}

const ::ary::idl::Gate &
RepositoryCenter::inq_Gate_Idl() const
{
    return const_cast< RepositoryCenter& >(*this).access_Gate_Idl();
}

const ::ary::cpp::DisplayGate &
RepositoryCenter::inq_Gate_Cpp() const
{
    return pTheOldInstance_->DisplayGate_Cpp();
}

::ary::idl::Gate &
RepositoryCenter::access_Gate_Idl()
{
    if (NOT pIdlPartition)
        pIdlPartition = new idl::RepositoryPartition(*this);

    return pIdlPartition->TheGate();
}

::ary::cpp::RwGate &
RepositoryCenter::access_Gate_Cpp()
{
    return pTheOldInstance_->RwGate_Cpp();
}

void
RepositoryCenter::do_Set_Name(const String & i_sName)
{
    sDisplayedName = i_sName;
    pTheOldInstance_->Set_Name(i_sName);
}

#if 0       // Version 2.2
/*
cpp::Gate &
RepositoryCenter::access_Gate_Cpp()
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
const cpp::Gate &
RepositoryCenter::inq_Gate_Cpp() const
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
*/
#endif    // Version 2.2

}   // namespace n22

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    info
    ----
    CodeInformation
        (IDL)          11002
*/

                        //      S P L I T           //

struct RepositoryCenter::CheshireCat
{
    //  DATA
    String              sName;
    Dyn<store::Storage> pStorage;
    Dyn<Storage_Ifc>    pStorage_Ifc;
    Dyn<IdGenerator>    pIdGenerator;

    Dyn<cpp::Gate>      pGate_Cpp;
    Dyn<loc::Gate>      pGate_Locations;
    bool                bHasCppContent;

                        CheshireCat(
                            DYN IdGenerator &   let_drIds );
                        ~CheshireCat();
};

Repository &
Repository::Create_( DYN IdGenerator *   let_dpIds )
{
    csv_assert( NOT pTheOldInstance_ );

    DYN IdGenerator * dpIds =
            let_dpIds != 0
                ?   let_dpIds
                :   new Std_IdGenerator;
    pTheOldInstance_ = new RepositoryCenter( *dpIds );
    return *pTheOldInstance_;
}

Repository &
Repository::The_()
{
    csv_assert( pTheOldInstance_ );
    return *pTheOldInstance_;
}

void
Repository::Destroy_()
{
    pTheOldInstance_ = 0;
}

RepositoryCenter::RepositoryCenter( DYN IdGenerator &   let_drIds )
    :   pi( new CheshireCat(let_drIds) )
{
}

RepositoryCenter::~RepositoryCenter()
{
}

bool
RepositoryCenter::HasCpp() const
{
    return pi->bHasCppContent;
}

void
RepositoryCenter::Set_Name( const String & i_name )
{
     pi->sName = i_name;
}

const cpp::DisplayGate &
RepositoryCenter::inq_DisplayGate_Cpp() const
{
    return *pi->pGate_Cpp;
}

const udmstri &
RepositoryCenter::inq_Name() const
{
    return pi->sName;
}

cpp::RwGate &
RepositoryCenter::access_RwGate_Cpp()
{
    pi->bHasCppContent = true;
    return *pi->pGate_Cpp;
}

RepositoryCenter::
CheshireCat::CheshireCat( DYN IdGenerator &   let_drIds )
    :   sName(),
        pStorage(0),
        pStorage_Ifc(0),
        pIdGenerator( &let_drIds ),
        pGate_Cpp(0),
        pGate_Locations(0),
        bHasCppContent(false)
{
    pStorage                = new store::Storage;
    pStorage_Ifc            = new Storage_Ifc( *pStorage );
    pGate_Locations         = new loc::Gate(
                                        pStorage_Ifc->Ifc_Locations(),
                                        *pIdGenerator );
    pGate_Cpp               = new cpp::Gate(
                                        *pStorage_Ifc,
                                        *pIdGenerator,
                                        *pGate_Locations );
}

RepositoryCenter::
CheshireCat::~CheshireCat()
{
}

}   // namespace ary

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS swundo03 (1.51.16); FILE MERGED 2004/08/12 15:11:46 hbrinkm 1.51.16.2: RESYNC: (1.51-1.52); FILE MERGED 2004/08/04 15:07:50 hbrinkm 1.51.16.1: #115575#,#115582#<commit_after><|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef std::vector<file_entry> list_type;

        for (list_type::const_iterator i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(*i);

        return result;
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(fs::path(path));
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>())
#endif
        .def(init<sha1_hash const&>())
        .def(init<char const*, int>())
        .def(init<boost::filesystem::path>())
        .def(init<boost::filesystem::wpath>())

        .def("add_tracker", &torrent_info::add_tracker, (arg("url"), arg("tier")=0))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &torrent_info::hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at, return_internal_reference<>())
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
       .add_property(
            "path"
          , make_getter(
                &file_entry::path, return_value_policy<copy_non_const_reference>()
            )
        )
        .def_readonly("offset", &file_entry::offset)
        .def_readonly("size", &file_entry::size)
        .def_readonly("file_base", &file_entry::file_base)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .def_readwrite("tier", &announce_entry::tier)
        ;
}
<commit_msg>Add torrent_info.rename_file() to the python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef std::vector<file_entry> list_type;

        for (list_type::const_iterator i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(*i);

        return result;
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(fs::path(path));
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>())
#endif
        .def(init<sha1_hash const&>())
        .def(init<char const*, int>())
        .def(init<boost::filesystem::path>())
        .def(init<boost::filesystem::wpath>())

        .def("add_tracker", &torrent_info::add_tracker, (arg("url"), arg("tier")=0))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &torrent_info::hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at, return_internal_reference<>())
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))
        .def("rename_file", &torrent_info::rename_file)

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
       .add_property(
            "path"
          , make_getter(
                &file_entry::path, return_value_policy<copy_non_const_reference>()
            )
        )
        .def_readonly("offset", &file_entry::offset)
        .def_readonly("size", &file_entry::size)
        .def_readonly("file_base", &file_entry::file_base)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .def_readwrite("tier", &announce_entry::tier)
        ;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prtopt.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 11:28:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#include <unomid.h>

using namespace utl;
using namespace rtl;
using namespace ::com::sun::star::uno;

/*--------------------------------------------------------------------
     Beschreibung: Ctor
 --------------------------------------------------------------------*/

Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Content/Graphic",              //  0
        "Content/Table",                //  1
        "Content/Control",              //  2
        "Content/Background",           //  3
        "Content/PrintBlack",           //  4
        "Content/Note",                 //  5
        "Page/Reversed",                //  6
        "Page/Brochure",                //  7
        "Page/BrochureRightToLeft",     //  8
        "Output/SinglePrintJob",        //  9
        "Output/Fax",                   // 10
        "Papertray/FromPrinterSetup",   // 11
        "Content/Drawing",              // 12 not in SW/Web
        "Page/LeftPage",                // 13 not in SW/Web
        "Page/RightPage",               // 14 not in SW/Web
        "EmptyPages"                   // 15 not in SW/Web
    };
    const int nCount = bIsWeb ? 12 : 16;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
    ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") :  C2U("Office.Writer/Print"),
        CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
    bIsWeb(bWeb)
{
    bPrintPageBackground = !bWeb;
    bPrintBlackFont = bWeb;
    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPrintGraphic      = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case  1: bPrintTable            = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  2: bPrintControl      = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case  3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  4: bPrintBlackFont        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  5:
                    {
                        sal_Int32 nTmp;
                        pValues[nProp] >>=  nTmp;
                        nPrintPostIts = (sal_Int16)nTmp;
                    }
                    break;
                    case  6: bPrintReverse      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  7: bPrintProspect      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  8: bPrintProspect_RTL  = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  9: bPrintSingleJobs   = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 10: pValues[nProp] >>= sFaxName;  break;
                    case 11: bPaperFromSetup    = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 12: bPrintDraw         = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case 13: bPrintLeftPage     = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 14: bPrintRightPage        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 15: bPrintEmptyPages       = *(sal_Bool*)pValues[nProp].getValue();  break;
                }
            }
        }
    }
}
/* -----------------------------06.09.00 16:50--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------

 ---------------------------------------------------------------------------*/
void    SwPrintOptions::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();

    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    BOOL bVal;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
            case  1: bVal = bPrintTable         ;pValues[nProp].setValue(&bVal, rType);  break;
            case  2: bVal = bPrintControl        ; pValues[nProp].setValue(&bVal, rType);  break;
            case  3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType);  break;
            case  4: bVal = bPrintBlackFont     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  5: pValues[nProp] <<=  (sal_Int32)nPrintPostIts       ; break;
            case  6: bVal = bPrintReverse       ; pValues[nProp].setValue(&bVal, rType);  break;
            case  7: bVal = bPrintProspect      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  8: bVal = bPrintProspect_RTL      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  9: bVal = bPrintSingleJobs     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 10: pValues[nProp] <<= sFaxName;  break;
            case 11: bVal = bPaperFromSetup     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 12: bVal = bPrintDraw           ; pValues[nProp].setValue(&bVal, rType);  break;
            case 13: bVal = bPrintLeftPage       ; pValues[nProp].setValue(&bVal, rType);  break;
            case 14: bVal = bPrintRightPage     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 15: bVal = bPrintEmptyPages    ; pValues[nProp].setValue(&bVal, rType);  break;
        }
    }
    PutProperties(aNames, aValues);
}

<commit_msg>INTEGRATION: CWS pj86 (1.11.4); FILE MERGED 2007/09/28 21:42:01 pjanik 1.11.4.1: #i81574#: Initialize variable(s) to prevent warnings on Mac OS X with gcc-4.0.1.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prtopt.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-12 16:30:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#include <unomid.h>

using namespace utl;
using namespace rtl;
using namespace ::com::sun::star::uno;

/*--------------------------------------------------------------------
     Beschreibung: Ctor
 --------------------------------------------------------------------*/

Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Content/Graphic",              //  0
        "Content/Table",                //  1
        "Content/Control",              //  2
        "Content/Background",           //  3
        "Content/PrintBlack",           //  4
        "Content/Note",                 //  5
        "Page/Reversed",                //  6
        "Page/Brochure",                //  7
        "Page/BrochureRightToLeft",     //  8
        "Output/SinglePrintJob",        //  9
        "Output/Fax",                   // 10
        "Papertray/FromPrinterSetup",   // 11
        "Content/Drawing",              // 12 not in SW/Web
        "Page/LeftPage",                // 13 not in SW/Web
        "Page/RightPage",               // 14 not in SW/Web
        "EmptyPages"                   // 15 not in SW/Web
    };
    const int nCount = bIsWeb ? 12 : 16;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
    ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") :  C2U("Office.Writer/Print"),
        CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
    bIsWeb(bWeb)
{
    bPrintPageBackground = !bWeb;
    bPrintBlackFont = bWeb;
    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPrintGraphic      = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case  1: bPrintTable            = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  2: bPrintControl      = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case  3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  4: bPrintBlackFont        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  5:
                    {
                        sal_Int32 nTmp = 0;
                        pValues[nProp] >>=  nTmp;
                        nPrintPostIts = (sal_Int16)nTmp;
                    }
                    break;
                    case  6: bPrintReverse      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  7: bPrintProspect      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  8: bPrintProspect_RTL  = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  9: bPrintSingleJobs   = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 10: pValues[nProp] >>= sFaxName;  break;
                    case 11: bPaperFromSetup    = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 12: bPrintDraw         = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case 13: bPrintLeftPage     = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 14: bPrintRightPage        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 15: bPrintEmptyPages       = *(sal_Bool*)pValues[nProp].getValue();  break;
                }
            }
        }
    }
}
/* -----------------------------06.09.00 16:50--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------

 ---------------------------------------------------------------------------*/
void    SwPrintOptions::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();

    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    BOOL bVal;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
            case  1: bVal = bPrintTable         ;pValues[nProp].setValue(&bVal, rType);  break;
            case  2: bVal = bPrintControl        ; pValues[nProp].setValue(&bVal, rType);  break;
            case  3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType);  break;
            case  4: bVal = bPrintBlackFont     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  5: pValues[nProp] <<=  (sal_Int32)nPrintPostIts       ; break;
            case  6: bVal = bPrintReverse       ; pValues[nProp].setValue(&bVal, rType);  break;
            case  7: bVal = bPrintProspect      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  8: bVal = bPrintProspect_RTL      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  9: bVal = bPrintSingleJobs     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 10: pValues[nProp] <<= sFaxName;  break;
            case 11: bVal = bPaperFromSetup     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 12: bVal = bPrintDraw           ; pValues[nProp].setValue(&bVal, rType);  break;
            case 13: bVal = bPrintLeftPage       ; pValues[nProp].setValue(&bVal, rType);  break;
            case 14: bVal = bPrintRightPage     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 15: bVal = bPrintEmptyPages    ; pValues[nProp].setValue(&bVal, rType);  break;
        }
    }
    PutProperties(aNames, aValues);
}

<|endoftext|>


<commit_before><commit_msg>#104515# reduce syntax highlighting in large documents<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.3.1174); FILE MERGED 2005/09/05 13:44:28 rt 1.3.1174.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>


<commit_before><commit_msg>sal_uInt16: to sal_Int32/long, constify, reworked some casts<commit_after><|endoftext|>


<commit_before><commit_msg>Fix filenames on linux being more than 255 bytes (fix #2277)<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Sebastian Ullrich
*/

#include <map>
#include "library/time_task.h"

namespace lean {

static std::map<std::string, second_duration> * g_cum_times;
static mutex * g_cum_times_mutex;

void report_profiling_time(std::string const & category, second_duration time) {
    lock_guard<mutex> _(*g_cum_times_mutex);
    (*g_cum_times)[category] += time;
}

void display_cumulative_profiling_times(std::ostream & out) {
    if (g_cum_times->empty())
        return;
    out << "cumulative profiling times:\n";
    for (auto const & p : *g_cum_times)
        out << "\t" << p.first << " " << display_profiling_time{p.second} << "\n";
}

void initialize_time_task() {
    g_cum_times_mutex = new mutex;
    g_cum_times = new std::map<std::string, second_duration>;
}

void finalize_time_task() {
    delete g_cum_times;
    delete g_cum_times_mutex;
}
}

<commit_msg>chore(library/time_task): style<commit_after>/*
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Sebastian Ullrich
*/
#include <string>
#include <map>
#include "library/time_task.h"

namespace lean {

static std::map<std::string, second_duration> * g_cum_times;
static mutex * g_cum_times_mutex;

void report_profiling_time(std::string const & category, second_duration time) {
    lock_guard<mutex> _(*g_cum_times_mutex);
    (*g_cum_times)[category] += time;
}

void display_cumulative_profiling_times(std::ostream & out) {
    if (g_cum_times->empty())
        return;
    out << "cumulative profiling times:\n";
    for (auto const & p : *g_cum_times)
        out << "\t" << p.first << " " << display_profiling_time{p.second} << "\n";
}

void initialize_time_task() {
    g_cum_times_mutex = new mutex;
    g_cum_times = new std::map<std::string, second_duration>;
}

void finalize_time_task() {
    delete g_cum_times;
    delete g_cum_times_mutex;
}
}
<|endoftext|>


<commit_before><commit_msg>Fix documentation<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed typo<commit_after><|endoftext|>


<commit_before>/*!
 *  Copyright (c) 2016 by Contributors
 * \file saveload_json.cc
 * \brief Save and load graph to/from JSON file.
 */
#include <nnvm/pass.h>
#include <nnvm/pass_functions.h>
#include <dmlc/json.h>
#include <algorithm>

namespace dmlc {
namespace json {
// overload handler for shared ptr
template<>
struct Handler<std::shared_ptr<any> > {
  inline static void Write(JSONWriter *writer, const std::shared_ptr<any> &data) {
    writer->Write(*data);
  }
  inline static void Read(JSONReader *reader, std::shared_ptr<any> *data) {
    any v;
    reader->Read(&v);
    *data = std::make_shared<any>(std::move(v));
  }
};
}  // namespace json
}  // namespace dmlc

namespace nnvm {
namespace pass {
namespace {

// auxiliary node structure for serialization.
struct JSONNode {
  // the node entry structure in serialized format
  struct Entry {
    uint32_t node_id;
    uint32_t index;
    uint32_t version;
    void Save(dmlc::JSONWriter *writer) const {
      writer->BeginArray(false);
      writer->WriteArrayItem(node_id);
      writer->WriteArrayItem(index);
      writer->WriteArrayItem(version);
      writer->EndArray();
    }
    void Load(dmlc::JSONReader *reader) {
      reader->BeginArray();
      CHECK(reader->NextArrayItem()) << "invalid json format";
      reader->Read(&node_id);
      CHECK(reader->NextArrayItem()) << "invalid json format";
      reader->Read(&index);
      if (reader->NextArrayItem()) {
        reader->Read(&version);
        CHECK(!reader->NextArrayItem()) << "invalid json format";
      } else {
        version = 0;
      }
    }
  };

  // pointer to the graph node
  NodePtr node;
  // inputs
  std::vector<Entry> inputs;
  // control flow dependencies
  std::vector<uint32_t> control_deps;

  // function to save JSON node.
  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    if (node->op() != nullptr) {
      writer->WriteObjectKeyValue("op", node->op()->name);
    } else {
      std::string json_null = "null";
      writer->WriteObjectKeyValue("op", json_null);
    }
    writer->WriteObjectKeyValue("name", node->attrs.name);
    if (node->attrs.dict.size() != 0) {
      // write attributes in order;
      std::map<std::string, std::string> dict(
          node->attrs.dict.begin(), node->attrs.dict.end());
      writer->WriteObjectKeyValue("attr", dict);
    }
    writer->WriteObjectKeyValue("inputs", inputs);
    if (control_deps.size() != 0) {
      writer->WriteObjectKeyValue("control_deps", control_deps);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    node = Node::Create();
    control_deps.clear();
    dmlc::JSONObjectReadHelper helper;
    std::string op_type_str;
    helper.DeclareField("op", &op_type_str);
    helper.DeclareField("name", &(node->attrs.name));
    helper.DeclareField("inputs", &inputs);
    helper.DeclareOptionalField("attr", &(node->attrs.dict));
    helper.DeclareOptionalField("control_deps", &control_deps);
    // backward compatible code with mxnet graph.
    int backward_source_id;
    std::unordered_map<std::string, std::string> param;
    helper.DeclareOptionalField("param", &param);
    helper.DeclareOptionalField("backward_source_id", &backward_source_id);
    helper.ReadAllFields(reader);
    node->attrs.dict.insert(param.begin(), param.end());

    if (op_type_str != "null") {
      try {
        node->attrs.op = Op::Get(op_type_str);
      } catch (const dmlc::Error &err) {
        std::ostringstream os;
        os << "Failed loading Op " << node->attrs.name
           << " of type " << op_type_str << ": " << err.what();
        throw dmlc::Error(os.str());
      }
    } else {
      node->attrs.op = nullptr;
    }
  }
};

// graph structure to help read/save JSON.
struct JSONGraph {
  std::vector<JSONNode> nodes;
  std::vector<uint32_t> arg_nodes;
  std::vector<uint32_t> node_row_ptr;
  std::vector<JSONNode::Entry> heads;
  std::unordered_map<std::string, std::shared_ptr<any> > attrs;

  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    writer->WriteObjectKeyValue("nodes", nodes);
    writer->WriteObjectKeyValue("arg_nodes", arg_nodes);
    writer->WriteObjectKeyValue("node_row_ptr", node_row_ptr);
    writer->WriteObjectKeyValue("heads", heads);
    if (attrs.size() != 0) {
      writer->WriteObjectKeyValue("attrs", attrs);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    attrs.clear();
    dmlc::JSONObjectReadHelper helper;
    helper.DeclareField("nodes", &nodes);
    helper.DeclareField("arg_nodes", &arg_nodes);
    helper.DeclareField("heads", &heads);
    helper.DeclareOptionalField("node_row_ptr", &node_row_ptr);
    helper.DeclareOptionalField("attrs", &attrs);
    helper.ReadAllFields(reader);
  }
};

// Load a graph from JSON file.
Graph LoadJSON(Graph src) {
  CHECK_NE(src.attrs.count("json"), 0U)
      << "Load JSON require json to be presented.";
  const std::string &json_str =
      nnvm::get<std::string>(*src.attrs.at("json"));
  bool no_parse = false;
  if (src.attrs.count("load_json_no_parse")) {
    no_parse = nnvm::get<bool>(*src.attrs.at("load_json_no_parse"));
  }
  std::istringstream is(json_str);
  dmlc::JSONReader reader(&is);
  JSONGraph jgraph;
  // load in json graph.
  jgraph.Load(&reader);
  // connects the nodes
  for (JSONNode &n : jgraph.nodes) {
    n.node->inputs.reserve(n.inputs.size());
    for (const JSONNode::Entry &e : n.inputs) {
      n.node->inputs.emplace_back(
          NodeEntry{jgraph.nodes[e.node_id].node, e.index, e.version});
    }
    n.node->control_deps.reserve(n.control_deps.size());
    for (uint32_t nid : n.control_deps) {
      n.node->control_deps.push_back(jgraph.nodes[nid].node);
    }
    // rebuild attribute parser
    if (!no_parse && n.node->op() != nullptr &&
        n.node->op()->attr_parser != nullptr) {
      n.node->op()->attr_parser(&(n.node->attrs));
    }
  }
  // consistent check
  for (uint32_t nid : jgraph.arg_nodes) {
    CHECK(jgraph.nodes[nid].node->is_variable());
  }

  // return the graph
  Graph ret;
  ret.attrs = std::move(jgraph.attrs);
  ret.outputs.reserve(jgraph.heads.size());
  for (const JSONNode::Entry &e : jgraph.heads) {
    ret.outputs.emplace_back(
        NodeEntry{jgraph.nodes[e.node_id].node, e.index, e.version});
  }
  return ret;
}

// save a graph to json
Graph SaveJSON(Graph src) {
  JSONGraph jgraph;
  jgraph.attrs = src.attrs;
  std::unordered_map<Node*, uint32_t> node2index;
  jgraph.node_row_ptr.push_back(0);
  DFSVisit(src.outputs, [&node2index, &jgraph](const NodePtr& n) {
      uint32_t nid = static_cast<uint32_t>(jgraph.nodes.size());
      node2index[n.get()] = nid;
      if (n->is_variable()) {
        jgraph.arg_nodes.push_back(nid);
      }
      JSONNode jnode;
      jnode.node = n;
      jnode.inputs.reserve(n->inputs.size());
      for (const NodeEntry& e : n->inputs) {
        jnode.inputs.emplace_back(
            JSONNode::Entry{node2index.at(e.node.get()), e.index, e.version});
      }
      for (const NodePtr& c : n->control_deps) {
        jnode.control_deps.push_back(node2index.at(c.get()));
      }
      jgraph.node_row_ptr.push_back(
          jgraph.node_row_ptr.back() + n->num_outputs());
      jgraph.nodes.emplace_back(std::move(jnode));
    });

  for (const NodeEntry& e : src.outputs) {
    jgraph.heads.push_back(
        JSONNode::Entry{node2index.at(e.node.get()), e.index, e.version});
  }

  std::ostringstream os;
  dmlc::JSONWriter writer(&os);
  jgraph.Save(&writer);
  Graph ret;
  ret.attrs["json"] = std::make_shared<any>(os.str());
  return ret;
}

// register pass
NNVM_REGISTER_PASS(LoadJSON)
.describe("Return a new Graph, loaded from src.attrs[\"json\"]")
.set_body(LoadJSON)
.set_change_graph(true)
.depend_graph_attr("json");

NNVM_REGISTER_PASS(SaveJSON)
.describe("Return a new empty Graph. Save graph to ret.attrs[\"json\"]")
.set_body(SaveJSON)
.set_change_graph(true)
.provide_graph_attr("json");

DMLC_JSON_ENABLE_ANY(std::string, str);
DMLC_JSON_ENABLE_ANY(std::vector<int>, list_int);

}  // namespace
}  // namespace pass
}  // namespace nnvm
<commit_msg>[JSON] attr->attrs in node attribute, keep backward read compatible (#152)<commit_after>/*!
 *  Copyright (c) 2016 by Contributors
 * \file saveload_json.cc
 * \brief Save and load graph to/from JSON file.
 */
#include <nnvm/pass.h>
#include <nnvm/pass_functions.h>
#include <dmlc/json.h>
#include <algorithm>

namespace dmlc {
namespace json {
// overload handler for shared ptr
template<>
struct Handler<std::shared_ptr<any> > {
  inline static void Write(JSONWriter *writer, const std::shared_ptr<any> &data) {
    writer->Write(*data);
  }
  inline static void Read(JSONReader *reader, std::shared_ptr<any> *data) {
    any v;
    reader->Read(&v);
    *data = std::make_shared<any>(std::move(v));
  }
};
}  // namespace json
}  // namespace dmlc

namespace nnvm {
namespace pass {
namespace {

// auxiliary node structure for serialization.
struct JSONNode {
  // the node entry structure in serialized format
  struct Entry {
    uint32_t node_id;
    uint32_t index;
    uint32_t version;
    void Save(dmlc::JSONWriter *writer) const {
      writer->BeginArray(false);
      writer->WriteArrayItem(node_id);
      writer->WriteArrayItem(index);
      writer->WriteArrayItem(version);
      writer->EndArray();
    }
    void Load(dmlc::JSONReader *reader) {
      reader->BeginArray();
      CHECK(reader->NextArrayItem()) << "invalid json format";
      reader->Read(&node_id);
      CHECK(reader->NextArrayItem()) << "invalid json format";
      reader->Read(&index);
      if (reader->NextArrayItem()) {
        reader->Read(&version);
        CHECK(!reader->NextArrayItem()) << "invalid json format";
      } else {
        version = 0;
      }
    }
  };

  // pointer to the graph node
  NodePtr node;
  // inputs
  std::vector<Entry> inputs;
  // control flow dependencies
  std::vector<uint32_t> control_deps;

  // function to save JSON node.
  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    if (node->op() != nullptr) {
      writer->WriteObjectKeyValue("op", node->op()->name);
    } else {
      std::string json_null = "null";
      writer->WriteObjectKeyValue("op", json_null);
    }
    writer->WriteObjectKeyValue("name", node->attrs.name);
    if (node->attrs.dict.size() != 0) {
      // write attributes in order;
      std::map<std::string, std::string> dict(
          node->attrs.dict.begin(), node->attrs.dict.end());
      writer->WriteObjectKeyValue("attrs", dict);
    }
    writer->WriteObjectKeyValue("inputs", inputs);
    if (control_deps.size() != 0) {
      writer->WriteObjectKeyValue("control_deps", control_deps);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    node = Node::Create();
    control_deps.clear();
    dmlc::JSONObjectReadHelper helper;
    std::string op_type_str;
    helper.DeclareField("op", &op_type_str);
    helper.DeclareField("name", &(node->attrs.name));
    helper.DeclareField("inputs", &inputs);
    helper.DeclareOptionalField("attrs", &(node->attrs.dict));
    helper.DeclareOptionalField("attr", &(node->attrs.dict));
    helper.DeclareOptionalField("control_deps", &control_deps);
    // backward compatible code with mxnet graph.
    int backward_source_id;
    std::unordered_map<std::string, std::string> param;
    helper.DeclareOptionalField("param", &param);
    helper.DeclareOptionalField("backward_source_id", &backward_source_id);
    helper.ReadAllFields(reader);
    node->attrs.dict.insert(param.begin(), param.end());

    if (op_type_str != "null") {
      try {
        node->attrs.op = Op::Get(op_type_str);
      } catch (const dmlc::Error &err) {
        std::ostringstream os;
        os << "Failed loading Op " << node->attrs.name
           << " of type " << op_type_str << ": " << err.what();
        throw dmlc::Error(os.str());
      }
    } else {
      node->attrs.op = nullptr;
    }
  }
};

// graph structure to help read/save JSON.
struct JSONGraph {
  std::vector<JSONNode> nodes;
  std::vector<uint32_t> arg_nodes;
  std::vector<uint32_t> node_row_ptr;
  std::vector<JSONNode::Entry> heads;
  std::unordered_map<std::string, std::shared_ptr<any> > attrs;

  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    writer->WriteObjectKeyValue("nodes", nodes);
    writer->WriteObjectKeyValue("arg_nodes", arg_nodes);
    writer->WriteObjectKeyValue("node_row_ptr", node_row_ptr);
    writer->WriteObjectKeyValue("heads", heads);
    if (attrs.size() != 0) {
      writer->WriteObjectKeyValue("attrs", attrs);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    attrs.clear();
    dmlc::JSONObjectReadHelper helper;
    helper.DeclareField("nodes", &nodes);
    helper.DeclareField("arg_nodes", &arg_nodes);
    helper.DeclareField("heads", &heads);
    helper.DeclareOptionalField("node_row_ptr", &node_row_ptr);
    helper.DeclareOptionalField("attrs", &attrs);
    helper.ReadAllFields(reader);
  }
};

// Load a graph from JSON file.
Graph LoadJSON(Graph src) {
  CHECK_NE(src.attrs.count("json"), 0U)
      << "Load JSON require json to be presented.";
  const std::string &json_str =
      nnvm::get<std::string>(*src.attrs.at("json"));
  bool no_parse = false;
  if (src.attrs.count("load_json_no_parse")) {
    no_parse = nnvm::get<bool>(*src.attrs.at("load_json_no_parse"));
  }
  std::istringstream is(json_str);
  dmlc::JSONReader reader(&is);
  JSONGraph jgraph;
  // load in json graph.
  jgraph.Load(&reader);
  // connects the nodes
  for (JSONNode &n : jgraph.nodes) {
    n.node->inputs.reserve(n.inputs.size());
    for (const JSONNode::Entry &e : n.inputs) {
      n.node->inputs.emplace_back(
          NodeEntry{jgraph.nodes[e.node_id].node, e.index, e.version});
    }
    n.node->control_deps.reserve(n.control_deps.size());
    for (uint32_t nid : n.control_deps) {
      n.node->control_deps.push_back(jgraph.nodes[nid].node);
    }
    // rebuild attribute parser
    if (!no_parse && n.node->op() != nullptr &&
        n.node->op()->attr_parser != nullptr) {
      n.node->op()->attr_parser(&(n.node->attrs));
    }
  }
  // consistent check
  for (uint32_t nid : jgraph.arg_nodes) {
    CHECK(jgraph.nodes[nid].node->is_variable());
  }

  // return the graph
  Graph ret;
  ret.attrs = std::move(jgraph.attrs);
  ret.outputs.reserve(jgraph.heads.size());
  for (const JSONNode::Entry &e : jgraph.heads) {
    ret.outputs.emplace_back(
        NodeEntry{jgraph.nodes[e.node_id].node, e.index, e.version});
  }
  return ret;
}

// save a graph to json
Graph SaveJSON(Graph src) {
  JSONGraph jgraph;
  jgraph.attrs = src.attrs;
  std::unordered_map<Node*, uint32_t> node2index;
  jgraph.node_row_ptr.push_back(0);
  DFSVisit(src.outputs, [&node2index, &jgraph](const NodePtr& n) {
      uint32_t nid = static_cast<uint32_t>(jgraph.nodes.size());
      node2index[n.get()] = nid;
      if (n->is_variable()) {
        jgraph.arg_nodes.push_back(nid);
      }
      JSONNode jnode;
      jnode.node = n;
      jnode.inputs.reserve(n->inputs.size());
      for (const NodeEntry& e : n->inputs) {
        jnode.inputs.emplace_back(
            JSONNode::Entry{node2index.at(e.node.get()), e.index, e.version});
      }
      for (const NodePtr& c : n->control_deps) {
        jnode.control_deps.push_back(node2index.at(c.get()));
      }
      jgraph.node_row_ptr.push_back(
          jgraph.node_row_ptr.back() + n->num_outputs());
      jgraph.nodes.emplace_back(std::move(jnode));
    });

  for (const NodeEntry& e : src.outputs) {
    jgraph.heads.push_back(
        JSONNode::Entry{node2index.at(e.node.get()), e.index, e.version});
  }

  std::ostringstream os;
  dmlc::JSONWriter writer(&os);
  jgraph.Save(&writer);
  Graph ret;
  ret.attrs["json"] = std::make_shared<any>(os.str());
  return ret;
}

// register pass
NNVM_REGISTER_PASS(LoadJSON)
.describe("Return a new Graph, loaded from src.attrs[\"json\"]")
.set_body(LoadJSON)
.set_change_graph(true)
.depend_graph_attr("json");

NNVM_REGISTER_PASS(SaveJSON)
.describe("Return a new empty Graph. Save graph to ret.attrs[\"json\"]")
.set_body(SaveJSON)
.set_change_graph(true)
.provide_graph_attr("json");

DMLC_JSON_ENABLE_ANY(std::string, str);
DMLC_JSON_ENABLE_ANY(std::vector<int>, list_int);
DMLC_JSON_ENABLE_ANY(std::vector<std::string>, list_str);

}  // namespace
}  // namespace pass
}  // namespace nnvm
<|endoftext|>


<commit_before><commit_msg>Adicionado botão de créditos e correção do alinhamento<commit_after><|endoftext|>


<commit_before><commit_msg>Include header file (typo)<commit_after><|endoftext|>


<commit_before>//
// RemoteConsole is an implementation of IConsole which spawns and communicates
// with a second ccons process for handling the user input.
//
// SerializedOutputConsole is used by the ccons process spawned by RemoteConsole
// to send its output in a serialized format.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include "RemoteConsole.h"

#include <iostream>
#include <sstream>
#include <signal.h>

#include <llvm/ADT/StringExtras.h>

#include "popen2.h"

using std::string;

namespace ccons {

//
// Private Classes
//

namespace {

class SerializedConsoleOutput {

public:

	SerializedConsoleOutput();
	SerializedConsoleOutput(const std::string& output,
	                        const std::string& error,
	                        const std::string& prompt,
	                        const std::string& input);

	bool readFromStream(FILE *stream);
	void writeToString(std::string *str) const;

	const std::string& output() const;
	const std::string& error() const;
	const std::string& prompt() const;
	const std::string& input() const;

private:

	std::string _output;
	std::string _error;
	std::string _prompt;
	std::string _input;

	static bool readEscapedString(FILE *stream, std::string *str);

};

/// UnescapeString - Modify the argument string, turning two character sequences
/// @verbatim
/// like '\\' 'n' into '\n'.  This handles: \e \a \b \f \n \r \t \v \' \ and
/// \num (where num is a 1-3 byte octal value).
/// @endverbatim
void UnescapeString(std::string &Str) {
  for (unsigned i = 0; i != Str.size(); ++i) {
    if (Str[i] == '\\' && i != Str.size()-1) {
      switch (Str[i+1]) {
      default: continue;  // Don't execute the code after the switch.
      case 'a': Str[i] = '\a'; break;
      case 'b': Str[i] = '\b'; break;
      case 'e': Str[i] = 27; break;
      case 'f': Str[i] = '\f'; break;
      case 'n': Str[i] = '\n'; break;
      case 'r': Str[i] = '\r'; break;
      case 't': Str[i] = '\t'; break;
      case 'v': Str[i] = '\v'; break;
      case '"': Str[i] = '\"'; break;
      case '\'': Str[i] = '\''; break;
      case '\\': Str[i] = '\\'; break;
      }
      // Nuke the second character.
      Str.erase(Str.begin()+i+1);
    }
  }
}

/// EscapeString - Modify the argument string, turning '\\' and anything that
/// doesn't satisfy std::isprint into an escape sequence.
void EscapeString(std::string &Str) {
  for (unsigned i = 0; i != Str.size(); ++i) {
    if (Str[i] == '\\') {
      ++i;
      Str.insert(Str.begin()+i, '\\');
    } else if (Str[i] == '\t') {
      Str[i++] = '\\';
      Str.insert(Str.begin()+i, 't');
    } else if (Str[i] == '"') {
      Str.insert(Str.begin()+i++, '\\');
    } else if (Str[i] == '\n') {
      Str[i++] = '\\';
      Str.insert(Str.begin()+i, 'n');
    } else if (!std::isprint(Str[i])) {
      // Always expand to a 3-digit octal escape.
      unsigned Char = Str[i];
      Str[i++] = '\\';
      Str.insert(Str.begin()+i++, '0'+((Char/64) & 7));
      Str.insert(Str.begin()+i++, '0'+((Char/8)  & 7));
      Str.insert(Str.begin()+i  , '0'+( Char     & 7));
    }
  }
}

} // anon namespace

//
// C callback functions
//

void gotsig(int signo)
{
	string str = strsignal(signo);
	str += "\n";
	SerializedConsoleOutput sco("", str, "", "");
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
	exit(-1);
}

void goodbye(void)
{
	string str;
	SerializedConsoleOutput sco("", "", "", "");
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
}

//
// SerializedConsoleOutput
//

SerializedConsoleOutput::SerializedConsoleOutput()
{
}

SerializedConsoleOutput::SerializedConsoleOutput(const std::string& output,
                                                 const std::string& error,
                                                 const std::string& prompt,
                                                 const std::string& input)
	: _output(output)
	, _error(error)
	, _prompt(prompt)
	, _input(input)
{
}

bool SerializedConsoleOutput::readEscapedString(FILE *stream, std::string *str)
{
	char buf[1024];
	if (fgets(buf, sizeof(buf), stream)) {
		buf[strlen(buf) - 1] = '\0';
		*str = buf;
		UnescapeString(*str);
		return true;
	}
	return false;
}

bool SerializedConsoleOutput::readFromStream(FILE *stream)
{
	return readEscapedString(stream, &_output) &&
	       readEscapedString(stream, &_error) &&
	       readEscapedString(stream, &_prompt) &&
	       readEscapedString(stream, &_input);
}

void SerializedConsoleOutput::writeToString(std::string *str) const
{
	std::stringstream ss;
	string temp;
	temp = _output;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _error;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _prompt;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _input;
	EscapeString(temp);
	ss << temp << "\n";
	*str = ss.str();
}

const std::string& SerializedConsoleOutput::output() const
{
	return _output;
}

const std::string& SerializedConsoleOutput::error() const
{
	return _error;
}

const std::string& SerializedConsoleOutput::prompt() const
{
	return _prompt;
}

const std::string& SerializedConsoleOutput::input() const
{
	return _input;
}

//
// RemoteConsole
//

RemoteConsole::RemoteConsole(bool DebugMode) :
	_DebugMode(DebugMode)
{
	signal(SIGCHLD, SIG_IGN);
	reset();
}

RemoteConsole::~RemoteConsole()
{
	cleanup();
}

void RemoteConsole::cleanup()
{
	if (_ostream) {
		fclose(_ostream);
		_ostream = NULL;
	}
	if (_istream) {
		fclose(_istream);
		_istream = NULL;
	}
}

void RemoteConsole::reset()
{
	// TODO: check for errors!
	int infp, outfp;
	if (_DebugMode)
		popen2("./ccons --ccons-debug --ccons-use-std-io --ccons-serialized-output", &infp, &outfp);
	else
		popen2("./ccons --ccons-use-std-io --ccons-serialized-output", &infp, &outfp);
	_ostream = fdopen(infp, "w");
	setlinebuf(_ostream);
	_istream = fdopen(outfp, "r");
	setlinebuf(_istream);
	_prompt = ">>> ";
	_input = "";
}

const char * RemoteConsole::prompt() const
{
	return _prompt.c_str();
}

const char * RemoteConsole::input() const
{
	return _input.c_str();
}

void RemoteConsole::process(const char *line)
{
	fputs(line, _ostream);

	SerializedConsoleOutput sco;
	bool success = sco.readFromStream(_istream);
	if (success) {
		if (sco.prompt().empty() && sco.output().empty() && sco.error().empty())
			exit(0);
		std::cout << sco.output();
		std::cerr << sco.error();
	}

	if (!success || sco.prompt().empty()) {
		cleanup();
		reset();
		std::cout << "\nNOTE: Interpreter restarted.\n";
		return;
	}

	_prompt = sco.prompt();
	_input = sco.input();
}

//
// SerializedOutputConsole
//

SerializedOutputConsole::SerializedOutputConsole(bool DebugMode)
	: _console(new Console(DebugMode, _ss_out, _ss_err))
	, _tmp_out(tmpfile())
	, _tmp_err(tmpfile())
{
	signal(SIGBUS, gotsig);
	signal(SIGSEGV, gotsig);
	signal(SIGABRT, gotsig);
	signal(SIGTRAP, gotsig);
	signal(SIGILL, gotsig);
	signal(SIGFPE, gotsig);
	signal(SIGSYS, gotsig);
	signal(SIGXCPU, gotsig);
	signal(SIGXFSZ, gotsig);
	atexit(goodbye);
}

SerializedOutputConsole::~SerializedOutputConsole()
{
}

const char * SerializedOutputConsole::prompt() const
{
	return _console->prompt();
}

const char * SerializedOutputConsole::input() const
{
	return _console->input();
}

namespace {

class StreamInterceptor {

public:

	StreamInterceptor(FILE **stream, FILE *tmp_file)
		: _stream(stream)
		, _orig_stream(*stream)
		, _tmp_file(tmp_file)
	{
		rewind(_tmp_file);
		ftruncate(fileno(_tmp_file), 0);
		*_stream = _tmp_file;
	}

	void getInterceptedOutput(std::stringstream& ss_out) {
		char buf[16 * 1024];
		*buf = '\0';
		rewind(_tmp_file);
		size_t nread = fread(buf, 1, sizeof(buf), _tmp_file);
		buf[nread] = '\0';
		ss_out << buf;
		*_stream = _orig_stream;
	}

private:

	FILE **_stream;
	FILE *_orig_stream;
	FILE *_tmp_file;

};

} // anon namespace

void SerializedOutputConsole::process(const char *line)
{
	_ss_out.str("");
	_ss_err.str("");
	StreamInterceptor iout(&stdout, _tmp_out);
	StreamInterceptor ierr(&stderr, _tmp_err);
	_console->process(line);
	iout.getInterceptedOutput(_ss_out);
	ierr.getInterceptedOutput(_ss_err);
	string str;
	SerializedConsoleOutput sco(_ss_out.str(),
	                            _ss_err.str(),
	                            _console->prompt(),
	                            _console->input());
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
}

} // namespace ccons
<commit_msg>remove unused include<commit_after>//
// RemoteConsole is an implementation of IConsole which spawns and communicates
// with a second ccons process for handling the user input.
//
// SerializedOutputConsole is used by the ccons process spawned by RemoteConsole
// to send its output in a serialized format.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include "RemoteConsole.h"

#include <iostream>
#include <sstream>
#include <signal.h>

#include "popen2.h"

using std::string;

namespace ccons {

//
// Private Classes
//

namespace {

class SerializedConsoleOutput {

public:

	SerializedConsoleOutput();
	SerializedConsoleOutput(const std::string& output,
	                        const std::string& error,
	                        const std::string& prompt,
	                        const std::string& input);

	bool readFromStream(FILE *stream);
	void writeToString(std::string *str) const;

	const std::string& output() const;
	const std::string& error() const;
	const std::string& prompt() const;
	const std::string& input() const;

private:

	std::string _output;
	std::string _error;
	std::string _prompt;
	std::string _input;

	static bool readEscapedString(FILE *stream, std::string *str);

};

/// UnescapeString - Modify the argument string, turning two character sequences
/// @verbatim
/// like '\\' 'n' into '\n'.  This handles: \e \a \b \f \n \r \t \v \' \ and
/// \num (where num is a 1-3 byte octal value).
/// @endverbatim
void UnescapeString(std::string &Str) {
  for (unsigned i = 0; i != Str.size(); ++i) {
    if (Str[i] == '\\' && i != Str.size()-1) {
      switch (Str[i+1]) {
      default: continue;  // Don't execute the code after the switch.
      case 'a': Str[i] = '\a'; break;
      case 'b': Str[i] = '\b'; break;
      case 'e': Str[i] = 27; break;
      case 'f': Str[i] = '\f'; break;
      case 'n': Str[i] = '\n'; break;
      case 'r': Str[i] = '\r'; break;
      case 't': Str[i] = '\t'; break;
      case 'v': Str[i] = '\v'; break;
      case '"': Str[i] = '\"'; break;
      case '\'': Str[i] = '\''; break;
      case '\\': Str[i] = '\\'; break;
      }
      // Nuke the second character.
      Str.erase(Str.begin()+i+1);
    }
  }
}

/// EscapeString - Modify the argument string, turning '\\' and anything that
/// doesn't satisfy std::isprint into an escape sequence.
void EscapeString(std::string &Str) {
  for (unsigned i = 0; i != Str.size(); ++i) {
    if (Str[i] == '\\') {
      ++i;
      Str.insert(Str.begin()+i, '\\');
    } else if (Str[i] == '\t') {
      Str[i++] = '\\';
      Str.insert(Str.begin()+i, 't');
    } else if (Str[i] == '"') {
      Str.insert(Str.begin()+i++, '\\');
    } else if (Str[i] == '\n') {
      Str[i++] = '\\';
      Str.insert(Str.begin()+i, 'n');
    } else if (!std::isprint(Str[i])) {
      // Always expand to a 3-digit octal escape.
      unsigned Char = Str[i];
      Str[i++] = '\\';
      Str.insert(Str.begin()+i++, '0'+((Char/64) & 7));
      Str.insert(Str.begin()+i++, '0'+((Char/8)  & 7));
      Str.insert(Str.begin()+i  , '0'+( Char     & 7));
    }
  }
}

} // anon namespace

//
// C callback functions
//

void gotsig(int signo)
{
	string str = strsignal(signo);
	str += "\n";
	SerializedConsoleOutput sco("", str, "", "");
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
	exit(-1);
}

void goodbye(void)
{
	string str;
	SerializedConsoleOutput sco("", "", "", "");
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
}

//
// SerializedConsoleOutput
//

SerializedConsoleOutput::SerializedConsoleOutput()
{
}

SerializedConsoleOutput::SerializedConsoleOutput(const std::string& output,
                                                 const std::string& error,
                                                 const std::string& prompt,
                                                 const std::string& input)
	: _output(output)
	, _error(error)
	, _prompt(prompt)
	, _input(input)
{
}

bool SerializedConsoleOutput::readEscapedString(FILE *stream, std::string *str)
{
	char buf[1024];
	if (fgets(buf, sizeof(buf), stream)) {
		buf[strlen(buf) - 1] = '\0';
		*str = buf;
		UnescapeString(*str);
		return true;
	}
	return false;
}

bool SerializedConsoleOutput::readFromStream(FILE *stream)
{
	return readEscapedString(stream, &_output) &&
	       readEscapedString(stream, &_error) &&
	       readEscapedString(stream, &_prompt) &&
	       readEscapedString(stream, &_input);
}

void SerializedConsoleOutput::writeToString(std::string *str) const
{
	std::stringstream ss;
	string temp;
	temp = _output;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _error;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _prompt;
	EscapeString(temp);
	ss << temp << "\n";
	temp = _input;
	EscapeString(temp);
	ss << temp << "\n";
	*str = ss.str();
}

const std::string& SerializedConsoleOutput::output() const
{
	return _output;
}

const std::string& SerializedConsoleOutput::error() const
{
	return _error;
}

const std::string& SerializedConsoleOutput::prompt() const
{
	return _prompt;
}

const std::string& SerializedConsoleOutput::input() const
{
	return _input;
}

//
// RemoteConsole
//

RemoteConsole::RemoteConsole(bool DebugMode) :
	_DebugMode(DebugMode)
{
	signal(SIGCHLD, SIG_IGN);
	reset();
}

RemoteConsole::~RemoteConsole()
{
	cleanup();
}

void RemoteConsole::cleanup()
{
	if (_ostream) {
		fclose(_ostream);
		_ostream = NULL;
	}
	if (_istream) {
		fclose(_istream);
		_istream = NULL;
	}
}

void RemoteConsole::reset()
{
	// TODO: check for errors!
	int infp, outfp;
	if (_DebugMode)
		popen2("./ccons --ccons-debug --ccons-use-std-io --ccons-serialized-output", &infp, &outfp);
	else
		popen2("./ccons --ccons-use-std-io --ccons-serialized-output", &infp, &outfp);
	_ostream = fdopen(infp, "w");
	setlinebuf(_ostream);
	_istream = fdopen(outfp, "r");
	setlinebuf(_istream);
	_prompt = ">>> ";
	_input = "";
}

const char * RemoteConsole::prompt() const
{
	return _prompt.c_str();
}

const char * RemoteConsole::input() const
{
	return _input.c_str();
}

void RemoteConsole::process(const char *line)
{
	fputs(line, _ostream);

	SerializedConsoleOutput sco;
	bool success = sco.readFromStream(_istream);
	if (success) {
		if (sco.prompt().empty() && sco.output().empty() && sco.error().empty())
			exit(0);
		std::cout << sco.output();
		std::cerr << sco.error();
	}

	if (!success || sco.prompt().empty()) {
		cleanup();
		reset();
		std::cout << "\nNOTE: Interpreter restarted.\n";
		return;
	}

	_prompt = sco.prompt();
	_input = sco.input();
}

//
// SerializedOutputConsole
//

SerializedOutputConsole::SerializedOutputConsole(bool DebugMode)
	: _console(new Console(DebugMode, _ss_out, _ss_err))
	, _tmp_out(tmpfile())
	, _tmp_err(tmpfile())
{
	signal(SIGBUS, gotsig);
	signal(SIGSEGV, gotsig);
	signal(SIGABRT, gotsig);
	signal(SIGTRAP, gotsig);
	signal(SIGILL, gotsig);
	signal(SIGFPE, gotsig);
	signal(SIGSYS, gotsig);
	signal(SIGXCPU, gotsig);
	signal(SIGXFSZ, gotsig);
	atexit(goodbye);
}

SerializedOutputConsole::~SerializedOutputConsole()
{
}

const char * SerializedOutputConsole::prompt() const
{
	return _console->prompt();
}

const char * SerializedOutputConsole::input() const
{
	return _console->input();
}

namespace {

class StreamInterceptor {

public:

	StreamInterceptor(FILE **stream, FILE *tmp_file)
		: _stream(stream)
		, _orig_stream(*stream)
		, _tmp_file(tmp_file)
	{
		rewind(_tmp_file);
		ftruncate(fileno(_tmp_file), 0);
		*_stream = _tmp_file;
	}

	void getInterceptedOutput(std::stringstream& ss_out) {
		char buf[16 * 1024];
		*buf = '\0';
		rewind(_tmp_file);
		size_t nread = fread(buf, 1, sizeof(buf), _tmp_file);
		buf[nread] = '\0';
		ss_out << buf;
		*_stream = _orig_stream;
	}

private:

	FILE **_stream;
	FILE *_orig_stream;
	FILE *_tmp_file;

};

} // anon namespace

void SerializedOutputConsole::process(const char *line)
{
	_ss_out.str("");
	_ss_err.str("");
	StreamInterceptor iout(&stdout, _tmp_out);
	StreamInterceptor ierr(&stderr, _tmp_err);
	_console->process(line);
	iout.getInterceptedOutput(_ss_out);
	ierr.getInterceptedOutput(_ss_err);
	string str;
	SerializedConsoleOutput sco(_ss_out.str(),
	                            _ss_err.str(),
	                            _console->prompt(),
	                            _console->input());
	sco.writeToString(&str);
	std::cout << str;
	std::cout.flush();
}

} // namespace ccons
<|endoftext|>