<commit_before>
#include "swganh/command/command_service.h"

#include <cctype>

#include "anh/app/kernel_interface.h"

#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher.h"
#include "anh/database/database_manager_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/command/command_filter.h"

#include "swganh/messages/controllers/command_queue_enqueue.h"
#include "swganh/messages/controllers/command_queue_remove.h"
#include "swganh/messages/controllers/combat_action_message.h"

#include "swganh/object/creature/creature.h"
#include "swganh/object/object_controller.h"

#include "python_command.h"
#include "swganh/simulation/simulation_service.h"

using namespace anh::app;
using namespace anh::service;
using namespace std;
using namespace swganh::command;
using namespace swganh::messages;
using namespace swganh::messages::controllers;
using namespace swganh::object;
using namespace swganh::object::creature;
using namespace swganh::scripting;
using namespace swganh::simulation;

using boost::asio::deadline_timer;
using boost::posix_time::milliseconds;

CommandService::CommandService(KernelInterface* kernel)
: BaseService(kernel)
{}

ServiceDescription CommandService::GetServiceDescription()
{
    ServiceDescription service_description(
        "CommandService",
        "command",
        "0.1",
        "127.0.0.1",
        0,
        0,
        0);

    return service_description;
}

void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)
{
	enqueue_filters_.push_back(move(filter));
}

void CommandService::AddCommandProcessFilter(CommandFilter&& filter)
{
    process_filters_.push_back(move(filter));
}

void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)
{
    handlers_[command_crc] = move(handler);
}

void CommandService::EnqueueCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    CommandQueueEnqueue command)
{
    bool is_valid;
    uint32_t error = 0, action = 0;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);

    if (!is_valid)
    {
        LOG(WARNING) << "Invalid command";
        SendCommandQueueRemove(actor, command, 0.0f, error, action);
        return;
    }
	auto object_id = actor->GetObjectId();
    command_queues_[object_id].push(command);

    if (!command_queue_timers_[object_id])
    {
        command_queue_timers_[object_id] = make_shared<deadline_timer>(kernel()->GetIoService());
        command_queue_timers_[object_id]->expires_from_now(
                milliseconds(command_properties_map_[command.command_crc].default_time));

        command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
    }
}

void CommandService::HandleCommandQueueEnqueue(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{
    auto actor = dynamic_pointer_cast<Creature>(controller->GetObject());

    CommandQueueEnqueue enqueue;
    enqueue.Deserialize(message.data);

	auto target = simulation_service_->GetObjectById(enqueue.target_id);

    auto find_iter = command_properties_map_.find(enqueue.command_crc);

    if (find_iter == command_properties_map_.end())
    {
        LOG(WARNING) << "Invalid handler requested: " << hex << enqueue.command_crc;
        return;
    }

    auto cooldown_find_iter = cooldown_timers_[actor->GetObjectId()].find(enqueue.command_crc);

    if (cooldown_find_iter != cooldown_timers_[actor->GetObjectId()].end())
    {
        LOG(WARNING) << "Cooldown timer still running";
		SendCommandQueueRemove(actor, enqueue, 0.0f, 0, 0);
        return;
    }

    if (find_iter->second.add_to_combat_queue)
    {
        EnqueueCommand(actor, target, enqueue);
    }
    else
    {
        ProcessCommand(actor, target, enqueue);
    }
}

void CommandService::HandleCommandQueueRemove(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{}

void CommandService::ProcessNextCommand(const shared_ptr<Creature>& actor)
{
    auto find_iter = command_queues_.find(actor->GetObjectId());

    CommandQueueEnqueue command;

    if (!find_iter->second.try_pop(command))
    {
        return;
    }

    auto target = simulation_service_->GetObjectById(command.target_id);

    ProcessCommand(actor, target, command);

    command_queue_timers_[actor->GetObjectId()]->expires_from_now(
        milliseconds(command_properties_map_[command.command_crc].default_time));

    command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
}

void CommandService::ProcessCommand(const shared_ptr<Creature>& actor, const shared_ptr<Object>& target, const swganh::messages::controllers::CommandQueueEnqueue& command)
{
	auto object_id = actor->GetObjectId();

    auto find_iter = handlers_.find(command.command_crc);

    if (find_iter == handlers_.end())
    {
        LOG(WARNING) << "No handler for command: " << std::hex << command.command_crc;
        return;
    }

    bool is_valid;
    uint32_t error = 0, action = 0;

    std::tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);

    if (is_valid)
    {
		find_iter->second(actor, target, command);

        SendCommandQueueRemove(actor, command, command_properties_map_[command.command_crc].default_time, 0, 0);

        if (command_properties_map_[command.command_crc].default_time != 0)
        {
            cooldown_timers_[object_id][command.command_crc] = make_shared<boost::asio::deadline_timer>(kernel()->GetIoService());

            cooldown_timers_[object_id][command.command_crc]->expires_from_now(
                boost::posix_time::milliseconds(command_properties_map_[command.command_crc].default_time));

            cooldown_timers_[object_id][command.command_crc]->async_wait([this, object_id, command] (const boost::system::error_code& ec) {
                cooldown_timers_[object_id].erase(command.command_crc);
            });
        }
    }

    SendCommandQueueRemove(actor, command, 0.0f, error, action);
}

void CommandService::onStart()
{
	LoadProperties();

    simulation_service_ = kernel()->GetServiceManager()
        ->GetService<SimulationService>("SimulationService");

    simulation_service_->RegisterControllerHandler(0x00000116, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueEnqueue(controller, message);
    });

    simulation_service_->RegisterControllerHandler(0x00000117, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueRemove(controller, message);
    });

	auto event_dispatcher = kernel()->GetEventDispatcher();
	event_dispatcher->Dispatch(
        make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties()));
}

void CommandService::LoadProperties()
{
    try {
        auto db_manager = kernel()->GetDatabaseManager();

        auto conn = db_manager->getConnection("galaxy");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();"));

        auto result = shared_ptr<sql::ResultSet>(statement->executeQuery());

        while (result->next())
        {
            CommandProperties properties;

            properties.name = result->getString("name");

            string tmp = properties.name;
            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
            properties.name_crc = anh::memcrc(tmp);

            properties.ability = result->getString("ability");
            properties.ability_crc = anh::memcrc(properties.ability);
            properties.deny_in_states = result->getUInt64("deny_in_states");
            properties.script_hook = result->getString("script_hook");
            properties.fail_script_hook = result->getString("fail_script_hook");
            properties.default_time = result->getUInt64("default_time");
            properties.command_group = result->getUInt("command_group");
            properties.max_range_to_target = result->getDouble("max_range_to_target");
            properties.add_to_combat_queue = result->getUInt("add_to_combat_queue");
            properties.health_cost = result->getUInt("health_cost");
            properties.health_cost_multiplier = result->getUInt("health_cost_multiplier");
            properties.action_cost = result->getUInt("action_cost");
            properties.action_cost_multiplier = result->getUInt("action_cost_multiplier");
            properties.mind_cost = result->getUInt("mind_cost");
            properties.mind_cost_multiplier = result->getUInt("mind_cost");
            properties.damage_multiplier = result->getDouble("damage_multiplier");
            properties.delay_multiplier = result->getDouble("delay_multiplier");
            properties.force_cost = result->getUInt("force_cost");
            properties.force_cost_multiplier = result->getUInt("force_cost_multiplier");
            properties.animation_crc = result->getUInt("animation_crc");
            properties.required_weapon_group = result->getUInt("required_weapon_group");
            properties.combat_spam = result->getString("combat_spam");
            properties.trail1 = result->getUInt("trail1");
            properties.trail2 = result->getUInt("trail2");
            properties.allow_in_posture = result->getUInt("allow_in_posture");
            properties.health_hit_chance = result->getDouble("health_hit_chance");
            properties.action_hit_chance = result->getDouble("action_hit_chance");
            properties.mind_hit_chance = result->getDouble("mind_hit_chance");
            properties.knockdown_hit_chance = result->getDouble("knockdown_chance");
            properties.dizzy_hit_chance = result->getDouble("dizzy_chance");
            properties.blind_chance = result->getDouble("blind_chance");
            properties.stun_chance = result->getDouble("stun_chance");
            properties.intimidate_chance = result->getDouble("intimidate_chance");
            properties.posture_down_chance = result->getDouble("posture_down_chance");
            properties.extended_range = result->getDouble("extended_range");
            properties.cone_angle = result->getDouble("cone_angle");
            properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion");

            command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));

            RegisterCommandScript(properties);
        }

        DLOG(WARNING) << "Loaded (" << command_properties_map_.size() << ") Commands";
    }
    catch(sql::SQLException &e)
    {
        DLOG(ERROR) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        DLOG(ERROR) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
}

void CommandService::RegisterCommandScript(const CommandProperties& properties)
{
    if (properties.script_hook.length() == 0)
    {
        return;
    }

    SetCommandHandler(properties.name_crc, PythonCommand(properties));
}

tuple<bool, uint32_t, uint32_t> CommandService::ValidateCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    const CommandProperties& command_properties,
    const std::vector<CommandFilter>& filters)
{
	tuple<bool, uint32_t, uint32_t> result;
    bool all_run = all_of(
        begin(filters),
        end(filters),
        [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool
    {
        result =  filter(actor, target, command, command_properties);
		return get<0>(result);
    });

    return result;
}

void CommandService::SendCommandQueueRemove(
    const shared_ptr<Creature>& actor,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    float default_time,
    uint32_t error,
    uint32_t action)
{
    CommandQueueRemove remove;
    remove.action_counter = command.action_counter;
    remove.timer = default_time / 1000; // Convert from milliseconds to seconds
    remove.error = error;
    remove.action = action;

	actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));
}
<commit_msg>Cleaned out unnecessary return path.<commit_after>
#include "swganh/command/command_service.h"

#include <cctype>

#include "anh/app/kernel_interface.h"

#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher.h"
#include "anh/database/database_manager_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/command/command_filter.h"

#include "swganh/messages/controllers/command_queue_enqueue.h"
#include "swganh/messages/controllers/command_queue_remove.h"
#include "swganh/messages/controllers/combat_action_message.h"

#include "swganh/object/creature/creature.h"
#include "swganh/object/object_controller.h"

#include "python_command.h"
#include "swganh/simulation/simulation_service.h"

using namespace anh::app;
using namespace anh::service;
using namespace std;
using namespace swganh::command;
using namespace swganh::messages;
using namespace swganh::messages::controllers;
using namespace swganh::object;
using namespace swganh::object::creature;
using namespace swganh::scripting;
using namespace swganh::simulation;

using boost::asio::deadline_timer;
using boost::posix_time::milliseconds;

CommandService::CommandService(KernelInterface* kernel)
: BaseService(kernel)
{}

ServiceDescription CommandService::GetServiceDescription()
{
    ServiceDescription service_description(
        "CommandService",
        "command",
        "0.1",
        "127.0.0.1",
        0,
        0,
        0);

    return service_description;
}

void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)
{
	enqueue_filters_.push_back(move(filter));
}

void CommandService::AddCommandProcessFilter(CommandFilter&& filter)
{
    process_filters_.push_back(move(filter));
}

void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)
{
    handlers_[command_crc] = move(handler);
}

void CommandService::EnqueueCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    CommandQueueEnqueue command)
{
    bool is_valid;
    uint32_t error = 0, action = 0;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);

    if (!is_valid)
    {
        LOG(WARNING) << "Invalid command";
        SendCommandQueueRemove(actor, command, 0.0f, error, action);
        return;
    }
	auto object_id = actor->GetObjectId();
    command_queues_[object_id].push(command);

    if (!command_queue_timers_[object_id])
    {
        command_queue_timers_[object_id] = make_shared<deadline_timer>(kernel()->GetIoService());
        command_queue_timers_[object_id]->expires_from_now(
                milliseconds(command_properties_map_[command.command_crc].default_time));

        command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
    }
}

void CommandService::HandleCommandQueueEnqueue(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{
    auto actor = dynamic_pointer_cast<Creature>(controller->GetObject());

    CommandQueueEnqueue enqueue;
    enqueue.Deserialize(message.data);

	auto target = simulation_service_->GetObjectById(enqueue.target_id);

    auto find_iter = command_properties_map_.find(enqueue.command_crc);

    if (find_iter == command_properties_map_.end())
    {
        LOG(WARNING) << "Invalid handler requested: " << hex << enqueue.command_crc;
        return;
    }

    auto cooldown_find_iter = cooldown_timers_[actor->GetObjectId()].find(enqueue.command_crc);

    if (cooldown_find_iter != cooldown_timers_[actor->GetObjectId()].end())
    {
        LOG(WARNING) << "Cooldown timer still running";
		SendCommandQueueRemove(actor, enqueue, 0.0f, 0, 0);
        return;
    }

    if (find_iter->second.add_to_combat_queue)
    {
        EnqueueCommand(actor, target, enqueue);
    }
    else
    {
        ProcessCommand(actor, target, enqueue);
    }
}

void CommandService::HandleCommandQueueRemove(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{}

void CommandService::ProcessNextCommand(const shared_ptr<Creature>& actor)
{
    auto find_iter = command_queues_.find(actor->GetObjectId());

    CommandQueueEnqueue command;

    if (!find_iter->second.try_pop(command))
    {
        return;
    }

    auto target = simulation_service_->GetObjectById(command.target_id);

    ProcessCommand(actor, target, command);

    command_queue_timers_[actor->GetObjectId()]->expires_from_now(
        milliseconds(command_properties_map_[command.command_crc].default_time));

    command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
}

void CommandService::ProcessCommand(const shared_ptr<Creature>& actor, const shared_ptr<Object>& target, const swganh::messages::controllers::CommandQueueEnqueue& command)
{
	auto object_id = actor->GetObjectId();

    auto find_iter = handlers_.find(command.command_crc);

    if (find_iter == handlers_.end())
    {
        LOG(WARNING) << "No handler for command: " << std::hex << command.command_crc;
        return;
    }

    bool is_valid;
    uint32_t error = 0, action = 0;

    std::tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);

    if (is_valid)
    {
		find_iter->second(actor, target, command);

        SendCommandQueueRemove(actor, command, command_properties_map_[command.command_crc].default_time, 0, 0);

        if (command_properties_map_[command.command_crc].default_time != 0)
        {
            cooldown_timers_[object_id][command.command_crc] = make_shared<boost::asio::deadline_timer>(kernel()->GetIoService());

            cooldown_timers_[object_id][command.command_crc]->expires_from_now(
                boost::posix_time::milliseconds(command_properties_map_[command.command_crc].default_time));

            cooldown_timers_[object_id][command.command_crc]->async_wait([this, object_id, command] (const boost::system::error_code& ec) {
                cooldown_timers_[object_id].erase(command.command_crc);
            });
        }
    }

    SendCommandQueueRemove(actor, command, 0.0f, error, action);
}

void CommandService::onStart()
{
	LoadProperties();

    simulation_service_ = kernel()->GetServiceManager()
        ->GetService<SimulationService>("SimulationService");

    simulation_service_->RegisterControllerHandler(0x00000116, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueEnqueue(controller, message);
    });

    simulation_service_->RegisterControllerHandler(0x00000117, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueRemove(controller, message);
    });

	auto event_dispatcher = kernel()->GetEventDispatcher();
	event_dispatcher->Dispatch(
        make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties()));
}

void CommandService::LoadProperties()
{
    try {
        auto db_manager = kernel()->GetDatabaseManager();

        auto conn = db_manager->getConnection("galaxy");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();"));

        auto result = shared_ptr<sql::ResultSet>(statement->executeQuery());

        while (result->next())
        {
            CommandProperties properties;

            properties.name = result->getString("name");

            string tmp = properties.name;
            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
            properties.name_crc = anh::memcrc(tmp);

            properties.ability = result->getString("ability");
            properties.ability_crc = anh::memcrc(properties.ability);
            properties.deny_in_states = result->getUInt64("deny_in_states");
            properties.script_hook = result->getString("script_hook");
            properties.fail_script_hook = result->getString("fail_script_hook");
            properties.default_time = result->getUInt64("default_time");
            properties.command_group = result->getUInt("command_group");
            properties.max_range_to_target = result->getDouble("max_range_to_target");
            properties.add_to_combat_queue = result->getUInt("add_to_combat_queue");
            properties.health_cost = result->getUInt("health_cost");
            properties.health_cost_multiplier = result->getUInt("health_cost_multiplier");
            properties.action_cost = result->getUInt("action_cost");
            properties.action_cost_multiplier = result->getUInt("action_cost_multiplier");
            properties.mind_cost = result->getUInt("mind_cost");
            properties.mind_cost_multiplier = result->getUInt("mind_cost");
            properties.damage_multiplier = result->getDouble("damage_multiplier");
            properties.delay_multiplier = result->getDouble("delay_multiplier");
            properties.force_cost = result->getUInt("force_cost");
            properties.force_cost_multiplier = result->getUInt("force_cost_multiplier");
            properties.animation_crc = result->getUInt("animation_crc");
            properties.required_weapon_group = result->getUInt("required_weapon_group");
            properties.combat_spam = result->getString("combat_spam");
            properties.trail1 = result->getUInt("trail1");
            properties.trail2 = result->getUInt("trail2");
            properties.allow_in_posture = result->getUInt("allow_in_posture");
            properties.health_hit_chance = result->getDouble("health_hit_chance");
            properties.action_hit_chance = result->getDouble("action_hit_chance");
            properties.mind_hit_chance = result->getDouble("mind_hit_chance");
            properties.knockdown_hit_chance = result->getDouble("knockdown_chance");
            properties.dizzy_hit_chance = result->getDouble("dizzy_chance");
            properties.blind_chance = result->getDouble("blind_chance");
            properties.stun_chance = result->getDouble("stun_chance");
            properties.intimidate_chance = result->getDouble("intimidate_chance");
            properties.posture_down_chance = result->getDouble("posture_down_chance");
            properties.extended_range = result->getDouble("extended_range");
            properties.cone_angle = result->getDouble("cone_angle");
            properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion");

            command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));

            RegisterCommandScript(properties);
        }

        DLOG(WARNING) << "Loaded (" << command_properties_map_.size() << ") Commands";
    }
    catch(sql::SQLException &e)
    {
        DLOG(ERROR) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        DLOG(ERROR) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
}

void CommandService::RegisterCommandScript(const CommandProperties& properties)
{
    if (properties.script_hook.length() != 0)
    {
        SetCommandHandler(properties.name_crc, PythonCommand(properties));
    }
}

tuple<bool, uint32_t, uint32_t> CommandService::ValidateCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    const CommandProperties& command_properties,
    const std::vector<CommandFilter>& filters)
{
	tuple<bool, uint32_t, uint32_t> result;
    bool all_run = all_of(
        begin(filters),
        end(filters),
        [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool
    {
        result =  filter(actor, target, command, command_properties);
		return get<0>(result);
    });

    return result;
}

void CommandService::SendCommandQueueRemove(
    const shared_ptr<Creature>& actor,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    float default_time,
    uint32_t error,
    uint32_t action)
{
    CommandQueueRemove remove;
    remove.action_counter = command.action_counter;
    remove.timer = default_time / 1000; // Convert from milliseconds to seconds
    remove.error = error;
    remove.action = action;

	actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsystemscreensaver.h"
#include "qsysteminfocommon_p.h"

QTM_BEGIN_NAMESPACE

/////
 /*!
   \class QSystemScreenSaver
   \ingroup systeminfo
   \inmodule QtSystemInfo

    \brief The QSystemScreenSaver class provides access to screen saver and blanking.

   On platforms where there is no one default screensaver mechanism, such as Linux, this class
   may not be available.
*/

/*!
   Constructs a QSystemScreenSaver object with the given \a parent.
 */
QSystemScreenSaver::QSystemScreenSaver(QObject *parent)
    : QObject(parent)
{
#if defined(Q_OS_LINUX) && !defined(QT_SIMULATOR)
    d = new QSystemScreenSaverPrivate(static_cast<QSystemScreenSaverLinuxCommonPrivate*>(parent));
#else
    d = new QSystemScreenSaverPrivate(parent);
#endif
    screenSaverIsInhibited = screenSaverInhibited();
}

/*!
  Destroys the QSystemScreenSaver object.
 */
QSystemScreenSaver::~QSystemScreenSaver()
{
    delete d;
}

/*!
  \brief Set the screensaver to be inhibited.

   Temporarily inhibits the screensaver.

   The screensaver will be set to a non inhibited state only when this QSystemScreenSaver object gets destroyed.

   This is a non blocking function that will return true if the inhibit procedure was successful, otherwise false.

    On platforms that support it, if screensaver is secure by policy, the policy will be honored
    and this will fail.
*/
bool QSystemScreenSaver::setScreenSaverInhibit()
{
    return d->setScreenSaverInhibit();
}

/*!
  \property QSystemScreenSaver::screenSaverInhibited
  \brief Screensaver inhibited.

   Returns true if the screensaver is inhibited, otherwise false.
*/
bool QSystemScreenSaver::screenSaverInhibited()
{
    return d->screenSaverInhibited();
}

void QSystemScreenSaver::setScreenSaverInhibited(bool on)
{
    return d->setScreenSaverInhibited(on);
}

#include "moc_qsystemscreensaver.cpp"

QTM_END_NAMESPACE
<commit_msg>fix build<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsystemscreensaver.h"
#include "qsysteminfocommon_p.h"

QTM_BEGIN_NAMESPACE

/////
 /*!
   \class QSystemScreenSaver
   \ingroup systeminfo
   \inmodule QtSystemInfo

    \brief The QSystemScreenSaver class provides access to screen saver and blanking.

   On platforms where there is no one default screensaver mechanism, such as Linux, this class
   may not be available.
*/

/*!
   Constructs a QSystemScreenSaver object with the given \a parent.
 */
QSystemScreenSaver::QSystemScreenSaver(QObject *parent)
    : QObject(parent)
{
#if defined(Q_OS_LINUX) && !defined(QT_SIMULATOR)
    d = new QSystemScreenSaverPrivate(static_cast<QSystemScreenSaverLinuxCommonPrivate*>(parent));
#else
    d = new QSystemScreenSaverPrivate(parent);
#endif
    screenSaverIsInhibited = screenSaverInhibited();
}

/*!
  Destroys the QSystemScreenSaver object.
 */
QSystemScreenSaver::~QSystemScreenSaver()
{
    delete d;
}

/*!
  \brief Set the screensaver to be inhibited.

   Temporarily inhibits the screensaver.

   The screensaver will be set to a non inhibited state only when this QSystemScreenSaver object gets destroyed.

   This is a non blocking function that will return true if the inhibit procedure was successful, otherwise false.

    On platforms that support it, if screensaver is secure by policy, the policy will be honored
    and this will fail.
*/
bool QSystemScreenSaver::setScreenSaverInhibit()
{
    return d->setScreenSaverInhibit();
}

/*!
  \property QSystemScreenSaver::screenSaverInhibited
  \brief Screensaver inhibited.

   Returns true if the screensaver is inhibited, otherwise false.
*/
bool QSystemScreenSaver::screenSaverInhibited()
{
    return d->screenSaverInhibited();
}

void QSystemScreenSaver::setScreenSaverInhibited(bool on)
{
     d->setScreenSaverInhibited(on);
}

#include "moc_qsystemscreensaver.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>//
// Created by pkanev on 12/8/2017.
//

#include <include/v8.h>
#include <assert.h>
#include <android/log.h>
#include <cstdlib>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <V8GlobalHelpers.h>
#include <v8_inspector/src/inspector/v8-log-agent-impl.h>
#include <JsV8InspectorClient.h>
#include "Console.h"

namespace tns {

v8::Local<v8::Object> Console::createConsole(v8::Local<v8::Context> context, const std::string& filesPath) {
    v8::Context::Scope contextScope(context);
    v8::Isolate* isolate = context->GetIsolate();

    v8::Local<v8::Object> console = v8::Object::New(isolate);
    bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false);

    assert(success);

    std::map<std::string, double> timersMap;
    Console::s_isolateToConsoleTimersMap.insert(std::make_pair(context->GetIsolate(), timersMap));

    bindFunctionProperty(context, console, "assert", assertCallback);
    bindFunctionProperty(context, console, "error", errorCallback);
    bindFunctionProperty(context, console, "info", infoCallback);
    bindFunctionProperty(context, console, "log", logCallback);
    bindFunctionProperty(context, console, "warn", warnCallback);
    bindFunctionProperty(context, console, "dir", dirCallback);
    bindFunctionProperty(context, console, "trace", traceCallback);
    bindFunctionProperty(context, console, "time", timeCallback);
    bindFunctionProperty(context, console, "timeEnd", timeEndCallback);

    return console;
}

void Console::sendToADBLogcat(const std::string& message, android_LogPriority logPriority) {
    // split strings into chunks of 4000 characters
    // __android_log_write can't send more than 4000 to the stdout at a time

    auto messageLength = message.length();
    int maxStringLength = 4000;

    if (messageLength < maxStringLength) {
        __android_log_write(logPriority, Console::LOG_TAG, message.c_str());
    } else {
        for (int i = 0; i < messageLength; i += maxStringLength) {
            auto messagePart = message.substr(i, maxStringLength);

            __android_log_write(logPriority, Console::LOG_TAG, messagePart.c_str());
        }
    }
}

void Console::sendToDevToolsFrontEnd(v8::Isolate* isolate, const std::string& message, const std::string& logLevel) {
    if (!JsV8InspectorClient::inspectorIsConnected()) {
        return;
    }

    auto stack = v8::StackTrace::CurrentStackTrace(isolate, 1, v8::StackTrace::StackTraceOptions::kDetailed);

    auto frame = stack->GetFrame(0);

    // will be no-op in non-debuggable builds
    v8_inspector::V8LogAgentImpl::EntryAdded(message, logLevel, ArgConverter::ConvertToString(frame->GetScriptNameOrSourceURL()), frame->GetLineNumber());
}

const v8::Local<v8::String> transformJSObject(v8::Isolate* isolate, v8::Local<v8::Object> object) {
    auto objToString = object->ToString(isolate);
    v8::Local<v8::String> resultString;

    auto hasCustomToStringImplementation = !objToString->SameValue(ArgConverter::ConvertToV8String(isolate, "[object Object]"));

    if (hasCustomToStringImplementation) {
        resultString = objToString;
    } else {
        resultString = JsonStringifyObject(isolate, object);
    }

    return resultString;
}

const std::string buildLogString(const v8::FunctionCallbackInfo<v8::Value>& info, int startingIndex = 0) {
    auto isolate = info.GetIsolate();

    v8::HandleScope scope(isolate);

    std::stringstream ss;

    auto argLen = info.Length();
    if (argLen) {
        for (int i = startingIndex; i < argLen; i++) {
            v8::Local<v8::String> argString;
            if (info[i]->IsFunction()) {
                info[i]->ToDetailString(isolate->GetCurrentContext()).ToLocal(&argString);
            } else if (info[i]->IsObject()) {
                v8::Local<v8::Object> obj = info[i].As<v8::Object>();

                argString = transformJSObject(isolate, obj);
            } else {
                info[i]->ToDetailString(isolate->GetCurrentContext()).ToLocal(&argString);
            }

            // separate args with a space
            if (i != 0) {
                ss << " ";
            }

            ss << ArgConverter::ConvertToString(argString);
        }
    } else {
        ss << std::endl;
    }

    std::string stringResult = ss.str();

    return stringResult;
}

void Console::assertCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    auto argLen = info.Length();
    auto expressionPasses = argLen && info[0]->BooleanValue();

    if (!expressionPasses) {
        std::stringstream assertionError;

        assertionError << "Assertion failed: ";

        if (argLen > 1) {
            assertionError << buildLogString(info, 1);
        } else {
            assertionError << "console.assert";
        }

        std::string log = assertionError.str();
        sendToADBLogcat(log, ANDROID_LOG_ERROR);
        sendToDevToolsFrontEnd(isolate, log, "error");
    }
}

void Console::errorCallback(const v8::FunctionCallbackInfo <v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_ERROR);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "error");
}

void Console::infoCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "info");
}

void Console::logCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "info");
}

void Console::warnCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_WARN);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "warning");
}

void Console::dirCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();
    auto context = isolate->GetCurrentContext();

    v8::HandleScope scope(isolate);

    std::stringstream ss;

    auto argLen = info.Length();
    if (argLen) {
        if (info[0]->IsObject()) {
            ss << "==== object dump start ====" << std::endl;
            v8::Local<v8::Object> argObject = info[0].As<v8::Object>();

            v8::Local<v8::Array> propNames;
            argObject->GetPropertyNames(context).ToLocal(&propNames);

            auto propertiesLen = propNames->Length();
            for (int i = 0; i < propertiesLen; i++) {
                auto propertyName = propNames->Get(context, i).ToLocalChecked();
                auto propertyValue = argObject->Get(context, propertyName).ToLocalChecked();

                auto propIsFunction = propertyValue->IsFunction();

                ss << ArgConverter::ConvertToString(propertyName->ToString(isolate));

                if (propIsFunction) {
                    ss << "()";
                } else if (propertyValue->IsObject()) {
                    auto obj = propertyValue->ToObject(isolate);
                    auto objString = transformJSObject(isolate, obj);
                    std::string jsonStringifiedObject = ArgConverter::ConvertToString(objString);
                    // if object prints out as the error string for circular references, replace with #CR instead for brevity
                    if (jsonStringifiedObject.find("circular structure") != std::string::npos) {
                        jsonStringifiedObject = "#CR";
                    }
                    ss << ": " << jsonStringifiedObject;
                } else {
                    ss << ": \"" << ArgConverter::ConvertToString(propertyValue->ToDetailString(isolate)) << "\"";
                }

                ss << std::endl;
            }

            ss << "==== object dump end ====" << std::endl;
        } else {
            std::string logString = buildLogString(info);

            ss << logString;
        }
    } else {
        ss << std::endl;
    }

    std::string log = ss.str();

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(isolate, log, "info");
}

const std::string buildStacktraceFrameLocationPart(v8::Local<v8::StackFrame> frame) {
    std::stringstream ss;

    auto scriptName = frame->GetScriptNameOrSourceURL();
    auto scriptNameConverted = ArgConverter::ConvertToString(scriptName);
    if (scriptNameConverted.length() < 1) {
        ss << "VM";
    } else {
        ss << scriptNameConverted << ":" << frame->GetLineNumber() << ":" << frame->GetColumn();
    }

    std::string stringResult = ss.str();

    return stringResult;
}

const std::string buildStacktraceFrameMessage(v8::Local<v8::StackFrame> frame) {
    std::stringstream ss;

    auto functionName = frame->GetFunctionName();
    auto functionNameConverted = ArgConverter::ConvertToString(functionName);
    if (functionNameConverted.length() < 1) {
        functionNameConverted = "<anonymous>";
    }

    if (frame->IsConstructor()) {
        ss << "at new " << functionNameConverted << " (" << buildStacktraceFrameLocationPart(frame) << ")";
    } else if (frame->IsEval()) {
        ss << "eval at " << buildStacktraceFrameLocationPart(frame) << std::endl;
    } else {
        ss << "at " << functionNameConverted << " (" << buildStacktraceFrameLocationPart(frame) << ")";
    }

    std::string stringResult = ss.str();

    return stringResult;
}

void Console::traceCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();
    std::stringstream ss;

    std::string logString = buildLogString(info);

    if (logString.compare("\n") == 0) {
        ss << "Trace";
    } else {
        ss << "Trace: " << logString;
    }

    ss << std::endl;

    v8::HandleScope scope(isolate);

    auto stack = v8::StackTrace::CurrentStackTrace(isolate, 10, v8::StackTrace::StackTraceOptions::kDetailed);

    auto framesCount = stack->GetFrameCount();

    for (int i = 0; i < framesCount; i++) {
        auto frame = stack->GetFrame(i);

        ss << buildStacktraceFrameMessage(frame) << std::endl;
    }

    std::string log = ss.str();
    __android_log_write(ANDROID_LOG_ERROR, LOG_TAG, log.c_str());
    sendToDevToolsFrontEnd(isolate, log, "error");
}

void Console::timeCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    v8::HandleScope scope(isolate);

    auto argLen = info.Length();
    std::string label = "default";

    v8::Local<v8::String> argString;
    if (argLen && info[0]->ToString(isolate->GetCurrentContext()).ToLocal(&argString)) {
        label = ArgConverter::ConvertToString(argString);
    }

    auto it = Console::s_isolateToConsoleTimersMap.find(isolate);
    if (it == Console::s_isolateToConsoleTimersMap.end()) {
        // throw?
    }

    auto nano = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    double timeStamp = nano.time_since_epoch().count();

    it->second.insert(std::make_pair(label, timeStamp));
}

void Console::timeEndCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    auto argLen = info.Length();
    std::string label = "default";

    v8::Local<v8::String> argString;
    if (argLen && info[0]->ToString(isolate->GetCurrentContext()).ToLocal(&argString)) {
        label = ArgConverter::ConvertToString(argString);
    }

    auto it = Console::s_isolateToConsoleTimersMap.find(isolate);
    if (it == Console::s_isolateToConsoleTimersMap.end()) {
        // throw?
    }

    std::map<std::string, double> timersMap = it->second;

    auto itTimersMap = timersMap.find(label);
    if (itTimersMap == timersMap.end()) {
        std::string warning = std::string("No such label '" + label + "' for console.timeEnd()");

        __android_log_write(ANDROID_LOG_WARN, LOG_TAG, warning.c_str());
        sendToDevToolsFrontEnd(isolate, warning, "warning");

        return;
    }

    auto nano = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    double endTimeStamp = nano.time_since_epoch().count();
    double startTimeStamp = itTimersMap->second;

    it->second.erase(label);

    auto diff = endTimeStamp - startTimeStamp;

    std::stringstream ss;
    ss << label << ": " << std::fixed << std::setprecision(2) << diff << "ms" ;
    std::string log = ss.str();

    __android_log_write(ANDROID_LOG_INFO, LOG_TAG, log.c_str());
    sendToDevToolsFrontEnd(isolate, log, "info");
}

const char* Console::LOG_TAG = "JS";
std::map<v8::Isolate*, std::map<std::string, double>> Console::s_isolateToConsoleTimersMap;
}<commit_msg>fix(console): prioritize array printing before object printing in order to properly transform array entries<commit_after>//
// Created by pkanev on 12/8/2017.
//

#include <include/v8.h>
#include <assert.h>
#include <android/log.h>
#include <cstdlib>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <V8GlobalHelpers.h>
#include <v8_inspector/src/inspector/v8-log-agent-impl.h>
#include <JsV8InspectorClient.h>
#include "Console.h"

namespace tns {

v8::Local<v8::Object> Console::createConsole(v8::Local<v8::Context> context, const std::string& filesPath) {
    v8::Context::Scope contextScope(context);
    v8::Isolate* isolate = context->GetIsolate();

    v8::Local<v8::Object> console = v8::Object::New(isolate);
    bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false);

    assert(success);

    std::map<std::string, double> timersMap;
    Console::s_isolateToConsoleTimersMap.insert(std::make_pair(context->GetIsolate(), timersMap));

    bindFunctionProperty(context, console, "assert", assertCallback);
    bindFunctionProperty(context, console, "error", errorCallback);
    bindFunctionProperty(context, console, "info", infoCallback);
    bindFunctionProperty(context, console, "log", logCallback);
    bindFunctionProperty(context, console, "warn", warnCallback);
    bindFunctionProperty(context, console, "dir", dirCallback);
    bindFunctionProperty(context, console, "trace", traceCallback);
    bindFunctionProperty(context, console, "time", timeCallback);
    bindFunctionProperty(context, console, "timeEnd", timeEndCallback);

    return console;
}

void Console::sendToADBLogcat(const std::string& message, android_LogPriority logPriority) {
    // split strings into chunks of 4000 characters
    // __android_log_write can't send more than 4000 to the stdout at a time

    auto messageLength = message.length();
    int maxStringLength = 4000;

    if (messageLength < maxStringLength) {
        __android_log_write(logPriority, Console::LOG_TAG, message.c_str());
    } else {
        for (int i = 0; i < messageLength; i += maxStringLength) {
            auto messagePart = message.substr(i, maxStringLength);

            __android_log_write(logPriority, Console::LOG_TAG, messagePart.c_str());
        }
    }
}

void Console::sendToDevToolsFrontEnd(v8::Isolate* isolate, const std::string& message, const std::string& logLevel) {
    if (!JsV8InspectorClient::inspectorIsConnected()) {
        return;
    }

    auto stack = v8::StackTrace::CurrentStackTrace(isolate, 1, v8::StackTrace::StackTraceOptions::kDetailed);

    auto frame = stack->GetFrame(0);

    // will be no-op in non-debuggable builds
    v8_inspector::V8LogAgentImpl::EntryAdded(message, logLevel, ArgConverter::ConvertToString(frame->GetScriptNameOrSourceURL()), frame->GetLineNumber());
}

const v8::Local<v8::String> transformJSObject(v8::Isolate* isolate, v8::Local<v8::Object> object) {
    auto objToString = object->ToString(isolate);
    v8::Local<v8::String> resultString;

    auto hasCustomToStringImplementation = ArgConverter::ConvertToString(objToString).find("[object Object]") == std::string::npos;

    if (hasCustomToStringImplementation) {
        resultString = objToString;
    } else {
        resultString = JsonStringifyObject(isolate, object);
    }

    return resultString;
}

const v8::Local<v8::String> buildStringFromArg(v8::Isolate* isolate, const v8::Local<v8::Value>& val) {
    v8::Local<v8::String> argString;
    if (val->IsFunction()) {
        val->ToDetailString(isolate->GetCurrentContext()).ToLocal(&argString);
    } else if (val->IsArray()) {
        auto cachedSelf = val;
        auto array = val->ToObject();
        auto arrayEntryKeys = array->GetPropertyNames(isolate->GetCurrentContext()).ToLocalChecked();
        auto context = isolate->GetCurrentContext();

        auto arrayLength = arrayEntryKeys->Length();

        argString = ArgConverter::ConvertToV8String(isolate, "[");

        for (int i = 0; i < arrayLength; i++) {
            auto propertyName = arrayEntryKeys->Get(context, i).ToLocalChecked();

            auto propertyValue = array->Get(context, propertyName).ToLocalChecked();

            // avoid bottomless recursion with cyclic reference to the same array
            if (propertyValue->StrictEquals(cachedSelf)) {
                argString = v8::String::Concat(argString, ArgConverter::ConvertToV8String(isolate, "[Circular]"));
                continue;
            }

            auto objectString = buildStringFromArg(isolate, propertyValue);

            argString = v8::String::Concat(argString, objectString);

            if (i != arrayLength - 1) {
                argString = v8::String::Concat(argString, ArgConverter::ConvertToV8String(isolate, ", "));
            }
        }

        argString = v8::String::Concat(argString, ArgConverter::ConvertToV8String(isolate, "]"));
    } else if (val->IsObject()) {
        v8::Local<v8::Object> obj = val.As<v8::Object>();

        argString = transformJSObject(isolate, obj);
    } else {
        val->ToDetailString(isolate->GetCurrentContext()).ToLocal(&argString);
    }

    return argString;
}

const std::string buildLogString(const v8::FunctionCallbackInfo<v8::Value>& info, int startingIndex = 0) {
    auto isolate = info.GetIsolate();

    v8::HandleScope scope(isolate);

    std::stringstream ss;

    auto argLen = info.Length();
    if (argLen) {
        for (int i = startingIndex; i < argLen; i++) {
            v8::Local<v8::String> argString;

            argString = buildStringFromArg(isolate, info[i]);

            // separate args with a space
            if (i != 0) {
                ss << " ";
            }

            ss << ArgConverter::ConvertToString(argString);
        }
    } else {
        ss << std::endl;
    }

    std::string stringResult = ss.str();

    return stringResult;
}

void Console::assertCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    auto argLen = info.Length();
    auto expressionPasses = argLen && info[0]->BooleanValue();

    if (!expressionPasses) {
        std::stringstream assertionError;

        assertionError << "Assertion failed: ";

        if (argLen > 1) {
            assertionError << buildLogString(info, 1);
        } else {
            assertionError << "console.assert";
        }

        std::string log = assertionError.str();
        sendToADBLogcat(log, ANDROID_LOG_ERROR);
        sendToDevToolsFrontEnd(isolate, log, "error");
    }
}

void Console::errorCallback(const v8::FunctionCallbackInfo <v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_ERROR);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "error");
}

void Console::infoCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "info");
}

void Console::logCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "info");
}

void Console::warnCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    std::string log = buildLogString(info);

    sendToADBLogcat(log, ANDROID_LOG_WARN);
    sendToDevToolsFrontEnd(info.GetIsolate(), log, "warning");
}

void Console::dirCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();
    auto context = isolate->GetCurrentContext();

    v8::HandleScope scope(isolate);

    std::stringstream ss;

    auto argLen = info.Length();
    if (argLen) {
        if (info[0]->IsObject()) {
            ss << "==== object dump start ====" << std::endl;
            v8::Local<v8::Object> argObject = info[0].As<v8::Object>();

            v8::Local<v8::Array> propNames;
            argObject->GetPropertyNames(context).ToLocal(&propNames);

            auto propertiesLen = propNames->Length();
            for (int i = 0; i < propertiesLen; i++) {
                auto propertyName = propNames->Get(context, i).ToLocalChecked();
                auto propertyValue = argObject->Get(context, propertyName).ToLocalChecked();

                auto propIsFunction = propertyValue->IsFunction();

                ss << ArgConverter::ConvertToString(propertyName->ToString(isolate));

                if (propIsFunction) {
                    ss << "()";
                } else if (propertyValue->IsObject()) {
                    auto obj = propertyValue->ToObject(isolate);
                    auto objString = transformJSObject(isolate, obj);
                    std::string jsonStringifiedObject = ArgConverter::ConvertToString(objString);
                    // if object prints out as the error string for circular references, replace with #CR instead for brevity
                    if (jsonStringifiedObject.find("circular structure") != std::string::npos) {
                        jsonStringifiedObject = "#CR";
                    }
                    ss << ": " << jsonStringifiedObject;
                } else {
                    ss << ": \"" << ArgConverter::ConvertToString(propertyValue->ToDetailString(isolate)) << "\"";
                }

                ss << std::endl;
            }

            ss << "==== object dump end ====" << std::endl;
        } else {
            std::string logString = buildLogString(info);

            ss << logString;
        }
    } else {
        ss << std::endl;
    }

    std::string log = ss.str();

    sendToADBLogcat(log, ANDROID_LOG_INFO);
    sendToDevToolsFrontEnd(isolate, log, "info");
}

const std::string buildStacktraceFrameLocationPart(v8::Local<v8::StackFrame> frame) {
    std::stringstream ss;

    auto scriptName = frame->GetScriptNameOrSourceURL();
    auto scriptNameConverted = ArgConverter::ConvertToString(scriptName);
    if (scriptNameConverted.length() < 1) {
        ss << "VM";
    } else {
        ss << scriptNameConverted << ":" << frame->GetLineNumber() << ":" << frame->GetColumn();
    }

    std::string stringResult = ss.str();

    return stringResult;
}

const std::string buildStacktraceFrameMessage(v8::Local<v8::StackFrame> frame) {
    std::stringstream ss;

    auto functionName = frame->GetFunctionName();
    auto functionNameConverted = ArgConverter::ConvertToString(functionName);
    if (functionNameConverted.length() < 1) {
        functionNameConverted = "<anonymous>";
    }

    if (frame->IsConstructor()) {
        ss << "at new " << functionNameConverted << " (" << buildStacktraceFrameLocationPart(frame) << ")";
    } else if (frame->IsEval()) {
        ss << "eval at " << buildStacktraceFrameLocationPart(frame) << std::endl;
    } else {
        ss << "at " << functionNameConverted << " (" << buildStacktraceFrameLocationPart(frame) << ")";
    }

    std::string stringResult = ss.str();

    return stringResult;
}

void Console::traceCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();
    std::stringstream ss;

    std::string logString = buildLogString(info);

    if (logString.compare("\n") == 0) {
        ss << "Trace";
    } else {
        ss << "Trace: " << logString;
    }

    ss << std::endl;

    v8::HandleScope scope(isolate);

    auto stack = v8::StackTrace::CurrentStackTrace(isolate, 10, v8::StackTrace::StackTraceOptions::kDetailed);

    auto framesCount = stack->GetFrameCount();

    for (int i = 0; i < framesCount; i++) {
        auto frame = stack->GetFrame(i);

        ss << buildStacktraceFrameMessage(frame) << std::endl;
    }

    std::string log = ss.str();
    __android_log_write(ANDROID_LOG_ERROR, LOG_TAG, log.c_str());
    sendToDevToolsFrontEnd(isolate, log, "error");
}

void Console::timeCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    v8::HandleScope scope(isolate);

    auto argLen = info.Length();
    std::string label = "default";

    v8::Local<v8::String> argString;
    if (argLen && info[0]->ToString(isolate->GetCurrentContext()).ToLocal(&argString)) {
        label = ArgConverter::ConvertToString(argString);
    }

    auto it = Console::s_isolateToConsoleTimersMap.find(isolate);
    if (it == Console::s_isolateToConsoleTimersMap.end()) {
        // throw?
    }

    auto nano = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    double timeStamp = nano.time_since_epoch().count();

    it->second.insert(std::make_pair(label, timeStamp));
}

void Console::timeEndCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    auto isolate = info.GetIsolate();

    auto argLen = info.Length();
    std::string label = "default";

    v8::Local<v8::String> argString;
    if (argLen && info[0]->ToString(isolate->GetCurrentContext()).ToLocal(&argString)) {
        label = ArgConverter::ConvertToString(argString);
    }

    auto it = Console::s_isolateToConsoleTimersMap.find(isolate);
    if (it == Console::s_isolateToConsoleTimersMap.end()) {
        // throw?
    }

    std::map<std::string, double> timersMap = it->second;

    auto itTimersMap = timersMap.find(label);
    if (itTimersMap == timersMap.end()) {
        std::string warning = std::string("No such label '" + label + "' for console.timeEnd()");

        __android_log_write(ANDROID_LOG_WARN, LOG_TAG, warning.c_str());
        sendToDevToolsFrontEnd(isolate, warning, "warning");

        return;
    }

    auto nano = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    double endTimeStamp = nano.time_since_epoch().count();
    double startTimeStamp = itTimersMap->second;

    it->second.erase(label);

    auto diff = endTimeStamp - startTimeStamp;

    std::stringstream ss;
    ss << label << ": " << std::fixed << std::setprecision(2) << diff << "ms" ;
    std::string log = ss.str();

    __android_log_write(ANDROID_LOG_INFO, LOG_TAG, log.c_str());
    sendToDevToolsFrontEnd(isolate, log, "info");
}

const char* Console::LOG_TAG = "JS";
std::map<v8::Isolate*, std::map<std::string, double>> Console::s_isolateToConsoleTimersMap;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: configgroup.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:45:39 $
 *
 *  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 CONFIGMGR_CONFIGGROUP_HXX_
#define CONFIGMGR_CONFIGGROUP_HXX_

#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_
#include "configexcept.hxx"
#endif
#ifndef CONFIGMGR_CONFIGNODE_HXX_
#include "noderef.hxx"
#endif
#ifndef CONFIGMGR_CONFIG_DEFAULTPROVIDER_HXX_
#include "configdefaultprovider.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace script { class XTypeConverter; }
} } }

namespace configmgr
{
//-----------------------------------------------------------------------------
    namespace configuration
    {
//-----------------------------------------------------------------------------

        typedef com::sun::star::uno::Type       UnoType;
        typedef com::sun::star::uno::Any        UnoAny;
        typedef com::sun::star::uno::Reference<com::sun::star::script::XTypeConverter>  UnoTypeConverter;
//-----------------------------------------------------------------------------

        class NodeChange;
        class RelativePath;
//-----------------------------------------------------------------------------

        /// helper for updating a <type>NodeRef</type> that refers to a Group
        class GroupUpdateHelper
        {
            Tree    m_aTree;
            NodeRef m_aNode;
        public:
            GroupUpdateHelper(Tree const& aParentTree, NodeRef const& aGroupNode);
            ~GroupUpdateHelper() {}

            void validateNode(ValueRef const& aNode) const;
            void validateNode(NodeRef const& aNode) const;

            Tree    const& tree() const { return m_aTree; }
            NodeRef const& node() const { return m_aNode; }
        private:
            void implValidateTree(Tree const& aTree) const;
            void implValidateNode(Tree const& aTree, NodeRef const& aNode) const;
            void implValidateNode(Tree const& aTree, ValueRef const& aNode) const;
        };
//-----------------------------------------------------------------------------
        /// allows to update values of a simple type within a <type>NodeRef</type> that refers to a Group
        class GroupUpdater
        {
            GroupUpdateHelper   m_aHelper;
            UnoTypeConverter    m_xTypeConverter;
        public:
            GroupUpdater(Tree const& aParentTree, NodeRef const& aGroupNode, UnoTypeConverter const& xConverter);

            NodeChange validateSetValue(ValueRef const& aValueNode, UnoAny const& newValue );

        private:
            UnoAny implValidateValue(Tree const& aTree, ValueRef const& aNode, UnoAny const& aValue) const;
        };
//-----------------------------------------------------------------------------

        /// allows to reset to default value or state members of a <type>NodeRef</type> that refers to a Group
        class GroupDefaulter
        {
            GroupUpdateHelper   m_aHelper;
            DefaultProvider     m_aDefaultProvider;
            bool                m_bHasDoneSet;
        public:
            GroupDefaulter(Tree const& _aParentTree, NodeRef const& _aGroupNode, DefaultProvider const& _aProvider);

            bool hasDoneSet() const { return m_bHasDoneSet; }

            bool isDataAvailable();

            NodeChange validateSetToDefaultValue(ValueRef const& aValueNode);

            NodeChange validateSetToDefaultState(NodeRef const& aNode);

            NodeChanges validateSetAllToDefault();

            static bool isDataAvailable(TreeRef const& _aParentTree, NodeRef const& _aGroupNode);
            static bool ensureDataAvailable(TreeRef const& _aParentTree, NodeRef const& _aGroupNode, DefaultProvider const& _aSource);
        };
//-----------------------------------------------------------------------------
        bool isPossibleValueType(UnoType const& aValueType);
//-----------------------------------------------------------------------------
        bool convertCompatibleValue(UnoTypeConverter const& xConverter, uno::Any& rConverted,
                                    UnoAny const& rNewValue, UnoType const& rTargetType);
//-----------------------------------------------------------------------------
    }
}

#endif // CONFIGMGR_CONFIGGROUP_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.8.130); FILE MERGED 2008/04/01 12:27:23 thb 1.8.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:43 rt 1.8.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: configgroup.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CONFIGMGR_CONFIGGROUP_HXX_
#define CONFIGMGR_CONFIGGROUP_HXX_

#include "configexcept.hxx"
#include "noderef.hxx"
#include "configdefaultprovider.hxx"

namespace com { namespace sun { namespace star {
    namespace script { class XTypeConverter; }
} } }

namespace configmgr
{
//-----------------------------------------------------------------------------
    namespace configuration
    {
//-----------------------------------------------------------------------------

        typedef com::sun::star::uno::Type       UnoType;
        typedef com::sun::star::uno::Any        UnoAny;
        typedef com::sun::star::uno::Reference<com::sun::star::script::XTypeConverter>  UnoTypeConverter;
//-----------------------------------------------------------------------------

        class NodeChange;
        class RelativePath;
//-----------------------------------------------------------------------------

        /// helper for updating a <type>NodeRef</type> that refers to a Group
        class GroupUpdateHelper
        {
            Tree    m_aTree;
            NodeRef m_aNode;
        public:
            GroupUpdateHelper(Tree const& aParentTree, NodeRef const& aGroupNode);
            ~GroupUpdateHelper() {}

            void validateNode(ValueRef const& aNode) const;
            void validateNode(NodeRef const& aNode) const;

            Tree    const& tree() const { return m_aTree; }
            NodeRef const& node() const { return m_aNode; }
        private:
            void implValidateTree(Tree const& aTree) const;
            void implValidateNode(Tree const& aTree, NodeRef const& aNode) const;
            void implValidateNode(Tree const& aTree, ValueRef const& aNode) const;
        };
//-----------------------------------------------------------------------------
        /// allows to update values of a simple type within a <type>NodeRef</type> that refers to a Group
        class GroupUpdater
        {
            GroupUpdateHelper   m_aHelper;
            UnoTypeConverter    m_xTypeConverter;
        public:
            GroupUpdater(Tree const& aParentTree, NodeRef const& aGroupNode, UnoTypeConverter const& xConverter);

            NodeChange validateSetValue(ValueRef const& aValueNode, UnoAny const& newValue );

        private:
            UnoAny implValidateValue(Tree const& aTree, ValueRef const& aNode, UnoAny const& aValue) const;
        };
//-----------------------------------------------------------------------------

        /// allows to reset to default value or state members of a <type>NodeRef</type> that refers to a Group
        class GroupDefaulter
        {
            GroupUpdateHelper   m_aHelper;
            DefaultProvider     m_aDefaultProvider;
            bool                m_bHasDoneSet;
        public:
            GroupDefaulter(Tree const& _aParentTree, NodeRef const& _aGroupNode, DefaultProvider const& _aProvider);

            bool hasDoneSet() const { return m_bHasDoneSet; }

            bool isDataAvailable();

            NodeChange validateSetToDefaultValue(ValueRef const& aValueNode);

            NodeChange validateSetToDefaultState(NodeRef const& aNode);

            NodeChanges validateSetAllToDefault();

            static bool isDataAvailable(TreeRef const& _aParentTree, NodeRef const& _aGroupNode);
            static bool ensureDataAvailable(TreeRef const& _aParentTree, NodeRef const& _aGroupNode, DefaultProvider const& _aSource);
        };
//-----------------------------------------------------------------------------
        bool isPossibleValueType(UnoType const& aValueType);
//-----------------------------------------------------------------------------
        bool convertCompatibleValue(UnoTypeConverter const& xConverter, uno::Any& rConverted,
                                    UnoAny const& rNewValue, UnoType const& rTargetType);
//-----------------------------------------------------------------------------
    }
}

#endif // CONFIGMGR_CONFIGGROUP_HXX_
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <string>
#include "itkHeldIsotropicWavelet.h"
#include "itkVowIsotropicWavelet.h"
#include "itkSimoncelliIsotropicWavelet.h"
#include "itkShannonIsotropicWavelet.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkNumberToString.h"
using namespace std;
using namespace itk;
namespace itk{
namespace Testing {
// Generate values from a linear space
std::vector<double> linSpaceForIWFF(double init = 0.0, double end = 1.0, size_t points = 1000)
{
  std::vector<double> w_array(points);
  if(points <= 1)
    throw("linSpace needs more points");
  double interval = (end - init)/(points - 1);
  for(unsigned int i = 0; i < points; ++i)
    {
    w_array[i] = init + interval*i;
    }
  return w_array;
}
}
}

template <unsigned int N, typename TWaveletFunction>
int runIsotropicWaveletFrequencyFunctionTest(
    const std::string& profileDataRootPath,
    const std::string& outputImage,
    const unsigned int& inputBands,
    const std::string & waveletTypeName)
{
  itk::NumberToString<float> n2s;
  typedef TWaveletFunction WaveletFunctionType;
  typename WaveletFunctionType::Pointer motherWavelet =
    WaveletFunctionType::New();
  motherWavelet->SetHighPassSubBands(inputBands);

  double init = 0.0;
  double end = 1.0;
  size_t points = 1000;
  std::vector< double > w_array = itk::Testing::linSpaceForIWFF(init,end,points);
  // Generate profile data for sub-bands and mother wavelet itself
  std::vector< std::vector< double > > subBandsResults;
  for(unsigned int k = 0; k<inputBands + 2; ++k)
    {
    std::vector<double> bandResults;
    for(unsigned int i = 0; i<points; ++i)
      {
      if (k == inputBands + 1) // mother wavelet
        bandResults.push_back(motherWavelet->EvaluateMagnitude(w_array[i]));
      else // bands
        bandResults.push_back(motherWavelet->EvaluateForwardSubBand(w_array[i], k));
      }
    subBandsResults.push_back(bandResults);
    }

  // Write profile.
  std::ofstream ofs(profileDataRootPath + "_" + waveletTypeName +  "_" + n2s(inputBands) + ".txt", std::ofstream::out);
  for(unsigned int i = 0; i<points; ++i)
    {
    ofs << w_array[i];
    for(unsigned int k = 0; k<inputBands + 2; ++k)
      {
      ofs << "," << subBandsResults[k][i];
      }
    ofs << "\n";
    }
  ofs.close();
  return EXIT_SUCCESS;
}

int itkIsotropicWaveletFrequencyFunctionTest(int argc, char *argv[])
{
  if( argc < 5 || argc > 6 )
    {
    std::cerr << "Usage: " << argv[0] <<
      "profileDataRootPath outputImage inputBands waveletFunction [dimension]" << std::endl;
    return EXIT_FAILURE;
    }
  const string profileDataRootPath  = argv[1];
  const string outputImage = argv[2];
  const unsigned int inputBands  = atoi(argv[3]);
  const string waveletFunction  = argv[4];
  unsigned int dimension = 3;
  if( argc == 6 )
    {
    dimension = atoi( argv[5] );
    }

  typedef itk::HeldIsotropicWavelet<>       HeldWavelet;
  typedef itk::VowIsotropicWavelet<>        VowWavelet;
  typedef itk::SimoncelliIsotropicWavelet<> SimoncelliWavelet;
  typedef itk::ShannonIsotropicWavelet<>    ShannonWavelet;
  if( dimension == 2 )
    {
    if (waveletFunction == "Held")
      return runIsotropicWaveletFrequencyFunctionTest<2, HeldWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Vow")
      return runIsotropicWaveletFrequencyFunctionTest<2, VowWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Simoncelli")
      return runIsotropicWaveletFrequencyFunctionTest<2, SimoncelliWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Shannon")
      return runIsotropicWaveletFrequencyFunctionTest<2, ShannonWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else
      {
      std::cerr << argv[4] << " is an unknown wavelet type " << std::endl;
      return EXIT_FAILURE;
      }
    }
  else if( dimension == 3 )
    {
    if (waveletFunction == "Held")
      return runIsotropicWaveletFrequencyFunctionTest<3, HeldWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Vow")
      return runIsotropicWaveletFrequencyFunctionTest<3, VowWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Simoncelli")
      return runIsotropicWaveletFrequencyFunctionTest<3, SimoncelliWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Shannon")
      return runIsotropicWaveletFrequencyFunctionTest<3, ShannonWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else
      {
      std::cerr << argv[4] << " is an unknown wavelet type " << std::endl;
      return EXIT_FAILURE;
      }
    }
  else
    {
    std::cerr << "Error: only 2 or 3 dimensions allowed, " << dimension << " selected." << std::endl;
    return EXIT_FAILURE;
    }
}
<commit_msg>COMP: ofstream requires explicit const char *<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <string>
#include <fstream>
#include "itkHeldIsotropicWavelet.h"
#include "itkVowIsotropicWavelet.h"
#include "itkSimoncelliIsotropicWavelet.h"
#include "itkShannonIsotropicWavelet.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkNumberToString.h"
using namespace std;
using namespace itk;
namespace itk{
namespace Testing {
// Generate values from a linear space
std::vector<double> linSpaceForIWFF(double init = 0.0, double end = 1.0, size_t points = 1000)
{
  std::vector<double> w_array(points);
  if(points <= 1)
    throw("linSpace needs more points");
  double interval = (end - init)/(points - 1);
  for(unsigned int i = 0; i < points; ++i)
    {
    w_array[i] = init + interval*i;
    }
  return w_array;
}
}
}

template <unsigned int N, typename TWaveletFunction>
int runIsotropicWaveletFrequencyFunctionTest(
    const std::string& profileDataRootPath,
    const std::string& outputImage,
    const unsigned int& inputBands,
    const std::string & waveletTypeName)
{
  itk::NumberToString<float> n2s;
  typedef TWaveletFunction WaveletFunctionType;
  typename WaveletFunctionType::Pointer motherWavelet =
    WaveletFunctionType::New();
  motherWavelet->SetHighPassSubBands(inputBands);

  double init = 0.0;
  double end = 1.0;
  size_t points = 1000;
  std::vector< double > w_array = itk::Testing::linSpaceForIWFF(init,end,points);
  // Generate profile data for sub-bands and mother wavelet itself
  std::vector< std::vector< double > > subBandsResults;
  for(unsigned int k = 0; k<inputBands + 2; ++k)
    {
    std::vector<double> bandResults;
    for(unsigned int i = 0; i<points; ++i)
      {
      if (k == inputBands + 1) // mother wavelet
        bandResults.push_back(motherWavelet->EvaluateMagnitude(w_array[i]));
      else // bands
        bandResults.push_back(motherWavelet->EvaluateForwardSubBand(w_array[i], k));
      }
    subBandsResults.push_back(bandResults);
    }

  // Write profile.
  const std::string outputFilePath = profileDataRootPath + "_" + waveletTypeName +  "_" + n2s(inputBands) + ".txt";
  std::ofstream ofs(outputFilePath.c_str(), std::ofstream::out);
  for(unsigned int i = 0; i<points; ++i)
    {
    ofs << w_array[i];
    for(unsigned int k = 0; k<inputBands + 2; ++k)
      {
      ofs << "," << subBandsResults[k][i];
      }
    ofs << "\n";
    }
  ofs.close();
  return EXIT_SUCCESS;
}

int itkIsotropicWaveletFrequencyFunctionTest(int argc, char *argv[])
{
  if( argc < 5 || argc > 6 )
    {
    std::cerr << "Usage: " << argv[0] <<
      "profileDataRootPath outputImage inputBands waveletFunction [dimension]" << std::endl;
    return EXIT_FAILURE;
    }
  const string profileDataRootPath  = argv[1];
  const string outputImage = argv[2];
  const unsigned int inputBands  = atoi(argv[3]);
  const string waveletFunction  = argv[4];
  unsigned int dimension = 3;
  if( argc == 6 )
    {
    dimension = atoi( argv[5] );
    }

  typedef itk::HeldIsotropicWavelet<>       HeldWavelet;
  typedef itk::VowIsotropicWavelet<>        VowWavelet;
  typedef itk::SimoncelliIsotropicWavelet<> SimoncelliWavelet;
  typedef itk::ShannonIsotropicWavelet<>    ShannonWavelet;
  if( dimension == 2 )
    {
    if (waveletFunction == "Held")
      return runIsotropicWaveletFrequencyFunctionTest<2, HeldWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Vow")
      return runIsotropicWaveletFrequencyFunctionTest<2, VowWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Simoncelli")
      return runIsotropicWaveletFrequencyFunctionTest<2, SimoncelliWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Shannon")
      return runIsotropicWaveletFrequencyFunctionTest<2, ShannonWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else
      {
      std::cerr << argv[4] << " is an unknown wavelet type " << std::endl;
      return EXIT_FAILURE;
      }
    }
  else if( dimension == 3 )
    {
    if (waveletFunction == "Held")
      return runIsotropicWaveletFrequencyFunctionTest<3, HeldWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Vow")
      return runIsotropicWaveletFrequencyFunctionTest<3, VowWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Simoncelli")
      return runIsotropicWaveletFrequencyFunctionTest<3, SimoncelliWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else if (waveletFunction == "Shannon")
      return runIsotropicWaveletFrequencyFunctionTest<3, ShannonWavelet>(profileDataRootPath, outputImage, inputBands, waveletFunction);
    else
      {
      std::cerr << argv[4] << " is an unknown wavelet type " << std::endl;
      return EXIT_FAILURE;
      }
    }
  else
    {
    std::cerr << "Error: only 2 or 3 dimensions allowed, " << dimension << " selected." << std::endl;
    return EXIT_FAILURE;
    }
}
<|endoftext|>