<commit_before>/*  Sirikata
 *  main.cpp
 *
 *  Copyright (c) 2008, Daniel Reiter Horn
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/PluginManager.hpp>
#include <sirikata/proxyobject/SimulationFactory.hpp>

#include <sirikata/oh/ObjectHost.hpp>
#include <sirikata/proxyobject/LightInfo.hpp>
#include <sirikata/oh/ObjectHostProxyManager.hpp>
#include <sirikata/oh/HostedObject.hpp>
#include <sirikata/oh/SpaceIDMap.hpp>
#include <sirikata/core/network/IOServiceFactory.hpp>
#include <sirikata/core/network/IOService.hpp>
#include <sirikata/core/util/KnownServices.hpp>
#include <Protocol_Persistence.pbj.hpp>
#include <time.h>
#include <boost/thread.hpp>

#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include <sirikata/oh/Trace.hpp>

#include <sirikata/core/network/ServerIDMap.hpp>
#include <sirikata/core/network/NTPTimeSync.hpp>

#include <sirikata/core/network/SSTImpl.hpp>

#include <sirikata/oh/ObjectHostContext.hpp>

#include <sirikata/oh/ObjectFactory.hpp>

#ifdef __GNUC__
#include <fenv.h>
#endif

int main (int argc, char** argv) {
    using namespace Sirikata;

    InitOptions();
    Trace::Trace::InitOptions();
    OHTrace::InitOptions();
    InitCPPOHOptions();

    ParseOptions(argc, argv);

    PluginManager plugins;
    plugins.loadList( GetOptionValue<String>(OPT_PLUGINS) );
    plugins.loadList( GetOptionValue<String>(OPT_OH_PLUGINS) );

    String time_server = GetOptionValue<String>("time-server");
    NTPTimeSync sync;
    if (time_server.size() > 0)
        sync.start(time_server);

#ifdef __GNUC__
#ifndef __APPLE__
    if (GetOptionValue<bool>(OPT_SIGFPE)) {
        feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
    }
#endif
#endif

    ObjectHostID oh_id = GetOptionValue<ObjectHostID>("ohid");
    String trace_file = GetPerServerFile(STATS_OH_TRACE_FILE, oh_id);
    Trace::Trace* trace = new Trace::Trace(trace_file);

    String servermap_type = GetOptionValue<String>("servermap");
    String servermap_options = GetOptionValue<String>("servermap-options");
    ServerIDMap * server_id_map =
        ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(servermap_options);

    srand( GetOptionValue<uint32>("rand-seed") );

    Network::IOService* ios = Network::IOServiceFactory::makeIOService();
    Network::IOStrand* mainStrand = ios->createStrand();

    Time start_time = Timer::now(); // Just for stats in ObjectHostContext.
    Duration duration = Duration::zero(); // Indicates to run forever.
    ObjectHostContext* ctx = new ObjectHostContext(oh_id, ios, mainStrand, trace, start_time, duration);

    SSTConnectionManager* sstConnMgr = new SSTConnectionManager(ctx);

    SpaceIDMap *spaceMap = new SpaceIDMap;
    SpaceID mainSpace(GetOptionValue<UUID>(OPT_MAIN_SPACE));
    typedef std::map<std::string,std::string> SimpleSpaceIDMap;
    SimpleSpaceIDMap spaceIdMap(GetOptionValue<SimpleSpaceIDMap>(OPT_SPACEID_MAP));
    for (SimpleSpaceIDMap::iterator i = spaceIdMap.begin(),
             ie=spaceIdMap.end();
         i!=ie;
         ++i) {
        SpaceID newSpace(UUID(i->first,UUID::HumanReadable()));
        spaceMap->insert(newSpace, Network::Address::lexical_cast(i->second).as<Network::Address>());
    }

    ObjectHost *oh = new ObjectHost(ctx, spaceMap, ios, "");

    // Add all the spaces to the ObjectHost.
    // FIXME we're adding all spaces and having them use the same ServerIDMap
    // because its difficult to encode this in the options.
    // FIXME once this is working, the above SpaceIDMap (spaceMap) shouldn't be
    // used the same way -- it was only mapping to a single address instead of
    // an entire ServerIDMap.
    for (SimpleSpaceIDMap::iterator i = spaceIdMap.begin(),
             ie=spaceIdMap.end();
         i!=ie;
         ++i) {
        SpaceID newSpace(UUID(i->first,UUID::HumanReadable()));
        oh->addServerIDMap(newSpace, server_id_map);
    }

    // FIXME simple test example
    // This is the camera.  We need it early on because other things depend on
    // having its ObjectHostProxyManager.
    HostedObjectPtr obj = HostedObject::construct<HostedObject>(ctx, oh, UUID::random(), true);
    obj->init();
    // Note: We currently just use the proxy manager for the default space. Not
    // sure if we should do something about handling multiple spaces.
    ProxyManagerPtr proxy_manager = obj->getProxyManager( mainSpace );

    typedef std::vector<TimeSteppedSimulation*> SimList;
    SimList sims;

    typedef std::list<String> StringList;
    StringList oh_sims(GetOptionValue<StringList>(OPT_OH_SIMS));
    for(StringList::iterator it = oh_sims.begin(); it != oh_sims.end(); it++)
        SILOG(cppoh,error,*it);
    for(StringList::iterator it = oh_sims.begin(); it != oh_sims.end(); it++) {
        String simName = *it;
        SILOG(cppoh,info,String("Initializing ") + simName);
        TimeSteppedSimulation *sim =
            SimulationFactory::getSingleton()
            .getConstructor ( simName ) ( ctx, proxy_manager.get(), "" );
        if (!sim) {
            SILOG(cppoh,error,String("Unable to load ") + simName + String(" plugin. The PATH environment variable is ignored, so make sure you have copied the DLLs from dependencies/ogre/bin/ into the current directory. Sorry about this!"));
            std::cerr << "Press enter to continue" << std::endl;
            fgetc(stdin);
            exit(0);
        }
        else {
            oh->addListener(sim);
            SILOG(cppoh,info,String("Successfully initialized ") + simName);
            sims.push_back(sim);
        }
    }

    // FIXME
    obj->connect(
        mainSpace,
        Location( Vector3d::nil(), Quaternion::identity(), Vector3f::nil(), Vector3f::nil(), 0),
        BoundingSphere3f(Vector3f::nil(), 1.f),
        "",
        SolidAngle(0.00000001f),
        UUID::null());

    String objfactory_type = GetOptionValue<String>(OPT_OBJECT_FACTORY);
    String objfactory_options = GetOptionValue<String>(OPT_OBJECT_FACTORY_OPTS);
    ObjectFactory* obj_factory = NULL;
    if (!objfactory_type.empty()) {
        obj_factory = ObjectFactoryFactory::getSingleton().getConstructor(objfactory_type)(ctx, oh, mainSpace, objfactory_options);
        obj_factory->generate();
    }

    ///////////Go go go!! start of simulation/////////////////////
    ctx->add(ctx);
    ctx->add(oh);
    ctx->add(sstConnMgr);
    for(SimList::iterator it = sims.begin(); it != sims.end(); it++)
        ctx->add(*it);
    ctx->run(1);

    obj.reset();

    ctx->cleanup();
    trace->prepareShutdown();

    proxy_manager.reset();
    delete oh;

    for(SimList::reverse_iterator it = sims.rbegin(); it != sims.rend(); it++) {
        delete *it;
    }
    sims.clear();
    plugins.gc();
    SimulationFactory::destroy();

    delete spaceMap;

    delete ctx;

    trace->shutdown();
    delete trace;
    trace = NULL;

    delete mainStrand;
    Network::IOServiceFactory::destroyIOService(ios);

    sync.stop();

    return 0;
}
<commit_msg>Only generate 'camera' object in cppoh if at least one simulation is requested.<commit_after>/*  Sirikata
 *  main.cpp
 *
 *  Copyright (c) 2008, Daniel Reiter Horn
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/PluginManager.hpp>
#include <sirikata/proxyobject/SimulationFactory.hpp>

#include <sirikata/oh/ObjectHost.hpp>
#include <sirikata/proxyobject/LightInfo.hpp>
#include <sirikata/oh/ObjectHostProxyManager.hpp>
#include <sirikata/oh/HostedObject.hpp>
#include <sirikata/oh/SpaceIDMap.hpp>
#include <sirikata/core/network/IOServiceFactory.hpp>
#include <sirikata/core/network/IOService.hpp>
#include <sirikata/core/util/KnownServices.hpp>
#include <Protocol_Persistence.pbj.hpp>
#include <time.h>
#include <boost/thread.hpp>

#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include <sirikata/oh/Trace.hpp>

#include <sirikata/core/network/ServerIDMap.hpp>
#include <sirikata/core/network/NTPTimeSync.hpp>

#include <sirikata/core/network/SSTImpl.hpp>

#include <sirikata/oh/ObjectHostContext.hpp>

#include <sirikata/oh/ObjectFactory.hpp>

#ifdef __GNUC__
#include <fenv.h>
#endif

int main (int argc, char** argv) {
    using namespace Sirikata;

    InitOptions();
    Trace::Trace::InitOptions();
    OHTrace::InitOptions();
    InitCPPOHOptions();

    ParseOptions(argc, argv);

    PluginManager plugins;
    plugins.loadList( GetOptionValue<String>(OPT_PLUGINS) );
    plugins.loadList( GetOptionValue<String>(OPT_OH_PLUGINS) );

    String time_server = GetOptionValue<String>("time-server");
    NTPTimeSync sync;
    if (time_server.size() > 0)
        sync.start(time_server);

#ifdef __GNUC__
#ifndef __APPLE__
    if (GetOptionValue<bool>(OPT_SIGFPE)) {
        feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
    }
#endif
#endif

    ObjectHostID oh_id = GetOptionValue<ObjectHostID>("ohid");
    String trace_file = GetPerServerFile(STATS_OH_TRACE_FILE, oh_id);
    Trace::Trace* trace = new Trace::Trace(trace_file);

    String servermap_type = GetOptionValue<String>("servermap");
    String servermap_options = GetOptionValue<String>("servermap-options");
    ServerIDMap * server_id_map =
        ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(servermap_options);

    srand( GetOptionValue<uint32>("rand-seed") );

    Network::IOService* ios = Network::IOServiceFactory::makeIOService();
    Network::IOStrand* mainStrand = ios->createStrand();

    Time start_time = Timer::now(); // Just for stats in ObjectHostContext.
    Duration duration = Duration::zero(); // Indicates to run forever.
    ObjectHostContext* ctx = new ObjectHostContext(oh_id, ios, mainStrand, trace, start_time, duration);

    SSTConnectionManager* sstConnMgr = new SSTConnectionManager(ctx);

    SpaceIDMap *spaceMap = new SpaceIDMap;
    SpaceID mainSpace(GetOptionValue<UUID>(OPT_MAIN_SPACE));
    typedef std::map<std::string,std::string> SimpleSpaceIDMap;
    SimpleSpaceIDMap spaceIdMap(GetOptionValue<SimpleSpaceIDMap>(OPT_SPACEID_MAP));
    for (SimpleSpaceIDMap::iterator i = spaceIdMap.begin(),
             ie=spaceIdMap.end();
         i!=ie;
         ++i) {
        SpaceID newSpace(UUID(i->first,UUID::HumanReadable()));
        spaceMap->insert(newSpace, Network::Address::lexical_cast(i->second).as<Network::Address>());
    }

    ObjectHost *oh = new ObjectHost(ctx, spaceMap, ios, "");

    // Add all the spaces to the ObjectHost.
    // FIXME we're adding all spaces and having them use the same ServerIDMap
    // because its difficult to encode this in the options.
    // FIXME once this is working, the above SpaceIDMap (spaceMap) shouldn't be
    // used the same way -- it was only mapping to a single address instead of
    // an entire ServerIDMap.
    for (SimpleSpaceIDMap::iterator i = spaceIdMap.begin(),
             ie=spaceIdMap.end();
         i!=ie;
         ++i) {
        SpaceID newSpace(UUID(i->first,UUID::HumanReadable()));
        oh->addServerIDMap(newSpace, server_id_map);
    }

    typedef std::list<String> StringList;
    StringList oh_sims(GetOptionValue<StringList>(OPT_OH_SIMS));

    // Note: We currently just use the proxy manager for the default space. Not
    // sure if we should do something about handling multiple spaces.
    ProxyManagerPtr proxy_manager;

    // FIXME simple test example
    // This is the camera.  We need it early on because other things depend on
    // having its ObjectHostProxyManager.
    // Currently, we only create the "camera" object if there's a simulation
    // that will want it
    HostedObjectPtr obj;
    if (!oh_sims.empty()) {
        obj = HostedObject::construct<HostedObject>(ctx, oh, UUID::random(), true);
        obj->init();
        proxy_manager = obj->getProxyManager( mainSpace );
    }

    typedef std::vector<TimeSteppedSimulation*> SimList;
    SimList sims;

    for(StringList::iterator it = oh_sims.begin(); it != oh_sims.end(); it++)
        SILOG(cppoh,error,*it);
    for(StringList::iterator it = oh_sims.begin(); it != oh_sims.end(); it++) {
        String simName = *it;
        SILOG(cppoh,info,String("Initializing ") + simName);
        TimeSteppedSimulation *sim =
            SimulationFactory::getSingleton()
            .getConstructor ( simName ) ( ctx, proxy_manager.get(), "" );
        if (!sim) {
            SILOG(cppoh,error,String("Unable to load ") + simName + String(" plugin. The PATH environment variable is ignored, so make sure you have copied the DLLs from dependencies/ogre/bin/ into the current directory. Sorry about this!"));
            std::cerr << "Press enter to continue" << std::endl;
            fgetc(stdin);
            exit(0);
        }
        else {
            oh->addListener(sim);
            SILOG(cppoh,info,String("Successfully initialized ") + simName);
            sims.push_back(sim);
        }
    }

    // FIXME
    if (obj) {
        obj->connect(
            mainSpace,
            Location( Vector3d::nil(), Quaternion::identity(), Vector3f::nil(), Vector3f::nil(), 0),
            BoundingSphere3f(Vector3f::nil(), 1.f),
            "",
            SolidAngle(0.00000001f),
            UUID::null());
    }

    String objfactory_type = GetOptionValue<String>(OPT_OBJECT_FACTORY);
    String objfactory_options = GetOptionValue<String>(OPT_OBJECT_FACTORY_OPTS);
    ObjectFactory* obj_factory = NULL;
    if (!objfactory_type.empty()) {
        obj_factory = ObjectFactoryFactory::getSingleton().getConstructor(objfactory_type)(ctx, oh, mainSpace, objfactory_options);
        obj_factory->generate();
    }

    ///////////Go go go!! start of simulation/////////////////////
    ctx->add(ctx);
    ctx->add(oh);
    ctx->add(sstConnMgr);
    for(SimList::iterator it = sims.begin(); it != sims.end(); it++)
        ctx->add(*it);
    ctx->run(1);

    obj.reset();

    ctx->cleanup();
    trace->prepareShutdown();

    proxy_manager.reset();
    delete oh;

    for(SimList::reverse_iterator it = sims.rbegin(); it != sims.rend(); it++) {
        delete *it;
    }
    sims.clear();
    plugins.gc();
    SimulationFactory::destroy();

    delete spaceMap;

    delete ctx;

    trace->shutdown();
    delete trace;
    trace = NULL;

    delete mainStrand;
    Network::IOServiceFactory::destroyIOService(ios);

    sync.stop();

    return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/execution_policy.hpp>
#include <agency/flattened_executor.hpp>
#include <agency/detail/ignore.hpp>
#include <type_traits>
#include <agency/cuda/execution_agent.hpp>
#include <agency/cuda/grid_executor.hpp>
#include <agency/cuda/block_executor.hpp>
#include <agency/cuda/parallel_executor.hpp>
#include <agency/cuda/nested_executor.hpp>
#include <agency/cuda/detail/bind.hpp>

namespace agency
{
namespace cuda
{
namespace detail
{

template<class Function, class ExecutionAgentTraits, class ExecutorShape, class AgentShape>
struct execute_agent_functor
{
  __agency_hd_warning_disable__
  __host__ __device__
  execute_agent_functor(const Function& f,
                        const typename ExecutionAgentTraits::param_type& param,
                        const ExecutorShape& executor_shape,
                        const AgentShape& agent_shape)
    : f_(f),
      param_(param),
      executor_shape_(executor_shape),
      agent_shape_(agent_shape)
  {}

  template<class ExecutorIndex, class SharedParam>
  __device__
  void operator()(ExecutorIndex executor_idx, SharedParam&& shared_params) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_, shared_params);
  }

  template<class ExecutorIndex, class SharedParam>
  __device__
  void operator()(ExecutorIndex executor_idx, SharedParam&& shared_params)
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_, shared_params);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx, decltype(agency::detail::ignore)) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx, decltype(agency::detail::ignore))
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx)
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  Function f_;
  typename ExecutionAgentTraits::param_type param_;
  ExecutorShape executor_shape_;
  AgentShape agent_shape_;
};

template<class ExecutionAgentTraits, class Function, class ExecutorShape, class AgentShape>
__host__ __device__
execute_agent_functor<Function, ExecutionAgentTraits, ExecutorShape, AgentShape>
  make_execute_agent_functor(const Function& f,const typename ExecutionAgentTraits::param_type& param,
                             const ExecutorShape& executor_shape, const AgentShape& agent_shape)
{
  return execute_agent_functor<Function,ExecutionAgentTraits,ExecutorShape,AgentShape>(f,param,executor_shape,agent_shape);
}

template<class ExecutionPolicy, class Function>
void bulk_invoke(const ExecutionPolicy& exec, Function&& f)
{
  using execution_agent_type = typename ExecutionPolicy::execution_agent_type;
  using traits = execution_agent_traits<execution_agent_type>;

  auto param = exec.param();
  auto agent_shape = traits::domain(param).shape();
  auto shared_init = traits::make_shared_initializer(param);

  using executor_type = typename ExecutionPolicy::executor_type;
  using executor_index_type = typename executor_traits<executor_type>::index_type;

  // convert the shape of the agent into the type of the executor's shape
  using executor_shape_type = typename executor_traits<executor_type>::shape_type;
  executor_shape_type executor_shape = agency::detail::shape_cast<executor_shape_type>(agent_shape);

  auto execute_me = make_execute_agent_functor<traits>(f, param, executor_shape, agent_shape);

  return executor_traits<executor_type>::bulk_invoke(exec.executor(), execute_me, executor_shape, shared_init);
}

// add basic_execution_policy to allow us to catch its derivations as overloads of bulk_invoke, etc.
template<class ExecutionAgent,
         class BulkExecutor,
         class ExecutionCategory = typename execution_agent_traits<ExecutionAgent>::execution_category,
         class DerivedExecutionPolicy = void>
class basic_execution_policy : public agency::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>
{
  public:
    using agency::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>::basic_execution_policy;
}; // end basic_execution_policy

} // end detail

class parallel_execution_policy : public detail::basic_execution_policy<cuda::parallel_agent, cuda::parallel_executor, parallel_execution_tag, parallel_execution_policy>
{
  public:
    using detail::basic_execution_policy<cuda::parallel_agent, cuda::parallel_executor, parallel_execution_tag, parallel_execution_policy>::basic_execution_policy;
};

const parallel_execution_policy par{};

class concurrent_execution_policy : public detail::basic_execution_policy<cuda::concurrent_agent, cuda::block_executor, concurrent_execution_tag, concurrent_execution_policy>
{
  public:
    using detail::basic_execution_policy<cuda::concurrent_agent, cuda::block_executor, concurrent_execution_tag, concurrent_execution_policy>::basic_execution_policy;
};

const concurrent_execution_policy con{};

template<class ExecutionPolicy, class Function, class... Args>
void bulk_invoke(const ExecutionPolicy& exec, Function&& f, Args&&... args)
{
  auto g = detail::bind(f, thrust::placeholders::_1, std::forward<Args>(args)...);
  detail::bulk_invoke(exec, g);
}

template<class ExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(const ExecutionPolicy& exec, Function&& f, Args&&... args)
{
  std::cout << "cuda::bulk_async(ExecutionPolicy): implement me!" << std::endl;
  return agency::detail::make_ready_future();
}

namespace detail
{

// specialize rebind_executor for cuda's executor types
template<class ExecutionPolicy, class Enable = void>
struct rebind_executor_impl;

template<class ExecutionPolicy>
struct rebind_executor_impl<
  ExecutionPolicy,
  typename std::enable_if<
    std::is_same<
      typename ExecutionPolicy::execution_category,
      parallel_execution_tag
    >::value
  >::type
>
{
  using type = cuda::parallel_execution_policy;
};

// specialize rebind_executor for cuda::block_executor
template<class ExecutionPolicy>
struct rebind_executor_impl<
  ExecutionPolicy,
  typename std::enable_if<
    std::is_same<
      typename ExecutionPolicy::execution_category,
      concurrent_execution_tag
    >::value
  >::type
>
{
  using type = cuda::concurrent_execution_policy;
};

} // end detail
} // end cuda

// specialize is_execution_policy
template<>
struct is_execution_policy<cuda::parallel_execution_policy> : std::true_type {};

template<>
struct is_execution_policy<cuda::concurrent_execution_policy> : std::true_type {};

template<class ExecutionPolicy>
struct rebind_executor<ExecutionPolicy, cuda::grid_executor>
{
  using type = typename cuda::detail::rebind_executor_impl<ExecutionPolicy>::type;
};

template<class ExecutionPolicy>
struct rebind_executor<ExecutionPolicy, cuda::block_executor>
{
  using type = typename cuda::detail::rebind_executor_impl<ExecutionPolicy>::type;
};

// the following functions are overloads of agency::bulk_invoke & agency::bulk_async
// for cuda execution policies. they forward along the to cuda::bulk_invoke & cuda::bulk_async
// we introduce these overloads to work around the use of lambdas in agency::bulk_invoke & agency::bulk_async

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(const cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::parallel_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(const cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::concurrent_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(const cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>&& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(const cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::parallel_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(const cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::concurrent_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(const cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

} // end agency

<commit_msg>Fix the type passed to the DerivedPolicy parameter of agency::detail::basic_execution_policy<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/execution_policy.hpp>
#include <agency/flattened_executor.hpp>
#include <agency/detail/ignore.hpp>
#include <type_traits>
#include <agency/cuda/execution_agent.hpp>
#include <agency/cuda/grid_executor.hpp>
#include <agency/cuda/block_executor.hpp>
#include <agency/cuda/parallel_executor.hpp>
#include <agency/cuda/nested_executor.hpp>
#include <agency/cuda/detail/bind.hpp>

namespace agency
{
namespace cuda
{
namespace detail
{

template<class Function, class ExecutionAgentTraits, class ExecutorShape, class AgentShape>
struct execute_agent_functor
{
  __agency_hd_warning_disable__
  __host__ __device__
  execute_agent_functor(const Function& f,
                        const typename ExecutionAgentTraits::param_type& param,
                        const ExecutorShape& executor_shape,
                        const AgentShape& agent_shape)
    : f_(f),
      param_(param),
      executor_shape_(executor_shape),
      agent_shape_(agent_shape)
  {}

  template<class ExecutorIndex, class SharedParam>
  __device__
  void operator()(ExecutorIndex executor_idx, SharedParam&& shared_params) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_, shared_params);
  }

  template<class ExecutorIndex, class SharedParam>
  __device__
  void operator()(ExecutorIndex executor_idx, SharedParam&& shared_params)
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_, shared_params);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx, decltype(agency::detail::ignore)) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx, decltype(agency::detail::ignore))
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx) const
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  template<class ExecutorIndex>
  __device__
  void operator()(ExecutorIndex executor_idx)
  {
    using agent_index_type = typename ExecutionAgentTraits::index_type;
    auto agent_idx = agency::detail::index_cast<agent_index_type>(executor_idx, executor_shape_, agent_shape_);

    ExecutionAgentTraits::execute(f_, agent_idx, param_);
  }

  Function f_;
  typename ExecutionAgentTraits::param_type param_;
  ExecutorShape executor_shape_;
  AgentShape agent_shape_;
};

template<class ExecutionAgentTraits, class Function, class ExecutorShape, class AgentShape>
__host__ __device__
execute_agent_functor<Function, ExecutionAgentTraits, ExecutorShape, AgentShape>
  make_execute_agent_functor(const Function& f,const typename ExecutionAgentTraits::param_type& param,
                             const ExecutorShape& executor_shape, const AgentShape& agent_shape)
{
  return execute_agent_functor<Function,ExecutionAgentTraits,ExecutorShape,AgentShape>(f,param,executor_shape,agent_shape);
}

template<class ExecutionPolicy, class Function>
void bulk_invoke_impl(const ExecutionPolicy& exec, Function&& f)
{
  using execution_agent_type = typename ExecutionPolicy::execution_agent_type;
  using traits = execution_agent_traits<execution_agent_type>;

  auto param = exec.param();
  auto agent_shape = traits::domain(param).shape();
  auto shared_init = traits::make_shared_initializer(param);

  using executor_type = typename ExecutionPolicy::executor_type;
  using executor_index_type = typename executor_traits<executor_type>::index_type;

  // convert the shape of the agent into the type of the executor's shape
  using executor_shape_type = typename executor_traits<executor_type>::shape_type;
  executor_shape_type executor_shape = agency::detail::shape_cast<executor_shape_type>(agent_shape);

  auto execute_me = make_execute_agent_functor<traits>(f, param, executor_shape, agent_shape);

  return executor_traits<executor_type>::bulk_invoke(exec.executor(), execute_me, executor_shape, shared_init);
}

// add basic_execution_policy to allow us to catch its derivations as overloads of bulk_invoke, etc.
template<class ExecutionAgent,
         class BulkExecutor,
         class ExecutionCategory = typename execution_agent_traits<ExecutionAgent>::execution_category,
         class DerivedExecutionPolicy = void>
class basic_execution_policy :
  public agency::detail::basic_execution_policy<
    ExecutionAgent,
    BulkExecutor,
    ExecutionCategory,
    typename std::conditional<
      std::is_void<DerivedExecutionPolicy>::value,
      basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>,
      DerivedExecutionPolicy
    >::type
>
{
  public:
    // inherit the base class's constructors
    using agency::detail::basic_execution_policy<
      ExecutionAgent,
      BulkExecutor,
      ExecutionCategory,
      typename std::conditional<
        std::is_void<DerivedExecutionPolicy>::value,
        basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>,
        DerivedExecutionPolicy
      >::type
    >::basic_execution_policy;
}; // end basic_execution_policy

} // end detail

class parallel_execution_policy : public detail::basic_execution_policy<cuda::parallel_agent, cuda::parallel_executor, parallel_execution_tag, parallel_execution_policy>
{
  public:
    using detail::basic_execution_policy<cuda::parallel_agent, cuda::parallel_executor, parallel_execution_tag, parallel_execution_policy>::basic_execution_policy;
};

const parallel_execution_policy par{};

class concurrent_execution_policy : public detail::basic_execution_policy<cuda::concurrent_agent, cuda::block_executor, concurrent_execution_tag, concurrent_execution_policy>
{
  public:
    using detail::basic_execution_policy<cuda::concurrent_agent, cuda::block_executor, concurrent_execution_tag, concurrent_execution_policy>::basic_execution_policy;
};

const concurrent_execution_policy con{};

template<class ExecutionPolicy, class Function, class... Args>
void bulk_invoke(const ExecutionPolicy& exec, Function&& f, Args&&... args)
{
  auto g = detail::bind(f, thrust::placeholders::_1, std::forward<Args>(args)...);
  detail::bulk_invoke_impl(exec, g);
}

template<class ExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(const ExecutionPolicy& exec, Function&& f, Args&&... args)
{
  std::cout << "cuda::bulk_async(ExecutionPolicy): implement me!" << std::endl;
  return agency::detail::make_ready_future();
}

namespace detail
{

// specialize rebind_executor for cuda's executor types
template<class ExecutionPolicy, class Enable = void>
struct rebind_executor_impl;

template<class ExecutionPolicy>
struct rebind_executor_impl<
  ExecutionPolicy,
  typename std::enable_if<
    std::is_same<
      typename ExecutionPolicy::execution_category,
      parallel_execution_tag
    >::value
  >::type
>
{
  using type = cuda::parallel_execution_policy;
};

// specialize rebind_executor for cuda::block_executor
template<class ExecutionPolicy>
struct rebind_executor_impl<
  ExecutionPolicy,
  typename std::enable_if<
    std::is_same<
      typename ExecutionPolicy::execution_category,
      concurrent_execution_tag
    >::value
  >::type
>
{
  using type = cuda::concurrent_execution_policy;
};

} // end detail
} // end cuda

// specialize is_execution_policy
template<>
struct is_execution_policy<cuda::parallel_execution_policy> : std::true_type {};

template<>
struct is_execution_policy<cuda::concurrent_execution_policy> : std::true_type {};

template<class ExecutionPolicy>
struct rebind_executor<ExecutionPolicy, cuda::grid_executor>
{
  using type = typename cuda::detail::rebind_executor_impl<ExecutionPolicy>::type;
};

template<class ExecutionPolicy>
struct rebind_executor<ExecutionPolicy, cuda::block_executor>
{
  using type = typename cuda::detail::rebind_executor_impl<ExecutionPolicy>::type;
};

// the following functions are overloads of agency::bulk_invoke & agency::bulk_async
// for cuda execution policies. they forward along the to cuda::bulk_invoke & cuda::bulk_async
// we introduce these overloads to work around the use of lambdas in agency::bulk_invoke & agency::bulk_async

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
void bulk_invoke(const cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::parallel_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(const cuda::parallel_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::concurrent_execution_policy&& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_invoke(const cuda::concurrent_execution_policy& exec,
                 Function&& f,
                 Args&&... args)
{
  return cuda::bulk_invoke(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>&& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class ExecutionAgent, class BulkExecutor, class ExecutionCategory, class DerivedExecutionPolicy, class Function, class... Args>
std::future<void> bulk_async(const cuda::detail::basic_execution_policy<ExecutionAgent,BulkExecutor,ExecutionCategory,DerivedExecutionPolicy>& exec, Function&& f, Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::parallel_execution_policy&& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::parallel_execution_policy& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(const cuda::parallel_execution_policy& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::concurrent_execution_policy&& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(cuda::concurrent_execution_policy& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

template<class Function, class... Args>
void bulk_async(const cuda::concurrent_execution_policy& exec,
                Function&& f,
                Args&&... args)
{
  return cuda::bulk_async(exec, std::forward<Function>(f), std::forward<Args>(args)...);
}

} // end agency

<|endoftext|>


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

#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX

#include <glyphcache.hxx>
#include <rtl/textcvt.h>

#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;

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

// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
    static FtFontFile*      FindFontFile( const ::rtl::OString& rNativeFileName );

    bool                    Map();
    void                    Unmap();

    const unsigned char*    GetBuffer() const { return mpFileMap; }
    int                     GetFileSize() const { return mnFileSize; }
    const ::rtl::OString*   GetFileName() const { return &maNativeFileName; }
    int                     GetLangBoost() const { return mnLangBoost; }

private:
                            FtFontFile( const ::rtl::OString& rNativeFileName );

    const ::rtl::OString    maNativeFileName;
    const unsigned char*    mpFileMap;
    int                     mnFileSize;
    int                     mnRefCount;
    int                     mnLangBoost;
};

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

// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
                           FtFontInfo( const ImplDevFontAttributes&,
                               const ::rtl::OString& rNativeFileName,
                               int nFaceNum, sal_IntPtr nFontId, int nSynthetic,
                                const ExtraKernInfo* );
                          ~FtFontInfo();

    const unsigned char*  GetTable( const char*, ULONG* pLength=0 ) const;

    FT_FaceRec_*          GetFaceFT();
    void                  ReleaseFaceFT( FT_FaceRec_* );

    const ::rtl::OString* GetFontFileName() const   { return mpFontFile->GetFileName(); }
    int                   GetFaceNum() const        { return mnFaceNum; }
    int                   GetSynthetic() const      { return mnSynthetic; }
    sal_IntPtr            GetFontId() const         { return mnFontId; }
    bool                  DontUseAntiAlias() const
        { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }
    bool                  DontUseEmbeddedBitmaps() const
        { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }
    bool                  IsSymbolFont() const      { return maDevFontAttributes.IsSymbolFont(); }
    const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }

    void                  AnnounceFont( ImplDevFontList* );

    int                   GetGlyphIndex( sal_UCS4 cChar ) const;
    void                  CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;

    bool                  HasExtraKerning() const;
    int                   GetExtraKernPairs( ImplKernPairData** ) const;
    int                   GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;

private:
    FT_FaceRec_*    maFaceFT;
    FtFontFile*     mpFontFile;
    const int       mnFaceNum;
    int             mnRefCount;
    const int       mnSynthetic;

    sal_IntPtr      mnFontId;
    ImplDevFontAttributes maDevFontAttributes;

    // cache unicode->glyphid mapping because looking it up is expensive
    // TODO: change to hash_multimap when a use case requires a m:n mapping
    typedef ::std::hash_map<int,int> Int2IntMap;
    mutable Int2IntMap maChar2Glyph;
    mutable Int2IntMap maGlyph2Char;

    const ExtraKernInfo* mpExtraKernInfo;
};

// these two inlines are very important for performance

inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
    Int2IntMap::const_iterator it = maChar2Glyph.find( cChar );
    if( it == maChar2Glyph.end() )
        return -1;
    return it->second;
}

inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
    maChar2Glyph[ cChar ] = nIndex;
    maGlyph2Char[ nIndex ] = cChar;
}

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

class FreetypeManager
{
public:
                        FreetypeManager();
                        ~FreetypeManager();

    long                AddFontDir( const String& rUrlName );
    void                AddFontFile( const rtl::OString& rNormalizedName,
                            int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,
                            const ExtraKernInfo* );
    void                AnnounceFonts( ImplDevFontList* ) const;
    void                ClearFontList();

    FreetypeServerFont* CreateFont( const ImplFontSelectData& );

private:
    typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;
    FontList            maFontList;

    sal_IntPtr          mnMaxFontId;
    sal_IntPtr          mnNextFontId;
};

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

class FreetypeServerFont : public ServerFont
{
public:
                                FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
    virtual                     ~FreetypeServerFont();

    virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
    virtual int                 GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
    virtual bool                TestFont() const;

    virtual void                FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;

    virtual int                 GetGlyphIndex( sal_UCS4 ) const;
    int                         GetRawGlyphIndex( sal_UCS4 ) const;
    int                         FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;

    virtual bool                GetAntialiasAdvice( void ) const;
    virtual bool                GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
    virtual int                 GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    const unsigned char*        GetTable( const char* pName, ULONG* pLength )
                                { return mpFontInfo->GetTable( pName, pLength ); }
    int                         GetEmUnits() const;
    const FT_Size_Metrics&      GetMetricsFT() const { return maSizeFT->metrics; }

protected:
    friend class GlyphCache;

    int                         ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
    virtual void                InitGlyphData( int nGlyphIndex, GlyphData& ) const;
    virtual ULONG               GetFontCodeRanges( sal_uInt32* pCodes ) const;
    bool                        ApplyGSUB( const ImplFontSelectData& );
    virtual ServerFontLayoutEngine* GetLayoutEngine();

private:
    int                         mnWidth;
    int                         mnPrioEmbedded;
    int                         mnPrioAntiAlias;
    FtFontInfo*                 mpFontInfo;
    FT_Int                      mnLoadFlags;
    double                      mfStretch;
    FT_FaceRec_*                maFaceFT;
    FT_SizeRec_*                maSizeFT;

    bool            mbArtItalic;
    bool            mbArtBold;
    bool            mbUseGamma;

    typedef ::std::hash_map<int,int> GlyphSubstitution;
    GlyphSubstitution           maGlyphSubstitution;
    rtl_UnicodeToTextConverter  maRecodeConverter;

    ServerFontLayoutEngine*     mpLayoutEngine;
};

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

class ImplFTSFontData : public ImplFontData
{
private:
    FtFontInfo*             mpFtFontInfo;
    enum { IFTSFONT_MAGIC = 0x1F150A1C };

public:
                            ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );
    virtual                 ~ImplFTSFontData();

    FtFontInfo*             GetFtFontInfo() const { return mpFtFontInfo; }

    virtual ImplFontEntry*  CreateFontInstance( ImplFontSelectData& ) const;
    virtual ImplFontData*   Clone() const   { return new ImplFTSFontData( *this ); }
    virtual sal_IntPtr      GetFontId() const { return mpFtFontInfo->GetFontId(); }

    static bool             CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};

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

#endif // _SV_GCACHFTYP_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.34.10); FILE MERGED 2006/05/23 19:52:07 sb 1.34.10.2: RESYNC: (1.34-1.35); FILE MERGED 2006/04/20 14:49:37 sb 1.34.10.1: #i53898# Made code compile and/or warning-free again after resync to SRC680m162 (done by PL).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gcach_ftyp.hxx,v $
 *
 *  $Revision: 1.36 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 19:32:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX

#include <glyphcache.hxx>
#include <rtl/textcvt.h>

#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;

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

// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
    static FtFontFile*      FindFontFile( const ::rtl::OString& rNativeFileName );

    bool                    Map();
    void                    Unmap();

    const unsigned char*    GetBuffer() const { return mpFileMap; }
    int                     GetFileSize() const { return mnFileSize; }
    const ::rtl::OString*   GetFileName() const { return &maNativeFileName; }
    int                     GetLangBoost() const { return mnLangBoost; }

private:
                            FtFontFile( const ::rtl::OString& rNativeFileName );

    const ::rtl::OString    maNativeFileName;
    const unsigned char*    mpFileMap;
    int                     mnFileSize;
    int                     mnRefCount;
    int                     mnLangBoost;
};

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

// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
                           FtFontInfo( const ImplDevFontAttributes&,
                               const ::rtl::OString& rNativeFileName,
                               int nFaceNum, sal_IntPtr nFontId, int nSynthetic,
                                const ExtraKernInfo* );
                          ~FtFontInfo();

    const unsigned char*  GetTable( const char*, ULONG* pLength=0 ) const;

    FT_FaceRec_*          GetFaceFT();
    void                  ReleaseFaceFT( FT_FaceRec_* );

    const ::rtl::OString* GetFontFileName() const   { return mpFontFile->GetFileName(); }
    int                   GetFaceNum() const        { return mnFaceNum; }
    int                   GetSynthetic() const      { return mnSynthetic; }
    sal_IntPtr            GetFontId() const         { return mnFontId; }
    bool                  DontUseAntiAlias() const
        { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }
    bool                  DontUseEmbeddedBitmaps() const
        { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }
    bool                  IsSymbolFont() const      { return maDevFontAttributes.IsSymbolFont(); }
    const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }

    void                  AnnounceFont( ImplDevFontList* );

    int                   GetGlyphIndex( sal_UCS4 cChar ) const;
    void                  CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;

    bool                  HasExtraKerning() const;
    int                   GetExtraKernPairs( ImplKernPairData** ) const;
    int                   GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;

private:
    FT_FaceRec_*    maFaceFT;
    FtFontFile*     mpFontFile;
    const int       mnFaceNum;
    int             mnRefCount;
    const int       mnSynthetic;

    sal_IntPtr      mnFontId;
    ImplDevFontAttributes maDevFontAttributes;

    // cache unicode->glyphid mapping because looking it up is expensive
    // TODO: change to hash_multimap when a use case requires a m:n mapping
    typedef ::std::hash_map<int,int> Int2IntMap;
    mutable Int2IntMap maChar2Glyph;
    mutable Int2IntMap maGlyph2Char;

    const ExtraKernInfo* mpExtraKernInfo;
};

// these two inlines are very important for performance

inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
    Int2IntMap::const_iterator it = maChar2Glyph.find( cChar );
    if( it == maChar2Glyph.end() )
        return -1;
    return it->second;
}

inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
    maChar2Glyph[ cChar ] = nIndex;
    maGlyph2Char[ nIndex ] = cChar;
}

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

class FreetypeManager
{
public:
                        FreetypeManager();
                        ~FreetypeManager();

    long                AddFontDir( const String& rUrlName );
    void                AddFontFile( const rtl::OString& rNormalizedName,
                            int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,
                            const ExtraKernInfo* );
    void                AnnounceFonts( ImplDevFontList* ) const;
    void                ClearFontList();

    FreetypeServerFont* CreateFont( const ImplFontSelectData& );

private:
    typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;
    FontList            maFontList;

    sal_IntPtr          mnMaxFontId;
    sal_IntPtr          mnNextFontId;
};

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

class FreetypeServerFont : public ServerFont
{
public:
                                FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
    virtual                     ~FreetypeServerFont();

    virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
    virtual int                 GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
    virtual bool                TestFont() const;

    virtual void                FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;

    virtual int                 GetGlyphIndex( sal_UCS4 ) const;
    int                         GetRawGlyphIndex( sal_UCS4 ) const;
    int                         FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;

    virtual bool                GetAntialiasAdvice( void ) const;
    virtual bool                GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
    virtual int                 GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    const unsigned char*        GetTable( const char* pName, ULONG* pLength )
                                { return mpFontInfo->GetTable( pName, pLength ); }
    int                         GetEmUnits() const;
    const FT_Size_Metrics&      GetMetricsFT() const { return maSizeFT->metrics; }

protected:
    friend class GlyphCache;

    int                         ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
    virtual void                InitGlyphData( int nGlyphIndex, GlyphData& ) const;
    virtual ULONG               GetFontCodeRanges( sal_uInt32* pCodes ) const;
    bool                        ApplyGSUB( const ImplFontSelectData& );
    virtual ServerFontLayoutEngine* GetLayoutEngine();

private:
    int                         mnWidth;
    int                         mnPrioEmbedded;
    int                         mnPrioAntiAlias;
    FtFontInfo*                 mpFontInfo;
    FT_Int                      mnLoadFlags;
    double                      mfStretch;
    FT_FaceRec_*                maFaceFT;
    FT_SizeRec_*                maSizeFT;

    bool            mbArtItalic;
    bool            mbArtBold;
    bool            mbUseGamma;

    typedef ::std::hash_map<int,int> GlyphSubstitution;
    GlyphSubstitution           maGlyphSubstitution;
    rtl_UnicodeToTextConverter  maRecodeConverter;

    ServerFontLayoutEngine*     mpLayoutEngine;
};

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

class ImplFTSFontData : public ImplFontData
{
private:
    FtFontInfo*             mpFtFontInfo;
    enum { IFTSFONT_MAGIC = 0x1F150A1C };

public:
                            ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );

    FtFontInfo*             GetFtFontInfo() const { return mpFtFontInfo; }

    virtual ImplFontEntry*  CreateFontInstance( ImplFontSelectData& ) const;
    virtual ImplFontData*   Clone() const   { return new ImplFTSFontData( *this ); }
    virtual sal_IntPtr      GetFontId() const { return mpFtFontInfo->GetFontId(); }

    static bool             CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};

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

#endif // _SV_GCACHFTYP_HXX
<|endoftext|>


<commit_before><commit_msg>vcl: WinSalGraphics: don't crash if there's no font<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2013, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#define L10N                                           // Localization complete.

#include <stdlib.h>
#include <Context.h>
#include <Date.h>
#include <ColDescription.h>
#include <text.h>
#include <utf8.h>
#include <util.h>
#include <i18n.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
ColumnDescription::ColumnDescription ()
{
  _name  = "description";
  _type  = "string";
  _style = "combined";
  _label = STRING_COLUMN_LABEL_DESC;

  _styles.push_back ("combined");
  _styles.push_back ("desc");
  _styles.push_back ("oneline");
  _styles.push_back ("truncated");
  _styles.push_back ("count");

  _dateformat = context.config.get ("dateformat.annotation");
  if (_dateformat == "")
    _dateformat = context.config.get ("dateformat");

  std::string t  = Date ().toString (_dateformat);
  std::string d  = STRING_COLUMN_EXAMPLES_DESC;
  std::string a1 = STRING_COLUMN_EXAMPLES_ANNO1;
  std::string a2 = STRING_COLUMN_EXAMPLES_ANNO2;
  std::string a3 = STRING_COLUMN_EXAMPLES_ANNO3;
  std::string a4 = STRING_COLUMN_EXAMPLES_ANNO4;

  _examples.push_back (d
                       + "\n  " + t + " " + a1
                       + "\n  " + t + " " + a2
                       + "\n  " + t + " " + a3
                       + "\n  " + t + " " + a4);
  _examples.push_back (d);
  _examples.push_back (d
                       + " " + t + " " + a1
                       + " " + t + " " + a2
                       + " " + t + " " + a3
                       + " " + t + " " + a4);
  _examples.push_back (d.substr (0, 20) + "...");
  _examples.push_back (d + " [4]");

  _hyphenate = context.config.getBoolean ("hyphenate");

  _indent = context.config.getInteger ("indent.annotation");
}

////////////////////////////////////////////////////////////////////////////////
ColumnDescription::~ColumnDescription ()
{
}

////////////////////////////////////////////////////////////////////////////////
bool ColumnDescription::validate (std::string& value)
{
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// Set the minimum and maximum widths for the value.
void ColumnDescription::measure (Task& task, unsigned int& minimum, unsigned int& maximum)
{
  std::string description = task.get (_name);

  // The text
  // <indent> <date> <anno>
  // ...
  if (_style == "default" ||
      _style == "combined")
  {
    minimum = longestWord (description);
    maximum = utf8_width (description);

    if (task.annotation_count)
    {
      int min_anno = _indent + Date::length (_dateformat);
      if (min_anno > minimum)
        minimum = min_anno;

      std::map <std::string, std::string> annos;
      task.getAnnotations (annos);
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        unsigned int len = min_anno + 1 + utf8_width (i->second);
        if (len > maximum)
          maximum = len;
      }
    }
  }

  // Just the text
  else if (_style == "desc")
  {
    maximum = utf8_width (description);
    minimum = longestWord (description);
  }

  // The text <date> <anno> ...
  else if (_style == "oneline")
  {
    minimum = longestWord (description);
    maximum = utf8_width (description);

    if (task.annotation_count)
    {
      int min_anno = Date::length (_dateformat);
      std::map <std::string, std::string> annos;
      task.getAnnotations (annos);
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
        maximum += min_anno + 1 + utf8_width (i->second);
    }
  }

  // The te...
  else if (_style == "truncated")
  {
    minimum = 4;
    maximum = utf8_width (description);
  }

  // The text [2]
  else if (_style == "count")
  {
    // <description> + ' ' + '[' + <count> + ']'
    maximum = utf8_width (description) + 1 + 1 + format (task.annotation_count).length () + 1;
    minimum = longestWord (description);
  }

  else
    throw format (STRING_COLUMN_BAD_FORMAT, _name, _style);
}

////////////////////////////////////////////////////////////////////////////////
void ColumnDescription::render (
  std::vector <std::string>& lines,
  Task& task,
  int width,
  Color& color)
{
  std::string description = task.get (_name);

  // This is a description
  // <date> <anno>
  // ...
  if (_style == "default" ||
      _style == "combined")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);
    if (annos.size ())
    {
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        Date dt (strtol (i->first.substr (11).c_str (), NULL, 10));
        description += "\n" + std::string (_indent, ' ') + dt.toString (_dateformat) + " " + i->second;
      }
    }

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a description
  else if (_style == "desc")
  {
    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a description <date> <anno> ...
  else if (_style == "oneline")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);
    if (annos.size ())
    {
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        Date dt (atoi (i->first.substr (11).c_str ()));
        description += " " + dt.toString (_dateformat) + " " + i->second;
      }
    }

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a des...
  else if (_style == "truncated")
  {
    int len = utf8_width (description);
    if (len > width)
      lines.push_back (color.colorize (description.substr (0, width - 3) + "..."));
    else
      lines.push_back (color.colorize (leftJustify (description, width)));
  }

  // This is a description [2]
  else if (_style == "count")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);

    if (annos.size ())
      description += " [" + format ((int) annos.size ()) + "]";

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Build Warnings<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2013, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#define L10N                                           // Localization complete.

#include <stdlib.h>
#include <Context.h>
#include <Date.h>
#include <ColDescription.h>
#include <text.h>
#include <utf8.h>
#include <util.h>
#include <i18n.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
ColumnDescription::ColumnDescription ()
{
  _name  = "description";
  _type  = "string";
  _style = "combined";
  _label = STRING_COLUMN_LABEL_DESC;

  _styles.push_back ("combined");
  _styles.push_back ("desc");
  _styles.push_back ("oneline");
  _styles.push_back ("truncated");
  _styles.push_back ("count");

  _dateformat = context.config.get ("dateformat.annotation");
  if (_dateformat == "")
    _dateformat = context.config.get ("dateformat");

  std::string t  = Date ().toString (_dateformat);
  std::string d  = STRING_COLUMN_EXAMPLES_DESC;
  std::string a1 = STRING_COLUMN_EXAMPLES_ANNO1;
  std::string a2 = STRING_COLUMN_EXAMPLES_ANNO2;
  std::string a3 = STRING_COLUMN_EXAMPLES_ANNO3;
  std::string a4 = STRING_COLUMN_EXAMPLES_ANNO4;

  _examples.push_back (d
                       + "\n  " + t + " " + a1
                       + "\n  " + t + " " + a2
                       + "\n  " + t + " " + a3
                       + "\n  " + t + " " + a4);
  _examples.push_back (d);
  _examples.push_back (d
                       + " " + t + " " + a1
                       + " " + t + " " + a2
                       + " " + t + " " + a3
                       + " " + t + " " + a4);
  _examples.push_back (d.substr (0, 20) + "...");
  _examples.push_back (d + " [4]");

  _hyphenate = context.config.getBoolean ("hyphenate");

  _indent = context.config.getInteger ("indent.annotation");
}

////////////////////////////////////////////////////////////////////////////////
ColumnDescription::~ColumnDescription ()
{
}

////////////////////////////////////////////////////////////////////////////////
bool ColumnDescription::validate (std::string& value)
{
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// Set the minimum and maximum widths for the value.
void ColumnDescription::measure (Task& task, unsigned int& minimum, unsigned int& maximum)
{
  std::string description = task.get (_name);

  // The text
  // <indent> <date> <anno>
  // ...
  if (_style == "default" ||
      _style == "combined")
  {
    minimum = longestWord (description);
    maximum = utf8_width (description);

    if (task.annotation_count)
    {
      unsigned int min_anno = _indent + Date::length (_dateformat);
      if (min_anno > minimum)
        minimum = min_anno;

      std::map <std::string, std::string> annos;
      task.getAnnotations (annos);
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        unsigned int len = min_anno + 1 + utf8_width (i->second);
        if (len > maximum)
          maximum = len;
      }
    }
  }

  // Just the text
  else if (_style == "desc")
  {
    maximum = utf8_width (description);
    minimum = longestWord (description);
  }

  // The text <date> <anno> ...
  else if (_style == "oneline")
  {
    minimum = longestWord (description);
    maximum = utf8_width (description);

    if (task.annotation_count)
    {
      unsigned int min_anno = Date::length (_dateformat);
      std::map <std::string, std::string> annos;
      task.getAnnotations (annos);
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
        maximum += min_anno + 1 + utf8_width (i->second);
    }
  }

  // The te...
  else if (_style == "truncated")
  {
    minimum = 4;
    maximum = utf8_width (description);
  }

  // The text [2]
  else if (_style == "count")
  {
    // <description> + ' ' + '[' + <count> + ']'
    maximum = utf8_width (description) + 1 + 1 + format (task.annotation_count).length () + 1;
    minimum = longestWord (description);
  }

  else
    throw format (STRING_COLUMN_BAD_FORMAT, _name, _style);
}

////////////////////////////////////////////////////////////////////////////////
void ColumnDescription::render (
  std::vector <std::string>& lines,
  Task& task,
  int width,
  Color& color)
{
  std::string description = task.get (_name);

  // This is a description
  // <date> <anno>
  // ...
  if (_style == "default" ||
      _style == "combined")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);
    if (annos.size ())
    {
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        Date dt (strtol (i->first.substr (11).c_str (), NULL, 10));
        description += "\n" + std::string (_indent, ' ') + dt.toString (_dateformat) + " " + i->second;
      }
    }

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a description
  else if (_style == "desc")
  {
    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a description <date> <anno> ...
  else if (_style == "oneline")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);
    if (annos.size ())
    {
      std::map <std::string, std::string>::iterator i;
      for (i = annos.begin (); i != annos.end (); i++)
      {
        Date dt (atoi (i->first.substr (11).c_str ()));
        description += " " + dt.toString (_dateformat) + " " + i->second;
      }
    }

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }

  // This is a des...
  else if (_style == "truncated")
  {
    int len = utf8_width (description);
    if (len > width)
      lines.push_back (color.colorize (description.substr (0, width - 3) + "..."));
    else
      lines.push_back (color.colorize (leftJustify (description, width)));
  }

  // This is a description [2]
  else if (_style == "count")
  {
    std::map <std::string, std::string> annos;
    task.getAnnotations (annos);

    if (annos.size ())
      description += " [" + format ((int) annos.size ()) + "]";

    std::vector <std::string> raw;
    wrapText (raw, description, width, _hyphenate);

    std::vector <std::string>::iterator i;
    for (i = raw.begin (); i != raw.end (); ++i)
      lines.push_back (color.colorize (leftJustify (*i, width)));
  }
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


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

#include "common/application_data.h"

#include <package_manager.h>
#include <manifest_parser/manifest_handler.h>
#include <manifest_handlers/widget_config_parser.h>
#include <manifest_handlers/application_manifest_constants.h>

#include <vector>

#include "common/logger.h"
#include "common/file_utils.h"

namespace wrt {

namespace {

const char* kPathSeparator = "/";
const char* kConfigXml = "config.xml";

static std::string GetPackageIdByAppId(const std::string& appid) {
  char* pkgid = NULL;
  package_manager_get_package_id_by_app_id(appid.c_str(), &pkgid);

  std::unique_ptr<char, decltype(std::free)*>
    pkgid_ptr {pkgid, std::free};

  if (pkgid != NULL) {
    return std::string(pkgid_ptr.get());
  } else {
    return std::string();
  }
}

static std::string GetPackageRootPath(const std::string& pkgid) {
  package_info_h pkg_info = NULL;
  if (package_manager_get_package_info(
        pkgid.c_str(), &pkg_info) != PACKAGE_MANAGER_ERROR_NONE) {
    return std::string();
  }

  char* pkg_root_path = NULL;
  package_info_get_root_path(pkg_info, &pkg_root_path);

  std::unique_ptr<char, decltype(std::free)*>
    path_ptr {pkg_root_path, std::free};

  package_info_destroy(pkg_info);

  if (pkg_root_path != NULL) {
    return std::string(path_ptr.get());
  } else {
    return std::string();
  }
}

}  // namespace

ApplicationData::ApplicationData(const std::string& appid) : app_id_(appid) {
  pkg_id_ = GetPackageIdByAppId(appid);

  if (!pkg_id_.empty()) {
    application_path_ = GetPackageRootPath(pkg_id_) + kPathSeparator +
                        appid + kPathSeparator;
  }
}

ApplicationData::~ApplicationData() {}

std::shared_ptr<const wgt::parse::AppControlInfoList>
    ApplicationData::app_control_info_list() const {
  return app_control_info_list_;
}

std::shared_ptr<const wgt::parse::CategoryInfoList>
    ApplicationData::category_info_list() const {
  return category_info_list_;
}

std::shared_ptr<const wgt::parse::MetaDataInfo>
    ApplicationData::meta_data_info() const {
  return meta_data_info_;
}

std::shared_ptr<const wgt::parse::AllowedNavigationInfo>
    ApplicationData::allowed_navigation_info() const {
  return allowed_navigation_info_;
}

std::shared_ptr<const wgt::parse::PermissionsInfo>
    ApplicationData::permissions_info() const {
  return permissions_info_;
}

std::shared_ptr<const wgt::parse::SettingInfo>
    ApplicationData::setting_info() const {
  return setting_info_;
}

std::shared_ptr<const wgt::parse::SplashScreenInfo>
    ApplicationData::splash_screen_info() const {
  return splash_screen_info_;
}

std::shared_ptr<const wgt::parse::TizenApplicationInfo>
    ApplicationData::tizen_application_info() const {
  return tizen_application_info_;
}

std::shared_ptr<const wgt::parse::WidgetInfo>
    ApplicationData::widget_info() const {
  return widget_info_;
}

std::shared_ptr<const wgt::parse::ContentInfo>
    ApplicationData::content_info() const {
  return content_info_;
}

std::shared_ptr<const wgt::parse::WarpInfo>
    ApplicationData::warp_info() const {
  return warp_info_;
}

std::shared_ptr<const wgt::parse::CSPInfo>
    ApplicationData::csp_info() const {
  return csp_info_;
}

std::shared_ptr<const wgt::parse::CSPInfo>
    ApplicationData::csp_report_info() const {
  return csp_report_info_;
}

bool ApplicationData::LoadManifestData() {
  std::string config_xml_path(application_path_ + kConfigXml);
  if (!utils::Exists(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load manifest data. : No such file '"
                  << config_xml_path << "'.";
    return false;
  }

  std::unique_ptr<wgt::parse::WidgetConfigParser> widget_config_parser;
  widget_config_parser.reset(new wgt::parse::WidgetConfigParser());
  if (!widget_config_parser->ParseManifest(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load widget config parser data: "
                  << widget_config_parser->GetErrorMessage();
    return false;
  }

  app_control_info_list_ =
    std::static_pointer_cast<const wgt::parse::AppControlInfoList>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenApplicationAppControlsKey));

  category_info_list_ =
    std::static_pointer_cast<const wgt::parse::CategoryInfoList>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenCategoryKey));

  meta_data_info_ =
    std::static_pointer_cast<const wgt::parse::MetaDataInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenMetaDataKey));

  allowed_navigation_info_ =
    std::static_pointer_cast<const wgt::parse::AllowedNavigationInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kAllowNavigationKey));

  permissions_info_ =
    std::static_pointer_cast<const wgt::parse::PermissionsInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenPermissionsKey));

  setting_info_ =
    std::static_pointer_cast<const wgt::parse::SettingInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenSettingKey));

  splash_screen_info_ =
    std::static_pointer_cast<const wgt::parse::SplashScreenInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenSplashScreenKey));

  tizen_application_info_ =
    std::static_pointer_cast<const wgt::parse::TizenApplicationInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenApplicationKey));

  widget_info_ =
    std::static_pointer_cast<const wgt::parse::WidgetInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenWidgetKey));

  content_info_ =
    std::static_pointer_cast<const wgt::parse::ContentInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenContentKey));

  warp_info_ =
    std::static_pointer_cast<const wgt::parse::WarpInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kAccessKey));

  std::unique_ptr<parser::ManifestHandlerRegistry> csp_registry;
  csp_registry.reset(new parser::ManifestHandlerRegistry({
    new wgt::parse::CSPHandler(wgt::parse::CSPHandler::SecurityType::CSP),
    new wgt::parse::CSPHandler(
      wgt::parse::CSPHandler::SecurityType::CSP_REPORT_ONLY)
  }));

  parser::ManifestParser csp_parser(std::move(csp_registry));
  if (!csp_parser.ParseManifest(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load manifest data : "
                  << csp_parser.GetErrorMessage();
    return false;
  }

  csp_info_ =
    std::static_pointer_cast<const wgt::parse::CSPInfo>(
      csp_parser.GetManifestData(
        wgt::application_widget_keys::kCSPKey));

  csp_report_info_ =
    std::static_pointer_cast<const wgt::parse::CSPInfo>(
      csp_parser.GetManifestData(
        wgt::application_widget_keys::kCSPReportOnlyKey));

  // Set default empty object
  if (widget_info_.get() == NULL) {
    widget_info_.reset(new wgt::parse::WidgetInfo);
  }
  if (setting_info_.get() == NULL) {
    setting_info_.reset(new wgt::parse::SettingInfo);
  }

  return true;
}

}  // namespace wrt
<commit_msg>Apply application path to restore 2.x directory structure<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#include "common/application_data.h"

#include <package_manager.h>
#include <manifest_parser/manifest_handler.h>
#include <manifest_handlers/widget_config_parser.h>
#include <manifest_handlers/application_manifest_constants.h>

#include <vector>

#include "common/logger.h"
#include "common/file_utils.h"

namespace wrt {

namespace {

const char* kPathSeparator = "/";
const char* kConfigXml = "config.xml";
const char* kResWgtPath = "res/wgt";

static std::string GetPackageIdByAppId(const std::string& appid) {
  char* pkgid = NULL;
  package_manager_get_package_id_by_app_id(appid.c_str(), &pkgid);

  std::unique_ptr<char, decltype(std::free)*>
    pkgid_ptr {pkgid, std::free};

  if (pkgid != NULL) {
    return std::string(pkgid_ptr.get());
  } else {
    LOGGER(ERROR) << "Failed to get package id";
    return std::string();
  }
}

static std::string GetPackageRootPath(const std::string& pkgid) {
  package_info_h pkg_info = NULL;
  if (package_manager_get_package_info(
        pkgid.c_str(), &pkg_info) != PACKAGE_MANAGER_ERROR_NONE) {
    return std::string();
  }

  char* pkg_root_path = NULL;
  package_info_get_root_path(pkg_info, &pkg_root_path);

  std::unique_ptr<char, decltype(std::free)*>
    path_ptr {pkg_root_path, std::free};

  package_info_destroy(pkg_info);

  if (pkg_root_path != NULL) {
    return std::string(path_ptr.get());
  } else {
    LOGGER(ERROR) << "Failed to get package root path";
    return std::string();
  }
}

}  // namespace

ApplicationData::ApplicationData(const std::string& appid) : app_id_(appid) {
  pkg_id_ = GetPackageIdByAppId(appid);
  if (!pkg_id_.empty())
    application_path_ = GetPackageRootPath(pkg_id_) + kPathSeparator
                        + kResWgtPath + kPathSeparator;
}

ApplicationData::~ApplicationData() {}

std::shared_ptr<const wgt::parse::AppControlInfoList>
    ApplicationData::app_control_info_list() const {
  return app_control_info_list_;
}

std::shared_ptr<const wgt::parse::CategoryInfoList>
    ApplicationData::category_info_list() const {
  return category_info_list_;
}

std::shared_ptr<const wgt::parse::MetaDataInfo>
    ApplicationData::meta_data_info() const {
  return meta_data_info_;
}

std::shared_ptr<const wgt::parse::AllowedNavigationInfo>
    ApplicationData::allowed_navigation_info() const {
  return allowed_navigation_info_;
}

std::shared_ptr<const wgt::parse::PermissionsInfo>
    ApplicationData::permissions_info() const {
  return permissions_info_;
}

std::shared_ptr<const wgt::parse::SettingInfo>
    ApplicationData::setting_info() const {
  return setting_info_;
}

std::shared_ptr<const wgt::parse::SplashScreenInfo>
    ApplicationData::splash_screen_info() const {
  return splash_screen_info_;
}

std::shared_ptr<const wgt::parse::TizenApplicationInfo>
    ApplicationData::tizen_application_info() const {
  return tizen_application_info_;
}

std::shared_ptr<const wgt::parse::WidgetInfo>
    ApplicationData::widget_info() const {
  return widget_info_;
}

std::shared_ptr<const wgt::parse::ContentInfo>
    ApplicationData::content_info() const {
  return content_info_;
}

std::shared_ptr<const wgt::parse::WarpInfo>
    ApplicationData::warp_info() const {
  return warp_info_;
}

std::shared_ptr<const wgt::parse::CSPInfo>
    ApplicationData::csp_info() const {
  return csp_info_;
}

std::shared_ptr<const wgt::parse::CSPInfo>
    ApplicationData::csp_report_info() const {
  return csp_report_info_;
}

bool ApplicationData::LoadManifestData() {
  std::string config_xml_path(application_path_ + kConfigXml);
  if (!utils::Exists(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load manifest data : No such file '"
                  << config_xml_path << "'.";
    return false;
  }

  std::unique_ptr<wgt::parse::WidgetConfigParser> widget_config_parser;
  widget_config_parser.reset(new wgt::parse::WidgetConfigParser());
  if (!widget_config_parser->ParseManifest(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load widget config parser data: "
                  << widget_config_parser->GetErrorMessage();
    return false;
  }

  app_control_info_list_ =
    std::static_pointer_cast<const wgt::parse::AppControlInfoList>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenApplicationAppControlsKey));

  category_info_list_ =
    std::static_pointer_cast<const wgt::parse::CategoryInfoList>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenCategoryKey));

  meta_data_info_ =
    std::static_pointer_cast<const wgt::parse::MetaDataInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenMetaDataKey));

  allowed_navigation_info_ =
    std::static_pointer_cast<const wgt::parse::AllowedNavigationInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kAllowNavigationKey));

  permissions_info_ =
    std::static_pointer_cast<const wgt::parse::PermissionsInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenPermissionsKey));

  setting_info_ =
    std::static_pointer_cast<const wgt::parse::SettingInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenSettingKey));

  splash_screen_info_ =
    std::static_pointer_cast<const wgt::parse::SplashScreenInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenSplashScreenKey));

  tizen_application_info_ =
    std::static_pointer_cast<const wgt::parse::TizenApplicationInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenApplicationKey));

  widget_info_ =
    std::static_pointer_cast<const wgt::parse::WidgetInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenWidgetKey));

  content_info_ =
    std::static_pointer_cast<const wgt::parse::ContentInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kTizenContentKey));

  warp_info_ =
    std::static_pointer_cast<const wgt::parse::WarpInfo>(
      widget_config_parser->GetManifestData(
        wgt::application_widget_keys::kAccessKey));

  std::unique_ptr<parser::ManifestHandlerRegistry> csp_registry;
  csp_registry.reset(new parser::ManifestHandlerRegistry({
    new wgt::parse::CSPHandler(wgt::parse::CSPHandler::SecurityType::CSP),
    new wgt::parse::CSPHandler(
      wgt::parse::CSPHandler::SecurityType::CSP_REPORT_ONLY)
  }));

  parser::ManifestParser csp_parser(std::move(csp_registry));
  if (!csp_parser.ParseManifest(config_xml_path)) {
    LOGGER(ERROR) << "Failed to load manifest data : "
                  << csp_parser.GetErrorMessage();
    return false;
  }

  csp_info_ =
    std::static_pointer_cast<const wgt::parse::CSPInfo>(
      csp_parser.GetManifestData(
        wgt::application_widget_keys::kCSPKey));

  csp_report_info_ =
    std::static_pointer_cast<const wgt::parse::CSPInfo>(
      csp_parser.GetManifestData(
        wgt::application_widget_keys::kCSPReportOnlyKey));

  // Set default empty object
  if (widget_info_.get() == NULL) {
    widget_info_.reset(new wgt::parse::WidgetInfo);
  }
  if (setting_info_.get() == NULL) {
    setting_info_.reset(new wgt::parse::SettingInfo);
  }

  return true;
}

}  // namespace wrt
<|endoftext|>