<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define MY_PARAM_TYPE(name, DType, MType) \
    struct name { \
        typedef DType DataType; \
        typedef MType MassType; \
    }; \

#include "Sofa_test.h"

#include <SofaComponentMain/init.h>

//Including Simulation
#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/graph/DAGSimulation.h>
#include <sofa/simulation/common/Node.h>
#include <SceneCreator/SceneCreator.h>

#include <SofaBaseMechanics/DiagonalMass.h>
#include <SofaBaseTopology/HexahedronSetTopologyContainer.h>
#include <SofaBaseTopology/HexahedronSetGeometryAlgorithms.h>
#include <SofaBaseMechanics/MechanicalObject.h>

//TODO : Perform smart tests :) Infrastructure for multi templated tests is ok.

namespace sofa {

template <class T>
class DiagonalMass_test : public ::testing::Test
{
public :

    typedef typename T::DataType dt;
    typedef typename T::MassType mt;
    typedef typename dt::Coord       Coord;
    typedef typename dt::VecCoord    VecCoord;
    typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType;
    typename DiagonalMassType::SPtr m;

    /// Root of the scene graph
    sofa::simulation::Node::SPtr root;
    /// Simulation
    sofa::simulation::Simulation* simulation;

    /**
     * Constructor call for each test
     */
    virtual void SetUp()
    {
        // Init simulation
        sofa::component::init();
        sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation());

        root = simulation::getSimulation()->createNewGraph("root");
    }

    void createSceneHexa()
    {
        simulation::Node::SPtr oneHexa = root->createChild("oneHexa");

        sofa::component::topology::HexahedronSetTopologyContainer::SPtr container = sofa::modeling::addNew<sofa::component::topology::HexahedronSetTopologyContainer>(oneHexa, "container");
        container->addHexa(0,1,2,3,4,5,6,7);
        typename sofa::component::topology::HexahedronSetGeometryAlgorithms<dt>::SPtr algo = sofa::modeling::addNew<sofa::component::topology::HexahedronSetGeometryAlgorithms<dt> >(oneHexa);
        typename sofa::component::container::MechanicalObject<dt>::SPtr meca= sofa::modeling::addNew<sofa::component::container::MechanicalObject<dt> >(oneHexa);
        VecCoord pos;
        pos.push_back(Coord(0.0, 0.0, 0.0));
        pos.push_back(Coord(1.0, 0.0, 0.0));
        pos.push_back(Coord(1.0, 1.0, 0.0));
        pos.push_back(Coord(0.0, 1.0, 0.0));
        pos.push_back(Coord(0.0, 0.0, 1.0));
        pos.push_back(Coord(1.0, 0.0, 1.0));
        pos.push_back(Coord(1.0, 1.0, 1.0));
        pos.push_back(Coord(0.0, 1.0, 1.0));
        meca->x = pos;

        typename sofa::component::mass::DiagonalMass<dt,mt>::SPtr mass = sofa::modeling::addNew<sofa::component::mass::DiagonalMass<dt,mt> >(oneHexa);
    }

    bool testHexaMass()
    {
        //initialize the simulation
        sofa::simulation::getSimulation()->init(root.get());

        //get the node called "oneHexa"
        simulation::Node *node = root->getChild("oneHexa");

        //the node is supposed to be found
        if (!node)
        {
            ADD_FAILURE() << "Cannot find first node" << std::endl;
            return false;
        }

        //get the mass
        sofa::component::mass::DiagonalMass<dt,mt> *mass = node->get<sofa::component::mass::DiagonalMass<dt,mt> >(node->SearchDown);
        if (!mass)
        {
            ADD_FAILURE() << "Cannot find mass" << std::endl;
            return false;
        }

        //get the mechanical object
        typename sofa::component::container::MechanicalObject<dt> *meca = node->get<sofa::component::container::MechanicalObject<dt> >(node->SearchDown);
        if (!meca)
        {
            ADD_FAILURE() << "Cannot find mechanical object" << std::endl;
            return false;
        }

        //test the number of mass points
        if (meca->x.getValue().size() != mass->f_mass.getValue().size())
        {
            ADD_FAILURE() << "Mass vector has not the same size as the number of points (" << mass->f_mass.getValue().size() << "!="<< meca->x.getValue().size() << ")" << std::endl;
            return false;
        }

        //check if the total mass is correct
        if ( fabs(1.0 - mass->m_totalMass.getValue()) > 1e-6)
        {
            ADD_FAILURE() << "Not the expected total mass: " << mass->m_totalMass << " and should be 1" << std::endl;
            return false;
        }

        return true;
    }

    void TearDown()
    {
        if (root!=NULL)
            sofa::simulation::getSimulation()->unload(root);
    }
};

TYPED_TEST_CASE_P(DiagonalMass_test);

TYPED_TEST_P(DiagonalMass_test, testHexahedra)
{
    this->createSceneHexa();
    ASSERT_TRUE(this->testHexaMass());
}

REGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, testHexahedra);

#ifndef SOFA_FLOAT

MY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double)
MY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double)
MY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double)

INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_hexa_test_case3d, DiagonalMass_test, Vec3dd);

//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1d, DiagonalMass_test, Vec3dd);
//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2d, DiagonalMass_test, Vec2dd);
//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3d, DiagonalMass_test, Vec1dd);

#endif

#ifndef SOFA_DOUBLE

MY_PARAM_TYPE(Vec3ff, sofa::defaulttype::Vec3fTypes, float)
MY_PARAM_TYPE(Vec2ff, sofa::defaulttype::Vec2fTypes, float)
MY_PARAM_TYPE(Vec1ff, sofa::defaulttype::Vec1fTypes, float)

INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_hexa_test_case3f, DiagonalMass_test, Vec3ff);

//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1f, DiagonalMass_test, Vec3ff);
//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2f, DiagonalMass_test, Vec2ff);
//INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3f, DiagonalMass_test, Vec1ff);

#endif

} // namespace sofa
<commit_msg>SofaBaseMechanics: clean up tests for DiagonalMass<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "Sofa_test.h"

#include <SofaComponentMain/init.h>

#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/graph/DAGSimulation.h>
#include <sofa/simulation/common/Node.h>

#include <SofaBaseMechanics/DiagonalMass.h>
#include <SofaBaseMechanics/MechanicalObject.h>
#include <SofaBaseTopology/HexahedronSetTopologyContainer.h>
#include <SofaBaseTopology/HexahedronSetGeometryAlgorithms.h>

using namespace sofa::defaulttype;
using namespace sofa::component::topology;

using sofa::core::objectmodel::New;
using sofa::component::mass::DiagonalMass;
using sofa::component::container::MechanicalObject;

namespace sofa {

template <class T>
class DiagonalMass_test : public ::testing::Test
{
public:
    simulation::Node::SPtr root;
    simulation::Simulation* simulation;

    virtual void SetUp()
    {
        component::init();
        simulation::setSimulation(simulation = new simulation::graph::DAGSimulation());
        root = simulation::getSimulation()->createNewGraph("root");
    }

    void TearDown()
    {
        if (root!=NULL)
            simulation::getSimulation()->unload(root);
    }
};

// Define the list of DataTypes to instanciate the tests with.
using testing::Types;
typedef Types<
#if defined(SOFA_FLOAT)
    Vec3fTypes
#elif defined(SOFA_DOUBLE)
    Vec3dTypes
#else
    Vec3fTypes,
    Vec3dTypes
#endif
> DataTypes;

// Instanciate the test suite for each type in 'DataTypes'.
TYPED_TEST_CASE(DiagonalMass_test, DataTypes);

TYPED_TEST(DiagonalMass_test, singleHexahedron)
{
    typedef TypeParam DataTypes;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::VecCoord VecCoord;
    typedef MechanicalObject<DataTypes> MechanicalObject;
    typedef DiagonalMass<DataTypes, typename DataTypes::Real> DiagonalMass;

    // Create the scene graph.
    simulation::Node::SPtr node = this->root->createChild("oneHexa");
    HexahedronSetTopologyContainer::SPtr container = New<HexahedronSetTopologyContainer>();
    node->addObject(container);
    typename MechanicalObject::SPtr mstate = New<MechanicalObject>();
    node->addObject(mstate);
    node->addObject(New<HexahedronSetGeometryAlgorithms<DataTypes> >());
    typename DiagonalMass::SPtr mass = New<DiagonalMass>();
    node->addObject(mass);

    // Handcraft a cubic hexahedron.
    VecCoord pos;
    pos.push_back(Coord(0.0, 0.0, 0.0));
    pos.push_back(Coord(1.0, 0.0, 0.0));
    pos.push_back(Coord(1.0, 1.0, 0.0));
    pos.push_back(Coord(0.0, 1.0, 0.0));
    pos.push_back(Coord(0.0, 0.0, 1.0));
    pos.push_back(Coord(1.0, 0.0, 1.0));
    pos.push_back(Coord(1.0, 1.0, 1.0));
    pos.push_back(Coord(0.0, 1.0, 1.0));
    mstate->x = pos;
    container->addHexa(0,1,2,3,4,5,6,7);

    // DiagonalMass computes the mass in reinit(), so init() the graph.
    simulation::getSimulation()->init(this->root.get());

    // Check that the mass vector has the right size.
    ASSERT_EQ(mstate->x.getValue().size(), mass->f_mass.getValue().size());

    // Check the mass at each index.
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[0]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[1]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[2]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[3]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[4]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[5]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[6]);
    EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[7]);

    // Check the total mass.
    EXPECT_FLOAT_EQ(mass->m_totalMass.getValue(), 1.0);
}

} // namespace sofa
<|endoftext|>


<commit_before>#include <sstream>
#include <algorithm>
#include <set>
#include <memory>
#include <dlfcn.h>

#include "plugin-loader.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/output.hpp"
#include "../core/wm.hpp"
#include "wayfire/core.hpp"
#include <wayfire/util/log.hpp>

namespace
{
    template<class A, class B> B union_cast(A object)
    {
        union {
            A x;
            B y;
        } helper;
        helper.x = object;
        return helper.y;
    }
}

plugin_manager::plugin_manager(wf::output_t *o)
{
    this->output = o;
    this->plugins_opt.load_option("core/plugins");

    reload_dynamic_plugins();
    load_static_plugins();

    this->plugins_opt.set_callback([=] ()
    {
        /* reload when config reload has finished */
        idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); });
    });
}

void plugin_manager::deinit_plugins(bool unloadable)
{
    for (auto& p : loaded_plugins)
    {
        if (!p.second) // already destroyed on the previous iteration
            continue;

        if (p.second->is_unloadable() == unloadable)
            destroy_plugin(p.second);
    }
}

plugin_manager::~plugin_manager()
{
    /* First remove unloadable plugins, then others */
    deinit_plugins(true);
    deinit_plugins(false);

    loaded_plugins.clear();
}

void plugin_manager::init_plugin(wayfire_plugin& p)
{
    p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output);
    p->output = output;
    p->init();
}

void plugin_manager::destroy_plugin(wayfire_plugin& p)
{
    p->grab_interface->ungrab();
    output->deactivate_plugin(p->grab_interface);

    p->fini();

    auto handle = p->handle;
    p.reset();

    /* dlopen()/dlclose() do reference counting, so we should close the plugin
     * as many times as we opened it.
     *
     * We also need to close the handle after deallocating the plugin, otherwise
     * we unload its destructor before calling it. */
    if (handle)
        dlclose(handle);
}

wayfire_plugin plugin_manager::load_plugin_from_file(std::string path)
{
    // RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins
    void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
    if(handle == NULL)
    {
        LOGE("error loading plugin: ", dlerror());
        return nullptr;
    }

    /* Check plugin version */
    auto version_func_ptr = dlsym(handle, "getWayfireVersion");
    if (version_func_ptr == NULL)
    {
        LOGE(path, ": missing getWayfireVersion()", path.c_str());
        dlclose(handle);
        return nullptr;
    }

    auto version_func =
        union_cast<void*, wayfire_plugin_version_func> (version_func_ptr);
    int32_t plugin_abi_version = version_func();

    if (version_func() != WAYFIRE_API_ABI_VERSION)
    {
        LOGE(path, ": API/ABI version mismatch: Wayfire is ",
            WAYFIRE_API_ABI_VERSION, ",  plugin built with ", plugin_abi_version);
        dlclose(handle);
        return nullptr;
    }

    auto new_instance_func_ptr = dlsym(handle, "newInstance");
    if(new_instance_func_ptr == NULL)
    {
        LOGE(path, ": missing newInstance(). ", dlerror());
        return nullptr;
    }

    LOGD("Loading plugin ", path.c_str());
    auto new_instance_func =
        union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr);

    auto ptr = wayfire_plugin(new_instance_func());
    ptr->handle = handle;
    return ptr;
}

void plugin_manager::reload_dynamic_plugins()
{
    std::string plugin_list = plugins_opt;
    if (plugin_list == "none")
    {
        LOGE("No plugins specified in the config file, or config file is "
            "missing. In this state the compositor is nearly unusable, please "
            "ensure your configuration file is set up properly.");
    }

    std::stringstream stream(plugin_list);
    std::vector<std::string> next_plugins;

    auto plugin_prefix = std::string(PLUGIN_PATH "/");

    std::string plugin_name;
    while(stream >> plugin_name)
    {
        if (plugin_name.size())
        {
            if (plugin_name.at(0) == '/')
                next_plugins.push_back(plugin_name);
            else
                next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so");
        }
    }

    /* erase plugins that have been removed from the config */
    auto it = loaded_plugins.begin();
    while(it != loaded_plugins.end())
    {
        /* skip built-in(static) plugins */
        if (it->first.size() && it->first[0] == '_')
        {
            ++it;
            continue;
        }

        if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&
            it->second->is_unloadable())
        {
            LOGD("unload plugin ", it->first.c_str());
            destroy_plugin(it->second);
            it = loaded_plugins.erase(it);
        }
        else
        {
            ++it;
        }
    }

    /* load new plugins */
    for (auto plugin : next_plugins)
    {
        if (loaded_plugins.count(plugin))
            continue;

        auto ptr = load_plugin_from_file(plugin);
        if (ptr)
        {
            init_plugin(ptr);
            loaded_plugins[plugin] = std::move(ptr);
        }
    }
}

template<class T> static wayfire_plugin create_plugin()
{
    return std::unique_ptr<wf::plugin_interface_t>(new T);
}

void plugin_manager::load_static_plugins()
{
    loaded_plugins["_exit"]         = create_plugin<wayfire_exit>();
    loaded_plugins["_focus"]        = create_plugin<wayfire_focus>();
    loaded_plugins["_close"]        = create_plugin<wayfire_close>();

    init_plugin(loaded_plugins["_exit"]);
    init_plugin(loaded_plugins["_focus"]);
    init_plugin(loaded_plugins["_close"]);
}
<commit_msg>plugin-loader: Call fini before ungrabbing<commit_after>#include <sstream>
#include <algorithm>
#include <set>
#include <memory>
#include <dlfcn.h>

#include "plugin-loader.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/output.hpp"
#include "../core/wm.hpp"
#include "wayfire/core.hpp"
#include <wayfire/util/log.hpp>

namespace
{
    template<class A, class B> B union_cast(A object)
    {
        union {
            A x;
            B y;
        } helper;
        helper.x = object;
        return helper.y;
    }
}

plugin_manager::plugin_manager(wf::output_t *o)
{
    this->output = o;
    this->plugins_opt.load_option("core/plugins");

    reload_dynamic_plugins();
    load_static_plugins();

    this->plugins_opt.set_callback([=] ()
    {
        /* reload when config reload has finished */
        idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); });
    });
}

void plugin_manager::deinit_plugins(bool unloadable)
{
    for (auto& p : loaded_plugins)
    {
        if (!p.second) // already destroyed on the previous iteration
            continue;

        if (p.second->is_unloadable() == unloadable)
            destroy_plugin(p.second);
    }
}

plugin_manager::~plugin_manager()
{
    /* First remove unloadable plugins, then others */
    deinit_plugins(true);
    deinit_plugins(false);

    loaded_plugins.clear();
}

void plugin_manager::init_plugin(wayfire_plugin& p)
{
    p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output);
    p->output = output;
    p->init();
}

void plugin_manager::destroy_plugin(wayfire_plugin& p)
{
    p->fini();

    p->grab_interface->ungrab();
    output->deactivate_plugin(p->grab_interface);

    auto handle = p->handle;
    p.reset();

    /* dlopen()/dlclose() do reference counting, so we should close the plugin
     * as many times as we opened it.
     *
     * We also need to close the handle after deallocating the plugin, otherwise
     * we unload its destructor before calling it. */
    if (handle)
        dlclose(handle);
}

wayfire_plugin plugin_manager::load_plugin_from_file(std::string path)
{
    // RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins
    void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
    if(handle == NULL)
    {
        LOGE("error loading plugin: ", dlerror());
        return nullptr;
    }

    /* Check plugin version */
    auto version_func_ptr = dlsym(handle, "getWayfireVersion");
    if (version_func_ptr == NULL)
    {
        LOGE(path, ": missing getWayfireVersion()", path.c_str());
        dlclose(handle);
        return nullptr;
    }

    auto version_func =
        union_cast<void*, wayfire_plugin_version_func> (version_func_ptr);
    int32_t plugin_abi_version = version_func();

    if (version_func() != WAYFIRE_API_ABI_VERSION)
    {
        LOGE(path, ": API/ABI version mismatch: Wayfire is ",
            WAYFIRE_API_ABI_VERSION, ",  plugin built with ", plugin_abi_version);
        dlclose(handle);
        return nullptr;
    }

    auto new_instance_func_ptr = dlsym(handle, "newInstance");
    if(new_instance_func_ptr == NULL)
    {
        LOGE(path, ": missing newInstance(). ", dlerror());
        return nullptr;
    }

    LOGD("Loading plugin ", path.c_str());
    auto new_instance_func =
        union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr);

    auto ptr = wayfire_plugin(new_instance_func());
    ptr->handle = handle;
    return ptr;
}

void plugin_manager::reload_dynamic_plugins()
{
    std::string plugin_list = plugins_opt;
    if (plugin_list == "none")
    {
        LOGE("No plugins specified in the config file, or config file is "
            "missing. In this state the compositor is nearly unusable, please "
            "ensure your configuration file is set up properly.");
    }

    std::stringstream stream(plugin_list);
    std::vector<std::string> next_plugins;

    auto plugin_prefix = std::string(PLUGIN_PATH "/");

    std::string plugin_name;
    while(stream >> plugin_name)
    {
        if (plugin_name.size())
        {
            if (plugin_name.at(0) == '/')
                next_plugins.push_back(plugin_name);
            else
                next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so");
        }
    }

    /* erase plugins that have been removed from the config */
    auto it = loaded_plugins.begin();
    while(it != loaded_plugins.end())
    {
        /* skip built-in(static) plugins */
        if (it->first.size() && it->first[0] == '_')
        {
            ++it;
            continue;
        }

        if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&
            it->second->is_unloadable())
        {
            LOGD("unload plugin ", it->first.c_str());
            destroy_plugin(it->second);
            it = loaded_plugins.erase(it);
        }
        else
        {
            ++it;
        }
    }

    /* load new plugins */
    for (auto plugin : next_plugins)
    {
        if (loaded_plugins.count(plugin))
            continue;

        auto ptr = load_plugin_from_file(plugin);
        if (ptr)
        {
            init_plugin(ptr);
            loaded_plugins[plugin] = std::move(ptr);
        }
    }
}

template<class T> static wayfire_plugin create_plugin()
{
    return std::unique_ptr<wf::plugin_interface_t>(new T);
}

void plugin_manager::load_static_plugins()
{
    loaded_plugins["_exit"]         = create_plugin<wayfire_exit>();
    loaded_plugins["_focus"]        = create_plugin<wayfire_focus>();
    loaded_plugins["_close"]        = create_plugin<wayfire_close>();

    init_plugin(loaded_plugins["_exit"]);
    init_plugin(loaded_plugins["_focus"]);
    init_plugin(loaded_plugins["_close"]);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:15:19 $
 *
 *  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_connectivity.hxx"

#ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_
#include "ado/AResultSetMetaData.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif

#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif

using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;

// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
    m_pRecordSet->Release();
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid() && aField.GetActualSize() != -1)
        return aField.GetActualSize();
    return 0;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    return ADOS::MapADOType2Jdbc(aField.GetADOType());
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount(  ) throw(SQLException, RuntimeException)
{
    if(m_nColCount != -1)
        return m_nColCount;

    ADOFields* pFields  = NULL;
    m_pRecordSet->get_Fields(&pFields);
    WpOLEAppendCollection<ADOFields, ADOField, WpADOField>  aFields(pFields);
    m_nColCount = aFields.GetItemCount();
    return m_nColCount;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Bool bRet = sal_False;
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
            bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISCASESENSITIVE")) );
    }
    return bRet;
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetName();

    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    ::rtl::OUString sTableName;

    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
            sTableName = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BASETABLENAME")) );
    }
    return sTableName;
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getColumnName(column);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return ((aField.GetAttributes() & adFldFixed) == adFldFixed) && (aField.GetADOType() == adCurrency);
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Bool bRet = sal_False;
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
        {
            bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISAUTOINCREMENT")) );
#if OSL_DEBUG_LEVEL > 0
            sal_Int32 nCount = aProps.GetItemCount();
            for (sal_Int32 i = 0; i<nCount; ++i)
            {
                WpADOProperty aProp = aProps.GetItem(i);
                ::rtl::OUString sName = aProp.GetName();
                ::rtl::OUString sVal = aProp.GetValue();
            }
#endif
        }
    }
    return bRet;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        DataTypeEnum eType = aField.GetADOType();
        return !(eType == adUnsignedBigInt || eType == adUnsignedInt || eType == adUnsignedSmallInt || eType == adUnsignedTinyInt);
    }
    return sal_False;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetPrecision();
    return 0;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetNumericScale();
    return 0;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable;
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        //  return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly;
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable;
    }
    return sal_False;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return isDefinitelyWritable(column);
}
// -------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba21fini (1.11.26); FILE MERGED 2006/10/27 08:14:33 oj 1.11.26.1: #142400# check recordset<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 14:34:57 $
 *
 *  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_connectivity.hxx"

#ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_
#include "ado/AResultSetMetaData.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif

#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif

using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;

OResultSetMetaData::OResultSetMetaData( ADORecordset* _pRecordSet)
                    :   m_pRecordSet(_pRecordSet),
                        m_nColCount(-1)
{
    if ( m_pRecordSet )
        m_pRecordSet->AddRef();
}
// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
    if ( m_pRecordSet )
        m_pRecordSet->Release();
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid() && aField.GetActualSize() != -1)
        return aField.GetActualSize();
    return 0;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    return ADOS::MapADOType2Jdbc(aField.GetADOType());
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount(  ) throw(SQLException, RuntimeException)
{
    if(m_nColCount != -1 )
        return m_nColCount;

    if ( !m_pRecordSet )
        return 0;

    ADOFields* pFields  = NULL;
    m_pRecordSet->get_Fields(&pFields);
    WpOLEAppendCollection<ADOFields, ADOField, WpADOField>  aFields(pFields);
    m_nColCount = aFields.GetItemCount();
    return m_nColCount;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Bool bRet = sal_False;
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
            bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISCASESENSITIVE")) );
    }
    return bRet;
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetName();

    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    ::rtl::OUString sTableName;

    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
            sTableName = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BASETABLENAME")) );
    }
    return sTableName;
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getColumnName(column);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return ((aField.GetAttributes() & adFldFixed) == adFldFixed) && (aField.GetADOType() == adCurrency);
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Bool bRet = sal_False;
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if ( aField.IsValid() )
    {
        WpADOProperties aProps( aField.get_Properties() );
        if ( aProps.IsValid() )
        {
            bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISAUTOINCREMENT")) );
#if OSL_DEBUG_LEVEL > 0
            sal_Int32 nCount = aProps.GetItemCount();
            for (sal_Int32 i = 0; i<nCount; ++i)
            {
                WpADOProperty aProp = aProps.GetItem(i);
                ::rtl::OUString sName = aProp.GetName();
                ::rtl::OUString sVal = aProp.GetValue();
            }
#endif
        }
    }
    return bRet;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        DataTypeEnum eType = aField.GetADOType();
        return !(eType == adUnsignedBigInt || eType == adUnsignedInt || eType == adUnsignedSmallInt || eType == adUnsignedTinyInt);
    }
    return sal_False;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetPrecision();
    return 0;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
        return aField.GetNumericScale();
    return 0;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable;
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        //  return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly;
    }
    return sal_False;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    WpADOField aField = ADOS::getField(m_pRecordSet,column);
    if(aField.IsValid())
    {
        return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable;
    }
    return sal_False;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return isDefinitelyWritable(column);
}
// -------------------------------------------------------------------------

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"

#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <utility>

#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
#include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h"

namespace apollo {
namespace planning {

using Trajectory1d = Curve1d;

TrajectoryEvaluator::TrajectoryEvaluator(
    const std::array<double, 3>& init_s, const PlanningTarget& planning_target,
    const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
    const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
    std::shared_ptr<PathTimeGraph> path_time_graph)
    : path_time_graph_(path_time_graph), init_s_(init_s) {
  const double start_time = 0.0;
  const double end_time = FLAGS_trajectory_time_length;
  path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
      start_time, end_time, FLAGS_trajectory_time_resolution);

  // if we have a stop point along the reference line,
  // filter out the lon. trajectories that pass the stop point.
  double stop_point = std::numeric_limits<double>::max();
  if (planning_target.has_stop_point()) {
    stop_point = planning_target.stop_point().s();
  }
  for (const auto lon_trajectory : lon_trajectories) {
    double lon_end_s = lon_trajectory->Evaluate(0, end_time);
    if (lon_end_s > stop_point) {
      continue;
    }

    if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
      continue;
    }
    for (const auto lat_trajectory : lat_trajectories) {
      /**
      if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
                                                         *lon_trajectory)) {
        continue;
      }
      */
      if (!FLAGS_enable_auto_tuning) {
        double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
        cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
      } else {
        std::vector<double> cost_components;
        double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
                               &cost_components);
        cost_queue_with_components_.push(PairCostWithComponents(
            {lon_trajectory, lat_trajectory}, {cost_components, cost}));
      }
    }
  }
  if (!FLAGS_enable_auto_tuning) {
    ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
  } else {
    ADEBUG << "Number of valid 1d trajectory pairs: "
           << cost_queue_with_components_.size();
  }
}

bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
  if (!FLAGS_enable_auto_tuning) {
    return !cost_queue_.empty();
  } else {
    return !cost_queue_with_components_.empty();
  }
}

std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
  if (!FLAGS_enable_auto_tuning) {
    return cost_queue_.size();
  } else {
    return cost_queue_with_components_.size();
  }
}

std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
  CHECK(has_more_trajectory_pairs() == true);
  if (!FLAGS_enable_auto_tuning) {
    auto top = cost_queue_.top();
    cost_queue_.pop();
    return top.first;
  } else {
    auto top = cost_queue_with_components_.top();
    cost_queue_with_components_.pop();
    return top.first;
  }
}

double TrajectoryEvaluator::top_trajectory_pair_cost() const {
  if (!FLAGS_enable_auto_tuning) {
    return cost_queue_.top().second;
  } else {
    return cost_queue_with_components_.top().second.second;
  }
}

std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
    const {
  CHECK(FLAGS_enable_auto_tuning);
  return cost_queue_with_components_.top().second.first;
}

double TrajectoryEvaluator::Evaluate(
    const PlanningTarget& planning_target,
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    std::vector<double>* cost_components) const {
  // Costs:
  // 1. Cost of missing the objective, e.g., cruise, stop, etc.
  // 2. Cost of logitudinal jerk
  // 3. Cost of logitudinal collision
  // 4. Cost of lateral offsets
  // 5. Cost of lateral comfort

  // Longitudinal costs
  auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target);

  double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target,
      reference_s_dot);

  double lon_jerk_cost = LonComfortCost(lon_trajectory);

  double lon_collision_cost = LonCollisionCost(lon_trajectory);

  // decides the longitudinal evaluation horizon for lateral trajectories.
  double evaluation_horizon =
      std::min(FLAGS_decision_horizon,
               lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
  std::vector<double> s_values;
  for (double s = 0.0; s < evaluation_horizon;
       s += FLAGS_trajectory_space_resolution) {
    s_values.push_back(s);
  }

  // Lateral costs
  double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);

  double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);

  if (cost_components != nullptr) {
    cost_components->push_back(lon_objective_cost);
    cost_components->push_back(lon_jerk_cost);
    cost_components->push_back(lon_collision_cost);
    cost_components->push_back(lat_offset_cost);
  }

  return lon_objective_cost * FLAGS_weight_lon_travel +
         lon_jerk_cost * FLAGS_weight_lon_jerk +
         lon_collision_cost * FLAGS_weight_lon_collision +
         lat_offset_cost * FLAGS_weight_lat_offset +
         lat_comfort_cost * FLAGS_weight_lat_comfort;
}

double TrajectoryEvaluator::LatOffsetCost(
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    const std::vector<double>& s_values) const {
  double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (const auto& s : s_values) {
    double lat_offset = lat_trajectory->Evaluate(0, s);
    double cost = lat_offset / FLAGS_lat_offset_bound;
    if (lat_offset * lat_offset_start < 0.0) {
      cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
      cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
    } else {
      cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
      cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::LatComfortCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
  double max_cost = 0.0;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double s = lon_trajectory->Evaluate(0, t);
    double s_dot = lon_trajectory->Evaluate(1, t);
    double s_dotdot = lon_trajectory->Evaluate(2, t);
    double l_prime = lat_trajectory->Evaluate(1, s);
    double l_primeprime = lat_trajectory->Evaluate(2, s);
    double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot;
    max_cost = std::max(max_cost, std::abs(cost));
  }
  return max_cost;
}

double TrajectoryEvaluator::LonComfortCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double jerk = lon_trajectory->Evaluate(3, t);
    double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
    cost_sqr_sum += cost * cost;
    cost_abs_sum += std::abs(cost);
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::LonObjectiveCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const PlanningTarget& planning_target,
    const std::vector<double>& ref_s_dots) const {
  double t_max = lon_trajectory->ParamLength();
  double dist_s = lon_trajectory->Evaluate(0, t_max)
      - lon_trajectory->Evaluate(0, 0.0);

  double speed_cost_sqr_sum = 0.0;
  double speed_cost_abs_sum = 0.0;
  for (std::size_t i = 0; i < ref_s_dots.size(); ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t);
    speed_cost_sqr_sum += cost * cost;
    speed_cost_abs_sum += std::abs(cost);
  }
  double speed_cost =
      speed_cost_sqr_sum / (speed_cost_abs_sum + FLAGS_lattice_epsilon);
  double dist_travelled_cost = 1.0 / (1.0 + dist_s);
  return (speed_cost * FLAGS_weight_target_speed +
          dist_travelled_cost * FLAGS_weight_dist_travelled) /
         (FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}

// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
    const auto& pt_interval = path_time_intervals_[i];
    if (pt_interval.empty()) {
      continue;
    }
    double t = i * FLAGS_trajectory_time_resolution;
    double traj_s = lon_trajectory->Evaluate(0, t);
    double sigma = FLAGS_lon_collision_cost_std;
    for (const auto& m : pt_interval) {
      double dist = 0.0;
      if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
        dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
      } else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
        dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
      }
      double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));

      cost_sqr_sum += cost * cost;
      cost_abs_sum += cost;
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
    const PlanningTarget& planning_target,
    const std::vector<apollo::common::SpeedPoint> st_points,
    const std::vector<apollo::common::FrenetFramePoint> sl_points) {
  std::vector<double> ret;
  return ret;
}

std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity(
    const PlanningTarget& planning_target) const {
  double comfort_a = FLAGS_longitudinal_acceleration_lower_bound *
                     FLAGS_comfort_acceleration_factor;

  double cruise_s_dot = planning_target.cruise_speed();

  ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot);

  if (!planning_target.has_stop_point()) {
    lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length);
  } else {
    double stop_s = planning_target.stop_point().s();
    double dist = stop_s - init_s_[0];
    double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist;
    if (stop_a > comfort_a) {
      double stop_t = cruise_s_dot / (-comfort_a);
      double stop_dist = cruise_s_dot * stop_t * 0.5;
      double cruise_t = (dist - stop_dist) / cruise_s_dot;
      lon_traj.AppendSgment(0.0, cruise_t);
      lon_traj.AppendSgment(comfort_a, stop_t);
    } else {
      double stop_t = cruise_s_dot / (-stop_a);
      lon_traj.AppendSgment(stop_a, stop_t);
    }
    if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) {
      lon_traj.AppendSgment(
          0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength());
    }
  }

  std::vector<double> reference_s_dot;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    reference_s_dot.push_back(lon_traj.Evaluate(1, t));
  }
  return reference_s_dot;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: adjust lon objective cost in lattice planner<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"

#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <utility>

#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
#include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h"

namespace apollo {
namespace planning {

using Trajectory1d = Curve1d;

TrajectoryEvaluator::TrajectoryEvaluator(
    const std::array<double, 3>& init_s, const PlanningTarget& planning_target,
    const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
    const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
    std::shared_ptr<PathTimeGraph> path_time_graph)
    : path_time_graph_(path_time_graph), init_s_(init_s) {
  const double start_time = 0.0;
  const double end_time = FLAGS_trajectory_time_length;
  path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
      start_time, end_time, FLAGS_trajectory_time_resolution);

  // if we have a stop point along the reference line,
  // filter out the lon. trajectories that pass the stop point.
  double stop_point = std::numeric_limits<double>::max();
  if (planning_target.has_stop_point()) {
    stop_point = planning_target.stop_point().s();
  }
  for (const auto lon_trajectory : lon_trajectories) {
    double lon_end_s = lon_trajectory->Evaluate(0, end_time);
    if (lon_end_s > stop_point) {
      continue;
    }

    if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
      continue;
    }
    for (const auto lat_trajectory : lat_trajectories) {
      /**
      if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
                                                         *lon_trajectory)) {
        continue;
      }
      */
      if (!FLAGS_enable_auto_tuning) {
        double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
        cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
      } else {
        std::vector<double> cost_components;
        double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
                               &cost_components);
        cost_queue_with_components_.push(PairCostWithComponents(
            {lon_trajectory, lat_trajectory}, {cost_components, cost}));
      }
    }
  }
  if (!FLAGS_enable_auto_tuning) {
    ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
  } else {
    ADEBUG << "Number of valid 1d trajectory pairs: "
           << cost_queue_with_components_.size();
  }
}

bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
  if (!FLAGS_enable_auto_tuning) {
    return !cost_queue_.empty();
  } else {
    return !cost_queue_with_components_.empty();
  }
}

std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
  if (!FLAGS_enable_auto_tuning) {
    return cost_queue_.size();
  } else {
    return cost_queue_with_components_.size();
  }
}

std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
  CHECK(has_more_trajectory_pairs() == true);
  if (!FLAGS_enable_auto_tuning) {
    auto top = cost_queue_.top();
    cost_queue_.pop();
    return top.first;
  } else {
    auto top = cost_queue_with_components_.top();
    cost_queue_with_components_.pop();
    return top.first;
  }
}

double TrajectoryEvaluator::top_trajectory_pair_cost() const {
  if (!FLAGS_enable_auto_tuning) {
    return cost_queue_.top().second;
  } else {
    return cost_queue_with_components_.top().second.second;
  }
}

std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
    const {
  CHECK(FLAGS_enable_auto_tuning);
  return cost_queue_with_components_.top().second.first;
}

double TrajectoryEvaluator::Evaluate(
    const PlanningTarget& planning_target,
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    std::vector<double>* cost_components) const {
  // Costs:
  // 1. Cost of missing the objective, e.g., cruise, stop, etc.
  // 2. Cost of logitudinal jerk
  // 3. Cost of logitudinal collision
  // 4. Cost of lateral offsets
  // 5. Cost of lateral comfort

  // Longitudinal costs
  auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target);

  double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target,
      reference_s_dot);

  double lon_jerk_cost = LonComfortCost(lon_trajectory);

  double lon_collision_cost = LonCollisionCost(lon_trajectory);

  // decides the longitudinal evaluation horizon for lateral trajectories.
  double evaluation_horizon =
      std::min(FLAGS_decision_horizon,
               lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
  std::vector<double> s_values;
  for (double s = 0.0; s < evaluation_horizon;
       s += FLAGS_trajectory_space_resolution) {
    s_values.push_back(s);
  }

  // Lateral costs
  double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);

  double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);

  if (cost_components != nullptr) {
    cost_components->push_back(lon_objective_cost);
    cost_components->push_back(lon_jerk_cost);
    cost_components->push_back(lon_collision_cost);
    cost_components->push_back(lat_offset_cost);
  }

  return lon_objective_cost * FLAGS_weight_lon_travel +
         lon_jerk_cost * FLAGS_weight_lon_jerk +
         lon_collision_cost * FLAGS_weight_lon_collision +
         lat_offset_cost * FLAGS_weight_lat_offset +
         lat_comfort_cost * FLAGS_weight_lat_comfort;
}

double TrajectoryEvaluator::LatOffsetCost(
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    const std::vector<double>& s_values) const {
  double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (const auto& s : s_values) {
    double lat_offset = lat_trajectory->Evaluate(0, s);
    double cost = lat_offset / FLAGS_lat_offset_bound;
    if (lat_offset * lat_offset_start < 0.0) {
      cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
      cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
    } else {
      cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
      cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::LatComfortCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
  double max_cost = 0.0;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double s = lon_trajectory->Evaluate(0, t);
    double s_dot = lon_trajectory->Evaluate(1, t);
    double s_dotdot = lon_trajectory->Evaluate(2, t);
    double l_prime = lat_trajectory->Evaluate(1, s);
    double l_primeprime = lat_trajectory->Evaluate(2, s);
    double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot;
    max_cost = std::max(max_cost, std::abs(cost));
  }
  return max_cost;
}

double TrajectoryEvaluator::LonComfortCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double jerk = lon_trajectory->Evaluate(3, t);
    double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
    cost_sqr_sum += cost * cost;
    cost_abs_sum += std::abs(cost);
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::LonObjectiveCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const PlanningTarget& planning_target,
    const std::vector<double>& ref_s_dots) const {
  double t_max = lon_trajectory->ParamLength();
  double dist_s = lon_trajectory->Evaluate(0, t_max)
      - lon_trajectory->Evaluate(0, 0.0);

  double speed_cost_sqr_sum = 0.0;
  double speed_cost_weight_sum = 0.0;
  for (std::size_t i = 0; i < ref_s_dots.size(); ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t);
    speed_cost_sqr_sum += t * t * std::abs(cost);
    speed_cost_weight_sum += t * t;
  }
  double speed_cost =
      speed_cost_sqr_sum / (speed_cost_weight_sum + FLAGS_lattice_epsilon);
  double dist_travelled_cost = 1.0 / (1.0 + dist_s);
  return (speed_cost * FLAGS_weight_target_speed +
          dist_travelled_cost * FLAGS_weight_dist_travelled) /
         (FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}

// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
    const auto& pt_interval = path_time_intervals_[i];
    if (pt_interval.empty()) {
      continue;
    }
    double t = i * FLAGS_trajectory_time_resolution;
    double traj_s = lon_trajectory->Evaluate(0, t);
    double sigma = FLAGS_lon_collision_cost_std;
    for (const auto& m : pt_interval) {
      double dist = 0.0;
      if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
        dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
      } else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
        dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
      }
      double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));

      cost_sqr_sum += cost * cost;
      cost_abs_sum += cost;
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
    const PlanningTarget& planning_target,
    const std::vector<apollo::common::SpeedPoint> st_points,
    const std::vector<apollo::common::FrenetFramePoint> sl_points) {
  std::vector<double> ret;
  return ret;
}

std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity(
    const PlanningTarget& planning_target) const {
  double comfort_a = FLAGS_longitudinal_acceleration_lower_bound *
                     FLAGS_comfort_acceleration_factor;

  double cruise_s_dot = planning_target.cruise_speed();

  ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot);

  if (!planning_target.has_stop_point()) {
    lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length);
  } else {
    double stop_s = planning_target.stop_point().s();
    double dist = stop_s - init_s_[0];
    double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist;
    if (stop_a > comfort_a) {
      double stop_t = cruise_s_dot / (-comfort_a);
      double stop_dist = cruise_s_dot * stop_t * 0.5;
      double cruise_t = (dist - stop_dist) / cruise_s_dot;
      lon_traj.AppendSgment(0.0, cruise_t);
      lon_traj.AppendSgment(comfort_a, stop_t);
    } else {
      double stop_t = cruise_s_dot / (-stop_a);
      lon_traj.AppendSgment(stop_a, stop_t);
    }
    if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) {
      lon_traj.AppendSgment(
          0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength());
    }
  }

  std::vector<double> reference_s_dot;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    reference_s_dot.push_back(lon_traj.Evaluate(1, t));
  }
  return reference_s_dot;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/****************************************************************************
 *
 * USBSerial core library for Arduino STM32 + HAL + CubeMX (HALMX).
 *
 * Copyright (c) 2016 by Vassilis Serasidis <info@serasidis.gr>
 * Home: http://www.serasidis.gr
 * email: avrsite@yahoo.gr
 *
 * Arduino_STM32 forum: http://www.stm32duino.com
 *
 * Permission to use, copy, modify, and/or distribute this software for
 * any purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all copies.
 *
 * Some functions follow the sam and samd arduino core libray files.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 *
 ****************************************************************************/
/*
 *  Modified on: 2016. 7.12.
 *       Author: Baram, PBHP
 */

#include  <chip.h>

#include <USBSerial.h>
#include "variant.h"

extern uint32_t usb_cdc_bitrate;
extern uint32_t usb_cdc_debug_cnt[];

USBSerial::USBSerial(){
  baudrate = 0;
  rx_cnt = 0;
  tx_cnt = 0;
  rx_err_cnt = 0;
  tx_err_cnt = 0;
}

void USBSerial::begin(uint32_t baud_count){
  UNUSED(baud_count);
}

void USBSerial::begin(uint32_t baud_count, uint8_t config){
  UNUSED(baud_count);
  UNUSED(config);
}

void USBSerial::end(void){
}

int USBSerial::available(void){
  return vcp_is_available();
}

int USBSerial::peek(void)
{
  return vcp_peek();
}

int USBSerial::read(void)
{
  if ( vcp_is_available() == 0 )
    return -1;

  rx_cnt++;

  return vcp_getch();
}

void USBSerial::flush(void){
  while(vcp_is_transmitted() == FALSE);
}

size_t USBSerial::write(const uint8_t *buffer, size_t size)
{
  uint32_t length;

  length = vcp_write((uint8_t *)buffer, (uint32_t)size);

  tx_cnt += length;

  return (size_t)length;
}

size_t USBSerial::write(uint8_t c) {
	return write(&c, 1);
}

uint32_t USBSerial::getBaudRate(void)
{
  return usb_cdc_bitrate;
}

uint32_t USBSerial::getRxCnt(void)
{
  return rx_cnt;
}

uint32_t USBSerial::getTxCnt(void)
{
  return tx_cnt;
}

uint32_t USBSerial::getRxErrCnt(void)
{
  return usb_cdc_debug_cnt[0];
}

uint32_t USBSerial::getTxErrCnt(void)
{
  return usb_cdc_debug_cnt[1];
}

// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
USBSerial::operator bool()
{
  if( vcp_is_connected() == TRUE ) return true;
  else                             return false;
}
<commit_msg>Fixed #92<commit_after>/****************************************************************************
 *
 * USBSerial core library for Arduino STM32 + HAL + CubeMX (HALMX).
 *
 * Copyright (c) 2016 by Vassilis Serasidis <info@serasidis.gr>
 * Home: http://www.serasidis.gr
 * email: avrsite@yahoo.gr
 *
 * Arduino_STM32 forum: http://www.stm32duino.com
 *
 * Permission to use, copy, modify, and/or distribute this software for
 * any purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all copies.
 *
 * Some functions follow the sam and samd arduino core libray files.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 *
 ****************************************************************************/
/*
 *  Modified on: 2016. 7.12.
 *       Author: Baram, PBHP
 */

#include  <chip.h>

#include <USBSerial.h>
#include "variant.h"

extern uint32_t usb_cdc_bitrate;
extern uint32_t usb_cdc_debug_cnt[];

USBSerial::USBSerial(){
  baudrate = 0;
  rx_cnt = 0;
  tx_cnt = 0;
  rx_err_cnt = 0;
  tx_err_cnt = 0;
}

void USBSerial::begin(uint32_t baud_count){
  UNUSED(baud_count);
}

void USBSerial::begin(uint32_t baud_count, uint8_t config){
  UNUSED(baud_count);
  UNUSED(config);
}

void USBSerial::end(void){
}

int USBSerial::available(void){
  return vcp_is_available();
}

int USBSerial::peek(void)
{
  return vcp_peek();
}

int USBSerial::read(void)
{
  if ( vcp_is_available() == 0 )
    return -1;

  rx_cnt++;

  return vcp_getch();
}

void USBSerial::flush(void){
  while( vcp_is_transmitted() == FALSE );
}

size_t USBSerial::write(const uint8_t *buffer, size_t size)
{
  uint32_t length;

  length = vcp_write((uint8_t *)buffer, (uint32_t)size);

  tx_cnt += length;

  return (size_t)length;
}

size_t USBSerial::write(uint8_t c) {
	return write(&c, 1);
}

uint32_t USBSerial::getBaudRate(void)
{
  return usb_cdc_bitrate;
}

uint32_t USBSerial::getRxCnt(void)
{
  return rx_cnt;
}

uint32_t USBSerial::getTxCnt(void)
{
  return tx_cnt;
}

uint32_t USBSerial::getRxErrCnt(void)
{
  return usb_cdc_debug_cnt[0];
}

uint32_t USBSerial::getTxErrCnt(void)
{
  return usb_cdc_debug_cnt[1];
}

// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
USBSerial::operator bool()
{
  if( vcp_is_connected() == TRUE ) return true;
  else                             return false;
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/composite_qoi.h"

namespace GRINS
{
  CompositeQoI::CompositeQoI()
    : libMesh::DifferentiableQoI()
  {
    return;
  }

  CompositeQoI::~CompositeQoI()
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        delete (*qoi);
      }

    return;
  }

  void CompositeQoI::add_qoi( QoIBase& qoi )
  {
    _qois.push_back( qoi.clone() );

    return;
  }

  void CompositeQoI::init_qoi( std::vector<Number>& sys_qoi )
  {
    sys_qoi.resize(qois.size(), 0.0);

    return;
  }

  void CompositeQoI::init( const GetPot& input, const MultiphysicsSystem& system )
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->init(input,system);
      }

    return;
  }

  void CompositeQoI::init_context( libMesh::DiffContext& context )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->init_context(c);
      }

    return;
  }

  void CompositeQoI::element_qoi( libMesh::DiffContext& context,
                                  const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).element_qoi(c,q);
      }

    return;
  }

  void CompositeQoI::element_qoi_derivative( libMesh::DiffContext& context,
                                             const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).element_qoi_derivative(c,q);
      }

    return;
  }

  void CompositeQoI::side_qoi( libMesh::DiffContext& context,
                               const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).side_qoi(c,q);
      }

    return;
  }

  void CompositeQoI::side_qoi_derivative( libMesh::DiffContext& context,
                                          const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).side_qoi_derivative(c,q);
      }

    return;
  }

  void CompositeQoI::parallel_op( const libMesh::Parallel::Communicator& communicator,
                                  std::vector<Number>& sys_qoi,
                                  std::vector<Number>& local_qoi,
                                  const QoISet& /*qoi_indices*/ )
  {
    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).parallel_op( communicator, sys_qoi[q], local_qoi[q] );
      }

    return;
  }

  void CompositeQoI::thread_join( std::vector<libMesh::Number>& qoi,
                                  const std::vector<libMesh::Number>& other_qoi,
                                  const QoISet& /*qoi_indices*/ )
  {
    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).thread_join( qoi[q], other_qoi[q] );
      }

    return;
  }

  void CompositeQoI::output_qoi( std::ostream& out ) const
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->output_qoi(out);
      }

    return;
  }

  libMesh::Number CompositeQoI::get_qoi( unsigned int qoi_index ) const
  {
    return (*_qois[qoi_index]).value();
  }

} // end namespace GRINS
<commit_msg>Need correct headers.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/composite_qoi.h"

// GRINS
#include "grins/assembly_context.h"

// libMesh
#include "libmesh/diff_context.h"

namespace GRINS
{
  CompositeQoI::CompositeQoI()
    : libMesh::DifferentiableQoI()
  {
    return;
  }

  CompositeQoI::~CompositeQoI()
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        delete (*qoi);
      }

    return;
  }

  void CompositeQoI::add_qoi( QoIBase& qoi )
  {
    _qois.push_back( qoi.clone() );

    return;
  }

  void CompositeQoI::init_qoi( std::vector<Number>& sys_qoi )
  {
    sys_qoi.resize(qois.size(), 0.0);

    return;
  }

  void CompositeQoI::init( const GetPot& input, const MultiphysicsSystem& system )
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->init(input,system);
      }

    return;
  }

  void CompositeQoI::init_context( libMesh::DiffContext& context )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->init_context(c);
      }

    return;
  }

  void CompositeQoI::element_qoi( libMesh::DiffContext& context,
                                  const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).element_qoi(c,q);
      }

    return;
  }

  void CompositeQoI::element_qoi_derivative( libMesh::DiffContext& context,
                                             const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).element_qoi_derivative(c,q);
      }

    return;
  }

  void CompositeQoI::side_qoi( libMesh::DiffContext& context,
                               const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).side_qoi(c,q);
      }

    return;
  }

  void CompositeQoI::side_qoi_derivative( libMesh::DiffContext& context,
                                          const libMesh::QoISet& /*qoi_indices*/ )
  {
    AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context);

    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).side_qoi_derivative(c,q);
      }

    return;
  }

  void CompositeQoI::parallel_op( const libMesh::Parallel::Communicator& communicator,
                                  std::vector<Number>& sys_qoi,
                                  std::vector<Number>& local_qoi,
                                  const QoISet& /*qoi_indices*/ )
  {
    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).parallel_op( communicator, sys_qoi[q], local_qoi[q] );
      }

    return;
  }

  void CompositeQoI::thread_join( std::vector<libMesh::Number>& qoi,
                                  const std::vector<libMesh::Number>& other_qoi,
                                  const QoISet& /*qoi_indices*/ )
  {
    for( unsigned int q = 0; q < _qois.size(); q++ )
      {
        (*_qois[q]).thread_join( qoi[q], other_qoi[q] );
      }

    return;
  }

  void CompositeQoI::output_qoi( std::ostream& out ) const
  {
    for( std::vector<QoIBase*>::iterator qoi = _qois.begin();
         qoi != _qois.end(); ++qoi )
      {
        qoi->output_qoi(out);
      }

    return;
  }

  libMesh::Number CompositeQoI::get_qoi( unsigned int qoi_index ) const
  {
    return (*_qois[qoi_index]).value();
  }

} // end namespace GRINS
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h"

#include "base/command_line.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/web_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace {
const struct ModifierKeysSelectItem {
  int message_id;
  chromeos::input_method::ModifierKey value;
} kModifierKeysSelectItems[] = {
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH,
    chromeos::input_method::kSearchKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL,
    chromeos::input_method::kControlKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT,
    chromeos::input_method::kAltKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_VOID,
    chromeos::input_method::kVoidKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK,
    chromeos::input_method::kCapsLockKey },
};

const char* kDataValuesNames[] = {
  "remapSearchKeyToValue",
  "remapControlKeyToValue",
  "remapAltKeyToValue",
  "remapCapsLockKeyToValue",
  "remapDiamondKeyToValue",
};
}  // namespace

namespace chromeos {
namespace options {

KeyboardHandler::KeyboardHandler() {
}

KeyboardHandler::~KeyboardHandler() {
}

void KeyboardHandler::GetLocalizedValues(DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("keyboardOverlayTitle",
      l10n_util::GetStringUTF16(IDS_OPTIONS_KEYBOARD_OVERLAY_TITLE));
  localized_strings->SetString("remapSearchKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH_LABEL));
  localized_strings->SetString("remapControlKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL_LABEL));
  localized_strings->SetString("remapAltKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT_LABEL));
  localized_strings->SetString("remapCapsLockKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK_LABEL));
  localized_strings->SetString("remapDiamondKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_DIAMOND_KEY_LABEL));
  localized_strings->SetString("changeLanguageAndInputSettings",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_CHANGE_LANGUAGE_AND_INPUT_SETTINGS));

  for (size_t i = 0; i < arraysize(kDataValuesNames); ++i) {
    ListValue* list_value = new ListValue();
    for (size_t j = 0; j < arraysize(kModifierKeysSelectItems); ++j) {
      const input_method::ModifierKey value =
          kModifierKeysSelectItems[j].value;
      const int message_id = kModifierKeysSelectItems[j].message_id;
      // Only the seach key can be remapped to the caps lock key.
      if (kDataValuesNames[i] != std::string("remapSearchKeyToValue") &&
          kDataValuesNames[i] != std::string("remapCapsLockKeyToValue") &&
          value == input_method::kCapsLockKey) {
        continue;
      }
      ListValue* option = new ListValue();
      option->Append(new base::FundamentalValue(value));
      option->Append(new base::StringValue(l10n_util::GetStringUTF16(
          message_id)));
      list_value->Append(option);
    }
    localized_strings->Set(kDataValuesNames[i], list_value);
  }
}

void KeyboardHandler::InitializePage() {
  bool chromeos_keyboard = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHasChromeOSKeyboard);
  const base::FundamentalValue show_caps_lock_options(chromeos_keyboard);

  bool has_diamond_key = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHasChromeOSDiamondKey);
  const base::FundamentalValue show_diamond_key_options(has_diamond_key);

  web_ui()->CallJavascriptFunction(
      "options.KeyboardOverlay.showCapsLockOptions",
      show_caps_lock_options);
  web_ui()->CallJavascriptFunction(
      "options.KeyboardOverlay.showDiamondKeyOptions",
      show_diamond_key_options);
}

}  // namespace options
}  // namespace chromeos
<commit_msg>Fix the badly inverted flag to show caps lock settings.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h"

#include "base/command_line.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/web_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace {
const struct ModifierKeysSelectItem {
  int message_id;
  chromeos::input_method::ModifierKey value;
} kModifierKeysSelectItems[] = {
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH,
    chromeos::input_method::kSearchKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL,
    chromeos::input_method::kControlKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT,
    chromeos::input_method::kAltKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_VOID,
    chromeos::input_method::kVoidKey },
  { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK,
    chromeos::input_method::kCapsLockKey },
};

const char* kDataValuesNames[] = {
  "remapSearchKeyToValue",
  "remapControlKeyToValue",
  "remapAltKeyToValue",
  "remapCapsLockKeyToValue",
  "remapDiamondKeyToValue",
};
}  // namespace

namespace chromeos {
namespace options {

KeyboardHandler::KeyboardHandler() {
}

KeyboardHandler::~KeyboardHandler() {
}

void KeyboardHandler::GetLocalizedValues(DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("keyboardOverlayTitle",
      l10n_util::GetStringUTF16(IDS_OPTIONS_KEYBOARD_OVERLAY_TITLE));
  localized_strings->SetString("remapSearchKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH_LABEL));
  localized_strings->SetString("remapControlKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL_LABEL));
  localized_strings->SetString("remapAltKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT_LABEL));
  localized_strings->SetString("remapCapsLockKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK_LABEL));
  localized_strings->SetString("remapDiamondKeyToContent",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_DIAMOND_KEY_LABEL));
  localized_strings->SetString("changeLanguageAndInputSettings",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_SETTINGS_CHANGE_LANGUAGE_AND_INPUT_SETTINGS));

  for (size_t i = 0; i < arraysize(kDataValuesNames); ++i) {
    ListValue* list_value = new ListValue();
    for (size_t j = 0; j < arraysize(kModifierKeysSelectItems); ++j) {
      const input_method::ModifierKey value =
          kModifierKeysSelectItems[j].value;
      const int message_id = kModifierKeysSelectItems[j].message_id;
      // Only the seach key can be remapped to the caps lock key.
      if (kDataValuesNames[i] != std::string("remapSearchKeyToValue") &&
          kDataValuesNames[i] != std::string("remapCapsLockKeyToValue") &&
          value == input_method::kCapsLockKey) {
        continue;
      }
      ListValue* option = new ListValue();
      option->Append(new base::FundamentalValue(value));
      option->Append(new base::StringValue(l10n_util::GetStringUTF16(
          message_id)));
      list_value->Append(option);
    }
    localized_strings->Set(kDataValuesNames[i], list_value);
  }
}

void KeyboardHandler::InitializePage() {
  bool chromeos_keyboard = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHasChromeOSKeyboard);
  const base::FundamentalValue show_caps_lock_options(!chromeos_keyboard);

  bool has_diamond_key = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHasChromeOSDiamondKey);
  const base::FundamentalValue show_diamond_key_options(has_diamond_key);

  web_ui()->CallJavascriptFunction(
      "options.KeyboardOverlay.showCapsLockOptions",
      show_caps_lock_options);
  web_ui()->CallJavascriptFunction(
      "options.KeyboardOverlay.showDiamondKeyOptions",
      show_diamond_key_options);
}

}  // namespace options
}  // namespace chromeos
<|endoftext|>