<commit_before>#pragma once

#include "core_configuration/core_configuration.hpp"
#include "json_utility.hpp"
#include "manipulator/manipulator_factory.hpp"
#include "manipulator/manipulator_manager.hpp"
#include "manipulator/manipulators/basic/basic.hpp"

namespace krbn {
namespace grabber {
namespace device_grabber_details {
class fn_function_keys_manipulator_manager final {
public:
  fn_function_keys_manipulator_manager(void) {
    manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
  }

  std::shared_ptr<manipulator::manipulator_manager> get_manipulator_manager(void) const {
    return manipulator_manager_;
  }

  void update(const core_configuration::details::profile& profile,
              const pqrs::osx::system_preferences::properties& system_preferences_properties) {
    manipulator_manager_->invalidate_manipulators();

    auto from_mandatory_modifiers = nlohmann::json::array();

    auto from_optional_modifiers = nlohmann::json::array();
    from_optional_modifiers.push_back("any");

    auto to_modifiers = nlohmann::json::array();

    if (system_preferences_properties.get_use_fkeys_as_standard_function_keys()) {
      // f1 -> f1
      // fn+f1 -> display_brightness_decrement

      from_mandatory_modifiers.push_back("fn");
      to_modifiers.push_back("fn");

    } else {
      // f1 -> display_brightness_decrement
      // fn+f1 -> f1

      // fn+f1 ... fn+f12 -> f1 .. f12

      for (int i = 1; i <= 12; ++i) {
        auto from_json = nlohmann::json::object({
            {"key_code", fmt::format("f{0}", i)},
            {"modifiers", nlohmann::json::object({
                              {"mandatory", nlohmann::json::array({"fn"})},
                              {"optional", nlohmann::json::array({"any"})},
                          })},
        });

        auto to_json = nlohmann::json::object({
            {"key_code", fmt::format("f{0}", i)},
            {"modifiers", nlohmann::json::array({"fn"})},
        });

        try {
          auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                                manipulator::to_event_definition(to_json));
          manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator));

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }

    // from_modifiers+f1 -> display_brightness_decrement ...

    for (const auto& device : profile.get_devices()) {
      for (const auto& pair : device.get_fn_function_keys().get_pairs()) {
        try {
          if (auto m = make_manipulator(pair,
                                        from_mandatory_modifiers,
                                        from_optional_modifiers,
                                        to_modifiers)) {
            m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false));

            auto c = manipulator::manipulator_factory::make_device_if_condition(device);
            m->push_back_condition(c);

            manipulator_manager_->push_back_manipulator(m);
          }

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }

    for (const auto& pair : profile.get_fn_function_keys().get_pairs()) {
      if (auto m = make_manipulator(pair,
                                    from_mandatory_modifiers,
                                    from_optional_modifiers,
                                    to_modifiers)) {
        m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false));

        manipulator_manager_->push_back_manipulator(m);
      }
    }

    // fn+return_or_enter -> keypad_enter ...
    {
      nlohmann::json data = nlohmann::json::array();

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "return_or_enter"}})},
          {"to", nlohmann::json::object({{"key_code", "keypad_enter"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "delete_or_backspace"}})},
          {"to", nlohmann::json::object({{"key_code", "delete_forward"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "right_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "end"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "left_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "home"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "down_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "page_down"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "up_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "page_up"}})},
      }));

      for (const auto& d : data) {
        auto from_json = d["from"];
        from_json["modifiers"]["mandatory"] = nlohmann::json::array({"fn"});
        from_json["modifiers"]["optional"] = nlohmann::json::array({"any"});

        auto to_json = d["to"];
        to_json["modifiers"] = nlohmann::json::array({"fn"});

        try {
          auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                                manipulator::to_event_definition(to_json));
          manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator));

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }
  }

private:
  std::shared_ptr<manipulator::manipulators::base> make_manipulator(const std::pair<std::string, std::string>& pair,
                                                                    const nlohmann::json& from_mandatory_modifiers,
                                                                    const nlohmann::json& from_optional_modifiers,
                                                                    const nlohmann::json& to_modifiers) const {
    try {
      auto from_json = json_utility::parse_jsonc(pair.first);
      if (from_json.empty()) {
        return nullptr;
      }
      from_json["modifiers"]["mandatory"] = from_mandatory_modifiers;
      from_json["modifiers"]["optional"] = from_optional_modifiers;

      auto to_json = json_utility::parse_jsonc(pair.second);
      if (to_json.empty()) {
        return nullptr;
      }
      to_json["modifiers"] = to_modifiers;

      return std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                       manipulator::to_event_definition(to_json));
    } catch (const pqrs::json::unmarshal_error& e) {
      logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));
    } catch (const std::exception& e) {
      logger::get_logger()->error(e.what());
    }

    return nullptr;
  }

  std::shared_ptr<manipulator::manipulator_manager> manipulator_manager_;
};
} // namespace device_grabber_details
} // namespace grabber
} // namespace krbn
<commit_msg>Fix to strip modifier_flag::fn with media keys @ fn_function_keys_manipulator_manager<commit_after>#pragma once

#include "core_configuration/core_configuration.hpp"
#include "json_utility.hpp"
#include "manipulator/manipulator_factory.hpp"
#include "manipulator/manipulator_manager.hpp"
#include "manipulator/manipulators/basic/basic.hpp"

namespace krbn {
namespace grabber {
namespace device_grabber_details {
class fn_function_keys_manipulator_manager final {
public:
  fn_function_keys_manipulator_manager(void) {
    manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
  }

  std::shared_ptr<manipulator::manipulator_manager> get_manipulator_manager(void) const {
    return manipulator_manager_;
  }

  void update(const core_configuration::details::profile& profile,
              const pqrs::osx::system_preferences::properties& system_preferences_properties) {
    manipulator_manager_->invalidate_manipulators();

    auto from_mandatory_modifiers = nlohmann::json::array();

    auto from_optional_modifiers = nlohmann::json::array();
    from_optional_modifiers.push_back("any");

    auto to_modifiers = nlohmann::json::array();

    if (system_preferences_properties.get_use_fkeys_as_standard_function_keys()) {
      // f1 -> f1
      // fn+f1 -> display_brightness_decrement

      from_mandatory_modifiers.push_back("fn");

      // consumer_key_code::dictation does not work with modifier_flag::fn.
      // So, we send the plain media keys.
      // (e.g., display_brightness_decrement, not fn+display_brightness_decrement)

    } else {
      // f1 -> display_brightness_decrement
      // fn+f1 -> f1

      // fn+f1 ... fn+f12 -> f1 .. f12

      for (int i = 1; i <= 12; ++i) {
        auto from_json = nlohmann::json::object({
            {"key_code", fmt::format("f{0}", i)},
            {"modifiers", nlohmann::json::object({
                              {"mandatory", nlohmann::json::array({"fn"})},
                              {"optional", nlohmann::json::array({"any"})},
                          })},
        });

        auto to_json = nlohmann::json::object({
            {"key_code", fmt::format("f{0}", i)},
            {"modifiers", nlohmann::json::array({"fn"})},
        });

        try {
          auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                                manipulator::to_event_definition(to_json));
          manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator));

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }

    // from_modifiers+f1 -> display_brightness_decrement ...

    for (const auto& device : profile.get_devices()) {
      for (const auto& pair : device.get_fn_function_keys().get_pairs()) {
        try {
          if (auto m = make_manipulator(pair,
                                        from_mandatory_modifiers,
                                        from_optional_modifiers,
                                        to_modifiers)) {
            m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false));

            auto c = manipulator::manipulator_factory::make_device_if_condition(device);
            m->push_back_condition(c);

            manipulator_manager_->push_back_manipulator(m);
          }

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }

    for (const auto& pair : profile.get_fn_function_keys().get_pairs()) {
      if (auto m = make_manipulator(pair,
                                    from_mandatory_modifiers,
                                    from_optional_modifiers,
                                    to_modifiers)) {
        m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false));

        manipulator_manager_->push_back_manipulator(m);
      }
    }

    // fn+return_or_enter -> keypad_enter ...
    {
      nlohmann::json data = nlohmann::json::array();

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "return_or_enter"}})},
          {"to", nlohmann::json::object({{"key_code", "keypad_enter"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "delete_or_backspace"}})},
          {"to", nlohmann::json::object({{"key_code", "delete_forward"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "right_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "end"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "left_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "home"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "down_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "page_down"}})},
      }));

      data.push_back(nlohmann::json::object({
          {"from", nlohmann::json::object({{"key_code", "up_arrow"}})},
          {"to", nlohmann::json::object({{"key_code", "page_up"}})},
      }));

      for (const auto& d : data) {
        auto from_json = d["from"];
        from_json["modifiers"]["mandatory"] = nlohmann::json::array({"fn"});
        from_json["modifiers"]["optional"] = nlohmann::json::array({"any"});

        auto to_json = d["to"];
        to_json["modifiers"] = nlohmann::json::array({"fn"});

        try {
          auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                                manipulator::to_event_definition(to_json));
          manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator));

        } catch (const pqrs::json::unmarshal_error& e) {
          logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));

        } catch (const std::exception& e) {
          logger::get_logger()->error(e.what());
        }
      }
    }
  }

private:
  std::shared_ptr<manipulator::manipulators::base> make_manipulator(const std::pair<std::string, std::string>& pair,
                                                                    const nlohmann::json& from_mandatory_modifiers,
                                                                    const nlohmann::json& from_optional_modifiers,
                                                                    const nlohmann::json& to_modifiers) const {
    try {
      auto from_json = json_utility::parse_jsonc(pair.first);
      if (from_json.empty()) {
        return nullptr;
      }
      from_json["modifiers"]["mandatory"] = from_mandatory_modifiers;
      from_json["modifiers"]["optional"] = from_optional_modifiers;

      auto to_json = json_utility::parse_jsonc(pair.second);
      if (to_json.empty()) {
        return nullptr;
      }
      to_json["modifiers"] = to_modifiers;

      return std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json),
                                                                       manipulator::to_event_definition(to_json));
    } catch (const pqrs::json::unmarshal_error& e) {
      logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what()));
    } catch (const std::exception& e) {
      logger::get_logger()->error(e.what());
    }

    return nullptr;
  }

  std::shared_ptr<manipulator::manipulator_manager> manipulator_manager_;
};
} // namespace device_grabber_details
} // namespace grabber
} // namespace krbn
<|endoftext|>


<commit_before>#include "Phantom_vrepHW.h"

#include "../v_repLib.h"

#include <string>
#include <iostream>

namespace MR
{

std::string Phantom_vrepHW::sm_jointsName[MR_JOINTS_NUM] = {
  "PhantomXPincher_joint1",
  "PhantomXPincher_joint2",
  "PhantomXPincher_joint3",
  "PhantomXPincher_joint4",
  "PhantomXPincher_gripperCenter_joint",
  "PhantomXPincher_gripperClose_joint",
  "PhantomXPincher_joint1_1",
  "PhantomXPincher_joint2_1",
  "PhantomXPincher_joint3_1",
  "PhantomXPincher_joint4_1",
  "PhantomXPincher_gripperCenter_joint_1",
  "PhantomXPincher_gripperClose_joint_1",
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Phantom_vrepHW::Phantom_vrepHW() :
    hardware_interface::RobotHW()
{
    // Init arrays m_cmd[], m_pos[], m_vel[], m_eff[].
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        m_pos_cmd[i] = 0.0;
        m_vel_cmd[i] = 0.0;
        m_pos[i] = 0.0;
        m_vel[i] = 0.0;
        m_eff[i] = 0.0;
    }

    // Init and get handles of the joints to control.
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
        m_vrepJointsHandle[i] = -1;

    // Register joint interfaces.
    registerHardwareInterfaces();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::init()
{
    // Get joint handles.
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        int vrepJointsHandle = simGetObjectHandle(sm_jointsName[i].c_str());

        if (vrepJointsHandle == -1)
        {
            ROS_ERROR_STREAM("MR robot interface not able to get handle for '" << sm_jointsName[i] << "'." << std::endl);

            return false;
        }

        m_vrepJointsHandle[i] = vrepJointsHandle;
    }
    read();

    for (int i=0; i < MR_JOINTS_NUM; i++){
      m_pos_cmd[i] = m_pos[i];
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Phantom_vrepHW::registerHardwareInterfaces()
{
  ROS_ERROR_STREAM("Join numbers =" << MR_JOINTS_NUM << std::endl);
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        // Joint state interface.
        hardware_interface::JointStateHandle jointStateHandle(sm_jointsName[i], &m_pos[i], &m_vel[i], &m_eff[i]);
        m_jointState_interface.registerHandle(jointStateHandle);

        // Joint velocity command interface
        hardware_interface::JointHandle jointVelocityHandle(jointStateHandle, &m_vel_cmd[i]);
        m_jointVelocity_interface.registerHandle(jointVelocityHandle);

	//Joint position command interface
	hardware_interface::JointHandle jointPositionHandle(jointStateHandle, &m_pos_cmd[i]);
	m_jointPosition_interface.registerHandle(jointPositionHandle);

    }

    registerInterface(&m_jointState_interface);
    registerInterface(&m_jointVelocity_interface);
    registerInterface(&m_jointPosition_interface);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::read()
{
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        float pos,
              vel,
              eff;

        if (simGetJointPosition(m_vrepJointsHandle[i], &pos) == -1 ||
            simGetObjectFloatParameter(m_vrepJointsHandle[i], 2012, &vel) == -1 || // Velocity.
            simGetJointForce(m_vrepJointsHandle[i], &eff) == -1)
        {
            ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);

            return false;
        }

        m_pos[i] = pos;
        m_vel[i] = vel;
        m_eff[i] = eff;
    }

    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::write()
{
    for (int i = 0; i < MR_JOINTS_NUM; ++i){
      //====== Velocity Control =========

      /*if (simSetJointTargetVelocity(m_vrepJointsHandle[i], m_vel_cmd[i]) == -1) {
	ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
	return false;
      }
      */

      //===== Position Control =======
      if (simSetJointTargetPosition(m_vrepJointsHandle[i], m_pos_cmd[i]) == -1) {
	ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
	return false;
      }
    }
    return true;
}

} // namespace MR.
<commit_msg>Wrong comma<commit_after>#include "Phantom_vrepHW.h"

#include "../v_repLib.h"

#include <string>
#include <iostream>

namespace MR
{

std::string Phantom_vrepHW::sm_jointsName[MR_JOINTS_NUM] = {
  "PhantomXPincher_joint1",
  "PhantomXPincher_joint2",
  "PhantomXPincher_joint3",
  "PhantomXPincher_joint4",
  "PhantomXPincher_gripperCenter_joint",
  "PhantomXPincher_gripperClose_joint",
  "PhantomXPincher_joint1_1",
  "PhantomXPincher_joint2_1",
  "PhantomXPincher_joint3_1",
  "PhantomXPincher_joint4_1",
  "PhantomXPincher_gripperCenter_joint_1",
  "PhantomXPincher_gripperClose_joint_1"
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Phantom_vrepHW::Phantom_vrepHW() :
    hardware_interface::RobotHW()
{
    // Init arrays m_cmd[], m_pos[], m_vel[], m_eff[].
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        m_pos_cmd[i] = 0.0;
        m_vel_cmd[i] = 0.0;
        m_pos[i] = 0.0;
        m_vel[i] = 0.0;
        m_eff[i] = 0.0;
    }

    // Init and get handles of the joints to control.
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
        m_vrepJointsHandle[i] = -1;

    // Register joint interfaces.
    registerHardwareInterfaces();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::init()
{
    // Get joint handles.
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        int vrepJointsHandle = simGetObjectHandle(sm_jointsName[i].c_str());

        if (vrepJointsHandle == -1)
        {
            ROS_ERROR_STREAM("MR robot interface not able to get handle for '" << sm_jointsName[i] << "'." << std::endl);

            return false;
        }

        m_vrepJointsHandle[i] = vrepJointsHandle;
    }
    read();

    for (int i=0; i < MR_JOINTS_NUM; i++){
      m_pos_cmd[i] = m_pos[i];
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Phantom_vrepHW::registerHardwareInterfaces()
{
  ROS_ERROR_STREAM("Join numbers =" << MR_JOINTS_NUM << std::endl);
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        // Joint state interface.
        hardware_interface::JointStateHandle jointStateHandle(sm_jointsName[i], &m_pos[i], &m_vel[i], &m_eff[i]);
        m_jointState_interface.registerHandle(jointStateHandle);

        // Joint velocity command interface
        hardware_interface::JointHandle jointVelocityHandle(jointStateHandle, &m_vel_cmd[i]);
        m_jointVelocity_interface.registerHandle(jointVelocityHandle);

	//Joint position command interface
	hardware_interface::JointHandle jointPositionHandle(jointStateHandle, &m_pos_cmd[i]);
	m_jointPosition_interface.registerHandle(jointPositionHandle);

    }

    registerInterface(&m_jointState_interface);
    registerInterface(&m_jointVelocity_interface);
    registerInterface(&m_jointPosition_interface);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::read()
{
    for (int i = 0; i < MR_JOINTS_NUM; ++i)
    {
        float pos,
              vel,
              eff;

        if (simGetJointPosition(m_vrepJointsHandle[i], &pos) == -1 ||
            simGetObjectFloatParameter(m_vrepJointsHandle[i], 2012, &vel) == -1 || // Velocity.
            simGetJointForce(m_vrepJointsHandle[i], &eff) == -1)
        {
            ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);

            return false;
        }

        m_pos[i] = pos;
        m_vel[i] = vel;
        m_eff[i] = eff;
    }

    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::write()
{
    for (int i = 0; i < MR_JOINTS_NUM; ++i){
      //====== Velocity Control =========

      /*if (simSetJointTargetVelocity(m_vrepJointsHandle[i], m_vel_cmd[i]) == -1) {
	ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
	return false;
      }
      */

      //===== Position Control =======
      if (simSetJointTargetPosition(m_vrepJointsHandle[i], m_pos_cmd[i]) == -1) {
	ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
	return false;
      }
    }
    return true;
}

} // namespace MR.
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "MyFakeComponent.h"
#include <sofa/core/ObjectFactory.h>

namespace sofa
{

namespace component
{

namespace behaviormodel
{

MyFakeComponent::MyFakeComponent()
    : myData( initData(&myData,(unsigned)1,"myData","Example of data") )
{
    myData.setWidget("myData_widget");
}

MyFakeComponent::~MyFakeComponent()
{
}

void MyFakeComponent::init()
{
}

void MyFakeComponent::reinit()
{
}

void MyFakeComponent::updatePosition(double /*dt*/)
{
}

SOFA_DECL_CLASS(MyFakeComponent)

int MyFakeComponentClass = core::RegisterObject("just an example of component")
        .add< MyFakeComponent >()
        ;

}	//behaviormodel

}	//component

}	//sofa

<commit_msg>r6864/sofa-dev : FIX : widget name mismatch with DataWidgetFactory key<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "MyFakeComponent.h"
#include <sofa/core/ObjectFactory.h>

namespace sofa
{

namespace component
{

namespace behaviormodel
{

MyFakeComponent::MyFakeComponent()
    : myData( initData(&myData,(unsigned)1,"myData","Example of data") )
{
    myData.setWidget("widget_myData");
}

MyFakeComponent::~MyFakeComponent()
{
}

void MyFakeComponent::init()
{
}

void MyFakeComponent::reinit()
{
}

void MyFakeComponent::updatePosition(double /*dt*/)
{
}

SOFA_DECL_CLASS(MyFakeComponent)

int MyFakeComponentClass = core::RegisterObject("just an example of component")
        .add< MyFakeComponent >()
        ;

}	//behaviormodel

}	//component

}	//sofa

<|endoftext|>


<commit_before>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/autofill/personal_data_manager_factory.h"

#include "base/memory/singleton.h"
#include "brave/browser/brave_content_browser_client.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/user_prefs/user_prefs.h"

namespace autofill {

// static
PersonalDataManager* PersonalDataManagerFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<PersonalDataManager*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
PersonalDataManagerFactory* PersonalDataManagerFactory::GetInstance() {
  return base::Singleton<PersonalDataManagerFactory>::get();
}

PersonalDataManagerFactory::PersonalDataManagerFactory()
    : BrowserContextKeyedServiceFactory(
        "PersonalDataManager",
        BrowserContextDependencyManager::GetInstance()) {
}

PersonalDataManagerFactory::~PersonalDataManagerFactory() {
}

KeyedService* PersonalDataManagerFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  PersonalDataManager* service =
      new PersonalDataManager(
          brave::BraveContentBrowserClient::Get()->GetApplicationLocale());
  service->Init(static_cast<Profile*>(context)
                ->GetAutofillWebdataService(),
                user_prefs::UserPrefs::Get(context),
                nullptr,
                nullptr,
                context->IsOffTheRecord());
  return service;
}

content::BrowserContext* PersonalDataManagerFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextRedirectedInIncognito(context);
}

}  // namespace autofill
<commit_msg>Convert PersonalDataManager to use IdentityManager<commit_after>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/autofill/personal_data_manager_factory.h"

#include "base/memory/singleton.h"
#include "brave/browser/brave_content_browser_client.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/user_prefs/user_prefs.h"

namespace autofill {

// static
PersonalDataManager* PersonalDataManagerFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<PersonalDataManager*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
PersonalDataManagerFactory* PersonalDataManagerFactory::GetInstance() {
  return base::Singleton<PersonalDataManagerFactory>::get();
}

PersonalDataManagerFactory::PersonalDataManagerFactory()
    : BrowserContextKeyedServiceFactory(
        "PersonalDataManager",
        BrowserContextDependencyManager::GetInstance()) {
}

PersonalDataManagerFactory::~PersonalDataManagerFactory() {
}

KeyedService* PersonalDataManagerFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  PersonalDataManager* service =
      new PersonalDataManager(
          brave::BraveContentBrowserClient::Get()->GetApplicationLocale());
  service->Init(static_cast<Profile*>(context)
                ->GetAutofillWebdataService(),
                user_prefs::UserPrefs::Get(context),
                nullptr,
                context->IsOffTheRecord());
  return service;
}

content::BrowserContext* PersonalDataManagerFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextRedirectedInIncognito(context);
}

}  // namespace autofill
<|endoftext|>


<commit_before>//===--- Module.cpp - Swift Language Module Implementation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the Module class and subclasses.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Module.h"
#include "swift/AST/AST.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/SmallPtrSet.h"

using namespace swift;

//===----------------------------------------------------------------------===//
// Builtin Module Name lookup
//===----------------------------------------------------------------------===//

namespace {
  /// BuiltinModuleCache - This is the type of the cache for the BuiltinModule.
  /// This is lazily created on its first use an hangs off
  /// Module::LookupCachePimpl.
  class BuiltinModuleCache {
    /// The cache of identifiers we've already looked up.  We use a
    /// single hashtable for both types and values as a minor
    /// optimization; this prevents us from having both a builtin type
    /// and a builtin value with the same name, but that's okay.
    llvm::DenseMap<Identifier, ValueDecl*> Cache;
  public:

    void lookupValue(Identifier Name, NLKind LookupKind, BuiltinModule &M,
                     SmallVectorImpl<ValueDecl*> &Result);
  };
} // end anonymous namespace.

static BuiltinModuleCache &getBuiltinCachePimpl(void *&Ptr) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new BuiltinModuleCache();
  return *(BuiltinModuleCache*)Ptr;
}

void BuiltinModuleCache::lookupValue(Identifier Name, NLKind LookupKind,
                                     BuiltinModule &M,
                                     SmallVectorImpl<ValueDecl*> &Result) {
  // Only qualified lookup ever finds anything in the builtin module.
  if (LookupKind != NLKind::QualifiedLookup) return;

  ValueDecl *&Entry = Cache[Name];

  if (Entry == 0)
    if (Type Ty = getBuiltinType(M.Ctx, Name.str()))
      Entry = new (M.Ctx) TypeAliasDecl(SourceLoc(), Name, SourceLoc(), Ty,
                                        M.Ctx.TheBuiltinModule,
                                        MutableArrayRef<Type>());

  if (Entry == 0)
    Entry = getBuiltinValue(M.Ctx, Name);

  if (ValueDecl *VD = dyn_cast_or_null<ValueDecl>(Entry))
    Result.push_back(VD);
}

//===----------------------------------------------------------------------===//
// Normal Module Name Lookup
//===----------------------------------------------------------------------===//

namespace {
  /// TUModuleCache - This is the type of the cache for the TranslationUnit.
  /// This is lazily created on its first use an hangs off
  /// Module::LookupCachePimpl.
  class TUModuleCache {
    llvm::DenseMap<Identifier, TinyPtrVector<ValueDecl*>> TopLevelValues;
  public:
    typedef Module::AccessPathTy AccessPathTy;

    TUModuleCache(TranslationUnit &TU);

    void lookupValue(AccessPathTy AccessPath, Identifier Name,
                     NLKind LookupKind, TranslationUnit &TU,
                     SmallVectorImpl<ValueDecl*> &Result);
  };
} // end anonymous namespace.

static TUModuleCache &getTUCachePimpl(void *&Ptr, TranslationUnit &TU) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new TUModuleCache(TU);
  return *(TUModuleCache*)Ptr;
}

static void freeTUCachePimpl(void *&Ptr) {
  delete (TUModuleCache*)Ptr;
  Ptr = 0;
}

/// Populate our cache on the first name lookup.
TUModuleCache::TUModuleCache(TranslationUnit &TU) {
  for (Decl *D : TU.Decls) {
    if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
      if (!VD->getName().empty())
        TopLevelValues[VD->getName()].push_back(VD);
  }
}

void TUModuleCache::lookupValue(AccessPathTy AccessPath, Identifier Name,
                                NLKind LookupKind, TranslationUnit &TU,
                                SmallVectorImpl<ValueDecl*> &Result) {
  // TODO: ImportDecls cannot specified namespaces or individual entities
  // yet, so everything is just a lookup at the top-level.
  assert(AccessPath.size() <= 1 && "Don't handle this yet");

  // If this import is specific to some named type or decl ("import swift.int")
  // then filter out any lookups that don't match.
  if (AccessPath.size() == 1 && AccessPath[0].first != Name)
    return;

  auto I = TopLevelValues.find(Name);
  if (I == TopLevelValues.end()) return;

  Result.reserve(I->second.size());
  for (ValueDecl *Elt : I->second)
    Result.push_back(Elt);
}

//===----------------------------------------------------------------------===//
// Module Extension Name Lookup
//===----------------------------------------------------------------------===//

namespace {
  class TUExtensionCache {
    llvm::DenseMap<CanType, TinyPtrVector<ExtensionDecl*>> Extensions;
  public:

    TUExtensionCache(TranslationUnit &TU);

    ArrayRef<ExtensionDecl*> getExtensions(CanType T) const{
      auto I = Extensions.find(T);
      if (I == Extensions.end())
        return ArrayRef<ExtensionDecl*>();
      return I->second;
    }
  };
}

static TUExtensionCache &getTUExtensionCachePimpl(void *&Ptr,
                                                  TranslationUnit &TU) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new TUExtensionCache(TU);
  return *(TUExtensionCache*)Ptr;
}

static void freeTUExtensionCachePimpl(void *&Ptr) {
  delete (TUExtensionCache*)Ptr;
  Ptr = 0;
}

TUExtensionCache::TUExtensionCache(TranslationUnit &TU) {
  for (Decl *D : TU.Decls) {
    if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D)) {
      // Ignore failed name lookups.
      if (ED->getExtendedType()->is<ErrorType>()) continue;

      Extensions[ED->getExtendedType()->getCanonicalType()].push_back(ED);
    }
  }
}

/// lookupExtensions - Look up all of the extensions in the module that are
/// extending the specified type and return a list of them.
ArrayRef<ExtensionDecl*> Module::lookupExtensions(Type T) {
  assert(ASTStage >= Parsed &&
         "Extensions should only be looked up after name binding is underway");

  // The builtin module just has free functions, not extensions.
  if (isa<BuiltinModule>(this)) return ArrayRef<ExtensionDecl*>();

  TUExtensionCache &Cache =
    getTUExtensionCachePimpl(ExtensionCachePimpl, *cast<TranslationUnit>(this));

  return Cache.getExtensions(T->getCanonicalType());
}

//===----------------------------------------------------------------------===//
// Module Implementation
//===----------------------------------------------------------------------===//

/// lookupValue - Look up a (possibly overloaded) value set at top-level scope
/// (but with the specified access path, which may come from an import decl)
/// within the current module. This does a simple local lookup, not
/// recursively looking through imports.
void Module::lookupValue(AccessPathTy AccessPath, Identifier Name,
                         NLKind LookupKind,
                         SmallVectorImpl<ValueDecl*> &Result) {
  if (BuiltinModule *BM = dyn_cast<BuiltinModule>(this)) {
    assert(AccessPath.empty() && "builtin module's access path always empty!");
    return getBuiltinCachePimpl(LookupCachePimpl)
      .lookupValue(Name, LookupKind, *BM, Result);
  }

  // Otherwise must be TranslationUnit.  Someday we should generalize this to
  // allow modules with multiple translation units.
  TranslationUnit &TU = *cast<TranslationUnit>(this);
  return getTUCachePimpl(LookupCachePimpl, TU)
    .lookupValue(AccessPath, Name, LookupKind, TU, Result);
}

static void DoGlobalExtensionLookup(Type BaseType, Identifier Name,
                                    ArrayRef<ValueDecl*> BaseMembers,
                                    Module *CurModule,
                                    Module *BaseModule,
                                    SmallVectorImpl<ValueDecl*> &Result) {
  bool CurModuleHasTypeDecl = false;
  llvm::SmallPtrSet<CanType, 8> CurModuleTypes;

  bool NameBindingLookup = CurModule->ASTStage == Module::Parsed;

  // Find all extensions in this module.
  for (ExtensionDecl *ED : CurModule->lookupExtensions(BaseType)) {
    for (Decl *Member : ED->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member)) {
        if (VD->getName() == Name) {
          Result.push_back(VD);
          if (!NameBindingLookup)
            CurModuleTypes.insert(VD->getType()->getCanonicalType());
          CurModuleHasTypeDecl |= isa<MetaTypeType>(VD->getType());
        }
      }
    }
  }

  if (BaseModule == CurModule) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Name) {
        Result.push_back(VD);
        if (!NameBindingLookup)
          CurModuleTypes.insert(VD->getType()->getCanonicalType());
        CurModuleHasTypeDecl |= isa<MetaTypeType>(VD->getType());
      }
    }
  }

  // The builtin module has no imports.
  if (isa<BuiltinModule>(CurModule)) return;

  // If we find a type in the current module, don't look into any
  // imported modules.
  if (CurModuleHasTypeDecl) return;

  TranslationUnit &TU = *cast<TranslationUnit>(CurModule);

  // Otherwise, check our imported extensions as well.
  // FIXME: Implement DAG-based shadowing rules.
  llvm::SmallPtrSet<Module *, 16> Visited;
  for (auto &ImpEntry : TU.getImportedModules()) {
    if (!Visited.insert(ImpEntry.second))
      continue;

    for (ExtensionDecl *ED : ImpEntry.second->lookupExtensions(BaseType)) {
      for (Decl *Member : ED->getMembers()) {
        if (ValueDecl *VD = dyn_cast<ValueDecl>(Member)) {
          if (VD->getName() == Name &&
              (NameBindingLookup || isa<TypeDecl>(VD) ||
               !CurModuleTypes.count(VD->getType()->getCanonicalType()))) {
            Result.push_back(VD);
          }
        }
      }
    }
  }

  if (BaseModule != CurModule) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Name &&
          (NameBindingLookup || isa<TypeDecl>(VD) ||
           !CurModuleTypes.count(VD->getType()->getCanonicalType()))) {
        Result.push_back(VD);
      }
    }
  }
}

/// lookupGlobalExtensionMethods - Lookup the extensions members for the
/// specified BaseType with the specified type, and return them in Result.
void Module::lookupMembers(Type BaseType, Identifier Name,
                           SmallVectorImpl<ValueDecl*> &Result) {
  assert(Result.empty() &&
         "This expects that the input list is empty, could be generalized");

  TypeDecl *D;
  ArrayRef<ValueDecl*> BaseMembers;
  SmallVector<ValueDecl*, 2> BaseMembersStorage;
  if (StructType *ST = BaseType->getAs<StructType>()) {
    // FIXME: Refuse to look up "constructors" until we have real constructors.
    if (ST->getDecl()->getName() == Name)
      return;

    D = ST->getDecl();
    for (Decl* Member : ST->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (ClassType *CT = BaseType->getAs<ClassType>()) {
    D = CT->getDecl();
    for (Decl* Member : CT->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (OneOfType *OOT = BaseType->getAs<OneOfType>()) {
    // FIXME: Refuse to look up "constructors" until we have real constructors.
    if (OOT->getDecl()->getName() == Name)
      return;

    D = OOT->getDecl();
    for (Decl* Member : OOT->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else {
    return;
  }

  DeclContext *DC = D->getDeclContext();
  while (!DC->isModuleContext())
    DC = DC->getParent();

  DoGlobalExtensionLookup(BaseType, Name, BaseMembers, this, cast<Module>(DC),
                          Result);
}

/// lookupGlobalExtensionMethods - Lookup the extensions members for the
/// specified BaseType with the specified type, and return them in Result.
void Module::lookupValueConstructors(Type BaseType,
                                     SmallVectorImpl<ValueDecl*> &Result) {
  assert(Result.empty() &&
         "This expects that the input list is empty, could be generalized");

  TypeDecl *D;
  Identifier Name;
  Identifier Constructor = Ctx.getIdentifier("constructor");
  ArrayRef<ValueDecl*> BaseMembers;
  SmallVector<ValueDecl*, 2> BaseMembersStorage;
  if (StructType *ST = BaseType->getAs<StructType>()) {
    D = ST->getDecl();
    Name = ST->getDecl()->getName();
    for (Decl* Member : ST->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (OneOfType *OOT = BaseType->getAs<OneOfType>()) {
    D = OOT->getDecl();
    Name = OOT->getDecl()->getName();
    for (Decl* Member : OOT->getDecl()->getMembers()) {
      // FIXME: We shouldn't be injecting OneOfElementDecls into the results
      // like this.
      if (OneOfElementDecl *OOED = dyn_cast<OneOfElementDecl>(Member))
        Result.push_back(OOED);
      else if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
  } else {
    return;
  }

  DeclContext *DC = D->getDeclContext();
  if (!DC->isModuleContext()) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Name || VD->getName() == Constructor)
        Result.push_back(VD);
    }
    return;
  }

  DoGlobalExtensionLookup(BaseType, Name, BaseMembers, this, cast<Module>(DC),
                          Result);
  DoGlobalExtensionLookup(BaseType, Constructor, BaseMembers, this,
                          cast<Module>(DC), Result);
}

//===----------------------------------------------------------------------===//
// TranslationUnit Implementation
//===----------------------------------------------------------------------===//

void TranslationUnit::clearLookupCache() {
  freeTUCachePimpl(LookupCachePimpl);
  freeTUExtensionCachePimpl(ExtensionCachePimpl);
}
<commit_msg>Switch everything over to new-style constructors.  Change name lookup so it doesn't use old-style constructors for construction anymore.<commit_after>//===--- Module.cpp - Swift Language Module Implementation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the Module class and subclasses.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Module.h"
#include "swift/AST/AST.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/SmallPtrSet.h"

using namespace swift;

//===----------------------------------------------------------------------===//
// Builtin Module Name lookup
//===----------------------------------------------------------------------===//

namespace {
  /// BuiltinModuleCache - This is the type of the cache for the BuiltinModule.
  /// This is lazily created on its first use an hangs off
  /// Module::LookupCachePimpl.
  class BuiltinModuleCache {
    /// The cache of identifiers we've already looked up.  We use a
    /// single hashtable for both types and values as a minor
    /// optimization; this prevents us from having both a builtin type
    /// and a builtin value with the same name, but that's okay.
    llvm::DenseMap<Identifier, ValueDecl*> Cache;
  public:

    void lookupValue(Identifier Name, NLKind LookupKind, BuiltinModule &M,
                     SmallVectorImpl<ValueDecl*> &Result);
  };
} // end anonymous namespace.

static BuiltinModuleCache &getBuiltinCachePimpl(void *&Ptr) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new BuiltinModuleCache();
  return *(BuiltinModuleCache*)Ptr;
}

void BuiltinModuleCache::lookupValue(Identifier Name, NLKind LookupKind,
                                     BuiltinModule &M,
                                     SmallVectorImpl<ValueDecl*> &Result) {
  // Only qualified lookup ever finds anything in the builtin module.
  if (LookupKind != NLKind::QualifiedLookup) return;

  ValueDecl *&Entry = Cache[Name];

  if (Entry == 0)
    if (Type Ty = getBuiltinType(M.Ctx, Name.str()))
      Entry = new (M.Ctx) TypeAliasDecl(SourceLoc(), Name, SourceLoc(), Ty,
                                        M.Ctx.TheBuiltinModule,
                                        MutableArrayRef<Type>());

  if (Entry == 0)
    Entry = getBuiltinValue(M.Ctx, Name);

  if (ValueDecl *VD = dyn_cast_or_null<ValueDecl>(Entry))
    Result.push_back(VD);
}

//===----------------------------------------------------------------------===//
// Normal Module Name Lookup
//===----------------------------------------------------------------------===//

namespace {
  /// TUModuleCache - This is the type of the cache for the TranslationUnit.
  /// This is lazily created on its first use an hangs off
  /// Module::LookupCachePimpl.
  class TUModuleCache {
    llvm::DenseMap<Identifier, TinyPtrVector<ValueDecl*>> TopLevelValues;
  public:
    typedef Module::AccessPathTy AccessPathTy;

    TUModuleCache(TranslationUnit &TU);

    void lookupValue(AccessPathTy AccessPath, Identifier Name,
                     NLKind LookupKind, TranslationUnit &TU,
                     SmallVectorImpl<ValueDecl*> &Result);
  };
} // end anonymous namespace.

static TUModuleCache &getTUCachePimpl(void *&Ptr, TranslationUnit &TU) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new TUModuleCache(TU);
  return *(TUModuleCache*)Ptr;
}

static void freeTUCachePimpl(void *&Ptr) {
  delete (TUModuleCache*)Ptr;
  Ptr = 0;
}

/// Populate our cache on the first name lookup.
TUModuleCache::TUModuleCache(TranslationUnit &TU) {
  for (Decl *D : TU.Decls) {
    if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
      if (!VD->getName().empty())
        TopLevelValues[VD->getName()].push_back(VD);
  }
}

void TUModuleCache::lookupValue(AccessPathTy AccessPath, Identifier Name,
                                NLKind LookupKind, TranslationUnit &TU,
                                SmallVectorImpl<ValueDecl*> &Result) {
  // TODO: ImportDecls cannot specified namespaces or individual entities
  // yet, so everything is just a lookup at the top-level.
  assert(AccessPath.size() <= 1 && "Don't handle this yet");

  // If this import is specific to some named type or decl ("import swift.int")
  // then filter out any lookups that don't match.
  if (AccessPath.size() == 1 && AccessPath[0].first != Name)
    return;

  auto I = TopLevelValues.find(Name);
  if (I == TopLevelValues.end()) return;

  Result.reserve(I->second.size());
  for (ValueDecl *Elt : I->second)
    Result.push_back(Elt);
}

//===----------------------------------------------------------------------===//
// Module Extension Name Lookup
//===----------------------------------------------------------------------===//

namespace {
  class TUExtensionCache {
    llvm::DenseMap<CanType, TinyPtrVector<ExtensionDecl*>> Extensions;
  public:

    TUExtensionCache(TranslationUnit &TU);

    ArrayRef<ExtensionDecl*> getExtensions(CanType T) const{
      auto I = Extensions.find(T);
      if (I == Extensions.end())
        return ArrayRef<ExtensionDecl*>();
      return I->second;
    }
  };
}

static TUExtensionCache &getTUExtensionCachePimpl(void *&Ptr,
                                                  TranslationUnit &TU) {
  // FIXME: This leaks.  Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (Ptr == 0)
    Ptr = new TUExtensionCache(TU);
  return *(TUExtensionCache*)Ptr;
}

static void freeTUExtensionCachePimpl(void *&Ptr) {
  delete (TUExtensionCache*)Ptr;
  Ptr = 0;
}

TUExtensionCache::TUExtensionCache(TranslationUnit &TU) {
  for (Decl *D : TU.Decls) {
    if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D)) {
      // Ignore failed name lookups.
      if (ED->getExtendedType()->is<ErrorType>()) continue;

      Extensions[ED->getExtendedType()->getCanonicalType()].push_back(ED);
    }
  }
}

/// lookupExtensions - Look up all of the extensions in the module that are
/// extending the specified type and return a list of them.
ArrayRef<ExtensionDecl*> Module::lookupExtensions(Type T) {
  assert(ASTStage >= Parsed &&
         "Extensions should only be looked up after name binding is underway");

  // The builtin module just has free functions, not extensions.
  if (isa<BuiltinModule>(this)) return ArrayRef<ExtensionDecl*>();

  TUExtensionCache &Cache =
    getTUExtensionCachePimpl(ExtensionCachePimpl, *cast<TranslationUnit>(this));

  return Cache.getExtensions(T->getCanonicalType());
}

//===----------------------------------------------------------------------===//
// Module Implementation
//===----------------------------------------------------------------------===//

/// lookupValue - Look up a (possibly overloaded) value set at top-level scope
/// (but with the specified access path, which may come from an import decl)
/// within the current module. This does a simple local lookup, not
/// recursively looking through imports.
void Module::lookupValue(AccessPathTy AccessPath, Identifier Name,
                         NLKind LookupKind,
                         SmallVectorImpl<ValueDecl*> &Result) {
  if (BuiltinModule *BM = dyn_cast<BuiltinModule>(this)) {
    assert(AccessPath.empty() && "builtin module's access path always empty!");
    return getBuiltinCachePimpl(LookupCachePimpl)
      .lookupValue(Name, LookupKind, *BM, Result);
  }

  // Otherwise must be TranslationUnit.  Someday we should generalize this to
  // allow modules with multiple translation units.
  TranslationUnit &TU = *cast<TranslationUnit>(this);
  return getTUCachePimpl(LookupCachePimpl, TU)
    .lookupValue(AccessPath, Name, LookupKind, TU, Result);
}

static void DoGlobalExtensionLookup(Type BaseType, Identifier Name,
                                    ArrayRef<ValueDecl*> BaseMembers,
                                    Module *CurModule,
                                    Module *BaseModule,
                                    SmallVectorImpl<ValueDecl*> &Result) {
  bool CurModuleHasTypeDecl = false;
  llvm::SmallPtrSet<CanType, 8> CurModuleTypes;

  bool NameBindingLookup = CurModule->ASTStage == Module::Parsed;

  // Find all extensions in this module.
  for (ExtensionDecl *ED : CurModule->lookupExtensions(BaseType)) {
    for (Decl *Member : ED->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member)) {
        if (VD->getName() == Name) {
          Result.push_back(VD);
          if (!NameBindingLookup)
            CurModuleTypes.insert(VD->getType()->getCanonicalType());
          CurModuleHasTypeDecl |= isa<MetaTypeType>(VD->getType());
        }
      }
    }
  }

  if (BaseModule == CurModule) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Name) {
        Result.push_back(VD);
        if (!NameBindingLookup)
          CurModuleTypes.insert(VD->getType()->getCanonicalType());
        CurModuleHasTypeDecl |= isa<MetaTypeType>(VD->getType());
      }
    }
  }

  // The builtin module has no imports.
  if (isa<BuiltinModule>(CurModule)) return;

  // If we find a type in the current module, don't look into any
  // imported modules.
  if (CurModuleHasTypeDecl) return;

  TranslationUnit &TU = *cast<TranslationUnit>(CurModule);

  // Otherwise, check our imported extensions as well.
  // FIXME: Implement DAG-based shadowing rules.
  llvm::SmallPtrSet<Module *, 16> Visited;
  for (auto &ImpEntry : TU.getImportedModules()) {
    if (!Visited.insert(ImpEntry.second))
      continue;

    for (ExtensionDecl *ED : ImpEntry.second->lookupExtensions(BaseType)) {
      for (Decl *Member : ED->getMembers()) {
        if (ValueDecl *VD = dyn_cast<ValueDecl>(Member)) {
          if (VD->getName() == Name &&
              (NameBindingLookup || isa<TypeDecl>(VD) ||
               !CurModuleTypes.count(VD->getType()->getCanonicalType()))) {
            Result.push_back(VD);
          }
        }
      }
    }
  }

  if (BaseModule != CurModule) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Name &&
          (NameBindingLookup || isa<TypeDecl>(VD) ||
           !CurModuleTypes.count(VD->getType()->getCanonicalType()))) {
        Result.push_back(VD);
      }
    }
  }
}

/// lookupGlobalExtensionMethods - Lookup the extensions members for the
/// specified BaseType with the specified type, and return them in Result.
void Module::lookupMembers(Type BaseType, Identifier Name,
                           SmallVectorImpl<ValueDecl*> &Result) {
  assert(Result.empty() &&
         "This expects that the input list is empty, could be generalized");

  TypeDecl *D;
  ArrayRef<ValueDecl*> BaseMembers;
  SmallVector<ValueDecl*, 2> BaseMembersStorage;
  if (StructType *ST = BaseType->getAs<StructType>()) {
    // FIXME: Refuse to look up "constructors" until we have real constructors.
    if (ST->getDecl()->getName() == Name)
      return;

    D = ST->getDecl();
    for (Decl* Member : ST->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (ClassType *CT = BaseType->getAs<ClassType>()) {
    D = CT->getDecl();
    for (Decl* Member : CT->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (OneOfType *OOT = BaseType->getAs<OneOfType>()) {
    // FIXME: Refuse to look up "constructors" until we have real constructors.
    if (OOT->getDecl()->getName() == Name)
      return;

    D = OOT->getDecl();
    for (Decl* Member : OOT->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else {
    return;
  }

  DeclContext *DC = D->getDeclContext();
  while (!DC->isModuleContext())
    DC = DC->getParent();

  DoGlobalExtensionLookup(BaseType, Name, BaseMembers, this, cast<Module>(DC),
                          Result);
}

/// lookupGlobalExtensionMethods - Lookup the extensions members for the
/// specified BaseType with the specified type, and return them in Result.
void Module::lookupValueConstructors(Type BaseType,
                                     SmallVectorImpl<ValueDecl*> &Result) {
  assert(Result.empty() &&
         "This expects that the input list is empty, could be generalized");

  TypeDecl *D;
  Identifier Constructor = Ctx.getIdentifier("constructor");
  ArrayRef<ValueDecl*> BaseMembers;
  SmallVector<ValueDecl*, 2> BaseMembersStorage;
  if (StructType *ST = BaseType->getAs<StructType>()) {
    D = ST->getDecl();
    for (Decl* Member : ST->getDecl()->getMembers()) {
      if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
    BaseMembers = BaseMembersStorage;
  } else if (OneOfType *OOT = BaseType->getAs<OneOfType>()) {
    D = OOT->getDecl();
    for (Decl* Member : OOT->getDecl()->getMembers()) {
      // FIXME: We shouldn't be injecting OneOfElementDecls into the results
      // like this.
      if (OneOfElementDecl *OOED = dyn_cast<OneOfElementDecl>(Member))
        Result.push_back(OOED);
      else if (ValueDecl *VD = dyn_cast<ValueDecl>(Member))
        BaseMembersStorage.push_back(VD);
    }
  } else {
    return;
  }

  DeclContext *DC = D->getDeclContext();
  if (!DC->isModuleContext()) {
    for (ValueDecl *VD : BaseMembers) {
      if (VD->getName() == Constructor)
        Result.push_back(VD);
    }
    return;
  }

  DoGlobalExtensionLookup(BaseType, Constructor, BaseMembers, this,
                          cast<Module>(DC), Result);
}

//===----------------------------------------------------------------------===//
// TranslationUnit Implementation
//===----------------------------------------------------------------------===//

void TranslationUnit::clearLookupCache() {
  freeTUCachePimpl(LookupCachePimpl);
  freeTUExtensionCachePimpl(ExtensionCachePimpl);
}
<|endoftext|>


<commit_before>/*
    messagebox.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "messagebox.h"

#include "kleo/job.h"

#include <gpgme++/signingresult.h>
#include <gpgme++/encryptionresult.h>

#include <kfiledialog.h>
#include <kdialog.h>
#include <klocale.h>
#include <ksavefile.h>
#include <kguiitem.h>

#include <qtextedit.h>
#include <qtextstream.h>

using namespace Kleo;
using namespace GpgME;

namespace {

static KGuiItem KGuiItem_save() {
    return KGuiItem( i18n("&Save to Disk..."), "filesaveas" );
}

static KGuiItem KGuiItem_copy() {
    return KGuiItem( i18n("&Copy to Clipboard"), "editcopy", i18n("Copy Audit Log to Clipboard") );
}

static KGuiItem KGuiItem_showAuditLog() {
    return KGuiItem( i18n("&Show Audit Log") ); // "view_log"?
}

class AuditLogViewer : public KDialog {
    // Q_OBJECT
public:
    explicit AuditLogViewer( const QString & log, QWidget * parent=0, Qt::WindowFlags f=0 )
        : KDialog( parent ),
          m_textEdit( new QTextEdit( this ) )
    {
        setCaption( i18n("View GnuPG Audit Log") );
        setButtons( Close|User1|User2 );
        setDefaultButton( Close );
        setButtonGuiItem( User1, KGuiItem_save() );
        setButtonGuiItem( User2, KGuiItem_copy() );
        showButtonSeparator( false );
        setModal( false );
        setWindowFlags( f );
        setMainWidget( m_textEdit );
        m_textEdit->setObjectName( "m_textEdit" );
        m_textEdit->setReadOnly( true );
        setAuditLog( log );

        connect( this, SIGNAL(user1Clicked()), SLOT(slotUser1()) );
        connect( this, SIGNAL(user2Clicked()), SLOT(slotUser2()) );
    }
    ~AuditLogViewer() {}

    void setAuditLog( const QString & log ) {
        m_textEdit->setHtml( log );
    }

private:
    void slotUser1() {
        const QString fileName = KFileDialog::getSaveFileName( QString(), QString(),
                                                               this, i18n("Choose File to Save GnuPG Audit Log to") );
        if ( fileName.isEmpty() )
            return;

        KSaveFile file( fileName );

        if ( file.open() ) {
            QTextStream s( &file );
            s << m_textEdit->toPlainText() << endl;
            s.flush();
            file.finalize();
        }

        if ( const int err = file.error() )
            KMessageBox::error( this, i18n("Couldn't save to file \"%1\": %2",
                                file.fileName(), QString::fromLocal8Bit( strerror( err ) ) ),
                                i18n("File Save Error") );
    }
    void slotUser2() {
        m_textEdit->selectAll();
        m_textEdit->copy();
        m_textEdit->textCursor().clearSelection();
    }

private:
    QTextEdit * m_textEdit;
};

} // anon namespace

// static
void MessageBox::auditLog( QWidget * parent, const Job * job, const QString & caption ) {

    if ( !job )
        return;

    if ( !GpgME::hasFeature( AuditLogFeature ) ) {
        KMessageBox::information( parent, i18n("Your system does not have support for GnuPG Audit Logs"),
                                  i18n("System Error") );
        return;
    }

    const QString log = job->auditLogAsHtml();
    if ( log.isEmpty() ) {
        KMessageBox::information( parent, i18n("No GnuPG Audit Log available for this operation."),
                                  i18n("No GnuPG Audit Log") );
        return;
    }

    auditLog( parent, log, caption );
}

// static
void MessageBox::auditLog( QWidget * parent, const QString & log, const QString & caption ) {
    AuditLogViewer * const alv = new AuditLogViewer( "<qt>" + log + "</qt>", parent, Qt::WDestructiveClose );
    alv->setObjectName( "alv" );
    alv->setCaption( caption );
    alv->show();
}

// static
void MessageBox::auditLog( QWidget * parent, const Job * job ) {
    auditLog( parent, job, i18n("GnuPG Audit Log Viewer") );
}

// static
void MessageBox::auditLog( QWidget * parent, const QString & log ) {
    auditLog( parent, log, i18n("GnuPG Audit Log Viewer") );
}

static QString to_information_string( const SigningResult & result ) {
    return result.error()
        ? i18n("Signing failed: %1", QString::fromLocal8Bit( result.error().asString() ) )
        : i18n("Signing successful") ;
}

static QString to_error_string( const SigningResult & result ) {
    return to_information_string( result );
}

static QString to_information_string( const EncryptionResult & result ) {
    return result.error()
        ? i18n("Encryption failed: %1", QString::fromLocal8Bit( result.error().asString() ) )
        : i18n("Encryption successful") ;
}

static QString to_error_string( const EncryptionResult & result ) {
    return to_information_string( result );
}

static QString to_information_string( const SigningResult & sresult, const EncryptionResult & eresult ) {
    return to_information_string( sresult ) + '\n' + to_information_string( eresult );
}

static QString to_error_string( const SigningResult & sresult, const EncryptionResult & eresult ) {
    return to_information_string( sresult, eresult );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, KMessageBox::Options options ) {
    information( parent, result, job, i18n("Signing Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, KMessageBox::Options options ) {
    error( parent, result, job, i18n("Signing Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options );
}

// static
void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, KMessageBox::Options options ) {
    information( parent, result, job, i18n("Encryption Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, KMessageBox::Options options ) {
    error( parent, result, job, i18n("Encryption Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, KMessageBox::Options options ) {
    information( parent, sresult, eresult, job, i18n("Encryption Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( sresult, eresult ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, KMessageBox::Options options ) {
    error( parent, sresult, eresult, job, i18n("Encryption Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( sresult, eresult ), job, caption, options );
}

// static
void MessageBox::make( QWidget * parent, QMessageBox::Icon icon, const QString & text, const Job * job, const QString & caption, KMessageBox::Options options ) {
    KDialog * dialog = new KDialog( parent );
    dialog->setCaption( caption );
    dialog->setButtons( GpgME::hasFeature( GpgME::AuditLogFeature ) ? ( KDialog::Yes | KDialog::No ) : KDialog::Yes );
    dialog->setDefaultButton( KDialog::Yes );
    dialog->setEscapeButton( KDialog::Yes );
    dialog->setObjectName( "error" );
    dialog->setModal( true );
    dialog->showButtonSeparator( true );
    dialog->setButtonGuiItem( KDialog::Yes, KStandardGuiItem::ok() );
    if ( GpgME::hasFeature( GpgME::AuditLogFeature ) )
      dialog->setButtonGuiItem( KDialog::No, KGuiItem_showAuditLog() );

    if ( options & KMessageBox::PlainCaption )
        dialog->setPlainCaption( caption );

    if ( KDialog::No == KMessageBox::createKMessageBox( dialog, icon, text, QStringList(), QString::null, 0, options ) )
        auditLog( 0, job );
}
<commit_msg>use QFileDialog with ONLY_KLEO<commit_after>/*
    messagebox.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "messagebox.h"

#include "kleo/job.h"

#include <gpgme++/signingresult.h>
#include <gpgme++/encryptionresult.h>

#ifndef ONLY_KLEO
# include <kfiledialog.h>
#else
# include <QFileDialog>
#endif

#include <kdialog.h>
#include <klocale.h>
#include <ksavefile.h>
#include <kguiitem.h>

#include <qtextedit.h>
#include <qtextstream.h>

using namespace Kleo;
using namespace GpgME;

namespace {

static KGuiItem KGuiItem_save() {
    return KGuiItem( i18n("&Save to Disk..."), "filesaveas" );
}

static KGuiItem KGuiItem_copy() {
    return KGuiItem( i18n("&Copy to Clipboard"), "editcopy", i18n("Copy Audit Log to Clipboard") );
}

static KGuiItem KGuiItem_showAuditLog() {
    return KGuiItem( i18n("&Show Audit Log") ); // "view_log"?
}

class AuditLogViewer : public KDialog {
    // Q_OBJECT
public:
    explicit AuditLogViewer( const QString & log, QWidget * parent=0, Qt::WindowFlags f=0 )
        : KDialog( parent ),
          m_textEdit( new QTextEdit( this ) )
    {
        setCaption( i18n("View GnuPG Audit Log") );
        setButtons( Close|User1|User2 );
        setDefaultButton( Close );
        setButtonGuiItem( User1, KGuiItem_save() );
        setButtonGuiItem( User2, KGuiItem_copy() );
        showButtonSeparator( false );
        setModal( false );
        setWindowFlags( f );
        setMainWidget( m_textEdit );
        m_textEdit->setObjectName( "m_textEdit" );
        m_textEdit->setReadOnly( true );
        setAuditLog( log );

        connect( this, SIGNAL(user1Clicked()), SLOT(slotUser1()) );
        connect( this, SIGNAL(user2Clicked()), SLOT(slotUser2()) );
    }
    ~AuditLogViewer() {}

    void setAuditLog( const QString & log ) {
        m_textEdit->setHtml( log );
    }

private:
    void slotUser1() {
#ifndef ONLY_KLEO
        const QString fileName = KFileDialog::getSaveFileName( QString(), QString(),
                                                               this, i18n("Choose File to Save GnuPG Audit Log to") );
#else
        const QString fileName = QFileDialog::getSaveFileName( this, i18n("Choose File to Save GnuPG Audit Log to") );
#endif
        if ( fileName.isEmpty() )
            return;

        KSaveFile file( fileName );

        if ( file.open() ) {
            QTextStream s( &file );
            s << m_textEdit->toPlainText() << endl;
            s.flush();
            file.finalize();
        }

        if ( const int err = file.error() )
            KMessageBox::error( this, i18n("Couldn't save to file \"%1\": %2",
                                file.fileName(), QString::fromLocal8Bit( strerror( err ) ) ),
                                i18n("File Save Error") );
    }
    void slotUser2() {
        m_textEdit->selectAll();
        m_textEdit->copy();
        m_textEdit->textCursor().clearSelection();
    }

private:
    QTextEdit * m_textEdit;
};

} // anon namespace

// static
void MessageBox::auditLog( QWidget * parent, const Job * job, const QString & caption ) {

    if ( !job )
        return;

    if ( !GpgME::hasFeature( AuditLogFeature ) ) {
        KMessageBox::information( parent, i18n("Your system does not have support for GnuPG Audit Logs"),
                                  i18n("System Error") );
        return;
    }

    const QString log = job->auditLogAsHtml();
    if ( log.isEmpty() ) {
        KMessageBox::information( parent, i18n("No GnuPG Audit Log available for this operation."),
                                  i18n("No GnuPG Audit Log") );
        return;
    }

    auditLog( parent, log, caption );
}

// static
void MessageBox::auditLog( QWidget * parent, const QString & log, const QString & caption ) {
    AuditLogViewer * const alv = new AuditLogViewer( "<qt>" + log + "</qt>", parent, Qt::WDestructiveClose );
    alv->setObjectName( "alv" );
    alv->setCaption( caption );
    alv->show();
}

// static
void MessageBox::auditLog( QWidget * parent, const Job * job ) {
    auditLog( parent, job, i18n("GnuPG Audit Log Viewer") );
}

// static
void MessageBox::auditLog( QWidget * parent, const QString & log ) {
    auditLog( parent, log, i18n("GnuPG Audit Log Viewer") );
}

static QString to_information_string( const SigningResult & result ) {
    return result.error()
        ? i18n("Signing failed: %1", QString::fromLocal8Bit( result.error().asString() ) )
        : i18n("Signing successful") ;
}

static QString to_error_string( const SigningResult & result ) {
    return to_information_string( result );
}

static QString to_information_string( const EncryptionResult & result ) {
    return result.error()
        ? i18n("Encryption failed: %1", QString::fromLocal8Bit( result.error().asString() ) )
        : i18n("Encryption successful") ;
}

static QString to_error_string( const EncryptionResult & result ) {
    return to_information_string( result );
}

static QString to_information_string( const SigningResult & sresult, const EncryptionResult & eresult ) {
    return to_information_string( sresult ) + '\n' + to_information_string( eresult );
}

static QString to_error_string( const SigningResult & sresult, const EncryptionResult & eresult ) {
    return to_information_string( sresult, eresult );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, KMessageBox::Options options ) {
    information( parent, result, job, i18n("Signing Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, KMessageBox::Options options ) {
    error( parent, result, job, i18n("Signing Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options );
}

// static
void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, KMessageBox::Options options ) {
    information( parent, result, job, i18n("Encryption Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, KMessageBox::Options options ) {
    error( parent, result, job, i18n("Encryption Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, KMessageBox::Options options ) {
    information( parent, sresult, eresult, job, i18n("Encryption Result"), options );
}

// static
void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Information, to_information_string( sresult, eresult ), job, caption, options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, KMessageBox::Options options ) {
    error( parent, sresult, eresult, job, i18n("Encryption Error"), options );
}

// static
void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, KMessageBox::Options options ) {
    make( parent, QMessageBox::Critical, to_error_string( sresult, eresult ), job, caption, options );
}

// static
void MessageBox::make( QWidget * parent, QMessageBox::Icon icon, const QString & text, const Job * job, const QString & caption, KMessageBox::Options options ) {
    KDialog * dialog = new KDialog( parent );
    dialog->setCaption( caption );
    dialog->setButtons( GpgME::hasFeature( GpgME::AuditLogFeature ) ? ( KDialog::Yes | KDialog::No ) : KDialog::Yes );
    dialog->setDefaultButton( KDialog::Yes );
    dialog->setEscapeButton( KDialog::Yes );
    dialog->setObjectName( "error" );
    dialog->setModal( true );
    dialog->showButtonSeparator( true );
    dialog->setButtonGuiItem( KDialog::Yes, KStandardGuiItem::ok() );
    if ( GpgME::hasFeature( GpgME::AuditLogFeature ) )
      dialog->setButtonGuiItem( KDialog::No, KGuiItem_showAuditLog() );

    if ( options & KMessageBox::PlainCaption )
        dialog->setPlainCaption( caption );

    if ( KDialog::No == KMessageBox::createKMessageBox( dialog, icon, text, QStringList(), QString::null, 0, options ) )
        auditLog( 0, job );
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// 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.

// Internal Includes
#include <osvr/common/PathTreeOwner.h>
#include <osvr/common/PathTreeObserver.h>
#include <osvr/Common/PathTreeSerialization.h>

// Library/third-party includes
// - none

// Standard includes
#include <algorithm>
#include <iterator>

namespace osvr {
namespace common {
    namespace {
        /// @brief Class for the sole purpose of being able to use
        /// make_shared with PathTreeObserver.
        class PathTreeObserverConcrete : public PathTreeObserver {
          public:
            PathTreeObserverConcrete() = default;
        };
    } // namespace

    /// Given a container of weak ptrs to some type and a functor that operates
    /// on references to that type, go through all elements of the container in
    /// a single pass, calling the functor on those elements still valid, and
    /// removing those invalid ones. (Uses member function resize with two
    /// iterators)
    template <typename T, typename F>
    inline void for_each_cleanup_pointers(T &c, F &&f) {
        using weak_ptr_type = typename T::value_type;
        auto newEnd =
            std::remove_if(begin(c), end(c), [&](weak_ptr_type const &ptr) {
                auto fullPtr = ptr.lock();
                if (fullPtr) {
                    f(*fullPtr);
                    return false; // don't remove this one
                }
                return true; // this one we couldn't lock - expired observer.
            });
        c.erase(newEnd, end(c));
    }

    PathTreeObserverPtr PathTreeOwner::makeObserver() {
        auto ret = PathTreeObserverPtr{make_shared<PathTreeObserverConcrete>()};
        m_observers.push_back(ret);
        return ret;
    }

    void PathTreeOwner::replaceTree(Json::Value const &nodes) {
        for_each_cleanup_pointers(
            m_observers, [&](PathTreeObserver const &observer) {
                observer.notifyEvent(PathTreeEvents::AboutToUpdate, m_tree);
            });

        m_tree.reset();

        common::jsonToPathTree(m_tree, nodes);

        m_valid = true;

        for_each_cleanup_pointers(
            m_observers, [&](PathTreeObserver const &observer) {
                observer.notifyEvent(PathTreeEvents::AfterUpdate, m_tree);
            });
    }
} // namespace common
} // namespace osvr
<commit_msg>Fix capitalization of include.<commit_after>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// 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.

// Internal Includes
#include <osvr/Common/PathTreeOwner.h>
#include <osvr/Common/PathTreeObserver.h>
#include <osvr/Common/PathTreeSerialization.h>

// Library/third-party includes
// - none

// Standard includes
#include <algorithm>
#include <iterator>

namespace osvr {
namespace common {
    namespace {
        /// @brief Class for the sole purpose of being able to use
        /// make_shared with PathTreeObserver.
        class PathTreeObserverConcrete : public PathTreeObserver {
          public:
            PathTreeObserverConcrete() = default;
        };
    } // namespace

    /// Given a container of weak ptrs to some type and a functor that operates
    /// on references to that type, go through all elements of the container in
    /// a single pass, calling the functor on those elements still valid, and
    /// removing those invalid ones. (Uses member function resize with two
    /// iterators)
    template <typename T, typename F>
    inline void for_each_cleanup_pointers(T &c, F &&f) {
        using weak_ptr_type = typename T::value_type;
        auto newEnd =
            std::remove_if(begin(c), end(c), [&](weak_ptr_type const &ptr) {
                auto fullPtr = ptr.lock();
                if (fullPtr) {
                    f(*fullPtr);
                    return false; // don't remove this one
                }
                return true; // this one we couldn't lock - expired observer.
            });
        c.erase(newEnd, end(c));
    }

    PathTreeObserverPtr PathTreeOwner::makeObserver() {
        auto ret = PathTreeObserverPtr{make_shared<PathTreeObserverConcrete>()};
        m_observers.push_back(ret);
        return ret;
    }

    void PathTreeOwner::replaceTree(Json::Value const &nodes) {
        for_each_cleanup_pointers(
            m_observers, [&](PathTreeObserver const &observer) {
                observer.notifyEvent(PathTreeEvents::AboutToUpdate, m_tree);
            });

        m_tree.reset();

        common::jsonToPathTree(m_tree, nodes);

        m_valid = true;

        for_each_cleanup_pointers(
            m_observers, [&](PathTreeObserver const &observer) {
                observer.notifyEvent(PathTreeEvents::AfterUpdate, m_tree);
            });
    }
} // namespace common
} // namespace osvr
<|endoftext|>