text
stringlengths 54
60.6k
|
---|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include "modules/prediction/common/prediction_gflags.h"
// System gflags
DEFINE_string(prediction_module_name, "prediction",
"Default prediciton module name");
DEFINE_string(prediction_conf_file,
"modules/prediction/conf/prediction_conf.pb.txt",
"Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
"modules/prediction/conf/adapter.conf",
"Default conf file for prediction");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
prediction_test_duration, -1.0,
"The runtime duration in test mode (in seconds). Negative value will not "
"restrict the runtime duration.");
DEFINE_double(prediction_duration, 5.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 50.0,
"Minimal length of prediction trajectory");
// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
"Max timestamp gap for rosbag replay");
// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");
// Obstacle features
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
"The rate to approach to the reference line of going straight");
DEFINE_double(cutin_approach_rate, 0.9,
"The rate to approach to the reference line of lane change");
DEFINE_int32(still_obstacle_history_length, 10,
"Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
"Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
"Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
"Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 1, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
"Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
"Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
"modules/prediction/data/mlp_vehicle_model.bin",
"mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
"modules/prediction/data/rnn_vehicle_model.bin",
"rnn model file for vehicle evaluator");
DEFINE_int32(max_num_obstacles, 100,
"maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
"threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
"threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5,
"obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
"Minimal relative s for RNN model.");
DEFINE_bool(enable_adjust_velocity_heading, false,
"adjust velocity heading to lane heading");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");
// Obstacle trajectory
DEFINE_double(lane_sequence_threshold, 0.5,
"Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
"If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
"If trim the prediction trajectory to avoid crossing"
"protected adc planning trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
"If the obstacle is in junction more than this threshold,"
"consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
"How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
"Default lateral speed approaching to center of lane");
// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 5.0,
"Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
"Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.2,
"Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
"The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lane_center, 5.0,
"The default time to lane center");
<commit_msg>Prediction: modify min_prediction_length to 20.0<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include "modules/prediction/common/prediction_gflags.h"
// System gflags
DEFINE_string(prediction_module_name, "prediction",
"Default prediciton module name");
DEFINE_string(prediction_conf_file,
"modules/prediction/conf/prediction_conf.pb.txt",
"Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
"modules/prediction/conf/adapter.conf",
"Default conf file for prediction");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
prediction_test_duration, -1.0,
"The runtime duration in test mode (in seconds). Negative value will not "
"restrict the runtime duration.");
DEFINE_double(prediction_duration, 5.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 20.0,
"Minimal length of prediction trajectory");
// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
"Max timestamp gap for rosbag replay");
// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");
// Obstacle features
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
"The rate to approach to the reference line of going straight");
DEFINE_double(cutin_approach_rate, 0.9,
"The rate to approach to the reference line of lane change");
DEFINE_int32(still_obstacle_history_length, 10,
"Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
"Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
"Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
"Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 1, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
"Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
"Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
"modules/prediction/data/mlp_vehicle_model.bin",
"mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
"modules/prediction/data/rnn_vehicle_model.bin",
"rnn model file for vehicle evaluator");
DEFINE_int32(max_num_obstacles, 100,
"maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
"threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
"threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5,
"obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
"Minimal relative s for RNN model.");
DEFINE_bool(enable_adjust_velocity_heading, false,
"adjust velocity heading to lane heading");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");
// Obstacle trajectory
DEFINE_double(lane_sequence_threshold, 0.5,
"Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
"If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
"If trim the prediction trajectory to avoid crossing"
"protected adc planning trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
"If the obstacle is in junction more than this threshold,"
"consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
"How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
"Default lateral speed approaching to center of lane");
// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 5.0,
"Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
"Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.2,
"Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
"The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lane_center, 5.0,
"The default time to lane center");
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <planning_models/transforms.h>
#include <ros/console.h>
bool planning_models::quatFromMsg(const geometry_msgs::Quaternion &qmsg, Eigen::Quaterniond &q)
{
q = Eigen::Quaterniond(qmsg.w, qmsg.x, qmsg.y, qmsg.z);
double error = fabs(q.squaredNorm() - 1.0);
if (error > 0.1)
{
ROS_ERROR("Quaternion is NOWHERE CLOSE TO NORMALIZED [x,y,z,w], [%.2f, %.2f, %.2f, %.2f]. Can't do much, returning identity.",
qmsg.x, qmsg.y, qmsg.z, qmsg.w);
q = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0);
return false;
}
else if(error > 1e-3)
q.normalize();
return true;
}
bool planning_models::poseFromMsg(const geometry_msgs::Pose &tmsg, Eigen::Affine3d &t)
{
Eigen::Quaterniond q; bool r = quatFromMsg(tmsg.orientation, q);
t = Eigen::Affine3d(Eigen::Translation3d(tmsg.position.x, tmsg.position.y, tmsg.position.z)*q.toRotationMatrix());
return r;
}
void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Pose &tmsg)
{
tmsg.position.x = t.translation().x(); tmsg.position.y = t.translation().y(); tmsg.position.z = t.translation().z();
Eigen::Quaterniond q(t.rotation());
tmsg.orientation.x = q.x(); tmsg.orientation.y = q.y(); tmsg.orientation.z = q.z(); tmsg.orientation.w = q.w();
}
void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Transform &tmsg)
{
tmsg.translation.x = t.translation().x(); tmsg.translation.y = t.translation().y(); tmsg.translation.z = t.translation().z();
Eigen::Quaterniond q(t.rotation());
tmsg.rotation.x = q.x(); tmsg.rotation.y = q.y(); tmsg.rotation.z = q.z(); tmsg.rotation.w = q.w();
}
planning_models::Transforms::Transforms(const std::string &target_frame) : target_frame_(target_frame)
{
Eigen::Affine3d t;
t.setIdentity();
transforms_[target_frame_] = t;
}
planning_models::Transforms::Transforms(const Transforms &other) : target_frame_(other.target_frame_), transforms_(other.transforms_)
{
}
planning_models::Transforms::~Transforms(void)
{
}
const std::string& planning_models::Transforms::getTargetFrame(void) const
{
return target_frame_;
}
const planning_models::EigenAffine3dMapType& planning_models::Transforms::getAllTransforms(void) const
{
return transforms_;
}
bool planning_models::Transforms::isFixedFrame(const std::string &frame) const
{
return transforms_.find(frame) != transforms_.end();
}
const Eigen::Affine3d& planning_models::Transforms::getTransform(const std::string &from_frame) const
{
EigenAffine3dMapType::const_iterator it = transforms_.find(from_frame);
if (it != transforms_.end())
return it->second;
ROS_ERROR_STREAM("Unable to transform from frame '" + from_frame + "' to frame '" + target_frame_ + "'");
// return identity
return transforms_.find(target_frame_)->second;
}
const Eigen::Affine3d& planning_models::Transforms::getTransform(const planning_models::KinematicState &kstate, const std::string &from_frame) const
{
std::map<std::string, Eigen::Affine3d>::const_iterator it = transforms_.find(from_frame);
if (it != transforms_.end())
return it->second;
if (kstate.getKinematicModel()->getModelFrame() != target_frame_)
ROS_ERROR("Target frame is assumed to be '%s' but the model of the kinematic state places the robot in frame '%s'",
target_frame_.c_str(), kstate.getKinematicModel()->getModelFrame().c_str());
const Eigen::Affine3d *t = kstate.getFrameTransform(from_frame);
if (t)
return *t;
else
// return identity
return transforms_.find(target_frame_)->second;
}
void planning_models::Transforms::transformVector3(const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const
{
v_out = getTransform(from_frame) * v_in;
}
void planning_models::Transforms::transformQuaternion(const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const
{
q_out = getTransform(from_frame).rotation() * q_in;
}
void planning_models::Transforms::transformRotationMatrix(const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const
{
m_out = getTransform(from_frame).rotation() * m_in;
}
void planning_models::Transforms::transformPose(const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const
{
t_out = getTransform(from_frame) * t_in;
}
// specify the kinematic state
void planning_models::Transforms::transformVector3(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const
{
v_out = getTransform(kstate, from_frame).rotation() * v_in;
}
void planning_models::Transforms::transformQuaternion(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const
{
q_out = getTransform(kstate, from_frame).rotation() * q_in;
}
void planning_models::Transforms::transformRotationMatrix(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const
{
m_out = getTransform(kstate, from_frame).rotation() * m_in;
}
void planning_models::Transforms::transformPose(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const
{
t_out = getTransform(kstate, from_frame) * t_in;
}
void planning_models::Transforms::setTransform(const Eigen::Affine3d &t, const std::string &from_frame)
{
transforms_[from_frame] = t;
}
void planning_models::Transforms::setTransform(const geometry_msgs::TransformStamped &transform)
{
if (transform.child_frame_id.rfind(target_frame_) == transform.child_frame_id.length() - target_frame_.length())
{
Eigen::Translation3d o(transform.transform.translation.x, transform.transform.translation.y, transform.transform.translation.z);
Eigen::Quaterniond q;
quatFromMsg(transform.transform.rotation, q);
setTransform(Eigen::Affine3d(o*q.toRotationMatrix()), transform.header.frame_id);
} else {
ROS_ERROR("Given transform is to frame '%s', but frame '%s' was expected.", transform.child_frame_id.c_str(), target_frame_.c_str());
}
}
void planning_models::Transforms::setTransforms(const std::vector<geometry_msgs::TransformStamped> &transforms)
{
for (std::size_t i = 0 ; i < transforms.size() ; ++i)
setTransform(transforms[i]);
}
void planning_models::Transforms::getTransforms(std::vector<geometry_msgs::TransformStamped> &transforms) const
{
transforms.resize(transforms_.size());
std::size_t i = 0;
for (EigenAffine3dMapType::const_iterator it = transforms_.begin() ; it != transforms_.end() ; ++it, ++i)
{
transforms[i].child_frame_id = target_frame_;
transforms[i].header.frame_id = it->first;
transforms[i].transform.translation.x = it->second.translation().x();
transforms[i].transform.translation.y = it->second.translation().y();
transforms[i].transform.translation.z = it->second.translation().z();
Eigen::Quaterniond q(it->second.rotation());
transforms[i].transform.rotation.x = q.x();
transforms[i].transform.rotation.y = q.y();
transforms[i].transform.rotation.z = q.z();
transforms[i].transform.rotation.w = q.w();
}
}
<commit_msg>tighter checks on quaternions<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <planning_models/transforms.h>
#include <ros/console.h>
bool planning_models::quatFromMsg(const geometry_msgs::Quaternion &qmsg, Eigen::Quaterniond &q)
{
q = Eigen::Quaterniond(qmsg.w, qmsg.x, qmsg.y, qmsg.z);
double error = fabs(q.squaredNorm() - 1.0);
if (error > 0.05)
{
ROS_ERROR("Quaternion is NOWHERE CLOSE TO NORMALIZED [x,y,z,w], [%.2f, %.2f, %.2f, %.2f]. Can't do much, returning identity.",
qmsg.x, qmsg.y, qmsg.z, qmsg.w);
q = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0);
return false;
}
else if(error > 1e-3)
q.normalize();
return true;
}
bool planning_models::poseFromMsg(const geometry_msgs::Pose &tmsg, Eigen::Affine3d &t)
{
Eigen::Quaterniond q; bool r = quatFromMsg(tmsg.orientation, q);
t = Eigen::Affine3d(Eigen::Translation3d(tmsg.position.x, tmsg.position.y, tmsg.position.z)*q.toRotationMatrix());
return r;
}
void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Pose &tmsg)
{
tmsg.position.x = t.translation().x(); tmsg.position.y = t.translation().y(); tmsg.position.z = t.translation().z();
Eigen::Quaterniond q(t.rotation());
tmsg.orientation.x = q.x(); tmsg.orientation.y = q.y(); tmsg.orientation.z = q.z(); tmsg.orientation.w = q.w();
}
void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Transform &tmsg)
{
tmsg.translation.x = t.translation().x(); tmsg.translation.y = t.translation().y(); tmsg.translation.z = t.translation().z();
Eigen::Quaterniond q(t.rotation());
tmsg.rotation.x = q.x(); tmsg.rotation.y = q.y(); tmsg.rotation.z = q.z(); tmsg.rotation.w = q.w();
}
planning_models::Transforms::Transforms(const std::string &target_frame) : target_frame_(target_frame)
{
Eigen::Affine3d t;
t.setIdentity();
transforms_[target_frame_] = t;
}
planning_models::Transforms::Transforms(const Transforms &other) : target_frame_(other.target_frame_), transforms_(other.transforms_)
{
}
planning_models::Transforms::~Transforms(void)
{
}
const std::string& planning_models::Transforms::getTargetFrame(void) const
{
return target_frame_;
}
const planning_models::EigenAffine3dMapType& planning_models::Transforms::getAllTransforms(void) const
{
return transforms_;
}
bool planning_models::Transforms::isFixedFrame(const std::string &frame) const
{
return transforms_.find(frame) != transforms_.end();
}
const Eigen::Affine3d& planning_models::Transforms::getTransform(const std::string &from_frame) const
{
EigenAffine3dMapType::const_iterator it = transforms_.find(from_frame);
if (it != transforms_.end())
return it->second;
ROS_ERROR_STREAM("Unable to transform from frame '" + from_frame + "' to frame '" + target_frame_ + "'");
// return identity
return transforms_.find(target_frame_)->second;
}
const Eigen::Affine3d& planning_models::Transforms::getTransform(const planning_models::KinematicState &kstate, const std::string &from_frame) const
{
std::map<std::string, Eigen::Affine3d>::const_iterator it = transforms_.find(from_frame);
if (it != transforms_.end())
return it->second;
if (kstate.getKinematicModel()->getModelFrame() != target_frame_)
ROS_ERROR("Target frame is assumed to be '%s' but the model of the kinematic state places the robot in frame '%s'",
target_frame_.c_str(), kstate.getKinematicModel()->getModelFrame().c_str());
const Eigen::Affine3d *t = kstate.getFrameTransform(from_frame);
if (t)
return *t;
else
// return identity
return transforms_.find(target_frame_)->second;
}
void planning_models::Transforms::transformVector3(const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const
{
v_out = getTransform(from_frame) * v_in;
}
void planning_models::Transforms::transformQuaternion(const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const
{
q_out = getTransform(from_frame).rotation() * q_in;
}
void planning_models::Transforms::transformRotationMatrix(const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const
{
m_out = getTransform(from_frame).rotation() * m_in;
}
void planning_models::Transforms::transformPose(const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const
{
t_out = getTransform(from_frame) * t_in;
}
// specify the kinematic state
void planning_models::Transforms::transformVector3(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const
{
v_out = getTransform(kstate, from_frame).rotation() * v_in;
}
void planning_models::Transforms::transformQuaternion(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const
{
q_out = getTransform(kstate, from_frame).rotation() * q_in;
}
void planning_models::Transforms::transformRotationMatrix(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const
{
m_out = getTransform(kstate, from_frame).rotation() * m_in;
}
void planning_models::Transforms::transformPose(const planning_models::KinematicState &kstate,
const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const
{
t_out = getTransform(kstate, from_frame) * t_in;
}
void planning_models::Transforms::setTransform(const Eigen::Affine3d &t, const std::string &from_frame)
{
transforms_[from_frame] = t;
}
void planning_models::Transforms::setTransform(const geometry_msgs::TransformStamped &transform)
{
if (transform.child_frame_id.rfind(target_frame_) == transform.child_frame_id.length() - target_frame_.length())
{
Eigen::Translation3d o(transform.transform.translation.x, transform.transform.translation.y, transform.transform.translation.z);
Eigen::Quaterniond q;
quatFromMsg(transform.transform.rotation, q);
setTransform(Eigen::Affine3d(o*q.toRotationMatrix()), transform.header.frame_id);
} else {
ROS_ERROR("Given transform is to frame '%s', but frame '%s' was expected.", transform.child_frame_id.c_str(), target_frame_.c_str());
}
}
void planning_models::Transforms::setTransforms(const std::vector<geometry_msgs::TransformStamped> &transforms)
{
for (std::size_t i = 0 ; i < transforms.size() ; ++i)
setTransform(transforms[i]);
}
void planning_models::Transforms::getTransforms(std::vector<geometry_msgs::TransformStamped> &transforms) const
{
transforms.resize(transforms_.size());
std::size_t i = 0;
for (EigenAffine3dMapType::const_iterator it = transforms_.begin() ; it != transforms_.end() ; ++it, ++i)
{
transforms[i].child_frame_id = target_frame_;
transforms[i].header.frame_id = it->first;
transforms[i].transform.translation.x = it->second.translation().x();
transforms[i].transform.translation.y = it->second.translation().y();
transforms[i].transform.translation.z = it->second.translation().z();
Eigen::Quaterniond q(it->second.rotation());
transforms[i].transform.rotation.x = q.x();
transforms[i].transform.rotation.y = q.y();
transforms[i].transform.rotation.z = q.z();
transforms[i].transform.rotation.w = q.w();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: decryptorimpl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:36:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"
#include "decryptorimpl.hxx"
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLENCRYPTIONTEMPLATE_HPP_
#include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_WRAPPER_XXMLELEMENTWRAPPER_HPP_
#include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxw = com::sun::star::xml::wrapper;
#define SERVICE_NAME "com.sun.star.xml.crypto.sax.Decryptor"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.framework.DecryptorImpl"
#define DECLARE_ASCII( SASCIIVALUE ) \
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SASCIIVALUE ) )
DecryptorImpl::DecryptorImpl( const cssu::Reference< cssl::XMultiServiceFactory >& rxMSF)
{
mxMSF = rxMSF;
}
DecryptorImpl::~DecryptorImpl()
{
}
bool DecryptorImpl::checkReady() const
/****** DecryptorImpl/checkReady *********************************************
*
* NAME
* checkReady -- checks the conditions for the decryption.
*
* SYNOPSIS
* bReady = checkReady( );
*
* FUNCTION
* checks whether all following conditions are satisfied:
* 1. the result listener is ready;
* 2. the EncryptionEngine is ready.
*
* INPUTS
* empty
*
* RESULT
* bReady - true if all conditions are satisfied, false otherwise
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
return (m_xResultListener.is() && EncryptionEngine::checkReady());
}
void DecryptorImpl::notifyResultListener() const
throw (cssu::Exception, cssu::RuntimeException)
/****** DecryptorImpl/notifyResultListener ***********************************
*
* NAME
* notifyResultListener -- notifies the listener about the decryption
* result.
*
* SYNOPSIS
* notifyResultListener( );
*
* FUNCTION
* see NAME.
*
* INPUTS
* empty
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
cssu::Reference< cssxc::sax::XDecryptionResultListener >
xDecryptionResultListener ( m_xResultListener , cssu::UNO_QUERY ) ;
xDecryptionResultListener->decrypted(m_nSecurityId,m_nStatus);
}
void DecryptorImpl::startEngine( const cssu::Reference<
cssxc::XXMLEncryptionTemplate >&
xEncryptionTemplate)
throw (cssu::Exception, cssu::RuntimeException)
/****** DecryptorImpl/startEngine ********************************************
*
* NAME
* startEngine -- decrypts the encryption.
*
* SYNOPSIS
* startEngine( xEncryptionTemplate );
*
* FUNCTION
* decrypts the encryption element, then if succeeds, updates the link
* of old template element to the new encryption element in
* SAXEventKeeper.
*
* INPUTS
* xEncryptionTemplate - the encryption template to be decrypted.
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
cssu::Reference< cssxc::XXMLEncryptionTemplate > xResultTemplate;
try
{
xResultTemplate = m_xXMLEncryption->decrypt(xEncryptionTemplate, m_xXMLSecurityContext);
m_nStatus = xResultTemplate->getStatus();
}
catch( cssu::Exception& )
{
m_nStatus = cssxc::SecurityOperationStatus_RUNTIMEERROR_FAILED;
}
if (m_nStatus == cssxc::SecurityOperationStatus_OPERATION_SUCCEEDED)
{
cssu::Reference< cssxw::XXMLElementWrapper > xDecryptedElement
= xResultTemplate->getTemplate();
m_xSAXEventKeeper->setElement(m_nIdOfTemplateEC, xDecryptedElement);
}
}
/* XDecryptionResultBroadcaster */
void SAL_CALL DecryptorImpl::addDecryptionResultListener( const cssu::Reference< cssxc::sax::XDecryptionResultListener >& listener )
throw (cssu::Exception, cssu::RuntimeException)
{
m_xResultListener = listener;
tryToPerform();
}
void SAL_CALL DecryptorImpl::removeDecryptionResultListener( const cssu::Reference< cssxc::sax::XDecryptionResultListener >& listener )
throw (cssu::RuntimeException)
{
}
/* XInitialization */
void SAL_CALL DecryptorImpl::initialize( const cssu::Sequence< cssu::Any >& aArguments )
throw (cssu::Exception, cssu::RuntimeException)
{
sal_Int32 nLength = aArguments.getLength();
OSL_ASSERT(nLength == 5);
rtl::OUString ouTempString;
aArguments[0] >>= ouTempString;
m_nSecurityId = ouTempString.toInt32();
aArguments[1] >>= m_xSAXEventKeeper;
aArguments[2] >>= ouTempString;
m_nIdOfTemplateEC = ouTempString.toInt32();
aArguments[3] >>= m_xXMLSecurityContext;
aArguments[4] >>= m_xXMLEncryption;
}
rtl::OUString DecryptorImpl_getImplementationName ()
throw (cssu::RuntimeException)
{
return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}
sal_Bool SAL_CALL DecryptorImpl_supportsService( const rtl::OUString& ServiceName )
throw (cssu::RuntimeException)
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}
cssu::Sequence< rtl::OUString > SAL_CALL DecryptorImpl_getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
cssu::Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
cssu::Reference< cssu::XInterface > SAL_CALL DecryptorImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory >& rSMgr)
throw( cssu::Exception )
{
return (cppu::OWeakObject*) new DecryptorImpl(rSMgr);
}
/* XServiceInfo */
rtl::OUString SAL_CALL DecryptorImpl::getImplementationName( )
throw (cssu::RuntimeException)
{
return DecryptorImpl_getImplementationName();
}
sal_Bool SAL_CALL DecryptorImpl::supportsService( const rtl::OUString& rServiceName )
throw (cssu::RuntimeException)
{
return DecryptorImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL DecryptorImpl::getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
return DecryptorImpl_getSupportedServiceNames();
}
<commit_msg>INTEGRATION: CWS jl51 (1.5.30); FILE MERGED 2007/02/05 13:54:18 jl 1.5.30.1: #i69228 warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: decryptorimpl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2007-04-17 10:17:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"
#include "decryptorimpl.hxx"
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLENCRYPTIONTEMPLATE_HPP_
#include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_WRAPPER_XXMLELEMENTWRAPPER_HPP_
#include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxw = com::sun::star::xml::wrapper;
#define SERVICE_NAME "com.sun.star.xml.crypto.sax.Decryptor"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.framework.DecryptorImpl"
#define DECLARE_ASCII( SASCIIVALUE ) \
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SASCIIVALUE ) )
DecryptorImpl::DecryptorImpl( const cssu::Reference< cssl::XMultiServiceFactory >& rxMSF)
{
mxMSF = rxMSF;
}
DecryptorImpl::~DecryptorImpl()
{
}
bool DecryptorImpl::checkReady() const
/****** DecryptorImpl/checkReady *********************************************
*
* NAME
* checkReady -- checks the conditions for the decryption.
*
* SYNOPSIS
* bReady = checkReady( );
*
* FUNCTION
* checks whether all following conditions are satisfied:
* 1. the result listener is ready;
* 2. the EncryptionEngine is ready.
*
* INPUTS
* empty
*
* RESULT
* bReady - true if all conditions are satisfied, false otherwise
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
return (m_xResultListener.is() && EncryptionEngine::checkReady());
}
void DecryptorImpl::notifyResultListener() const
throw (cssu::Exception, cssu::RuntimeException)
/****** DecryptorImpl/notifyResultListener ***********************************
*
* NAME
* notifyResultListener -- notifies the listener about the decryption
* result.
*
* SYNOPSIS
* notifyResultListener( );
*
* FUNCTION
* see NAME.
*
* INPUTS
* empty
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
cssu::Reference< cssxc::sax::XDecryptionResultListener >
xDecryptionResultListener ( m_xResultListener , cssu::UNO_QUERY ) ;
xDecryptionResultListener->decrypted(m_nSecurityId,m_nStatus);
}
void DecryptorImpl::startEngine( const cssu::Reference<
cssxc::XXMLEncryptionTemplate >&
xEncryptionTemplate)
throw (cssu::Exception, cssu::RuntimeException)
/****** DecryptorImpl/startEngine ********************************************
*
* NAME
* startEngine -- decrypts the encryption.
*
* SYNOPSIS
* startEngine( xEncryptionTemplate );
*
* FUNCTION
* decrypts the encryption element, then if succeeds, updates the link
* of old template element to the new encryption element in
* SAXEventKeeper.
*
* INPUTS
* xEncryptionTemplate - the encryption template to be decrypted.
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* Michael Mi
* Email: [email protected]
******************************************************************************/
{
cssu::Reference< cssxc::XXMLEncryptionTemplate > xResultTemplate;
try
{
xResultTemplate = m_xXMLEncryption->decrypt(xEncryptionTemplate, m_xXMLSecurityContext);
m_nStatus = xResultTemplate->getStatus();
}
catch( cssu::Exception& )
{
m_nStatus = cssxc::SecurityOperationStatus_RUNTIMEERROR_FAILED;
}
if (m_nStatus == cssxc::SecurityOperationStatus_OPERATION_SUCCEEDED)
{
cssu::Reference< cssxw::XXMLElementWrapper > xDecryptedElement
= xResultTemplate->getTemplate();
m_xSAXEventKeeper->setElement(m_nIdOfTemplateEC, xDecryptedElement);
}
}
/* XDecryptionResultBroadcaster */
void SAL_CALL DecryptorImpl::addDecryptionResultListener( const cssu::Reference< cssxc::sax::XDecryptionResultListener >& listener )
throw (cssu::Exception, cssu::RuntimeException)
{
m_xResultListener = listener;
tryToPerform();
}
void SAL_CALL DecryptorImpl::removeDecryptionResultListener( const cssu::Reference< cssxc::sax::XDecryptionResultListener >&)
throw (cssu::RuntimeException)
{
}
/* XInitialization */
void SAL_CALL DecryptorImpl::initialize( const cssu::Sequence< cssu::Any >& aArguments )
throw (cssu::Exception, cssu::RuntimeException)
{
OSL_ASSERT(aArguments.getLength() == 5);
rtl::OUString ouTempString;
aArguments[0] >>= ouTempString;
m_nSecurityId = ouTempString.toInt32();
aArguments[1] >>= m_xSAXEventKeeper;
aArguments[2] >>= ouTempString;
m_nIdOfTemplateEC = ouTempString.toInt32();
aArguments[3] >>= m_xXMLSecurityContext;
aArguments[4] >>= m_xXMLEncryption;
}
rtl::OUString DecryptorImpl_getImplementationName ()
throw (cssu::RuntimeException)
{
return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}
sal_Bool SAL_CALL DecryptorImpl_supportsService( const rtl::OUString& ServiceName )
throw (cssu::RuntimeException)
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}
cssu::Sequence< rtl::OUString > SAL_CALL DecryptorImpl_getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
cssu::Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
cssu::Reference< cssu::XInterface > SAL_CALL DecryptorImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory >& rSMgr)
throw( cssu::Exception )
{
return (cppu::OWeakObject*) new DecryptorImpl(rSMgr);
}
/* XServiceInfo */
rtl::OUString SAL_CALL DecryptorImpl::getImplementationName( )
throw (cssu::RuntimeException)
{
return DecryptorImpl_getImplementationName();
}
sal_Bool SAL_CALL DecryptorImpl::supportsService( const rtl::OUString& rServiceName )
throw (cssu::RuntimeException)
{
return DecryptorImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL DecryptorImpl::getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
return DecryptorImpl_getSupportedServiceNames();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/function_call.hpp>
namespace mapnik {
// functions
// exp
//template <typename T>
struct exp_impl
{
//using type = T;
value_type operator() (value_type const& val) const
{
return std::exp(val.to_double());
}
};
// sin
struct sin_impl
{
value_type operator() (value_type const& val) const
{
return std::sin(val.to_double());
}
};
// cos
struct cos_impl
{
value_type operator() (value_type const& val) const
{
return std::cos(val.to_double());
}
};
// tan
struct tan_impl
{
value_type operator() (value_type const& val) const
{
return std::tan(val.to_double());
}
};
// atan
struct atan_impl
{
value_type operator()(value_type const& val) const
{
return std::atan(val.to_double());
}
};
// abs
struct abs_impl
{
value_type operator() (value_type const& val) const
{
return std::fabs(val.to_double());
}
};
// length
struct length_impl
{
value_type operator() (value_type const& val) const
{
return val.to_unicode().length();
}
};
unary_function_types::unary_function_types()
{
add
("sin", sin_impl())
("cos", cos_impl())
("tan", tan_impl())
("atan", atan_impl())
("exp", exp_impl())
("abs", abs_impl())
("length",length_impl())
;
}
char const* unary_function_name(unary_function_impl const& fun)
{
if (fun.target<sin_impl>()) return "sin";
else if (fun.target<cos_impl>()) return "cos";
else if (fun.target<tan_impl>()) return "tan";
else if (fun.target<atan_impl>()) return "atan";
else if (fun.target<exp_impl>()) return "exp";
else if (fun.target<abs_impl>()) return "abs";
else return "unknown";
}
// binary functions
// min
inline value_type min_impl(value_type const& arg1, value_type const& arg2)
{
return std::min(arg1.to_double(), arg2.to_double());
}
// max
inline value_type max_impl(value_type const& arg1, value_type const& arg2)
{
return std::max(arg1.to_double(), arg2.to_double());
}
// pow
inline value_type pow_impl(value_type const& arg1, value_type const& arg2)
{
return std::pow(arg1.to_double(), arg2.to_double());
}
binary_function_types::binary_function_types()
{
add
("min", binary_function_impl(min_impl))
("max", binary_function_impl(max_impl))
("pow", binary_function_impl(pow_impl))
;
}
char const* binary_function_name(binary_function_impl const& fun)
{
value_type(*const* f_ptr)(value_type const&, value_type const&) =
fun.target<value_type(*)
(value_type const&, value_type const&)>();
if (f_ptr)
{
if (*f_ptr == min_impl) return "min";
else if(*f_ptr == max_impl) return "max";
else if(*f_ptr == pow_impl) return "pow";
}
return "unknown";
}
}
<commit_msg>add to string impl for length func - closes #2437<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/function_call.hpp>
namespace mapnik {
// functions
// exp
//template <typename T>
struct exp_impl
{
//using type = T;
value_type operator() (value_type const& val) const
{
return std::exp(val.to_double());
}
};
// sin
struct sin_impl
{
value_type operator() (value_type const& val) const
{
return std::sin(val.to_double());
}
};
// cos
struct cos_impl
{
value_type operator() (value_type const& val) const
{
return std::cos(val.to_double());
}
};
// tan
struct tan_impl
{
value_type operator() (value_type const& val) const
{
return std::tan(val.to_double());
}
};
// atan
struct atan_impl
{
value_type operator()(value_type const& val) const
{
return std::atan(val.to_double());
}
};
// abs
struct abs_impl
{
value_type operator() (value_type const& val) const
{
return std::fabs(val.to_double());
}
};
// length
struct length_impl
{
value_type operator() (value_type const& val) const
{
return val.to_unicode().length();
}
};
unary_function_types::unary_function_types()
{
add
("sin", sin_impl())
("cos", cos_impl())
("tan", tan_impl())
("atan", atan_impl())
("exp", exp_impl())
("abs", abs_impl())
("length",length_impl())
;
}
char const* unary_function_name(unary_function_impl const& fun)
{
if (fun.target<sin_impl>()) return "sin";
else if (fun.target<cos_impl>()) return "cos";
else if (fun.target<tan_impl>()) return "tan";
else if (fun.target<atan_impl>()) return "atan";
else if (fun.target<exp_impl>()) return "exp";
else if (fun.target<abs_impl>()) return "abs";
else if (fun.target<length_impl>()) return "length";
else return "unknown";
}
// binary functions
// min
inline value_type min_impl(value_type const& arg1, value_type const& arg2)
{
return std::min(arg1.to_double(), arg2.to_double());
}
// max
inline value_type max_impl(value_type const& arg1, value_type const& arg2)
{
return std::max(arg1.to_double(), arg2.to_double());
}
// pow
inline value_type pow_impl(value_type const& arg1, value_type const& arg2)
{
return std::pow(arg1.to_double(), arg2.to_double());
}
binary_function_types::binary_function_types()
{
add
("min", binary_function_impl(min_impl))
("max", binary_function_impl(max_impl))
("pow", binary_function_impl(pow_impl))
;
}
char const* binary_function_name(binary_function_impl const& fun)
{
value_type(*const* f_ptr)(value_type const&, value_type const&) =
fun.target<value_type(*)
(value_type const&, value_type const&)>();
if (f_ptr)
{
if (*f_ptr == min_impl) return "min";
else if(*f_ptr == max_impl) return "max";
else if(*f_ptr == pow_impl) return "pow";
}
return "unknown";
}
}
<|endoftext|> |
<commit_before>
#include "FlareTechnologyMenu.h"
#include "../../Flare.h"
#include "../Components/FlareTechnologyInfo.h"
#include "../Components/FlareTabView.h"
#include "../../Data/FlareTechnologyCatalog.h"
#include "../../Data/FlareScannableCatalog.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareCompany.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareTechnologyMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareTechnologyMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
AFlarePlayerController* PC = MenuManager->GetPC();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.Padding(FMargin(0, AFlareMenuManager::GetMainOverlayHeight(), 0, 0))
[
SNew(SFlareTabView)
// Technology block
+ SFlareTabView::Slot()
.Header(LOCTEXT("TechnologyMainTab", "Technologies"))
.HeaderHelp(LOCTEXT("TechnologyMainTabInfo", "Technology tree & research status"))
[
SNew(SBox)
.WidthOverride(2.2 * Theme.ContentWidth)
.HAlign(HAlign_Center)
.VAlign(VAlign_Fill)
[
SNew(SHorizontalBox)
// Info block
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.AutoWidth()
[
SNew(SBox)
.WidthOverride(0.75 * Theme.ContentWidth)
.HAlign(HAlign_Left)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.Text(LOCTEXT("CompanyTechnologyTitle", "Company technology"))
.TextStyle(&Theme.SubTitleFont)
]
// Company info
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(SRichTextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTechnologyMenu::GetCompanyTechnologyInfo)
.DecoratorStyleSet(&FFlareStyleSet::Get())
.WrapTextAt(0.7 * Theme.ContentWidth)
]
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.TextStyle(&Theme.SubTitleFont)
.Text(this, &SFlareTechnologyMenu::GetTechnologyName)
]
// Description
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTechnologyMenu::GetTechnologyDescription)
.WrapTextAt(0.7 * Theme.ContentWidth)
]
// Button
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(SFlareButton)
.Width(6)
.Icon(FFlareStyleSet::GetIcon("ResearchValue"))
.Text(this, &SFlareTechnologyMenu::GetTechnologyUnlockText)
.HelpText(this, &SFlareTechnologyMenu::GetTechnologyUnlockHintText)
.OnClicked(this, &SFlareTechnologyMenu::OnTechnologyUnlocked)
.IsDisabled(this, &SFlareTechnologyMenu::IsUnlockDisabled)
]
]
]
// Tree block
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Top)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.Text(LOCTEXT("AvailableTechnologyTitle", "Available technologies"))
.TextStyle(&Theme.SubTitleFont)
]
// Data
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SAssignNew(TechnologyTree, SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
]
]
]
]
// Scannable block
+ SFlareTabView::Slot()
.Header(LOCTEXT("TechnologyScannableTab", "Artifacts"))
.HeaderHelp(LOCTEXT("TechnologyScannableTabInfo", "Artifacts are found drifting in the world and unlock research data"))
[
SNew(SBox)
.WidthOverride(2.2 * Theme.ContentWidth)
.HAlign(HAlign_Center)
.VAlign(VAlign_Fill)
[
SNew(SBox)
.HAlign(HAlign_Left)
.WidthOverride(2.2 * Theme.ContentWidth)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
.HAlign(HAlign_Left)
[
SNew(STextBlock)
.Text(LOCTEXT("CompanyScannableTitle", "Artifacts found"))
.TextStyle(&Theme.SubTitleFont)
]
// Count
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(STextBlock)
.Text(this, &SFlareTechnologyMenu::GetUnlockedScannableCount)
.TextStyle(&Theme.TextFont)
.WrapTextAt(2 * Theme.ContentWidth)
]
// Content
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SAssignNew(ArtifactList, SVerticalBox)
]
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareTechnologyMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareTechnologyMenu::Enter()
{
FLOG("SFlareTechnologyMenu::Enter");
// Menu data
SetEnabled(true);
SetVisibility(EVisibility::Visible);
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
// Sorting criteria for technologies
struct FSortByLevelCategoryAndCost
{
FORCEINLINE bool operator()(const FFlareTechnologyDescription& A, const FFlareTechnologyDescription& B) const
{
if (A.Level > B.Level)
{
return true;
}
else if (A.Level < B.Level)
{
return false;
}
else if (A.Category < B.Category)
{
return true;
}
else if (A.Category > B.Category)
{
return false;
}
else
{
if (A.ResearchCost > B.ResearchCost)
{
return true;
}
else
{
return false;
}
}
}
};
// List all technologies
SelectedTechnology = NULL;
TArray<const FFlareTechnologyDescription*> Technologies;
for (auto& Entry : MenuManager->GetGame()->GetTechnologyCatalog()->TechnologyCatalog)
{
Technologies.Add(&Entry->Data);
}
Technologies.Sort(FSortByLevelCategoryAndCost());
// Add technologies to the tree
int CurrentLevel = -1;
TSharedPtr<SHorizontalBox> CurrentLevelRow;
for (const FFlareTechnologyDescription* Technology : Technologies)
{
// Add a new row
if (Technology->Level != CurrentLevel)
{
CurrentLevel = Technology->Level;
// Row
TechnologyTree->AddSlot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SAssignNew(CurrentLevelRow, SHorizontalBox)
];
// Row title
CurrentLevelRow->AddSlot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.Padding(FMargin(0, 0, 0, 10))
[
SNew(STextBlock)
.TextStyle(&Theme.TitleFont)
.Text(FText::Format(LOCTEXT("CurrentLevelFormat", "{0}"), FText::AsNumber(CurrentLevel)))
.ColorAndOpacity(this, &SFlareTechnologyMenu::GetTitleTextColor, CurrentLevel)
];
}
// Add entry to the row
CurrentLevelRow->AddSlot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SFlareTechnologyInfo)
.MenuManager(MenuManager)
.Technology(Technology)
.OnClicked(FFlareButtonClicked::CreateSP(this, &SFlareTechnologyMenu::OnTechnologySelected, Technology))
];
}
// List artifacts
ArtifactList->ClearChildren();
for (FName UnlockedScannableIdentifier : MenuManager->GetPC()->GetUnlockedScannables())
{
auto Scannable = MenuManager->GetGame()->GetScannableCatalog()->Get(UnlockedScannableIdentifier);
ArtifactList->AddSlot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
// Upper line
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(Theme.SmallContentPadding)
[
SNew(SImage)
.Image(FFlareStyleSet::GetIcon("OK"))
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(STextBlock)
.TextStyle(&Theme.NameFont)
.Text(Scannable->Name)
]
]
// Lower line
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(Scannable->Description)
.WrapTextAt(Theme.ContentWidth)
]
];
}
SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale());
}
void SFlareTechnologyMenu::Exit()
{
SetEnabled(false);
SelectedTechnology = NULL;
TechnologyTree->ClearChildren();
ArtifactList->ClearChildren();
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
bool SFlareTechnologyMenu::IsUnlockDisabled() const
{
if (SelectedTechnology)
{
FText Unused;
return !MenuManager->GetPC()->GetCompany()->IsTechnologyAvailable(SelectedTechnology->Identifier, Unused);
}
else
{
return true;
}
}
FText SFlareTechnologyMenu::GetCompanyTechnologyInfo() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
CompanyValue CompanyValue = Company->GetCompanyValue(NULL, false);
return FText::Format(LOCTEXT("TechnologyCompanyFormat", "\u2022 You can currently research technology up to <HighlightText>level {0}</>.\n\u2022 You have <HighlightText>{1} research</> left to spend in technology.\n\u2022 You have already spent {2} research."),
FText::AsNumber(Company->GetTechnologyLevel()),
FText::AsNumber(Company->GetResearchAmount()),
FText::AsNumber(Company->GetResearchSpent()));
}
FText SFlareTechnologyMenu::GetTechnologyName() const
{
if (SelectedTechnology)
{
return SelectedTechnology->Name;
}
else
{
return LOCTEXT("TechnologyDetailsTitle", "Technology details");
}
}
FText SFlareTechnologyMenu::GetTechnologyDescription() const
{
if (SelectedTechnology)
{
return SelectedTechnology->Description;
}
else
{
return LOCTEXT("NotechnologySelected", "No technology selected.");
}
}
FSlateColor SFlareTechnologyMenu::GetTitleTextColor(int32 RowLevel) const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
if (RowLevel <= Company->GetTechnologyLevel())
{
return Theme.NeutralColor;
}
else
{
return Theme.UnknownColor;
}
}
FText SFlareTechnologyMenu::GetTechnologyUnlockText() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
FText Unused;
if (SelectedTechnology && !Company->IsTechnologyAvailable(SelectedTechnology->Identifier, Unused))
{
return LOCTEXT("UnlockTechImpossible", "Can't research");
}
else
{
return LOCTEXT("UnlockTechOK", "Research technology");
}
}
FText SFlareTechnologyMenu::GetTechnologyUnlockHintText() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
FText Reason;
if (SelectedTechnology && !Company->IsTechnologyAvailable(SelectedTechnology->Identifier, Reason))
{
return Reason;
}
else
{
return LOCTEXT("UnlockTechInfo", "Research this technology by spending some of your available budget");
}
}
void SFlareTechnologyMenu::OnTechnologySelected(const FFlareTechnologyDescription* Technology)
{
SelectedTechnology = Technology;
}
void SFlareTechnologyMenu::OnTechnologyUnlocked()
{
if (SelectedTechnology)
{
MenuManager->GetPC()->GetCompany()->UnlockTechnology(SelectedTechnology->Identifier);
}
}
FText SFlareTechnologyMenu::GetUnlockedScannableCount() const
{
return FText::Format(LOCTEXT("ScannableCountFormat", "You have found {0} out of {1} artifacts. Explore the world and discover new sectors to unlock more research data !"),
FText::AsNumber(MenuManager->GetPC()->GetUnlockedScannableCount()),
FText::AsNumber(MenuManager->GetGame()->GetScannableCatalog()->ScannableCatalog.Num()));
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Add assertion<commit_after>
#include "FlareTechnologyMenu.h"
#include "../../Flare.h"
#include "../Components/FlareTechnologyInfo.h"
#include "../Components/FlareTabView.h"
#include "../../Data/FlareTechnologyCatalog.h"
#include "../../Data/FlareScannableCatalog.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareCompany.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareTechnologyMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareTechnologyMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
AFlarePlayerController* PC = MenuManager->GetPC();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.Padding(FMargin(0, AFlareMenuManager::GetMainOverlayHeight(), 0, 0))
[
SNew(SFlareTabView)
// Technology block
+ SFlareTabView::Slot()
.Header(LOCTEXT("TechnologyMainTab", "Technologies"))
.HeaderHelp(LOCTEXT("TechnologyMainTabInfo", "Technology tree & research status"))
[
SNew(SBox)
.WidthOverride(2.2 * Theme.ContentWidth)
.HAlign(HAlign_Center)
.VAlign(VAlign_Fill)
[
SNew(SHorizontalBox)
// Info block
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.AutoWidth()
[
SNew(SBox)
.WidthOverride(0.75 * Theme.ContentWidth)
.HAlign(HAlign_Left)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.Text(LOCTEXT("CompanyTechnologyTitle", "Company technology"))
.TextStyle(&Theme.SubTitleFont)
]
// Company info
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(SRichTextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTechnologyMenu::GetCompanyTechnologyInfo)
.DecoratorStyleSet(&FFlareStyleSet::Get())
.WrapTextAt(0.7 * Theme.ContentWidth)
]
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.TextStyle(&Theme.SubTitleFont)
.Text(this, &SFlareTechnologyMenu::GetTechnologyName)
]
// Description
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTechnologyMenu::GetTechnologyDescription)
.WrapTextAt(0.7 * Theme.ContentWidth)
]
// Button
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(SFlareButton)
.Width(6)
.Icon(FFlareStyleSet::GetIcon("ResearchValue"))
.Text(this, &SFlareTechnologyMenu::GetTechnologyUnlockText)
.HelpText(this, &SFlareTechnologyMenu::GetTechnologyUnlockHintText)
.OnClicked(this, &SFlareTechnologyMenu::OnTechnologyUnlocked)
.IsDisabled(this, &SFlareTechnologyMenu::IsUnlockDisabled)
]
]
]
// Tree block
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Top)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
[
SNew(STextBlock)
.Text(LOCTEXT("AvailableTechnologyTitle", "Available technologies"))
.TextStyle(&Theme.SubTitleFont)
]
// Data
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SAssignNew(TechnologyTree, SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
]
]
]
]
// Scannable block
+ SFlareTabView::Slot()
.Header(LOCTEXT("TechnologyScannableTab", "Artifacts"))
.HeaderHelp(LOCTEXT("TechnologyScannableTabInfo", "Artifacts are found drifting in the world and unlock research data"))
[
SNew(SBox)
.WidthOverride(2.2 * Theme.ContentWidth)
.HAlign(HAlign_Center)
.VAlign(VAlign_Fill)
[
SNew(SBox)
.HAlign(HAlign_Left)
.WidthOverride(2.2 * Theme.ContentWidth)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.TitlePadding)
.HAlign(HAlign_Left)
[
SNew(STextBlock)
.Text(LOCTEXT("CompanyScannableTitle", "Artifacts found"))
.TextStyle(&Theme.SubTitleFont)
]
// Count
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(STextBlock)
.Text(this, &SFlareTechnologyMenu::GetUnlockedScannableCount)
.TextStyle(&Theme.TextFont)
.WrapTextAt(2 * Theme.ContentWidth)
]
// Content
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SAssignNew(ArtifactList, SVerticalBox)
]
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareTechnologyMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareTechnologyMenu::Enter()
{
FLOG("SFlareTechnologyMenu::Enter");
// Menu data
SetEnabled(true);
SetVisibility(EVisibility::Visible);
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
// Sorting criteria for technologies
struct FSortByLevelCategoryAndCost
{
FORCEINLINE bool operator()(const FFlareTechnologyDescription& A, const FFlareTechnologyDescription& B) const
{
if (A.Level > B.Level)
{
return true;
}
else if (A.Level < B.Level)
{
return false;
}
else if (A.Category < B.Category)
{
return true;
}
else if (A.Category > B.Category)
{
return false;
}
else
{
if (A.ResearchCost > B.ResearchCost)
{
return true;
}
else
{
return false;
}
}
}
};
// List all technologies
SelectedTechnology = NULL;
TArray<const FFlareTechnologyDescription*> Technologies;
for (auto& Entry : MenuManager->GetGame()->GetTechnologyCatalog()->TechnologyCatalog)
{
Technologies.Add(&Entry->Data);
}
Technologies.Sort(FSortByLevelCategoryAndCost());
// Add technologies to the tree
int CurrentLevel = -1;
TSharedPtr<SHorizontalBox> CurrentLevelRow;
for (const FFlareTechnologyDescription* Technology : Technologies)
{
// Add a new row
if (Technology->Level != CurrentLevel)
{
CurrentLevel = Technology->Level;
// Row
TechnologyTree->AddSlot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SAssignNew(CurrentLevelRow, SHorizontalBox)
];
// Row title
CurrentLevelRow->AddSlot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.Padding(FMargin(0, 0, 0, 10))
[
SNew(STextBlock)
.TextStyle(&Theme.TitleFont)
.Text(FText::Format(LOCTEXT("CurrentLevelFormat", "{0}"), FText::AsNumber(CurrentLevel)))
.ColorAndOpacity(this, &SFlareTechnologyMenu::GetTitleTextColor, CurrentLevel)
];
}
// Add entry to the row
CurrentLevelRow->AddSlot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SFlareTechnologyInfo)
.MenuManager(MenuManager)
.Technology(Technology)
.OnClicked(FFlareButtonClicked::CreateSP(this, &SFlareTechnologyMenu::OnTechnologySelected, Technology))
];
}
// List artifacts
ArtifactList->ClearChildren();
for (FName UnlockedScannableIdentifier : MenuManager->GetPC()->GetUnlockedScannables())
{
auto Scannable = MenuManager->GetGame()->GetScannableCatalog()->Get(UnlockedScannableIdentifier);
FCHECK(Scannable);
ArtifactList->AddSlot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
// Upper line
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(Theme.SmallContentPadding)
[
SNew(SImage)
.Image(FFlareStyleSet::GetIcon("OK"))
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(STextBlock)
.TextStyle(&Theme.NameFont)
.Text(Scannable->Name)
]
]
// Lower line
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(Scannable->Description)
.WrapTextAt(Theme.ContentWidth)
]
];
}
SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale());
}
void SFlareTechnologyMenu::Exit()
{
SetEnabled(false);
SelectedTechnology = NULL;
TechnologyTree->ClearChildren();
ArtifactList->ClearChildren();
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
bool SFlareTechnologyMenu::IsUnlockDisabled() const
{
if (SelectedTechnology)
{
FText Unused;
return !MenuManager->GetPC()->GetCompany()->IsTechnologyAvailable(SelectedTechnology->Identifier, Unused);
}
else
{
return true;
}
}
FText SFlareTechnologyMenu::GetCompanyTechnologyInfo() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
CompanyValue CompanyValue = Company->GetCompanyValue(NULL, false);
return FText::Format(LOCTEXT("TechnologyCompanyFormat", "\u2022 You can currently research technology up to <HighlightText>level {0}</>.\n\u2022 You have <HighlightText>{1} research</> left to spend in technology.\n\u2022 You have already spent {2} research."),
FText::AsNumber(Company->GetTechnologyLevel()),
FText::AsNumber(Company->GetResearchAmount()),
FText::AsNumber(Company->GetResearchSpent()));
}
FText SFlareTechnologyMenu::GetTechnologyName() const
{
if (SelectedTechnology)
{
return SelectedTechnology->Name;
}
else
{
return LOCTEXT("TechnologyDetailsTitle", "Technology details");
}
}
FText SFlareTechnologyMenu::GetTechnologyDescription() const
{
if (SelectedTechnology)
{
return SelectedTechnology->Description;
}
else
{
return LOCTEXT("NotechnologySelected", "No technology selected.");
}
}
FSlateColor SFlareTechnologyMenu::GetTitleTextColor(int32 RowLevel) const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
if (RowLevel <= Company->GetTechnologyLevel())
{
return Theme.NeutralColor;
}
else
{
return Theme.UnknownColor;
}
}
FText SFlareTechnologyMenu::GetTechnologyUnlockText() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
FText Unused;
if (SelectedTechnology && !Company->IsTechnologyAvailable(SelectedTechnology->Identifier, Unused))
{
return LOCTEXT("UnlockTechImpossible", "Can't research");
}
else
{
return LOCTEXT("UnlockTechOK", "Research technology");
}
}
FText SFlareTechnologyMenu::GetTechnologyUnlockHintText() const
{
UFlareCompany* Company = MenuManager->GetPC()->GetCompany();
FText Reason;
if (SelectedTechnology && !Company->IsTechnologyAvailable(SelectedTechnology->Identifier, Reason))
{
return Reason;
}
else
{
return LOCTEXT("UnlockTechInfo", "Research this technology by spending some of your available budget");
}
}
void SFlareTechnologyMenu::OnTechnologySelected(const FFlareTechnologyDescription* Technology)
{
SelectedTechnology = Technology;
}
void SFlareTechnologyMenu::OnTechnologyUnlocked()
{
if (SelectedTechnology)
{
MenuManager->GetPC()->GetCompany()->UnlockTechnology(SelectedTechnology->Identifier);
}
}
FText SFlareTechnologyMenu::GetUnlockedScannableCount() const
{
return FText::Format(LOCTEXT("ScannableCountFormat", "You have found {0} out of {1} artifacts. Explore the world and discover new sectors to unlock more research data !"),
FText::AsNumber(MenuManager->GetPC()->GetUnlockedScannableCount()),
FText::AsNumber(MenuManager->GetGame()->GetScannableCatalog()->ScannableCatalog.Num()));
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include <gtest/gtest.h>
#include "SurgSim/Blocks/PoseInterpolator.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Representation.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/Quaternion.h"
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::interpolate;
namespace
{
RigidTransform3d startPose = makeRigidTransform(Quaterniond::Identity(), Vector3d(1.0,2.0,3.0));
RigidTransform3d endPose = makeRigidTransform(Quaterniond::Identity(), Vector3d(3.0,2.0,1.0));
}
class PoseTestRepresentation : public SurgSim::Framework::Representation
{
public:
PoseTestRepresentation(const std::string& name) : Representation(name)
{
}
virtual void setInitialPose(const SurgSim::Math::RigidTransform3d& pose)
{
m_pose = pose;
}
virtual const SurgSim::Math::RigidTransform3d& getInitialPose() const
{
return m_pose;
}
virtual void setPose(const SurgSim::Math::RigidTransform3d& pose)
{
m_pose = pose;
}
virtual const SurgSim::Math::RigidTransform3d& getPose() const
{
return m_pose;
}
private:
RigidTransform3d m_pose;
};
namespace SurgSim
{
namespace Blocks
{
TEST(PoseInterpolatorTests, InitTest)
{
ASSERT_NO_THROW({auto interpolator = std::make_shared<PoseInterpolator>("test");});
}
TEST(PoseInterpolatorTests, StartAndEndPose)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.5);
RigidTransform3d pose = interpolate(startPose, endPose, 0.5);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UseOptionalStartPose)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
representation->setInitialPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.5);
RigidTransform3d pose = interpolate(startPose, endPose, 0.5);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UseLoop)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->setPingPong(true);
interpolator->setLoop(true);
// Enabling loop should disable pingpong
EXPECT_TRUE(interpolator->isLoop());
EXPECT_FALSE(interpolator->isPingPong());
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.25);
RigidTransform3d pose = interpolate(startPose, endPose, 0.25);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
// We advance by 1.0, this should wrap around to 0.25 again and the poses should be the same
interpolator->update(1.0);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UsePingPong)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->setLoop(true);
interpolator->setPingPong(true);
// Enabling PingPong should disable Loop
EXPECT_FALSE(interpolator->isLoop());
EXPECT_TRUE(interpolator->isPingPong());
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.25);
RigidTransform3d pose = interpolate(startPose, endPose, 0.25);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
// We advance by 1.0, this should wrap around to 0.25 and the poses should be flipped
pose = interpolate(endPose, startPose, 0.25);
interpolator->update(1.0);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
}
}
<commit_msg>Add keyword 'explicit' to PoseTestRepresentation()<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include <gtest/gtest.h>
#include "SurgSim/Blocks/PoseInterpolator.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Representation.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/Quaternion.h"
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::interpolate;
namespace
{
RigidTransform3d startPose = makeRigidTransform(Quaterniond::Identity(), Vector3d(1.0, 2.0, 3.0));
RigidTransform3d endPose = makeRigidTransform(Quaterniond::Identity(), Vector3d(3.0, 2.0, 1.0));
}
class PoseTestRepresentation : public SurgSim::Framework::Representation
{
public:
explicit PoseTestRepresentation(const std::string& name) : Representation(name)
{
}
virtual void setInitialPose(const SurgSim::Math::RigidTransform3d& pose)
{
m_pose = pose;
}
virtual const SurgSim::Math::RigidTransform3d& getInitialPose() const
{
return m_pose;
}
virtual void setPose(const SurgSim::Math::RigidTransform3d& pose)
{
m_pose = pose;
}
virtual const SurgSim::Math::RigidTransform3d& getPose() const
{
return m_pose;
}
private:
RigidTransform3d m_pose;
};
namespace SurgSim
{
namespace Blocks
{
TEST(PoseInterpolatorTests, InitTest)
{
ASSERT_NO_THROW({auto interpolator = std::make_shared<PoseInterpolator>("test");});
}
TEST(PoseInterpolatorTests, StartAndEndPose)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.5);
RigidTransform3d pose = interpolate(startPose, endPose, 0.5);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UseOptionalStartPose)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
representation->setInitialPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.5);
RigidTransform3d pose = interpolate(startPose, endPose, 0.5);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UseLoop)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->setPingPong(true);
interpolator->setLoop(true);
// Enabling loop should disable pingpong
EXPECT_TRUE(interpolator->isLoop());
EXPECT_FALSE(interpolator->isPingPong());
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.25);
RigidTransform3d pose = interpolate(startPose, endPose, 0.25);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
// We advance by 1.0, this should wrap around to 0.25 again and the poses should be the same
interpolator->update(1.0);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
TEST(PoseInterpolatorTests, UsePingPong)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>();
auto representation = std::make_shared<PoseTestRepresentation>("representation");
auto interpolator = std::make_shared<PoseInterpolator>("interpolator");
interpolator->setStartingPose(startPose);
interpolator->setEndingPose(endPose);
interpolator->setTarget(representation);
interpolator->setLoop(true);
interpolator->setPingPong(true);
// Enabling PingPong should disable Loop
EXPECT_FALSE(interpolator->isLoop());
EXPECT_TRUE(interpolator->isPingPong());
interpolator->initialize(runtime);
interpolator->wakeUp();
interpolator->update(0.0);
EXPECT_TRUE(startPose.isApprox(representation->getPose()));
interpolator->update(0.25);
RigidTransform3d pose = interpolate(startPose, endPose, 0.25);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
// We advance by 1.0, this should wrap around to 0.25 and the poses should be flipped
pose = interpolate(endPose, startPose, 0.25);
interpolator->update(1.0);
EXPECT_TRUE(pose.matrix().isApprox(representation->getPose().matrix())) << pose.matrix() << std::endl
<< representation->getPose().matrix();
}
};
};
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/username_view.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "gfx/canvas.h"
#include "gfx/canvas_skia.h"
#include "gfx/rect.h"
#include "third_party/skia/include/core/SkComposeShader.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "views/background.h"
namespace {
// Username label background color.
const SkColor kLabelBackgoundColor = 0x55000000;
// Holds margin to height ratio.
const double kMarginRatio = 1.0 / 3.0;
} // namespace
namespace chromeos {
UsernameView::UsernameView(const std::wstring& username)
: views::Label(username) {
}
void UsernameView::Paint(gfx::Canvas* canvas) {
gfx::Rect bounds = GetLocalBounds(false);
if (!text_image_.get())
PaintUsername(bounds);
DCHECK(bounds.size() ==
gfx::Size(text_image_->width(), text_image_->height()));
// Only alpha channel counts.
SkColor gradient_colors[2];
gradient_colors[0] = 0xFFFFFFFF;
gradient_colors[1] = 0x00FFFFFF;
int gradient_start = std::min(margin_width_ + text_width_,
bounds.width() - bounds.height());
SkPoint gradient_borders[2];
gradient_borders[0].set(SkIntToScalar(gradient_start), SkIntToScalar(0));
gradient_borders[1].set(SkIntToScalar(
gradient_start + bounds.height()), SkIntToScalar(0));
SkShader* gradient_shader =
SkGradientShader::CreateLinear(gradient_borders, gradient_colors, NULL, 2,
SkShader::kClamp_TileMode, NULL);
SkShader* image_shader = SkShader::CreateBitmapShader(
*text_image_,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrcIn_Mode);
SkShader* composite_shader = new SkComposeShader(gradient_shader,
image_shader, mode);
gradient_shader->unref();
image_shader->unref();
SkPaint paint;
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setShader(composite_shader)->unref();
canvas->DrawRectInt(bounds.x(), bounds.y(),
bounds.width(), bounds.height(), paint);
}
void UsernameView::PaintUsername(const gfx::Rect& bounds) {
margin_width_ = bounds.height() * kMarginRatio;
gfx::CanvasSkia canvas(bounds.width(), bounds.height(), false);
// Draw background.
canvas.drawColor(kLabelBackgoundColor);
// Calculate needed space.
int flags = gfx::Canvas::TEXT_ALIGN_LEFT |
gfx::Canvas::TEXT_VALIGN_MIDDLE |
gfx::Canvas::NO_ELLIPSIS;
int text_height;
gfx::CanvasSkia::SizeStringInt(WideToUTF16Hack(GetText()), font(),
&text_width_, &text_height,
flags);
text_width_ = std::min(text_width_, bounds.width() - margin_width_);
// Draw the text.
canvas.DrawStringInt(GetText(), font(), GetColor(),
bounds.x() + margin_width_, bounds.y(),
bounds.width() - margin_width_, bounds.height(),
flags);
text_image_.reset(new SkBitmap(canvas.ExtractBitmap()));
text_image_->buildMipMap(false);
}
} // namespace chromeos
<commit_msg>Avoid green artifacts on the username label.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/username_view.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "gfx/canvas.h"
#include "gfx/canvas_skia.h"
#include "gfx/rect.h"
#include "third_party/skia/include/core/SkComposeShader.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
namespace {
// Username label background color.
const SkColor kLabelBackgoundColor = 0x55000000;
// Holds margin to height ratio.
const double kMarginRatio = 1.0 / 3.0;
} // namespace
namespace chromeos {
UsernameView::UsernameView(const std::wstring& username)
: views::Label(username) {
}
void UsernameView::Paint(gfx::Canvas* canvas) {
gfx::Rect bounds = GetLocalBounds(false);
if (!text_image_.get())
PaintUsername(bounds);
DCHECK(bounds.size() ==
gfx::Size(text_image_->width(), text_image_->height()));
// Only alpha channel counts.
SkColor gradient_colors[2];
gradient_colors[0] = 0xFFFFFFFF;
gradient_colors[1] = 0x00FFFFFF;
int gradient_start = std::min(margin_width_ + text_width_,
bounds.width() - bounds.height());
SkPoint gradient_borders[2];
gradient_borders[0].set(SkIntToScalar(gradient_start), SkIntToScalar(0));
gradient_borders[1].set(SkIntToScalar(
gradient_start + bounds.height()), SkIntToScalar(0));
SkShader* gradient_shader =
SkGradientShader::CreateLinear(gradient_borders, gradient_colors, NULL, 2,
SkShader::kClamp_TileMode, NULL);
SkShader* image_shader = SkShader::CreateBitmapShader(
*text_image_,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrcIn_Mode);
SkShader* composite_shader = new SkComposeShader(gradient_shader,
image_shader, mode);
gradient_shader->unref();
image_shader->unref();
SkPaint paint;
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setShader(composite_shader)->unref();
canvas->DrawRectInt(bounds.x(), bounds.y(),
bounds.width(), bounds.height(), paint);
}
void UsernameView::PaintUsername(const gfx::Rect& bounds) {
margin_width_ = bounds.height() * kMarginRatio;
gfx::CanvasSkia canvas(bounds.width(), bounds.height(), false);
// Draw background.
canvas.drawColor(kLabelBackgoundColor);
// Calculate needed space.
int flags = gfx::Canvas::TEXT_ALIGN_LEFT |
gfx::Canvas::TEXT_VALIGN_MIDDLE |
gfx::Canvas::NO_ELLIPSIS;
int text_height;
gfx::CanvasSkia::SizeStringInt(WideToUTF16Hack(GetText()), font(),
&text_width_, &text_height,
flags);
text_width_ = std::min(text_width_, bounds.width() - margin_width_);
// Draw the text.
// Note, direct call of the DrawStringInt method produces the green dots
// along the text perimeter (when the label is place on the white background).
SkColor kInvisibleHaloColor = 0x00000000;
canvas.DrawStringWithHalo(GetText(), font(), GetColor(), kInvisibleHaloColor,
bounds.x() + margin_width_, bounds.y(),
bounds.width() - margin_width_, bounds.height(),
flags);
text_image_.reset(new SkBitmap(canvas.ExtractBitmap()));
text_image_->buildMipMap(false);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
int main(){
unsigned int i, j, g;
int n;
string s;
bool newline = false;
while (cin >> n && n != 0){
if (newline) cout << endl;
else newline = !newline;
g = 0;
vector<string> ss;
while (n--){
cin >> s;
if (s.length() > g) g = s.length();
ss.push_back(s);
}
for (i = 0; i < ss.size(); i++){
for (j = 0; j < g - ss[i].length(); j++) cout << " ";
cout << ss[i] << endl;
}
}
return 0;
}
<commit_msg>Refatorando 1273.<commit_after>#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main(){
unsigned int i, g;
int n;
string s;
bool newline = false;
while (cin >> n && n != 0){
if (newline) cout << endl;
else newline = !newline;
g = 0;
vector<string> ss;
while (n--){
cin >> s;
if (s.length() > g) g = s.length();
ss.push_back(s);
}
for (i = 0; i < ss.size(); i++){
cout << setw(g);
cout << ss[i] << endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/debugger/devtools_window_win.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_view.h"
#include "chrome/views/window.h"
// static
DevToolsWindow* DevToolsWindow::Create(DevToolsInstanceDescriptor* descriptor) {
DevToolsView* view = new DevToolsView(descriptor);
DevToolsWindowWin* window = new DevToolsWindowWin(view);
descriptor->SetDevToolsWindow(window);
views::Window::CreateChromeWindow(NULL, gfx::Rect(), window);
return window;
}
DevToolsWindowWin::DevToolsWindowWin(DevToolsView* view)
: tools_view_(view) {
}
DevToolsWindowWin::~DevToolsWindowWin() {
DCHECK(!tools_view_);
}
void DevToolsWindowWin::Show() {
if (window()) {
window()->Show();
} else {
NOTREACHED();
}
}
void DevToolsWindowWin::Close() {
if (window()) {
window()->Close();
} else {
NOTREACHED();
}
}
std::wstring DevToolsWindowWin::GetWindowTitle() const {
return L"Developer Tools";
}
void DevToolsWindowWin::WindowClosing() {
if (tools_view_) {
ReleaseWindow();
tools_view_->OnWindowClosing();
tools_view_ = NULL;
} else {
NOTREACHED() << "WindowClosing called twice.";
}
}
bool DevToolsWindowWin::CanResize() const {
return true;
}
views::View* DevToolsWindowWin::GetContentsView() {
return tools_view_;
}
void DevToolsWindowWin::DeleteDelegate() {
DCHECK(!tools_view_) << "WindowClosing should have been called.";
delete this;
}
<commit_msg>bustage fix - file moved<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/debugger/devtools_window_win.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_view.h"
#include "chrome/views/window/window.h"
// static
DevToolsWindow* DevToolsWindow::Create(DevToolsInstanceDescriptor* descriptor) {
DevToolsView* view = new DevToolsView(descriptor);
DevToolsWindowWin* window = new DevToolsWindowWin(view);
descriptor->SetDevToolsWindow(window);
views::Window::CreateChromeWindow(NULL, gfx::Rect(), window);
return window;
}
DevToolsWindowWin::DevToolsWindowWin(DevToolsView* view)
: tools_view_(view) {
}
DevToolsWindowWin::~DevToolsWindowWin() {
DCHECK(!tools_view_);
}
void DevToolsWindowWin::Show() {
if (window()) {
window()->Show();
} else {
NOTREACHED();
}
}
void DevToolsWindowWin::Close() {
if (window()) {
window()->Close();
} else {
NOTREACHED();
}
}
std::wstring DevToolsWindowWin::GetWindowTitle() const {
return L"Developer Tools";
}
void DevToolsWindowWin::WindowClosing() {
if (tools_view_) {
ReleaseWindow();
tools_view_->OnWindowClosing();
tools_view_ = NULL;
} else {
NOTREACHED() << "WindowClosing called twice.";
}
}
bool DevToolsWindowWin::CanResize() const {
return true;
}
views::View* DevToolsWindowWin::GetContentsView() {
return tools_view_;
}
void DevToolsWindowWin::DeleteDelegate() {
DCHECK(!tools_view_) << "WindowClosing should have been called.";
delete this;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMSeriesFileNames.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkGDCMSeriesFileNames_h
#define _itkGDCMSeriesFileNames_h
#include "itkGDCMSeriesFileNames.h"
#include "gdcm/src/gdcmSerieHelper.h"
#include "gdcm/src/gdcmFile.h"
#include "gdcm/src/gdcmUtil.h"
#include <itksys/SystemTools.hxx>
#include <vector>
#include <string>
namespace itk
{
GDCMSeriesFileNames::GDCMSeriesFileNames()
{
m_SerieHelper = new gdcm::SerieHelper();
m_InputDirectory = "";
m_OutputDirectory = "";
m_UseSeriesDetails = true;
}
GDCMSeriesFileNames::~GDCMSeriesFileNames()
{
delete m_SerieHelper;
}
void GDCMSeriesFileNames::SetInputDirectory (std::string const &name)
{
if ( name == "" )
{
itkWarningMacro( << "You need to specify a directory where "
"the DICOM files are located");
return;
}
m_InputDirectory = name;
m_SerieHelper->SetUseSeriesDetails( m_UseSeriesDetails );
m_SerieHelper->SetDirectory( name ); //as a side effect it also execute
this->Modified();
}
const SerieUIDContainer &GDCMSeriesFileNames::GetSeriesUIDs()
{
m_SeriesUIDs.clear();
// Accessing the first serie found (assume there is at least one)
gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList();
while(flist)
{
if( flist->size() ) //make sure we have at leat one serie
{
gdcm::File *file = (*flist)[0]; //for example take the first one
// Create its unique series ID
std::string id = m_SerieHelper->
CreateUniqueSeriesIdentifier( file ).c_str();
m_SeriesUIDs.push_back( id.c_str() );
}
flist = m_SerieHelper->GetNextCoherentFileList();
}
if( !m_SeriesUIDs.size() )
{
itkWarningMacro(<<"No Series were found");
}
return m_SeriesUIDs;
}
const FilenamesContainer &GDCMSeriesFileNames::GetFileNames(const std::string serie)
{
m_InputFileNames.clear();
// Accessing the first serie found (assume there is at least one)
gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList();
bool found = false;
if( serie != "" ) // user did not specify any sub selcection based on UID
{
while(flist && !found)
{
if( flist->size() ) //make sure we have at leat one serie
{
gdcm::File *file = (*flist)[0]; //for example take the first one
std::string id = m_SerieHelper->
CreateUniqueSeriesIdentifier( file ).c_str();
if( id == serie )
{
found = true; // we found a match
break;
}
}
flist = m_SerieHelper->GetNextCoherentFileList();
}
if( !found)
{
itkWarningMacro(<<"No Series were found");
return m_InputFileNames;
}
}
m_SerieHelper->OrderGdcmFileList(flist);
gdcm::GdcmFileList::iterator it;
if( flist->size() )
{
for(it = flist->begin();
it != flist->end(); ++it )
{
gdcm::File * header = *it;
if( !header )
{
itkWarningMacro( << "GDCMSeriesFileNames got NULL header, "
"this is a serious bug" );
continue;
}
if( !header->IsReadable() )
{
itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:"
<< header->GetFileName() );
continue;
}
m_InputFileNames.push_back( header->GetFileName() );
}
}
else
{
itkDebugMacro(<<"No files were found");
}
return m_InputFileNames;
}
const FilenamesContainer &GDCMSeriesFileNames::GetInputFileNames()
{
// Do not specify any UID
return GetFileNames("");
}
const FilenamesContainer &GDCMSeriesFileNames::GetOutputFileNames()
{
// We are trying to extract the original filename and compose it with a path:
//There are two different approachs if directory does not exist:
// 1. Exit
// 2. Mkdir
//bool SystemTools::FileExists(const char* filename)
//bool SystemTools::FileIsDirectory(const char* name)
m_OutputFileNames.clear();
if( m_OutputDirectory.empty() )
{
itkDebugMacro(<<"No output directory was specified");
return m_OutputFileNames;
}
itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory );
if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/')
{
m_OutputDirectory += '/';
}
if( m_InputFileNames.size() )
{
bool hasExtension = false;
for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin();
it != m_InputFileNames.end(); ++it )
{
// look for extension ".dcm" and ".DCM"
std::string::size_type dcmPos = (*it).rfind(".dcm");
if ( (dcmPos != std::string::npos)
&& (dcmPos == (*it).length() - 4) )
{
hasExtension = true;
}
else
{
dcmPos = (*it).rfind(".DCM");
if ( (dcmPos != std::string::npos)
&& (dcmPos == (*it).length() - 4) )
{
hasExtension = true;
}
}
// look for extension ".dicom" and ".DICOM"
std::string::size_type dicomPos = (*it).rfind(".dicom");
if ( (dicomPos != std::string::npos)
&& (dicomPos == (*it).length() - 6) )
{
hasExtension = true;
}
else
{
dicomPos = (*it).rfind(".DICOM");
if ( (dicomPos != std::string::npos)
&& (dicomPos == (*it).length() - 6) )
{
hasExtension = true;
}
}
// construct a filename, adding an extension if necessary
std::string filename;
if (hasExtension)
{
filename =
m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it );
}
else
{
// input filename has no extension, add a ".dcm"
filename =
m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it )
+ ".dcm";
}
// Add the file name to the output list
m_OutputFileNames.push_back( filename );
}
}
else
{
itkDebugMacro(<<"No files were found.");
}
return m_OutputFileNames;
}
void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
unsigned int i;
os << indent << "InputDirectory: " << m_InputDirectory << std::endl;
for (i = 0; i < m_InputFileNames.size(); i++)
{
os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl;
}
os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl;
for (i = 0; i < m_OutputFileNames.size(); i++)
{
os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl;
}
}
} //namespace ITK
#endif
<commit_msg>BUG: If too many restrictions we could not even be able to construct one single serie<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMSeriesFileNames.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkGDCMSeriesFileNames_h
#define _itkGDCMSeriesFileNames_h
#include "itkGDCMSeriesFileNames.h"
#include "gdcm/src/gdcmSerieHelper.h"
#include "gdcm/src/gdcmFile.h"
#include "gdcm/src/gdcmUtil.h"
#include <itksys/SystemTools.hxx>
#include <vector>
#include <string>
namespace itk
{
GDCMSeriesFileNames::GDCMSeriesFileNames()
{
m_SerieHelper = new gdcm::SerieHelper();
m_InputDirectory = "";
m_OutputDirectory = "";
m_UseSeriesDetails = true;
}
GDCMSeriesFileNames::~GDCMSeriesFileNames()
{
delete m_SerieHelper;
}
void GDCMSeriesFileNames::SetInputDirectory (std::string const &name)
{
if ( name == "" )
{
itkWarningMacro( << "You need to specify a directory where "
"the DICOM files are located");
return;
}
m_InputDirectory = name;
m_SerieHelper->SetUseSeriesDetails( m_UseSeriesDetails );
m_SerieHelper->SetDirectory( name ); //as a side effect it also execute
this->Modified();
}
const SerieUIDContainer &GDCMSeriesFileNames::GetSeriesUIDs()
{
m_SeriesUIDs.clear();
// Accessing the first serie found (assume there is at least one)
gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList();
while(flist)
{
if( flist->size() ) //make sure we have at leat one serie
{
gdcm::File *file = (*flist)[0]; //for example take the first one
// Create its unique series ID
std::string id = m_SerieHelper->
CreateUniqueSeriesIdentifier( file ).c_str();
m_SeriesUIDs.push_back( id.c_str() );
}
flist = m_SerieHelper->GetNextCoherentFileList();
}
if( !m_SeriesUIDs.size() )
{
itkWarningMacro(<<"No Series were found");
}
return m_SeriesUIDs;
}
const FilenamesContainer &GDCMSeriesFileNames::GetFileNames(const std::string serie)
{
m_InputFileNames.clear();
// Accessing the first serie found (assume there is at least one)
gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList();
if( !flist )
{
itkWarningMacro(<<"No Series can be found, make sure you restiction are not too strong");
return m_InputFileNames;
}
if( serie != "" ) // user did not specify any sub selcection based on UID
{
bool found = false;
while(flist && !found)
{
if( flist->size() ) //make sure we have at leat one serie
{
gdcm::File *file = (*flist)[0]; //for example take the first one
std::string id = m_SerieHelper->
CreateUniqueSeriesIdentifier( file ).c_str();
if( id == serie )
{
found = true; // we found a match
break;
}
}
flist = m_SerieHelper->GetNextCoherentFileList();
}
if( !found)
{
itkWarningMacro(<<"No Series were found");
return m_InputFileNames;
}
}
m_SerieHelper->OrderGdcmFileList(flist);
gdcm::GdcmFileList::iterator it;
if( flist->size() )
{
for(it = flist->begin();
it != flist->end(); ++it )
{
gdcm::File * header = *it;
if( !header )
{
itkWarningMacro( << "GDCMSeriesFileNames got NULL header, "
"this is a serious bug" );
continue;
}
if( !header->IsReadable() )
{
itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:"
<< header->GetFileName() );
continue;
}
m_InputFileNames.push_back( header->GetFileName() );
}
}
else
{
itkDebugMacro(<<"No files were found");
}
return m_InputFileNames;
}
const FilenamesContainer &GDCMSeriesFileNames::GetInputFileNames()
{
// Do not specify any UID
return GetFileNames("");
}
const FilenamesContainer &GDCMSeriesFileNames::GetOutputFileNames()
{
// We are trying to extract the original filename and compose it with a path:
//There are two different approachs if directory does not exist:
// 1. Exit
// 2. Mkdir
//bool SystemTools::FileExists(const char* filename)
//bool SystemTools::FileIsDirectory(const char* name)
m_OutputFileNames.clear();
if( m_OutputDirectory.empty() )
{
itkDebugMacro(<<"No output directory was specified");
return m_OutputFileNames;
}
itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory );
if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/')
{
m_OutputDirectory += '/';
}
if( m_InputFileNames.size() )
{
bool hasExtension = false;
for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin();
it != m_InputFileNames.end(); ++it )
{
// look for extension ".dcm" and ".DCM"
std::string::size_type dcmPos = (*it).rfind(".dcm");
if ( (dcmPos != std::string::npos)
&& (dcmPos == (*it).length() - 4) )
{
hasExtension = true;
}
else
{
dcmPos = (*it).rfind(".DCM");
if ( (dcmPos != std::string::npos)
&& (dcmPos == (*it).length() - 4) )
{
hasExtension = true;
}
}
// look for extension ".dicom" and ".DICOM"
std::string::size_type dicomPos = (*it).rfind(".dicom");
if ( (dicomPos != std::string::npos)
&& (dicomPos == (*it).length() - 6) )
{
hasExtension = true;
}
else
{
dicomPos = (*it).rfind(".DICOM");
if ( (dicomPos != std::string::npos)
&& (dicomPos == (*it).length() - 6) )
{
hasExtension = true;
}
}
// construct a filename, adding an extension if necessary
std::string filename;
if (hasExtension)
{
filename =
m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it );
}
else
{
// input filename has no extension, add a ".dcm"
filename =
m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it )
+ ".dcm";
}
// Add the file name to the output list
m_OutputFileNames.push_back( filename );
}
}
else
{
itkDebugMacro(<<"No files were found.");
}
return m_OutputFileNames;
}
void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
unsigned int i;
os << indent << "InputDirectory: " << m_InputDirectory << std::endl;
for (i = 0; i < m_InputFileNames.size(); i++)
{
os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl;
}
os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl;
for (i = 0; i < m_OutputFileNames.size(); i++)
{
os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl;
}
}
} //namespace ITK
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __otbGlWidget_cxx
#define __otbGlWidget_cxx
#include "otbGlWidget.h"
namespace otb
{
GlWidget
::GlWidget() : Fl_Gl_Window(0,0,0,0), m_Identifier(), m_UseGlAcceleration(false),
m_BackgroundColor()
{
m_Identifier = "Default";
#ifdef OTB_GL_USE_ACCEL
m_UseGlAcceleration = true;
#endif
// Default background color
m_BackgroundColor.Fill(0);
}
GlWidget::~GlWidget()
{}
void GlWidget::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call the superclass implementation
Superclass::PrintSelf(os,indent);
// Display information about the widget
os<<indent<<"Widget "<<m_Identifier<<": "<<std::endl;
#ifndef OTB_GL_USE_ACCEL
os<<indent<<indent<<"OpenGl acceleration is not allowed."<<std::endl;
#else
if(m_UseGlAcceleration)
{
os<<indent<<indent<<"OpenGl acceleration is allowed and enabled."<<std::endl;
}
else
{
os<<indent<<indent<<"OpenGl acceleration is allowed but disabled."<<std::endl;
}
#endif
}
void GlWidget::draw()
{
// Check if Gl acceleration mode is correct
#ifndef OTB_GL_USE_ACCEL
if(m_UseGlAcceleration)
{
itkWarningMacro(<<"Gl acceleration enabled but not allowed. Consider rebuilding with OTB_USE_GL_ACCEL to ON. For now, disabling Gl acceleration.");
m_UseGlAcceleration=false;
}
#endif
// Set up Gl environement
if (!this->valid())
{
valid(1);
glLoadIdentity();
glViewport(0,0,w(),h());
glClearColor(m_BackgroundColor[0],m_BackgroundColor[1], m_BackgroundColor[2],m_BackgroundColor[3]);
glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black
glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
this->ortho();
glDisable(GL_BLEND);
}
void GlWidget::resize(int x, int y, int w, int h)
{
// Distinguish between resize, move and not changed events
// (The system window manager may generate multiple resizing events,
// so we'd rather avoid event flooding here)
bool reportMove = false;
bool reportResize = false;
if(this->x() != x || this->y() != y)
{
reportMove = true;
}
if(this->w() != w || this->h() != h)
{
reportResize = true;
}
// First call the superclass implementation
Fl_Gl_Window::resize(x,y,w,h);
// If There is a controller
if(m_Controller.IsNotNull())
{
if(reportMove)
{
m_Controller->HandleWidgetMove(m_Identifier,x,y);
}
if(reportResize)
{
m_Controller->HandleWidgetResize(m_Identifier,w,h);
}
}
}
int GlWidget::handle(int event)
{
// If there is a controller
if(m_Controller.IsNotNull())
{
return m_Controller->HandleWidgetEvent(m_Identifier,event);
}
else
{
return 0;
}
}
GlWidget::PointType GlWidget::GetMousePosition()
{
// Get the cursor position
PointType index;
index[0] = Fl::event_x();
index[1] = Fl::event_y();
// Flip the y axis
index[1]= this->h()-index[1];
return index;
}
}
#endif
<commit_msg>BUG: Fl_Widget destructor generates one last FL_HIDE event which causes segmentation fault (maybe because the object is already in its desctruction process). Therefore we should avoid to process FL_HIDE events.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __otbGlWidget_cxx
#define __otbGlWidget_cxx
#include "otbGlWidget.h"
namespace otb
{
GlWidget
::GlWidget() : Fl_Gl_Window(0,0,0,0), m_Identifier(), m_UseGlAcceleration(false),
m_BackgroundColor()
{
m_Identifier = "Default";
#ifdef OTB_GL_USE_ACCEL
m_UseGlAcceleration = true;
#endif
// Default background color
m_BackgroundColor.Fill(0);
}
GlWidget::~GlWidget()
{
// Clear registered controller
m_Controller = NULL;
}
void GlWidget::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call the superclass implementation
Superclass::PrintSelf(os,indent);
// Display information about the widget
os<<indent<<"Widget "<<m_Identifier<<": "<<std::endl;
#ifndef OTB_GL_USE_ACCEL
os<<indent<<indent<<"OpenGl acceleration is not allowed."<<std::endl;
#else
if(m_UseGlAcceleration)
{
os<<indent<<indent<<"OpenGl acceleration is allowed and enabled."<<std::endl;
}
else
{
os<<indent<<indent<<"OpenGl acceleration is allowed but disabled."<<std::endl;
}
#endif
}
void GlWidget::draw()
{
// Check if Gl acceleration mode is correct
#ifndef OTB_GL_USE_ACCEL
if(m_UseGlAcceleration)
{
itkWarningMacro(<<"Gl acceleration enabled but not allowed. Consider rebuilding with OTB_USE_GL_ACCEL to ON. For now, disabling Gl acceleration.");
m_UseGlAcceleration=false;
}
#endif
// Set up Gl environement
if (!this->valid())
{
valid(1);
glLoadIdentity();
glViewport(0,0,w(),h());
glClearColor(m_BackgroundColor[0],m_BackgroundColor[1], m_BackgroundColor[2],m_BackgroundColor[3]);
glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black
glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
this->ortho();
glDisable(GL_BLEND);
}
void GlWidget::resize(int x, int y, int w, int h)
{
// Distinguish between resize, move and not changed events
// (The system window manager may generate multiple resizing events,
// so we'd rather avoid event flooding here)
bool reportMove = false;
bool reportResize = false;
if(this->x() != x || this->y() != y)
{
reportMove = true;
}
if(this->w() != w || this->h() != h)
{
reportResize = true;
}
// First call the superclass implementation
Fl_Gl_Window::resize(x,y,w,h);
// If There is a controller
if(m_Controller.IsNotNull())
{
if(reportMove)
{
m_Controller->HandleWidgetMove(m_Identifier,x,y);
}
if(reportResize)
{
m_Controller->HandleWidgetResize(m_Identifier,w,h);
}
}
}
int GlWidget::handle(int event)
{
// Call superclass implementation
int resp = Fl_Widget::handle(event);
// Check if there is a controller
// Avoid processing hide events, since it causes segfault (the
// destructor of the Fl class generates hide events).
if(m_Controller.IsNotNull() && event != FL_HIDE)
{
resp = m_Controller->HandleWidgetEvent(m_Identifier,event);
}
return resp;
}
GlWidget::PointType GlWidget::GetMousePosition()
{
// Get the cursor position
PointType index;
index[0] = Fl::event_x();
index[1] = Fl::event_y();
// Flip the y axis
index[1]= this->h()-index[1];
return index;
}
}
#endif
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2016 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "CFocus.h"
#include "../nodes/NodeReviews.h"
#include "../nodes/ReviewComment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/model/AllTreeManagers.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/overlays/HighlightOverlay.h"
#include "../CodeReviewManager.h"
#include "../overlays/CodeReviewCommentOverlay.h"
using namespace Visualization;
namespace CodeReview {
int CFocus::currentStep_{0};
CFocus::CFocus() : Command{"focus"} {}
QHash<int, CFocus::FocusInformation> CFocus::focusList_;
bool CFocus::canInterpret(Visualization::Item*, Visualization::Item*,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
if (commandTokens.size() > 0)
return name() == commandTokens.first();
return false;
}
Interaction::CommandResult* CFocus::execute(Visualization::Item*, Visualization::Item*,
const QStringList&, const std::unique_ptr<Visualization::Cursor>&)
{
focusStep({}, {}, {});
return new Interaction::CommandResult{};
}
bool CFocus::focusStep(Visualization::Item *, QKeySequence, Interaction::ActionRegistry::InputState)
{
Visualization::VisualizationManager::instance().mainScene()->removeOverlayGroup("focusOverlay");
auto focusInformations = focusList_.values(currentStep_);
if (focusInformations.isEmpty()){
currentStep_ = 0;
focusInformations = focusList_.values(currentStep_);
}
if (focusInformations.isEmpty())
return false;
for (auto focusInformation : focusInformations)
{
auto focusItem = CodeReviewManager::instance().overlayForNodeReviews(focusInformation.node_);
if (focusInformation.type_.testFlag(FocusInformation::Center))
{
Visualization::VisualizationManager::instance().mainView()->centerOn(focusItem);
}
if (focusInformation.type_.testFlag(FocusInformation::Highlight))
{
auto overlay = new Visualization::HighlightOverlay{focusItem,
Visualization::HighlightOverlay::itemStyles().get("focus")};
focusItem->addOverlay(overlay, "focusOverlay");
}
}
currentStep_++;
return true;
}
QList<Interaction::CommandSuggestion*> CFocus::suggest(Visualization::Item*, Visualization::Item*,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
if (name().startsWith(textSoFar))
return {new Interaction::CommandSuggestion{name()}};
return {};
}
CFocus::FocusInformation CFocus::extractFocusInformation(QString line)
{
QStringList commandTokens = line.split(" ");
FocusInformation focusInformation;
while (!commandTokens.isEmpty())
{
auto token = commandTokens.takeFirst();
if (QString{"highlight"}.startsWith(token))
focusInformation.type_ |= FocusInformation::FocusType::Highlight;
else if (QString{"center"}.startsWith(token))
focusInformation.type_ |= FocusInformation::FocusType::Center;
else
{
bool isNumber;
auto step = token.toInt(&isNumber);
if (isNumber)
{
focusInformation.step_ = step;
break;
}
}
}
return focusInformation;
}
void CFocus::loadFocusInformation()
{
for (NodeReviews* nodeReviews : *CodeReviewManager::instance().nodeReviewsList())
{
auto focusInformation = extractFocusInformation(nodeReviews->focusInformation());
if (!focusInformation.type_.testFlag(FocusInformation::None))
{
focusInformation.node_ = nodeReviews;
focusList_.insertMulti(focusInformation.step_, focusInformation);
}
}
}
}
<commit_msg>Use target in focusStep to get the scene<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2016 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "CFocus.h"
#include "../nodes/NodeReviews.h"
#include "../nodes/ReviewComment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/model/AllTreeManagers.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/overlays/HighlightOverlay.h"
#include "../CodeReviewManager.h"
#include "../overlays/CodeReviewCommentOverlay.h"
using namespace Visualization;
namespace CodeReview {
int CFocus::currentStep_{0};
CFocus::CFocus() : Command{"focus"} {}
QHash<int, CFocus::FocusInformation> CFocus::focusList_;
bool CFocus::canInterpret(Visualization::Item*, Visualization::Item*,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
if (commandTokens.size() > 0)
return name() == commandTokens.first();
return false;
}
Interaction::CommandResult* CFocus::execute(Visualization::Item* source, Visualization::Item*,
const QStringList&, const std::unique_ptr<Visualization::Cursor>&)
{
focusStep(source, {}, {});
return new Interaction::CommandResult{};
}
bool CFocus::focusStep(Visualization::Item* target, QKeySequence, Interaction::ActionRegistry::InputState)
{
target->scene()->removeOverlayGroup("focusOverlay");
auto focusInformations = focusList_.values(currentStep_);
if (focusInformations.isEmpty()){
currentStep_ = 0;
focusInformations = focusList_.values(currentStep_);
}
if (focusInformations.isEmpty())
return false;
for (auto focusInformation : focusInformations)
{
auto focusItem = CodeReviewManager::instance().overlayForNodeReviews(focusInformation.node_);
if (focusInformation.type_.testFlag(FocusInformation::Center))
{
Visualization::VisualizationManager::instance().mainView()->centerOn(focusItem);
}
if (focusInformation.type_.testFlag(FocusInformation::Highlight))
{
auto overlay = new Visualization::HighlightOverlay{focusItem,
Visualization::HighlightOverlay::itemStyles().get("focus")};
focusItem->addOverlay(overlay, "focusOverlay");
}
}
currentStep_++;
return true;
}
QList<Interaction::CommandSuggestion*> CFocus::suggest(Visualization::Item*, Visualization::Item*,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
if (name().startsWith(textSoFar))
return {new Interaction::CommandSuggestion{name()}};
return {};
}
CFocus::FocusInformation CFocus::extractFocusInformation(QString line)
{
QStringList commandTokens = line.split(" ");
FocusInformation focusInformation;
while (!commandTokens.isEmpty())
{
auto token = commandTokens.takeFirst();
if (QString{"highlight"}.startsWith(token))
focusInformation.type_ |= FocusInformation::FocusType::Highlight;
else if (QString{"center"}.startsWith(token))
focusInformation.type_ |= FocusInformation::FocusType::Center;
else
{
bool isNumber;
auto step = token.toInt(&isNumber);
if (isNumber)
{
focusInformation.step_ = step;
break;
}
}
}
return focusInformation;
}
void CFocus::loadFocusInformation()
{
for (NodeReviews* nodeReviews : *CodeReviewManager::instance().nodeReviewsList())
{
auto focusInformation = extractFocusInformation(nodeReviews->focusInformation());
if (!focusInformation.type_.testFlag(FocusInformation::None))
{
focusInformation.node_ = nodeReviews;
focusList_.insertMulti(focusInformation.step_, focusInformation);
}
}
}
}
<|endoftext|> |
<commit_before>
#include "CommonSingleFileTesting.hpp"
#include "UseUnaryOperator/UseUnaryOperator.h"
#include "UseUnaryOperator/UseUnaryOperatorActions.h"
#include "UseUnaryOperator/UseUnaryOperatorMatchers.h"
namespace {
class MatcherProvider {
protected:
auto makeMatcher(){
return makeUseUnaryOperatorMatcher();
}
};
typedef Fixture<UseUnaryOperatorFixer,UseUnaryOperatorTransform,MatcherProvider> LocalFixture;
}
TEST( UseUnaryOperatorTest, PlusEqualToPrefixPlusPlus ) {
// input for the transformation
std::string cpp_input =
"void fun() {\n"
" a += 1;\n"
"}\n"
;
// the text that i expect to get after the transformation
std::string cpp_output =
"void fun() {\n"
" ++a;\n"
"}\n"
;
LocalFixture Test(cpp_input,cpp_output);
}
<commit_msg>forgot to declare a variable in the tests<commit_after>
#include "CommonSingleFileTesting.hpp"
#include "UseUnaryOperator/UseUnaryOperator.h"
#include "UseUnaryOperator/UseUnaryOperatorActions.h"
#include "UseUnaryOperator/UseUnaryOperatorMatchers.h"
namespace {
class MatcherProvider {
protected:
auto makeMatcher(){
return makeUseUnaryOperatorMatcher();
}
};
typedef Fixture<UseUnaryOperatorFixer,UseUnaryOperatorTransform,MatcherProvider> LocalFixture;
}
TEST( UseUnaryOperatorTest, PlusEqualToPrefixPlusPlus ) {
// input for the transformation
std::string cpp_input =
"void fun() {\n"
" int a = 0;\n"
" a += 1;\n"
"}\n"
;
// the text that i expect to get after the transformation
std::string cpp_output =
"void fun() {\n"
" int a = 0;\n"
" ++a;\n"
"}\n"
;
LocalFixture Test(cpp_input,cpp_output);
}
<|endoftext|> |
<commit_before>#include "xalt_obfuscate.h"
#include "xalt_syshost.h"
#include "xalt_config.h"
#include "xalt_regex.h"
#include "xalt_version.h"
#include <iostream>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "epoch.h"
#include "Json.h"
const int dateSZ=100;
void displayArray(const char *name, int n, const char **A)
{
std::cout << "*----------------------*\n";
std::cout << " Array: " << name << "\n";
std::cout << "*----------------------*\n";
for (int i = 0; i < n; ++i)
std::cout << std::setw(4) << i << ": " << A[i] << "\n";
std::cout << "\n";
}
int main(int argc, char* argv[])
{
std::string syshost(xalt_syshost());
std::string syslog_tag("XALT_LOGGING_");
syslog_tag.append(syshost);
char dateStr[dateSZ];
time_t now = (time_t) epoch();
strftime(dateStr,dateSZ, "%c", localtime(&now));
const char* transmission = getenv("XALT_TRANSMISSION_STYLE");
if (transmission == NULL)
transmission = TRANSMISSION;
const char* computeSHA1 = getenv("XALT_COMPUTE_SHA1");
if (computeSHA1 == NULL)
computeSHA1 = XALT_COMPUTE_SHA1;
const char* enable_backgrounding = getenv("XALT_ENABLE_BACKGROUNDING");
if (enable_backgrounding == NULL)
enable_backgrounding = XALT_ENABLE_BACKGROUNDING;
const char* xalt_etc_dir = getenv("XALT_ETC_DIR");
if (xalt_etc_dir == NULL)
xalt_etc_dir = XALT_ETC_DIR;
const char* xalt_tracking_mpi_only = getenv("XALT_TRACKING_MPI_ONLY");
if (xalt_tracking_mpi_only == NULL)
xalt_tracking_mpi_only = XALT_TRACKING_MPI_ONLY;
if (argc == 2 && strcmp(argv[1],"--json") == 0)
{
Json json;
json.add("DATE", dateStr);
json.add("XALT_SYSHOST", syshost);
json.add("XALT_VERSION", XALT_VERSION);
json.add("XALT_GIT_VERSION", XALT_GIT_VERSION);
json.add("XALT_VERSION_STR", XALT_VERSION_STR);
json.add("XALT_FILE_PREFIX", XALT_FILE_PREFIX);
json.add("XALT_ENABLE_BACKGROUNDING", enable_backgrounding);
json.add("XALT_TRANSMISSION_STYLE", transmission);
if (strcmp(transmission,"syslog") == 0)
json.add("XALT_LOGGING_TAG", syslog_tag);
json.add("XALT_COMPUTE_SHA1", computeSHA1);
json.add("XALT_ETC_DIR", xalt_etc_dir);
json.add("XALT_CONFIG_PY", XALT_CONFIG_PY);
json.add("XALT_SYSTEM_PATH", XALT_SYSTEM_PATH);
json.add("XALT_SYSHOST_CONFIG", SYSHOST_CONFIG);
json.add("XALT_TRACKING_MPI_ONLY", xalt_tracking_mpi_only);
json.add("XALT_SYSLOG_MSG_SZ", SYSLOG_MSG_SZ);
json.add("HAVE_32BIT", HAVE_32BIT);
json.add("USING_LIBUUID", HAVE_WORKING_LIBUUID);
json.add("BUILT_W_MySQL", BUILT_W_MySQL);
json.add("hostnameA", hostnameSz, hostnameA);
json.add("pathPatternA", pathPatternSz, pathPatternA);
json.add("envPatternA", envPatternSz, envPatternA);
json.fini();
std::string jsonStr = json.result();
std::cout << jsonStr << std::endl;
return 0;
}
std::cout << "*------------------------------------------------------------------------------*\n";
std::cout << " XALT Configuration Report\n";
std::cout << "*------------------------------------------------------------------------------*\n\n";
std::cout << "Today's DATE: " << dateStr << "\n";
std::cout << "XALT_VERSION: " << XALT_VERSION << "\n";
std::cout << "XALT_GIT_VERSION: " << XALT_GIT_VERSION << "\n";
std::cout << "XALT_VERSION_STR: " << XALT_VERSION_STR << "\n";
std::cout << "*------------------------------------------------------------------------------*\n";
std::cout << "XALT_SYSHOST: " << syshost << "\n";
std::cout << "XALT_FILE_PREFIX: " << XALT_FILE_PREFIX << "\n";
std::cout << "XALT_TRANSMISSION_STYLE: " << transmission << "\n";
if (strcmp(transmission,"syslog") == 0)
std::cout << "XALT_LOGGING_TAG: " << syslog_tag << "\n";
std::cout << "XALT_COMPUTE_SHA1: " << computeSHA1 << "\n";
std::cout << "XALT_ENABLE_BACKGROUNDING: " << enable_backgrounding << "\n";
std::cout << "XALT_ETC_DIR: " << xalt_etc_dir << "\n";
std::cout << "XALT_CONFIG_PY: " << XALT_CONFIG_PY << "\n";
std::cout << "XALT_TRACKING_MPI_ONLY: " << xalt_tracking_mpi_only << "\n";
std::cout << "XALT_SYSTEM_PATH: " << XALT_SYSTEM_PATH << "\n";
std::cout << "XALT_SYSHOST_CONFIG: " << SYSHOST_CONFIG << "\n";
std::cout << "XALT_SYSLOG_MSG_SZ: " << SYSLOG_MSG_SZ << "\n";
std::cout << "HAVE_32BIT: " << HAVE_32BIT << "\n";
std::cout << "Using libuuid: " << HAVE_WORKING_LIBUUID << "\n";
std::cout << "Built with MySQL: " << BUILT_W_MySQL << "\n";
std::cout << "*------------------------------------------------------------------------------*\n\n";
displayArray("hostnameA", hostnameSz, hostnameA);
std::cout << "\nRemember that \"SPSR\" means a scalar program that creates a start record\n";
displayArray("pathPatternA", pathPatternSz, pathPatternA);
displayArray("envPatternA", envPatternSz, envPatternA);
return 0;
}
<commit_msg>better alignment for xalt_configuration report<commit_after>#include "xalt_obfuscate.h"
#include "xalt_syshost.h"
#include "xalt_config.h"
#include "xalt_regex.h"
#include "xalt_version.h"
#include <iostream>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "epoch.h"
#include "Json.h"
const int dateSZ=100;
void displayArray(const char *name, int n, const char **A)
{
std::cout << "*----------------------*\n";
std::cout << " Array: " << name << "\n";
std::cout << "*----------------------*\n";
for (int i = 0; i < n; ++i)
std::cout << std::setw(4) << i << ": " << A[i] << "\n";
std::cout << "\n";
}
int main(int argc, char* argv[])
{
std::string syshost(xalt_syshost());
std::string syslog_tag("XALT_LOGGING_");
syslog_tag.append(syshost);
char dateStr[dateSZ];
time_t now = (time_t) epoch();
strftime(dateStr,dateSZ, "%c", localtime(&now));
const char* transmission = getenv("XALT_TRANSMISSION_STYLE");
if (transmission == NULL)
transmission = TRANSMISSION;
const char* computeSHA1 = getenv("XALT_COMPUTE_SHA1");
if (computeSHA1 == NULL)
computeSHA1 = XALT_COMPUTE_SHA1;
const char* enable_backgrounding = getenv("XALT_ENABLE_BACKGROUNDING");
if (enable_backgrounding == NULL)
enable_backgrounding = XALT_ENABLE_BACKGROUNDING;
const char* xalt_etc_dir = getenv("XALT_ETC_DIR");
if (xalt_etc_dir == NULL)
xalt_etc_dir = XALT_ETC_DIR;
const char* xalt_tracking_mpi_only = getenv("XALT_TRACKING_MPI_ONLY");
if (xalt_tracking_mpi_only == NULL)
xalt_tracking_mpi_only = XALT_TRACKING_MPI_ONLY;
if (argc == 2 && strcmp(argv[1],"--json") == 0)
{
Json json;
json.add("DATE", dateStr);
json.add("XALT_SYSHOST", syshost);
json.add("XALT_VERSION", XALT_VERSION);
json.add("XALT_GIT_VERSION", XALT_GIT_VERSION);
json.add("XALT_VERSION_STR", XALT_VERSION_STR);
json.add("XALT_FILE_PREFIX", XALT_FILE_PREFIX);
json.add("XALT_ENABLE_BACKGROUNDING", enable_backgrounding);
json.add("XALT_TRANSMISSION_STYLE", transmission);
if (strcmp(transmission,"syslog") == 0)
json.add("XALT_LOGGING_TAG", syslog_tag);
json.add("XALT_COMPUTE_SHA1", computeSHA1);
json.add("XALT_ETC_DIR", xalt_etc_dir);
json.add("XALT_CONFIG_PY", XALT_CONFIG_PY);
json.add("XALT_SYSTEM_PATH", XALT_SYSTEM_PATH);
json.add("XALT_SYSHOST_CONFIG", SYSHOST_CONFIG);
json.add("XALT_TRACKING_MPI_ONLY", xalt_tracking_mpi_only);
json.add("XALT_SYSLOG_MSG_SZ", SYSLOG_MSG_SZ);
json.add("HAVE_32BIT", HAVE_32BIT);
json.add("USING_LIBUUID", HAVE_WORKING_LIBUUID);
json.add("BUILT_W_MySQL", BUILT_W_MySQL);
json.add("hostnameA", hostnameSz, hostnameA);
json.add("pathPatternA", pathPatternSz, pathPatternA);
json.add("envPatternA", envPatternSz, envPatternA);
json.fini();
std::string jsonStr = json.result();
std::cout << jsonStr << std::endl;
return 0;
}
std::cout << "*------------------------------------------------------------------------------*\n";
std::cout << " XALT Configuration Report\n";
std::cout << "*------------------------------------------------------------------------------*\n\n";
std::cout << "Today's DATE: " << dateStr << "\n";
std::cout << "XALT_VERSION: " << XALT_VERSION << "\n";
std::cout << "XALT_GIT_VERSION: " << XALT_GIT_VERSION << "\n";
std::cout << "XALT_VERSION_STR: " << XALT_VERSION_STR << "\n";
std::cout << "*------------------------------------------------------------------------------*\n";
std::cout << "XALT_SYSHOST: " << syshost << "\n";
std::cout << "XALT_FILE_PREFIX: " << XALT_FILE_PREFIX << "\n";
std::cout << "XALT_TRANSMISSION_STYLE: " << transmission << "\n";
if (strcmp(transmission,"syslog") == 0)
std::cout << "XALT_LOGGING_TAG: " << syslog_tag << "\n";
std::cout << "XALT_COMPUTE_SHA1: " << computeSHA1 << "\n";
std::cout << "XALT_ENABLE_BACKGROUNDING: " << enable_backgrounding << "\n";
std::cout << "XALT_ETC_DIR: " << xalt_etc_dir << "\n";
std::cout << "XALT_CONFIG_PY: " << XALT_CONFIG_PY << "\n";
std::cout << "XALT_TRACKING_MPI_ONLY: " << xalt_tracking_mpi_only << "\n";
std::cout << "XALT_SYSTEM_PATH: " << XALT_SYSTEM_PATH << "\n";
std::cout << "XALT_SYSHOST_CONFIG: " << SYSHOST_CONFIG << "\n";
std::cout << "XALT_SYSLOG_MSG_SZ: " << SYSLOG_MSG_SZ << "\n";
std::cout << "HAVE_32BIT: " << HAVE_32BIT << "\n";
std::cout << "Using libuuid: " << HAVE_WORKING_LIBUUID << "\n";
std::cout << "Built with MySQL: " << BUILT_W_MySQL << "\n";
std::cout << "*------------------------------------------------------------------------------*\n\n";
displayArray("hostnameA", hostnameSz, hostnameA);
std::cout << "\nRemember that \"SPSR\" means a scalar program that creates a start record\n";
displayArray("pathPatternA", pathPatternSz, pathPatternA);
displayArray("envPatternA", envPatternSz, envPatternA);
return 0;
}
<|endoftext|> |
<commit_before>/*
** Copyright 2011-2015 Centreon
**
** 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.
**
** For more information : [email protected]
*/
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/engine_state.hh"
#include "com/centreon/broker/correlation/factory.hh"
#include "com/centreon/broker/correlation/internal.hh"
#include "com/centreon/broker/correlation/issue.hh"
#include "com/centreon/broker/correlation/issue_parent.hh"
#include "com/centreon/broker/correlation/log_issue.hh"
#include "com/centreon/broker/correlation/state.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
// Load count.
static unsigned int instances(0);
extern "C" {
/**
* Module version symbol. Used to check for version mismatch.
*/
char const* broker_module_version = CENTREON_BROKER_VERSION;
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
// Decrement instance number.
if (!--instances) {
// Unregister correlation layer.
io::protocols::instance().unreg("correlation");
// Remove events.
io::events::instance().unregister_category(io::events::correlation);
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
(void)arg;
// Increment instance number.
if (!instances++) {
// Correlation module.
logging::info(logging::high)
<< "correlation: module for Centreon Broker "
<< CENTREON_BROKER_VERSION;
// Register correlation layer.
io::protocols::instance().reg(
"correlation",
correlation::factory(),
1,
7);
// Register category.
io::events& e(io::events::instance());
int correlation_category(e.register_category(
"correlation",
io::events::correlation));
if (correlation_category != io::events::correlation) {
e.unregister_category(correlation_category);
--instances;
throw (exceptions::msg() << "correlation: category "
<< io::events::correlation
<< " is already registered whereas it should be "
<< "reserved for the correlation module");
}
// Register events.
{
e.register_event(
io::events::correlation,
correlation::de_engine_state,
io::event_info(
"engine_state",
&correlation::engine_state::operations,
correlation::engine_state::entries));
e.register_event(
io::events::correlation,
correlation::de_state,
io::event_info(
"state",
&correlation::state::operations,
correlation::state::entries,
"rt_servicestateevents"));
e.register_event(
io::events::correlation,
correlation::de_issue,
io::event_info(
"issue",
&correlation::issue::operations,
correlation::issue::entries,
"rt_issues"));
e.register_event(
io::events::correlation,
correlation::de_issue_parent,
io::event_info(
"issue_parent",
&correlation::issue_parent::operations,
correlation::issue_parent::entries,
"rt_issues_issues_parents"));
e.register_event(
io::events::correlation,
correlation::de_log_issue,
io::event_info(
"log_issue",
&correlation::log_issue::operations,
correlation::log_issue::entries,
"log_logs"));
}
}
return ;
}
}
<commit_msg>correlation: provide 2.x table names to events.<commit_after>/*
** Copyright 2011-2016 Centreon
**
** 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.
**
** For more information : [email protected]
*/
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/engine_state.hh"
#include "com/centreon/broker/correlation/factory.hh"
#include "com/centreon/broker/correlation/internal.hh"
#include "com/centreon/broker/correlation/issue.hh"
#include "com/centreon/broker/correlation/issue_parent.hh"
#include "com/centreon/broker/correlation/log_issue.hh"
#include "com/centreon/broker/correlation/state.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
// Load count.
static unsigned int instances(0);
extern "C" {
/**
* Module version symbol. Used to check for version mismatch.
*/
char const* broker_module_version = CENTREON_BROKER_VERSION;
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
// Decrement instance number.
if (!--instances) {
// Unregister correlation layer.
io::protocols::instance().unreg("correlation");
// Remove events.
io::events::instance().unregister_category(io::events::correlation);
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
(void)arg;
// Increment instance number.
if (!instances++) {
// Correlation module.
logging::info(logging::high)
<< "correlation: module for Centreon Broker "
<< CENTREON_BROKER_VERSION;
// Register correlation layer.
io::protocols::instance().reg(
"correlation",
correlation::factory(),
1,
7);
// Register category.
io::events& e(io::events::instance());
int correlation_category(e.register_category(
"correlation",
io::events::correlation));
if (correlation_category != io::events::correlation) {
e.unregister_category(correlation_category);
--instances;
throw (exceptions::msg() << "correlation: category "
<< io::events::correlation
<< " is already registered whereas it should be "
<< "reserved for the correlation module");
}
// Register events.
{
e.register_event(
io::events::correlation,
correlation::de_engine_state,
io::event_info(
"engine_state",
&correlation::engine_state::operations,
correlation::engine_state::entries));
e.register_event(
io::events::correlation,
correlation::de_state,
io::event_info(
"state",
&correlation::state::operations,
correlation::state::entries,
"rt_servicestateevents"));
e.register_event(
io::events::correlation,
correlation::de_issue,
io::event_info(
"issue",
&correlation::issue::operations,
correlation::issue::entries,
"rt_issues",
"issues"));
e.register_event(
io::events::correlation,
correlation::de_issue_parent,
io::event_info(
"issue_parent",
&correlation::issue_parent::operations,
correlation::issue_parent::entries,
"rt_issues_issues_parents",
"issues_issues_parents"));
e.register_event(
io::events::correlation,
correlation::de_log_issue,
io::event_info(
"log_issue",
&correlation::log_issue::operations,
correlation::log_issue::entries,
"log_logs",
"logs"));
}
}
return ;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/net/http/HttpConnectionServicer.h"
#include "db/net/http/HttpRequest.h"
#include "db/net/http/HttpResponse.h"
#include "db/io/ByteArrayInputStream.h"
#include <cstdlib>
using namespace std;
using namespace db::io;
using namespace db::net::http;
using namespace db::rt;
HttpConnectionServicer::HttpConnectionServicer(const char* serverName)
{
mServerName = strdup(serverName);
}
HttpConnectionServicer::~HttpConnectionServicer()
{
free(mServerName);
}
HttpRequestServicer* HttpConnectionServicer::findRequestServicer(
char* path, ServicerMap& servicerMap)
{
HttpRequestServicer* rval = NULL;
// strip any query
if(path != NULL)
{
char* end = strrchr(path, '?');
if(end != NULL)
{
end[0] = 0;
}
}
mRequestServicerLock.lockShared();
{
// try to find servicer for path
ServicerMap::iterator i;
while(rval == NULL && path != NULL)
{
i = servicerMap.find(path);
if(i != servicerMap.end())
{
rval = i->second;
}
else if(strlen(path) > 1)
{
// try to find servicer at parent path
char* end = strrchr(path, '/');
if(end != NULL)
{
end[0] = 0;
}
else
{
// no path left to search
path = NULL;
}
}
else
{
// no path left to search
path = NULL;
}
}
}
mRequestServicerLock.unlockShared();
return rval;
}
void HttpConnectionServicer::serviceConnection(Connection* c)
{
// wrap connection, set default timeouts to 30 seconds
HttpConnection hc(c, false);
hc.setReadTimeout(30000);
hc.setWriteTimeout(30000);
// create request
HttpRequest* request = (HttpRequest*)hc.createRequest();
HttpRequestHeader* reqHeader = request->getHeader();
// create response
HttpResponse* response = (HttpResponse*)request->createResponse();
HttpResponseHeader* resHeader = response->getHeader();
// handle keep-alive (HTTP/1.1 keep-alive is on by default)
bool keepAlive = true;
bool noerror = true;
while(keepAlive && noerror)
{
// set defaults
resHeader->setVersion("HTTP/1.1");
resHeader->setDate();
resHeader->setField("Server", mServerName);
// receive request header
if((noerror = request->receiveHeader()))
{
// check http version
bool version10 = (strcmp(reqHeader->getVersion(), "HTTP/1.0") == 0);
bool version11 = (strcmp(reqHeader->getVersion(), "HTTP/1.1") == 0);
// only version 1.0 and 1.1 supported
if(version10 || version11)
{
// set response version according to request version
resHeader->setVersion(reqHeader->getVersion());
// include host path if one was used
string host;
if(reqHeader->getField("Host", host))
{
resHeader->setField("Host", host);
}
// get connection header
string connHeader;
if(reqHeader->getField("Connection", connHeader))
{
if(strcasecmp(connHeader.c_str(), "close") == 0)
{
keepAlive = false;
}
else if(strcasecmp(connHeader.c_str(), "keep-alive") == 0)
{
keepAlive = true;
}
}
else if(version10)
{
// if HTTP/1.0 and no keep-alive header, keep-alive is off
keepAlive = false;
}
// get request path and normalize it
const char* inPath = reqHeader->getPath();
char outPath[strlen(inPath) + 2];
HttpRequestServicer::normalizePath(inPath, outPath);
// find appropriate request servicer for path
HttpRequestServicer* hrs = NULL;
// find secure/non-secure servicer
hrs = hc.isSecure() ?
findRequestServicer(outPath, mSecureServicers) :
findRequestServicer(outPath, mNonSecureServicers);
if(hrs != NULL)
{
// service request
hrs->serviceRequest(request, response);
// if servicer closed connection, turn off keep-alive
if(c->isClosed())
{
keepAlive = false;
}
// turn off keep-alive if response has close connection field
if(keepAlive)
{
if(resHeader->getField("Connection", connHeader) &&
strcasecmp(connHeader.c_str(), "close") == 0)
{
keepAlive = false;
}
}
}
else
{
// no servicer, so send 404 Not Found
char html[] = "<html><h2>404 Not Found</h2></html>";
resHeader->setStatus(404, "Not Found");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 35);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 35);
noerror = response->sendBody(&is);
}
}
}
else
{
// send 505 HTTP Version Not Supported
char html[] =
"<html><h2>505 HTTP Version Not Supported</h2></html>";
resHeader->setStatus(505, "HTTP Version Not Supported");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 52);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 52);
noerror = response->sendBody(&is);
}
}
}
else
{
// exception occurred while receiving header
ExceptionRef e = Exception::getLast();
if(!e.isNull() && strcmp(e->getType(), "db.net.http.BadRequest") == 1)
{
// send 400 Bad Request
char html[] = "<html><h2>400 Bad Request</h2></html>";
response->getHeader()->setStatus(400, "Bad Request");
response->getHeader()->setField("Content-Type", "text/html");
response->getHeader()->setField("Content-Length", 38);
response->getHeader()->setField("Connection", "close");
if(response->sendHeader())
{
ByteArrayInputStream is(html, 38);
response->sendBody(&is);
}
}
else
{
// if the exception was not an interruption or socket error then
// send an internal server error response
if(!e.isNull() &&
strcmp(e->getType(), "db.io.InterruptedException") != 0 &&
strncmp(e->getType(), "db.net.Socket", 13) != 0)
{
// send 500 Internal Server Error
char html[] = "<html><h2>500 Internal Server Error</h2></html>";
resHeader->setStatus(500, "Internal Server Error");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 47);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 47);
noerror = response->sendBody(&is);
}
}
}
}
if(keepAlive && noerror)
{
// clear request and response header fields
reqHeader->clearFields();
resHeader->clearFields();
resHeader->clearStatus();
}
}
// clean up request and response
delete request;
delete response;
// close connection
hc.close();
}
void HttpConnectionServicer::addRequestServicer(
HttpRequestServicer* s, bool secure)
{
mRequestServicerLock.lockExclusive();
{
if(secure)
{
mSecureServicers[s->getPath()] = s;
}
else
{
mNonSecureServicers[s->getPath()] = s;
}
}
mRequestServicerLock.unlockExclusive();
}
void HttpConnectionServicer::removeRequestServicer(
HttpRequestServicer* s, bool secure)
{
mRequestServicerLock.lockExclusive();
{
if(secure)
{
mSecureServicers.erase(s->getPath());
}
else
{
mNonSecureServicers.erase(s->getPath());
}
}
mRequestServicerLock.unlockExclusive();
}
HttpRequestServicer* HttpConnectionServicer::removeRequestServicer(
const char* path, bool secure)
{
HttpRequestServicer* rval = NULL;
mRequestServicerLock.lockExclusive();
{
if(secure)
{
ServicerMap::iterator i = mSecureServicers.find(path);
if(i != mSecureServicers.end())
{
rval = i->second;
mSecureServicers.erase(path);
}
}
else
{
ServicerMap::iterator i = mNonSecureServicers.find(path);
if(i != mNonSecureServicers.end())
{
rval = i->second;
mNonSecureServicers.erase(path);
}
}
}
mRequestServicerLock.unlockExclusive();
return rval;
}
<commit_msg>Added code to use X-Forwarded-Server for host for proxy'd stuff.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/net/http/HttpConnectionServicer.h"
#include "db/net/http/HttpRequest.h"
#include "db/net/http/HttpResponse.h"
#include "db/io/ByteArrayInputStream.h"
#include <cstdlib>
using namespace std;
using namespace db::io;
using namespace db::net::http;
using namespace db::rt;
HttpConnectionServicer::HttpConnectionServicer(const char* serverName)
{
mServerName = strdup(serverName);
}
HttpConnectionServicer::~HttpConnectionServicer()
{
free(mServerName);
}
HttpRequestServicer* HttpConnectionServicer::findRequestServicer(
char* path, ServicerMap& servicerMap)
{
HttpRequestServicer* rval = NULL;
// strip any query
if(path != NULL)
{
char* end = strrchr(path, '?');
if(end != NULL)
{
end[0] = 0;
}
}
mRequestServicerLock.lockShared();
{
// try to find servicer for path
ServicerMap::iterator i;
while(rval == NULL && path != NULL)
{
i = servicerMap.find(path);
if(i != servicerMap.end())
{
rval = i->second;
}
else if(strlen(path) > 1)
{
// try to find servicer at parent path
char* end = strrchr(path, '/');
if(end != NULL)
{
end[0] = 0;
}
else
{
// no path left to search
path = NULL;
}
}
else
{
// no path left to search
path = NULL;
}
}
}
mRequestServicerLock.unlockShared();
return rval;
}
void HttpConnectionServicer::serviceConnection(Connection* c)
{
// wrap connection, set default timeouts to 30 seconds
HttpConnection hc(c, false);
hc.setReadTimeout(30000);
hc.setWriteTimeout(30000);
// create request
HttpRequest* request = (HttpRequest*)hc.createRequest();
HttpRequestHeader* reqHeader = request->getHeader();
// create response
HttpResponse* response = (HttpResponse*)request->createResponse();
HttpResponseHeader* resHeader = response->getHeader();
// handle keep-alive (HTTP/1.1 keep-alive is on by default)
bool keepAlive = true;
bool noerror = true;
while(keepAlive && noerror)
{
// set defaults
resHeader->setVersion("HTTP/1.1");
resHeader->setDate();
resHeader->setField("Server", mServerName);
// receive request header
if((noerror = request->receiveHeader()))
{
// check http version
bool version10 = (strcmp(reqHeader->getVersion(), "HTTP/1.0") == 0);
bool version11 = (strcmp(reqHeader->getVersion(), "HTTP/1.1") == 0);
// only version 1.0 and 1.1 supported
if(version10 || version11)
{
// set response version according to request version
resHeader->setVersion(reqHeader->getVersion());
// use proxy'd host field if one was used
// else use host field if one was used
string host;
if(reqHeader->getField("X-Forwarded-Server", host) ||
reqHeader->getField("Host", host))
{
resHeader->setField("Host", host);
}
// get connection header
string connHeader;
if(reqHeader->getField("Connection", connHeader))
{
if(strcasecmp(connHeader.c_str(), "close") == 0)
{
keepAlive = false;
}
else if(strcasecmp(connHeader.c_str(), "keep-alive") == 0)
{
keepAlive = true;
}
}
else if(version10)
{
// if HTTP/1.0 and no keep-alive header, keep-alive is off
keepAlive = false;
}
// get request path and normalize it
const char* inPath = reqHeader->getPath();
char outPath[strlen(inPath) + 2];
HttpRequestServicer::normalizePath(inPath, outPath);
// find appropriate request servicer for path
HttpRequestServicer* hrs = NULL;
// find secure/non-secure servicer
hrs = hc.isSecure() ?
findRequestServicer(outPath, mSecureServicers) :
findRequestServicer(outPath, mNonSecureServicers);
if(hrs != NULL)
{
// service request
hrs->serviceRequest(request, response);
// if servicer closed connection, turn off keep-alive
if(c->isClosed())
{
keepAlive = false;
}
// turn off keep-alive if response has close connection field
if(keepAlive)
{
if(resHeader->getField("Connection", connHeader) &&
strcasecmp(connHeader.c_str(), "close") == 0)
{
keepAlive = false;
}
}
}
else
{
// no servicer, so send 404 Not Found
char html[] = "<html><h2>404 Not Found</h2></html>";
resHeader->setStatus(404, "Not Found");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 35);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 35);
noerror = response->sendBody(&is);
}
}
}
else
{
// send 505 HTTP Version Not Supported
char html[] =
"<html><h2>505 HTTP Version Not Supported</h2></html>";
resHeader->setStatus(505, "HTTP Version Not Supported");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 52);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 52);
noerror = response->sendBody(&is);
}
}
}
else
{
// exception occurred while receiving header
ExceptionRef e = Exception::getLast();
if(!e.isNull() && strcmp(e->getType(), "db.net.http.BadRequest") == 1)
{
// send 400 Bad Request
char html[] = "<html><h2>400 Bad Request</h2></html>";
response->getHeader()->setStatus(400, "Bad Request");
response->getHeader()->setField("Content-Type", "text/html");
response->getHeader()->setField("Content-Length", 38);
response->getHeader()->setField("Connection", "close");
if(response->sendHeader())
{
ByteArrayInputStream is(html, 38);
response->sendBody(&is);
}
}
else
{
// if the exception was not an interruption or socket error then
// send an internal server error response
if(!e.isNull() &&
strcmp(e->getType(), "db.io.InterruptedException") != 0 &&
strncmp(e->getType(), "db.net.Socket", 13) != 0)
{
// send 500 Internal Server Error
char html[] = "<html><h2>500 Internal Server Error</h2></html>";
resHeader->setStatus(500, "Internal Server Error");
resHeader->setField("Content-Type", "text/html");
resHeader->setField("Content-Length", 47);
resHeader->setField("Connection", "close");
if((noerror = response->sendHeader()))
{
ByteArrayInputStream is(html, 47);
noerror = response->sendBody(&is);
}
}
}
}
if(keepAlive && noerror)
{
// clear request and response header fields
reqHeader->clearFields();
resHeader->clearFields();
resHeader->clearStatus();
}
}
// clean up request and response
delete request;
delete response;
// close connection
hc.close();
}
void HttpConnectionServicer::addRequestServicer(
HttpRequestServicer* s, bool secure)
{
mRequestServicerLock.lockExclusive();
{
if(secure)
{
mSecureServicers[s->getPath()] = s;
}
else
{
mNonSecureServicers[s->getPath()] = s;
}
}
mRequestServicerLock.unlockExclusive();
}
void HttpConnectionServicer::removeRequestServicer(
HttpRequestServicer* s, bool secure)
{
mRequestServicerLock.lockExclusive();
{
if(secure)
{
mSecureServicers.erase(s->getPath());
}
else
{
mNonSecureServicers.erase(s->getPath());
}
}
mRequestServicerLock.unlockExclusive();
}
HttpRequestServicer* HttpConnectionServicer::removeRequestServicer(
const char* path, bool secure)
{
HttpRequestServicer* rval = NULL;
mRequestServicerLock.lockExclusive();
{
if(secure)
{
ServicerMap::iterator i = mSecureServicers.find(path);
if(i != mSecureServicers.end())
{
rval = i->second;
mSecureServicers.erase(path);
}
}
else
{
ServicerMap::iterator i = mNonSecureServicers.find(path);
if(i != mNonSecureServicers.end())
{
rval = i->second;
mNonSecureServicers.erase(path);
}
}
}
mRequestServicerLock.unlockExclusive();
return rval;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/base/algorithm/camerautils.h>
#include <inviwo/core/network/networklock.h>
namespace inviwo {
namespace camerautil {
namespace detail {
vec3 getViewDir(Side side) {
switch (side) {
case Side::XNegative:
return vec3(1, 0, 0);
case Side::XPositive:
return vec3(-1, 0, 0);
case Side::YNegative:
return vec3(0, 1, 0);
case Side::YPositive:
return vec3(0, -1, 0);
case Side::ZNegative:
return vec3(0, 0, 1);
case Side::ZPositive:
return vec3(0, 0, -1);
default:
return vec3(0);
}
}
vec3 getLookUp(Side side) {
switch (side) {
case Side::XNegative:
return vec3(0, 1, 0);
case Side::XPositive:
return vec3(0, 1, 0);
case Side::YNegative:
return vec3(1, 0, 0);
case Side::YPositive:
return vec3(1, 0, 0);
case Side::ZNegative:
return vec3(0, 1, 0);
case Side::ZPositive:
return vec3(0, 1, 0);
default:
return vec3(0);
}
}
} // namespace detail
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, vec3 inViewDir, vec3 inLookUp,
float fitRatio, UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
if (auto perspectiveCamera = dynamic_cast<PerspectiveCamera *>(&cam.get())) {
const auto offset = vec3{.5f};
const auto lookTo = vec3(boundingBox * vec4(offset, 1.f));
const auto viewDir = glm::normalize(inViewDir);
const auto lookUp = glm::normalize(inLookUp);
const auto sideDir = glm::cross(viewDir, lookUp);
const float fovy = perspectiveCamera->getFovy() / 2.0f;
const float fovx =
glm::degrees(std::atan(cam.getAspectRatio() * std::tan(glm::radians(fovy))));
const std::array<vec3, 8> corners = {vec3{0, 0, 0}, vec3{1, 0, 0}, vec3{1, 1, 0},
vec3{0, 1, 0}, vec3{0, 0, 1}, vec3{1, 0, 1},
vec3{1, 1, 1}, vec3{0, 1, 1}};
// Find the needed distance from the camera to lookTo given a field of view such that a
// corner of the bounding box are within the view
const auto dist = [&](vec3 corner) {
const auto point = vec3(boundingBox * vec4(corner, 1.f));
const auto d0 = glm::dot(point - lookTo, -viewDir);
const auto height = glm::abs(glm::dot(point - lookTo, lookUp)) * fitRatio;
const auto width = glm::abs(glm::dot(point - lookTo, sideDir)) * fitRatio;
const float d1 = height * std::tan(glm::radians(90 - fovy));
const float d2 = width * std::tan(glm::radians(90 - fovx));
return d0 + std::max(d1, d2);
};
// take the largest needed distance for all corners.
const auto it = std::max_element(corners.begin(), corners.end(),
[&](vec3 a, vec3 b) { return dist(a) < dist(b); });
const auto lookFrom = dist(*it) * viewDir;
NetworkLock lock(&cam);
if (updateNearFar == UpdateNearFar::Yes) {
setCameraNearFar(cam, boundingBox);
}
if (updateLookRanges == UpdateLookRanges::Yes) {
setCameraLookRanges(cam, boundingBox);
}
cam.setLook(lookFrom, lookTo, lookUp);
} else {
LogWarnCustom("camerautil::setCameraView",
"setCameraView only supports perspective cameras");
}
}
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
setCameraView(cam, boundingBox, cam.getLookFrom() - cam.getLookTo(), cam.getLookUp(), fitRatio,
updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, Side side, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
setCameraView(cam, boundingBox, detail::getViewDir(side), detail::getLookUp(side), fitRatio,
updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const std::vector<std::shared_ptr<const Mesh>> &meshes,
Side side, float fitRatio, UpdateNearFar updateNearFar,
UpdateLookRanges updateLookRanges) {
auto minMax = meshutil::axisAlignedBoundingBox(meshes);
auto m = glm::scale(minMax.second - minMax.first);
m[3] = vec4(minMax.first, 1.0f);
setCameraView(cam, m, side, fitRatio, updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const Mesh &mesh, Side side, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
auto minMax = meshutil::axisAlignedBoundingBox(mesh);
auto m = glm::scale(minMax.second - minMax.first);
m[3] = vec4(minMax.first, 1.0f);
setCameraView(cam, m, side, fitRatio, updateNearFar, updateLookRanges);
}
void setCameraLookRanges(CameraProperty &cam, const mat4 &boundingBox, float zoomRange) {
NetworkLock lock(&cam);
vec3 lookTo(boundingBox * vec4(vec3(.5f), 1.f));
vec3 dx(boundingBox[0]);
vec3 dy(boundingBox[1]);
vec3 dz(boundingBox[2]);
auto p0 = lookTo + (dx + dy + dz) * zoomRange;
auto p1 = lookTo - (dx + dy + dz) * zoomRange;
cam.lookFrom_.setMinValue(glm::min(p0, p1));
cam.lookFrom_.setMaxValue(glm::max(p0, p1));
p0 = lookTo + (dx + dy + dz);
p1 = lookTo - (dx + dy + dz);
cam.lookTo_.setMinValue(glm::min(p0, p1));
cam.lookTo_.setMaxValue(glm::max(p0, p1));
}
std::pair<float, float> computeCameraNearFar(const mat4 &boundingBox, float zoomRange,
float nearFarRatio) {
vec3 bx(boundingBox[0]);
vec3 by(boundingBox[1]);
vec3 bz(boundingBox[2]);
float dx = glm::length(bx);
float dy = glm::length(by);
float dz = glm::length(bz);
auto d = std::max({dx, dy, dz});
auto newFar = d * (zoomRange + 1);
auto newNear = newFar * nearFarRatio;
return {newNear, newFar};
}
void setCameraNearFar(CameraProperty &cam, const mat4 &boundingBox, float zoomRange,
float nearFarRatio) {
auto [newNear, newFar] = computeCameraNearFar(boundingBox, zoomRange, nearFarRatio);
cam.setNearFarPlaneDist(newNear, newFar);
}
} // namespace camerautil
} // namespace inviwo
<commit_msg>Base: Camera fitter: Fixes for basis not centered at zero and with rotated basises<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/base/algorithm/camerautils.h>
#include <inviwo/core/network/networklock.h>
namespace inviwo {
namespace camerautil {
namespace detail {
vec3 getViewDir(Side side) {
switch (side) {
case Side::XNegative:
return vec3(1, 0, 0);
case Side::XPositive:
return vec3(-1, 0, 0);
case Side::YNegative:
return vec3(0, 1, 0);
case Side::YPositive:
return vec3(0, -1, 0);
case Side::ZNegative:
return vec3(0, 0, 1);
case Side::ZPositive:
return vec3(0, 0, -1);
default:
return vec3(0);
}
}
vec3 getLookUp(Side side) {
switch (side) {
case Side::XNegative:
return vec3(0, 1, 0);
case Side::XPositive:
return vec3(0, 1, 0);
case Side::YNegative:
return vec3(1, 0, 0);
case Side::YPositive:
return vec3(1, 0, 0);
case Side::ZNegative:
return vec3(0, 1, 0);
case Side::ZPositive:
return vec3(0, 1, 0);
default:
return vec3(0);
}
}
} // namespace detail
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, vec3 inViewDir, vec3 inLookUp,
float fitRatio, UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
if (auto perspectiveCamera = dynamic_cast<PerspectiveCamera *>(&cam.get())) {
const auto offset = vec3{.5f};
const auto lookTo = vec3(boundingBox * vec4(offset, 1.f));
const auto viewDir = glm::normalize(inViewDir);
const auto lookUp = glm::normalize(inLookUp);
const auto sideDir = glm::cross(viewDir, lookUp);
const float fovy = perspectiveCamera->getFovy() / 2.0f;
const float fovx =
glm::degrees(std::atan(cam.getAspectRatio() * std::tan(glm::radians(fovy))));
const std::array<vec3, 8> corners = {vec3{0, 0, 0}, vec3{1, 0, 0}, vec3{1, 1, 0},
vec3{0, 1, 0}, vec3{0, 0, 1}, vec3{1, 0, 1},
vec3{1, 1, 1}, vec3{0, 1, 1}};
// Find the needed distance from the camera to lookTo given a field of view such that a
// corner of the bounding box are within the view
const auto dist = [&](vec3 corner) {
const auto point = vec3(boundingBox * vec4(corner, 1.f));
const auto d0 = glm::dot(point - lookTo, -viewDir);
const auto height = glm::abs(glm::dot(point - lookTo, lookUp)) * fitRatio;
const auto width = glm::abs(glm::dot(point - lookTo, sideDir)) * fitRatio;
const float d1 = height * std::tan(glm::radians(90 - fovy));
const float d2 = width * std::tan(glm::radians(90 - fovx));
return d0 + std::max(d1, d2);
};
// take the largest needed distance for all corners.
const auto it = std::max_element(corners.begin(), corners.end(),
[&](vec3 a, vec3 b) { return dist(a) < dist(b); });
const auto lookOffset = dist(*it) * viewDir;
NetworkLock lock(&cam);
if (updateNearFar == UpdateNearFar::Yes) {
setCameraNearFar(cam, boundingBox);
}
if (updateLookRanges == UpdateLookRanges::Yes) {
setCameraLookRanges(cam, boundingBox);
}
cam.setLook(lookTo + lookOffset, lookTo, lookUp);
} else {
LogWarnCustom("camerautil::setCameraView",
"setCameraView only supports perspective cameras");
}
}
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
setCameraView(cam, boundingBox, cam.getLookFrom() - cam.getLookTo(), cam.getLookUp(), fitRatio,
updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const mat4 &boundingBox, Side side, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
const auto viewDir = mat3(boundingBox) * detail::getViewDir(side);
const auto lookUp = mat3(boundingBox) * detail::getLookUp(side);
setCameraView(cam, boundingBox, viewDir, lookUp, fitRatio,
updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const std::vector<std::shared_ptr<const Mesh>> &meshes,
Side side, float fitRatio, UpdateNearFar updateNearFar,
UpdateLookRanges updateLookRanges) {
auto minMax = meshutil::axisAlignedBoundingBox(meshes);
auto m = glm::scale(minMax.second - minMax.first);
m[3] = vec4(minMax.first, 1.0f);
setCameraView(cam, m, side, fitRatio, updateNearFar, updateLookRanges);
}
void setCameraView(CameraProperty &cam, const Mesh &mesh, Side side, float fitRatio,
UpdateNearFar updateNearFar, UpdateLookRanges updateLookRanges) {
auto minMax = meshutil::axisAlignedBoundingBox(mesh);
auto m = glm::scale(minMax.second - minMax.first);
m[3] = vec4(minMax.first, 1.0f);
setCameraView(cam, m, side, fitRatio, updateNearFar, updateLookRanges);
}
void setCameraLookRanges(CameraProperty &cam, const mat4 &boundingBox, float zoomRange) {
NetworkLock lock(&cam);
vec3 lookTo(boundingBox * vec4(vec3(.5f), 1.f));
vec3 dx(boundingBox[0]);
vec3 dy(boundingBox[1]);
vec3 dz(boundingBox[2]);
auto p0 = lookTo + (dx + dy + dz) * zoomRange;
auto p1 = lookTo - (dx + dy + dz) * zoomRange;
cam.lookFrom_.setMinValue(glm::min(p0, p1));
cam.lookFrom_.setMaxValue(glm::max(p0, p1));
p0 = lookTo + (dx + dy + dz);
p1 = lookTo - (dx + dy + dz);
cam.lookTo_.setMinValue(glm::min(p0, p1));
cam.lookTo_.setMaxValue(glm::max(p0, p1));
}
std::pair<float, float> computeCameraNearFar(const mat4 &boundingBox, float zoomRange,
float nearFarRatio) {
vec3 bx(boundingBox[0]);
vec3 by(boundingBox[1]);
vec3 bz(boundingBox[2]);
float dx = glm::length(bx);
float dy = glm::length(by);
float dz = glm::length(bz);
auto d = std::max({dx, dy, dz});
auto newFar = d * (zoomRange + 1);
auto newNear = newFar * nearFarRatio;
return {newNear, newFar};
}
void setCameraNearFar(CameraProperty &cam, const mat4 &boundingBox, float zoomRange,
float nearFarRatio) {
auto [newNear, newFar] = computeCameraNearFar(boundingBox, zoomRange, nearFarRatio);
cam.setNearFarPlaneDist(newNear, newFar);
}
} // namespace camerautil
} // namespace inviwo
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <boost/lexical_cast.hpp>
#include "master.hpp"
#include "nexus_sched.hpp"
#include "nexus_local.hpp"
using std::string;
using std::vector;
using boost::lexical_cast;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::master;
class NoopScheduler : public Scheduler
{
public:
bool registeredCalled;
int offersGotten;
int slavesExpected;
public:
NoopScheduler(int _slavesExpected)
: slavesExpected(_slavesExpected),
registeredCalled(false),
offersGotten(0)
{}
virtual ~NoopScheduler() {}
virtual void registered(SchedulerDriver*, FrameworkID fid) {
LOG(INFO) << "NoopScheduler registered";
registeredCalled = true;
}
virtual void resourceOffer(SchedulerDriver *d,
OfferID id,
const vector<SlaveOffer>& offers) {
LOG(INFO) << "NoopScheduler got a slot offer";
offersGotten++;
EXPECT_EQ(slavesExpected, offers.size());
foreach (const SlaveOffer& offer, offers) {
string cpus = offer.params.find("cpus")->second;
string mem = offer.params.find("mem")->second;
EXPECT_EQ("2", cpus);
EXPECT_EQ(lexical_cast<string>(1 * Gigabyte), mem);
}
vector<TaskDescription> tasks;
d->replyToOffer(id, tasks, string_map());
d->stop();
}
};
TEST(MasterTest, NoopFrameworkWithOneSlave)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 2, 1 * Gigabyte, false, false);
NoopScheduler sched(1);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_TRUE(sched.registeredCalled);
EXPECT_EQ(1, sched.offersGotten);
kill_nexus();
}
TEST(MasterTest, NoopFrameworkWithMultipleSlaves)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(10, 2, 1 * Gigabyte, false, false);
NoopScheduler sched(10);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_TRUE(sched.registeredCalled);
EXPECT_EQ(1, sched.offersGotten);
kill_nexus();
}
class FixedResponseScheduler : public Scheduler
{
public:
vector<TaskDescription> response;
string errorMessage;
FixedResponseScheduler(vector<TaskDescription> _response)
: response(_response) {}
virtual ~FixedResponseScheduler() {}
virtual void resourceOffer(SchedulerDriver* d,
OfferID id,
const vector<SlaveOffer>& offers) {
LOG(INFO) << "FixedResponseScheduler got a slot offer";
d->replyToOffer(id, response, string_map());
}
virtual void error(SchedulerDriver* d,
int code,
const std::string& message) {
errorMessage = message;
d->stop();
}
};
TEST(MasterTest, DuplicateTaskIdsInResponse)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Duplicate task ID: 1", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchMemoryInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(4 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchCpuInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "4";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooLittleCpuInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "0";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Invalid task size: <0 CPUs, 1073741824 MEM>", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooLittleMemoryInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = "1";
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Invalid task size: <1 CPUs, 1 MEM>", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchMemoryAcrossTasks)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(2 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchCpuAcrossTasks)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "2";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, ResourcesReofferedAfterReject)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(10, 2, 1 * Gigabyte, false, false);
NoopScheduler sched1(10);
NexusSchedulerDriver driver1(&sched1, master);
driver1.run();
EXPECT_TRUE(sched1.registeredCalled);
EXPECT_EQ(1, sched1.offersGotten);
NoopScheduler sched2(10);
NexusSchedulerDriver driver2(&sched2, master);
driver2.run();
EXPECT_TRUE(sched2.registeredCalled);
EXPECT_EQ(1, sched2.offersGotten);
kill_nexus();
}
TEST(MasterTest, ResourcesReofferedAfterBadResponse)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 2, 1 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "0";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched1(tasks);
NexusSchedulerDriver driver1(&sched1, master);
driver1.run();
EXPECT_EQ("Invalid task size: <0 CPUs, 1073741824 MEM>", sched1.errorMessage);
NoopScheduler sched2(1);
NexusSchedulerDriver driver2(&sched2, master);
driver2.run();
EXPECT_TRUE(sched2.registeredCalled);
EXPECT_EQ(1, sched2.offersGotten);
kill_nexus();
}
<commit_msg>Fix unit tests after commit c1827f9e9cef5275b99b96705a23ad1869c90774<commit_after>#include <gtest/gtest.h>
#include <boost/lexical_cast.hpp>
#include "master.hpp"
#include "nexus_sched.hpp"
#include "nexus_local.hpp"
using std::string;
using std::vector;
using boost::lexical_cast;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::master;
class NoopScheduler : public Scheduler
{
public:
bool registeredCalled;
int offersGotten;
int slavesExpected;
public:
NoopScheduler(int _slavesExpected)
: slavesExpected(_slavesExpected),
registeredCalled(false),
offersGotten(0)
{}
virtual ~NoopScheduler() {}
virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {
return ExecutorInfo("noexecutor", "");
}
virtual void registered(SchedulerDriver*, FrameworkID fid) {
LOG(INFO) << "NoopScheduler registered";
registeredCalled = true;
}
virtual void resourceOffer(SchedulerDriver *d,
OfferID id,
const vector<SlaveOffer>& offers) {
LOG(INFO) << "NoopScheduler got a slot offer";
offersGotten++;
EXPECT_EQ(slavesExpected, offers.size());
foreach (const SlaveOffer& offer, offers) {
string cpus = offer.params.find("cpus")->second;
string mem = offer.params.find("mem")->second;
EXPECT_EQ("2", cpus);
EXPECT_EQ(lexical_cast<string>(1 * Gigabyte), mem);
}
vector<TaskDescription> tasks;
d->replyToOffer(id, tasks, string_map());
d->stop();
}
};
TEST(MasterTest, NoopFrameworkWithOneSlave)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 2, 1 * Gigabyte, false, false);
NoopScheduler sched(1);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_TRUE(sched.registeredCalled);
EXPECT_EQ(1, sched.offersGotten);
kill_nexus();
}
TEST(MasterTest, NoopFrameworkWithMultipleSlaves)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(10, 2, 1 * Gigabyte, false, false);
NoopScheduler sched(10);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_TRUE(sched.registeredCalled);
EXPECT_EQ(1, sched.offersGotten);
kill_nexus();
}
class FixedResponseScheduler : public Scheduler
{
public:
vector<TaskDescription> response;
string errorMessage;
FixedResponseScheduler(vector<TaskDescription> _response)
: response(_response) {}
virtual ~FixedResponseScheduler() {}
virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {
return ExecutorInfo("noexecutor", "");
}
virtual void resourceOffer(SchedulerDriver* d,
OfferID id,
const vector<SlaveOffer>& offers) {
LOG(INFO) << "FixedResponseScheduler got a slot offer";
d->replyToOffer(id, response, string_map());
}
virtual void error(SchedulerDriver* d,
int code,
const std::string& message) {
errorMessage = message;
d->stop();
}
};
TEST(MasterTest, DuplicateTaskIdsInResponse)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Duplicate task ID: 1", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchMemoryInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(4 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchCpuInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "4";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooLittleCpuInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "0";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Invalid task size: <0 CPUs, 1073741824 MEM>", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooLittleMemoryInTask)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = "1";
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Invalid task size: <1 CPUs, 1 MEM>", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchMemoryAcrossTasks)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "1";
params["mem"] = lexical_cast<string>(2 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, TooMuchCpuAcrossTasks)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 3, 3 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "2";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
tasks.push_back(TaskDescription(2, 0, "", params, ""));
FixedResponseScheduler sched(tasks);
NexusSchedulerDriver driver(&sched, master);
driver.run();
EXPECT_EQ("Too many resources accepted", sched.errorMessage);
kill_nexus();
}
TEST(MasterTest, ResourcesReofferedAfterReject)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(10, 2, 1 * Gigabyte, false, false);
NoopScheduler sched1(10);
NexusSchedulerDriver driver1(&sched1, master);
driver1.run();
EXPECT_TRUE(sched1.registeredCalled);
EXPECT_EQ(1, sched1.offersGotten);
NoopScheduler sched2(10);
NexusSchedulerDriver driver2(&sched2, master);
driver2.run();
EXPECT_TRUE(sched2.registeredCalled);
EXPECT_EQ(1, sched2.offersGotten);
kill_nexus();
}
TEST(MasterTest, ResourcesReofferedAfterBadResponse)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
PID master = run_nexus(1, 2, 1 * Gigabyte, false, false);
vector<TaskDescription> tasks;
map<string, string> params;
params["cpus"] = "0";
params["mem"] = lexical_cast<string>(1 * Gigabyte);
tasks.push_back(TaskDescription(1, 0, "", params, ""));
FixedResponseScheduler sched1(tasks);
NexusSchedulerDriver driver1(&sched1, master);
driver1.run();
EXPECT_EQ("Invalid task size: <0 CPUs, 1073741824 MEM>", sched1.errorMessage);
NoopScheduler sched2(1);
NexusSchedulerDriver driver2(&sched2, master);
driver2.run();
EXPECT_TRUE(sched2.registeredCalled);
EXPECT_EQ(1, sched2.offersGotten);
kill_nexus();
}
<|endoftext|> |
<commit_before>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission. The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose. It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author: Mike Litzkow
**
*/
#if defined(Solaris) && !defined(Solaris251)
#include "condor_fix_timeval.h"
#include </usr/ucbinclude/sys/rusage.h>
#endif
#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "filter.h"
#include "alloc.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#include "condor_qmgr.h"
char *param();
char *MyName;
int PrioAdjustment;
int NewPriority;
int PrioritySet;
int AdjustmentSet;
int InvokingUid; // user id of person ivoking this program
char *InvokingUserName; // user name of person ivoking this program
const int MIN_PRIO = -20;
const int MAX_PRIO = 20;
// Prototypes of local interest only
void usage();
int compute_adj( char * );
void ProcArg( const char * );
int calc_prio( int old_prio );
void init_user_credentials();
char hostname[512];
// Tell folks how to use this program
void
usage()
{
fprintf( stderr, "Usage: %s [{+|-}priority ] [-p priority] ", MyName );
fprintf( stderr, "[ -a ] [-r host] [user | cluster | cluster.proc] ...\n");
exit( 1 );
}
int
main( int argc, char *argv[] )
{
char *arg;
int prio_adj;
char *args[argc - 1];
int nArgs = 0;
int i;
Qmgr_connection *q;
MyName = argv[0];
config( 0 );
if( argc < 2 ) {
usage();
}
PrioritySet = 0;
AdjustmentSet = 0;
hostname[0] = '\0';
for( argv++; arg = *argv; argv++ ) {
if( (arg[0] == '-' || arg[0] == '+') && isdigit(arg[1]) ) {
PrioAdjustment = compute_adj(arg);
AdjustmentSet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'p' ) {
argv++;
NewPriority = atoi(*argv);
PrioritySet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'r' ) {
// use the given name as the host name to connect to
argv++;
strcpy (hostname, *argv);
} else {
args[nArgs] = arg;
nArgs++;
}
}
if( PrioritySet == FALSE && AdjustmentSet == FALSE ) {
fprintf( stderr,
"You must specify a new priority or priority adjustment.\n");
usage();
exit(1);
}
if( PrioritySet && (NewPriority < MIN_PRIO || NewPriority > MAX_PRIO) ) {
fprintf( stderr,
"Invalid priority specified. Must be between %d and %d.\n",
MIN_PRIO, MAX_PRIO );
exit(1);
}
/* Open job queue */
if (hostname[0] == '\0')
{
// hostname was not set at command line; obtain from system
if(gethostname(hostname, 200) < 0)
{
EXCEPT("gethostname failed, errno = %d", errno);
}
}
if((q = ConnectQ(hostname)) == 0)
{
EXCEPT("Failed to connect to qmgr on host %s", hostname);
}
for(i = 0; i < nArgs; i++)
{
ProcArg(args[i]);
}
DisconnectQ(q);
#if defined(ALLOC_DEBUG)
print_alloc_stats();
#endif
return 0;
}
/*
Given the old priority of a given process, calculate the new
one based on information gotten from the command line arguments.
*/
int
calc_prio( int old_prio )
{
int answer;
if( AdjustmentSet == TRUE && PrioritySet == FALSE ) {
answer = old_prio + PrioAdjustment;
if( answer > MAX_PRIO )
answer = MAX_PRIO;
else if( answer < MIN_PRIO )
answer = MIN_PRIO;
} else {
answer = NewPriority;
}
return answer;
}
/*
Given a command line argument specifing a relative adjustment
of priority of the form "+adj" or "-adj", return the correct
value as a positive or negative integer.
*/
int
compute_adj( char *arg )
{
char *ptr;
int val;
ptr = arg+1;
val = atoi(ptr);
if( *arg == '-' ) {
return( -val );
} else {
return( val );
}
}
extern "C" int SetSyscalls( int foo ) { return foo; }
void UpdateJobAd(int cluster, int proc)
{
int old_prio, new_prio;
if (GetAttributeInt(cluster, proc, "Prio", &old_prio) < 0)
{
fprintf(stderr, "Couldn't retrieve current prio for %d.%d.\n",
cluster, proc);
return;
}
new_prio = calc_prio( old_prio );
SetAttributeInt(cluster, proc, "Prio", new_prio);
}
void ProcArg(const char* arg)
{
int cluster, proc;
char *tmp;
if(isdigit(*arg))
// set prio by cluster/proc #
{
cluster = strtol(arg, &tmp, 10);
if(cluster <= 0)
{
fprintf(stderr, "Invalid cluster # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for all jobs in the cluster
{
int next_cluster = cluster;
proc = -1;
while(next_cluster == cluster) {
if (GetNextJob(cluster, proc, &next_cluster, &proc) < 0) {
return;
}
UpdateJobAd(cluster, proc);
}
return;
}
if(*tmp == '.')
{
proc = strtol(tmp + 1, &tmp, 10);
if(proc < 0)
{
fprintf(stderr, "Invalid proc # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for proc
{
UpdateJobAd(cluster, proc);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
else if(isalpha(*arg) || (arg[0] == '-' && arg[1] == 'a'))
// update prio by user name
{
char owner[1000];
cluster = proc = -1;
while (GetNextJob(cluster, proc, &cluster, &proc) >= 0) {
if (arg[0] == '-' && arg[1] == 'a') {
UpdateJobAd(cluster, proc);
}
else {
if (GetAttributeString(cluster, proc, "Owner", owner) < 0) {
fprintf(stderr, "Couldn't retrieve owner attribute for "
"%d.%d\n", cluster, proc);
return;
}
if (strcmp(owner, arg) == MATCH) {
UpdateJobAd(cluster, proc);
}
}
}
}
else
{
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
}
<commit_msg>use new qmgmt interface<commit_after>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission. The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose. It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author: Mike Litzkow
**
*/
#if defined(Solaris) && !defined(Solaris251)
#include "condor_fix_timeval.h"
#include </usr/ucbinclude/sys/rusage.h>
#endif
#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_attributes.h"
#include "filter.h"
#include "alloc.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#include "condor_qmgr.h"
char *param();
char *MyName;
int PrioAdjustment;
int NewPriority;
int PrioritySet;
int AdjustmentSet;
int InvokingUid; // user id of person ivoking this program
char *InvokingUserName; // user name of person ivoking this program
const int MIN_PRIO = -20;
const int MAX_PRIO = 20;
// Prototypes of local interest only
void usage();
int compute_adj( char * );
void ProcArg( const char * );
int calc_prio( int old_prio );
void init_user_credentials();
char hostname[512];
// Tell folks how to use this program
void
usage()
{
fprintf( stderr, "Usage: %s [{+|-}priority ] [-p priority] ", MyName );
fprintf( stderr, "[ -a ] [-r host] [user | cluster | cluster.proc] ...\n");
exit( 1 );
}
int
main( int argc, char *argv[] )
{
char *arg;
int prio_adj;
char *args[argc - 1];
int nArgs = 0;
int i;
Qmgr_connection *q;
MyName = argv[0];
config( 0 );
if( argc < 2 ) {
usage();
}
PrioritySet = 0;
AdjustmentSet = 0;
hostname[0] = '\0';
for( argv++; arg = *argv; argv++ ) {
if( (arg[0] == '-' || arg[0] == '+') && isdigit(arg[1]) ) {
PrioAdjustment = compute_adj(arg);
AdjustmentSet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'p' ) {
argv++;
NewPriority = atoi(*argv);
PrioritySet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'r' ) {
// use the given name as the host name to connect to
argv++;
strcpy (hostname, *argv);
} else {
args[nArgs] = arg;
nArgs++;
}
}
if( PrioritySet == FALSE && AdjustmentSet == FALSE ) {
fprintf( stderr,
"You must specify a new priority or priority adjustment.\n");
usage();
exit(1);
}
if( PrioritySet && (NewPriority < MIN_PRIO || NewPriority > MAX_PRIO) ) {
fprintf( stderr,
"Invalid priority specified. Must be between %d and %d.\n",
MIN_PRIO, MAX_PRIO );
exit(1);
}
/* Open job queue */
if (hostname[0] == '\0')
{
// hostname was not set at command line; obtain from system
if(gethostname(hostname, 200) < 0)
{
EXCEPT("gethostname failed, errno = %d", errno);
}
}
if((q = ConnectQ(hostname)) == 0)
{
EXCEPT("Failed to connect to qmgr on host %s", hostname);
}
for(i = 0; i < nArgs; i++)
{
ProcArg(args[i]);
}
DisconnectQ(q);
#if defined(ALLOC_DEBUG)
print_alloc_stats();
#endif
return 0;
}
/*
Given the old priority of a given process, calculate the new
one based on information gotten from the command line arguments.
*/
int
calc_prio( int old_prio )
{
int answer;
if( AdjustmentSet == TRUE && PrioritySet == FALSE ) {
answer = old_prio + PrioAdjustment;
if( answer > MAX_PRIO )
answer = MAX_PRIO;
else if( answer < MIN_PRIO )
answer = MIN_PRIO;
} else {
answer = NewPriority;
}
return answer;
}
/*
Given a command line argument specifing a relative adjustment
of priority of the form "+adj" or "-adj", return the correct
value as a positive or negative integer.
*/
int
compute_adj( char *arg )
{
char *ptr;
int val;
ptr = arg+1;
val = atoi(ptr);
if( *arg == '-' ) {
return( -val );
} else {
return( val );
}
}
extern "C" int SetSyscalls( int foo ) { return foo; }
void UpdateJobAd(int cluster, int proc)
{
int old_prio, new_prio;
if (GetAttributeInt(cluster, proc, ATTR_JOB_PRIO, &old_prio) < 0)
{
fprintf(stderr, "Couldn't retrieve current prio for %d.%d.\n",
cluster, proc);
return;
}
new_prio = calc_prio( old_prio );
SetAttributeInt(cluster, proc, ATTR_JOB_PRIO, new_prio);
}
void ProcArg(const char* arg)
{
int cluster, proc;
char *tmp;
if(isdigit(*arg))
// set prio by cluster/proc #
{
cluster = strtol(arg, &tmp, 10);
if(cluster <= 0)
{
fprintf(stderr, "Invalid cluster # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for all jobs in the cluster
{
ClassAd *ad = new ClassAd;
char constraint[100];
sprintf(constraint, "%s == %d", ATTR_CLUSTER_ID, cluster);
int firstTime = 1;
while(GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
return;
}
if(*tmp == '.')
{
proc = strtol(tmp + 1, &tmp, 10);
if(proc < 0)
{
fprintf(stderr, "Invalid proc # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for proc
{
UpdateJobAd(cluster, proc);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
else if(arg[0] == '-' && arg[1] == 'a')
{
ClassAd *ad = new ClassAd;
int firstTime = 1;
while(GetNextJob(ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else if(isalpha(*arg))
// update prio by user name
{
char constraint[100];
ClassAd *ad = new ClassAd;
int firstTime = 1;
sprintf(constraint, "%s == \"%s\"", ATTR_OWNER, arg);
while (GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else
{
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
}
<|endoftext|> |
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "nifty/python/converter.hxx"
#include "nifty/graph/rag/grid_rag_features.hxx"
#ifdef WITH_HDF5
#include "vigra/multi_array_chunked_hdf5.hxx"
#include "nifty/graph/rag/grid_rag_features_chunked.hxx"
#endif
namespace py = pybind11;
namespace nifty{
namespace graph{
using namespace py;
template<class RAG,class T,size_t DATA_DIM, class EDGE_MAP, class NODE_MAP>
void exportGridRagAccumulateFeaturesT(py::module & ragModule){
ragModule.def("gridRagAccumulateFeatures",
[](
const RAG & rag,
nifty::marray::PyView<T, DATA_DIM> data,
EDGE_MAP & edgeMap,
NODE_MAP & nodeMap
){
{
py::gil_scoped_release allowThreads;
gridRagAccumulateFeatures(rag, data, edgeMap, nodeMap);
}
},
py::arg("graph"),py::arg("data"),py::arg("edgeMap"),py::arg("nodeMap")
);
}
template<class RAG,class T,size_t DATA_DIM>
void exportGridRagAccumulateLabelsT(py::module & ragModule){
ragModule.def("gridRagAccumulateLabels",
[](
const RAG & rag,
nifty::marray::PyView<T, DATA_DIM> labels
){
nifty::marray::PyView<T> nodeLabels({rag.numberOfNodes()});
{
py::gil_scoped_release allowThreads;
gridRagAccumulateLabels(rag, labels, nodeLabels);
}
return nodeLabels;
},
py::arg("graph"),py::arg("labels")
);
}
// export only if we have HDF5 support
#ifdef WITH_HDF5
template<class RAG,class T, class EDGE_MAP, class NODE_MAP>
void exportGridRagSlicedAccumulateFeaturesT(py::module & ragModule){
ragModule.def("gridRagSlicedAccumulateFeatures",
[](
const RAG & rag,
nifty::marray::PyView<T, 3> data,
EDGE_MAP & edgeMap,
NODE_MAP & nodeMap,
size_t z0
){
{
py::gil_scoped_release allowThreads;
gridRagAccumulateFeatures(rag, data, edgeMap, nodeMap, z0);
}
},
py::arg("graph"),py::arg("data"),py::arg("edgeMap"),py::arg("nodeMap"),py::arg("z0")
);
}
template<class RAG,class T>
void exportGridRagSlicedAccumulateLabelsT(py::module & ragModule){
ragModule.def("gridRagSlicedAccumulateLabels",
[](
const RAG & rag,
const std::string & labels_file,
const std::string & labels_key
){
nifty::marray::PyView<T> nodeLabels({rag.numberOfNodes()});
{
vigra::HDF5File h5_file(labels_file, vigra::HDF5File::ReadOnly);
vigra::ChunkedArrayHDF5<3,T> labels(h5_file, labels_key);
py::gil_scoped_release allowThreads;
gridRagAccumulateLabels(rag, labels, nodeLabels);
}
return nodeLabels;
},
py::arg("graph"),py::arg("labels_file"),py::arg("labels_key")
);
}
#endif
void exportGraphAccumulator(py::module & ragModule, py::module & graphModule) {
typedef UndirectedGraph<> Graph;
// gridRagAccumulateFeatures
{
typedef DefaultAccEdgeMap<Graph, double> EdgeMapType;
typedef DefaultAccNodeMap<Graph, double> NodeMapType;
/* TODO test and export the vigra accumulators
typedef VigraAccEdgeMap<Graph, double> VigraEdgeMapType;
typedef VigraAccNodeMap<Graph, double> VigraNodeMapType;
// vigra edge map
py::class_<VigraAccEdgeMap>(ragModule, "VigraAccEdgeMapUndirectedGraph")
.def("getFeatures",
[]() {
})
*/
// edge map
{
py::class_<EdgeMapType>(ragModule, "DefaultAccEdgeMapUndirectedGraph")
// move implementation to grid_rag_features.hxx instead?
.def("getFeatureMatrix",[](EdgeMapType * self){
marray::PyView<double> featMat({self->numberOfEdges(),self->numberOfFeatures()});
for(size_t e = 0; e < self->numberOfEdges(); e++) {
double feats[self->numberOfFeatures()];
self->getFeatures(e, feats);
// TODO acces row of the view instead
for(size_t f = 0; f < self->numberOfFeatures(); f++) {
featMat(e,f) = feats[f];
}
}
return featMat;
})
;
ragModule.def("defaultAccEdgeMap", [](const Graph & graph, const double minVal, const double maxVal){
EdgeMapType * ptr = nullptr;
{
py::gil_scoped_release allowThreads;
ptr = new EdgeMapType(graph, minVal, maxVal);
}
return ptr;
},
py::return_value_policy::take_ownership,
py::keep_alive<0, 1>(),
py::arg("graph"),py::arg("minVal"),py::arg("maxVal")
);
}
// node map
{
py::class_<NodeMapType>(ragModule, "DefaultAccNodeMapUndirectedGraph")
// move implementation to grid_rag_features.hxx instead?
.def("getFeatureMatrix",[](NodeMapType * self){
marray::PyView<double> featMat({self->numberOfNodes(),self->numberOfFeatures()});
for(size_t n = 0; n < self->numberOfNodes(); n++) {
double feats[self->numberOfFeatures()];
self->getFeatures(n, feats);
// TODO acces row of the view instead
for(size_t f = 0; f < self->numberOfFeatures(); f++) {
featMat(n,f) = feats[f];
}
}
return featMat;
})
;
ragModule.def("defaultAccNodeMap", [](const Graph & graph, const double minVal, const double maxVal){
NodeMapType * ptr = nullptr;
{
py::gil_scoped_release allowThreads;
ptr = new NodeMapType(graph, minVal, maxVal);
}
return ptr;
},
py::return_value_policy::take_ownership,
py::keep_alive<0, 1>(),
py::arg("graph"),py::arg("minVal"),py::arg("maxVal")
);
}
// accumulate features
typedef ExplicitLabelsGridRag<2, uint32_t> ExplicitLabelsGridRag2D;
typedef ExplicitLabelsGridRag<3, uint32_t> ExplicitLabelsGridRag3D;
exportGridRagAccumulateFeaturesT<ExplicitLabelsGridRag2D, float, 2, EdgeMapType, NodeMapType>(ragModule);
exportGridRagAccumulateFeaturesT<ExplicitLabelsGridRag3D, float, 3, EdgeMapType, NodeMapType>(ragModule);
// accumulate labels
exportGridRagAccumulateLabelsT<ExplicitLabelsGridRag2D, uint32_t, 2>(ragModule);
exportGridRagAccumulateLabelsT<ExplicitLabelsGridRag3D, uint32_t, 3>(ragModule);
// export sliced rag (only if we have hdf5 support)
#ifdef WITH_HDF5
typedef ChunkedLabelsGridRagSliced<uint32_t> ChunkedLabelsGridRagSliced;
exportGridRagSlicedAccumulateFeaturesT<ChunkedLabelsGridRagSliced, float, EdgeMapType, NodeMapType>(ragModule);
exportGridRagSlicedAccumulateLabelsT<ChunkedLabelsGridRagSliced, uint32_t>(ragModule);
#endif
}
}
} // end namespace graph
} // end namespace nifty
<commit_msg>Making mac build happy...<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "nifty/python/converter.hxx"
#include "nifty/graph/rag/grid_rag_features.hxx"
#ifdef WITH_HDF5
#include "vigra/multi_array_chunked_hdf5.hxx"
#include "nifty/graph/rag/grid_rag_features_chunked.hxx"
#endif
namespace py = pybind11;
namespace nifty{
namespace graph{
using namespace py;
template<class RAG,class T,size_t DATA_DIM, class EDGE_MAP, class NODE_MAP>
void exportGridRagAccumulateFeaturesT(py::module & ragModule){
ragModule.def("gridRagAccumulateFeatures",
[](
const RAG & rag,
nifty::marray::PyView<T, DATA_DIM> data,
EDGE_MAP & edgeMap,
NODE_MAP & nodeMap
){
{
py::gil_scoped_release allowThreads;
gridRagAccumulateFeatures(rag, data, edgeMap, nodeMap);
}
},
py::arg("graph"),py::arg("data"),py::arg("edgeMap"),py::arg("nodeMap")
);
}
template<class RAG,class T,size_t DATA_DIM>
void exportGridRagAccumulateLabelsT(py::module & ragModule){
ragModule.def("gridRagAccumulateLabels",
[](
const RAG & rag,
nifty::marray::PyView<T, DATA_DIM> labels
){
nifty::marray::PyView<T> nodeLabels({rag.numberOfNodes()});
{
py::gil_scoped_release allowThreads;
gridRagAccumulateLabels(rag, labels, nodeLabels);
}
return nodeLabels;
},
py::arg("graph"),py::arg("labels")
);
}
// export only if we have HDF5 support
#ifdef WITH_HDF5
template<class RAG,class T, class EDGE_MAP, class NODE_MAP>
void exportGridRagSlicedAccumulateFeaturesT(py::module & ragModule){
ragModule.def("gridRagSlicedAccumulateFeatures",
[](
const RAG & rag,
nifty::marray::PyView<T, 3> data,
EDGE_MAP & edgeMap,
NODE_MAP & nodeMap,
size_t z0
){
{
py::gil_scoped_release allowThreads;
gridRagAccumulateFeatures(rag, data, edgeMap, nodeMap, z0);
}
},
py::arg("graph"),py::arg("data"),py::arg("edgeMap"),py::arg("nodeMap"),py::arg("z0")
);
}
template<class RAG,class T>
void exportGridRagSlicedAccumulateLabelsT(py::module & ragModule){
ragModule.def("gridRagSlicedAccumulateLabels",
[](
const RAG & rag,
const std::string & labels_file,
const std::string & labels_key
){
nifty::marray::PyView<T> nodeLabels({rag.numberOfNodes()});
{
vigra::HDF5File h5_file(labels_file, vigra::HDF5File::ReadOnly);
vigra::ChunkedArrayHDF5<3,T> labels(h5_file, labels_key);
py::gil_scoped_release allowThreads;
gridRagAccumulateLabels(rag, labels, nodeLabels);
}
return nodeLabels;
},
py::arg("graph"),py::arg("labels_file"),py::arg("labels_key")
);
}
#endif
void exportGraphAccumulator(py::module & ragModule, py::module & graphModule) {
typedef UndirectedGraph<> Graph;
// gridRagAccumulateFeatures
{
typedef DefaultAccEdgeMap<Graph, double> EdgeMapType;
typedef DefaultAccNodeMap<Graph, double> NodeMapType;
/* TODO test and export the vigra accumulators
typedef VigraAccEdgeMap<Graph, double> VigraEdgeMapType;
typedef VigraAccNodeMap<Graph, double> VigraNodeMapType;
// vigra edge map
py::class_<VigraAccEdgeMap>(ragModule, "VigraAccEdgeMapUndirectedGraph")
.def("getFeatures",
[]() {
})
*/
// edge map
{
py::class_<EdgeMapType>(ragModule, "DefaultAccEdgeMapUndirectedGraph")
// move implementation to grid_rag_features.hxx instead?
.def("getFeatureMatrix",[](EdgeMapType * self){
marray::PyView<double> featMat({self->numberOfEdges(),self->numberOfFeatures()});
for(size_t e = 0; e < self->numberOfEdges(); e++) {
double feats[self->numberOfFeatures()];
self->getFeatures(e, feats);
// TODO acces row of the view instead
for(size_t f = 0; f < self->numberOfFeatures(); f++) {
featMat(e,f) = feats[f];
}
}
return featMat;
})
;
ragModule.def("defaultAccEdgeMap", [](const Graph & graph, const double minVal, const double maxVal){
EdgeMapType * ptr = nullptr;
{
py::gil_scoped_release allowThreads;
ptr = new EdgeMapType(graph, minVal, maxVal);
}
return ptr;
},
py::return_value_policy::take_ownership,
py::keep_alive<0, 1>(),
py::arg("graph"),py::arg("minVal"),py::arg("maxVal")
);
}
// node map
{
py::class_<NodeMapType>(ragModule, "DefaultAccNodeMapUndirectedGraph")
// move implementation to grid_rag_features.hxx instead?
.def("getFeatureMatrix",[](NodeMapType * self){
size_t shape[] = {self->numberOfNodes(),self->numberOfFeatures()};
marray::PyView<double> featMat(shape, shape+2);
for(size_t n = 0; n < self->numberOfNodes(); n++) {
double feats[self->numberOfFeatures()];
self->getFeatures(n, feats);
// TODO acces row of the view instead
for(size_t f = 0; f < self->numberOfFeatures(); f++) {
featMat(n,f) = feats[f];
}
}
return featMat;
})
;
ragModule.def("defaultAccNodeMap", [](const Graph & graph, const double minVal, const double maxVal){
NodeMapType * ptr = nullptr;
{
py::gil_scoped_release allowThreads;
ptr = new NodeMapType(graph, minVal, maxVal);
}
return ptr;
},
py::return_value_policy::take_ownership,
py::keep_alive<0, 1>(),
py::arg("graph"),py::arg("minVal"),py::arg("maxVal")
);
}
// accumulate features
typedef ExplicitLabelsGridRag<2, uint32_t> ExplicitLabelsGridRag2D;
typedef ExplicitLabelsGridRag<3, uint32_t> ExplicitLabelsGridRag3D;
exportGridRagAccumulateFeaturesT<ExplicitLabelsGridRag2D, float, 2, EdgeMapType, NodeMapType>(ragModule);
exportGridRagAccumulateFeaturesT<ExplicitLabelsGridRag3D, float, 3, EdgeMapType, NodeMapType>(ragModule);
// accumulate labels
exportGridRagAccumulateLabelsT<ExplicitLabelsGridRag2D, uint32_t, 2>(ragModule);
exportGridRagAccumulateLabelsT<ExplicitLabelsGridRag3D, uint32_t, 3>(ragModule);
// export sliced rag (only if we have hdf5 support)
#ifdef WITH_HDF5
typedef ChunkedLabelsGridRagSliced<uint32_t> ChunkedLabelsGridRagSliced;
exportGridRagSlicedAccumulateFeaturesT<ChunkedLabelsGridRagSliced, float, EdgeMapType, NodeMapType>(ragModule);
exportGridRagSlicedAccumulateLabelsT<ChunkedLabelsGridRagSliced, uint32_t>(ragModule);
#endif
}
}
} // end namespace graph
} // end namespace nifty
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// See http://crbug.com/40764 for details.
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kEvalTestPage[] = "files/devtools/eval_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kPauseOnExceptionTestPage[] =
"files/devtools/pause_on_exception.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kSyntaxErrorTestPage[] =
"files/devtools/script_syntax_error.html";
const char kDebuggerStepTestPage[] =
"files/devtools/debugger_step.html";
const char kDebuggerClosurePage[] =
"files/devtools/debugger_closure.html";
const char kDebuggerIntrinsicPropertiesPage[] =
"files/devtools/debugger_intrinsic_properties.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPage(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kEvalTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<commit_msg>Mark DevToolsSanityTest.TestStepIn as flaky on CrOS.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// See http://crbug.com/40764 for details.
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kEvalTestPage[] = "files/devtools/eval_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kPauseOnExceptionTestPage[] =
"files/devtools/pause_on_exception.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kSyntaxErrorTestPage[] =
"files/devtools/script_syntax_error.html";
const char kDebuggerStepTestPage[] =
"files/devtools/debugger_step.html";
const char kDebuggerClosurePage[] =
"files/devtools/debugger_closure.html";
const char kDebuggerIntrinsicPropertiesPage[] =
"files/devtools/debugger_intrinsic_properties.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPage(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
#if defined(OS_CHROMEOS)
#define MAYBE_TestStepIn FLAKY_TestStepIn
#else
#define MAYBE_TestStepIn TestStepIn
#endif
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kEvalTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright 2017 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
namespace boosted_trees {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
REGISTER_RESOURCE_HANDLE_OP(QuantileStreamResource);
REGISTER_OP("QuantileAccumulatorIsInitialized")
.Input("quantile_accumulator_handle: resource")
.Output("is_initialized: bool")
.SetShapeFn(shape_inference::ScalarShape)
.Doc(R"doc(
Checks whether a quantile accumulator has been initialized.
)doc");
REGISTER_OP("CreateQuantileAccumulator")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.Attr("max_elements: int = 1099511627776") // 1 << 40
.Attr("epsilon: float")
.Attr("num_quantiles: int")
.Attr("generate_quantiles: bool=False")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.SetShapeFn([](shape_inference::InferenceContext* c) {
shape_inference::ShapeHandle unused_input;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &unused_input));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused_input));
return Status::OK();
})
.Doc(R"doc(
Creates a stateful accumulator for quantile summaries.
epsilon: Error bound on the quantile summary.
num_quantiles: Number of buckets that we create from the data.
stamp_token: Token to use as the initial value of the resource stamp.
quantile_accumulator_handle: The handle to the accumulator.
)doc");
REGISTER_OP("QuantileAccumulatorAddSummaries")
.Attr("num_resource_handles: int >= 1")
.Input("quantile_accumulator_handles: num_resource_handles * resource")
.Input("stamp_token: int64")
.Input("summaries: num_resource_handles * string")
.SetShapeFn([](InferenceContext* c) {
int num_resource_handles;
TF_RETURN_IF_ERROR(
c->GetAttr("num_resource_handles", &num_resource_handles));
// All the inputs are scalars.
shape_inference::ShapeHandle unused_input;
for (int i = 0; i < 2 * num_resource_handles + 1; ++i) {
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 0, &unused_input));
}
return Status::OK();
})
.Doc(R"doc(
Adds each quantile summary to its stream.
quantile_accumulator_handles: The handles to the quantile stream resources.
stamp_token: Stamp token to validate the Read/Write operation.
summaries: A list of serialized QuantileSummaryState.
)doc");
REGISTER_OP("QuantileAccumulatorGetBuckets")
.Attr("num_resource_handles: int >= 1")
.Input("quantile_accumulator_handles: num_resource_handles * resource")
.Input("stamp_token: int64")
.Output("are_buckets_ready: num_resource_handles * bool")
.Output("buckets: num_resource_handles * float")
.SetShapeFn([](InferenceContext* c) {
int num_resource_handles;
TF_RETURN_IF_ERROR(
c->GetAttr("num_resource_handles", &num_resource_handles));
for (int i = 0; i < num_resource_handles; ++i) {
c->set_output(i, c->Scalar());
c->set_output(i + num_resource_handles, c->Vector(c->UnknownDim()));
}
return Status::OK();
})
.Doc(R"doc(
Returns quantile buckets created during previous flush of the accumulator.
quantile_accumulator_handles: The handles to the quantile stream resources.
stamp_token: Stamp token to validate the Read/Write operation.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile summary representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("QuantileAccumulatorFlush")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("next_stamp_token: int64")
.Doc(R"doc(
Resets quantile summary streams for each column with a new token.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
next_stamp_token: Stamp token to be used for the next iteration.
)doc");
REGISTER_OP("QuantileAccumulatorFlushSummary")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("next_stamp_token: int64")
.Output("output: string")
.Doc(R"doc(
Resets quantile summary stream and returns the summary.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
next_stamp_token: Stamp token to be used for the next iteration.
output: A scalar string that is the a summary of the accumulator.
)doc");
REGISTER_OP("QuantileAccumulatorSerialize")
.Input("quantile_accumulator_handle: resource")
.Output("stamp_token: int64")
.Output("stream_state: string")
.Output("are_buckets_ready: bool")
.Output("buckets: float")
.Doc(R"doc(
Serializes the state of the given resource.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
stream_state: A serialized QuantileStreamState.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile buckets representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("QuantileAccumulatorDeserialize")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("stream_state: string")
.Input("are_buckets_ready: bool")
.Input("buckets: float")
.Doc(R"doc(
Serializes the state of the given resource.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
stream_state: A serialized QuantileStreamState.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile summary representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("MakeQuantileSummaries")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Attr("epsilon: float")
.Input("dense_float_features: num_dense_features * float")
.Input("sparse_float_feature_indices: num_sparse_features * int64")
.Input("sparse_float_feature_values: num_sparse_features * float")
.Input("sparse_float_feature_shapes: num_sparse_features * int64")
.Input("example_weights: float")
.Output("dense_summaries: num_dense_features * string")
.Output("sparse_summaries: num_sparse_features * string")
.SetShapeFn([](InferenceContext* c) {
int num_dense_features;
TF_RETURN_IF_ERROR(c->GetAttr("num_dense_features", &num_dense_features));
int num_sparse_features;
TF_RETURN_IF_ERROR(
c->GetAttr("num_sparse_features", &num_sparse_features));
ShapeHandle example_weights_shape;
int example_weights_index = num_dense_features + num_sparse_features * 3;
TF_RETURN_IF_ERROR(c->WithRank(c->input(example_weights_index), 2,
&example_weights_shape));
for (int i = 0; i < num_dense_features; ++i) {
ShapeHandle dense_feature_shape;
DimensionHandle unused_dim;
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 2, &dense_feature_shape));
TF_RETURN_IF_ERROR(c->Merge(c->Dim(dense_feature_shape, 0),
c->Dim(example_weights_shape, 0),
&unused_dim));
c->set_output(i, c->Scalar());
}
for (int i = 0; i < num_sparse_features; ++i) {
c->set_output(i + num_dense_features, c->Scalar());
}
return Status::OK();
})
.Doc(R"doc(
Creates a summary for the given features.
num_dense_features: Number of dense feature groups to compute quantiles on.
num_sparse_features: Number of sparse feature groups to compute quantiles on.
epsilon: Error bound on the computed summary.
dense_float_features: A list of vectors which contains dense values.
sparse_float_feature_indices: List of rank 2 tensors containing the sparse float
feature indices.
sparse_float_feature_values: List of rank 1 tensors containing the sparse float
feature values.
sparse_float_feature_shapes: List of rank 1 tensors containing the shape of the
float feature.
example_weights: Rank 2 (N, 1) tensor of per-example weights. Should match
dense and sparse features shape.
dense_summaries: A list of serialized QuantileSummaryState for dense columns.
sparse_summaries: A list of serialized QuantileSummaryState for sparse columns.
)doc");
REGISTER_OP("QuantileBuckets")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Attr("dense_config: list(string)")
.Attr("sparse_config: list(string)")
.Input("dense_float_features: num_dense_features * float")
.Input("sparse_float_feature_indices: num_sparse_features * int64")
.Input("sparse_float_feature_values: num_sparse_features * float")
.Input("sparse_float_feature_shapes: num_sparse_features * int64")
.Input("example_weights: float")
.Output("dense_buckets: num_dense_features * float")
.Output("sparse_buckets: num_sparse_features * float")
.Doc(R"doc(
Computes quantile buckets for a given list of dense and sparse features with
given example weights.
num_dense_features: Number of dense feature groups to compute quantiles on.
num_sparse_features: Number of sparse feature groups to compute quantiles on.
dense_config: Config for computing buckets for dense values.
Each entry is QuantileConfig proto.
sparse_config: Config for computing buckets for sparse feature values.
Each entry is QuantileConfig proto.
dense_float_features: A list of vectors which contains dense values.
sparse_float_feature_indices: List of rank 2 tensors containing the sparse float
feature indices.
sparse_float_feature_values: List of rank 1 tensors containing the sparse float
feature values.
sparse_float_feature_shapes: List of rank 1 tensors containing the shape of the
float feature.
example_weights: Rank 1 tensor containing the example weight tensor.
dense_buckets: Output quantile summary for each dense float tensor
representing boundaries each with "num_quantile" elements.
sparse_buckets: Output quantile summary for each sparse float value tensor
representing boundaries each with "num_quantile" elements.
)doc");
REGISTER_OP("Quantiles")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Input("dense_values: num_dense_features * float")
.Input("sparse_values: num_sparse_features * float")
.Input("dense_buckets: num_dense_features * float")
.Input("sparse_buckets: num_sparse_features * float")
.Input("sparse_indices: num_sparse_features * int64")
.Output("dense_quantiles: num_dense_features * int32")
.Output("sparse_quantiles: num_sparse_features * int32")
.Doc(R"doc(
Computes quantile for each a given list of dense and sparse feature values using
the given buckets.
num_dense_features: Number of dense feature groups to generate quantiles for.
num_sparse_features: Number of sparse feature groups to generate quantiles for.
dense_values: List of rank 1 tensors containing the dense values.
sparse_values: List of rank 1 tensors containing the sparse feature values.
dense_buckets: Quantile summary for each of the dense float tensor.
sparse_buckets: Quantile summary for each of the sparse feature float tensor.
sparse_indices: List of rank 2 tensors with indices for sparse float
tensors.
dense_quantiles: Rank 2 tensors representing associated quantiles for each of
dense float tensors and the dimension.
sparse_quantiles: Rank 2 tensors representing associated quantiles for each of
the sparse feature tensors for each of sparse feature dimensions:
[quantile id, dimension id].
)doc");
REGISTER_OP("BucketizeWithInputBoundaries")
.Input("input: T")
.Input("boundaries: float")
.Output("output: int32")
.Attr("T: {int32, int64, float, double}")
.SetShapeFn(shape_inference::UnchangedShape)
.Doc(R"doc(
Bucketizes 'input' based on 'boundaries'. This function is similar to Bucketize
op in core math_ops, except that boundaries are specified using an input tensor,
as compared with a fixed attribute in Bucketize().
For example, if the inputs are
boundaries = [0, 10, 100]
input = [[-5, 10000]
[150, 10]
[5, 100]]
then the output will be
output = [[0, 3]
[3, 2]
[1, 3]]
input: Any shape of Tensor contains with numeric type.
boundaries: A vector Tensor of sorted floats specifies the boundaries
of the buckets.
output: Same shape as 'input', where each value of input is replaced with its corresponding bucket index.
)doc");
} // namespace boosted_trees
} // namespace tensorflow
<commit_msg>boosted_trees: infer the output shapes of Quantiles Op from the input shapes.<commit_after>// Copyright 2017 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
namespace boosted_trees {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
REGISTER_RESOURCE_HANDLE_OP(QuantileStreamResource);
REGISTER_OP("QuantileAccumulatorIsInitialized")
.Input("quantile_accumulator_handle: resource")
.Output("is_initialized: bool")
.SetShapeFn(shape_inference::ScalarShape)
.Doc(R"doc(
Checks whether a quantile accumulator has been initialized.
)doc");
REGISTER_OP("CreateQuantileAccumulator")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.Attr("max_elements: int = 1099511627776") // 1 << 40
.Attr("epsilon: float")
.Attr("num_quantiles: int")
.Attr("generate_quantiles: bool=False")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.SetShapeFn([](shape_inference::InferenceContext* c) {
shape_inference::ShapeHandle unused_input;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &unused_input));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused_input));
return Status::OK();
})
.Doc(R"doc(
Creates a stateful accumulator for quantile summaries.
epsilon: Error bound on the quantile summary.
num_quantiles: Number of buckets that we create from the data.
stamp_token: Token to use as the initial value of the resource stamp.
quantile_accumulator_handle: The handle to the accumulator.
)doc");
REGISTER_OP("QuantileAccumulatorAddSummaries")
.Attr("num_resource_handles: int >= 1")
.Input("quantile_accumulator_handles: num_resource_handles * resource")
.Input("stamp_token: int64")
.Input("summaries: num_resource_handles * string")
.SetShapeFn([](InferenceContext* c) {
int num_resource_handles;
TF_RETURN_IF_ERROR(
c->GetAttr("num_resource_handles", &num_resource_handles));
// All the inputs are scalars.
shape_inference::ShapeHandle unused_input;
for (int i = 0; i < 2 * num_resource_handles + 1; ++i) {
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 0, &unused_input));
}
return Status::OK();
})
.Doc(R"doc(
Adds each quantile summary to its stream.
quantile_accumulator_handles: The handles to the quantile stream resources.
stamp_token: Stamp token to validate the Read/Write operation.
summaries: A list of serialized QuantileSummaryState.
)doc");
REGISTER_OP("QuantileAccumulatorGetBuckets")
.Attr("num_resource_handles: int >= 1")
.Input("quantile_accumulator_handles: num_resource_handles * resource")
.Input("stamp_token: int64")
.Output("are_buckets_ready: num_resource_handles * bool")
.Output("buckets: num_resource_handles * float")
.SetShapeFn([](InferenceContext* c) {
int num_resource_handles;
TF_RETURN_IF_ERROR(
c->GetAttr("num_resource_handles", &num_resource_handles));
for (int i = 0; i < num_resource_handles; ++i) {
c->set_output(i, c->Scalar());
c->set_output(i + num_resource_handles, c->Vector(c->UnknownDim()));
}
return Status::OK();
})
.Doc(R"doc(
Returns quantile buckets created during previous flush of the accumulator.
quantile_accumulator_handles: The handles to the quantile stream resources.
stamp_token: Stamp token to validate the Read/Write operation.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile summary representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("QuantileAccumulatorFlush")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("next_stamp_token: int64")
.Doc(R"doc(
Resets quantile summary streams for each column with a new token.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
next_stamp_token: Stamp token to be used for the next iteration.
)doc");
REGISTER_OP("QuantileAccumulatorFlushSummary")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("next_stamp_token: int64")
.Output("output: string")
.Doc(R"doc(
Resets quantile summary stream and returns the summary.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
next_stamp_token: Stamp token to be used for the next iteration.
output: A scalar string that is the a summary of the accumulator.
)doc");
REGISTER_OP("QuantileAccumulatorSerialize")
.Input("quantile_accumulator_handle: resource")
.Output("stamp_token: int64")
.Output("stream_state: string")
.Output("are_buckets_ready: bool")
.Output("buckets: float")
.Doc(R"doc(
Serializes the state of the given resource.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
stream_state: A serialized QuantileStreamState.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile buckets representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("QuantileAccumulatorDeserialize")
.Input("quantile_accumulator_handle: resource")
.Input("stamp_token: int64")
.Input("stream_state: string")
.Input("are_buckets_ready: bool")
.Input("buckets: float")
.Doc(R"doc(
Serializes the state of the given resource.
quantile_accumulator_handle: The handle to the accumulator.
stamp_token: Stamp token for Read/Write operations.
Any operation with a mismatching token will be dropped.
stream_state: A serialized QuantileStreamState.
are_buckets_ready: Whether the buckets are ready or not.
buckets: Output quantile summary representing boundaries with "num_quantile"
elements.
)doc");
REGISTER_OP("MakeQuantileSummaries")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Attr("epsilon: float")
.Input("dense_float_features: num_dense_features * float")
.Input("sparse_float_feature_indices: num_sparse_features * int64")
.Input("sparse_float_feature_values: num_sparse_features * float")
.Input("sparse_float_feature_shapes: num_sparse_features * int64")
.Input("example_weights: float")
.Output("dense_summaries: num_dense_features * string")
.Output("sparse_summaries: num_sparse_features * string")
.SetShapeFn([](InferenceContext* c) {
int num_dense_features;
TF_RETURN_IF_ERROR(c->GetAttr("num_dense_features", &num_dense_features));
int num_sparse_features;
TF_RETURN_IF_ERROR(
c->GetAttr("num_sparse_features", &num_sparse_features));
ShapeHandle example_weights_shape;
int example_weights_index = num_dense_features + num_sparse_features * 3;
TF_RETURN_IF_ERROR(c->WithRank(c->input(example_weights_index), 2,
&example_weights_shape));
for (int i = 0; i < num_dense_features; ++i) {
ShapeHandle dense_feature_shape;
DimensionHandle unused_dim;
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 2, &dense_feature_shape));
TF_RETURN_IF_ERROR(c->Merge(c->Dim(dense_feature_shape, 0),
c->Dim(example_weights_shape, 0),
&unused_dim));
c->set_output(i, c->Scalar());
}
for (int i = 0; i < num_sparse_features; ++i) {
c->set_output(i + num_dense_features, c->Scalar());
}
return Status::OK();
})
.Doc(R"doc(
Creates a summary for the given features.
num_dense_features: Number of dense feature groups to compute quantiles on.
num_sparse_features: Number of sparse feature groups to compute quantiles on.
epsilon: Error bound on the computed summary.
dense_float_features: A list of vectors which contains dense values.
sparse_float_feature_indices: List of rank 2 tensors containing the sparse float
feature indices.
sparse_float_feature_values: List of rank 1 tensors containing the sparse float
feature values.
sparse_float_feature_shapes: List of rank 1 tensors containing the shape of the
float feature.
example_weights: Rank 2 (N, 1) tensor of per-example weights. Should match
dense and sparse features shape.
dense_summaries: A list of serialized QuantileSummaryState for dense columns.
sparse_summaries: A list of serialized QuantileSummaryState for sparse columns.
)doc");
REGISTER_OP("QuantileBuckets")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Attr("dense_config: list(string)")
.Attr("sparse_config: list(string)")
.Input("dense_float_features: num_dense_features * float")
.Input("sparse_float_feature_indices: num_sparse_features * int64")
.Input("sparse_float_feature_values: num_sparse_features * float")
.Input("sparse_float_feature_shapes: num_sparse_features * int64")
.Input("example_weights: float")
.Output("dense_buckets: num_dense_features * float")
.Output("sparse_buckets: num_sparse_features * float")
.Doc(R"doc(
Computes quantile buckets for a given list of dense and sparse features with
given example weights.
num_dense_features: Number of dense feature groups to compute quantiles on.
num_sparse_features: Number of sparse feature groups to compute quantiles on.
dense_config: Config for computing buckets for dense values.
Each entry is QuantileConfig proto.
sparse_config: Config for computing buckets for sparse feature values.
Each entry is QuantileConfig proto.
dense_float_features: A list of vectors which contains dense values.
sparse_float_feature_indices: List of rank 2 tensors containing the sparse float
feature indices.
sparse_float_feature_values: List of rank 1 tensors containing the sparse float
feature values.
sparse_float_feature_shapes: List of rank 1 tensors containing the shape of the
float feature.
example_weights: Rank 1 tensor containing the example weight tensor.
dense_buckets: Output quantile summary for each dense float tensor
representing boundaries each with "num_quantile" elements.
sparse_buckets: Output quantile summary for each sparse float value tensor
representing boundaries each with "num_quantile" elements.
)doc");
REGISTER_OP("Quantiles")
.Attr("num_dense_features: int >= 0")
.Attr("num_sparse_features: int >= 0")
.Input("dense_values: num_dense_features * float")
.Input("sparse_values: num_sparse_features * float")
.Input("dense_buckets: num_dense_features * float")
.Input("sparse_buckets: num_sparse_features * float")
.Input("sparse_indices: num_sparse_features * int64")
.Output("dense_quantiles: num_dense_features * int32")
.Output("sparse_quantiles: num_sparse_features * int32")
.SetShapeFn([](InferenceContext* c) {
int num_dense_features;
TF_RETURN_IF_ERROR(c->GetAttr("num_dense_features", &num_dense_features));
int num_sparse_features;
TF_RETURN_IF_ERROR(
c->GetAttr("num_sparse_features", &num_sparse_features));
// Set output shapes (dense_quantiles and sparse_quantiles) by the
// relevant inputs (dense_values and sparse_values). Note that the output
// has an additional dimension for dimension_ids.
for (int i = 0; i < num_dense_features + num_sparse_features; ++i) {
c->set_output(i, c->MakeShape({c->Dim(c->input(i), 0), 2}));
}
return Status::OK();
})
.Doc(R"doc(
Computes quantile for each a given list of dense and sparse feature values using
the given buckets.
num_dense_features: Number of dense feature groups to generate quantiles for.
num_sparse_features: Number of sparse feature groups to generate quantiles for.
dense_values: List of rank 1 tensors containing the dense values.
sparse_values: List of rank 1 tensors containing the sparse feature values.
dense_buckets: Quantile summary for each of the dense float tensor.
sparse_buckets: Quantile summary for each of the sparse feature float tensor.
sparse_indices: List of rank 2 tensors with indices for sparse float
tensors.
dense_quantiles: Rank 2 tensors representing associated quantiles for each of
dense float tensors and the dimension.
sparse_quantiles: Rank 2 tensors representing associated quantiles for each of
the sparse feature tensors for each of sparse feature dimensions:
[quantile id, dimension id].
)doc");
REGISTER_OP("BucketizeWithInputBoundaries")
.Input("input: T")
.Input("boundaries: float")
.Output("output: int32")
.Attr("T: {int32, int64, float, double}")
.SetShapeFn(shape_inference::UnchangedShape)
.Doc(R"doc(
Bucketizes 'input' based on 'boundaries'. This function is similar to Bucketize
op in core math_ops, except that boundaries are specified using an input tensor,
as compared with a fixed attribute in Bucketize().
For example, if the inputs are
boundaries = [0, 10, 100]
input = [[-5, 10000]
[150, 10]
[5, 100]]
then the output will be
output = [[0, 3]
[3, 2]
[1, 3]]
input: Any shape of Tensor contains with numeric type.
boundaries: A vector Tensor of sorted floats specifies the boundaries
of the buckets.
output: Same shape as 'input', where each value of input is replaced with its corresponding bucket index.
)doc");
} // namespace boosted_trees
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
"files/workers/workers_ui_shared_worker.html";
void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name)),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
}
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest()
: window_(NULL),
inspected_rvh_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
RunTestFuntion(window_, test_name.c_str());
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_LOADED:
case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
public:
explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
ui_test_utils::RunMessageLoop();
}
private:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == content::NOTIFICATION_LOAD_STOP) {
if (done_)
return;
done_ = true;
MessageLoopForUI::current()->Quit();
}
}
NotificationRegistrar registrar_;
bool done_;
DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};
class WorkerDevToolsSanityTest : public InProcessBrowserTest {
public:
WorkerDevToolsSanityTest() : window_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const char* test_name, const char* test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
OpenDevToolsWindowForFirstSharedWorker();
RunTestFuntion(window_, test_name);
CloseDevToolsWindow();
}
static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
bool found = false;
for (; !iter.Done(); ++iter) {
WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
const WorkerProcessHost::Instances& instances = worker->instances();
for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
i != instances.end(); ++i) {
if (!i->shared())
continue;
WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
worker->id(), i->worker_route_id());
found = true;
break;
}
}
if (found) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new MessageLoop::QuitTask);
} else if (attempt < 30) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
100);
} else {
FAIL() << "Shared worker not found.";
}
}
void OpenDevToolsWindowForFirstSharedWorker() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
ui_test_utils::RunMessageLoop();
window_ = static_cast<DevToolsWindow*>(
DevToolsClientHost::GetDevToolsClientHostForTest());
ASSERT_TRUE(window_ != NULL);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
if (client_contents->IsLoading()) {
LoadStopObserver(
Source<NavigationController>(&client_contents->controller()));
}
}
void CloseDevToolsWindow() {
Browser* browser = window_->browser();
browser->CloseAllTabs();
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
content::GetContentClient()->browser()->ClearInspectorSettings(
GetInspectedTab()->render_view_host());
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
OpenDevToolsWindow("about:blank");
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window_->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
ASSERT_EQ("function", result) << "DevTools front-end is broken.";
CloseDevToolsWindow();
}
#if defined(OS_WINDOWS)
// Flakily fails: http://crbug.com/89845
#define MAYBE_InspectSharedWorker FLAKY_InspectSharedWorker
#else
#define MAYBE_InspectSharedWorker InspectSharedWorker
#endif
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, MAYBE_InspectSharedWorker) {
RunTest("testSharedWorker", kSharedWorkerTestPage);
}
} // namespace
<commit_msg>Extending the flaky test flag for the InspectSharedWorker interactive test to Linux and Chrome OS.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
"files/workers/workers_ui_shared_worker.html";
void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name)),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
}
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest()
: window_(NULL),
inspected_rvh_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
RunTestFuntion(window_, test_name.c_str());
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_LOADED:
case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
public:
explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
ui_test_utils::RunMessageLoop();
}
private:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == content::NOTIFICATION_LOAD_STOP) {
if (done_)
return;
done_ = true;
MessageLoopForUI::current()->Quit();
}
}
NotificationRegistrar registrar_;
bool done_;
DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};
class WorkerDevToolsSanityTest : public InProcessBrowserTest {
public:
WorkerDevToolsSanityTest() : window_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const char* test_name, const char* test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
OpenDevToolsWindowForFirstSharedWorker();
RunTestFuntion(window_, test_name);
CloseDevToolsWindow();
}
static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
bool found = false;
for (; !iter.Done(); ++iter) {
WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
const WorkerProcessHost::Instances& instances = worker->instances();
for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
i != instances.end(); ++i) {
if (!i->shared())
continue;
WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
worker->id(), i->worker_route_id());
found = true;
break;
}
}
if (found) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new MessageLoop::QuitTask);
} else if (attempt < 30) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
100);
} else {
FAIL() << "Shared worker not found.";
}
}
void OpenDevToolsWindowForFirstSharedWorker() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
ui_test_utils::RunMessageLoop();
window_ = static_cast<DevToolsWindow*>(
DevToolsClientHost::GetDevToolsClientHostForTest());
ASSERT_TRUE(window_ != NULL);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
if (client_contents->IsLoading()) {
LoadStopObserver(
Source<NavigationController>(&client_contents->controller()));
}
}
void CloseDevToolsWindow() {
Browser* browser = window_->browser();
browser->CloseAllTabs();
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
content::GetContentClient()->browser()->ClearInspectorSettings(
GetInspectedTab()->render_view_host());
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
OpenDevToolsWindow("about:blank");
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window_->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
ASSERT_EQ("function", result) << "DevTools front-end is broken.";
CloseDevToolsWindow();
}
#if defined(OS_WINDOWS) || defined(OS_LINUX) || defined(OS_CHROMEOS)
// Flakily fails: http://crbug.com/89845
#define MAYBE_InspectSharedWorker FLAKY_InspectSharedWorker
#else
#define MAYBE_InspectSharedWorker InspectSharedWorker
#endif
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, MAYBE_InspectSharedWorker) {
RunTest("testSharedWorker", kSharedWorkerTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CmdLineOutput.hpp"
#include "Config.hpp"
#include "Converter.hpp"
#include "UTF8Util.hpp"
using namespace opencc;
Optional<string> inputFileName = Optional<string>::Null();
Optional<string> outputFileName = Optional<string>::Null();
string configFileName;
bool noFlush;
Config config;
ConverterPtr converter;
FILE* GetOutputStream() {
if (outputFileName.IsNull()) {
return stdout;
} else {
FILE* fp = fopen(outputFileName.Get().c_str(), "w");
if (!fp) {
throw FileNotWritable(outputFileName.Get());
}
return fp;
}
}
void ConvertLineByLine() {
std::istream& inputStream = std::cin;
FILE* fout = GetOutputStream();
bool isFirstLine = true;
while (!inputStream.eof()) {
if (!isFirstLine) {
fputs("\n", fout);
} else {
isFirstLine = false;
}
string line;
std::getline(inputStream, line);
const string& converted = converter->Convert(line);
fputs(converted.c_str(), fout);
if (!noFlush) {
// Flush every line if the output stream is stdout.
fflush(fout);
}
}
fclose(fout);
}
void Convert() {
const int BUFFER_SIZE = 1024 * 1024;
static bool bufferInitialized = false;
static string buffer;
static char* bufferBegin;
static const char* bufferEnd;
static char* bufferPtr;
static size_t bufferSizeAvailble;
if (!bufferInitialized) {
bufferInitialized = true;
buffer.resize(BUFFER_SIZE + 1);
bufferBegin = const_cast<char*>(buffer.c_str());
bufferEnd = buffer.c_str() + BUFFER_SIZE;
bufferPtr = bufferBegin;
bufferSizeAvailble = BUFFER_SIZE;
}
FILE* fin = fopen(inputFileName.Get().c_str(), "r");
if (!fin) {
throw FileNotFound(inputFileName.Get());
}
FILE* fout = GetOutputStream();
while (!feof(fin)) {
size_t length = fread(bufferPtr, sizeof(char), bufferSizeAvailble, fin);
bufferPtr[length] = '\0';
size_t remainingLength = 0;
string remainingTemp;
if (length == bufferSizeAvailble) {
// fread may breaks UTF8 character
// Find the end of last character
char* lastChPtr = bufferBegin;
while (lastChPtr < bufferEnd) {
size_t nextCharLen = UTF8Util::NextCharLength(lastChPtr);
if (lastChPtr + nextCharLen > bufferEnd) {
break;
}
lastChPtr += nextCharLen;
}
remainingLength = bufferEnd - lastChPtr;
if (remainingLength > 0) {
remainingTemp = UTF8Util::FromSubstr(lastChPtr, remainingLength);
*lastChPtr = '\0';
}
}
// Perform conversion
const string& converted = converter->Convert(buffer);
fputs(converted.c_str(), fout);
if (!noFlush) {
// Flush every line if the output stream is stdout.
fflush(fout);
}
// Reset pointer
bufferPtr = bufferBegin + remainingLength;
bufferSizeAvailble = BUFFER_SIZE - remainingLength;
if (remainingLength > 0) {
strncpy(bufferBegin, remainingTemp.c_str(), remainingLength);
}
}
fclose(fout);
}
int main(int argc, const char* argv[]) {
try {
TCLAP::CmdLine cmd("Open Chinese Convert (OpenCC) Command Line Tool", ' ',
VERSION);
CmdLineOutput cmdLineOutput;
cmd.setOutput(&cmdLineOutput);
TCLAP::ValueArg<string> configArg(
"c", "config", "Configuration file", false /* required */,
"s2t.json" /* default */, "file" /* type */, cmd);
TCLAP::ValueArg<string> outputArg("o", "output", "Write converted text to",
false /* required */, "" /* default */,
"file" /* type */, cmd);
TCLAP::ValueArg<string> inputArg("i", "input", "Read original text from",
false /* required */, "" /* default */,
"file" /* type */, cmd);
TCLAP::ValueArg<bool> noFlushArg(
"", "noflush", "Disable flush for every line", false /* required */,
false /* default */, "bool" /* type */, cmd);
cmd.parse(argc, argv);
configFileName = configArg.getValue();
noFlush = noFlushArg.getValue();
if (inputArg.isSet()) {
inputFileName = Optional<string>(inputArg.getValue());
}
if (outputArg.isSet()) {
outputFileName = Optional<string>(outputArg.getValue());
noFlush = true;
}
converter = config.NewFromFile(configFileName);
bool lineByLine = inputFileName.IsNull();
if (lineByLine) {
ConvertLineByLine();
} else {
Convert();
}
} catch (TCLAP::ArgException& e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId()
<< std::endl;
} catch (Exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>OpenCC CLI: if -i and -o are *literally* the same, create a temporary file for input<commit_after>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CmdLineOutput.hpp"
#include "Config.hpp"
#include "Converter.hpp"
#include "UTF8Util.hpp"
using namespace opencc;
Optional<string> inputFileName = Optional<string>::Null();
Optional<string> outputFileName = Optional<string>::Null();
string configFileName;
bool noFlush;
Config config;
ConverterPtr converter;
FILE* GetOutputStream() {
if (outputFileName.IsNull()) {
return stdout;
} else {
FILE* fp = fopen(outputFileName.Get().c_str(), "w");
if (!fp) {
throw FileNotWritable(outputFileName.Get());
}
return fp;
}
}
void ConvertLineByLine() {
std::istream& inputStream = std::cin;
FILE* fout = GetOutputStream();
bool isFirstLine = true;
while (!inputStream.eof()) {
if (!isFirstLine) {
fputs("\n", fout);
} else {
isFirstLine = false;
}
string line;
std::getline(inputStream, line);
const string& converted = converter->Convert(line);
fputs(converted.c_str(), fout);
if (!noFlush) {
// Flush every line if the output stream is stdout.
fflush(fout);
}
}
fclose(fout);
}
void Convert(string inputFileName) {
const int BUFFER_SIZE = 1024 * 1024;
static bool bufferInitialized = false;
static string buffer;
static char* bufferBegin;
static const char* bufferEnd;
static char* bufferPtr;
static size_t bufferSizeAvailble;
if (!bufferInitialized) {
bufferInitialized = true;
buffer.resize(BUFFER_SIZE + 1);
bufferBegin = const_cast<char*>(buffer.c_str());
bufferEnd = buffer.c_str() + BUFFER_SIZE;
bufferPtr = bufferBegin;
bufferSizeAvailble = BUFFER_SIZE;
}
bool needToRemove = false;
if (!outputFileName.IsNull() && inputFileName == outputFileName.Get()) {
// Special case: input == output
const string tempFileName = std::tmpnam(nullptr);
std::ifstream src(inputFileName, std::ios::binary);
std::ofstream dst(tempFileName, std::ios::binary);
dst << src.rdbuf();
dst.close();
inputFileName = tempFileName;
needToRemove = true;
}
FILE* fin = fopen(inputFileName.c_str(), "r");
if (!fin) {
throw FileNotFound(inputFileName);
}
FILE* fout = GetOutputStream();
while (!feof(fin)) {
size_t length = fread(bufferPtr, sizeof(char), bufferSizeAvailble, fin);
bufferPtr[length] = '\0';
size_t remainingLength = 0;
string remainingTemp;
if (length == bufferSizeAvailble) {
// fread may breaks UTF8 character
// Find the end of last character
char* lastChPtr = bufferBegin;
while (lastChPtr < bufferEnd) {
size_t nextCharLen = UTF8Util::NextCharLength(lastChPtr);
if (lastChPtr + nextCharLen > bufferEnd) {
break;
}
lastChPtr += nextCharLen;
}
remainingLength = bufferEnd - lastChPtr;
if (remainingLength > 0) {
remainingTemp = UTF8Util::FromSubstr(lastChPtr, remainingLength);
*lastChPtr = '\0';
}
}
// Perform conversion
const string& converted = converter->Convert(buffer);
fputs(converted.c_str(), fout);
if (!noFlush) {
// Flush every line if the output stream is stdout.
fflush(fout);
}
// Reset pointer
bufferPtr = bufferBegin + remainingLength;
bufferSizeAvailble = BUFFER_SIZE - remainingLength;
if (remainingLength > 0) {
strncpy(bufferBegin, remainingTemp.c_str(), remainingLength);
}
}
fclose(fout);
if (needToRemove) {
// Remove temporary file.
std::remove(inputFileName.c_str());
}
}
int main(int argc, const char* argv[]) {
try {
TCLAP::CmdLine cmd("Open Chinese Convert (OpenCC) Command Line Tool", ' ',
VERSION);
CmdLineOutput cmdLineOutput;
cmd.setOutput(&cmdLineOutput);
TCLAP::ValueArg<string> configArg(
"c", "config", "Configuration file", false /* required */,
"s2t.json" /* default */, "file" /* type */, cmd);
TCLAP::ValueArg<string> outputArg(
"o", "output", "Write converted text to <file>.", false /* required */,
"" /* default */, "file" /* type */, cmd);
TCLAP::ValueArg<string> inputArg(
"i", "input", "Read original text from <file>.", false /* required */,
"" /* default */, "file" /* type */, cmd);
TCLAP::ValueArg<bool> noFlushArg(
"", "noflush", "Disable flush for every line", false /* required */,
false /* default */, "bool" /* type */, cmd);
cmd.parse(argc, argv);
configFileName = configArg.getValue();
noFlush = noFlushArg.getValue();
if (inputArg.isSet()) {
inputFileName = Optional<string>(inputArg.getValue());
}
if (outputArg.isSet()) {
outputFileName = Optional<string>(outputArg.getValue());
noFlush = true;
}
converter = config.NewFromFile(configFileName);
bool lineByLine = inputFileName.IsNull();
if (lineByLine) {
ConvertLineByLine();
} else {
Convert(inputFileName.Get());
}
} catch (TCLAP::ArgException& e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId()
<< std::endl;
} catch (Exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 20109 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
// This test failed at times on the Vista dbg builder and has been marked as
// flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) {
// We need a.com to be a little bit slow to trigger a race condition.
host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
host_resolver()->AddRule("b.com", "127.0.0.1");
host_resolver()->AddRule("c.com", "127.0.0.1");
StartHTTPServer();
ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}
<commit_msg>Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!<commit_after>// Copyright (c) 20109 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
// EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare
// to re-enable without a real fix or at least adding more debugging info.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) {
// We need a.com to be a little bit slow to trigger a race condition.
host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
host_resolver()->AddRule("b.com", "127.0.0.1");
host_resolver()->AddRule("c.com", "127.0.0.1");
StartHTTPServer();
ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "net/dns/mock_host_resolver.h"
#if defined(OS_WIN)
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#endif
#if defined(USE_AURA) || defined(OS_MACOSX)
// Maximizing/fullscreen popup window doesn't work on aura's managed mode.
// See bug crbug.com/116305.
// Mac: http://crbug.com/103912
#define MAYBE_UpdateWindowShowState DISABLED_UpdateWindowShowState
#else
#define MAYBE_UpdateWindowShowState UpdateWindowShowState
#endif // defined(USE_AURA) || defined(OS_MACOSX)
// http://crbug.com/145639
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TabEvents DISABLED_TabEvents
#else
#define MAYBE_TabEvents TabEvents
#endif
class ExtensionApiNewTabTest : public ExtensionApiTest {
public:
ExtensionApiNewTabTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
// Override the default which InProcessBrowserTest adds if it doesn't see a
// homepage.
command_line->AppendSwitchASCII(
switches::kHomePage, chrome::kChromeUINewTabURL);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiNewTabTest, Tabs) {
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabAudible) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "audible.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMuted) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "muted.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_Tabs2 DISABLED_Tabs2
#else
#define MAYBE_Tabs2 Tabs2
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs2) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_;
}
// crbug.com/149924
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabDuplicate) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "duplicate.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabSize) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "tab_size.html")) << message_;
}
// Flaky on linux: http://crbug.com/396364
#if defined(OS_LINUX)
#define MAYBE_TabUpdate DISABLED_TabUpdate
#else
#define MAYBE_TabUpdate TabUpdate
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabUpdate) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "update.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_TabMove DISABLED_TabMove
#else
#define MAYBE_TabMove TabMove
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabRelativeURLs) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "query.html")) << message_;
}
// Flaky on windows: http://crbug.com/239022
#if defined(OS_WIN)
#define MAYBE_TabHighlight DISABLED_TabHighlight
#else
#define MAYBE_TabHighlight TabHighlight
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabHighlight) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "highlight.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_TabOpener DISABLED_TabOpener
#else
#define MAYBE_TabOpener TabOpener
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOpener) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "opener.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabGetCurrent) {
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
// Flaky on the trybots. See http://crbug.com/96725.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabConnect) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
// Possible race in ChromeURLDataManager. http://crbug.com/59198
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabOnRemoved) {
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabReload) {
ASSERT_TRUE(RunExtensionTest("tabs/reload")) << message_;
}
class ExtensionApiCaptureTest : public ExtensionApiTest {
public:
ExtensionApiCaptureTest() {}
void SetUp() override {
EnablePixelOutput();
ExtensionApiTest::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleTabJpeg) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabPng) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
// Times out on non-Windows.
// See http://crbug.com/80212
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleTabRace) {
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_race.html")) << message_;
}
// Disabled for being flaky, see http://crbug/367695.
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleFile) {
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_file.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, CaptureVisibleDisabled) {
browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableScreenshots,
true);
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_disabled.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsNoPermissions) {
ASSERT_TRUE(RunExtensionTest("tabs/no_permissions")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, UpdateWindowResize) {
ASSERT_TRUE(RunExtensionTest("window_update/resize")) << message_;
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
HWND window =
browser()->window()->GetNativeWindow()->GetHost()->GetAcceleratedWidget();
::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_TRUE(::IsZoomed(window));
}
#endif // OS_WIN
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) {
ASSERT_TRUE(RunExtensionTest("window_update/show_state")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
IncognitoModePrefs::DISABLED);
// This makes sure that creating an incognito window fails due to pref
// (policy) being set.
ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedPopup) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedWindow) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
<< message_;
}
// Adding a new test? Awesome. But API tests are the old hotness. The new
// hotness is extension_function_test_utils. See tabs_test.cc for an example.
// We are trying to phase out many uses of API tests as they tend to be flaky.
<commit_msg>Disable ExtensionApiTest.TabMuted as it's flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "net/dns/mock_host_resolver.h"
#if defined(OS_WIN)
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#endif
#if defined(USE_AURA) || defined(OS_MACOSX)
// Maximizing/fullscreen popup window doesn't work on aura's managed mode.
// See bug crbug.com/116305.
// Mac: http://crbug.com/103912
#define MAYBE_UpdateWindowShowState DISABLED_UpdateWindowShowState
#else
#define MAYBE_UpdateWindowShowState UpdateWindowShowState
#endif // defined(USE_AURA) || defined(OS_MACOSX)
// http://crbug.com/145639
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TabEvents DISABLED_TabEvents
#else
#define MAYBE_TabEvents TabEvents
#endif
class ExtensionApiNewTabTest : public ExtensionApiTest {
public:
ExtensionApiNewTabTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
// Override the default which InProcessBrowserTest adds if it doesn't see a
// homepage.
command_line->AppendSwitchASCII(
switches::kHomePage, chrome::kChromeUINewTabURL);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiNewTabTest, Tabs) {
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabAudible) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "audible.html")) << message_;
}
// http://crbug.com/521410
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabMuted) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "muted.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_Tabs2 DISABLED_Tabs2
#else
#define MAYBE_Tabs2 Tabs2
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs2) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_;
}
// crbug.com/149924
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabDuplicate) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "duplicate.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabSize) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "tab_size.html")) << message_;
}
// Flaky on linux: http://crbug.com/396364
#if defined(OS_LINUX)
#define MAYBE_TabUpdate DISABLED_TabUpdate
#else
#define MAYBE_TabUpdate TabUpdate
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabUpdate) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "update.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_TabMove DISABLED_TabMove
#else
#define MAYBE_TabMove TabMove
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabRelativeURLs) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "query.html")) << message_;
}
// Flaky on windows: http://crbug.com/239022
#if defined(OS_WIN)
#define MAYBE_TabHighlight DISABLED_TabHighlight
#else
#define MAYBE_TabHighlight TabHighlight
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabHighlight) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "highlight.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}
// Flaky on windows: http://crbug.com/238667
#if defined(OS_WIN)
#define MAYBE_TabOpener DISABLED_TabOpener
#else
#define MAYBE_TabOpener TabOpener
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOpener) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "opener.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabGetCurrent) {
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
// Flaky on the trybots. See http://crbug.com/96725.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabConnect) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
// Possible race in ChromeURLDataManager. http://crbug.com/59198
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabOnRemoved) {
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabReload) {
ASSERT_TRUE(RunExtensionTest("tabs/reload")) << message_;
}
class ExtensionApiCaptureTest : public ExtensionApiTest {
public:
ExtensionApiCaptureTest() {}
void SetUp() override {
EnablePixelOutput();
ExtensionApiTest::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleTabJpeg) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabPng) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
// Times out on non-Windows.
// See http://crbug.com/80212
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleTabRace) {
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_race.html")) << message_;
}
// Disabled for being flaky, see http://crbug/367695.
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest,
DISABLED_CaptureVisibleFile) {
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_file.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, CaptureVisibleDisabled) {
browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableScreenshots,
true);
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_disabled.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsNoPermissions) {
ASSERT_TRUE(RunExtensionTest("tabs/no_permissions")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, UpdateWindowResize) {
ASSERT_TRUE(RunExtensionTest("window_update/resize")) << message_;
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
HWND window =
browser()->window()->GetNativeWindow()->GetHost()->GetAcceleratedWidget();
::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_TRUE(::IsZoomed(window));
}
#endif // OS_WIN
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) {
ASSERT_TRUE(RunExtensionTest("window_update/show_state")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
IncognitoModePrefs::DISABLED);
// This makes sure that creating an incognito window fails due to pref
// (policy) being set.
ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedPopup) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedWindow) {
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
<< message_;
}
// Adding a new test? Awesome. But API tests are the old hotness. The new
// hotness is extension_function_test_utils. See tabs_test.cc for an example.
// We are trying to phase out many uses of API tests as they tend to be flaky.
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<commit_msg>Mark ExtensionApiTest.Tabs flaky on win and linux.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
// It's flaky on win and linux.
// http://crbug.com/58269
#define MAYBE_Tabs FLAKY_Tabs
#endif
// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <list>
#include <map>
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"
namespace {
class LoginPromptBrowserTest : public InProcessBrowserTest {
public:
LoginPromptBrowserTest()
: bad_password_(L"incorrect"), bad_username_(L"nouser") {
set_show_window(true);
auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
}
protected:
void SetAuthFor(LoginHandler* handler);
struct AuthInfo {
std::wstring username_;
std::wstring password_;
AuthInfo() {}
AuthInfo(const std::wstring username,
const std::wstring password)
: username_(username), password_(password) {}
};
std::map<std::wstring, AuthInfo> auth_map_;
std::wstring bad_password_;
std::wstring bad_username_;
};
void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
const net::AuthChallengeInfo* challenge = handler->auth_info();
ASSERT_TRUE(challenge);
std::map<std::wstring, AuthInfo>::iterator i =
auth_map_.find(challenge->realm);
EXPECT_TRUE(auth_map_.end() != i);
if (i != auth_map_.end()) {
const AuthInfo& info = i->second;
handler->SetAuth(info.username_, info.password_);
}
}
// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
public:
LoginPromptBrowserTestObserver()
: auth_needed_count_(0),
auth_supplied_count_(0),
auth_cancelled_count_(0) {}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
void AddHandler(LoginHandler* handler);
void RemoveHandler(LoginHandler* handler);
void Register(const NotificationSource& source);
std::list<LoginHandler*> handlers_;
// The exact number of notifications we receive is depedent on the
// number of requests that were dispatched and is subject to a
// number of factors that we don't directly control here. The
// values below should only be used qualitatively.
int auth_needed_count_;
int auth_supplied_count_;
int auth_cancelled_count_;
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};
void LoginPromptBrowserTestObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::AUTH_NEEDED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
AddHandler(login_details->handler());
auth_needed_count_++;
} else if (type == NotificationType::AUTH_SUPPLIED) {
AuthSuppliedLoginNotificationDetails* login_details =
Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_supplied_count_++;
} else if (type == NotificationType::AUTH_CANCELLED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_cancelled_count_++;
}
}
void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i == handlers_.end());
if (i == handlers_.end())
handlers_.push_back(handler);
}
void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i != handlers_.end());
if (i != handlers_.end())
handlers_.erase(i);
}
void LoginPromptBrowserTestObserver::Register(
const NotificationSource& source) {
registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}
template <NotificationType::Type T>
class WindowedNavigationObserver
: public ui_test_utils::WindowedNotificationObserver {
public:
explicit WindowedNavigationObserver(NavigationController* controller)
: ui_test_utils::WindowedNotificationObserver(
T, Source<NavigationController>(controller)) {}
};
typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
WindowedLoadStopObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
WindowedAuthNeededObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
WindowedAuthCancelledObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
WindowedAuthSuppliedObserver;
const char* kPrefetchAuthPage = "files/login/prefetch.html";
const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int kMultiRealmTestRealmCount = 2;
const int kMultiRealmTestResourceCount = 4;
const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int kSingleRealmTestResourceCount = 6;
// Confirm that <link rel="prefetch"> targetting an auth required
// resource does not provide a login dialog. These types of requests
// should instead just cancel the auth.
// Unfortunately, this test doesn't assert on anything for its
// correctness. Instead, it relies on the auth dialog blocking the
// browser, and triggering a timeout to cause failure when the
// prefetch resource requires authorization.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, PrefetchAuthCancels) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kPrefetchAuthPage);
class SetPrefetchForTest {
public:
explicit SetPrefetchForTest(bool prefetch)
: old_prefetch_state_(ResourceDispatcherHost::is_prefetch_enabled()) {
ResourceDispatcherHost::set_is_prefetch_enabled(prefetch);
}
~SetPrefetchForTest() {
ResourceDispatcherHost::set_is_prefetch_enabled(old_prefetch_state_);
}
private:
bool old_prefetch_state_;
} set_prefetch_for_test(true);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
load_stop_waiter.Wait();
EXPECT_TRUE(observer.handlers_.empty());
EXPECT_TRUE(test_server()->Stop());
}
// Test handling of resources that require authentication even though
// the page they are included on doesn't. In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page. First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
handler->CancelAuth();
auth_cancelled_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_EQ(0, observer.auth_supplied_count_);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
#if defined(OS_WIN)
// See http://crbug.com/70960
#define MAYBE_MultipleRealmConfirmation DISABLED_MultipleRealmConfirmation
#else
#define MAYBE_MultipleRealmConfirmation MultipleRealmConfirmation
#endif
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest,
MAYBE_MultipleRealmConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
int n_handlers = 0;
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
auth_supplied_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_supplied_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
// Marked as flaky. See http://crbug.com/69266 and http://crbug.com/68860
// TODO(asanka): Remove logging when timeout issues are resolved.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, FLAKY_IncorrectConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kSingleRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
LOG(INFO) <<
"Begin test run "
"(tracing for potential hang. crbug.com/69266)";
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
LOG(INFO) << "Waiting for initial AUTH_NEEDED";
auth_needed_waiter.Wait();
}
EXPECT_FALSE(observer.handlers_.empty());
if (!observer.handlers_.empty()) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
handler->SetAuth(bad_username_, bad_password_);
LOG(INFO) << "Waiting for initial AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
// The request should be retried after the incorrect password is
// supplied. This should result in a new AUTH_NEEDED notification
// for the same realm.
LOG(INFO) << "Waiting for secondary AUTH_NEEDED";
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < 1) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
LOG(INFO) << "Waiting for secondary AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
}
if (n_handlers < 1) {
LOG(INFO) << "Waiting for additional AUTH_NEEDED";
auth_needed_waiter.Wait();
}
}
// The single realm test has only one realm, and thus only one login
// prompt.
EXPECT_EQ(1, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_EQ(observer.auth_needed_count_, observer.auth_supplied_count_);
LOG(INFO) << "Waiting for LOAD_STOP";
load_stop_waiter.Wait();
EXPECT_TRUE(test_server()->Stop());
LOG(INFO) << "Done with test";
}
} // namespace
<commit_msg>Disable LoginPromptBrowserTest.IncorrectConfirmation<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <list>
#include <map>
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"
namespace {
class LoginPromptBrowserTest : public InProcessBrowserTest {
public:
LoginPromptBrowserTest()
: bad_password_(L"incorrect"), bad_username_(L"nouser") {
set_show_window(true);
auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
}
protected:
void SetAuthFor(LoginHandler* handler);
struct AuthInfo {
std::wstring username_;
std::wstring password_;
AuthInfo() {}
AuthInfo(const std::wstring username,
const std::wstring password)
: username_(username), password_(password) {}
};
std::map<std::wstring, AuthInfo> auth_map_;
std::wstring bad_password_;
std::wstring bad_username_;
};
void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
const net::AuthChallengeInfo* challenge = handler->auth_info();
ASSERT_TRUE(challenge);
std::map<std::wstring, AuthInfo>::iterator i =
auth_map_.find(challenge->realm);
EXPECT_TRUE(auth_map_.end() != i);
if (i != auth_map_.end()) {
const AuthInfo& info = i->second;
handler->SetAuth(info.username_, info.password_);
}
}
// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
public:
LoginPromptBrowserTestObserver()
: auth_needed_count_(0),
auth_supplied_count_(0),
auth_cancelled_count_(0) {}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
void AddHandler(LoginHandler* handler);
void RemoveHandler(LoginHandler* handler);
void Register(const NotificationSource& source);
std::list<LoginHandler*> handlers_;
// The exact number of notifications we receive is depedent on the
// number of requests that were dispatched and is subject to a
// number of factors that we don't directly control here. The
// values below should only be used qualitatively.
int auth_needed_count_;
int auth_supplied_count_;
int auth_cancelled_count_;
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};
void LoginPromptBrowserTestObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::AUTH_NEEDED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
AddHandler(login_details->handler());
auth_needed_count_++;
} else if (type == NotificationType::AUTH_SUPPLIED) {
AuthSuppliedLoginNotificationDetails* login_details =
Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_supplied_count_++;
} else if (type == NotificationType::AUTH_CANCELLED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_cancelled_count_++;
}
}
void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i == handlers_.end());
if (i == handlers_.end())
handlers_.push_back(handler);
}
void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i != handlers_.end());
if (i != handlers_.end())
handlers_.erase(i);
}
void LoginPromptBrowserTestObserver::Register(
const NotificationSource& source) {
registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}
template <NotificationType::Type T>
class WindowedNavigationObserver
: public ui_test_utils::WindowedNotificationObserver {
public:
explicit WindowedNavigationObserver(NavigationController* controller)
: ui_test_utils::WindowedNotificationObserver(
T, Source<NavigationController>(controller)) {}
};
typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
WindowedLoadStopObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
WindowedAuthNeededObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
WindowedAuthCancelledObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
WindowedAuthSuppliedObserver;
const char* kPrefetchAuthPage = "files/login/prefetch.html";
const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int kMultiRealmTestRealmCount = 2;
const int kMultiRealmTestResourceCount = 4;
const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int kSingleRealmTestResourceCount = 6;
// Confirm that <link rel="prefetch"> targetting an auth required
// resource does not provide a login dialog. These types of requests
// should instead just cancel the auth.
// Unfortunately, this test doesn't assert on anything for its
// correctness. Instead, it relies on the auth dialog blocking the
// browser, and triggering a timeout to cause failure when the
// prefetch resource requires authorization.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, PrefetchAuthCancels) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kPrefetchAuthPage);
class SetPrefetchForTest {
public:
explicit SetPrefetchForTest(bool prefetch)
: old_prefetch_state_(ResourceDispatcherHost::is_prefetch_enabled()) {
ResourceDispatcherHost::set_is_prefetch_enabled(prefetch);
}
~SetPrefetchForTest() {
ResourceDispatcherHost::set_is_prefetch_enabled(old_prefetch_state_);
}
private:
bool old_prefetch_state_;
} set_prefetch_for_test(true);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
load_stop_waiter.Wait();
EXPECT_TRUE(observer.handlers_.empty());
EXPECT_TRUE(test_server()->Stop());
}
// Test handling of resources that require authentication even though
// the page they are included on doesn't. In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page. First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
handler->CancelAuth();
auth_cancelled_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_EQ(0, observer.auth_supplied_count_);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
#if defined(OS_WIN)
// See http://crbug.com/70960
#define MAYBE_MultipleRealmConfirmation DISABLED_MultipleRealmConfirmation
#else
#define MAYBE_MultipleRealmConfirmation MultipleRealmConfirmation
#endif
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest,
MAYBE_MultipleRealmConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
int n_handlers = 0;
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
auth_supplied_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_supplied_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
// Marked as flaky. See http://crbug.com/69266 and http://crbug.com/68860
// TODO(asanka): Remove logging when timeout issues are resolved.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, DISABLED_IncorrectConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kSingleRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
LOG(INFO) <<
"Begin test run "
"(tracing for potential hang. crbug.com/69266)";
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
LOG(INFO) << "Waiting for initial AUTH_NEEDED";
auth_needed_waiter.Wait();
}
EXPECT_FALSE(observer.handlers_.empty());
if (!observer.handlers_.empty()) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
handler->SetAuth(bad_username_, bad_password_);
LOG(INFO) << "Waiting for initial AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
// The request should be retried after the incorrect password is
// supplied. This should result in a new AUTH_NEEDED notification
// for the same realm.
LOG(INFO) << "Waiting for secondary AUTH_NEEDED";
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < 1) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
LOG(INFO) << "Waiting for secondary AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
}
if (n_handlers < 1) {
LOG(INFO) << "Waiting for additional AUTH_NEEDED";
auth_needed_waiter.Wait();
}
}
// The single realm test has only one realm, and thus only one login
// prompt.
EXPECT_EQ(1, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_EQ(observer.auth_needed_count_, observer.auth_supplied_count_);
LOG(INFO) << "Waiting for LOAD_STOP";
load_stop_waiter.Wait();
EXPECT_TRUE(test_server()->Stop());
LOG(INFO) << "Done with test";
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <list>
#include <map>
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"
namespace {
class LoginPromptBrowserTest : public InProcessBrowserTest {
public:
LoginPromptBrowserTest()
: bad_password_(L"incorrect"), bad_username_(L"nouser") {
set_show_window(true);
auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
}
protected:
void SetAuthFor(LoginHandler* handler);
struct AuthInfo {
std::wstring username_;
std::wstring password_;
AuthInfo() {}
AuthInfo(const std::wstring username,
const std::wstring password)
: username_(username), password_(password) {}
};
std::map<std::wstring, AuthInfo> auth_map_;
std::wstring bad_password_;
std::wstring bad_username_;
};
void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
const net::AuthChallengeInfo* challenge = handler->auth_info();
ASSERT_TRUE(challenge);
std::map<std::wstring, AuthInfo>::iterator i =
auth_map_.find(challenge->realm);
EXPECT_TRUE(auth_map_.end() != i);
if (i != auth_map_.end()) {
const AuthInfo& info = i->second;
handler->SetAuth(info.username_, info.password_);
}
}
// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
public:
LoginPromptBrowserTestObserver()
: auth_needed_count_(0),
auth_supplied_count_(0),
auth_cancelled_count_(0) {}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
void AddHandler(LoginHandler* handler);
void RemoveHandler(LoginHandler* handler);
void Register(const NotificationSource& source);
std::list<LoginHandler*> handlers_;
// The exact number of notifications we receive is depedent on the
// number of requests that were dispatched and is subject to a
// number of factors that we don't directly control here. The
// values below should only be used qualitatively.
int auth_needed_count_;
int auth_supplied_count_;
int auth_cancelled_count_;
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};
void LoginPromptBrowserTestObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::AUTH_NEEDED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
AddHandler(login_details->handler());
auth_needed_count_++;
} else if (type == NotificationType::AUTH_SUPPLIED) {
AuthSuppliedLoginNotificationDetails* login_details =
Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_supplied_count_++;
} else if (type == NotificationType::AUTH_CANCELLED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_cancelled_count_++;
}
}
void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i == handlers_.end());
if (i == handlers_.end())
handlers_.push_back(handler);
}
void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i != handlers_.end());
if (i != handlers_.end())
handlers_.erase(i);
}
void LoginPromptBrowserTestObserver::Register(
const NotificationSource& source) {
registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}
template <NotificationType::Type T>
class WindowedNavigationObserver
: public ui_test_utils::WindowedNotificationObserver {
public:
explicit WindowedNavigationObserver(NavigationController* controller)
: ui_test_utils::WindowedNotificationObserver(
T, Source<NavigationController>(controller)) {}
};
typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
WindowedLoadStopObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
WindowedAuthNeededObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
WindowedAuthCancelledObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
WindowedAuthSuppliedObserver;
const char* kPrefetchAuthPage = "files/login/prefetch.html";
const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int kMultiRealmTestRealmCount = 2;
const int kMultiRealmTestResourceCount = 4;
const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int kSingleRealmTestResourceCount = 6;
// Confirm that <link rel="prefetch"> targetting an auth required
// resource does not provide a login dialog. These types of requests
// should instead just cancel the auth.
// Unfortunately, this test doesn't assert on anything for its
// correctness. Instead, it relies on the auth dialog blocking the
// browser, and triggering a timeout to cause failure when the
// prefetch resource requires authorization.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, PrefetchAuthCancels) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kPrefetchAuthPage);
class SetPrefetchForTest {
public:
explicit SetPrefetchForTest(bool prefetch)
: old_prefetch_state_(ResourceDispatcherHost::is_prefetch_enabled()) {
ResourceDispatcherHost::set_is_prefetch_enabled(prefetch);
}
~SetPrefetchForTest() {
ResourceDispatcherHost::set_is_prefetch_enabled(old_prefetch_state_);
}
private:
bool old_prefetch_state_;
} set_prefetch_for_test(true);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
load_stop_waiter.Wait();
EXPECT_TRUE(observer.handlers_.empty());
EXPECT_TRUE(test_server()->Stop());
}
// Test handling of resources that require authentication even though
// the page they are included on doesn't. In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page. First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
handler->CancelAuth();
auth_cancelled_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_EQ(0, observer.auth_supplied_count_);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
int n_handlers = 0;
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
auth_supplied_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_supplied_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
// Marked as flaky. See http://crbug.com/69266 and http://crbug.com/68860
// TODO(asanka): Remove logging when timeout issues are resolved.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, FLAKY_IncorrectConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kSingleRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
LOG(INFO) <<
"Begin test run "
"(tracing for potential hang. crbug.com/69266)";
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
LOG(INFO) << "Waiting for initial AUTH_NEEDED";
auth_needed_waiter.Wait();
}
EXPECT_FALSE(observer.handlers_.empty());
if (!observer.handlers_.empty()) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
handler->SetAuth(bad_username_, bad_password_);
LOG(INFO) << "Waiting for initial AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
// The request should be retried after the incorrect password is
// supplied. This should result in a new AUTH_NEEDED notification
// for the same realm.
LOG(INFO) << "Waiting for secondary AUTH_NEEDED";
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < 1) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
LOG(INFO) << "Waiting for secondary AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
}
if (n_handlers < 1) {
LOG(INFO) << "Waiting for additional AUTH_NEEDED";
auth_needed_waiter.Wait();
}
}
// The single realm test has only one realm, and thus only one login
// prompt.
EXPECT_EQ(1, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_EQ(observer.auth_needed_count_, observer.auth_supplied_count_);
LOG(INFO) << "Waiting for LOAD_STOP";
load_stop_waiter.Wait();
EXPECT_TRUE(test_server()->Stop());
LOG(INFO) << "Done with test";
}
} // namespace
<commit_msg>MultipleRealmConfirmation hangs on vista tests. TEST=none BUG=70960<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <list>
#include <map>
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"
namespace {
class LoginPromptBrowserTest : public InProcessBrowserTest {
public:
LoginPromptBrowserTest()
: bad_password_(L"incorrect"), bad_username_(L"nouser") {
set_show_window(true);
auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
}
protected:
void SetAuthFor(LoginHandler* handler);
struct AuthInfo {
std::wstring username_;
std::wstring password_;
AuthInfo() {}
AuthInfo(const std::wstring username,
const std::wstring password)
: username_(username), password_(password) {}
};
std::map<std::wstring, AuthInfo> auth_map_;
std::wstring bad_password_;
std::wstring bad_username_;
};
void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
const net::AuthChallengeInfo* challenge = handler->auth_info();
ASSERT_TRUE(challenge);
std::map<std::wstring, AuthInfo>::iterator i =
auth_map_.find(challenge->realm);
EXPECT_TRUE(auth_map_.end() != i);
if (i != auth_map_.end()) {
const AuthInfo& info = i->second;
handler->SetAuth(info.username_, info.password_);
}
}
// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
public:
LoginPromptBrowserTestObserver()
: auth_needed_count_(0),
auth_supplied_count_(0),
auth_cancelled_count_(0) {}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
void AddHandler(LoginHandler* handler);
void RemoveHandler(LoginHandler* handler);
void Register(const NotificationSource& source);
std::list<LoginHandler*> handlers_;
// The exact number of notifications we receive is depedent on the
// number of requests that were dispatched and is subject to a
// number of factors that we don't directly control here. The
// values below should only be used qualitatively.
int auth_needed_count_;
int auth_supplied_count_;
int auth_cancelled_count_;
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};
void LoginPromptBrowserTestObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::AUTH_NEEDED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
AddHandler(login_details->handler());
auth_needed_count_++;
} else if (type == NotificationType::AUTH_SUPPLIED) {
AuthSuppliedLoginNotificationDetails* login_details =
Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_supplied_count_++;
} else if (type == NotificationType::AUTH_CANCELLED) {
LoginNotificationDetails* login_details =
Details<LoginNotificationDetails>(details).ptr();
RemoveHandler(login_details->handler());
auth_cancelled_count_++;
}
}
void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i == handlers_.end());
if (i == handlers_.end())
handlers_.push_back(handler);
}
void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
handlers_.end(),
handler);
EXPECT_TRUE(i != handlers_.end());
if (i != handlers_.end())
handlers_.erase(i);
}
void LoginPromptBrowserTestObserver::Register(
const NotificationSource& source) {
registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}
template <NotificationType::Type T>
class WindowedNavigationObserver
: public ui_test_utils::WindowedNotificationObserver {
public:
explicit WindowedNavigationObserver(NavigationController* controller)
: ui_test_utils::WindowedNotificationObserver(
T, Source<NavigationController>(controller)) {}
};
typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
WindowedLoadStopObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
WindowedAuthNeededObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
WindowedAuthCancelledObserver;
typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
WindowedAuthSuppliedObserver;
const char* kPrefetchAuthPage = "files/login/prefetch.html";
const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int kMultiRealmTestRealmCount = 2;
const int kMultiRealmTestResourceCount = 4;
const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int kSingleRealmTestResourceCount = 6;
// Confirm that <link rel="prefetch"> targetting an auth required
// resource does not provide a login dialog. These types of requests
// should instead just cancel the auth.
// Unfortunately, this test doesn't assert on anything for its
// correctness. Instead, it relies on the auth dialog blocking the
// browser, and triggering a timeout to cause failure when the
// prefetch resource requires authorization.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, PrefetchAuthCancels) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kPrefetchAuthPage);
class SetPrefetchForTest {
public:
explicit SetPrefetchForTest(bool prefetch)
: old_prefetch_state_(ResourceDispatcherHost::is_prefetch_enabled()) {
ResourceDispatcherHost::set_is_prefetch_enabled(prefetch);
}
~SetPrefetchForTest() {
ResourceDispatcherHost::set_is_prefetch_enabled(old_prefetch_state_);
}
private:
bool old_prefetch_state_;
} set_prefetch_for_test(true);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
load_stop_waiter.Wait();
EXPECT_TRUE(observer.handlers_.empty());
EXPECT_TRUE(test_server()->Stop());
}
// Test handling of resources that require authentication even though
// the page they are included on doesn't. In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page. First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
handler->CancelAuth();
auth_cancelled_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_EQ(0, observer.auth_supplied_count_);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
#if defined(OS_WIN)
// See http://crbug.com/70960
#define MAYBE_MultipleRealmConfirmation DISABLED_MultipleRealmConfirmation
#else
#define MAYBE_MultipleRealmConfirmation MultipleRealmConfirmation
#endif
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest,
MAYBE_MultipleRealmConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kMultiRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
int n_handlers = 0;
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
auth_needed_waiter.Wait();
}
while (n_handlers < kMultiRealmTestRealmCount) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
auth_supplied_waiter.Wait();
}
if (n_handlers < kMultiRealmTestRealmCount)
auth_needed_waiter.Wait();
}
load_stop_waiter.Wait();
EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_LT(0, observer.auth_supplied_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_TRUE(test_server()->Stop());
}
// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
// Marked as flaky. See http://crbug.com/69266 and http://crbug.com/68860
// TODO(asanka): Remove logging when timeout issues are resolved.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, FLAKY_IncorrectConfirmation) {
ASSERT_TRUE(test_server()->Start());
GURL test_page = test_server()->GetURL(kSingleRealmTestPage);
TabContentsWrapper* contents =
browser()->GetSelectedTabContentsWrapper();
ASSERT_TRUE(contents);
NavigationController* controller = &contents->controller();
LoginPromptBrowserTestObserver observer;
observer.Register(Source<NavigationController>(controller));
WindowedLoadStopObserver load_stop_waiter(controller);
LOG(INFO) <<
"Begin test run "
"(tracing for potential hang. crbug.com/69266)";
{
WindowedAuthNeededObserver auth_needed_waiter(controller);
browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
LOG(INFO) << "Waiting for initial AUTH_NEEDED";
auth_needed_waiter.Wait();
}
EXPECT_FALSE(observer.handlers_.empty());
if (!observer.handlers_.empty()) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
handler->SetAuth(bad_username_, bad_password_);
LOG(INFO) << "Waiting for initial AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
// The request should be retried after the incorrect password is
// supplied. This should result in a new AUTH_NEEDED notification
// for the same realm.
LOG(INFO) << "Waiting for secondary AUTH_NEEDED";
auth_needed_waiter.Wait();
}
int n_handlers = 0;
while (n_handlers < 1) {
WindowedAuthNeededObserver auth_needed_waiter(controller);
while (!observer.handlers_.empty()) {
WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
LoginHandler* handler = *observer.handlers_.begin();
ASSERT_TRUE(handler);
n_handlers++;
SetAuthFor(handler);
LOG(INFO) << "Waiting for secondary AUTH_SUPPLIED";
auth_supplied_waiter.Wait();
}
if (n_handlers < 1) {
LOG(INFO) << "Waiting for additional AUTH_NEEDED";
auth_needed_waiter.Wait();
}
}
// The single realm test has only one realm, and thus only one login
// prompt.
EXPECT_EQ(1, n_handlers);
EXPECT_LT(0, observer.auth_needed_count_);
EXPECT_EQ(0, observer.auth_cancelled_count_);
EXPECT_EQ(observer.auth_needed_count_, observer.auth_supplied_count_);
LOG(INFO) << "Waiting for LOAD_STOP";
load_stop_waiter.Wait();
EXPECT_TRUE(test_server()->Stop());
LOG(INFO) << "Done with test";
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"[email protected]",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"[email protected]",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<commit_msg>Disable crashing WebUIBidiCheckerBrowserTestFakeBidi.TestNewTabPageRTL<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif
// Disabled, http://crbug.com/97453
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"[email protected]",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"[email protected]",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<|endoftext|> |
<commit_before>#include "LayeredWnd.h"
#include <dwmapi.h>
#pragma comment(lib, "dwmapi.lib")
#include <VersionHelpers.h>
#include "..\Error.h"
LayeredWnd::LayeredWnd(LPCWSTR className, LPCWSTR title, HINSTANCE hInstance,
Gdiplus::Bitmap *bitmap, DWORD exStyles) :
_className(className),
_hInstance(hInstance),
_title(title),
_transparency(255),
_visible(false) {
if (_hInstance == NULL) {
_hInstance = (HINSTANCE) GetModuleHandle(NULL);
}
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = &LayeredWnd::StaticWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = _hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = _className;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
throw SYSERR_REGISTERCLASS;
}
DWORD styles = WS_EX_LAYERED | exStyles;
_hWnd = CreateWindowEx(
styles,
_className, _title,
WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
_size.cx, _size.cy,
NULL, NULL, _hInstance, this);
if (_hWnd == NULL) {
throw SYSERR_CREATEWINDOW;
}
Bitmap(bitmap);
}
LayeredWnd::~LayeredWnd() {
DestroyWindow(_hWnd);
UnregisterClass(_className, _hInstance);
}
void LayeredWnd::UpdateWindow(RECT *dirtyRect) {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = _transparency;
HDC screenDc = GetDC(GetDesktopWindow());
HDC sourceDc = CreateCompatibleDC(screenDc);
HBITMAP hBmp;
_bitmap->GetHBITMAP(Gdiplus::Color(0, 0, 0, 0), &hBmp);
HGDIOBJ hReplaced = SelectObject(sourceDc, hBmp);
POINT pt = { 0, 0 };
SIZE size = { _bitmap->GetWidth(), _bitmap->GetHeight() };
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = screenDc;
lwInfo.hdcSrc = sourceDc;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = &_location;
lwInfo.pptSrc = &pt;
lwInfo.prcDirty = dirtyRect;
lwInfo.psize = &size;
UpdateLayeredWindowIndirect(_hWnd, &lwInfo);
SelectObject(sourceDc, hReplaced);
DeleteDC(sourceDc);
DeleteObject(hBmp);
ReleaseDC(GetDesktopWindow(), screenDc);
}
void LayeredWnd::UpdateTransparency() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = _transparency;
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = NULL;
lwInfo.hdcSrc = NULL;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = NULL;
lwInfo.pptSrc = NULL;
lwInfo.prcDirty = NULL;
lwInfo.psize = NULL;
UpdateLayeredWindowIndirect(_hWnd, &lwInfo);
}
bool LayeredWnd::EnableGlass(Gdiplus::Bitmap *mask) {
if (mask == NULL) {
return false;
}
/* Disable for Windows 8+ */
if (IsWindows8OrGreater()) {
return false;
}
/* Disable for Windows XP */
if (IsWindowsXPOrGreater() == true && IsWindowsVistaOrGreater() == false) {
return false;
}
_glassMask = mask;
using namespace Gdiplus;
ARGB searchArgb = 0xFF000000;
unsigned int height = _glassMask->GetHeight();
unsigned int width = _glassMask->GetWidth();
Region glassRegion;
glassRegion.MakeEmpty();
bool match = false;
/* One row of pixels is scanned at a time, so the height is 1. */
Rect rec(0, 0, 0, 1);
for (unsigned int y = 0; y < height; ++y) {
for (unsigned int x = 0; x < width; ++x) {
Color pixelColor;
_glassMask->GetPixel(x, y, &pixelColor);
ARGB pixelArgb = pixelColor.GetValue();
if (searchArgb == pixelArgb && (x + 1 != width)) {
if (match) {
continue;
}
match = true;
rec.X = x;
rec.Y = y;
} else if (match) {
/* Reached the end of a matching line */
match = false;
rec.Width = x - rec.X;
glassRegion.Union(rec);
}
}
}
DWM_BLURBEHIND blurBehind = { 0 };
blurBehind.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
blurBehind.fEnable = TRUE;
Graphics g(_glassMask);
blurBehind.hRgnBlur = glassRegion.GetHRGN(&g);
HRESULT hr = DwmEnableBlurBehindWindow(_hWnd, &blurBehind);
return SUCCEEDED(hr);
}
bool LayeredWnd::DisableGlass() {
DWM_BLURBEHIND blurBehind = { 0 };
blurBehind.dwFlags = DWM_BB_ENABLE;
blurBehind.fEnable = FALSE;
HRESULT hr = DwmEnableBlurBehindWindow(_hWnd, &blurBehind);
return SUCCEEDED(hr);
}
void LayeredWnd::UpdateWindowPosition() {
MoveWindow(_hWnd, _location.x, _location.y, _size.cx, _size.cy, FALSE);
}
void LayeredWnd::Show() {
if (_visible == true) {
return;
}
UpdateWindow();
ShowWindow(_hWnd, SW_SHOW);
_visible = true;
}
void LayeredWnd::Hide() {
if (_visible == false) {
return;
}
ShowWindow(_hWnd, SW_HIDE);
_visible = false;
}
Gdiplus::Bitmap *LayeredWnd::Bitmap() {
return _bitmap;
}
void LayeredWnd::Bitmap(Gdiplus::Bitmap *bitmap) {
if (bitmap == NULL) {
return;
}
_bitmap = bitmap;
_size.cx = bitmap->GetWidth();
_size.cy = bitmap->GetHeight();
UpdateWindow();
}
byte LayeredWnd::Transparency() {
return _transparency;
}
void LayeredWnd::Transparency(byte transparency) {
_transparency = transparency;
UpdateTransparency();
}
int LayeredWnd::X() {
return _location.x;
}
void LayeredWnd::X(int x) {
_location.x = x;
}
int LayeredWnd::Y() {
return _location.y;
}
void LayeredWnd::Y(int y) {
_location.y = y;
}
int LayeredWnd::Width() {
return _size.cx;
}
int LayeredWnd::Height() {
return _size.cy;
}
POINT LayeredWnd::Position() {
return _location;
}
void LayeredWnd::Position(int x, int y) {
_location.x = x;
_location.y = y;
UpdateWindowPosition();
}
LRESULT CALLBACK
LayeredWnd::StaticWndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
LayeredWnd* wnd;
if (message == WM_CREATE) {
wnd = (LayeredWnd *) ((LPCREATESTRUCT) lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) wnd);
} else {
wnd = (LayeredWnd *) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!wnd) {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return wnd->WndProc(message, wParam, lParam);
}
LRESULT LayeredWnd::WndProc(UINT message, WPARAM wParam, LPARAM lParam) {
if (_glassMask && message == WM_DWMCOMPOSITIONCHANGED) {
BOOL compositionEnabled = FALSE;
DwmIsCompositionEnabled(&compositionEnabled);
if (compositionEnabled) {
EnableGlass(_glassMask);
} else {
DisableGlass();
}
}
return DefWindowProc(_hWnd, message, wParam, lParam);
}<commit_msg>Check HRESULT<commit_after>#include "LayeredWnd.h"
#include <dwmapi.h>
#pragma comment(lib, "dwmapi.lib")
#include <VersionHelpers.h>
#include "..\Error.h"
LayeredWnd::LayeredWnd(LPCWSTR className, LPCWSTR title, HINSTANCE hInstance,
Gdiplus::Bitmap *bitmap, DWORD exStyles) :
_className(className),
_hInstance(hInstance),
_title(title),
_transparency(255),
_visible(false) {
if (_hInstance == NULL) {
_hInstance = (HINSTANCE) GetModuleHandle(NULL);
}
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = &LayeredWnd::StaticWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = _hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = _className;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
throw SYSERR_REGISTERCLASS;
}
DWORD styles = WS_EX_LAYERED | exStyles;
_hWnd = CreateWindowEx(
styles,
_className, _title,
WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
_size.cx, _size.cy,
NULL, NULL, _hInstance, this);
if (_hWnd == NULL) {
throw SYSERR_CREATEWINDOW;
}
Bitmap(bitmap);
}
LayeredWnd::~LayeredWnd() {
DestroyWindow(_hWnd);
UnregisterClass(_className, _hInstance);
}
void LayeredWnd::UpdateWindow(RECT *dirtyRect) {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = _transparency;
HDC screenDc = GetDC(GetDesktopWindow());
HDC sourceDc = CreateCompatibleDC(screenDc);
HBITMAP hBmp;
_bitmap->GetHBITMAP(Gdiplus::Color(0, 0, 0, 0), &hBmp);
HGDIOBJ hReplaced = SelectObject(sourceDc, hBmp);
POINT pt = { 0, 0 };
SIZE size = { _bitmap->GetWidth(), _bitmap->GetHeight() };
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = screenDc;
lwInfo.hdcSrc = sourceDc;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = &_location;
lwInfo.pptSrc = &pt;
lwInfo.prcDirty = dirtyRect;
lwInfo.psize = &size;
UpdateLayeredWindowIndirect(_hWnd, &lwInfo);
SelectObject(sourceDc, hReplaced);
DeleteDC(sourceDc);
DeleteObject(hBmp);
ReleaseDC(GetDesktopWindow(), screenDc);
}
void LayeredWnd::UpdateTransparency() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = _transparency;
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = NULL;
lwInfo.hdcSrc = NULL;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = NULL;
lwInfo.pptSrc = NULL;
lwInfo.prcDirty = NULL;
lwInfo.psize = NULL;
UpdateLayeredWindowIndirect(_hWnd, &lwInfo);
}
bool LayeredWnd::EnableGlass(Gdiplus::Bitmap *mask) {
if (mask == NULL) {
return false;
}
/* Disable for Windows 8+ */
if (IsWindows8OrGreater()) {
return false;
}
/* Disable for Windows XP */
if (IsWindowsXPOrGreater() == true && IsWindowsVistaOrGreater() == false) {
return false;
}
_glassMask = mask;
using namespace Gdiplus;
ARGB searchArgb = 0xFF000000;
unsigned int height = _glassMask->GetHeight();
unsigned int width = _glassMask->GetWidth();
Region glassRegion;
glassRegion.MakeEmpty();
bool match = false;
/* One row of pixels is scanned at a time, so the height is 1. */
Rect rec(0, 0, 0, 1);
for (unsigned int y = 0; y < height; ++y) {
for (unsigned int x = 0; x < width; ++x) {
Color pixelColor;
_glassMask->GetPixel(x, y, &pixelColor);
ARGB pixelArgb = pixelColor.GetValue();
if (searchArgb == pixelArgb && (x + 1 != width)) {
if (match) {
continue;
}
match = true;
rec.X = x;
rec.Y = y;
} else if (match) {
/* Reached the end of a matching line */
match = false;
rec.Width = x - rec.X;
glassRegion.Union(rec);
}
}
}
DWM_BLURBEHIND blurBehind = { 0 };
blurBehind.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
blurBehind.fEnable = TRUE;
Graphics g(_glassMask);
blurBehind.hRgnBlur = glassRegion.GetHRGN(&g);
HRESULT hr = DwmEnableBlurBehindWindow(_hWnd, &blurBehind);
return SUCCEEDED(hr);
}
bool LayeredWnd::DisableGlass() {
DWM_BLURBEHIND blurBehind = { 0 };
blurBehind.dwFlags = DWM_BB_ENABLE;
blurBehind.fEnable = FALSE;
HRESULT hr = DwmEnableBlurBehindWindow(_hWnd, &blurBehind);
return SUCCEEDED(hr);
}
void LayeredWnd::UpdateWindowPosition() {
MoveWindow(_hWnd, _location.x, _location.y, _size.cx, _size.cy, FALSE);
}
void LayeredWnd::Show() {
if (_visible == true) {
return;
}
UpdateWindow();
ShowWindow(_hWnd, SW_SHOW);
_visible = true;
}
void LayeredWnd::Hide() {
if (_visible == false) {
return;
}
ShowWindow(_hWnd, SW_HIDE);
_visible = false;
}
Gdiplus::Bitmap *LayeredWnd::Bitmap() {
return _bitmap;
}
void LayeredWnd::Bitmap(Gdiplus::Bitmap *bitmap) {
if (bitmap == NULL) {
return;
}
_bitmap = bitmap;
_size.cx = bitmap->GetWidth();
_size.cy = bitmap->GetHeight();
UpdateWindow();
}
byte LayeredWnd::Transparency() {
return _transparency;
}
void LayeredWnd::Transparency(byte transparency) {
_transparency = transparency;
UpdateTransparency();
}
int LayeredWnd::X() {
return _location.x;
}
void LayeredWnd::X(int x) {
_location.x = x;
}
int LayeredWnd::Y() {
return _location.y;
}
void LayeredWnd::Y(int y) {
_location.y = y;
}
int LayeredWnd::Width() {
return _size.cx;
}
int LayeredWnd::Height() {
return _size.cy;
}
POINT LayeredWnd::Position() {
return _location;
}
void LayeredWnd::Position(int x, int y) {
_location.x = x;
_location.y = y;
UpdateWindowPosition();
}
LRESULT CALLBACK
LayeredWnd::StaticWndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
LayeredWnd* wnd;
if (message == WM_CREATE) {
wnd = (LayeredWnd *) ((LPCREATESTRUCT) lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) wnd);
} else {
wnd = (LayeredWnd *) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!wnd) {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return wnd->WndProc(message, wParam, lParam);
}
LRESULT LayeredWnd::WndProc(UINT message, WPARAM wParam, LPARAM lParam) {
if (_glassMask && message == WM_DWMCOMPOSITIONCHANGED) {
BOOL compositionEnabled = FALSE;
HRESULT hr = DwmIsCompositionEnabled(&compositionEnabled);
if (SUCCEEDED(hr)) {
if (compositionEnabled) {
EnableGlass(_glassMask);
} else {
DisableGlass();
}
}
}
return DefWindowProc(_hWnd, message, wParam, lParam);
}<|endoftext|> |
<commit_before>/*
TSIframework . Framework for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2009 Carles F. Julià <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SINGLETON_H
#define SINGLETON_H
//Inspired by http://cc.byexamples.com/20080609/stl-singleton-template/
template<typename T>
class Singleton
{
public:
static T& Instance()
{
static T me;
return me;
}
static T* get()
{
return &Instance();
}
};
#endif //SINGLETON_H
<commit_msg>Extending Singleton Template to admit Base Classes<commit_after>/*
TSIframework . Framework for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2009 Carles F. Julià <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SINGLETON_H
#define SINGLETON_H
//Inspired by http://cc.byexamples.com/20080609/stl-singleton-template/
class VoidClass{};
template<typename T, class Base=VoidClass>
class Singleton : public Base
{
public:
static T& Instance()
{
static T me;
return me;
}
static T* get()
{
return &Instance();
}
};
#endif //SINGLETON_H
<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "qtlocalpeer.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QTime>
#if defined(Q_OS_WIN)
#include <QtCore/QLibrary>
#include <QtCore/qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif
namespace SharedTools {
const char *QtLocalPeer::ack = "ack";
QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
: QObject(parent), id(appId)
{
if (id.isEmpty())
id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win
QByteArray idc = id.toUtf8();
quint16 idNum = qChecksum(idc.constData(), idc.size());
//### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.
socketName = QLatin1String("qtsingleapplication-")
+ QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
QLibrary lib("kernel32");
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
socketName += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
server = new QLocalServer(this);
QString lockName = QDir(QDir::tempPath()).absolutePath()
+ QLatin1Char('/') + socketName
+ QLatin1String("-lockfile");
lockFile.setFileName(lockName);
lockFile.open(QIODevice::ReadWrite);
}
bool QtLocalPeer::isClient()
{
if (lockFile.isLocked())
return false;
if (!lockFile.lock(QtLockedFile::WriteLock, false))
return true;
if (!QLocalServer::removeServer(socketName))
qWarning("QtSingleCoreApplication: could not cleanup socket");
bool res = server->listen(socketName);
if (!res)
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false;
}
bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if (!connOk)
return false;
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
return res;
}
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if (!socket)
return;
// Why doesn't Qt have a blocking stream that takes care of this shait???
while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32)))
socket->waitForReadyRead();
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
//qDebug() << "RCV: remaining" << remaining;
do {
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
//qDebug() << "RCV: got" << got << "remaining" << remaining;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
//### error check: got<0
if (got < 0) {
qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
delete socket;
return;
}
// ### async this
QString message(QString::fromUtf8(uMsg));
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
delete socket;
emit messageReceived(message); // ##(might take a long time to return)
}
} // namespace SharedTools
<commit_msg>Fixes: work on QT_NO_CAST_FROM_BYTEARRAY<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "qtlocalpeer.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QTime>
#if defined(Q_OS_WIN)
#include <QtCore/QLibrary>
#include <QtCore/qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif
namespace SharedTools {
const char *QtLocalPeer::ack = "ack";
QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
: QObject(parent), id(appId)
{
if (id.isEmpty())
id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win
QByteArray idc = id.toUtf8();
quint16 idNum = qChecksum(idc.constData(), idc.size());
//### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.
socketName = QLatin1String("qtsingleapplication-")
+ QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
QLibrary lib("kernel32");
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
socketName += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
server = new QLocalServer(this);
QString lockName = QDir(QDir::tempPath()).absolutePath()
+ QLatin1Char('/') + socketName
+ QLatin1String("-lockfile");
lockFile.setFileName(lockName);
lockFile.open(QIODevice::ReadWrite);
}
bool QtLocalPeer::isClient()
{
if (lockFile.isLocked())
return false;
if (!lockFile.lock(QtLockedFile::WriteLock, false))
return true;
if (!QLocalServer::removeServer(socketName))
qWarning("QtSingleCoreApplication: could not cleanup socket");
bool res = server->listen(socketName);
if (!res)
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false;
}
bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if (!connOk)
return false;
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
return res;
}
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if (!socket)
return;
// Why doesn't Qt have a blocking stream that takes care of this shait???
while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32)))
socket->waitForReadyRead();
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
//qDebug() << "RCV: remaining" << remaining;
do {
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
//qDebug() << "RCV: got" << got << "remaining" << remaining;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
//### error check: got<0
if (got < 0) {
qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
delete socket;
return;
}
// ### async this
QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
delete socket;
emit messageReceived(message); // ##(might take a long time to return)
}
} // namespace SharedTools
<|endoftext|> |
<commit_before>// $Id$
// Category: event
//
// See the class description in the header file.
#include <G4Timer.hh>
// in order to avoid the odd dependency for the
// times system function this include must be the first
#include "AliEventAction.h"
#include "AliEventActionMessenger.h"
#include "AliRun.h"
#include "AliTrackingAction.h"
#include "AliGlobals.h"
#include <G4Event.hh>
#include <G4TrajectoryContainer.hh>
#include <G4Trajectory.hh>
#include <G4VVisManager.hh>
#include <G4UImanager.hh>
AliEventAction::AliEventAction()
: fVerboseLevel(1),
fDrawFlag("CHARGED")
{
//
fMessenger = new AliEventActionMessenger(this);
fTimer = new G4Timer();
}
AliEventAction::AliEventAction(const AliEventAction& right) {
//
AliGlobals::Exception("AliEventAction is protected from copying.");
}
AliEventAction::~AliEventAction() {
//
delete fMessenger;
delete fTimer;
}
// operators
AliEventAction& AliEventAction::operator=(const AliEventAction &right)
{
// check assignement to self
if (this == &right) return *this;
AliGlobals::Exception("AliEventAction is protected from assigning.");
return *this;
}
// private methods
void AliEventAction::DisplayEvent(const G4Event* event) const
{
// Draws trajectories.
// ---
// trajectories processing
G4TrajectoryContainer* trajectoryContainer
= event->GetTrajectoryContainer();
G4int nofTrajectories = 0;
if (trajectoryContainer)
{ nofTrajectories = trajectoryContainer->entries(); }
if (fVerboseLevel>0) {
G4cout << " " << nofTrajectories;
G4cout << " trajectories stored." << G4endl;
}
G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance();
if(pVVisManager && nofTrajectories>0)
{
G4UImanager::GetUIpointer()->ApplyCommand("/vis~/draw/current");
for (G4int i=0; i<nofTrajectories; i++)
{
G4VTrajectory* vtrajectory = (*(event->GetTrajectoryContainer()))[i];
G4Trajectory* trajectory = dynamic_cast<G4Trajectory*>(vtrajectory);
if (!trajectory) {
AliGlobals::Exception(
"AliEventAction::DisplayEvent: Unknown trajectory type.");
}
if ( (fDrawFlag == "ALL") ||
((fDrawFlag == "CHARGED") && (trajectory->GetCharge() != 0.))){
trajectory->DrawTrajectory(50);
// the argument number defines the size of the step points
// use 2000 to make step points well visible
}
}
G4UImanager::GetUIpointer()->ApplyCommand("/vis~/show/view");
}
}
// public methods
void AliEventAction::BeginOfEventAction(const G4Event* event)
{
// Called by G4 kernel at the beginning of event.
// ---
G4int eventID = event->GetEventID();
// reset the counters (primary tracks, saved tracks)
AliTrackingAction* trackingAction
= AliTrackingAction::Instance();
trackingAction->PrepareNewEvent();
if (fVerboseLevel>0)
G4cout << ">>> Event " << event->GetEventID() << G4endl;
fTimer->Start();
}
void AliEventAction::EndOfEventAction(const G4Event* event)
{
// Called by G4 kernel at the end of event.
// ---
// save the last primary track store of
// the current event
AliTrackingAction* trackingAction
= AliTrackingAction::Instance();
trackingAction->SaveAndDestroyTrack();
if (fVerboseLevel>0) {
G4int nofPrimaryTracks = trackingAction->GetNofPrimaryTracks();
G4int nofTracks = trackingAction->GetNofTracks();
G4cout << " " << nofPrimaryTracks <<
" primary tracks processed." << G4endl;
G4cout << " " << nofTracks <<
" all tracks processed." << G4endl;
}
// display event
DisplayEvent(event);
// aliroot
// store event header data
gAlice->GetHeader()->SetEvent(event->GetEventID());
gAlice->GetHeader()->SetNvertex(event->GetNumberOfPrimaryVertex());
gAlice->GetHeader()->SetNprimary(trackingAction->GetNofPrimaryTracks());
gAlice->GetHeader()->SetNtrack(trackingAction->GetNofSavedTracks());
gAlice->FinishEvent();
if (fVerboseLevel>0) {
// print time
fTimer->Stop();
G4cout << "Time of this event = " << *fTimer << G4endl;
}
}
<commit_msg>updated to AliTrackingAction changes; removed settings to AliHeader in EndOfEventAction() (not needed)<commit_after>// $Id$
// Category: event
//
// See the class description in the header file.
#include <G4Timer.hh>
// in order to avoid the odd dependency for the
// times system function this include must be the first
#include "AliEventAction.h"
#include "AliEventActionMessenger.h"
#include "AliTrackingAction.h"
#include "AliGlobals.h"
#include "AliRun.h"
#include <G4Event.hh>
#include <G4TrajectoryContainer.hh>
#include <G4Trajectory.hh>
#include <G4VVisManager.hh>
#include <G4UImanager.hh>
AliEventAction::AliEventAction()
: fVerboseLevel(1),
fDrawFlag("CHARGED")
{
//
fMessenger = new AliEventActionMessenger(this);
fTimer = new G4Timer();
}
AliEventAction::AliEventAction(const AliEventAction& right) {
//
AliGlobals::Exception("AliEventAction is protected from copying.");
}
AliEventAction::~AliEventAction() {
//
delete fMessenger;
delete fTimer;
}
// operators
AliEventAction& AliEventAction::operator=(const AliEventAction &right)
{
// check assignement to self
if (this == &right) return *this;
AliGlobals::Exception("AliEventAction is protected from assigning.");
return *this;
}
// private methods
void AliEventAction::DisplayEvent(const G4Event* event) const
{
// Draws trajectories.
// ---
// trajectories processing
G4TrajectoryContainer* trajectoryContainer
= event->GetTrajectoryContainer();
G4int nofTrajectories = 0;
if (trajectoryContainer)
{ nofTrajectories = trajectoryContainer->entries(); }
if (fVerboseLevel>0 && nofTrajectories>0) {
G4cout << " " << nofTrajectories;
G4cout << " trajectories stored." << G4endl;
}
G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance();
if(pVVisManager && nofTrajectories>0)
{
G4UImanager::GetUIpointer()->ApplyCommand("/vis~/draw/current");
for (G4int i=0; i<nofTrajectories; i++)
{
G4VTrajectory* vtrajectory = (*(event->GetTrajectoryContainer()))[i];
G4Trajectory* trajectory = dynamic_cast<G4Trajectory*>(vtrajectory);
if (!trajectory) {
AliGlobals::Exception(
"AliEventAction::DisplayEvent: Unknown trajectory type.");
}
if ( (fDrawFlag == "ALL") ||
((fDrawFlag == "CHARGED") && (trajectory->GetCharge() != 0.))){
trajectory->DrawTrajectory(50);
// the argument number defines the size of the step points
// use 2000 to make step points well visible
}
}
G4UImanager::GetUIpointer()->ApplyCommand("/vis~/show/view");
}
}
// public methods
void AliEventAction::BeginOfEventAction(const G4Event* event)
{
// Called by G4 kernel at the beginning of event.
// ---
G4int eventID = event->GetEventID();
// reset the tracks counters
AliTrackingAction::Instance()->PrepareNewEvent();
if (fVerboseLevel>0)
G4cout << ">>> Event " << event->GetEventID() << G4endl;
fTimer->Start();
}
void AliEventAction::EndOfEventAction(const G4Event* event)
{
// Called by G4 kernel at the end of event.
// ---
// finish the last primary track of the current event
AliTrackingAction* trackingAction = AliTrackingAction::Instance();
trackingAction->FinishPrimaryTrack();
// verbose output
if (fVerboseLevel>0) {
//G4int nofPrimaryTracks = trackingAction->GetNofPrimaryTracks();
G4int nofPrimaryTracks = gAlice->GetHeader()->GetNprimary();
G4int nofSavedTracks = gAlice->GetNtrack();
G4int nofAllTracks = trackingAction->GetNofTracks();
G4cout << " " << nofPrimaryTracks <<
" primary tracks processed." << G4endl;
G4cout << " " << nofSavedTracks <<
" tracks saved." << G4endl;
G4cout << " " << nofAllTracks <<
" all tracks processed." << G4endl;
}
// display event
DisplayEvent(event);
// aliroot finish event
gAlice->FinishEvent();
if (fVerboseLevel>0) {
// print time
fTimer->Stop();
G4cout << "Time of this event: " << *fTimer << G4endl;
}
}
<|endoftext|> |
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "command_line_master.hpp"
#include "code/ylikuutio/map/ylikuutio_map.hpp"
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <limits> // std::numeric_limits
#include <string> // std::string
#include <unordered_map> // std::unordered_map
namespace yli
{
namespace command_line
{
CommandLineMaster::CommandLineMaster(const int argc, const char* const argv[])
{
this->argc = argc;
this->arg_vector.assign(argv + 1, argv + argc); // Copy all arguments except the executable name.
bool is_previous_argument_available = false;
std::string previous_argument = ""; // dummy value.
// Go through the command line arguments and store the keys and values.
for (std::vector<std::string>::const_iterator it = this->arg_vector.begin(); it != this->arg_vector.end(); it++)
{
const std::string argument = *it;
// If the argument begins with `---`, the the argument is invalid.
// If the argument begins with `--`, then leave those out of the argument key.
// If the argument begins with `-`, then each char after `-` is an argument key.
// If the argument begins with something else and it the 1st argument, discard the argument.
// If the argument begins with something else and the previous argument contained `=`, discard the current argument.
// If the argument begins with something else, use it as a value for the previous argument.
// If the argument contains `=`, then use the value `=` as the value, and the argument key is the char or chars before `=`.
std::size_t n_leading_dashes = 0;
std::size_t index_of_equal_sign = std::numeric_limits<std::size_t>::max(); // maximum value here means "not found yet".
// count the number of leading dashes and check the location of potential equal sign.
for (std::size_t i = 0; i < argument.size(); i++)
{
if (i == n_leading_dashes && argument[i] == '-')
{
n_leading_dashes++;
}
else if (argument[i] == '=')
{
// only first equal sign `=` matters.
// the rest equal signs (if any) are part of the value.
index_of_equal_sign = i;
break;
}
}
if (n_leading_dashes == 0 && is_previous_argument_available)
{
this->arg_map[previous_argument] = argument;
is_previous_argument_available = false;
continue;
}
else if (n_leading_dashes == 0)
{
// there is no previous argument available for this value.
continue;
}
if (is_previous_argument_available)
{
// there was no value available for the previous argument.
this->arg_map[previous_argument] = "";
}
// arguments without dashes are processed already.
is_previous_argument_available = false;
if (n_leading_dashes > 2)
{
// an argument beginning with `---` is invalid, therefore it is discarded.
continue;
}
if (index_of_equal_sign == std::numeric_limits<std::size_t>::max())
{
// no equal sign.
if (n_leading_dashes == 2)
{
// the string without dashes is the key, the value is an empty string.
const std::string string_without_dashes = argument.substr(2); // the string without 2 leading dashes.
previous_argument = string_without_dashes;
is_previous_argument_available = true;
}
else
{
// 1 leading dash.
// each character is a key, concatenated with a leading dash.
// the last one may have a value.
for (std::size_t j = 1; j < argument.size() - 1; j++)
{
std::string current_argument_string = "-";
const std::string current_char_string = argument.substr(j, 1);
current_argument_string.append(current_char_string);
this->arg_map[current_argument_string] = "";
}
previous_argument = argument[argument.size() - 1];
is_previous_argument_available = true;
}
}
else
{
// there was at least 1 equal sign.
if (n_leading_dashes == 2)
{
// the characters between leading dashes and the equal sign are the key.
// the characters after the equal sign are the value.
const std::string key = argument.substr(2, index_of_equal_sign - 2); // the characters between leading dashes and the equal sign.
const std::string value = argument.substr(index_of_equal_sign + 1);
this->arg_map[key] = value;
}
else
{
// 1 leading dash.
// each character is a key, concatenated with a leading dash.
// the value of the last key is the characters after the equal sign.
// the value of the other keys is an empty string.
for (std::size_t j = 1; j < index_of_equal_sign; j++)
{
std::string current_argument_string = "-";
const std::string current_char_string = argument.substr(j, 1);
current_argument_string.append(current_char_string);
if (j < index_of_equal_sign - 1)
{
this->arg_map[current_argument_string] = "";
}
else
{
const std::string value = argument.substr(index_of_equal_sign + 1);
this->arg_map[current_argument_string] = value;
}
}
}
}
}
if (is_previous_argument_available)
{
this->arg_map[previous_argument] = "";
}
}
bool CommandLineMaster::is_key(const std::string& key) const
{
return this->arg_map.count(key) == 1;
}
std::string CommandLineMaster::get_value(const std::string& key) const
{
if (this->arg_map.count(key) == 1)
{
return this->arg_map.at(key);
}
return "";
}
void CommandLineMaster::print_keys() const
{
if (this->argc > 1)
{
// Print command line arguments (without the executable name string).
for (std::string argument : arg_vector)
{
std::cout << argument << "\n";
}
}
else
{
std::cout << "no command line arguments.\n";
}
}
void CommandLineMaster::print_keys_and_values() const
{
yli::map::print_keys_and_values<std::string>(this->arg_map);
}
}
}
<commit_msg>Bugfix: added missing `#include` line.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "command_line_master.hpp"
#include "code/ylikuutio/map/ylikuutio_map.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <limits> // std::numeric_limits
#include <string> // std::string
#include <unordered_map> // std::unordered_map
namespace yli
{
namespace command_line
{
CommandLineMaster::CommandLineMaster(const int argc, const char* const argv[])
{
this->argc = argc;
this->arg_vector.assign(argv + 1, argv + argc); // Copy all arguments except the executable name.
bool is_previous_argument_available = false;
std::string previous_argument = ""; // dummy value.
// Go through the command line arguments and store the keys and values.
for (std::vector<std::string>::const_iterator it = this->arg_vector.begin(); it != this->arg_vector.end(); it++)
{
const std::string argument = *it;
// If the argument begins with `---`, the the argument is invalid.
// If the argument begins with `--`, then leave those out of the argument key.
// If the argument begins with `-`, then each char after `-` is an argument key.
// If the argument begins with something else and it the 1st argument, discard the argument.
// If the argument begins with something else and the previous argument contained `=`, discard the current argument.
// If the argument begins with something else, use it as a value for the previous argument.
// If the argument contains `=`, then use the value `=` as the value, and the argument key is the char or chars before `=`.
std::size_t n_leading_dashes = 0;
std::size_t index_of_equal_sign = std::numeric_limits<std::size_t>::max(); // maximum value here means "not found yet".
// count the number of leading dashes and check the location of potential equal sign.
for (std::size_t i = 0; i < argument.size(); i++)
{
if (i == n_leading_dashes && argument[i] == '-')
{
n_leading_dashes++;
}
else if (argument[i] == '=')
{
// only first equal sign `=` matters.
// the rest equal signs (if any) are part of the value.
index_of_equal_sign = i;
break;
}
}
if (n_leading_dashes == 0 && is_previous_argument_available)
{
this->arg_map[previous_argument] = argument;
is_previous_argument_available = false;
continue;
}
else if (n_leading_dashes == 0)
{
// there is no previous argument available for this value.
continue;
}
if (is_previous_argument_available)
{
// there was no value available for the previous argument.
this->arg_map[previous_argument] = "";
}
// arguments without dashes are processed already.
is_previous_argument_available = false;
if (n_leading_dashes > 2)
{
// an argument beginning with `---` is invalid, therefore it is discarded.
continue;
}
if (index_of_equal_sign == std::numeric_limits<std::size_t>::max())
{
// no equal sign.
if (n_leading_dashes == 2)
{
// the string without dashes is the key, the value is an empty string.
const std::string string_without_dashes = argument.substr(2); // the string without 2 leading dashes.
previous_argument = string_without_dashes;
is_previous_argument_available = true;
}
else
{
// 1 leading dash.
// each character is a key, concatenated with a leading dash.
// the last one may have a value.
for (std::size_t j = 1; j < argument.size() - 1; j++)
{
std::string current_argument_string = "-";
const std::string current_char_string = argument.substr(j, 1);
current_argument_string.append(current_char_string);
this->arg_map[current_argument_string] = "";
}
previous_argument = argument[argument.size() - 1];
is_previous_argument_available = true;
}
}
else
{
// there was at least 1 equal sign.
if (n_leading_dashes == 2)
{
// the characters between leading dashes and the equal sign are the key.
// the characters after the equal sign are the value.
const std::string key = argument.substr(2, index_of_equal_sign - 2); // the characters between leading dashes and the equal sign.
const std::string value = argument.substr(index_of_equal_sign + 1);
this->arg_map[key] = value;
}
else
{
// 1 leading dash.
// each character is a key, concatenated with a leading dash.
// the value of the last key is the characters after the equal sign.
// the value of the other keys is an empty string.
for (std::size_t j = 1; j < index_of_equal_sign; j++)
{
std::string current_argument_string = "-";
const std::string current_char_string = argument.substr(j, 1);
current_argument_string.append(current_char_string);
if (j < index_of_equal_sign - 1)
{
this->arg_map[current_argument_string] = "";
}
else
{
const std::string value = argument.substr(index_of_equal_sign + 1);
this->arg_map[current_argument_string] = value;
}
}
}
}
}
if (is_previous_argument_available)
{
this->arg_map[previous_argument] = "";
}
}
bool CommandLineMaster::is_key(const std::string& key) const
{
return this->arg_map.count(key) == 1;
}
std::string CommandLineMaster::get_value(const std::string& key) const
{
if (this->arg_map.count(key) == 1)
{
return this->arg_map.at(key);
}
return "";
}
void CommandLineMaster::print_keys() const
{
if (this->argc > 1)
{
// Print command line arguments (without the executable name string).
for (std::string argument : arg_vector)
{
std::cout << argument << "\n";
}
}
else
{
std::cout << "no command line arguments.\n";
}
}
void CommandLineMaster::print_keys_and_values() const
{
yli::map::print_keys_and_values<std::string>(this->arg_map);
}
}
}
<|endoftext|> |
<commit_before>//===-- Process.cpp - Implement OS Process Concept --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the operating system Process concept.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Process.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Config/config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
using namespace llvm;
using namespace sys;
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//=== independent code.
//===----------------------------------------------------------------------===//
Optional<std::string> Process::FindInEnvPath(StringRef EnvName,
StringRef FileName) {
return FindInEnvPath(EnvName, FileName, {});
}
Optional<std::string> Process::FindInEnvPath(StringRef EnvName,
StringRef FileName,
ArrayRef<std::string> IgnoreList) {
assert(!path::is_absolute(FileName));
Optional<std::string> FoundPath;
Optional<std::string> OptPath = Process::GetEnv(EnvName);
if (!OptPath.hasValue())
return FoundPath;
const char EnvPathSeparatorStr[] = {EnvPathSeparator, '\0'};
SmallVector<StringRef, 8> Dirs;
SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr);
for (StringRef Dir : Dirs) {
if (Dir.empty())
continue;
if (any_of(IgnoreList, [&](StringRef S) { return fs::equivalent(S, Dir); }))
continue;
SmallString<128> FilePath(Dir);
path::append(FilePath, FileName);
if (fs::exists(Twine(FilePath))) {
FoundPath = FilePath.str();
break;
}
}
return FoundPath;
}
#define COLOR(FGBG, CODE, BOLD) "\033[0;" BOLD FGBG CODE "m"
#define ALLCOLORS(FGBG,BOLD) {\
COLOR(FGBG, "0", BOLD),\
COLOR(FGBG, "1", BOLD),\
COLOR(FGBG, "2", BOLD),\
COLOR(FGBG, "3", BOLD),\
COLOR(FGBG, "4", BOLD),\
COLOR(FGBG, "5", BOLD),\
COLOR(FGBG, "6", BOLD),\
COLOR(FGBG, "7", BOLD)\
}
static const char colorcodes[2][2][8][10] = {
{ ALLCOLORS("3",""), ALLCOLORS("3","1;") },
{ ALLCOLORS("4",""), ALLCOLORS("4","1;") }
};
// This is set to true when Process::PreventCoreFiles() is called.
static bool coreFilesPrevented = false;
bool Process::AreCoreFilesPrevented() {
return LLVM_ENABLE_CRASH_DUMPS ? coreFilesPrevented : false;
}
// Include the platform-specific parts of this class.
#ifdef LLVM_ON_UNIX
#include "Unix/Process.inc"
#endif
#ifdef _WIN32
#include "Windows/Process.inc"
#endif
<commit_msg>Make LLVM_ENABLE_CRASH_DUMPS set a variable default<commit_after>//===-- Process.cpp - Implement OS Process Concept --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the operating system Process concept.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Process.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Config/config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
using namespace llvm;
using namespace sys;
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//=== independent code.
//===----------------------------------------------------------------------===//
Optional<std::string> Process::FindInEnvPath(StringRef EnvName,
StringRef FileName) {
return FindInEnvPath(EnvName, FileName, {});
}
Optional<std::string> Process::FindInEnvPath(StringRef EnvName,
StringRef FileName,
ArrayRef<std::string> IgnoreList) {
assert(!path::is_absolute(FileName));
Optional<std::string> FoundPath;
Optional<std::string> OptPath = Process::GetEnv(EnvName);
if (!OptPath.hasValue())
return FoundPath;
const char EnvPathSeparatorStr[] = {EnvPathSeparator, '\0'};
SmallVector<StringRef, 8> Dirs;
SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr);
for (StringRef Dir : Dirs) {
if (Dir.empty())
continue;
if (any_of(IgnoreList, [&](StringRef S) { return fs::equivalent(S, Dir); }))
continue;
SmallString<128> FilePath(Dir);
path::append(FilePath, FileName);
if (fs::exists(Twine(FilePath))) {
FoundPath = FilePath.str();
break;
}
}
return FoundPath;
}
#define COLOR(FGBG, CODE, BOLD) "\033[0;" BOLD FGBG CODE "m"
#define ALLCOLORS(FGBG,BOLD) {\
COLOR(FGBG, "0", BOLD),\
COLOR(FGBG, "1", BOLD),\
COLOR(FGBG, "2", BOLD),\
COLOR(FGBG, "3", BOLD),\
COLOR(FGBG, "4", BOLD),\
COLOR(FGBG, "5", BOLD),\
COLOR(FGBG, "6", BOLD),\
COLOR(FGBG, "7", BOLD)\
}
static const char colorcodes[2][2][8][10] = {
{ ALLCOLORS("3",""), ALLCOLORS("3","1;") },
{ ALLCOLORS("4",""), ALLCOLORS("4","1;") }
};
// A CMake option controls wheter we emit core dumps by default. An application
// may disable core dumps by calling Process::PreventCoreFiles().
static bool coreFilesPrevented = !LLVM_ENABLE_CRASH_DUMPS;
bool Process::AreCoreFilesPrevented() { return coreFilesPrevented; }
// Include the platform-specific parts of this class.
#ifdef LLVM_ON_UNIX
#include "Unix/Process.inc"
#endif
#ifdef _WIN32
#include "Windows/Process.inc"
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBasicFiltersTests.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkBasicFiltersPrintTest );
REGISTER_TEST(itkBasicFiltersPrintTest2 );
REGISTER_TEST(itkAcosImageFilterAndAdaptorTest );
REGISTER_TEST(itkAdaptImageFilterTest );
REGISTER_TEST(itkAdaptImageFilterTest2 );
REGISTER_TEST(itkAdaptiveHistogramEqualizationImageFilterTest);
REGISTER_TEST(itkAddImageFilterTest );
REGISTER_TEST(itkAsinImageFilterAndAdaptorTest );
REGISTER_TEST(itkAtanImageFilterAndAdaptorTest );
REGISTER_TEST(itkBSplineDecompositionImageFilterTest );
REGISTER_TEST(itkBSplineInterpolateImageFunctionTest );
REGISTER_TEST(itkBSplineResampleImageFilterTest );
REGISTER_TEST(itkBSplineResampleImageFunctionTest );
REGISTER_TEST(itkBasicArchitectureTest );
REGISTER_TEST(itkBilateralImageFilterTest );
REGISTER_TEST(itkBilateralImageFilterTest2 );
REGISTER_TEST(itkBilateralImageFilterTest3 );
REGISTER_TEST(itkBinaryDilateImageFilterTest );
REGISTER_TEST(itkBinaryErodeImageFilterTest );
REGISTER_TEST(itkBinaryMagnitudeImageFilterTest );
REGISTER_TEST(itkBinaryMaskToNarrowBandPointSetFilterTest);
REGISTER_TEST(itkBinaryMedianImageFilterTest );
REGISTER_TEST(itkBinaryThresholdImageFilterTest );
REGISTER_TEST(itkBloxBoundaryPointImageTest );
REGISTER_TEST(itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilterTest );
REGISTER_TEST(itkBloxCoreAtomTest );
REGISTER_TEST(itkCannyEdgeDetectionImageFilterTest );
REGISTER_TEST(itkChangeInformationImageFilterTest );
REGISTER_TEST(itkComposeRGBImageFilterTest );
REGISTER_TEST(itkConfidenceConnectedImageFilterTest );
REGISTER_TEST(itkConnectedComponentImageFilterTest );
REGISTER_TEST(itkConnectedThresholdImageFilterTest );
REGISTER_TEST(itkConstantPadImageTest );
REGISTER_TEST(itkCosImageFilterAndAdaptorTest );
REGISTER_TEST(itkCropImageFilterTest );
REGISTER_TEST(itkCurvatureAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkCyclicReferences );
REGISTER_TEST(itkDanielssonDistanceMapImageFilterTest );
REGISTER_TEST(itkDerivativeImageFilterTest );
REGISTER_TEST(itkDifferenceOfGaussiansGradientTest );
REGISTER_TEST(itkDiscreteGaussianImageFilterTest );
REGISTER_TEST(itkDivideImageFilterTest );
REGISTER_TEST(itkDoubleThresholdImageFilterTest );
REGISTER_TEST(itkEdgePotentialImageFilterTest );
REGISTER_TEST(itkEigenAnalysis2DImageFilterTest );
REGISTER_TEST(itkExpImageFilterAndAdaptorTest );
REGISTER_TEST(itkExpNegativeImageFilterAndAdaptorTest );
REGISTER_TEST(itkExpandImageFilterTest );
REGISTER_TEST(itkExtractImageTest );
REGISTER_TEST(itkFilterDispatchTest );
REGISTER_TEST(itkFlipImageFilterTest );
REGISTER_TEST(itkFloodFillIteratorTest );
REGISTER_TEST(itkGaussianImageSourceTest );
REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest2 );
REGISTER_TEST(itkGradientImageFilterTest );
REGISTER_TEST(itkGradientMagnitudeImageFilterTest );
REGISTER_TEST(itkGradientMagnitudeRecursiveGaussianFilterTest );
REGISTER_TEST(itkGradientRecursiveGaussianFilterTest );
REGISTER_TEST(itkGradientToMagnitudeImageFilterTest );
REGISTER_TEST(itkGrayscaleConnectedClosingImageFilterTest );
REGISTER_TEST(itkGrayscaleConnectedOpeningImageFilterTest );
REGISTER_TEST(itkGrayscaleFillholeImageFilterTest );
REGISTER_TEST(itkHardConnectedComponentImageFilterTest );
REGISTER_TEST(itkHausdorffDistanceImageFilterTest );
REGISTER_TEST(itkHConvexConcaveImageFilterTest );
REGISTER_TEST(itkHMaximaMinimaImageFilterTest );
REGISTER_TEST(itkHoughTransform2DCirclesImageTest );
REGISTER_TEST(itkHoughTransform2DLinesImageTest );
REGISTER_TEST(itkImageAdaptorNthElementTest );
REGISTER_TEST(itkImageAdaptorPipeLineTest );
REGISTER_TEST(itkImageToParametricSpaceFilterTest );
REGISTER_TEST(itkImportImageTest );
REGISTER_TEST(itkIntensityWindowingImageFilterTest );
REGISTER_TEST(itkInteriorExteriorMeshFilterTest );
REGISTER_TEST(itkInterpolateImageFilterTest );
REGISTER_TEST(itkInterpolateImagePointsFilterTest );
REGISTER_TEST(itkIsolatedConnectedImageFilterTest );
REGISTER_TEST(itkJoinImageFilterTest );
REGISTER_TEST(itkLaplacianImageFilterTest );
REGISTER_TEST(itkLaplacianRecursiveGaussianImageFilterTest );
REGISTER_TEST(itkLog10ImageFilterAndAdaptorTest );
REGISTER_TEST(itkLogImageFilterAndAdaptorTest );
REGISTER_TEST(itkMaskImageFilterTest );
REGISTER_TEST(itkMathematicalMorphologyImageFilterTest );
REGISTER_TEST(itkMaximumImageFilterTest );
REGISTER_TEST(itkMeanImageFilterTest );
REGISTER_TEST(itkMedianImageFilterTest );
REGISTER_TEST(itkMinimumImageFilterTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinimumMaximumImageFilterTest );
REGISTER_TEST(itkMirrorPadImageTest );
REGISTER_TEST(itkMultiplyImageFilterTest );
REGISTER_TEST(itkNaryAddImageFilterTest );
REGISTER_TEST(itkNeighborhoodConnectedImageFilterTest );
REGISTER_TEST(itkNeighborhoodOperatorImageFilterTest );
REGISTER_TEST(itkNormalizeImageFilterTest );
REGISTER_TEST(itkObjectMorphologyImageFilterTest );
REGISTER_TEST(itkPasteImageFilterTest );
REGISTER_TEST(itkPathToChainCodePathFilterTest );
REGISTER_TEST(itkPathToImageFilterTest );
REGISTER_TEST(itkPermuteAxesImageFilterTest );
REGISTER_TEST(itkPromoteDimensionImageTest);
REGISTER_TEST(itkPlaheImageFilterTest );
REGISTER_TEST(itkRGBToVectorAdaptImageFilterTest );
REGISTER_TEST(itkRecursiveGaussianImageFiltersTest );
REGISTER_TEST(itkReflectImageFilterTest );
REGISTER_TEST(itkReflectiveImageRegionIteratorTest );
REGISTER_TEST(itkRegionOfInterestImageFilterTest );
REGISTER_TEST(itkRelabelComponentImageFilterTest );
REGISTER_TEST(itkResampleImageTest );
REGISTER_TEST(itkRescaleIntensityImageFilterTest );
REGISTER_TEST(itkShiftScaleImageFilterTest );
REGISTER_TEST(itkShiftScaleInPlaceImageFilterTest );
REGISTER_TEST(itkShrinkImageTest );
REGISTER_TEST(itkSigmoidImageFilterTest );
REGISTER_TEST(itkSimilarityIndexImageFilterTest );
REGISTER_TEST(itkSinImageFilterAndAdaptorTest );
REGISTER_TEST(itkSobelEdgeDetectionImageFilterTest );
REGISTER_TEST(itkSmoothingRecursiveGaussianImageFilterTest );
REGISTER_TEST(itkSparseFieldFourthOrderLevelSetImageFilterTest );
REGISTER_TEST(itkSparseFieldLayerTest);
REGISTER_TEST(itkSpatialObjectToImageFilterTest );
REGISTER_TEST(itkSpatialObjectToImageStatisticsCalculatorTest );
REGISTER_TEST(itkSpatialFunctionImageEvaluatorFilterTest );
REGISTER_TEST(itkSqrtImageFilterAndAdaptorTest );
REGISTER_TEST(itkSquareImageFilterTest );
REGISTER_TEST(itkSquaredDifferenceImageFilterTest );
REGISTER_TEST(itkStatisticsImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest2 );
REGISTER_TEST(itkSubtractImageFilterTest );
REGISTER_TEST(itkTanImageFilterAndAdaptorTest );
REGISTER_TEST(itkTernaryMagnitudeImageFilterTest );
REGISTER_TEST(itkThresholdImageFilterTest );
REGISTER_TEST(itkTobogganImageFilterTest );
REGISTER_TEST(itkTransformMeshFilterTest );
REGISTER_TEST(itkTwoOutputExampleImageFilterTest );
REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkVectorExpandImageFilterTest );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest1 );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest2 );
REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest );
REGISTER_TEST(itkVectorConfidenceConnectedImageFilterTest );
REGISTER_TEST(itkWarpImageFilterTest );
REGISTER_TEST(itkWrapPadImageTest );
REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest );
REGISTER_TEST(itkZeroCrossingImageFilterTest );
}
<commit_msg>ENH: Added new test for narrow band classes<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBasicFiltersTests.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkBasicFiltersPrintTest );
REGISTER_TEST(itkBasicFiltersPrintTest2 );
REGISTER_TEST(itkAcosImageFilterAndAdaptorTest );
REGISTER_TEST(itkAdaptImageFilterTest );
REGISTER_TEST(itkAdaptImageFilterTest2 );
REGISTER_TEST(itkAdaptiveHistogramEqualizationImageFilterTest);
REGISTER_TEST(itkAddImageFilterTest );
REGISTER_TEST(itkAsinImageFilterAndAdaptorTest );
REGISTER_TEST(itkAtanImageFilterAndAdaptorTest );
REGISTER_TEST(itkBSplineDecompositionImageFilterTest );
REGISTER_TEST(itkBSplineInterpolateImageFunctionTest );
REGISTER_TEST(itkBSplineResampleImageFilterTest );
REGISTER_TEST(itkBSplineResampleImageFunctionTest );
REGISTER_TEST(itkBasicArchitectureTest );
REGISTER_TEST(itkBilateralImageFilterTest );
REGISTER_TEST(itkBilateralImageFilterTest2 );
REGISTER_TEST(itkBilateralImageFilterTest3 );
REGISTER_TEST(itkBinaryDilateImageFilterTest );
REGISTER_TEST(itkBinaryErodeImageFilterTest );
REGISTER_TEST(itkBinaryMagnitudeImageFilterTest );
REGISTER_TEST(itkBinaryMaskToNarrowBandPointSetFilterTest);
REGISTER_TEST(itkBinaryMedianImageFilterTest );
REGISTER_TEST(itkBinaryThresholdImageFilterTest );
REGISTER_TEST(itkBloxBoundaryPointImageTest );
REGISTER_TEST(itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilterTest );
REGISTER_TEST(itkBloxCoreAtomTest );
REGISTER_TEST(itkCannyEdgeDetectionImageFilterTest );
REGISTER_TEST(itkChangeInformationImageFilterTest );
REGISTER_TEST(itkComposeRGBImageFilterTest );
REGISTER_TEST(itkConfidenceConnectedImageFilterTest );
REGISTER_TEST(itkConnectedComponentImageFilterTest );
REGISTER_TEST(itkConnectedThresholdImageFilterTest );
REGISTER_TEST(itkConstantPadImageTest );
REGISTER_TEST(itkCosImageFilterAndAdaptorTest );
REGISTER_TEST(itkCropImageFilterTest );
REGISTER_TEST(itkCurvatureAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkCyclicReferences );
REGISTER_TEST(itkDanielssonDistanceMapImageFilterTest );
REGISTER_TEST(itkDerivativeImageFilterTest );
REGISTER_TEST(itkDifferenceOfGaussiansGradientTest );
REGISTER_TEST(itkDiscreteGaussianImageFilterTest );
REGISTER_TEST(itkDivideImageFilterTest );
REGISTER_TEST(itkDoubleThresholdImageFilterTest );
REGISTER_TEST(itkEdgePotentialImageFilterTest );
REGISTER_TEST(itkEigenAnalysis2DImageFilterTest );
REGISTER_TEST(itkExpImageFilterAndAdaptorTest );
REGISTER_TEST(itkExpNegativeImageFilterAndAdaptorTest );
REGISTER_TEST(itkExpandImageFilterTest );
REGISTER_TEST(itkExtractImageTest );
REGISTER_TEST(itkFilterDispatchTest );
REGISTER_TEST(itkFlipImageFilterTest );
REGISTER_TEST(itkFloodFillIteratorTest );
REGISTER_TEST(itkGaussianImageSourceTest );
REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest2 );
REGISTER_TEST(itkGradientImageFilterTest );
REGISTER_TEST(itkGradientMagnitudeImageFilterTest );
REGISTER_TEST(itkGradientMagnitudeRecursiveGaussianFilterTest );
REGISTER_TEST(itkGradientRecursiveGaussianFilterTest );
REGISTER_TEST(itkGradientToMagnitudeImageFilterTest );
REGISTER_TEST(itkGrayscaleConnectedClosingImageFilterTest );
REGISTER_TEST(itkGrayscaleConnectedOpeningImageFilterTest );
REGISTER_TEST(itkGrayscaleFillholeImageFilterTest );
REGISTER_TEST(itkHardConnectedComponentImageFilterTest );
REGISTER_TEST(itkHausdorffDistanceImageFilterTest );
REGISTER_TEST(itkHConvexConcaveImageFilterTest );
REGISTER_TEST(itkHMaximaMinimaImageFilterTest );
REGISTER_TEST(itkHoughTransform2DCirclesImageTest );
REGISTER_TEST(itkHoughTransform2DLinesImageTest );
REGISTER_TEST(itkImageAdaptorNthElementTest );
REGISTER_TEST(itkImageAdaptorPipeLineTest );
REGISTER_TEST(itkImageToParametricSpaceFilterTest );
REGISTER_TEST(itkImportImageTest );
REGISTER_TEST(itkIntensityWindowingImageFilterTest );
REGISTER_TEST(itkInteriorExteriorMeshFilterTest );
REGISTER_TEST(itkInterpolateImageFilterTest );
REGISTER_TEST(itkInterpolateImagePointsFilterTest );
REGISTER_TEST(itkIsolatedConnectedImageFilterTest );
REGISTER_TEST(itkJoinImageFilterTest );
REGISTER_TEST(itkLaplacianImageFilterTest );
REGISTER_TEST(itkLaplacianRecursiveGaussianImageFilterTest );
REGISTER_TEST(itkLog10ImageFilterAndAdaptorTest );
REGISTER_TEST(itkLogImageFilterAndAdaptorTest );
REGISTER_TEST(itkMaskImageFilterTest );
REGISTER_TEST(itkMathematicalMorphologyImageFilterTest );
REGISTER_TEST(itkMaximumImageFilterTest );
REGISTER_TEST(itkMeanImageFilterTest );
REGISTER_TEST(itkMedianImageFilterTest );
REGISTER_TEST(itkMinimumImageFilterTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinimumMaximumImageFilterTest );
REGISTER_TEST(itkMirrorPadImageTest );
REGISTER_TEST(itkMultiplyImageFilterTest );
REGISTER_TEST(itkNaryAddImageFilterTest );
REGISTER_TEST(itkNarrowBandImageFilterBaseTest );
REGISTER_TEST(itkNarrowBandTest );
REGISTER_TEST(itkNeighborhoodConnectedImageFilterTest );
REGISTER_TEST(itkNeighborhoodOperatorImageFilterTest );
REGISTER_TEST(itkNormalizeImageFilterTest );
REGISTER_TEST(itkObjectMorphologyImageFilterTest );
REGISTER_TEST(itkPasteImageFilterTest );
REGISTER_TEST(itkPathToChainCodePathFilterTest );
REGISTER_TEST(itkPathToImageFilterTest );
REGISTER_TEST(itkPermuteAxesImageFilterTest );
REGISTER_TEST(itkPromoteDimensionImageTest);
REGISTER_TEST(itkPlaheImageFilterTest );
REGISTER_TEST(itkRGBToVectorAdaptImageFilterTest );
REGISTER_TEST(itkRecursiveGaussianImageFiltersTest );
REGISTER_TEST(itkReflectImageFilterTest );
REGISTER_TEST(itkReflectiveImageRegionIteratorTest );
REGISTER_TEST(itkRegionOfInterestImageFilterTest );
REGISTER_TEST(itkRelabelComponentImageFilterTest );
REGISTER_TEST(itkResampleImageTest );
REGISTER_TEST(itkRescaleIntensityImageFilterTest );
REGISTER_TEST(itkShiftScaleImageFilterTest );
REGISTER_TEST(itkShiftScaleInPlaceImageFilterTest );
REGISTER_TEST(itkShrinkImageTest );
REGISTER_TEST(itkSigmoidImageFilterTest );
REGISTER_TEST(itkSimilarityIndexImageFilterTest );
REGISTER_TEST(itkSinImageFilterAndAdaptorTest );
REGISTER_TEST(itkSobelEdgeDetectionImageFilterTest );
REGISTER_TEST(itkSmoothingRecursiveGaussianImageFilterTest );
REGISTER_TEST(itkSparseFieldFourthOrderLevelSetImageFilterTest );
REGISTER_TEST(itkSparseFieldLayerTest);
REGISTER_TEST(itkSpatialObjectToImageFilterTest );
REGISTER_TEST(itkSpatialObjectToImageStatisticsCalculatorTest );
REGISTER_TEST(itkSpatialFunctionImageEvaluatorFilterTest );
REGISTER_TEST(itkSqrtImageFilterAndAdaptorTest );
REGISTER_TEST(itkSquareImageFilterTest );
REGISTER_TEST(itkSquaredDifferenceImageFilterTest );
REGISTER_TEST(itkStatisticsImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest2 );
REGISTER_TEST(itkSubtractImageFilterTest );
REGISTER_TEST(itkTanImageFilterAndAdaptorTest );
REGISTER_TEST(itkTernaryMagnitudeImageFilterTest );
REGISTER_TEST(itkThresholdImageFilterTest );
REGISTER_TEST(itkTobogganImageFilterTest );
REGISTER_TEST(itkTransformMeshFilterTest );
REGISTER_TEST(itkTwoOutputExampleImageFilterTest );
REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkVectorExpandImageFilterTest );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest1 );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest2 );
REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest );
REGISTER_TEST(itkVectorConfidenceConnectedImageFilterTest );
REGISTER_TEST(itkWarpImageFilterTest );
REGISTER_TEST(itkWrapPadImageTest );
REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest );
REGISTER_TEST(itkZeroCrossingImageFilterTest );
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "TypeUtilities.h"
#include <clang/AST/DeclTemplate.h>
QString TypeUtilities::nestedNameSpecifierToString(const clang::NestedNameSpecifier* nestedName)
{
switch (nestedName->getKind())
{
case clang::NestedNameSpecifier::Identifier:
return QString(nestedName->getAsIdentifier()->getNameStart());
case clang::NestedNameSpecifier::Namespace:
return QString::fromStdString(nestedName->getAsNamespace()->getQualifiedNameAsString());
case clang::NestedNameSpecifier::NamespaceAlias:
return QString::fromStdString(nestedName->getAsNamespaceAlias()->getQualifiedNameAsString());
case clang::NestedNameSpecifier::Global:
// if we have the Global specifier there can not be a prefix() other wise it is invalid C++
Q_ASSERT(!nestedName->getPrefix());
return "::";
default:
Q_ASSERT(false);// Implement support for more cases if needed.
}
}
QString TypeUtilities::templateArgToString(const clang::TemplateArgument& templateArg)
{
switch (templateArg.getKind())
{
case clang::TemplateArgument::ArgKind::Null:
return {};
case clang::TemplateArgument::ArgKind::Type:
return typePtrToString(templateArg.getAsType().getTypePtr());
case clang::TemplateArgument::ArgKind::Declaration:
return QString::fromStdString(templateArg.getAsDecl()->getQualifiedNameAsString());
default:
Q_ASSERT(false); // Implement support for more cases if needed.
}
}
QString TypeUtilities::typePtrToString(const clang::Type* type)
{
if (auto recordType = llvm::dyn_cast<clang::RecordType>(type))
{
return QString::fromStdString(recordType->getDecl()->getQualifiedNameAsString());
}
else if (auto elaboratedType = llvm::dyn_cast<clang::ElaboratedType>(type))
{
// TODO: this might also have a keyword in front (like e.g. class, typename)
return typePtrToString(elaboratedType->getNamedType().getTypePtr());
}
else if (auto templateSpecialization = llvm::dyn_cast<clang::TemplateSpecializationType>(type))
{
QString baseName = QString::fromStdString(
templateSpecialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString());
if (baseName == "Super")
{
// We "unwrap" the Super baseclass
Q_ASSERT(templateSpecialization->getNumArgs() == 1u); // Super should only have one template argument!
return templateArgToString(templateSpecialization->getArg(0));
}
else
{
QStringList stringifiedTemplateArgs;
for (auto arg : *templateSpecialization) stringifiedTemplateArgs << templateArgToString(arg);
return QString("%1<%2>").arg(baseName, stringifiedTemplateArgs.join(", "));
}
}
else if (auto ptrType = llvm::dyn_cast<clang::PointerType>(type))
{
return typePtrToString(ptrType->getPointeeType().getTypePtr());
}
Q_ASSERT(false); // Implement support for more cases if needed.
}
<commit_msg>TypeUtilities only warn if type is not supported.<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "TypeUtilities.h"
#include <clang/AST/DeclTemplate.h>
QString TypeUtilities::nestedNameSpecifierToString(const clang::NestedNameSpecifier* nestedName)
{
switch (nestedName->getKind())
{
case clang::NestedNameSpecifier::Identifier:
return QString(nestedName->getAsIdentifier()->getNameStart());
case clang::NestedNameSpecifier::Namespace:
return QString::fromStdString(nestedName->getAsNamespace()->getQualifiedNameAsString());
case clang::NestedNameSpecifier::NamespaceAlias:
return QString::fromStdString(nestedName->getAsNamespaceAlias()->getQualifiedNameAsString());
case clang::NestedNameSpecifier::Global:
// if we have the Global specifier there can not be a prefix() other wise it is invalid C++
Q_ASSERT(!nestedName->getPrefix());
return "::";
default:
Q_ASSERT(false);// Implement support for more cases if needed.
}
}
QString TypeUtilities::templateArgToString(const clang::TemplateArgument& templateArg)
{
switch (templateArg.getKind())
{
case clang::TemplateArgument::ArgKind::Null:
return {};
case clang::TemplateArgument::ArgKind::Type:
return typePtrToString(templateArg.getAsType().getTypePtr());
case clang::TemplateArgument::ArgKind::Declaration:
return QString::fromStdString(templateArg.getAsDecl()->getQualifiedNameAsString());
default:
Q_ASSERT(false); // Implement support for more cases if needed.
}
}
QString TypeUtilities::typePtrToString(const clang::Type* type)
{
if (auto recordType = llvm::dyn_cast<clang::RecordType>(type))
{
return QString::fromStdString(recordType->getDecl()->getQualifiedNameAsString());
}
else if (auto elaboratedType = llvm::dyn_cast<clang::ElaboratedType>(type))
{
// TODO: this might also have a keyword in front (like e.g. class, typename)
return typePtrToString(elaboratedType->getNamedType().getTypePtr());
}
else if (auto templateSpecialization = llvm::dyn_cast<clang::TemplateSpecializationType>(type))
{
QString baseName = QString::fromStdString(
templateSpecialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString());
if (baseName == "Super")
{
// We "unwrap" the Super baseclass
Q_ASSERT(templateSpecialization->getNumArgs() == 1u); // Super should only have one template argument!
return templateArgToString(templateSpecialization->getArg(0));
}
else
{
QStringList stringifiedTemplateArgs;
for (auto arg : *templateSpecialization) stringifiedTemplateArgs << templateArgToString(arg);
return QString("%1<%2>").arg(baseName, stringifiedTemplateArgs.join(", "));
}
}
else if (auto ptrType = llvm::dyn_cast<clang::PointerType>(type))
{
return typePtrToString(ptrType->getPointeeType().getTypePtr());
}
// Implement support for more cases if needed.
qWarning() << "###Unsupported type: ###";
type->dump();
return {};
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkCropLabelMapFilterTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkCropLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
#include "itkTestingMacros.h"
int itkCropLabelMapFilterTest1(int argc, char * argv[])
{
if( argc != 5 )
{
std::cerr << "usage: " << argv[0] << " input output size0 size1" << std::endl;
return EXIT_FAILURE;
}
const unsigned int dim = 2;
typedef itk::Image< unsigned char, dim > ImageType;
typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
typedef itk::LabelMap< LabelObjectType > LabelMapType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
I2LType::Pointer i2l = I2LType::New();
i2l->SetInput( reader->GetOutput() );
typedef itk::CropLabelMapFilter< LabelMapType > ChangeType;
ChangeType::Pointer change = ChangeType::New();
change->SetInput( i2l->GetOutput() );
ChangeType::SizeType size;
size[0] = atoi( argv[3] );
size[1] = atoi( argv[4] );
change->SetCropSize( size );
TEST_SET_GET_VALUE( size, change->GetUpperBoundaryCropSize() );
TEST_SET_GET_VALUE( size, change->GetLowerBoundaryCropSize() );
itk::SimpleFilterWatcher watcher6(change, "filter");
typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
L2IType::Pointer l2i = L2IType::New();
l2i->SetInput( change->GetOutput() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( l2i->GetOutput() );
writer->SetFileName( argv[2] );
writer->UseCompressionOn();
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
<commit_msg>ENH: Full test coverage of CropLabelMapFilter. STYLE: better filter name.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkCropLabelMapFilterTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkCropLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
#include "itkTestingMacros.h"
int itkCropLabelMapFilterTest1(int argc, char * argv[])
{
if( argc != 5 )
{
std::cerr << "usage: " << argv[0] << " input output size0 size1" << std::endl;
return EXIT_FAILURE;
}
const unsigned int dim = 2;
typedef itk::Image< unsigned char, dim > ImageType;
typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
typedef itk::LabelMap< LabelObjectType > LabelMapType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
I2LType::Pointer i2l = I2LType::New();
i2l->SetInput( reader->GetOutput() );
typedef itk::CropLabelMapFilter< LabelMapType > CropType;
CropType::Pointer crop = CropType::New();
// test the behavior without input
TRY_EXPECT_EXCEPTION( crop->Update() );
crop->ResetPipeline();
crop->SetInput( i2l->GetOutput() );
CropType::SizeType size;
size[0] = atoi( argv[3] );
size[1] = atoi( argv[4] );
crop->SetCropSize( size );
TEST_SET_GET_VALUE( size, crop->GetUpperBoundaryCropSize() );
TEST_SET_GET_VALUE( size, crop->GetLowerBoundaryCropSize() );
itk::SimpleFilterWatcher watcher6(crop, "filter");
typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
L2IType::Pointer l2i = L2IType::New();
l2i->SetInput( crop->GetOutput() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( l2i->GetOutput() );
writer->SetFileName( argv[2] );
writer->UseCompressionOn();
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "SDBPRequestMessage.h"
bool SDBPRequestMessage::Read(ReadBuffer& buffer)
{
int read;
unsigned i, numNodes;
uint64_t nodeID;
if (buffer.GetLength() < 1)
return false;
switch (buffer.GetCharAt(0))
{
/* Master query */
case CLIENTREQUEST_GET_MASTER:
read = buffer.Readf("%c:%U",
&request->type, &request->commandID);
break;
/* Get config state: databases, tables, shards, quora */
case CLIENTREQUEST_GET_CONFIG_STATE:
read = buffer.Readf("%c:%U",
&request->type, &request->commandID);
break;
/* Quorum management */
case CLIENTREQUEST_CREATE_QUORUM:
read = buffer.Readf("%c:%U:%u",
&request->type, &request->commandID, &numNodes);
if (read < 0 || read == (signed)buffer.GetLength())
return false;
buffer.Advance(read);
for (i = 0; i < numNodes; i++)
{
read = buffer.Readf(":%U", &nodeID);
if (read < 0)
return false;
buffer.Advance(read);
request->nodes.Append(nodeID);
}
if (buffer.GetLength() == 0)
return true;
else
return false;
break;
case CLIENTREQUEST_ACTIVATE_NODE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID, &request->nodeID);
break;
/* Database management */
case CLIENTREQUEST_CREATE_DATABASE:
read = buffer.Readf("%c:%U:%#B",
&request->type, &request->commandID, &request->name);
break;
case CLIENTREQUEST_RENAME_DATABASE:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID, &request->databaseID,
&request->name);
break;
case CLIENTREQUEST_DELETE_DATABASE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID, &request->databaseID);
break;
case CLIENTREQUEST_SPLIT_SHARD:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->shardID, &request->key);
break;
/* Table management */
case CLIENTREQUEST_CREATE_TABLE:
read = buffer.Readf("%c:%U:%U:%U:%#B",
&request->type, &request->commandID, &request->databaseID,
&request->quorumID, &request->name);
break;
case CLIENTREQUEST_RENAME_TABLE:
read = buffer.Readf("%c:%U:%U:%U:%#B",
&request->type, &request->commandID, &request->databaseID,
&request->tableID, &request->name);
break;
case CLIENTREQUEST_DELETE_TABLE:
read = buffer.Readf("%c:%U:%U:%U",
&request->type, &request->commandID, &request->databaseID,
&request->tableID);
break;
/* Data operations */
case CLIENTREQUEST_GET:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key);
break;
case CLIENTREQUEST_SET:
case CLIENTREQUEST_SET_IF_NOT_EXISTS:
case CLIENTREQUEST_GET_AND_SET:
read = buffer.Readf("%c:%U:%U:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->value);
break;
case CLIENTREQUEST_TEST_AND_SET:
read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->test, &request->value);
break;
case CLIENTREQUEST_ADD:
read = buffer.Readf("%c:%U:%U:%#B:%I",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->number);
break;
case CLIENTREQUEST_APPEND:
read = buffer.Readf("%c:%U:%U:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->value);
break;
case CLIENTREQUEST_DELETE:
case CLIENTREQUEST_REMOVE:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key);
break;
case CLIENTREQUEST_SUBMIT:
read = buffer.Readf("%c:%U",
&request->type, &request->quorumID);
break;
default:
return false;
}
return (read == (signed)buffer.GetLength() ? true : false);
}
bool SDBPRequestMessage::Write(Buffer& buffer)
{
uint64_t* it;
switch (request->type)
{
/* Master query */
case CLIENTREQUEST_GET_MASTER:
buffer.Appendf("%c:%U",
request->type, request->commandID);
return true;
/* Get config state: databases, tables, shards, quora */
case CLIENTREQUEST_GET_CONFIG_STATE:
buffer.Appendf("%c:%U",
request->type, request->commandID);
return true;
/* Quorum management */
case CLIENTREQUEST_CREATE_QUORUM:
buffer.Appendf("%c:%U:%u",
request->type, request->commandID, request->nodes.GetLength());
for (it = request->nodes.First(); it != NULL; it = request->nodes.Next(it))
buffer.Appendf(":%U", *it);
return true;
case CLIENTREQUEST_ACTIVATE_NODE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID, request->nodeID);
return true;
/* Database management */
case CLIENTREQUEST_CREATE_DATABASE:
buffer.Appendf("%c:%U:%#B",
request->type, request->commandID, &request->name);
return true;
case CLIENTREQUEST_RENAME_DATABASE:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID, request->databaseID,
&request->name);
return true;
case CLIENTREQUEST_DELETE_DATABASE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID, request->databaseID);
return true;
case CLIENTREQUEST_SPLIT_SHARD:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID, request->shardID, &request->key);
return true;
/* Table management */
case CLIENTREQUEST_CREATE_TABLE:
buffer.Appendf("%c:%U:%U:%U:%#B",
request->type, request->commandID, request->databaseID,
request->quorumID, &request->name);
return true;
case CLIENTREQUEST_RENAME_TABLE:
buffer.Appendf("%c:%U:%U:%U:%#B",
request->type, request->commandID, request->databaseID,
request->tableID, &request->name);
return true;
case CLIENTREQUEST_DELETE_TABLE:
buffer.Appendf("%c:%U:%U:%U",
request->type, request->commandID, request->databaseID,
request->tableID);
return true;
/* Data operations */
case CLIENTREQUEST_GET:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID,
request->tableID, &request->key);
return true;
case CLIENTREQUEST_SET:
case CLIENTREQUEST_SET_IF_NOT_EXISTS:
case CLIENTREQUEST_GET_AND_SET:
buffer.Appendf("%c:%U:%U:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->value);
return true;
case CLIENTREQUEST_TEST_AND_SET:
buffer.Appendf("%c:%U:%U:%#B:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->test, &request->value);
return true;
case CLIENTREQUEST_ADD:
buffer.Appendf("%c:%U:%U:%#B:%I",
request->type, request->commandID,
request->tableID, &request->key, request->number);
return true;
case CLIENTREQUEST_APPEND:
buffer.Appendf("%c:%U:%U:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->value);
return true;
case CLIENTREQUEST_DELETE:
case CLIENTREQUEST_REMOVE:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID,
request->tableID, &request->key);
return true;
case CLIENTREQUEST_SUBMIT:
buffer.Appendf("%c:%U", request->type, request->quorumID);
return true;
default:
return false;
}
}
<commit_msg>Fixed metadata operations in SDBP.<commit_after>#include "SDBPRequestMessage.h"
bool SDBPRequestMessage::Read(ReadBuffer& buffer)
{
int read;
unsigned i, numNodes;
uint64_t nodeID;
if (buffer.GetLength() < 1)
return false;
switch (buffer.GetCharAt(0))
{
/* Master query */
case CLIENTREQUEST_GET_MASTER:
read = buffer.Readf("%c:%U",
&request->type, &request->commandID);
break;
/* Get config state: databases, tables, shards, quora */
case CLIENTREQUEST_GET_CONFIG_STATE:
read = buffer.Readf("%c:%U",
&request->type, &request->commandID);
break;
/* Quorum management */
case CLIENTREQUEST_CREATE_QUORUM:
read = buffer.Readf("%c:%U:%u",
&request->type, &request->commandID, &numNodes);
if (read < 0 || read == (signed)buffer.GetLength())
return false;
buffer.Advance(read);
for (i = 0; i < numNodes; i++)
{
read = buffer.Readf(":%U", &nodeID);
if (read < 0)
return false;
buffer.Advance(read);
request->nodes.Append(nodeID);
}
if (buffer.GetLength() == 0)
return true;
else
return false;
break;
case CLIENTREQUEST_DELETE_QUORUM:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID, &request->quorumID);
break;
case CLIENTREQUEST_ADD_NODE:
read = buffer.Readf("%c:%U:%U:%U",
&request->type, &request->commandID, &request->quorumID, &request->nodeID);
break;
case CLIENTREQUEST_REMOVE_NODE:
read = buffer.Readf("%c:%U:%U:%U",
&request->type, &request->commandID, &request->quorumID, &request->nodeID);
break;
case CLIENTREQUEST_ACTIVATE_NODE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID, &request->nodeID);
break;
/* Database management */
case CLIENTREQUEST_CREATE_DATABASE:
read = buffer.Readf("%c:%U:%#B",
&request->type, &request->commandID, &request->name);
break;
case CLIENTREQUEST_RENAME_DATABASE:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID, &request->databaseID,
&request->name);
break;
case CLIENTREQUEST_DELETE_DATABASE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID, &request->databaseID);
break;
// case CLIENTREQUEST_SPLIT_SHARD:
// read = buffer.Readf("%c:%U:%U:%#B",
// &request->type, &request->commandID,
// &request->shardID, &request->key);
// break;
/* Table management */
case CLIENTREQUEST_CREATE_TABLE:
read = buffer.Readf("%c:%U:%U:%U:%#B",
&request->type, &request->commandID, &request->databaseID,
&request->quorumID, &request->name);
break;
case CLIENTREQUEST_RENAME_TABLE:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->tableID, &request->name);
break;
case CLIENTREQUEST_DELETE_TABLE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID,
&request->tableID);
break;
case CLIENTREQUEST_TRUNCATE_TABLE:
read = buffer.Readf("%c:%U:%U",
&request->type, &request->commandID,
&request->tableID);
break;
/* Data operations */
case CLIENTREQUEST_GET:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key);
break;
case CLIENTREQUEST_SET:
case CLIENTREQUEST_SET_IF_NOT_EXISTS:
case CLIENTREQUEST_GET_AND_SET:
read = buffer.Readf("%c:%U:%U:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->value);
break;
case CLIENTREQUEST_TEST_AND_SET:
read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->test, &request->value);
break;
case CLIENTREQUEST_ADD:
read = buffer.Readf("%c:%U:%U:%#B:%I",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->number);
break;
case CLIENTREQUEST_APPEND:
read = buffer.Readf("%c:%U:%U:%#B:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key, &request->value);
break;
case CLIENTREQUEST_DELETE:
case CLIENTREQUEST_REMOVE:
read = buffer.Readf("%c:%U:%U:%#B",
&request->type, &request->commandID,
&request->tableID, &request->key);
break;
case CLIENTREQUEST_SUBMIT:
read = buffer.Readf("%c:%U",
&request->type, &request->quorumID);
break;
default:
return false;
}
return (read == (signed)buffer.GetLength() ? true : false);
}
bool SDBPRequestMessage::Write(Buffer& buffer)
{
uint64_t* it;
switch (request->type)
{
/* Master query */
case CLIENTREQUEST_GET_MASTER:
buffer.Appendf("%c:%U",
request->type, request->commandID);
return true;
/* Get config state: databases, tables, shards, quora */
case CLIENTREQUEST_GET_CONFIG_STATE:
buffer.Appendf("%c:%U",
request->type, request->commandID);
return true;
/* Quorum management */
case CLIENTREQUEST_CREATE_QUORUM:
buffer.Appendf("%c:%U:%u",
request->type, request->commandID, request->nodes.GetLength());
for (it = request->nodes.First(); it != NULL; it = request->nodes.Next(it))
buffer.Appendf(":%U", *it);
return true;
case CLIENTREQUEST_DELETE_QUORUM:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID, request->quorumID);
return true;
case CLIENTREQUEST_ADD_NODE:
buffer.Appendf("%c:%U:%U:%U",
request->type, request->commandID, request->quorumID, request->nodeID);
return true;
case CLIENTREQUEST_REMOVE_NODE:
buffer.Appendf("%c:%U:%U:%U",
request->type, request->commandID, request->quorumID, request->nodeID);
return true;
case CLIENTREQUEST_ACTIVATE_NODE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID, request->nodeID);
return true;
/* Database management */
case CLIENTREQUEST_CREATE_DATABASE:
buffer.Appendf("%c:%U:%#B",
request->type, request->commandID, &request->name);
return true;
case CLIENTREQUEST_RENAME_DATABASE:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID, request->databaseID,
&request->name);
return true;
case CLIENTREQUEST_DELETE_DATABASE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID, request->databaseID);
return true;
// case CLIENTREQUEST_SPLIT_SHARD:
// buffer.Appendf("%c:%U:%U:%#B",
// request->type, request->commandID, request->shardID, &request->key);
// return true;
/* Table management */
case CLIENTREQUEST_CREATE_TABLE:
buffer.Appendf("%c:%U:%U:%U:%#B",
request->type, request->commandID, request->databaseID,
request->quorumID, &request->name);
return true;
case CLIENTREQUEST_RENAME_TABLE:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID,
request->tableID, &request->name);
return true;
case CLIENTREQUEST_DELETE_TABLE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID,
request->tableID);
return true;
case CLIENTREQUEST_TRUNCATE_TABLE:
buffer.Appendf("%c:%U:%U",
request->type, request->commandID,
request->tableID);
return true;
/* Data operations */
case CLIENTREQUEST_GET:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID,
request->tableID, &request->key);
return true;
case CLIENTREQUEST_SET:
case CLIENTREQUEST_SET_IF_NOT_EXISTS:
case CLIENTREQUEST_GET_AND_SET:
buffer.Appendf("%c:%U:%U:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->value);
return true;
case CLIENTREQUEST_TEST_AND_SET:
buffer.Appendf("%c:%U:%U:%#B:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->test, &request->value);
return true;
case CLIENTREQUEST_ADD:
buffer.Appendf("%c:%U:%U:%#B:%I",
request->type, request->commandID,
request->tableID, &request->key, request->number);
return true;
case CLIENTREQUEST_APPEND:
buffer.Appendf("%c:%U:%U:%#B:%#B",
request->type, request->commandID,
request->tableID, &request->key, &request->value);
return true;
case CLIENTREQUEST_DELETE:
case CLIENTREQUEST_REMOVE:
buffer.Appendf("%c:%U:%U:%#B",
request->type, request->commandID,
request->tableID, &request->key);
return true;
case CLIENTREQUEST_SUBMIT:
buffer.Appendf("%c:%U", request->type, request->quorumID);
return true;
default:
return false;
}
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2016 Dawid Bautsch [email protected]
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "ImageUploader.h"
#include "ImageShackUploader.h"
ImageUploader::ImageUploader(QObject *parent) : QObject(parent)
{
}
ServicesList ImageUploader::GetServices()
{
return ServicesList { "ImageShack.us" };
}
ImageUploader * ImageUploader::CreateInstance(const QString & strServiceName)
{
if (strServiceName.toLower() == "imageshack.us")
return new ImageShackUploader(nullptr);
return nullptr;
}
QString ImageUploader::LogoResourcePath()
{
//!< Returns the resource path of the service logo.
return strLogoResourcePath;
}
void ImageUploader::SetLoginPassword(const QString & strLogin, const QString & strPassword)
{
this->strLogin = strLogin;
this->strPassword = strPassword;
}
<commit_msg>postimage.ord service enable in the popup menu.<commit_after>/*!
* Copyright (c) 2016 Dawid Bautsch [email protected]
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "ImageUploader.h"
#include "ImageShackUploader.h"
ImageUploader::ImageUploader(QObject *parent) : QObject(parent)
{
}
ServicesList ImageUploader::GetServices()
{
return ServicesList { "ImageShack.us", "postimage.org" };
}
ImageUploader * ImageUploader::CreateInstance(const QString & strServiceName)
{
if (strServiceName.toLower() == "imageshack.us")
return new ImageShackUploader(nullptr);
return nullptr;
}
QString ImageUploader::LogoResourcePath()
{
//!< Returns the resource path of the service logo.
return strLogoResourcePath;
}
void ImageUploader::SetLoginPassword(const QString & strLogin, const QString & strPassword)
{
this->strLogin = strLogin;
this->strPassword = strPassword;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Texture.h"
#include "OgreGLES2PixelFormat.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreRoot.h"
namespace Ogre {
static inline void doImageIO(const String &name, const String &group,
const String &ext,
vector<Image>::type &images,
Resource *r)
{
size_t imgIdx = images.size();
images.push_back(Image());
DataStreamPtr dstream =
ResourceGroupManager::getSingleton().openResource(
name, group, true, r);
images[imgIdx].load(dstream, ext);
}
GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader, GLES2Support& support)
: Texture(creator, name, handle, group, isManual, loader),
mTextureID(0), mGLSupport(support)
{
}
GLES2Texture::~GLES2Texture()
{
// have to call this here rather than in Resource destructor
// since calling virtual methods in base destructors causes crash
if (isLoaded())
{
unload();
}
else
{
freeInternalResources();
}
}
GLenum GLES2Texture::getGLES2TextureTarget(void) const
{
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
return GL_TEXTURE_2D;
case TEX_TYPE_CUBE_MAP:
return GL_TEXTURE_CUBE_MAP;
default:
return 0;
};
}
// Creation / loading methods
void GLES2Texture::createInternalResourcesImpl(void)
{
// Convert to nearest power-of-two size if required
mWidth = GLES2PixelUtil::optionalPO2(mWidth);
mHeight = GLES2PixelUtil::optionalPO2(mHeight);
mDepth = GLES2PixelUtil::optionalPO2(mDepth);
// Adjust format if required
mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage);
// Check requested number of mipmaps
size_t maxMips = GLES2PixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat);
if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0))
mNumRequestedMipmaps = 0;
mNumMipmaps = mNumRequestedMipmaps;
if (mNumMipmaps > maxMips)
mNumMipmaps = maxMips;
// Generate texture name
glGenTextures(1, &mTextureID);
GL_CHECK_ERROR;
// Set texture type
glBindTexture(getGLES2TextureTarget(), mTextureID);
GL_CHECK_ERROR;
#if GL_APPLE_texture_max_level
glTexParameteri( getGLES2TextureTarget(), GL_TEXTURE_MAX_LEVEL_APPLE, mNumMipmaps );
#endif
// Set some misc default parameters, these can of course be changed later
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_MIN_FILTER, GL_NEAREST);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GL_CHECK_ERROR;
// If we can do automip generation and the user desires this, do so
mMipmapsHardwareGenerated =
Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP) && !PixelUtil::isCompressed(mFormat);
if ((mUsage & TU_AUTOMIPMAP) &&
mNumRequestedMipmaps && mMipmapsHardwareGenerated)
{
glGenerateMipmap(getGLES2TextureTarget());
GL_CHECK_ERROR;
}
// Allocate internal buffer so that glTexSubImageXD can be used
// Internal format
GLenum format = GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma);
GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat);
size_t width = mWidth;
size_t height = mHeight;
size_t depth = mDepth;
if (PixelUtil::isCompressed(mFormat))
{
// Compressed formats
size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
// Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not
// accept a 0 pointer like normal glTexImageXD
// Run through this process for every mipmap to pregenerate mipmap pyramid
uint8* tmpdata = OGRE_NEW_FIX_FOR_WIN32 uint8[size];
memset(tmpdata, 0, size);
for (size_t mip = 0; mip <= mNumMipmaps; mip++)
{
size = PixelUtil::getMemorySize(width, height, depth, mFormat);
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
glCompressedTexImage2D(GL_TEXTURE_2D,
mip,
format,
width, height,
0,
size,
tmpdata);
GL_CHECK_ERROR;
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
width, height, 0,
size, tmpdata);
GL_CHECK_ERROR;
}
break;
case TEX_TYPE_3D:
default:
break;
};
// LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
// " Width: " + StringConverter::toString(width) +
// " Height: " + StringConverter::toString(height) +
// " Internal Format: " + StringConverter::toString(format)
// );
if(width > 1)
{
width = width / 2;
}
if(height > 1)
{
height = height / 2;
}
if(depth > 1)
{
depth = depth / 2;
}
}
OGRE_DELETE [] tmpdata;
}
else
{
// Run through this process to pregenerate mipmap pyramid
for(size_t mip = 0; mip <= mNumMipmaps; mip++)
{
// Normal formats
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
glTexImage2D(GL_TEXTURE_2D,
mip,
format,
width, height,
0,
format,
datatype, 0);
GL_CHECK_ERROR;
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
width, height, 0,
format, datatype, 0);
}
break;
case TEX_TYPE_3D:
default:
break;
};
// LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
// " Width: " + StringConverter::toString(width) +
// " Height: " + StringConverter::toString(height) +
// " Internal Format: " + StringConverter::toString(format)
// );
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
}
}
_createSurfaceList();
// Get final internal format
mFormat = getBuffer(0,0)->getFormat();
}
void GLES2Texture::createRenderTexture(void)
{
// Create the GL texture
// This already does everything necessary
createInternalResources();
}
void GLES2Texture::prepareImpl()
{
if (mUsage & TU_RENDERTARGET) return;
String baseName, ext;
size_t pos = mName.find_last_of(".");
baseName = mName.substr(0, pos);
if (pos != String::npos)
{
ext = mName.substr(pos+1);
}
LoadedImages loadedImages = LoadedImages(OGRE_NEW_FIX_FOR_WIN32 vector<Image>::type());
if (mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D)
{
doImageIO(mName, mGroup, ext, *loadedImages, this);
// If this is a volumetric texture set the texture type flag accordingly.
// If this is a cube map, set the texture type flag accordingly.
if ((*loadedImages)[0].hasFlag(IF_CUBEMAP))
mTextureType = TEX_TYPE_CUBE_MAP;
// If PVRTC and 0 custom mipmap disable auto mip generation and disable software mipmap creation
PixelFormat imageFormat = (*loadedImages)[0].getFormat();
if (imageFormat == PF_PVRTC_RGB2 || imageFormat == PF_PVRTC_RGBA2 ||
imageFormat == PF_PVRTC_RGB4 || imageFormat == PF_PVRTC_RGBA4)
{
size_t imageMips = (*loadedImages)[0].getNumMipmaps();
if (imageMips == 0)
{
mNumMipmaps = mNumRequestedMipmaps = imageMips;
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
}
}
else if (mTextureType == TEX_TYPE_CUBE_MAP)
{
if(getSourceFileType() == "dds")
{
// XX HACK there should be a better way to specify whether
// all faces are in the same file or not
doImageIO(mName, mGroup, ext, *loadedImages, this);
}
else
{
vector<Image>::type images(6);
ConstImagePtrList imagePtrs;
static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
for(size_t i = 0; i < 6; i++)
{
String fullName = baseName + suffixes[i];
if (!ext.empty())
fullName = fullName + "." + ext;
// find & load resource data intro stream to allow resource
// group changes if required
doImageIO(fullName, mGroup, ext, *loadedImages, this);
}
}
}
else
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"**** Unknown texture type ****",
"GLES2Texture::prepare");
}
mLoadedImages = loadedImages;
}
void GLES2Texture::unprepareImpl()
{
mLoadedImages.setNull();
}
void GLES2Texture::loadImpl()
{
if (mUsage & TU_RENDERTARGET)
{
createRenderTexture();
return;
}
// Now the only copy is on the stack and will be cleaned in case of
// exceptions being thrown from _loadImages
LoadedImages loadedImages = mLoadedImages;
mLoadedImages.setNull();
// Call internal _loadImages, not loadImage since that's external and
// will determine load status etc again
ConstImagePtrList imagePtrs;
for (size_t i = 0; i < loadedImages->size(); ++i)
{
imagePtrs.push_back(&(*loadedImages)[i]);
}
_loadImages(imagePtrs);
}
void GLES2Texture::freeInternalResourcesImpl()
{
mSurfaceList.clear();
glDeleteTextures(1, &mTextureID);
GL_CHECK_ERROR;
}
void GLES2Texture::_createSurfaceList()
{
mSurfaceList.clear();
// For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr
bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0;
// Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course,
// only when mipmap generation is desired.
bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps();
for (size_t face = 0; face < getNumFaces(); face++)
{
size_t width = mWidth;
size_t height = mHeight;
for (size_t mip = 0; mip <= getNumMipmaps(); mip++)
{
GLES2HardwarePixelBuffer *buf = OGRE_NEW GLES2TextureBuffer(mName,
getGLES2TextureTarget(),
mTextureID,
width, height,
GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma),
GLES2PixelUtil::getGLOriginDataType(mFormat),
face,
mip,
static_cast<HardwareBuffer::Usage>(mUsage),
doSoftware && mip==0, mHwGamma, mFSAA);
mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf));
// Check for error
if (buf->getWidth() == 0 ||
buf->getHeight() == 0 ||
buf->getDepth() == 0)
{
OGRE_EXCEPT(
Exception::ERR_RENDERINGAPI_ERROR,
"Zero sized texture surface on texture "+getName()+
" face "+StringConverter::toString(face)+
" mipmap "+StringConverter::toString(mip)+
". The GL driver probably refused to create the texture.",
"GLES2Texture::_createSurfaceList");
}
}
}
}
HardwarePixelBufferSharedPtr GLES2Texture::getBuffer(size_t face, size_t mipmap)
{
if (face >= getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Face index out of range",
"GLES2Texture::getBuffer");
}
if (mipmap > mNumMipmaps)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Mipmap index out of range",
"GLES2Texture::getBuffer");
}
unsigned int idx = face * (mNumMipmaps + 1) + mipmap;
assert(idx < mSurfaceList.size());
return mSurfaceList[idx];
}
}
<commit_msg>GLES2: Resolve some GL errors by excluding cube maps from getting auto generated mipmaps<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Texture.h"
#include "OgreGLES2PixelFormat.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreRoot.h"
namespace Ogre {
static inline void doImageIO(const String &name, const String &group,
const String &ext,
vector<Image>::type &images,
Resource *r)
{
size_t imgIdx = images.size();
images.push_back(Image());
DataStreamPtr dstream =
ResourceGroupManager::getSingleton().openResource(
name, group, true, r);
images[imgIdx].load(dstream, ext);
}
GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader, GLES2Support& support)
: Texture(creator, name, handle, group, isManual, loader),
mTextureID(0), mGLSupport(support)
{
}
GLES2Texture::~GLES2Texture()
{
// have to call this here rather than in Resource destructor
// since calling virtual methods in base destructors causes crash
if (isLoaded())
{
unload();
}
else
{
freeInternalResources();
}
}
GLenum GLES2Texture::getGLES2TextureTarget(void) const
{
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
return GL_TEXTURE_2D;
case TEX_TYPE_CUBE_MAP:
return GL_TEXTURE_CUBE_MAP;
default:
return 0;
};
}
// Creation / loading methods
void GLES2Texture::createInternalResourcesImpl(void)
{
// Convert to nearest power-of-two size if required
mWidth = GLES2PixelUtil::optionalPO2(mWidth);
mHeight = GLES2PixelUtil::optionalPO2(mHeight);
mDepth = GLES2PixelUtil::optionalPO2(mDepth);
// Adjust format if required
mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage);
// Check requested number of mipmaps
size_t maxMips = GLES2PixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat);
if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0))
mNumRequestedMipmaps = 0;
mNumMipmaps = mNumRequestedMipmaps;
if (mNumMipmaps > maxMips)
mNumMipmaps = maxMips;
// Generate texture name
glGenTextures(1, &mTextureID);
GL_CHECK_ERROR;
// Set texture type
glBindTexture(getGLES2TextureTarget(), mTextureID);
GL_CHECK_ERROR;
#if GL_APPLE_texture_max_level
glTexParameteri( getGLES2TextureTarget(), GL_TEXTURE_MAX_LEVEL_APPLE, mNumMipmaps );
#endif
// Set some misc default parameters, these can of course be changed later
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_MIN_FILTER, GL_NEAREST);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
GL_CHECK_ERROR;
glTexParameteri(getGLES2TextureTarget(),
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GL_CHECK_ERROR;
// If we can do automip generation and the user desires this, do so
mMipmapsHardwareGenerated =
Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP) && !PixelUtil::isCompressed(mFormat);
if ((mUsage & TU_AUTOMIPMAP) &&
mNumRequestedMipmaps && mMipmapsHardwareGenerated &&
(mTextureType != TEX_TYPE_CUBE_MAP))
{
glGenerateMipmap(getGLES2TextureTarget());
GL_CHECK_ERROR;
}
// Allocate internal buffer so that glTexSubImageXD can be used
// Internal format
GLenum format = GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma);
GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat);
size_t width = mWidth;
size_t height = mHeight;
size_t depth = mDepth;
if (PixelUtil::isCompressed(mFormat))
{
// Compressed formats
size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
// Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not
// accept a 0 pointer like normal glTexImageXD
// Run through this process for every mipmap to pregenerate mipmap pyramid
uint8* tmpdata = OGRE_NEW_FIX_FOR_WIN32 uint8[size];
memset(tmpdata, 0, size);
for (size_t mip = 0; mip <= mNumMipmaps; mip++)
{
size = PixelUtil::getMemorySize(width, height, depth, mFormat);
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
glCompressedTexImage2D(GL_TEXTURE_2D,
mip,
format,
width, height,
0,
size,
tmpdata);
GL_CHECK_ERROR;
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
width, height, 0,
size, tmpdata);
GL_CHECK_ERROR;
}
break;
case TEX_TYPE_3D:
default:
break;
};
// LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
// " Width: " + StringConverter::toString(width) +
// " Height: " + StringConverter::toString(height) +
// " Internal Format: " + StringConverter::toString(format)
// );
if(width > 1)
{
width = width / 2;
}
if(height > 1)
{
height = height / 2;
}
if(depth > 1)
{
depth = depth / 2;
}
}
OGRE_DELETE [] tmpdata;
}
else
{
// Run through this process to pregenerate mipmap pyramid
for(size_t mip = 0; mip <= mNumMipmaps; mip++)
{
// Normal formats
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
glTexImage2D(GL_TEXTURE_2D,
mip,
format,
width, height,
0,
format,
datatype, 0);
GL_CHECK_ERROR;
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
width, height, 0,
format, datatype, 0);
}
break;
case TEX_TYPE_3D:
default:
break;
};
// LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
// " Width: " + StringConverter::toString(width) +
// " Height: " + StringConverter::toString(height) +
// " Internal Format: " + StringConverter::toString(format)
// );
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
}
}
_createSurfaceList();
// Get final internal format
mFormat = getBuffer(0,0)->getFormat();
}
void GLES2Texture::createRenderTexture(void)
{
// Create the GL texture
// This already does everything necessary
createInternalResources();
}
void GLES2Texture::prepareImpl()
{
if (mUsage & TU_RENDERTARGET) return;
String baseName, ext;
size_t pos = mName.find_last_of(".");
baseName = mName.substr(0, pos);
if (pos != String::npos)
{
ext = mName.substr(pos+1);
}
LoadedImages loadedImages = LoadedImages(OGRE_NEW_FIX_FOR_WIN32 vector<Image>::type());
if (mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D)
{
doImageIO(mName, mGroup, ext, *loadedImages, this);
// If this is a volumetric texture set the texture type flag accordingly.
// If this is a cube map, set the texture type flag accordingly.
if ((*loadedImages)[0].hasFlag(IF_CUBEMAP))
mTextureType = TEX_TYPE_CUBE_MAP;
// If PVRTC and 0 custom mipmap disable auto mip generation and disable software mipmap creation
PixelFormat imageFormat = (*loadedImages)[0].getFormat();
if (imageFormat == PF_PVRTC_RGB2 || imageFormat == PF_PVRTC_RGBA2 ||
imageFormat == PF_PVRTC_RGB4 || imageFormat == PF_PVRTC_RGBA4)
{
size_t imageMips = (*loadedImages)[0].getNumMipmaps();
if (imageMips == 0)
{
mNumMipmaps = mNumRequestedMipmaps = imageMips;
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
}
}
else if (mTextureType == TEX_TYPE_CUBE_MAP)
{
if(getSourceFileType() == "dds")
{
// XX HACK there should be a better way to specify whether
// all faces are in the same file or not
doImageIO(mName, mGroup, ext, *loadedImages, this);
}
else
{
vector<Image>::type images(6);
ConstImagePtrList imagePtrs;
static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
for(size_t i = 0; i < 6; i++)
{
String fullName = baseName + suffixes[i];
if (!ext.empty())
fullName = fullName + "." + ext;
// find & load resource data intro stream to allow resource
// group changes if required
doImageIO(fullName, mGroup, ext, *loadedImages, this);
}
}
}
else
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"**** Unknown texture type ****",
"GLES2Texture::prepare");
}
mLoadedImages = loadedImages;
}
void GLES2Texture::unprepareImpl()
{
mLoadedImages.setNull();
}
void GLES2Texture::loadImpl()
{
if (mUsage & TU_RENDERTARGET)
{
createRenderTexture();
return;
}
// Now the only copy is on the stack and will be cleaned in case of
// exceptions being thrown from _loadImages
LoadedImages loadedImages = mLoadedImages;
mLoadedImages.setNull();
// Call internal _loadImages, not loadImage since that's external and
// will determine load status etc again
ConstImagePtrList imagePtrs;
for (size_t i = 0; i < loadedImages->size(); ++i)
{
imagePtrs.push_back(&(*loadedImages)[i]);
}
_loadImages(imagePtrs);
}
void GLES2Texture::freeInternalResourcesImpl()
{
mSurfaceList.clear();
glDeleteTextures(1, &mTextureID);
GL_CHECK_ERROR;
}
void GLES2Texture::_createSurfaceList()
{
mSurfaceList.clear();
// For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr
bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0;
// Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course,
// only when mipmap generation is desired.
bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps();
for (size_t face = 0; face < getNumFaces(); face++)
{
size_t width = mWidth;
size_t height = mHeight;
for (size_t mip = 0; mip <= getNumMipmaps(); mip++)
{
GLES2HardwarePixelBuffer *buf = OGRE_NEW GLES2TextureBuffer(mName,
getGLES2TextureTarget(),
mTextureID,
width, height,
GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma),
GLES2PixelUtil::getGLOriginDataType(mFormat),
face,
mip,
static_cast<HardwareBuffer::Usage>(mUsage),
doSoftware && mip==0, mHwGamma, mFSAA);
mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf));
// Check for error
if (buf->getWidth() == 0 ||
buf->getHeight() == 0 ||
buf->getDepth() == 0)
{
OGRE_EXCEPT(
Exception::ERR_RENDERINGAPI_ERROR,
"Zero sized texture surface on texture "+getName()+
" face "+StringConverter::toString(face)+
" mipmap "+StringConverter::toString(mip)+
". The GL driver probably refused to create the texture.",
"GLES2Texture::_createSurfaceList");
}
}
}
}
HardwarePixelBufferSharedPtr GLES2Texture::getBuffer(size_t face, size_t mipmap)
{
if (face >= getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Face index out of range",
"GLES2Texture::getBuffer");
}
if (mipmap > mNumMipmaps)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Mipmap index out of range",
"GLES2Texture::getBuffer");
}
unsigned int idx = face * (mNumMipmaps + 1) + mipmap;
assert(idx < mSurfaceList.size());
return mSurfaceList[idx];
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Client.hxx"
#include "net/RConnectSocket.hxx"
#include "net/SendMessage.hxx"
#include "net/ScmRightsBuilder.hxx"
#include "net/MsgHdr.hxx"
#include "io/Iovec.hxx"
#include "system/Error.hxx"
#include "util/ByteOrder.hxx"
#include <cstring>
inline
BengControlClient::BengControlClient(UniqueSocketDescriptor _socket) noexcept
:socket(std::move(_socket)) {}
BengControlClient::BengControlClient(const char *host_and_port)
:BengControlClient(ResolveConnectDatagramSocket(host_and_port,
5478)) {}
static constexpr size_t
PaddingSize(size_t size) noexcept
{
return (3 - ((size - 1) & 0x3));
}
void
BengControlClient::Send(BengProxy::ControlCommand cmd,
std::span<const std::byte> payload,
std::span<const FileDescriptor> fds) const
{
static constexpr uint32_t magic = ToBE32(BengProxy::control_magic);
const BengProxy::ControlHeader header{ToBE16(payload.size()), ToBE16(uint16_t(cmd))};
static constexpr uint8_t padding[3] = {0, 0, 0};
const struct iovec v[] = {
MakeIovecT(magic),
MakeIovecT(header),
MakeIovec(payload),
MakeIovec(std::span{padding, PaddingSize(payload.size())}),
};
MessageHeader msg{std::span{v}};
ScmRightsBuilder<1> b(msg);
for (const auto &i : fds)
b.push_back(i.Get());
b.Finish(msg);
SendMessage(socket, msg, 0);
}
std::pair<BengProxy::ControlCommand, std::string>
BengControlClient::Receive() const
{
int result = socket.WaitReadable(10000);
if (result < 0)
throw MakeErrno("poll() failed");
if (result == 0)
throw std::runtime_error("Timeout");
BengProxy::ControlHeader header;
char payload[4096];
struct iovec v[] = {
MakeIovecT(header),
MakeIovecT(payload),
};
auto msg = MakeMsgHdr(v);
auto nbytes = recvmsg(socket.Get(), &msg, 0);
if (nbytes < 0)
throw MakeErrno("recvmsg() failed");
if (size_t(nbytes) < sizeof(header))
throw std::runtime_error("Short receive");
size_t payload_length = FromBE16(header.length);
if (sizeof(header) + payload_length > size_t(nbytes))
throw std::runtime_error("Truncated datagram");
return std::make_pair(BengProxy::ControlCommand(FromBE16(header.command)),
std::string(payload, payload_length));
}
std::string
BengControlClient::MakeTcacheInvalidate(TranslationCommand cmd,
std::span<const std::byte> payload) noexcept
{
TranslationHeader h;
h.length = ToBE16(payload.size());
h.command = TranslationCommand(ToBE16(uint16_t(cmd)));
std::string result;
result.append((const char *)&h, sizeof(h));
if (!payload.empty()) {
result.append((const char *)payload.data(), payload.size());
result.append(PaddingSize(payload.size()), '\0');
}
return result;
}
std::string
BengControlClient::MakeTcacheInvalidate(TranslationCommand cmd,
const char *value) noexcept
{
const std::span value_span{value, strlen(value) + 1};
return MakeTcacheInvalidate(cmd, std::as_bytes(value_span));
}
<commit_msg>control/Client: omit the null terminator<commit_after>/*
* Copyright 2007-2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Client.hxx"
#include "net/RConnectSocket.hxx"
#include "net/SendMessage.hxx"
#include "net/ScmRightsBuilder.hxx"
#include "net/MsgHdr.hxx"
#include "io/Iovec.hxx"
#include "system/Error.hxx"
#include "util/ByteOrder.hxx"
#include <cstring>
inline
BengControlClient::BengControlClient(UniqueSocketDescriptor _socket) noexcept
:socket(std::move(_socket)) {}
BengControlClient::BengControlClient(const char *host_and_port)
:BengControlClient(ResolveConnectDatagramSocket(host_and_port,
5478)) {}
static constexpr size_t
PaddingSize(size_t size) noexcept
{
return (3 - ((size - 1) & 0x3));
}
void
BengControlClient::Send(BengProxy::ControlCommand cmd,
std::span<const std::byte> payload,
std::span<const FileDescriptor> fds) const
{
static constexpr uint32_t magic = ToBE32(BengProxy::control_magic);
const BengProxy::ControlHeader header{ToBE16(payload.size()), ToBE16(uint16_t(cmd))};
static constexpr uint8_t padding[3] = {0, 0, 0};
const struct iovec v[] = {
MakeIovecT(magic),
MakeIovecT(header),
MakeIovec(payload),
MakeIovec(std::span{padding, PaddingSize(payload.size())}),
};
MessageHeader msg{std::span{v}};
ScmRightsBuilder<1> b(msg);
for (const auto &i : fds)
b.push_back(i.Get());
b.Finish(msg);
SendMessage(socket, msg, 0);
}
std::pair<BengProxy::ControlCommand, std::string>
BengControlClient::Receive() const
{
int result = socket.WaitReadable(10000);
if (result < 0)
throw MakeErrno("poll() failed");
if (result == 0)
throw std::runtime_error("Timeout");
BengProxy::ControlHeader header;
char payload[4096];
struct iovec v[] = {
MakeIovecT(header),
MakeIovecT(payload),
};
auto msg = MakeMsgHdr(v);
auto nbytes = recvmsg(socket.Get(), &msg, 0);
if (nbytes < 0)
throw MakeErrno("recvmsg() failed");
if (size_t(nbytes) < sizeof(header))
throw std::runtime_error("Short receive");
size_t payload_length = FromBE16(header.length);
if (sizeof(header) + payload_length > size_t(nbytes))
throw std::runtime_error("Truncated datagram");
return std::make_pair(BengProxy::ControlCommand(FromBE16(header.command)),
std::string(payload, payload_length));
}
std::string
BengControlClient::MakeTcacheInvalidate(TranslationCommand cmd,
std::span<const std::byte> payload) noexcept
{
TranslationHeader h;
h.length = ToBE16(payload.size());
h.command = TranslationCommand(ToBE16(uint16_t(cmd)));
std::string result;
result.append((const char *)&h, sizeof(h));
if (!payload.empty()) {
result.append((const char *)payload.data(), payload.size());
result.append(PaddingSize(payload.size()), '\0');
}
return result;
}
std::string
BengControlClient::MakeTcacheInvalidate(TranslationCommand cmd,
const char *value) noexcept
{
const std::span value_span{value, strlen(value)};
return MakeTcacheInvalidate(cmd, std::as_bytes(value_span));
}
<|endoftext|> |
<commit_before>#line 2 "togo/tool_build/interface/command_list.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
namespace togo {
namespace tool_build {
static void print_package(
PackageCompiler const& pkg,
bool const list_resources
) {
auto const pkg_name = package_compiler::name(pkg);
TOGO_LOGF(
"[%08x] %.*s\n",
package_compiler::name_hash(pkg),
pkg_name.size, pkg_name.data
);
if (!list_resources) {
return;
} else if (array::empty(package_compiler::manifest(pkg))) {
TOGO_LOG(" no resources\n\n");
return;
}
for (auto const& metadata : package_compiler::manifest(pkg)) {
TOGO_LOGF(
" %c [%08x %016lx] %.*s\n",
metadata.last_compiled == 0 ? ' ' : 'C',
metadata.type, metadata.name_hash,
string::size(metadata.path),
fixed_array::begin(metadata.path)
);
}
TOGO_LOG("\n");
}
bool interface::command_list(
Interface const& interface,
bool const list_resources,
StringRef const* const package_names,
unsigned const num_package_names
) {
TOGO_ASSERTE(package_names || num_package_names == 0);
auto const& packages = compiler_manager::packages(interface._manager);
if (num_package_names > 0) {
PackageCompiler* pkg;
for (unsigned i = 0; i < num_package_names; ++i) {
auto const& pkg_name = package_names[i];
pkg = compiler_manager::get_package(
const_cast<CompilerManager&>(interface._manager),
resource::hash_package_name(pkg_name)
);
if (pkg) {
print_package(*pkg, true);
} else {
TOGO_LOGF(
"package not found: '%.*s'\n",
pkg_name.size, pkg_name.data
);
}
}
} else if (array::any(packages)) {
for (auto const* pkg : packages) {
print_package(*pkg, list_resources);
}
} else {
TOGO_LOG("no packages\n");
}
return true;
}
bool interface::command_list(
Interface const& interface,
KVS const& k_command_options,
KVS const& k_command
) {
bool opt_resources = false;
for (KVS const& k_opt : k_command_options) {
switch (kvs::name_hash(k_opt)) {
case "-r"_kvs_name:
if (!kvs::is_boolean(k_opt)) {
TOGO_LOG("error: -r: expected boolean value\n");
return false;
}
opt_resources = kvs::boolean(k_opt);
break;
default:
TOGO_LOGF(
"error: option '%.*s' not recognized\n",
kvs::name_size(k_opt), kvs::name(k_opt)
);
return false;
}
}
if (opt_resources) {
if (kvs::any(k_command)) {
TOGO_LOG("NB: takes no arguments with -r\n");
}
return interface::command_list(interface, true, nullptr, 0);
} else {
FixedArray<StringRef, 32> package_names{};
for (KVS const& k_pkg_name : k_command) {
if (!kvs::is_string(k_pkg_name) || kvs::string_size(k_pkg_name) == 0) {
TOGO_LOG("error: expected non-empty string argument\n");
return false;
}
fixed_array::push_back(package_names, kvs::string_ref(k_pkg_name));
}
return interface::command_list(
interface,
false,
fixed_array::begin(package_names),
fixed_array::size(package_names)
);
}
}
} // namespace tool_build
} // namespace togo
<commit_msg>tool_build/interface/command_list: output tidy.<commit_after>#line 2 "togo/tool_build/interface/command_list.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
namespace togo {
namespace tool_build {
static void print_package(
PackageCompiler const& pkg,
bool const list_resources
) {
auto const pkg_name = package_compiler::name(pkg);
TOGO_LOGF(
"[%08x] %.*s\n",
package_compiler::name_hash(pkg),
pkg_name.size, pkg_name.data
);
if (!list_resources) {
return;
} else if (array::empty(package_compiler::manifest(pkg))) {
TOGO_LOG(" no resources\n");
return;
}
for (auto const& metadata : package_compiler::manifest(pkg)) {
TOGO_LOGF(
" %c [%08x %016lx] %.*s\n",
metadata.last_compiled == 0 ? ' ' : 'C',
metadata.type, metadata.name_hash,
string::size(metadata.path),
fixed_array::begin(metadata.path)
);
}
}
bool interface::command_list(
Interface const& interface,
bool const list_resources,
StringRef const* const package_names,
unsigned const num_package_names
) {
TOGO_ASSERTE(package_names || num_package_names == 0);
auto const& packages = compiler_manager::packages(interface._manager);
if (num_package_names > 0) {
PackageCompiler* pkg;
for (unsigned i = 0; i < num_package_names; ++i) {
auto const& pkg_name = package_names[i];
pkg = compiler_manager::get_package(
const_cast<CompilerManager&>(interface._manager),
resource::hash_package_name(pkg_name)
);
if (pkg) {
print_package(*pkg, true);
if (list_resources && i + 1 < num_package_names) {
TOGO_LOG("\n");
}
} else {
TOGO_LOGF(
"package not found: '%.*s'\n",
pkg_name.size, pkg_name.data
);
}
}
} else if (array::any(packages)) {
for (unsigned i = 0; i < array::size(packages); ++i) {
auto const* pkg = packages[i];
print_package(*pkg, list_resources);
if (list_resources && i + 1 < array::size(packages)) {
TOGO_LOG("\n");
}
}
} else {
TOGO_LOG("no packages\n");
}
return true;
}
bool interface::command_list(
Interface const& interface,
KVS const& k_command_options,
KVS const& k_command
) {
bool opt_resources = false;
for (KVS const& k_opt : k_command_options) {
switch (kvs::name_hash(k_opt)) {
case "-r"_kvs_name:
if (!kvs::is_boolean(k_opt)) {
TOGO_LOG("error: -r: expected boolean value\n");
return false;
}
opt_resources = kvs::boolean(k_opt);
break;
default:
TOGO_LOGF(
"error: option '%.*s' not recognized\n",
kvs::name_size(k_opt), kvs::name(k_opt)
);
return false;
}
}
if (opt_resources) {
if (kvs::any(k_command)) {
TOGO_LOG("NB: takes no arguments with -r\n");
}
return interface::command_list(interface, true, nullptr, 0);
} else {
FixedArray<StringRef, 32> package_names{};
for (KVS const& k_pkg_name : k_command) {
if (!kvs::is_string(k_pkg_name) || kvs::string_size(k_pkg_name) == 0) {
TOGO_LOG("error: expected non-empty string argument\n");
return false;
}
fixed_array::push_back(package_names, kvs::string_ref(k_pkg_name));
}
return interface::command_list(
interface,
false,
fixed_array::begin(package_names),
fixed_array::size(package_names)
);
}
}
} // namespace tool_build
} // namespace togo
<|endoftext|> |
<commit_before>// (c) ZaKlaus 2016; Apache 2 Licensed, see LICENSE;;
#if !defined(DZM_H)
#define _CRT_SECURE_NO_WARNINGS
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#include <float.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#if defined(__linux)
#include <readline/readline.h>
#include <readline/history.h>
static inline FILE *
read_input(FILE *Stream)
{
char *Buffer = readline("");
FILE *NewStream = Stream;
if(Buffer[0] != 0)
{
add_history(Buffer);
NewStream = fmemopen((void *)Buffer, strlen(Buffer), "r");
}
return(NewStream);
}
#else
static inline FILE *
read_input(FILE *Stream)
{
return(Stream);
}
#endif
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef int32 bool32;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef intptr_t intptr;
typedef uintptr_t uintptr;
typedef size_t memory_index;
typedef size_t mi;
typedef float real32;
typedef double real64;
typedef int8 s8;
typedef int8 s08;
typedef int16 s16;
typedef int32 s32;
typedef int64 s64;
typedef bool32 b32;
typedef uint8 u8;
typedef uint8 u08;
typedef uint16 u16;
typedef uint32 u32;
typedef uint64 u64;
typedef real32 r32;
typedef real64 r64;
typedef uintptr_t umm;
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#if !defined(COMPILER_MSVC)
#define COMPILER_MSVC 0
#endif
#if !defined(COMPILER_LLVM)
#define COMPILER_LLVM 0
#endif
#include "../dzm_ver.hpp"
#define MAKE(Type, Value) make_object(Type, (void *)&Value)
#define MAKE1(Type, Value, Value1) make_object(Type, (void *)&Value, (void *)&Value1)
#define MAKE2(Type, Value, Value1, Value2) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2)
#define MAKE3(Type, Value, Value1, Value2, Value3) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2, (void *)&Value3)
#ifdef COMPILER_MSVC
#define TRAP() *(int *)0 = 0
#elif COMPILER_LLVM
#define TRAP() __builtin_trap()
#else
#define TRAP() volatile *(int *)0 = 0
#endif
#define IGNORE(x) x
#ifdef DZM_SLOW
#define zassert(Expression) if(!(Expression)) {TRAP();}
#else
#define zassert(Expression)
#endif
#define InvalidCodePath zassert(!"InvalidCodePath")
#define InvalidDefaultCase default: {InvalidCodePath;} break
#define Unreachable(Statement) return(Statement)
#define Kilobytes(Value) ((Value)*1024LL)
#define Megabytes(Value) (Kilobytes(Value)*1024LL)
#define Gigabytes(Value) (Megabytes(Value)*1024LL)
#define Terabytes(Value) (Gigabytes(Value)*1024LL)
#define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Alignment) - 1))
#define Align4(Value) ((Value + 3) & ~3)
#define Align8(Value) ((Value + 7) & ~7)
#define Align16(Value) ((Value + 15) & ~15)
#define STRINGIFY(X) #X
#define CONCAT(X,Y) X##Y
#define SQUOTE(X, I, C) char __s_quote__I; sprintf(__s_quote__I, "'%s'", X); C =
#define UL_ (u8 *)
#define L_ (s8 *)
#define MAX_VM_SIZE 4096 * 1024 * 32
static inline void
zero_size(memory_index Size, void *Ptr)
{
uint8 *Byte = (uint8 *)Ptr;
while(Size--)
{
*Byte++ = 0;
}
}
#define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0]))
#ifdef DZM_ELEVATED
#undef _ELEVATED
#define _ELEVATED 1
#else
#undef _ELEVATED
#define _ELEVATED 0
#endif
// == Memory Manager
#include "dzm_mem.hpp"
// == Util
#include "dzm_utl.hpp"
#include "dzm_log.hpp"
// == Interpreter
#include "lang/dzm_mdl.hpp"
#include "lang/dzm_lex.hpp"
#include "lang/dzm_evl.hpp"
#include "lang/dzm_prt.hpp"
#include "lang/dzm_rep.hpp"
#define DZM_H
#endif<commit_msg>Fixed Mac OS X TRAP() problem on GCC compiler.<commit_after>// (c) ZaKlaus 2016; Apache 2 Licensed, see LICENSE;;
#if !defined(DZM_H)
#define _CRT_SECURE_NO_WARNINGS
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#include <float.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#if defined(__linux)
#include <readline/readline.h>
#include <readline/history.h>
static inline FILE *
read_input(FILE *Stream)
{
char *Buffer = readline("");
FILE *NewStream = Stream;
if(Buffer[0] != 0)
{
add_history(Buffer);
NewStream = fmemopen((void *)Buffer, strlen(Buffer), "r");
}
return(NewStream);
}
#else
static inline FILE *
read_input(FILE *Stream)
{
return(Stream);
}
#endif
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef int32 bool32;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef intptr_t intptr;
typedef uintptr_t uintptr;
typedef size_t memory_index;
typedef size_t mi;
typedef float real32;
typedef double real64;
typedef int8 s8;
typedef int8 s08;
typedef int16 s16;
typedef int32 s32;
typedef int64 s64;
typedef bool32 b32;
typedef uint8 u8;
typedef uint8 u08;
typedef uint16 u16;
typedef uint32 u32;
typedef uint64 u64;
typedef real32 r32;
typedef real64 r64;
typedef uintptr_t umm;
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#if !defined(COMPILER_MSVC)
#define COMPILER_MSVC 0
#endif
#if !defined(COMPILER_LLVM)
#define COMPILER_LLVM 0
#endif
#include "../dzm_ver.hpp"
#define MAKE(Type, Value) make_object(Type, (void *)&Value)
#define MAKE1(Type, Value, Value1) make_object(Type, (void *)&Value, (void *)&Value1)
#define MAKE2(Type, Value, Value1, Value2) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2)
#define MAKE3(Type, Value, Value1, Value2, Value3) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2, (void *)&Value3)
#ifdef COMPILER_MSVC
#define TRAP() *(int *)0 = 0
#elif COMPILER_LLVM
#define TRAP() __builtin_trap()
#else
#ifdef __APPLE__
#define TRAP() __builtin_trap()
#else
#define TRAP() volatile *(int *)0 = 0
#endif
#define IGNORE(x) x
#ifdef DZM_SLOW
#define zassert(Expression) if(!(Expression)) {TRAP();}
#else
#define zassert(Expression)
#endif
#define InvalidCodePath zassert(!"InvalidCodePath")
#define InvalidDefaultCase default: {InvalidCodePath;} break
#define Unreachable(Statement) return(Statement)
#define Kilobytes(Value) ((Value)*1024LL)
#define Megabytes(Value) (Kilobytes(Value)*1024LL)
#define Gigabytes(Value) (Megabytes(Value)*1024LL)
#define Terabytes(Value) (Gigabytes(Value)*1024LL)
#define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Alignment) - 1))
#define Align4(Value) ((Value + 3) & ~3)
#define Align8(Value) ((Value + 7) & ~7)
#define Align16(Value) ((Value + 15) & ~15)
#define STRINGIFY(X) #X
#define CONCAT(X,Y) X##Y
#define SQUOTE(X, I, C) char __s_quote__I; sprintf(__s_quote__I, "'%s'", X); C =
#define UL_ (u8 *)
#define L_ (s8 *)
#define MAX_VM_SIZE 4096 * 1024 * 32
static inline void
zero_size(memory_index Size, void *Ptr)
{
uint8 *Byte = (uint8 *)Ptr;
while(Size--)
{
*Byte++ = 0;
}
}
#define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0]))
#ifdef DZM_ELEVATED
#undef _ELEVATED
#define _ELEVATED 1
#else
#undef _ELEVATED
#define _ELEVATED 0
#endif
// == Memory Manager
#include "dzm_mem.hpp"
// == Util
#include "dzm_utl.hpp"
#include "dzm_log.hpp"
// == Interpreter
#include "lang/dzm_mdl.hpp"
#include "lang/dzm_lex.hpp"
#include "lang/dzm_evl.hpp"
#include "lang/dzm_prt.hpp"
#include "lang/dzm_rep.hpp"
#define DZM_H
#endif<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"
using namespace boost;
using namespace flusspferd;
void flusspferd::load_encodings_module(object container) {
object exports = container.get_property_object("exports");
// Load the binary module
global().call("require", "binary");
create_native_function(
exports,
"convertToString", &encodings::convert_to_string);
create_native_function(
exports,
"convertFromString", &encodings::convert_from_string);
create_native_function( exports, "convert", &encodings::convert);
}
// HELPER METHODS
// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::vector_type const &in);
// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);
// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
binary const &source);
string
encodings::convert_to_string(std::string &enc, binary &source_binary) {
binary::vector_type const &source = source_binary.get_const_data();
to_lower(enc);
if (enc == "utf-8") {
binary::vector_type const &source = source_binary.get_const_data();
return string( (char*)&source[0], source.size());
}
else if (enc == "utf-16") {
// TODO: Assert on the possible alignment issue here
binary::vector_type const &source = source_binary.get_const_data();
return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
}
else {
// Not UTF-8 or UTF-16, so convert to utf-16
// Except UTF-8 seems to suffer from a byte order issue. UTF-8 is less
// error prone it seems. FIXME
iconv_t conv = open_convert(enc, "utf-8");
binary::vector_type utf16 = do_convert(conv, source);
iconv_close(conv);
return string( reinterpret_cast<char const*>(&utf16[0]), utf16.size());
}
return string();
}
object
encodings::convert_from_string(std::string &, binary const &) {
size_t n = 0;
return create_native_object<byte_string>(object(), (unsigned char*)"", n);
}
object encodings::convert(std::string &from, std::string &to,
binary &source_binary)
{
binary::vector_type const &source = source_binary.get_const_data();
to_lower(from);
to_lower(to);
if ( from == to ) {
// Encodings are the same, just return a copy of the binary
return create_native_object<byte_string>(
object(),
&source[0],
source.size()
);
}
iconv_t conv = open_convert(from, to);
binary::vector_type buf = do_convert(conv, source);
iconv_close(conv);
return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods
binary::vector_type
do_convert(iconv_t conv, binary::vector_type const &source) {
binary::vector_type outbuf;
size_t out_left,
in_left = source.size();
out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.
outbuf.resize(out_left);
const unsigned char *inbytes = &source[0],
*outbytes = &outbuf[0];
while (in_left) {
size_t n = iconv(conv,
(char**)&inbytes, &in_left,
(char**)&outbytes, &out_left
);
if (n == (size_t)(-1)) {
switch (errno) {
case E2BIG:
// Not enough space in output
// Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
// bytes(!) pre character. Probably a safe bet.
size_t new_size = in_left + in_left/4 + 32,
old_size = outbytes - &outbuf[0];
outbuf.resize(old_size + new_size);
// The vector has probably realloced, so recalculate outbytes
outbytes = &outbuf[old_size];
out_left += new_size;
continue;
case EILSEQ:
// An invalid multibyte sequence has been encountered in the input.
case EINVAL:
// An incomplete multibyte sequence has been encountered in the input.
// Since we have provided the entire input, both these cases are the
// same.
throw flusspferd::exception("convert error", "TypeError");
break;
}
}
// Else all chars got converted
in_left -= n;
}
outbuf.resize(outbytes - &outbuf[0]);
return outbuf;
}
iconv_t open_convert(std::string const &from, std::string const &to) {
iconv_t conv = iconv_open(to.c_str(), from.c_str());
if (conv == (iconv_t)(-1)) {
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return conv;
}
object
convert_via_utf8(std::string const &to, std::string const &from,
binary const &) {
iconv_t to_utf = iconv_open("utf-8", from.c_str()),
from_utf = iconv_open(to.c_str(), "utf-8");
if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {
if (to_utf)
iconv_close(to_utf);
if (from_utf)
iconv_close(from_utf);
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return object();
}
<commit_msg>core/encodings: add {} block to make the compiler not complain<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"
using namespace boost;
using namespace flusspferd;
void flusspferd::load_encodings_module(object container) {
object exports = container.get_property_object("exports");
// Load the binary module
global().call("require", "binary");
create_native_function(
exports,
"convertToString", &encodings::convert_to_string);
create_native_function(
exports,
"convertFromString", &encodings::convert_from_string);
create_native_function( exports, "convert", &encodings::convert);
}
// HELPER METHODS
// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::vector_type const &in);
// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);
// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
binary const &source);
string
encodings::convert_to_string(std::string &enc, binary &source_binary) {
binary::vector_type const &source = source_binary.get_const_data();
to_lower(enc);
if (enc == "utf-8") {
binary::vector_type const &source = source_binary.get_const_data();
return string( (char*)&source[0], source.size());
}
else if (enc == "utf-16") {
// TODO: Assert on the possible alignment issue here
binary::vector_type const &source = source_binary.get_const_data();
return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
}
else {
// Not UTF-8 or UTF-16, so convert to utf-16
// Except UTF-8 seems to suffer from a byte order issue. UTF-8 is less
// error prone it seems. FIXME
iconv_t conv = open_convert(enc, "utf-8");
binary::vector_type utf16 = do_convert(conv, source);
iconv_close(conv);
return string( reinterpret_cast<char const*>(&utf16[0]), utf16.size());
}
return string();
}
object
encodings::convert_from_string(std::string &, binary const &) {
size_t n = 0;
return create_native_object<byte_string>(object(), (unsigned char*)"", n);
}
object encodings::convert(std::string &from, std::string &to,
binary &source_binary)
{
binary::vector_type const &source = source_binary.get_const_data();
to_lower(from);
to_lower(to);
if ( from == to ) {
// Encodings are the same, just return a copy of the binary
return create_native_object<byte_string>(
object(),
&source[0],
source.size()
);
}
iconv_t conv = open_convert(from, to);
binary::vector_type buf = do_convert(conv, source);
iconv_close(conv);
return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods
binary::vector_type
do_convert(iconv_t conv, binary::vector_type const &source) {
binary::vector_type outbuf;
size_t out_left,
in_left = source.size();
out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.
outbuf.resize(out_left);
const unsigned char *inbytes = &source[0],
*outbytes = &outbuf[0];
while (in_left) {
size_t n = iconv(conv,
(char**)&inbytes, &in_left,
(char**)&outbytes, &out_left
);
if (n == (size_t)(-1)) {
switch (errno) {
case E2BIG: {
// Not enough space in output
// Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
// bytes(!) per character. Probably a safe bet.
size_t new_size = in_left + in_left/4 + 32,
old_size = outbytes - &outbuf[0];
outbuf.resize(old_size + new_size);
// The vector has probably realloced, so recalculate outbytes
outbytes = &outbuf[old_size];
out_left += new_size;
continue;
}
case EILSEQ:
// An invalid multibyte sequence has been encountered in the input.
case EINVAL:
// An incomplete multibyte sequence has been encountered in the input.
// Since we have provided the entire input, both these cases are the
// same.
throw flusspferd::exception("convert error", "TypeError");
break;
}
}
// Else all chars got converted
in_left -= n;
}
outbuf.resize(outbytes - &outbuf[0]);
return outbuf;
}
iconv_t open_convert(std::string const &from, std::string const &to) {
iconv_t conv = iconv_open(to.c_str(), from.c_str());
if (conv == (iconv_t)(-1)) {
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return conv;
}
object
convert_via_utf8(std::string const &to, std::string const &from,
binary const &) {
iconv_t to_utf = iconv_open("utf-8", from.c_str()),
from_utf = iconv_open(to.c_str(), "utf-8");
if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {
if (to_utf)
iconv_close(to_utf);
if (from_utf)
iconv_close(from_utf);
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return object();
}
<|endoftext|> |
<commit_before>#include "FunctionCallOperatorNode.h"
#include "../../Parser.h"
#include <assert.h>
namespace Three {
FunctionCallOperatorNode* FunctionCallOperatorNode::parse(Parser& parser, ASTNode* receiver) {
FunctionCallOperatorNode* node = new FunctionCallOperatorNode();
node->_receiver = receiver;
node->setOp("()");
assert(parser.next().type() == Token::Type::PunctuationOpenParen);
// now, we need to parse the arguments, each of which
// is an expression
parser.parseUntil(true, [&] (const Token& token) {
if (token.type() == Token::Type::PunctuationCloseParen) {
return true;
}
node->addChild(parser.parseExpression());
// if we run into a comma, parse it and return false
return !parser.nextIf(",");
});
// here we've ended including parsing the close-paren
if (parser.peek().type() == Token::Type::Newline) {
node->setStatement(true);
}
return node;
}
ASTNode* FunctionCallOperatorNode::receiver() const {
return _receiver;
}
TypeReference FunctionCallOperatorNode::receiverNodeType() const {
if (this->receiverIsClosure()) {
// TODO: this is a crazy hack to make sure that
// our indirection level is correct for calling closures
TypeReference ref = _receiver->nodeType();
ref.incrementIndirectionDepth();
return ref;
}
return _receiver->nodeType();
}
bool FunctionCallOperatorNode::receiverIsClosure() const {
assert(_receiver);
assert(_receiver->nodeType().referencedType());
return _receiver->nodeType().referencedType()->flavor() == DataType::Flavor::Closure;
}
void FunctionCallOperatorNode::codeGen(CSourceContext& context) {
if (this->receiverIsClosure()) {
context << "THREE_CALL_CLOSURE(";
this->_receiver->nodeType().codeGenFunction(context, "");
context << ", ";
this->_receiver->codeGen(context);
if (this->childCount() > 0) {
context << ", ";
}
} else {
this->_receiver->codeGen(context);
context << "(";
}
this->eachChildWithLast([=, &context] (ASTNode* node, bool last) {
node->codeGen(context);
if (!last) {
context << ", ";
}
});
context << ")";
}
}
<commit_msg>Small change to make it possible to call c-imported function-like macros in more situations<commit_after>#include "FunctionCallOperatorNode.h"
#include "../../Parser.h"
#include <assert.h>
namespace Three {
FunctionCallOperatorNode* FunctionCallOperatorNode::parse(Parser& parser, ASTNode* receiver) {
FunctionCallOperatorNode* node = new FunctionCallOperatorNode();
node->_receiver = receiver;
node->setOp("()");
assert(parser.next().type() == Token::Type::PunctuationOpenParen);
// now, we need to parse the arguments, each of which
// is an expression
parser.parseUntil(true, [&] (const Token& token) {
if (token.type() == Token::Type::PunctuationCloseParen) {
return true;
}
node->addChild(parser.parseExpression());
// if we run into a comma, parse it and return false
return !parser.nextIf(",");
});
// here we've ended including parsing the close-paren
if (parser.peek().type() == Token::Type::Newline) {
node->setStatement(true);
}
return node;
}
ASTNode* FunctionCallOperatorNode::receiver() const {
return _receiver;
}
TypeReference FunctionCallOperatorNode::receiverNodeType() const {
if (this->receiverIsClosure()) {
// TODO: this is a crazy hack to make sure that
// our indirection level is correct for calling closures
TypeReference ref = _receiver->nodeType();
ref.incrementIndirectionDepth();
return ref;
}
return _receiver->nodeType();
}
bool FunctionCallOperatorNode::receiverIsClosure() const {
assert(_receiver);
if (!_receiver->nodeType().referencedType()) {
return false;
}
return _receiver->nodeType().referencedType()->flavor() == DataType::Flavor::Closure;
}
void FunctionCallOperatorNode::codeGen(CSourceContext& context) {
if (this->receiverIsClosure()) {
context << "THREE_CALL_CLOSURE(";
this->_receiver->nodeType().codeGenFunction(context, "");
context << ", ";
this->_receiver->codeGen(context);
if (this->childCount() > 0) {
context << ", ";
}
} else {
this->_receiver->codeGen(context);
context << "(";
}
this->eachChildWithLast([=, &context] (ASTNode* node, bool last) {
node->codeGen(context);
if (!last) {
context << ", ";
}
});
context << ")";
}
}
<|endoftext|> |
<commit_before>#include <occa/core/device.hpp>
#include <occa/core/memory.hpp>
#include <occa/core/kernelArg.hpp>
#include <occa/tools/uva.hpp>
namespace occa {
//---[ KernelArg ]--------------------
const nullKernelArg_t nullKernelArg;
kernelArgData::kernelArgData() :
modeMemory(NULL),
size(0),
info(kArgInfo::none) {
::memset(&data, 0, sizeof(data));
}
kernelArgData::kernelArgData(const kernelArgData &other) :
modeMemory(other.modeMemory),
data(other.data),
size(other.size),
info(other.info) {}
kernelArgData& kernelArgData::operator = (const kernelArgData &other) {
modeMemory = other.modeMemory;
data = other.data;
size = other.size;
info = other.info;
return *this;
}
kernelArgData::~kernelArgData() {}
occa::modeDevice_t* kernelArgData::getModeDevice() const {
if (!modeMemory) {
return NULL;
}
return modeMemory->modeDevice;
}
occa::modeMemory_t* kernelArgData::getModeMemory() const {
return modeMemory;
}
void* kernelArgData::ptr() const {
if (!isNull()) {
if (info & kArgInfo::usePointer) {
return data.void_;
} else {
return (void*) &data;
}
}
return NULL;
}
bool kernelArgData::isNull() const {
return (info & kArgInfo::isNull);
}
void kernelArgData::setupForKernelCall(const bool isConst) const {
if (!modeMemory ||
!modeMemory->isManaged() ||
!modeMemory->modeDevice->hasSeparateMemorySpace()) {
return;
}
if (!modeMemory->inDevice()) {
modeMemory->copyFrom(modeMemory->uvaPtr, modeMemory->size);
modeMemory->memInfo |= uvaFlag::inDevice;
}
if (!isConst && !modeMemory->isStale()) {
uvaStaleMemory.push_back(modeMemory);
modeMemory->memInfo |= uvaFlag::isStale;
}
}
kernelArg::kernelArg() {}
kernelArg::~kernelArg() {}
kernelArg::kernelArg(const kernelArgData &arg) {
args.push_back(arg);
}
kernelArg::kernelArg(const kernelArg &other) :
args(other.args) {}
kernelArg& kernelArg::operator = (const kernelArg &other) {
args = other.args;
return *this;
}
template <>
kernelArg::kernelArg(modeMemory_t *arg) {
if (arg) {
add(arg->makeKernelArg());
} else {
add(kernelArg(nullKernelArg));
}
}
template <>
kernelArg::kernelArg(const modeMemory_t *arg) {
add(arg->makeKernelArg());
}
int kernelArg::size() const {
return (int) args.size();
}
device kernelArg::getDevice() const {
const int argCount = (int) args.size();
for (int i = 0; i < argCount; ++i) {
const kernelArgData &arg = args[i];
if (arg.modeMemory) {
return device(arg.modeMemory->modeDevice);
}
}
return device();
}
const kernelArgData& kernelArg::operator [] (const int index) const {
return args[index];
}
kernelArg::kernelArg(const nullKernelArg_t arg) {
kernelArgData kArg;
kArg.data.void_ = NULL;
kArg.size = sizeof(void*);
kArg.info = (
kArgInfo::usePointer
| kArgInfo::isNull
);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint8_t arg) {
kernelArgData kArg;
kArg.data.uint8_ = arg;
kArg.size = sizeof(uint8_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint16_t arg) {
kernelArgData kArg;
kArg.data.uint16_ = arg;
kArg.size = sizeof(uint16_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint32_t arg) {
kernelArgData kArg;
kArg.data.uint32_ = arg;
kArg.size = sizeof(uint32_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint64_t arg) {
kernelArgData kArg;
kArg.data.uint64_ = arg;
kArg.size = sizeof(uint64_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int8_t arg) {
kernelArgData kArg;
kArg.data.int8_ = arg;
kArg.size = sizeof(int8_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int16_t arg) {
kernelArgData kArg;
kArg.data.int16_ = arg;
kArg.size = sizeof(int16_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int32_t arg) {
kernelArgData kArg;
kArg.data.int32_ = arg;
kArg.size = sizeof(int32_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int64_t arg) {
kernelArgData kArg;
kArg.data.int64_ = arg;
kArg.size = sizeof(int64_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const float arg) {
kernelArgData kArg;
kArg.data.float_ = arg;
kArg.size = sizeof(float);
args.push_back(kArg);
}
kernelArg::kernelArg(const double arg) {
kernelArgData kArg;
kArg.data.double_ = arg;
kArg.size = sizeof(double);
args.push_back(kArg);
}
void kernelArg::add(const kernelArg &arg) {
const int newArgs = (int) arg.args.size();
for (int i = 0; i < newArgs; ++i) {
args.push_back(arg.args[i]);
}
}
void kernelArg::add(void *arg,
bool lookAtUva, bool argIsUva) {
add(arg, sizeof(void*), lookAtUva, argIsUva);
}
void kernelArg::add(void *arg, size_t bytes,
bool lookAtUva, bool argIsUva) {
modeMemory_t *modeMemory = NULL;
if (argIsUva) {
modeMemory = (modeMemory_t*) arg;
} else if (lookAtUva) {
ptrRangeMap::iterator it = uvaMap.find(arg);
if (it != uvaMap.end()) {
modeMemory = it->second;
}
}
if (modeMemory) {
add(modeMemory->makeKernelArg());
} else if (arg != NULL) {
kernelArgData kArg;
kArg.data.void_ = arg;
kArg.size = bytes;
kArg.info = kArgInfo::usePointer;
args.push_back(kArg);
}
}
int kernelArg::argumentCount(const std::vector<kernelArg> &arguments) {
const int kArgCount = (int) arguments.size();
int argc = 0;
for (int i = 0; i < kArgCount; ++i) {
argc += arguments[i].args.size();
}
return argc;
}
//====================================
}
<commit_msg>[Memory] Fixes the null case when memory size is 0<commit_after>#include <occa/core/device.hpp>
#include <occa/core/memory.hpp>
#include <occa/core/kernelArg.hpp>
#include <occa/tools/uva.hpp>
namespace occa {
//---[ KernelArg ]--------------------
const nullKernelArg_t nullKernelArg;
kernelArgData::kernelArgData() :
modeMemory(NULL),
size(0),
info(kArgInfo::none) {
::memset(&data, 0, sizeof(data));
}
kernelArgData::kernelArgData(const kernelArgData &other) :
modeMemory(other.modeMemory),
data(other.data),
size(other.size),
info(other.info) {}
kernelArgData& kernelArgData::operator = (const kernelArgData &other) {
modeMemory = other.modeMemory;
data = other.data;
size = other.size;
info = other.info;
return *this;
}
kernelArgData::~kernelArgData() {}
occa::modeDevice_t* kernelArgData::getModeDevice() const {
if (!modeMemory) {
return NULL;
}
return modeMemory->modeDevice;
}
occa::modeMemory_t* kernelArgData::getModeMemory() const {
return modeMemory;
}
void* kernelArgData::ptr() const {
if (!isNull()) {
if (info & kArgInfo::usePointer) {
return data.void_;
} else {
return (void*) &data;
}
}
return NULL;
}
bool kernelArgData::isNull() const {
return (info & kArgInfo::isNull);
}
void kernelArgData::setupForKernelCall(const bool isConst) const {
if (!modeMemory ||
!modeMemory->isManaged() ||
!modeMemory->modeDevice->hasSeparateMemorySpace()) {
return;
}
if (!modeMemory->inDevice()) {
modeMemory->copyFrom(modeMemory->uvaPtr, modeMemory->size);
modeMemory->memInfo |= uvaFlag::inDevice;
}
if (!isConst && !modeMemory->isStale()) {
uvaStaleMemory.push_back(modeMemory);
modeMemory->memInfo |= uvaFlag::isStale;
}
}
kernelArg::kernelArg() {}
kernelArg::~kernelArg() {}
kernelArg::kernelArg(const kernelArgData &arg) {
args.push_back(arg);
}
kernelArg::kernelArg(const kernelArg &other) :
args(other.args) {}
kernelArg& kernelArg::operator = (const kernelArg &other) {
args = other.args;
return *this;
}
template <>
kernelArg::kernelArg(modeMemory_t *arg) {
if (arg && arg->size) {
add(arg->makeKernelArg());
} else {
add(kernelArg(nullKernelArg));
}
}
template <>
kernelArg::kernelArg(const modeMemory_t *arg) {
add(arg->makeKernelArg());
}
int kernelArg::size() const {
return (int) args.size();
}
device kernelArg::getDevice() const {
const int argCount = (int) args.size();
for (int i = 0; i < argCount; ++i) {
const kernelArgData &arg = args[i];
if (arg.modeMemory) {
return device(arg.modeMemory->modeDevice);
}
}
return device();
}
const kernelArgData& kernelArg::operator [] (const int index) const {
return args[index];
}
kernelArg::kernelArg(const nullKernelArg_t arg) {
kernelArgData kArg;
kArg.data.void_ = NULL;
kArg.size = sizeof(void*);
kArg.info = (
kArgInfo::usePointer
| kArgInfo::isNull
);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint8_t arg) {
kernelArgData kArg;
kArg.data.uint8_ = arg;
kArg.size = sizeof(uint8_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint16_t arg) {
kernelArgData kArg;
kArg.data.uint16_ = arg;
kArg.size = sizeof(uint16_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint32_t arg) {
kernelArgData kArg;
kArg.data.uint32_ = arg;
kArg.size = sizeof(uint32_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const uint64_t arg) {
kernelArgData kArg;
kArg.data.uint64_ = arg;
kArg.size = sizeof(uint64_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int8_t arg) {
kernelArgData kArg;
kArg.data.int8_ = arg;
kArg.size = sizeof(int8_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int16_t arg) {
kernelArgData kArg;
kArg.data.int16_ = arg;
kArg.size = sizeof(int16_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int32_t arg) {
kernelArgData kArg;
kArg.data.int32_ = arg;
kArg.size = sizeof(int32_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const int64_t arg) {
kernelArgData kArg;
kArg.data.int64_ = arg;
kArg.size = sizeof(int64_t);
args.push_back(kArg);
}
kernelArg::kernelArg(const float arg) {
kernelArgData kArg;
kArg.data.float_ = arg;
kArg.size = sizeof(float);
args.push_back(kArg);
}
kernelArg::kernelArg(const double arg) {
kernelArgData kArg;
kArg.data.double_ = arg;
kArg.size = sizeof(double);
args.push_back(kArg);
}
void kernelArg::add(const kernelArg &arg) {
const int newArgs = (int) arg.args.size();
for (int i = 0; i < newArgs; ++i) {
args.push_back(arg.args[i]);
}
}
void kernelArg::add(void *arg,
bool lookAtUva, bool argIsUva) {
add(arg, sizeof(void*), lookAtUva, argIsUva);
}
void kernelArg::add(void *arg, size_t bytes,
bool lookAtUva, bool argIsUva) {
modeMemory_t *modeMemory = NULL;
if (argIsUva) {
modeMemory = (modeMemory_t*) arg;
} else if (lookAtUva) {
ptrRangeMap::iterator it = uvaMap.find(arg);
if (it != uvaMap.end()) {
modeMemory = it->second;
}
}
if (modeMemory) {
add(modeMemory->makeKernelArg());
} else if (arg != NULL) {
kernelArgData kArg;
kArg.data.void_ = arg;
kArg.size = bytes;
kArg.info = kArgInfo::usePointer;
args.push_back(kArg);
}
}
int kernelArg::argumentCount(const std::vector<kernelArg> &arguments) {
const int kArgCount = (int) arguments.size();
int argc = 0;
for (int i = 0; i < kArgCount; ++i) {
argc += arguments[i].args.size();
}
return argc;
}
//====================================
}
<|endoftext|> |
<commit_before>// RUN: %clangxx -fsanitize=undefined -O0 %s -o %t && UBSAN_OPTIONS=stack_trace_format=DEFAULT:fast_unwind_on_fatal=1 %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=undefined -O0 %s -o %t && UBSAN_OPTIONS=stack_trace_format=DEFAULT:fast_unwind_on_fatal=0 %run %t 2>&1 | FileCheck %s
// The test doesn't pass on Darwin in UBSan-TSan configuration, because TSan is
// using the slow unwinder which is not supported on Darwin. The test should
// be universal after landing of https://reviews.llvm.org/D32806.
#include <sanitizer/common_interface_defs.h>
static inline void FooBarBaz() {
__sanitizer_print_stack_trace();
}
int main() {
FooBarBaz();
return 0;
}
// CHECK: {{.*}} in FooBarBaz{{.*}}print_stack_trace.cc{{.*}}
// CHECK: {{.*}} in main{{.*}}print_stack_trace.cc{{.*}}
<commit_msg>[ubsan]: temporarily disable print_stack_trace.cc test<commit_after>// RUN: %clangxx -fsanitize=undefined -O0 %s -o %t && UBSAN_OPTIONS=stack_trace_format=DEFAULT:fast_unwind_on_fatal=1 %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=undefined -O0 %s -o %t && UBSAN_OPTIONS=stack_trace_format=DEFAULT:fast_unwind_on_fatal=0 %run %t 2>&1 | FileCheck %s
// This test is temporarily disabled due to broken unwinding on ARM.
// UNSUPPORTED: -linux-
// The test doesn't pass on Darwin in UBSan-TSan configuration, because TSan is
// using the slow unwinder which is not supported on Darwin. The test should
// be universal after landing of https://reviews.llvm.org/D32806.
#include <sanitizer/common_interface_defs.h>
static inline void FooBarBaz() {
__sanitizer_print_stack_trace();
}
int main() {
FooBarBaz();
return 0;
}
// CHECK: {{.*}} in FooBarBaz{{.*}}print_stack_trace.cc{{.*}}
// CHECK: {{.*}} in main{{.*}}print_stack_trace.cc{{.*}}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Alexander Gallego. All rights reserved.
//
#include "smf/rpc_server.h"
// seastar
#include <seastar/core/execution_stage.hh>
#include <seastar/core/metrics.hh>
#include <seastar/core/prometheus.hh>
#include "smf/histogram_seastar_utils.h"
#include "smf/log.h"
#include "smf/rpc_connection_limits.h"
#include "smf/rpc_envelope.h"
#include "smf/rpc_header_ostream.h"
namespace smf {
namespace stdx = std::experimental;
std::ostream &
operator<<(std::ostream &o, const smf::rpc_server &s) {
o << "rpc_server{args.ip=" << s.args_.ip << ", args.flags=" << s.args_.flags
<< ", args.rpc_port=" << s.args_.rpc_port
<< ", args.http_port=" << s.args_.http_port << ", rpc_routes=" << s.routes_
<< ", limits=" << *s.limits_
<< ", incoming_filters=" << s.in_filters_.size()
<< ", outgoing_filters=" << s.out_filters_.size() << "}";
return o;
}
rpc_server::rpc_server(rpc_server_args args)
: args_(args), limits_(seastar::make_lw_shared<rpc_connection_limits>(
args.memory_avail_per_core, args.recv_timeout)) {
namespace sm = seastar::metrics;
metrics_.add_group(
"smf::rpc_server",
{
sm::make_derive("active_connections", stats_->active_connections,
sm::description("Currently active connections")),
sm::make_derive("total_connections", stats_->total_connections,
sm::description("Counts a total connetions")),
sm::make_derive("incoming_bytes", stats_->in_bytes,
sm::description("Total bytes received of healthy "
"connections - ignores bad connections")),
sm::make_derive("outgoing_bytes", stats_->out_bytes,
sm::description("Total bytes sent to clients")),
sm::make_derive("bad_requests", stats_->bad_requests,
sm::description("Bad requests")),
sm::make_derive(
"no_route_requests", stats_->no_route_requests,
sm::description(
"Requests made to this sersvice with correct header but no handler")),
sm::make_derive("completed_requests", stats_->completed_requests,
sm::description("Correct round-trip returned responses")),
sm::make_derive(
"too_large_requests", stats_->too_large_requests,
sm::description(
"Requests made to this server larger than max allowedd (2GB)")),
});
}
rpc_server::~rpc_server() {}
seastar::future<std::unique_ptr<smf::histogram>>
rpc_server::copy_histogram() {
auto h = smf::histogram::make_unique();
*h += *hist_;
return seastar::make_ready_future<std::unique_ptr<smf::histogram>>(
std::move(h));
}
void
rpc_server::start() {
LOG_INFO("Starging server:{}", *this);
if (!(args_.flags & rpc_server_flags_disable_http_server)) {
LOG_INFO("Starting HTTP admin server on background future");
admin_ = seastar::make_lw_shared<seastar::http_server>("smf admin server");
LOG_INFO("HTTP server started, adding prometheus routes");
seastar::prometheus::config conf;
conf.metric_help = "smf rpc server statistics";
conf.prefix = "smf";
// start on background co-routine
seastar::prometheus::add_prometheus_routes(*admin_, conf)
.then([http_port = args_.http_port, admin = admin_, ip = args_.ip]() {
return admin
->listen(seastar::make_ipv4_address(
ip.empty() ? seastar::ipv4_addr{http_port}
: seastar::ipv4_addr{ip, http_port}))
.handle_exception([](auto ep) {
LOG_ERROR("Exception on HTTP Admin: {}", ep);
return seastar::make_exception_future<>(ep);
});
});
}
LOG_INFO("Starting rpc server");
seastar::listen_options lo;
lo.reuse_address = true;
listener_ = seastar::listen(
seastar::make_ipv4_address(
args_.ip.empty() ? seastar::ipv4_addr{args_.rpc_port}
: seastar::ipv4_addr{args_.ip, args_.rpc_port}),
lo);
seastar::keep_doing([this] {
return listener_->accept().then(
[this, stats = stats_, limits = limits_](
seastar::connected_socket fd, seastar::socket_address addr) mutable {
auto conn = seastar::make_lw_shared<rpc_server_connection>(
std::move(fd), limits, addr, stats, ++connection_idx_);
open_connections_.insert({connection_idx_, conn});
// DO NOT return the future. Need to execute in parallel
handle_client_connection(conn);
});
})
.handle_exception([this](std::exception_ptr eptr) {
stopped_.set_value();
try {
std::rethrow_exception(eptr);
} catch (const std::system_error &e) {
// Current and future \ref accept() calls will terminate immediately
auto const err_value = e.code().value();
if (err_value == 103 || err_value == 22) {
LOG_INFO("Shutting down server with expected exit codes");
} else {
LOG_ERROR("Unknown system error: {}", e);
}
} catch (const std::exception &e) {
LOG_ERROR("Abrupt server stop: {}", e);
}
});
}
seastar::future<>
rpc_server::stop() {
LOG_INFO("Stopped seastar::accept() calls");
listener_->abort_accept();
return stopped_.get_future().then([this] {
std::for_each(
open_connections_.begin(), open_connections_.end(),
[](auto &client_conn) {
try {
client_conn.second->conn.socket.shutdown_input();
} catch (...) {
LOG_ERROR("Detected error shutting down client connection: ignoring");
}
});
return reply_gate_.close().then([admin = admin_ ? admin_ : nullptr] {
if (!admin) { return seastar::make_ready_future<>(); }
return admin->stop().handle_exception([](auto ep) {
LOG_WARN("Warning (ignoring...) shutting down HTTP server: {}", ep);
return seastar::make_ready_future<>();
});
});
});
}
// NOTE!!
// Before you refactor this method, please note that parsing the body *MUST*
// come *right* after parsing the header in the same continuation chain.
// therwise you will run into incorrect parsing
//
seastar::future<>
rpc_server::handle_one_client_session(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
return rpc_recv_context::parse_header(&conn->conn)
.then([this, conn](stdx::optional<rpc::header> hdr) {
if (!hdr) {
conn->set_error("Error parsing connection header");
return seastar::make_ready_future<>();
}
auto payload_size = hdr->size();
return conn->limits()
->resources_available.wait(payload_size)
.then([this, conn, h = hdr.value(), payload_size] {
return rpc_recv_context::parse_payload(&conn->conn, std::move(h))
.then([this, conn, payload_size](auto maybe_payload) {
// Launch the actual processing on a background
dispatch_rpc(payload_size, conn, std::move(maybe_payload));
return seastar::make_ready_future<>();
});
});
});
}
seastar::future<>
rpc_server::handle_client_connection(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
return seastar::do_until(
[conn] { return !conn->is_valid(); },
[this, conn]() mutable { return handle_one_client_session(conn); })
.handle_exception([this, conn](auto ptr) {
LOG_INFO("Error with client rpc session: {}", ptr);
conn->set_error("handling client session exception");
return cleanup_dispatch_rpc(conn);
});
}
seastar::future<>
rpc_server::dispatch_rpc(int32_t payload_size,
seastar::lw_shared_ptr<rpc_server_connection> conn,
stdx::optional<rpc_recv_context> ctx) {
if (!ctx) {
conn->limits()->resources_available.signal(payload_size);
conn->set_error("Could not parse payload");
return seastar::make_ready_future<>();
}
return seastar::with_gate(
reply_gate_,
[this, conn, context = std::move(ctx.value()), payload_size]() mutable {
return do_dispatch_rpc(conn, std::move(context))
.then([this, conn] { return cleanup_dispatch_rpc(conn); })
.finally(
[m = hist_->auto_measure(), limits = conn->limits(), payload_size] {
// these limits are acquired *BEFORE* the call to dispatch_rpc()
// happens. Critical to understand memory ownership since it happens
// accross multiple futures.
limits->resources_available.signal(payload_size);
});
});
}
seastar::future<>
rpc_server::do_dispatch_rpc(seastar::lw_shared_ptr<rpc_server_connection> conn,
rpc_recv_context &&ctx) {
if (ctx.request_id() == 0) {
conn->set_error("Missing request_id. Invalid request");
return seastar::make_ready_future<>();
}
auto method_dispatch = routes_.get_handle_for_request(ctx.request_id());
if (method_dispatch == nullptr) {
conn->stats->no_route_requests++;
conn->set_error("Can't find route for request. Invalid");
return seastar::make_ready_future<>();
}
conn->stats->in_bytes += ctx.header.size() + ctx.payload.size();
/// the request follow [filters] -> handle -> [filters]
/// the only way for the handle not to receive the information is if
/// the filters invalidate the request - they have full mutable access
/// to it, or they throw an exception if they wish to interrupt the entire
/// connection
return stage_apply_incoming_filters(std::move(ctx))
.then([this, conn, method_dispatch](auto ctx) {
if (ctx.header.compression() !=
rpc::compression_flags::compression_flags_none) {
conn->set_error(fmt::format("There was no decompression filter for "
"compression enum: {}",
ctx.header.compression()));
return seastar::make_ready_future<>();
}
return method_dispatch->apply(std::move(ctx))
.then([this](rpc_envelope e) {
return stage_apply_outgoing_filters(std::move(e));
})
.then([this, conn](rpc_envelope e) {
if (!conn->is_valid()) {
DLOG_INFO("Cannot send respond. client connection '{}' "
"is invalid. Skipping reply from server",
conn->id);
return seastar::make_ready_future<>();
}
conn->stats->out_bytes += e.letter.size();
return seastar::with_semaphore(
conn->serialize_writes, 1, [conn, ee = std::move(e)]() mutable {
return smf::rpc_envelope::send(&conn->conn.ostream,
std::move(ee));
});
});
})
.then([this, conn] {
if (conn->is_valid()) { return conn->conn.ostream.flush(); }
return seastar::make_ready_future<>();
});
}
seastar::future<>
rpc_server::cleanup_dispatch_rpc(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
if (conn->has_error()) {
auto it = open_connections_.find(conn->id);
if (it != open_connections_.end()) {
open_connections_.erase(it);
LOG_ERROR("There was an error with the connection: {}",
conn->get_error());
conn->stats->bad_requests++;
conn->stats->active_connections--;
LOG_INFO("Closing connection for client: {}", conn->conn.remote_address);
try {
// after nice shutdow; force it
conn->conn.disable();
conn->conn.socket.shutdown_input();
conn->conn.socket.shutdown_output();
} catch (...) {}
}
} else {
conn->stats->completed_requests++;
}
return seastar::make_ready_future<>();
}
static thread_local auto incoming_stage = seastar::make_execution_stage(
"smf::rpc_server::incoming::filter", &rpc_server::apply_incoming_filters);
static thread_local auto outgoing_stage = seastar::make_execution_stage(
"smf::rpc_server::outgoing::filter", &rpc_server::apply_outgoing_filters);
seastar::future<rpc_recv_context>
rpc_server::apply_incoming_filters(rpc_recv_context ctx) {
return rpc_filter_apply(&in_filters_, std::move(ctx));
}
seastar::future<rpc_envelope>
rpc_server::apply_outgoing_filters(rpc_envelope e) {
return rpc_filter_apply(&out_filters_, std::move(e));
}
seastar::future<rpc_recv_context>
rpc_server::stage_apply_incoming_filters(rpc_recv_context ctx) {
return incoming_stage(this, std::move(ctx));
}
seastar::future<rpc_envelope>
rpc_server::stage_apply_outgoing_filters(rpc_envelope e) {
return outgoing_stage(this, std::move(e));
}
} // namespace smf
<commit_msg>fix typo<commit_after>// Copyright (c) 2016 Alexander Gallego. All rights reserved.
//
#include "smf/rpc_server.h"
// seastar
#include <seastar/core/execution_stage.hh>
#include <seastar/core/metrics.hh>
#include <seastar/core/prometheus.hh>
#include "smf/histogram_seastar_utils.h"
#include "smf/log.h"
#include "smf/rpc_connection_limits.h"
#include "smf/rpc_envelope.h"
#include "smf/rpc_header_ostream.h"
namespace smf {
namespace stdx = std::experimental;
std::ostream &
operator<<(std::ostream &o, const smf::rpc_server &s) {
o << "rpc_server{args.ip=" << s.args_.ip << ", args.flags=" << s.args_.flags
<< ", args.rpc_port=" << s.args_.rpc_port
<< ", args.http_port=" << s.args_.http_port << ", rpc_routes=" << s.routes_
<< ", limits=" << *s.limits_
<< ", incoming_filters=" << s.in_filters_.size()
<< ", outgoing_filters=" << s.out_filters_.size() << "}";
return o;
}
rpc_server::rpc_server(rpc_server_args args)
: args_(args), limits_(seastar::make_lw_shared<rpc_connection_limits>(
args.memory_avail_per_core, args.recv_timeout)) {
namespace sm = seastar::metrics;
metrics_.add_group(
"smf::rpc_server",
{
sm::make_derive("active_connections", stats_->active_connections,
sm::description("Currently active connections")),
sm::make_derive("total_connections", stats_->total_connections,
sm::description("Counts a total connetions")),
sm::make_derive("incoming_bytes", stats_->in_bytes,
sm::description("Total bytes received of healthy "
"connections - ignores bad connections")),
sm::make_derive("outgoing_bytes", stats_->out_bytes,
sm::description("Total bytes sent to clients")),
sm::make_derive("bad_requests", stats_->bad_requests,
sm::description("Bad requests")),
sm::make_derive(
"no_route_requests", stats_->no_route_requests,
sm::description(
"Requests made to this sersvice with correct header but no handler")),
sm::make_derive("completed_requests", stats_->completed_requests,
sm::description("Correct round-trip returned responses")),
sm::make_derive(
"too_large_requests", stats_->too_large_requests,
sm::description(
"Requests made to this server larger than max allowedd (2GB)")),
});
}
rpc_server::~rpc_server() {}
seastar::future<std::unique_ptr<smf::histogram>>
rpc_server::copy_histogram() {
auto h = smf::histogram::make_unique();
*h += *hist_;
return seastar::make_ready_future<std::unique_ptr<smf::histogram>>(
std::move(h));
}
void
rpc_server::start() {
LOG_INFO("Starting server:{}", *this);
if (!(args_.flags & rpc_server_flags_disable_http_server)) {
LOG_INFO("Starting HTTP admin server on background future");
admin_ = seastar::make_lw_shared<seastar::http_server>("smf admin server");
LOG_INFO("HTTP server started, adding prometheus routes");
seastar::prometheus::config conf;
conf.metric_help = "smf rpc server statistics";
conf.prefix = "smf";
// start on background co-routine
seastar::prometheus::add_prometheus_routes(*admin_, conf)
.then([http_port = args_.http_port, admin = admin_, ip = args_.ip]() {
return admin
->listen(seastar::make_ipv4_address(
ip.empty() ? seastar::ipv4_addr{http_port}
: seastar::ipv4_addr{ip, http_port}))
.handle_exception([](auto ep) {
LOG_ERROR("Exception on HTTP Admin: {}", ep);
return seastar::make_exception_future<>(ep);
});
});
}
LOG_INFO("Starting rpc server");
seastar::listen_options lo;
lo.reuse_address = true;
listener_ = seastar::listen(
seastar::make_ipv4_address(
args_.ip.empty() ? seastar::ipv4_addr{args_.rpc_port}
: seastar::ipv4_addr{args_.ip, args_.rpc_port}),
lo);
seastar::keep_doing([this] {
return listener_->accept().then(
[this, stats = stats_, limits = limits_](
seastar::connected_socket fd, seastar::socket_address addr) mutable {
auto conn = seastar::make_lw_shared<rpc_server_connection>(
std::move(fd), limits, addr, stats, ++connection_idx_);
open_connections_.insert({connection_idx_, conn});
// DO NOT return the future. Need to execute in parallel
handle_client_connection(conn);
});
})
.handle_exception([this](std::exception_ptr eptr) {
stopped_.set_value();
try {
std::rethrow_exception(eptr);
} catch (const std::system_error &e) {
// Current and future \ref accept() calls will terminate immediately
auto const err_value = e.code().value();
if (err_value == 103 || err_value == 22) {
LOG_INFO("Shutting down server with expected exit codes");
} else {
LOG_ERROR("Unknown system error: {}", e);
}
} catch (const std::exception &e) {
LOG_ERROR("Abrupt server stop: {}", e);
}
});
}
seastar::future<>
rpc_server::stop() {
LOG_INFO("Stopped seastar::accept() calls");
listener_->abort_accept();
return stopped_.get_future().then([this] {
std::for_each(
open_connections_.begin(), open_connections_.end(),
[](auto &client_conn) {
try {
client_conn.second->conn.socket.shutdown_input();
} catch (...) {
LOG_ERROR("Detected error shutting down client connection: ignoring");
}
});
return reply_gate_.close().then([admin = admin_ ? admin_ : nullptr] {
if (!admin) { return seastar::make_ready_future<>(); }
return admin->stop().handle_exception([](auto ep) {
LOG_WARN("Warning (ignoring...) shutting down HTTP server: {}", ep);
return seastar::make_ready_future<>();
});
});
});
}
// NOTE!!
// Before you refactor this method, please note that parsing the body *MUST*
// come *right* after parsing the header in the same continuation chain.
// therwise you will run into incorrect parsing
//
seastar::future<>
rpc_server::handle_one_client_session(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
return rpc_recv_context::parse_header(&conn->conn)
.then([this, conn](stdx::optional<rpc::header> hdr) {
if (!hdr) {
conn->set_error("Error parsing connection header");
return seastar::make_ready_future<>();
}
auto payload_size = hdr->size();
return conn->limits()
->resources_available.wait(payload_size)
.then([this, conn, h = hdr.value(), payload_size] {
return rpc_recv_context::parse_payload(&conn->conn, std::move(h))
.then([this, conn, payload_size](auto maybe_payload) {
// Launch the actual processing on a background
dispatch_rpc(payload_size, conn, std::move(maybe_payload));
return seastar::make_ready_future<>();
});
});
});
}
seastar::future<>
rpc_server::handle_client_connection(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
return seastar::do_until(
[conn] { return !conn->is_valid(); },
[this, conn]() mutable { return handle_one_client_session(conn); })
.handle_exception([this, conn](auto ptr) {
LOG_INFO("Error with client rpc session: {}", ptr);
conn->set_error("handling client session exception");
return cleanup_dispatch_rpc(conn);
});
}
seastar::future<>
rpc_server::dispatch_rpc(int32_t payload_size,
seastar::lw_shared_ptr<rpc_server_connection> conn,
stdx::optional<rpc_recv_context> ctx) {
if (!ctx) {
conn->limits()->resources_available.signal(payload_size);
conn->set_error("Could not parse payload");
return seastar::make_ready_future<>();
}
return seastar::with_gate(
reply_gate_,
[this, conn, context = std::move(ctx.value()), payload_size]() mutable {
return do_dispatch_rpc(conn, std::move(context))
.then([this, conn] { return cleanup_dispatch_rpc(conn); })
.finally(
[m = hist_->auto_measure(), limits = conn->limits(), payload_size] {
// these limits are acquired *BEFORE* the call to dispatch_rpc()
// happens. Critical to understand memory ownership since it happens
// accross multiple futures.
limits->resources_available.signal(payload_size);
});
});
}
seastar::future<>
rpc_server::do_dispatch_rpc(seastar::lw_shared_ptr<rpc_server_connection> conn,
rpc_recv_context &&ctx) {
if (ctx.request_id() == 0) {
conn->set_error("Missing request_id. Invalid request");
return seastar::make_ready_future<>();
}
auto method_dispatch = routes_.get_handle_for_request(ctx.request_id());
if (method_dispatch == nullptr) {
conn->stats->no_route_requests++;
conn->set_error("Can't find route for request. Invalid");
return seastar::make_ready_future<>();
}
conn->stats->in_bytes += ctx.header.size() + ctx.payload.size();
/// the request follow [filters] -> handle -> [filters]
/// the only way for the handle not to receive the information is if
/// the filters invalidate the request - they have full mutable access
/// to it, or they throw an exception if they wish to interrupt the entire
/// connection
return stage_apply_incoming_filters(std::move(ctx))
.then([this, conn, method_dispatch](auto ctx) {
if (ctx.header.compression() !=
rpc::compression_flags::compression_flags_none) {
conn->set_error(fmt::format("There was no decompression filter for "
"compression enum: {}",
ctx.header.compression()));
return seastar::make_ready_future<>();
}
return method_dispatch->apply(std::move(ctx))
.then([this](rpc_envelope e) {
return stage_apply_outgoing_filters(std::move(e));
})
.then([this, conn](rpc_envelope e) {
if (!conn->is_valid()) {
DLOG_INFO("Cannot send respond. client connection '{}' "
"is invalid. Skipping reply from server",
conn->id);
return seastar::make_ready_future<>();
}
conn->stats->out_bytes += e.letter.size();
return seastar::with_semaphore(
conn->serialize_writes, 1, [conn, ee = std::move(e)]() mutable {
return smf::rpc_envelope::send(&conn->conn.ostream,
std::move(ee));
});
});
})
.then([this, conn] {
if (conn->is_valid()) { return conn->conn.ostream.flush(); }
return seastar::make_ready_future<>();
});
}
seastar::future<>
rpc_server::cleanup_dispatch_rpc(
seastar::lw_shared_ptr<rpc_server_connection> conn) {
if (conn->has_error()) {
auto it = open_connections_.find(conn->id);
if (it != open_connections_.end()) {
open_connections_.erase(it);
LOG_ERROR("There was an error with the connection: {}",
conn->get_error());
conn->stats->bad_requests++;
conn->stats->active_connections--;
LOG_INFO("Closing connection for client: {}", conn->conn.remote_address);
try {
// after nice shutdow; force it
conn->conn.disable();
conn->conn.socket.shutdown_input();
conn->conn.socket.shutdown_output();
} catch (...) {}
}
} else {
conn->stats->completed_requests++;
}
return seastar::make_ready_future<>();
}
static thread_local auto incoming_stage = seastar::make_execution_stage(
"smf::rpc_server::incoming::filter", &rpc_server::apply_incoming_filters);
static thread_local auto outgoing_stage = seastar::make_execution_stage(
"smf::rpc_server::outgoing::filter", &rpc_server::apply_outgoing_filters);
seastar::future<rpc_recv_context>
rpc_server::apply_incoming_filters(rpc_recv_context ctx) {
return rpc_filter_apply(&in_filters_, std::move(ctx));
}
seastar::future<rpc_envelope>
rpc_server::apply_outgoing_filters(rpc_envelope e) {
return rpc_filter_apply(&out_filters_, std::move(e));
}
seastar::future<rpc_recv_context>
rpc_server::stage_apply_incoming_filters(rpc_recv_context ctx) {
return incoming_stage(this, std::move(ctx));
}
seastar::future<rpc_envelope>
rpc_server::stage_apply_outgoing_filters(rpc_envelope e) {
return outgoing_stage(this, std::move(e));
}
} // namespace smf
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mbuttonview.h"
#include "mbuttonview_p.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include <QFontMetricsF>
#include <QPixmap>
#include <QIcon>
#include "mbutton.h"
#include "mfeedback.h"
#include "mtheme.h"
#include "mscalableimage.h"
#include "mviewcreator.h"
#include "mscenemanager.h"
#include "mlabel.h"
#include "mdebug.h"
#include "mtimestamp.h"
// Distance in pixels from the widget bounding box inside which a release is still accepted
#define RELEASE_MISS_DELTA 30
MButtonViewPrivate::MButtonViewPrivate()
: icon(0), toggledIcon(0), label(NULL), iconFromQIcon(false), toggledIconFromQIcon(false)
{
}
void MButtonViewPrivate::freeIcons()
{
if (iconFromQIcon && icon) {
delete icon;
} else {
MTheme::releasePixmap(icon);
}
if (toggledIconFromQIcon && toggledIcon) {
delete toggledIcon;
} else {
MTheme::releasePixmap(toggledIcon);
}
icon = 0;
toggledIcon = 0;
}
MButtonViewPrivate::~MButtonViewPrivate()
{
freeIcons();
}
// As the condition of text color and background change for button
bool MButtonViewPrivate::toggleState() const
{
Q_Q(const MButtonView);
if (q->model()->checkable()) {
bool state = (!q->model()->checked() && q->model()->down())
|| (q->model()->checked() && !q->model()->down());
return state;
} else
return q->model()->down();
}
void MButtonViewPrivate::refreshStyleMode()
{
Q_Q(MButtonView);
if (q->model()->down())
q->style().setModePressed();
else if (q->model()->checked())
q->style().setModeSelected();
else
q->style().setModeDefault();
label->setAlignment(q->style()->horizontalTextAlign() | q->style()->verticalTextAlign());
label->setFont(q->style()->font());
label->setColor(q->style()->textColor());
//update the icons only if the iconSize in the style has changed
QSize size = q->style()->iconSize();
if (icon && icon->size() != size) {
if (iconFromQIcon)
loadIcon(q->model()->icon(), size);
else
loadIcon(q->model()->iconID(), size);
}
if (toggledIcon && toggledIcon->size() != size) {
if (toggledIconFromQIcon)
loadIcon(q->model()->icon(), size);
else
loadIcon(q->model()->toggledIconID(), size, QIcon::Selected);
}
calcIconTextRects();
}
void MButtonViewPrivate::calcIconTextRects()
{
Q_Q(const MButtonView);
//total horizontal and vertical text margins
int hTextMargin = q->style()->textMarginLeft() + q->style()->textMarginRight();
int vTextMargin = q->style()->textMarginTop() + q->style()->textMarginBottom();
//total horizontal and vertical padding
int hPadding = q->style()->paddingLeft() + q->style()->paddingRight();
int vPadding = q->style()->paddingTop() + q->style()->paddingBottom();
//area for the content (icon and text)
QRect contentRect(q->style()->paddingLeft(), q->style()->paddingTop(),
q->size().width() - hPadding,
q->size().height() - vPadding);
//text rect when there is no icon
QRect textRect = QRect(contentRect.left() + q->style()->textMarginLeft(),
contentRect.top() + q->style()->textMarginTop(),
contentRect.width() - hTextMargin,
contentRect.height() - vTextMargin);
//icon visible and valid?
if (q->model()->iconVisible() && (icon || toggledIcon)) {
int iconWidth = q->style()->iconSize().width();
int iconHeight = q->style()->iconSize().height();
//text visible and valid?
if (q->model()->textVisible() && !q->model()->text().isEmpty()) {
switch (q->style()->iconAlign()) {
//icon on left and text on right
case Qt::AlignLeft: {
iconRect = QRectF(contentRect.left(), contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
textRect.setX(iconRect.right() + q->style()->textMarginLeft());
textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);
break;
}
//icon on right and text on left
case Qt::AlignRight: {
iconRect = QRectF(contentRect.right() - iconWidth, contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);
break;
}
//icon on bottom and text on top
case Qt::AlignBottom: {
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.bottom() - iconHeight, iconWidth, iconHeight);
textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);
break;
}
//icon on top and text on bottom
default: {
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.top(), iconWidth, iconHeight);
textRect.setY(iconRect.bottom() + q->style()->textMarginTop());
textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);
break;
}
}
}
// no text
else {
//icon on center
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
}
}
//adjust label with button margins
label->setGeometry(textRect.translated(q->marginLeft(), q->marginTop()));
}
void MButtonViewPrivate::loadIcon(const QIcon &newQIcon, const QSize &newIconSize)
{
freeIcons();
icon = new QPixmap(newQIcon.pixmap(newIconSize));
iconFromQIcon = true;
toggledIcon = new QPixmap(newQIcon.pixmap(newIconSize, QIcon::Selected));
if (toggledIcon && !toggledIcon->isNull()) {
toggledIconFromQIcon = true;
}
}
void MButtonViewPrivate::loadIcon(const QString &newIconId, const QSize &newIconSize, QIcon::Mode mode)
{
const QPixmap **tmp;
bool *fromQIcon;
if (mode == QIcon::Selected)
{
fromQIcon = &toggledIconFromQIcon;
tmp = &toggledIcon;
}
else
{
fromQIcon = &iconFromQIcon;
tmp = &icon;
}
if (*tmp)
{
if (*fromQIcon)
delete *tmp;
else
MTheme::releasePixmap(*tmp);
}
*fromQIcon = false;
*tmp = 0;
if (!newIconId.isEmpty())
*tmp = MTheme::pixmap(newIconId, newIconSize);
}
MButtonView::MButtonView(MButton *controller) :
MWidgetView(* new MButtonViewPrivate, controller)
{
Q_D(MButtonView);
d->label = new MLabel(controller);
d->label->setParentItem(controller);
d->label->setTextElide(true);
d->label->setObjectName("ButtonLabel");
}
MButtonView::MButtonView(MButtonViewPrivate &dd, MButton *controller) :
MWidgetView(dd, controller)
{
Q_D(MButtonView);
d->label = new MLabel(controller);
d->label->setParentItem(controller);
d->label->setTextElide(true);
d->label->setObjectName("ButtonLabel");
}
MButtonView::~MButtonView()
{
Q_D(MButtonView);
if (d->label) {
delete d->label;
d->label = 0;
}
}
void MButtonView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
Q_D(MButtonView);
MWidgetView::resizeEvent(event);
d->calcIconTextRects();
}
void MButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MButtonView);
mTimestamp("MButtonView", QString("start text=%1").arg(model()->text()));
drawIcon(painter, d->iconRect);
mTimestamp("MButtonView", QString("end text=%1").arg(model()->text()));
}
void MButtonView::drawIcon(QPainter *painter, const QRectF &iconRect) const
{
if (model()->iconVisible()) {
Q_D(const MButtonView);
bool toggleState = d->toggleState();
const QPixmap *pixmap = NULL;
if (toggleState && d->toggledIcon)
pixmap = d->toggledIcon;
else
pixmap = d->icon;
if (pixmap)
painter->drawPixmap(iconRect, *pixmap, QRectF(pixmap->rect()));
}
}
/*MLabel* MButtonView::label()
{
Q_D(const MButtonView);
return d->label;
}*/
void MButtonView::applyStyle()
{
Q_D(MButtonView);
MWidgetView::applyStyle();
d->refreshStyleMode();
update();
}
void MButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event);
if (model()->down()) {
return;
}
model()->setDown(true);
style()->pressFeedback().play();
}
void MButtonView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MButtonView);
QPointF touch = event->scenePos();
QRectF rect = d->controller->sceneBoundingRect();
rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,
RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);
bool pressed = rect.contains(touch);
if ( pressed != model()->down()) {
model()->setDown(pressed);
}
}
void MButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MButtonView);
if (!model()->down()) {
return;
}
model()->setDown(false);
style()->releaseFeedback().play();
QPointF touch = event->scenePos();
QRectF rect = d->controller->sceneBoundingRect();
rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,
RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);
if (rect.contains(touch))
model()->click();
}
void MButtonView::cancelEvent(MCancelEvent *event)
{
Q_UNUSED(event);
if (!model()->down()) {
return;
}
model()->setDown(false);
}
void MButtonView::updateData(const QList<const char *>& modifications)
{
Q_D(MButtonView);
MWidgetView::updateData(modifications);
const char *member;
foreach(member, modifications) {
if (member == MButtonModel::Text) {
d->label->setText(model()->text());
d->calcIconTextRects();
} else if (member == MButtonModel::TextVisible) {
d->label->setVisible(model()->textVisible());
d->calcIconTextRects();
} else if (member == MButtonModel::IconID) {
d->loadIcon(model()->iconID(), style()->iconSize());
d->calcIconTextRects();
} else if (member == MButtonModel::ToggledIconID) {
d->loadIcon(model()->toggledIconID(), style()->iconSize(), QIcon::Selected);
d->calcIconTextRects();
} else if (member == MButtonModel::Icon) {
d->loadIcon(model()->icon(), style()->iconSize());
d->calcIconTextRects();
} else if (member == MButtonModel::IconVisible) {
d->calcIconTextRects();
} else if (member == MButtonModel::Down || member == MButtonModel::Checked ||
member == MButtonModel::Checkable) {
d->refreshStyleMode();
}
}
update();
}
void MButtonView::setupModel()
{
Q_D(MButtonView);
MWidgetView::setupModel();
QList<const char *> members;
if (model()->icon().isNull())
members << MButtonModel::IconID;
else
members << MButtonModel::Icon;
if (!model()->toggledIconID().isEmpty())
members << MButtonModel::ToggledIconID;
updateData(members);
d->label->setText(model()->text());
d->label->setVisible(model()->textVisible());
update();
}
QSizeF MButtonView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MButtonView);
if (which == Qt::MinimumSize || which == Qt::MaximumSize)
return MWidgetView::sizeHint(which, constraint);
if (style()->preferredSize().isValid())
return style()->preferredSize();
QSizeF iconSize(0, 0);
if (model()->iconVisible() && d->icon)
iconSize = d->icon->size();
QSizeF textSize(0, 0);
if (model()->textVisible() && !model()->text().isEmpty()) {
QFontMetricsF fm(style()->font());
textSize = fm.size(0, model()->text());
textSize += QSizeF(style()->textMarginLeft() + style()->textMarginRight(), style()->textMarginTop() + style()->textMarginBottom());
}
qreal width = 0, height = 0;
if (style()->iconAlign() == Qt::AlignTop || style()->iconAlign() == Qt::AlignBottom) {
width = qMax(iconSize.width(), textSize.width());
height = iconSize.height() + textSize.height();
} else {
width = iconSize.width() + textSize.width();
height = qMax(iconSize.height(), textSize.height());
}
return QSizeF(width + style()->paddingLeft() + style()->paddingRight(), height + style()->paddingTop() + style()->paddingBottom());
}
M_REGISTER_VIEW_NEW(MButtonView, MButton)
<commit_msg>Changes: Tuned feedbacks of MButton<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mbuttonview.h"
#include "mbuttonview_p.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include <QFontMetricsF>
#include <QPixmap>
#include <QIcon>
#include "mbutton.h"
#include "mfeedback.h"
#include "mtheme.h"
#include "mscalableimage.h"
#include "mviewcreator.h"
#include "mscenemanager.h"
#include "mlabel.h"
#include "mdebug.h"
#include "mtimestamp.h"
// Distance in pixels from the widget bounding box inside which a release is still accepted
#define RELEASE_MISS_DELTA 30
MButtonViewPrivate::MButtonViewPrivate()
: icon(0), toggledIcon(0), label(NULL), iconFromQIcon(false), toggledIconFromQIcon(false)
{
}
void MButtonViewPrivate::freeIcons()
{
if (iconFromQIcon && icon) {
delete icon;
} else {
MTheme::releasePixmap(icon);
}
if (toggledIconFromQIcon && toggledIcon) {
delete toggledIcon;
} else {
MTheme::releasePixmap(toggledIcon);
}
icon = 0;
toggledIcon = 0;
}
MButtonViewPrivate::~MButtonViewPrivate()
{
freeIcons();
}
// As the condition of text color and background change for button
bool MButtonViewPrivate::toggleState() const
{
Q_Q(const MButtonView);
if (q->model()->checkable()) {
bool state = (!q->model()->checked() && q->model()->down())
|| (q->model()->checked() && !q->model()->down());
return state;
} else
return q->model()->down();
}
void MButtonViewPrivate::refreshStyleMode()
{
Q_Q(MButtonView);
if (q->model()->down())
q->style().setModePressed();
else if (q->model()->checked())
q->style().setModeSelected();
else
q->style().setModeDefault();
label->setAlignment(q->style()->horizontalTextAlign() | q->style()->verticalTextAlign());
label->setFont(q->style()->font());
label->setColor(q->style()->textColor());
//update the icons only if the iconSize in the style has changed
QSize size = q->style()->iconSize();
if (icon && icon->size() != size) {
if (iconFromQIcon)
loadIcon(q->model()->icon(), size);
else
loadIcon(q->model()->iconID(), size);
}
if (toggledIcon && toggledIcon->size() != size) {
if (toggledIconFromQIcon)
loadIcon(q->model()->icon(), size);
else
loadIcon(q->model()->toggledIconID(), size, QIcon::Selected);
}
calcIconTextRects();
}
void MButtonViewPrivate::calcIconTextRects()
{
Q_Q(const MButtonView);
//total horizontal and vertical text margins
int hTextMargin = q->style()->textMarginLeft() + q->style()->textMarginRight();
int vTextMargin = q->style()->textMarginTop() + q->style()->textMarginBottom();
//total horizontal and vertical padding
int hPadding = q->style()->paddingLeft() + q->style()->paddingRight();
int vPadding = q->style()->paddingTop() + q->style()->paddingBottom();
//area for the content (icon and text)
QRect contentRect(q->style()->paddingLeft(), q->style()->paddingTop(),
q->size().width() - hPadding,
q->size().height() - vPadding);
//text rect when there is no icon
QRect textRect = QRect(contentRect.left() + q->style()->textMarginLeft(),
contentRect.top() + q->style()->textMarginTop(),
contentRect.width() - hTextMargin,
contentRect.height() - vTextMargin);
//icon visible and valid?
if (q->model()->iconVisible() && (icon || toggledIcon)) {
int iconWidth = q->style()->iconSize().width();
int iconHeight = q->style()->iconSize().height();
//text visible and valid?
if (q->model()->textVisible() && !q->model()->text().isEmpty()) {
switch (q->style()->iconAlign()) {
//icon on left and text on right
case Qt::AlignLeft: {
iconRect = QRectF(contentRect.left(), contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
textRect.setX(iconRect.right() + q->style()->textMarginLeft());
textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);
break;
}
//icon on right and text on left
case Qt::AlignRight: {
iconRect = QRectF(contentRect.right() - iconWidth, contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);
break;
}
//icon on bottom and text on top
case Qt::AlignBottom: {
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.bottom() - iconHeight, iconWidth, iconHeight);
textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);
break;
}
//icon on top and text on bottom
default: {
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.top(), iconWidth, iconHeight);
textRect.setY(iconRect.bottom() + q->style()->textMarginTop());
textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);
break;
}
}
}
// no text
else {
//icon on center
iconRect = QRectF(contentRect.center().x() - (iconWidth / 2), contentRect.center().y() - (iconHeight / 2), iconWidth, iconHeight);
}
}
//adjust label with button margins
label->setGeometry(textRect.translated(q->marginLeft(), q->marginTop()));
}
void MButtonViewPrivate::loadIcon(const QIcon &newQIcon, const QSize &newIconSize)
{
freeIcons();
icon = new QPixmap(newQIcon.pixmap(newIconSize));
iconFromQIcon = true;
toggledIcon = new QPixmap(newQIcon.pixmap(newIconSize, QIcon::Selected));
if (toggledIcon && !toggledIcon->isNull()) {
toggledIconFromQIcon = true;
}
}
void MButtonViewPrivate::loadIcon(const QString &newIconId, const QSize &newIconSize, QIcon::Mode mode)
{
const QPixmap **tmp;
bool *fromQIcon;
if (mode == QIcon::Selected)
{
fromQIcon = &toggledIconFromQIcon;
tmp = &toggledIcon;
}
else
{
fromQIcon = &iconFromQIcon;
tmp = &icon;
}
if (*tmp)
{
if (*fromQIcon)
delete *tmp;
else
MTheme::releasePixmap(*tmp);
}
*fromQIcon = false;
*tmp = 0;
if (!newIconId.isEmpty())
*tmp = MTheme::pixmap(newIconId, newIconSize);
}
MButtonView::MButtonView(MButton *controller) :
MWidgetView(* new MButtonViewPrivate, controller)
{
Q_D(MButtonView);
d->label = new MLabel(controller);
d->label->setParentItem(controller);
d->label->setTextElide(true);
d->label->setObjectName("ButtonLabel");
}
MButtonView::MButtonView(MButtonViewPrivate &dd, MButton *controller) :
MWidgetView(dd, controller)
{
Q_D(MButtonView);
d->label = new MLabel(controller);
d->label->setParentItem(controller);
d->label->setTextElide(true);
d->label->setObjectName("ButtonLabel");
}
MButtonView::~MButtonView()
{
Q_D(MButtonView);
if (d->label) {
delete d->label;
d->label = 0;
}
}
void MButtonView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
Q_D(MButtonView);
MWidgetView::resizeEvent(event);
d->calcIconTextRects();
}
void MButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MButtonView);
mTimestamp("MButtonView", QString("start text=%1").arg(model()->text()));
drawIcon(painter, d->iconRect);
mTimestamp("MButtonView", QString("end text=%1").arg(model()->text()));
}
void MButtonView::drawIcon(QPainter *painter, const QRectF &iconRect) const
{
if (model()->iconVisible()) {
Q_D(const MButtonView);
bool toggleState = d->toggleState();
const QPixmap *pixmap = NULL;
if (toggleState && d->toggledIcon)
pixmap = d->toggledIcon;
else
pixmap = d->icon;
if (pixmap)
painter->drawPixmap(iconRect, *pixmap, QRectF(pixmap->rect()));
}
}
/*MLabel* MButtonView::label()
{
Q_D(const MButtonView);
return d->label;
}*/
void MButtonView::applyStyle()
{
Q_D(MButtonView);
MWidgetView::applyStyle();
d->refreshStyleMode();
update();
}
void MButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event);
if (model()->down()) {
return;
}
model()->setDown(true);
style()->pressFeedback().play();
}
void MButtonView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MButtonView);
QPointF touch = event->scenePos();
QRectF rect = d->controller->sceneBoundingRect();
rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,
RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);
if (rect.contains(touch)) {
if (!model()->down()) {
model()->setDown(true);
style()->pressFeedback().play();
}
} else {
if (model()->down()) {
model()->setDown(false);
style()->cancelFeedback().play();
}
}
}
void MButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MButtonView);
if (!model()->down()) {
return;
}
model()->setDown(false);
style()->releaseFeedback().play();
QPointF touch = event->scenePos();
QRectF rect = d->controller->sceneBoundingRect();
rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,
RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);
if (rect.contains(touch))
model()->click();
}
void MButtonView::cancelEvent(MCancelEvent *event)
{
Q_UNUSED(event);
if (!model()->down()) {
return;
}
style()->cancelFeedback().play();
model()->setDown(false);
}
void MButtonView::updateData(const QList<const char *>& modifications)
{
Q_D(MButtonView);
MWidgetView::updateData(modifications);
const char *member;
foreach(member, modifications) {
if (member == MButtonModel::Text) {
d->label->setText(model()->text());
d->calcIconTextRects();
} else if (member == MButtonModel::TextVisible) {
d->label->setVisible(model()->textVisible());
d->calcIconTextRects();
} else if (member == MButtonModel::IconID) {
d->loadIcon(model()->iconID(), style()->iconSize());
d->calcIconTextRects();
} else if (member == MButtonModel::ToggledIconID) {
d->loadIcon(model()->toggledIconID(), style()->iconSize(), QIcon::Selected);
d->calcIconTextRects();
} else if (member == MButtonModel::Icon) {
d->loadIcon(model()->icon(), style()->iconSize());
d->calcIconTextRects();
} else if (member == MButtonModel::IconVisible) {
d->calcIconTextRects();
} else if (member == MButtonModel::Down || member == MButtonModel::Checked ||
member == MButtonModel::Checkable) {
d->refreshStyleMode();
}
}
update();
}
void MButtonView::setupModel()
{
Q_D(MButtonView);
MWidgetView::setupModel();
QList<const char *> members;
if (model()->icon().isNull())
members << MButtonModel::IconID;
else
members << MButtonModel::Icon;
if (!model()->toggledIconID().isEmpty())
members << MButtonModel::ToggledIconID;
updateData(members);
d->label->setText(model()->text());
d->label->setVisible(model()->textVisible());
update();
}
QSizeF MButtonView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MButtonView);
if (which == Qt::MinimumSize || which == Qt::MaximumSize)
return MWidgetView::sizeHint(which, constraint);
if (style()->preferredSize().isValid())
return style()->preferredSize();
QSizeF iconSize(0, 0);
if (model()->iconVisible() && d->icon)
iconSize = d->icon->size();
QSizeF textSize(0, 0);
if (model()->textVisible() && !model()->text().isEmpty()) {
QFontMetricsF fm(style()->font());
textSize = fm.size(0, model()->text());
textSize += QSizeF(style()->textMarginLeft() + style()->textMarginRight(), style()->textMarginTop() + style()->textMarginBottom());
}
qreal width = 0, height = 0;
if (style()->iconAlign() == Qt::AlignTop || style()->iconAlign() == Qt::AlignBottom) {
width = qMax(iconSize.width(), textSize.width());
height = iconSize.height() + textSize.height();
} else {
width = iconSize.width() + textSize.width();
height = qMax(iconSize.height(), textSize.height());
}
return QSizeF(width + style()->paddingLeft() + style()->paddingRight(), height + style()->paddingTop() + style()->paddingBottom());
}
M_REGISTER_VIEW_NEW(MButtonView, MButton)
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <adios2.h>
#include <adios2/common/ADIOSTypes.h>
#include <gtest/gtest.h>
class ADIOSHierarchicalReadVariableTest : public ::testing::Test
{
public:
ADIOSHierarchicalReadVariableTest() = default;
};
TEST_F(ADIOSHierarchicalReadVariableTest, Read)
{
std::string filename = "ADIOSHierarchicalReadVariable.bp";
// Number of steps
const std::size_t NSteps = 2;
long unsigned int rank, size;
#if ADIOS2_USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
#else
rank = 0;
size = 1;
#endif
// Write test data using BP
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO io = adios.DeclareIO("TestIO");
io.SetEngine("BPFile");
io.AddTransport("file");
adios2::Engine engine = io.Open(filename, adios2::Mode::Write);
const std::size_t Nx = 10;
const adios2::Dims shape = {size * Nx};
const adios2::Dims start = {rank * Nx};
const adios2::Dims count = {Nx};
auto var1 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable1", shape, start, count);
auto var2 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable2", shape, start, count);
auto var3 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable3", shape, start, count);
auto var4 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable4", shape, start, count);
auto var5 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable5", shape, start, count);
auto var6 =
io.DefineVariable<int32_t>("variable6", shape, start, count);
std::vector<int32_t> Ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (size_t step = 0; step < NSteps; ++step)
{
engine.BeginStep();
engine.Put(var1, Ints.data());
engine.Put(var2, Ints.data());
engine.Put(var3, Ints.data());
engine.Put(var4, Ints.data());
engine.Put(var5, Ints.data());
engine.Put(var6, Ints.data());
engine.EndStep();
}
engine.Close();
engine = io.Open(filename, adios2::Mode::Read);
for (size_t step = 0; step < NSteps; step++)
{
engine.BeginStep();
auto g = io.InquireGroup('/');
auto res = g.AvailableGroups();
EXPECT_EQ(res[0], "group1");
res = g.AvailableVariables();
EXPECT_EQ(res[0], "variable6");
g.setPath("group1/group2");
res = g.AvailableGroups();
EXPECT_EQ(res[0], "group3");
g.setPath("group1/group2/group3");
res = g.AvailableGroups();
EXPECT_EQ(res[0], "group4");
g.setPath("group1/group2/group3/group4");
res = g.AvailableGroups();
EXPECT_EQ(res.size(), 0);
res = g.AvailableVariables();
EXPECT_EQ(res.size(), 5);
res = g.AvailableAttributes();
EXPECT_EQ(res.size(), 0);
engine.EndStep();
}
for (size_t step = 0; step < NSteps; step++)
{
engine.BeginStep();
auto g = io.InquireGroup('/');
auto res = g.AvailableGroups();
EXPECT_EQ(res[0], "group1");
res = g.AvailableVariables();
EXPECT_EQ(res[0], "variable6");
engine.EndStep();
}
for (size_t step = 0; step < NSteps; step++)
{
auto g = io.InquireGroup('/');
auto var = g.InquireVariable<int32_t>("variable6");
EXPECT_TRUE(var);
if (var)
{
std::vector<int32_t> myInts;
var.SetSelection({{Nx * rank}, {Nx}});
engine.Get<int32_t>(var, myInts, adios2::Mode::Sync);
EXPECT_EQ(Ints, myInts);
}
}
for (size_t step = 0; step < NSteps; step++)
{
auto g = io.InquireGroup('/');
g.setPath("group1/group2/group3/group4");
auto var = g.InquireVariable<int32_t>("variable1");
EXPECT_TRUE(var);
if (var)
{
std::vector<int32_t> myInts;
var.SetSelection({{Nx * rank}, {Nx}});
engine.Get<int32_t>(var, myInts, adios2::Mode::Sync);
EXPECT_EQ(Ints, myInts);
}
}
engine.Close();
}
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fix Hierarchical test<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <adios2.h>
#include <adios2/common/ADIOSTypes.h>
#include <gtest/gtest.h>
class ADIOSHierarchicalReadVariableTest : public ::testing::Test
{
public:
ADIOSHierarchicalReadVariableTest() = default;
};
TEST_F(ADIOSHierarchicalReadVariableTest, Read)
{
std::string filename = "ADIOSHierarchicalReadVariable.bp";
// Number of steps
const std::size_t NSteps = 2;
long unsigned int rank, size;
#if ADIOS2_USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
#else
rank = 0;
size = 1;
#endif
// Write test data using BP
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO io = adios.DeclareIO("TestIO");
io.SetEngine("BPFile");
io.AddTransport("file");
adios2::Engine engine = io.Open(filename, adios2::Mode::Write);
const std::size_t Nx = 10;
const adios2::Dims shape = {size * Nx};
const adios2::Dims start = {rank * Nx};
const adios2::Dims count = {Nx};
auto var1 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable1", shape, start, count);
auto var2 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable2", shape, start, count);
auto var3 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable3", shape, start, count);
auto var4 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable4", shape, start, count);
auto var5 = io.DefineVariable<int32_t>(
"group1/group2/group3/group4/variable5", shape, start, count);
auto var6 =
io.DefineVariable<int32_t>("variable6", shape, start, count);
std::vector<int32_t> Ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (size_t step = 0; step < NSteps; ++step)
{
engine.BeginStep();
engine.Put(var1, Ints.data());
engine.Put(var2, Ints.data());
engine.Put(var3, Ints.data());
engine.Put(var4, Ints.data());
engine.Put(var5, Ints.data());
engine.Put(var6, Ints.data());
engine.EndStep();
}
engine.Close();
engine = io.Open(filename, adios2::Mode::Read);
for (size_t step = 0; step < NSteps; step++)
{
engine.BeginStep();
auto g = io.InquireGroup('/');
auto res = g.AvailableGroups();
EXPECT_EQ(res[0], "group1");
res = g.AvailableVariables();
EXPECT_EQ(res[0], "variable6");
g.setPath("group1/group2");
res = g.AvailableGroups();
EXPECT_EQ(res[0], "group3");
g.setPath("group1/group2/group3");
res = g.AvailableGroups();
EXPECT_EQ(res[0], "group4");
g.setPath("group1/group2/group3/group4");
res = g.AvailableGroups();
EXPECT_EQ(res.size(), 0);
res = g.AvailableVariables();
EXPECT_EQ(res.size(), 5);
res = g.AvailableAttributes();
EXPECT_EQ(res.size(), 0);
g = io.InquireGroup('/');
auto var = g.InquireVariable<int32_t>("variable6");
EXPECT_TRUE(var);
if (var)
{
std::vector<int32_t> myInts;
var.SetSelection({{Nx * rank}, {Nx}});
engine.Get<int32_t>(var, myInts, adios2::Mode::Sync);
EXPECT_EQ(Ints, myInts);
}
g.setPath("group1/group2/group3/group4");
var = g.InquireVariable<int32_t>("variable1");
EXPECT_TRUE(var);
if (var)
{
std::vector<int32_t> myInts;
var.SetSelection({{Nx * rank}, {Nx}});
engine.Get<int32_t>(var, myInts, adios2::Mode::Sync);
EXPECT_EQ(Ints, myInts);
}
engine.EndStep();
}
engine.Close();
}
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/documentgallery
#include <qdocumentgallery.h>
#include <QtTest/QtTest>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QGalleryProperty::Attributes)
class tst_QDocumentGallery : public QObject
{
Q_OBJECT
private Q_SLOTS:
void isRequestSupported();
void itemTypeProperties_data();
void itemTypeProperties();
void propertyAttributes_data();
void propertyAttributes();
private:
QDocumentGallery gallery;
};
void tst_QDocumentGallery::isRequestSupported()
{
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
const bool platformSupported = true;
#else
const bool platformSupported = false;
#endif
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::QueryRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::ItemRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::TypeRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::RequestType(1000)), false);
}
void tst_QDocumentGallery::itemTypeProperties_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QStringList>("propertyNames");
QTest::newRow("null item type") << QString() << QStringList();
QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList();
const QStringList fileProperties = QStringList()
#if defined(Q_WS_MAEMO_6)
<< QDocumentGallery::author
<< QDocumentGallery::comments
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::fileExtension
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::keywords
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType
<< QDocumentGallery::path
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
<< QDocumentGallery::url;
#elif defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::copyright
<< QDocumentGallery::fileName
<< QDocumentGallery::path
<< QDocumentGallery::filePath
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType;
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
<< QDocumentGallery::author
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::comments
<< QDocumentGallery::rating
#endif
;
QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties)
#if !defined(Q_WS_MAEMO_6) && defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::author
<< QDocumentGallery::description
<< QDocumentGallery::keywords
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
#endif
);
QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::audioCodec
<< QDocumentGallery::channelCount
<< QDocumentGallery::discNumber
<< QDocumentGallery::duration
<< QDocumentGallery::genre
<< QDocumentGallery::lastPlayed
<< QDocumentGallery::lyrics
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::trackNumber
<< QDocumentGallery::performer
#if defined(Q_WS_MAEMO_6)
<< QDocumentGallery::composer
<< QDocumentGallery::resumePosition
#else
<< QDocumentGallery::description
<< QDocumentGallery::title
#endif
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::audioCodec
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::albumTitle
<< QDocumentGallery::trackNumber
<< QDocumentGallery::albumArtist
<< QDocumentGallery::artist
<< QDocumentGallery::composer
<< QDocumentGallery::genre
#endif
);
QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::duration
#if !defined(Q_WS_MAEMO_6)
<< QDocumentGallery::rating
#endif
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#endif
);
QTest::newRow("PhotoAlbum") << QString(QDocumentGallery::PhotoAlbum) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::title
#if defined (Q_WS_MAEMO_6)
<< QDocumentGallery::count
#else
<< QDocumentGallery::trackCount
#endif
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
#endif
);
#if defined (Q_OS_SYMBIAN)
QTest::newRow("Image") << QString(QDocumentGallery::Image) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::orientation
<< QDocumentGallery::dateTaken
<< QDocumentGallery::cameraManufacturer
<< QDocumentGallery::cameraModel
<< QDocumentGallery::exposureProgram
<< QDocumentGallery::exposureTime
<< QDocumentGallery::fNumber
<< QDocumentGallery::flashEnabled
<< QDocumentGallery::focalLength
<< QDocumentGallery::meteringMode
<< QDocumentGallery::whiteBalance
);
QTest::newRow("Video") << QString(QDocumentGallery::Video) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::videoBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::language
<< QDocumentGallery::frameRate
<< QDocumentGallery::resumePosition
);
#endif
}
void tst_QDocumentGallery::itemTypeProperties()
{
QFETCH(QString, itemType);
QFETCH(QStringList, propertyNames);
QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType);
propertyNames.sort();
galleryPropertyNames.sort();
QCOMPARE(galleryPropertyNames, propertyNames);
}
void tst_QDocumentGallery::propertyAttributes_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QString>("propertyName");
QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes");
QTest::newRow("Null itemType, propertyName")
<< QString()
<< QString()
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, invalid propertyName")
<< QString()
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, valid propertyName")
<< QString()
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, invalid propertyName")
<< QString::fromLatin1("Hello")
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, valid propertyName")
<< QString::fromLatin1("Hello")
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Valid itemType, invalid propertyName")
<< QString(QDocumentGallery::File)
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("File.fileName")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::fileName)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("File.filePath")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::filePath)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead | QGalleryProperty::CanFilter);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Audio.albumTitle")
<< QString(QDocumentGallery::Audio)
<< QString(QDocumentGallery::albumTitle)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
#if !defined(Q_WS_MAEMO_6)
| QGalleryProperty::CanWrite
#endif
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Album.duration")
<< QString(QDocumentGallery::Album)
<< QString(QDocumentGallery::duration)
#if defined(Q_WS_MAEMO_6)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#elif defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QGalleryProperty::Attributes(QGalleryProperty::CanRead);
#else
<< QGalleryProperty::Attributes();
#endif
}
void tst_QDocumentGallery::propertyAttributes()
{
QFETCH(QString, itemType);
QFETCH(QString, propertyName);
QFETCH(QGalleryProperty::Attributes, propertyAttributes);
QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes));
}
#include "tst_qdocumentgallery.moc"
QTEST_MAIN(tst_QDocumentGallery)
<commit_msg>Fix test failure.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/documentgallery
#include <qdocumentgallery.h>
#include <QtTest/QtTest>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QGalleryProperty::Attributes)
class tst_QDocumentGallery : public QObject
{
Q_OBJECT
private Q_SLOTS:
void isRequestSupported();
void itemTypeProperties_data();
void itemTypeProperties();
void propertyAttributes_data();
void propertyAttributes();
private:
QDocumentGallery gallery;
};
void tst_QDocumentGallery::isRequestSupported()
{
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
const bool platformSupported = true;
#else
const bool platformSupported = false;
#endif
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::QueryRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::ItemRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::TypeRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::RequestType(1000)), false);
}
void tst_QDocumentGallery::itemTypeProperties_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QStringList>("propertyNames");
QTest::newRow("null item type") << QString() << QStringList();
QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList();
const QStringList fileProperties = QStringList()
#if defined(Q_WS_MAEMO_6)
<< QDocumentGallery::author
<< QDocumentGallery::comments
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::fileExtension
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::keywords
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType
<< QDocumentGallery::path
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
<< QDocumentGallery::url;
#elif defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::copyright
<< QDocumentGallery::fileName
<< QDocumentGallery::path
<< QDocumentGallery::filePath
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType;
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
<< QDocumentGallery::author
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::comments
<< QDocumentGallery::rating
#endif
;
QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties)
#if !defined(Q_WS_MAEMO_6) && defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::author
<< QDocumentGallery::description
<< QDocumentGallery::keywords
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
#endif
);
QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::audioCodec
<< QDocumentGallery::channelCount
<< QDocumentGallery::discNumber
<< QDocumentGallery::duration
<< QDocumentGallery::genre
<< QDocumentGallery::lastPlayed
<< QDocumentGallery::lyrics
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::trackNumber
<< QDocumentGallery::performer
#if defined(Q_WS_MAEMO_6)
<< QDocumentGallery::composer
<< QDocumentGallery::resumePosition
#else
<< QDocumentGallery::description
<< QDocumentGallery::title
#endif
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::audioCodec
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::albumTitle
<< QDocumentGallery::trackNumber
<< QDocumentGallery::albumArtist
<< QDocumentGallery::artist
<< QDocumentGallery::composer
<< QDocumentGallery::genre
#endif
);
QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::duration
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#endif
);
QTest::newRow("PhotoAlbum") << QString(QDocumentGallery::PhotoAlbum) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::title
#if defined (Q_WS_MAEMO_6)
<< QDocumentGallery::count
#else
<< QDocumentGallery::trackCount
#endif
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
#endif
);
#if defined (Q_OS_SYMBIAN)
QTest::newRow("Image") << QString(QDocumentGallery::Image) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::orientation
<< QDocumentGallery::dateTaken
<< QDocumentGallery::cameraManufacturer
<< QDocumentGallery::cameraModel
<< QDocumentGallery::exposureProgram
<< QDocumentGallery::exposureTime
<< QDocumentGallery::fNumber
<< QDocumentGallery::flashEnabled
<< QDocumentGallery::focalLength
<< QDocumentGallery::meteringMode
<< QDocumentGallery::whiteBalance
);
QTest::newRow("Video") << QString(QDocumentGallery::Video) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::videoBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::language
<< QDocumentGallery::frameRate
<< QDocumentGallery::resumePosition
);
#endif
}
void tst_QDocumentGallery::itemTypeProperties()
{
QFETCH(QString, itemType);
QFETCH(QStringList, propertyNames);
QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType);
propertyNames.sort();
galleryPropertyNames.sort();
QCOMPARE(galleryPropertyNames, propertyNames);
}
void tst_QDocumentGallery::propertyAttributes_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QString>("propertyName");
QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes");
QTest::newRow("Null itemType, propertyName")
<< QString()
<< QString()
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, invalid propertyName")
<< QString()
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, valid propertyName")
<< QString()
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, invalid propertyName")
<< QString::fromLatin1("Hello")
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, valid propertyName")
<< QString::fromLatin1("Hello")
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Valid itemType, invalid propertyName")
<< QString(QDocumentGallery::File)
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("File.fileName")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::fileName)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("File.filePath")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::filePath)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead | QGalleryProperty::CanFilter);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Audio.albumTitle")
<< QString(QDocumentGallery::Audio)
<< QString(QDocumentGallery::albumTitle)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
#if !defined(Q_WS_MAEMO_6)
| QGalleryProperty::CanWrite
#endif
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Album.duration")
<< QString(QDocumentGallery::Album)
<< QString(QDocumentGallery::duration)
#if defined(Q_WS_MAEMO_6)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#elif defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QGalleryProperty::Attributes(QGalleryProperty::CanRead);
#else
<< QGalleryProperty::Attributes();
#endif
}
void tst_QDocumentGallery::propertyAttributes()
{
QFETCH(QString, itemType);
QFETCH(QString, propertyName);
QFETCH(QGalleryProperty::Attributes, propertyAttributes);
QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes));
}
#include "tst_qdocumentgallery.moc"
QTEST_MAIN(tst_QDocumentGallery)
<|endoftext|> |
<commit_before>#include "file.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "assert.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
namespace Kakoune
{
std::string read_file(const std::string& filename)
{
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
throw file_not_found(filename);
throw file_access_error(filename, strerror(errno));
}
std::string content;
char buf[256];
while (true)
{
ssize_t size = read(fd, buf, 256);
if (size == -1 or size == 0)
break;
content += std::string(buf, size);
}
close(fd);
return content;
}
Buffer* create_buffer_from_file(const std::string& filename)
{
std::string content = read_file(filename);
if (Buffer* buffer = BufferManager::instance().get_buffer(filename))
BufferManager::instance().delete_buffer(buffer);
return new Buffer(filename, Buffer::Type::File, content);
}
void write_buffer_to_file(const Buffer& buffer, const std::string& filename)
{
int fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1)
throw file_access_error(filename, strerror(errno));
const BufferString& content = buffer.content();
ssize_t count = content.length() * sizeof(BufferChar);
const char* ptr = content.c_str();
while (count)
{
ssize_t written = write(fd, ptr, count);
ptr += written;
count -= written;
if (written == -1)
throw file_access_error(filename, strerror(errno));
}
close(fd);
}
}
<commit_msg>whitespace fix<commit_after>#include "file.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "assert.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
namespace Kakoune
{
std::string read_file(const std::string& filename)
{
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
throw file_not_found(filename);
throw file_access_error(filename, strerror(errno));
}
std::string content;
char buf[256];
while (true)
{
ssize_t size = read(fd, buf, 256);
if (size == -1 or size == 0)
break;
content += std::string(buf, size);
}
close(fd);
return content;
}
Buffer* create_buffer_from_file(const std::string& filename)
{
std::string content = read_file(filename);
if (Buffer* buffer = BufferManager::instance().get_buffer(filename))
BufferManager::instance().delete_buffer(buffer);
return new Buffer(filename, Buffer::Type::File, content);
}
void write_buffer_to_file(const Buffer& buffer, const std::string& filename)
{
int fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1)
throw file_access_error(filename, strerror(errno));
const BufferString& content = buffer.content();
ssize_t count = content.length() * sizeof(BufferChar);
const char* ptr = content.c_str();
while (count)
{
ssize_t written = write(fd, ptr, count);
ptr += written;
count -= written;
if (written == -1)
throw file_access_error(filename, strerror(errno));
}
close(fd);
}
}
<|endoftext|> |
<commit_before>#include <tansa/action.h>
#include <tansa/control.h>
#include <tansa/core.h>
#include <tansa/jocsParser.h>
#include <tansa/config.h>
#include <tansa/jocsPlayer.h>
#include <tansa/mocap.h>
#include <tansa/gazebo.h>
#include <tansa/osc.h>
#ifdef __linux__
#include <sys/signal.h>
#endif
//TODO check if these work on OSX
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;
using namespace tansa;
static bool running;
static bool killmode = false;
static bool pauseMode = false;
static bool stopMode = false;
static bool playMode = false;
static JocsPlayer* player;
static vector<Vehicle *> vehicles;
static std::vector<vehicle_config> vconfigs;
static vector<unsigned> jocsActiveIds;
void signal_sigint(int s) {
// TODO: Prevent
running = false;
}
/* For sending a system state update to the gui */
void send_status_message() {
json j;
j["type"] = "status";
j["time"] = player->currentTime();
json vehs = json::array();
for(int i = 0; i < vehicles.size(); i++) {
json v;
v["id"] = vconfigs[i].net_id;
v["role"] = i <= jocsActiveIds.size() - 1? jocsActiveIds[i] : -1;
v["connected"] = vehicles[i]->connected;
v["armed"] = vehicles[i]->armed;
v["tracking"] = vehicles[i]->tracking;
json pos = json::array();
pos.push_back(vehicles[i]->state.position.x());
pos.push_back(vehicles[i]->state.position.y());
pos.push_back(vehicles[i]->state.position.z());
v["position"] = pos;
json bat = {
{"voltage", vehicles[i]->battery.voltage},
{"percent", vehicles[i]->battery.percent}
};
v["battery"] = bat;
vehs.push_back(v);
}
j["vehicles"] = vehs;
json global;
global["playing"] = player->isPlaying();
global["ready"] = player->isReady();
j["global"] = global;
tansa::send_message(j);
}
void send_file_list() {
std::vector<std::string> jocsFilePaths;
json j;
j["type"] = "list_reply";
json files = json::array();
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("data")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
if(ent->d_type == DT_REG && std::string(ent->d_name).find(".jocs") != std::string::npos)
files.push_back(std::string(ent->d_name));
}
closedir (dir);
} else {
/* could not open directory */
}
j["files"] = files;
tansa::send_message(j);
// sio::message::ptr obj = sio::object_message::create();
// obj->get_map()["type"] = sio::string_message::create("status");
// obj->get_map()["time"] = sio::double_message::create(t.seconds());
// sio::message::list li(obj);
// tansa::send_message(li);
}
void socket_on_message(const json &data) {
string type = data["type"];
if(type == "prepare") {
printf("Preparing...\n");
player->prepare();
}
else if(type == "play") { printf("Playing...\n");
playMode = true;
}
else if(type == "land") {
player->land();
}
else if (type == "pause") {
printf("Pausing...\n");
pauseMode = true;
} else if (type == "stop") {
printf("Stopping...\n");
stopMode = true;
} else if (type == "reset") {
printf("Resetting...\n");
} else if (type == "list"){
send_file_list();
}
else if(type == "kill") {
bool enabled = data["enabled"];
printf("Killing...\n");
killmode = enabled;
}
else {
// TODO: Send an error message back to the browser
printf("Unexpected message type recieved!\n");
}
}
void osc_on_message(OSCMessage &msg) {
// Address will look something like: '/cue/0101/start'
if(msg.address[0] == "cue") {
int num = std::stoi(msg.address[1]);
if(msg.address[2] == "load") {
player->prepare();
}
else if(msg.address[2] == "start") {
printf("Starting at cue #: %d\n", num);
// Assert that it is already prepared at the given cue
player->play();
}
}
/*
printf("Address:\n");
for(auto str : msg.address)
printf("- %s\n", str.c_str());
printf("\nArgs:\n");
for(auto str : msg.args)
printf("- %s\n", str.c_str());
*/
}
pthread_t console_handle;
void *console_thread(void *arg) {
while(running) {
// Read a command
cout << "> ";
string line;
getline(cin, line);
// Split into arguments
vector<string> args;
istringstream iss(line);
while(!iss.eof()) {
string a;
iss >> a;
if(iss.fail())
break;
args.push_back(a);
}
if(args.size() == 0)
continue;
if (args[0] == "prepare") {
cout << "Preparing..." << endl;
player->prepare();
} else if (args[0] == "play") {
cout << "Playing..." << endl;
playMode = true;
} else if (args[0] == "pause") {
cout << "Pausing..." << endl;
pauseMode = true;
} else if (args[0] == "stop") {
cout << "Stopping..." << endl;
stopMode = true;
} else if (args[0] == "land") {
cout << "Landing..." << endl;
player->land();
} else if (args[0] == "kill") {
killmode = args.size() <= 1 || !(args[1] == "off");
}
}
}
void console_start() {
pthread_create(&console_handle, NULL, console_thread, NULL);
}
int main(int argc, char *argv[]) {
assert(argc == 2);
string configPath = argv[1];
ifstream configStream(configPath);
if (!configStream) throw "Unable to read config file!";
/// Parse the config file
std::string configData((std::istreambuf_iterator<char>(configStream)), std::istreambuf_iterator<char>());
nlohmann::json rawJson = nlohmann::json::parse(configData);
hardware_config config;
string jocsPath = rawJson["jocsPath"];
vector<unsigned> activeids = rawJson["jocsActiveIds"];
jocsActiveIds = activeids;
bool useMocap = rawJson["useMocap"];
float scale = rawJson["theaterScale"];
bool enableMessaging = rawJson["enableMessaging"];
bool enableOSC = rawJson["enableOSC"];
if (useMocap) {
nlohmann::json hardwareConfig = rawJson["hardwareConfig"];
config.clientAddress = hardwareConfig["clientAddress"];
config.serverAddress = hardwareConfig["serverAddress"];
}
vconfigs.resize(rawJson["vehicles"].size());
for(unsigned i = 0; i < rawJson["vehicles"].size(); i++) {
vconfigs[i].net_id = rawJson["vehicles"][i]["net_id"];
if(useMocap) {
vconfigs[i].lport = 14550 + 10*vconfigs[i].net_id;
vconfigs[i].rport = 14555;
}
else { // The simulated ones are zero-indexed and
vconfigs[i].lport = 14550 + 10*(vconfigs[i].net_id - 1);
vconfigs[i].rport = 14555 + 10*(vconfigs[i].net_id - 1);
}
}
Jocs *jocs = Jocs::Parse(jocsPath, scale);
auto homes = jocs->GetHomes();
// Only pay attention to homes of active drones
std::vector<Point> spawns;
for (int i = 0; i < jocsActiveIds.size(); i++) {
int chosenId = jocsActiveIds[i];
// We assume the user only configured for valid IDs..
spawns.push_back(homes[chosenId]);
spawns[i].z() = 0;
}
tansa::init(enableMessaging);
if(enableMessaging) {
tansa::on_message(socket_on_message);
}
Mocap *mocap = nullptr;
GazeboConnector *gazebo = nullptr;
// Only pay attention to homes of active drones
// TODO: Have a better check for mocap initialization/health
if (useMocap) {
mocap = new Mocap();
mocap->connect(config.clientAddress, config.serverAddress);
} else {
gazebo = new GazeboConnector();
gazebo->connect();
gazebo->spawn(spawns);
}
int n = spawns.size();
if (n > vconfigs.size()) {
printf("Not enough drones on the network\n");
return 1;
}
vehicles.resize(n);
for(int i = 0; i < n; i++) {
const vehicle_config &v = vconfigs[i];
vehicles[i] = new Vehicle();
// Load default parameters
vehicles[i]->readParams("./config/params/default.json");
// TODO: Also read in per-drone ones
vehicles[i]->connect(v.lport, v.rport);
if (useMocap) {
mocap->track(vehicles[i], i+1);
} else {
gazebo->track(vehicles[i], i);
}
}
if(enableOSC) {
OSC *osc = new OSC();
osc->start(53100);
osc->set_listener(osc_on_message);
}
player = new JocsPlayer(vehicles, jocsActiveIds);
player->loadJocs(jocs);
running = true;
signal(SIGINT, signal_sigint);
int i = 0;
/*
// For sample lighting demo
float level = 0;
float dl = 0.005;
*/
signal(SIGINT, signal_sigint);
printf("running...\n");
running = true;
console_start();
Rate r(100);
while(running) {
// Regular status messages
if(enableMessaging && i % 20 == 0) {
send_status_message();
}
if (killmode) {
for(Vehicle *v : vehicles)
v->terminate();
} else if (playMode) {
playMode = false;
player->play();
} else if (pauseMode) {
pauseMode = false;
player->pause();
} else if (stopMode) {
stopMode = false;
player->stop();
} else {
player->step();
}
r.sleep();
i++;
}
/// Cleanup
if (useMocap) {
mocap->disconnect();
delete mocap;
} else {
gazebo->disconnect();
delete gazebo;
}
// Stop all vehicles
for(int vi = 0; vi < n; vi++) {
Vehicle *v = vehicles[vi];
v->disconnect();
delete v;
}
player->cleanup();
printf("Done!\n");
}
<commit_msg>Cleaned up jocs file listing and some other related style issues<commit_after>#include <tansa/action.h>
#include <tansa/control.h>
#include <tansa/core.h>
#include <tansa/jocsParser.h>
#include <tansa/config.h>
#include <tansa/jocsPlayer.h>
#include <tansa/mocap.h>
#include <tansa/gazebo.h>
#include <tansa/osc.h>
#ifdef __linux__
#include <sys/signal.h>
#endif
//TODO check if these work on OSX
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;
using namespace tansa;
static bool running;
static bool killmode = false;
static bool pauseMode = false;
static bool stopMode = false;
static bool playMode = false;
static JocsPlayer* player;
static vector<Vehicle *> vehicles;
static std::vector<vehicle_config> vconfigs;
static vector<unsigned> jocsActiveIds;
void signal_sigint(int s) {
// TODO: Prevent
running = false;
}
/* For sending a system state update to the gui */
void send_status_message() {
json j;
j["type"] = "status";
j["time"] = player->currentTime();
json vehs = json::array();
for(int i = 0; i < vehicles.size(); i++) {
json v;
v["id"] = vconfigs[i].net_id;
v["role"] = i <= jocsActiveIds.size() - 1? jocsActiveIds[i] : -1;
v["connected"] = vehicles[i]->connected;
v["armed"] = vehicles[i]->armed;
v["tracking"] = vehicles[i]->tracking;
json pos = json::array();
pos.push_back(vehicles[i]->state.position.x());
pos.push_back(vehicles[i]->state.position.y());
pos.push_back(vehicles[i]->state.position.z());
v["position"] = pos;
json bat = {
{"voltage", vehicles[i]->battery.voltage},
{"percent", vehicles[i]->battery.percent}
};
v["battery"] = bat;
vehs.push_back(v);
}
j["vehicles"] = vehs;
json global;
global["playing"] = player->isPlaying();
global["ready"] = player->isReady();
j["global"] = global;
tansa::send_message(j);
}
void send_file_list() {
json j;
j["type"] = "list_reply";
json files = json::array();
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("data")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
if(ent->d_type == DT_REG && std::string(ent->d_name).find(".jocs") != std::string::npos)
files.push_back(std::string(ent->d_name));
}
closedir (dir);
} else {
/* could not open directory */
//TODO Do something intelligent here
}
j["files"] = files;
tansa::send_message(j);
}
void socket_on_message(const json &data) {
string type = data["type"];
if(type == "prepare") {
printf("Preparing...\n");
player->prepare();
} else if(type == "play") {
printf("Playing...\n");
playMode = true;
} else if(type == "land") {
player->land();
} else if (type == "pause") {
printf("Pausing...\n");
pauseMode = true;
} else if (type == "stop") {
printf("Stopping...\n");
stopMode = true;
} else if (type == "reset") {
printf("Resetting...\n");
} else if (type == "list"){
printf("Sending file list...\n");
send_file_list();
} else if (type == "load"){
printf("Loading jocs file...\n")
} else if(type == "kill") {
bool enabled = data["enabled"];
printf("Killing...\n");
killmode = enabled;
} else {
// TODO: Send an error message back to the browser
printf("Unexpected message type recieved!\n");
}
}
void osc_on_message(OSCMessage &msg) {
// Address will look something like: '/cue/0101/start'
if(msg.address[0] == "cue") {
int num = std::stoi(msg.address[1]);
if(msg.address[2] == "load") {
player->prepare();
}
else if(msg.address[2] == "start") {
printf("Starting at cue #: %d\n", num);
// Assert that it is already prepared at the given cue
player->play();
}
}
/*
printf("Address:\n");
for(auto str : msg.address)
printf("- %s\n", str.c_str());
printf("\nArgs:\n");
for(auto str : msg.args)
printf("- %s\n", str.c_str());
*/
}
pthread_t console_handle;
void *console_thread(void *arg) {
while(running) {
// Read a command
cout << "> ";
string line;
getline(cin, line);
// Split into arguments
vector<string> args;
istringstream iss(line);
while(!iss.eof()) {
string a;
iss >> a;
if(iss.fail())
break;
args.push_back(a);
}
if(args.size() == 0)
continue;
if (args[0] == "prepare") {
cout << "Preparing..." << endl;
player->prepare();
} else if (args[0] == "play") {
cout << "Playing..." << endl;
playMode = true;
} else if (args[0] == "pause") {
cout << "Pausing..." << endl;
pauseMode = true;
} else if (args[0] == "stop") {
cout << "Stopping..." << endl;
stopMode = true;
} else if (args[0] == "land") {
cout << "Landing..." << endl;
player->land();
} else if (args[0] == "kill") {
killmode = args.size() <= 1 || !(args[1] == "off");
}
}
}
void console_start() {
pthread_create(&console_handle, NULL, console_thread, NULL);
}
int main(int argc, char *argv[]) {
assert(argc == 2);
string configPath = argv[1];
ifstream configStream(configPath);
if (!configStream) throw "Unable to read config file!";
/// Parse the config file
std::string configData((std::istreambuf_iterator<char>(configStream)), std::istreambuf_iterator<char>());
nlohmann::json rawJson = nlohmann::json::parse(configData);
hardware_config config;
string jocsPath = rawJson["jocsPath"];
vector<unsigned> activeids = rawJson["jocsActiveIds"];
jocsActiveIds = activeids;
bool useMocap = rawJson["useMocap"];
float scale = rawJson["theaterScale"];
bool enableMessaging = rawJson["enableMessaging"];
bool enableOSC = rawJson["enableOSC"];
if (useMocap) {
nlohmann::json hardwareConfig = rawJson["hardwareConfig"];
config.clientAddress = hardwareConfig["clientAddress"];
config.serverAddress = hardwareConfig["serverAddress"];
}
vconfigs.resize(rawJson["vehicles"].size());
for(unsigned i = 0; i < rawJson["vehicles"].size(); i++) {
vconfigs[i].net_id = rawJson["vehicles"][i]["net_id"];
if(useMocap) {
vconfigs[i].lport = 14550 + 10*vconfigs[i].net_id;
vconfigs[i].rport = 14555;
}
else { // The simulated ones are zero-indexed and
vconfigs[i].lport = 14550 + 10*(vconfigs[i].net_id - 1);
vconfigs[i].rport = 14555 + 10*(vconfigs[i].net_id - 1);
}
}
Jocs *jocs = Jocs::Parse(jocsPath, scale);
auto homes = jocs->GetHomes();
// Only pay attention to homes of active drones
std::vector<Point> spawns;
for (int i = 0; i < jocsActiveIds.size(); i++) {
int chosenId = jocsActiveIds[i];
// We assume the user only configured for valid IDs..
spawns.push_back(homes[chosenId]);
spawns[i].z() = 0;
}
tansa::init(enableMessaging);
if(enableMessaging) {
tansa::on_message(socket_on_message);
}
Mocap *mocap = nullptr;
GazeboConnector *gazebo = nullptr;
// Only pay attention to homes of active drones
// TODO: Have a better check for mocap initialization/health
if (useMocap) {
mocap = new Mocap();
mocap->connect(config.clientAddress, config.serverAddress);
} else {
gazebo = new GazeboConnector();
gazebo->connect();
gazebo->spawn(spawns);
}
int n = spawns.size();
if (n > vconfigs.size()) {
printf("Not enough drones on the network\n");
return 1;
}
vehicles.resize(n);
for(int i = 0; i < n; i++) {
const vehicle_config &v = vconfigs[i];
vehicles[i] = new Vehicle();
// Load default parameters
vehicles[i]->readParams("./config/params/default.json");
// TODO: Also read in per-drone ones
vehicles[i]->connect(v.lport, v.rport);
if (useMocap) {
mocap->track(vehicles[i], i+1);
} else {
gazebo->track(vehicles[i], i);
}
}
if(enableOSC) {
OSC *osc = new OSC();
osc->start(53100);
osc->set_listener(osc_on_message);
}
player = new JocsPlayer(vehicles, jocsActiveIds);
player->loadJocs(jocs);
running = true;
signal(SIGINT, signal_sigint);
int i = 0;
/*
// For sample lighting demo
float level = 0;
float dl = 0.005;
*/
signal(SIGINT, signal_sigint);
printf("running...\n");
running = true;
console_start();
Rate r(100);
while(running) {
// Regular status messages
if(enableMessaging && i % 20 == 0) {
send_status_message();
}
if (killmode) {
for(Vehicle *v : vehicles)
v->terminate();
} else if (playMode) {
playMode = false;
player->play();
} else if (pauseMode) {
pauseMode = false;
player->pause();
} else if (stopMode) {
stopMode = false;
player->stop();
} else {
player->step();
}
r.sleep();
i++;
}
/// Cleanup
if (useMocap) {
mocap->disconnect();
delete mocap;
} else {
gazebo->disconnect();
delete gazebo;
}
// Stop all vehicles
for(int vi = 0; vi < n; vi++) {
Vehicle *v = vehicles[vi];
v->disconnect();
delete v;
}
player->cleanup();
printf("Done!\n");
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Jason White
*
* MIT License
*
* Description:
* Globbing.
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <string>
#include <set>
#include "lua.hpp"
#include "glob.h"
#include "path.h"
namespace {
/**
* Compare a character with case sensitivity or not.
*/
template <bool CaseSensitive>
static int charCmp(char a, char b) {
if (CaseSensitive)
return (int)a - (int)b;
else
return (int)tolower(a) - (int)tolower(b);
}
/**
* Returns true if the pattern matches the given filename, false otherwise.
*/
template <bool CaseSensitive>
bool globMatch(path::Path path, path::Path pattern) {
size_t i = 0;
for (size_t j = 0; j < pattern.length; ++j) {
switch (pattern.path[j]) {
case '?': {
// Match any single character
if (i == path.length)
return false;
++i;
break;
}
case '*': {
// Match 0 or more characters
if (j+1 == pattern.length)
return true;
// Consume characters while looking ahead for matches
for (; i < path.length; ++i) {
if (globMatch<CaseSensitive>(
path::Path(path.path+i, path.length-i),
path::Path(pattern.path+j+1, pattern.length-j-1)))
return true;
}
return false;
}
case '[': {
// Match any of the characters that appear in the square brackets
if (i == path.length) return false;
// Skip past the opening bracket
if (++j == pattern.length) return false;
// Invert the match?
bool invert = false;
if (pattern.path[j] == '!') {
invert = true;
if (++j == pattern.length)
return false;
}
// Find the closing bracket
size_t end = j;
while (end < pattern.length && pattern.path[end] != ']')
++end;
// No matching bracket?
if (end == pattern.length) return false;
// Check each character between the brackets for a match
bool match = false;
while (j < end) {
// Found a match
if (!match && charCmp<CaseSensitive>(path.path[i], pattern.path[j]) == 0) {
match = true;
}
++j;
}
if (match == invert)
return false;
++i;
break;
}
default: {
// Match the next character in the pattern
if (i == path.length || charCmp<CaseSensitive>(path.path[i], pattern.path[j]))
return false;
++i;
break;
}
}
}
// If we ran out of pattern and out of path, then we have a complete match.
return i == path.length;
}
bool globMatch(path::Path path, path::Path pattern) {
#ifdef _WIN32
return globMatch<false>(path, pattern);
#else
return globMatch<true>(path, pattern);
#endif
}
/**
* Returns true if the given string contains a glob pattern.
*/
bool isGlobPattern(path::Path p) {
for (size_t i = 0; i < p.length; ++i) {
switch (p.path[i]) {
case '?':
case '*':
case '[':
return true;
}
}
return false;
}
/**
* Returns true if the given path element is a recursive glob pattern.
*/
bool isRecursiveGlob(path::Path p) {
return p.length == 2 && p.path[0] == '*' && p.path[1] == '*';
}
/**
* Returns true if the given path element is a hidden directory (i.e., "." or
* "..").
*/
bool isHiddenDir(const char* s, size_t len) {
switch (len) {
case 1:
return s[0] == '.';
case 2:
return s[0] == '.' && s[1] == '.';
default:
return false;
}
}
typedef void (*GlobCallback)(path::Path path, bool isDir, void* data);
struct GlobClosure {
path::Path pattern;
// Next callback
GlobCallback next;
void* nextData;
};
/**
* Helper function for listing a directory with the given pattern. If the
* pattern is empty,
*/
void glob(path::Path path, path::Path pattern,
GlobCallback callback, void* data) {
std::string buf(path.path, path.length);
if (pattern.length == 0) {
path::join(buf, pattern);
callback(path::Path(buf.data(), buf.size()), true, data);
return;
}
struct dirent* entry;
DIR* dir = opendir(path.length > 0 ? buf.c_str() : ".");
if (!dir)
return;
// TODO: Implement this for windows, too.
while ((entry = readdir(dir))) {
const char* name = entry->d_name;
size_t nameLength = strlen(entry->d_name);
bool isDir = entry->d_type == DT_DIR;
if (isHiddenDir(name, nameLength))
continue;
if (globMatch(path::Path(name, nameLength), pattern)) {
path::join(buf, path::Path(entry->d_name, nameLength));
callback(path::Path(buf.data(), buf.size()), isDir, data);
buf.assign(path.path, path.length);
}
}
closedir(dir);
}
/**
* Helper function to recursively yield directories for the given path.
*/
void globRecursive(std::string& path, GlobCallback callback, void* data) {
size_t len = path.size();
struct dirent* entry;
DIR* dir = opendir(len > 0 ? path.c_str() : ".");
if (!dir)
return;
// "**" matches 0 or more directories and thus includes this one.
callback(path::Path(path.data(), path.size()), true, data);
// TODO: Implement this for windows, too.
while ((entry = readdir(dir))) {
const char* name = entry->d_name;
size_t nameLength = strlen(entry->d_name);
bool isDir = entry->d_type == DT_DIR;
if (isHiddenDir(name, nameLength))
continue;
path::join(path, path::Path(entry->d_name, nameLength));
callback(path::Path(path.data(), path.size()), isDir, data);
if (isDir)
globRecursive(path, callback, data);
path.resize(len);
}
closedir(dir);
}
void globCallback(path::Path path, bool isDir, void* data) {
if (isDir) {
const GlobClosure* c = (const GlobClosure*)data;
glob(path, c->pattern, c->next, c->nextData);
}
}
/**
* Glob a directory.
*/
void glob(path::Path path, GlobCallback callback, void* data = NULL) {
path::Split s = path::split(path);
if (isGlobPattern(s.head)) {
// Directory name contains a glob pattern
GlobClosure c;
c.pattern = s.tail;
c.next = callback;
c.nextData = data;
glob(s.head, &globCallback, &c);
}
else if (isRecursiveGlob(s.tail)) {
std::string buf(s.head.path, s.head.length);
globRecursive(buf, callback, data);
}
else if (isGlobPattern(s.tail)) {
// Only base name contains a glob pattern.
glob(s.head, s.tail, callback, data);
}
else {
// No glob pattern in this path.
if (s.tail.length) {
// TODO: If file exists, then return it
callback(path, false, data);
}
else {
// TODO: If directory exists, then return it
callback(s.head, true, data);
}
}
}
/**
* Callback to put globbed items into a set.
*/
void fs_globcallback(path::Path path, bool isDir, void* data) {
std::set<std::string>* paths = (std::set<std::string>*)data;
paths->insert(std::string(path.path, path.length));
}
/**
* Callback to remove globbed items from a set.
*/
void fs_globcallback_exclude(path::Path path, bool isDir, void* data) {
std::set<std::string>* paths = (std::set<std::string>*)data;
paths->erase(std::string(path.path, path.length));
}
/**
* Lua wrapper to prepend the current script directory to the requested path.
*/
void glob(lua_State* L, path::Path path, GlobCallback callback, void* data) {
// Join the SCRIPT_DIR with this path.
lua_getglobal(L, "path");
lua_getfield(L, -1, "join");
lua_getglobal(L, "SCRIPT_DIR");
lua_pushlstring(L, path.path, path.length);
lua_call(L, 2, 1);
size_t len;
const char* scriptDir = lua_tolstring(L, -1, &len);
if (scriptDir)
glob(path::Path(scriptDir, len), callback, data);
lua_pop(L, 2); // Pop new path and path table
}
} // anonymous namespace
int lua_glob_match(lua_State* L) {
size_t len, patlen;
const char* path = luaL_checklstring(L, 1, &len);
const char* pattern = luaL_checklstring(L, 2, &patlen);
lua_pushboolean(L, globMatch(path::Path(path, len), path::Path(pattern, patlen)));
return 1;
}
int lua_glob(lua_State* L) {
// TODO: Cache results of a directory listing and use that for further globs.
std::set<std::string> paths;
int argc = lua_gettop(L);
size_t len;
const char* path;
for (int i = 1; i <= argc; ++i) {
const int type = lua_type(L, i);
if (type == LUA_TTABLE) {
for (int j = 1; ; ++j) {
if (lua_rawgeti(L, i, j) == LUA_TNIL) {
lua_pop(L, 1);
break;
}
path = lua_tolstring(L, -1, &len);
if (path) {
if (len > 0 && path[0] == '!')
glob(L, path::Path(path+1, len-1), &fs_globcallback_exclude, &paths);
else
glob(L, path::Path(path, len), &fs_globcallback, &paths);
}
lua_pop(L, 1); // Pop path
}
}
else if (type == LUA_TSTRING) {
path = luaL_checklstring(L, i, &len);
if (len > 0 && path[0] == '!')
glob(L, path::Path(path+1, len-1), &fs_globcallback_exclude, &paths);
else
glob(L, path::Path(path, len), &fs_globcallback, &paths);
}
}
// Construct the Lua table.
lua_newtable(L);
lua_Number n = 1;
for (std::set<std::string>::iterator it = paths.begin(); it != paths.end(); ++it) {
lua_pushlstring(L, it->data(), it->size());
lua_seti(L, -2, n);
++n;
}
return 1;
}
<commit_msg>Fallback to stat() if DT_DIR is not available<commit_after>/**
* Copyright (c) Jason White
*
* MIT License
*
* Description:
* Globbing.
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <string>
#include <set>
#include "lua.hpp"
#include "glob.h"
#include "path.h"
namespace {
/**
* Compare a character with case sensitivity or not.
*/
template <bool CaseSensitive>
static int charCmp(char a, char b) {
if (CaseSensitive)
return (int)a - (int)b;
else
return (int)tolower(a) - (int)tolower(b);
}
/**
* Returns true if the pattern matches the given filename, false otherwise.
*/
template <bool CaseSensitive>
bool globMatch(path::Path path, path::Path pattern) {
size_t i = 0;
for (size_t j = 0; j < pattern.length; ++j) {
switch (pattern.path[j]) {
case '?': {
// Match any single character
if (i == path.length)
return false;
++i;
break;
}
case '*': {
// Match 0 or more characters
if (j+1 == pattern.length)
return true;
// Consume characters while looking ahead for matches
for (; i < path.length; ++i) {
if (globMatch<CaseSensitive>(
path::Path(path.path+i, path.length-i),
path::Path(pattern.path+j+1, pattern.length-j-1)))
return true;
}
return false;
}
case '[': {
// Match any of the characters that appear in the square brackets
if (i == path.length) return false;
// Skip past the opening bracket
if (++j == pattern.length) return false;
// Invert the match?
bool invert = false;
if (pattern.path[j] == '!') {
invert = true;
if (++j == pattern.length)
return false;
}
// Find the closing bracket
size_t end = j;
while (end < pattern.length && pattern.path[end] != ']')
++end;
// No matching bracket?
if (end == pattern.length) return false;
// Check each character between the brackets for a match
bool match = false;
while (j < end) {
// Found a match
if (!match && charCmp<CaseSensitive>(path.path[i], pattern.path[j]) == 0) {
match = true;
}
++j;
}
if (match == invert)
return false;
++i;
break;
}
default: {
// Match the next character in the pattern
if (i == path.length || charCmp<CaseSensitive>(path.path[i], pattern.path[j]))
return false;
++i;
break;
}
}
}
// If we ran out of pattern and out of path, then we have a complete match.
return i == path.length;
}
bool globMatch(path::Path path, path::Path pattern) {
#ifdef _WIN32
return globMatch<false>(path, pattern);
#else
return globMatch<true>(path, pattern);
#endif
}
/**
* Returns true if the given string contains a glob pattern.
*/
bool isGlobPattern(path::Path p) {
for (size_t i = 0; i < p.length; ++i) {
switch (p.path[i]) {
case '?':
case '*':
case '[':
return true;
}
}
return false;
}
/**
* Returns true if the given path element is a recursive glob pattern.
*/
bool isRecursiveGlob(path::Path p) {
return p.length == 2 && p.path[0] == '*' && p.path[1] == '*';
}
/**
* Returns true if the given path element is a hidden directory (i.e., "." or
* "..").
*/
bool isHiddenDir(const char* s, size_t len) {
switch (len) {
case 1:
return s[0] == '.';
case 2:
return s[0] == '.' && s[1] == '.';
default:
return false;
}
}
typedef void (*GlobCallback)(path::Path path, bool isDir, void* data);
struct GlobClosure {
path::Path pattern;
// Next callback
GlobCallback next;
void* nextData;
};
/**
* Helper function for listing a directory with the given pattern. If the
* pattern is empty,
*/
void glob(path::Path path, path::Path pattern,
GlobCallback callback, void* data) {
std::string buf(path.path, path.length);
if (pattern.length == 0) {
path::join(buf, pattern);
callback(path::Path(buf.data(), buf.size()), true, data);
return;
}
struct dirent* entry;
DIR* dir = opendir(path.length > 0 ? buf.c_str() : ".");
if (!dir)
return;
// TODO: Implement this for windows, too.
while ((entry = readdir(dir))) {
const char* name = entry->d_name;
size_t nameLength = strlen(entry->d_name);
bool isDir;
if (entry->d_type == DT_UNKNOWN) {
struct stat statbuf;
if (fstatat(dirfd(dir), entry->d_name, &statbuf, 0) == 0)
isDir = (statbuf.st_mode & S_IFMT) == S_IFDIR;
else
isDir = false;
}
else {
isDir = entry->d_type == DT_DIR;
}
if (isHiddenDir(name, nameLength))
continue;
if (globMatch(path::Path(name, nameLength), pattern)) {
path::join(buf, path::Path(entry->d_name, nameLength));
callback(path::Path(buf.data(), buf.size()), isDir, data);
buf.assign(path.path, path.length);
}
}
closedir(dir);
}
/**
* Helper function to recursively yield directories for the given path.
*/
void globRecursive(std::string& path, GlobCallback callback, void* data) {
size_t len = path.size();
struct dirent* entry;
DIR* dir = opendir(len > 0 ? path.c_str() : ".");
if (!dir)
return;
// "**" matches 0 or more directories and thus includes this one.
callback(path::Path(path.data(), path.size()), true, data);
// TODO: Implement this for windows, too.
while ((entry = readdir(dir))) {
const char* name = entry->d_name;
size_t nameLength = strlen(entry->d_name);
bool isDir;
if (entry->d_type == DT_UNKNOWN) {
struct stat statbuf;
if (fstatat(dirfd(dir), entry->d_name, &statbuf, 0) == 0)
isDir = (statbuf.st_mode & S_IFMT) == S_IFDIR;
else
isDir = false;
}
else {
isDir = entry->d_type == DT_DIR;
}
if (isHiddenDir(name, nameLength))
continue;
path::join(path, path::Path(entry->d_name, nameLength));
callback(path::Path(path.data(), path.size()), isDir, data);
if (isDir)
globRecursive(path, callback, data);
path.resize(len);
}
closedir(dir);
}
void globCallback(path::Path path, bool isDir, void* data) {
if (isDir) {
const GlobClosure* c = (const GlobClosure*)data;
glob(path, c->pattern, c->next, c->nextData);
}
}
/**
* Glob a directory.
*/
void glob(path::Path path, GlobCallback callback, void* data = NULL) {
path::Split s = path::split(path);
if (isGlobPattern(s.head)) {
// Directory name contains a glob pattern
GlobClosure c;
c.pattern = s.tail;
c.next = callback;
c.nextData = data;
glob(s.head, &globCallback, &c);
}
else if (isRecursiveGlob(s.tail)) {
std::string buf(s.head.path, s.head.length);
globRecursive(buf, callback, data);
}
else if (isGlobPattern(s.tail)) {
// Only base name contains a glob pattern.
glob(s.head, s.tail, callback, data);
}
else {
// No glob pattern in this path.
if (s.tail.length) {
// TODO: If file exists, then return it
callback(path, false, data);
}
else {
// TODO: If directory exists, then return it
callback(s.head, true, data);
}
}
}
/**
* Callback to put globbed items into a set.
*/
void fs_globcallback(path::Path path, bool isDir, void* data) {
std::set<std::string>* paths = (std::set<std::string>*)data;
paths->insert(std::string(path.path, path.length));
}
/**
* Callback to remove globbed items from a set.
*/
void fs_globcallback_exclude(path::Path path, bool isDir, void* data) {
std::set<std::string>* paths = (std::set<std::string>*)data;
paths->erase(std::string(path.path, path.length));
}
/**
* Lua wrapper to prepend the current script directory to the requested path.
*/
void glob(lua_State* L, path::Path path, GlobCallback callback, void* data) {
// Join the SCRIPT_DIR with this path.
lua_getglobal(L, "path");
lua_getfield(L, -1, "join");
lua_getglobal(L, "SCRIPT_DIR");
lua_pushlstring(L, path.path, path.length);
lua_call(L, 2, 1);
size_t len;
const char* scriptDir = lua_tolstring(L, -1, &len);
if (scriptDir)
glob(path::Path(scriptDir, len), callback, data);
lua_pop(L, 2); // Pop new path and path table
}
} // anonymous namespace
int lua_glob_match(lua_State* L) {
size_t len, patlen;
const char* path = luaL_checklstring(L, 1, &len);
const char* pattern = luaL_checklstring(L, 2, &patlen);
lua_pushboolean(L, globMatch(path::Path(path, len), path::Path(pattern, patlen)));
return 1;
}
int lua_glob(lua_State* L) {
// TODO: Cache results of a directory listing and use that for further globs.
std::set<std::string> paths;
int argc = lua_gettop(L);
size_t len;
const char* path;
for (int i = 1; i <= argc; ++i) {
const int type = lua_type(L, i);
if (type == LUA_TTABLE) {
for (int j = 1; ; ++j) {
if (lua_rawgeti(L, i, j) == LUA_TNIL) {
lua_pop(L, 1);
break;
}
path = lua_tolstring(L, -1, &len);
if (path) {
if (len > 0 && path[0] == '!')
glob(L, path::Path(path+1, len-1), &fs_globcallback_exclude, &paths);
else
glob(L, path::Path(path, len), &fs_globcallback, &paths);
}
lua_pop(L, 1); // Pop path
}
}
else if (type == LUA_TSTRING) {
path = luaL_checklstring(L, i, &len);
if (len > 0 && path[0] == '!')
glob(L, path::Path(path+1, len-1), &fs_globcallback_exclude, &paths);
else
glob(L, path::Path(path, len), &fs_globcallback, &paths);
}
}
// Construct the Lua table.
lua_newtable(L);
lua_Number n = 1;
for (std::set<std::string>::iterator it = paths.begin(); it != paths.end(); ++it) {
lua_pushlstring(L, it->data(), it->size());
lua_seti(L, -2, n);
++n;
}
return 1;
}
<|endoftext|> |
<commit_before>#ifndef GUI_HPP
#define GUI_HPP
#endif // GUI_HPP
<commit_msg>Delete useless files<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
void parse(char x[], vector<string> &v){
//cout << "parse executes" << endl;
char* tmp;
tmp = strtok(x, " ");
while(tmp != NULL){
v.push_back(tmp);
//cout << "*" << tmp << "*" << endl;
tmp = strtok(NULL, " ");
}
}
bool isExit(char x[]){
string tmp = x;
string ext = "exit";
int e = tmp.find('e');
int t = tmp.find('t', e);
if(e == -1 || t == -1){
return false;
}
int k = 0;
for(int i = e; i < t + 1; i++){
if(tmp.at(i) != ext.at(k)){
return false;
}
k++;
}
return true;
}
bool run(char str[]){
char* pch;
bool sucs = true;
int status = 0;
string ext = "exit";
string connector;
string strz = str;
vector<string> cmd;
pch = strtok(str, ";");
if(pch==NULL){
return true;
}
else if(pch != strz){
connector = ";";
}
if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "&&";
}
}
if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "||";
}
}
if(pch != NULL && isExit(pch)){
exit(0);
}
while(pch != NULL){
//cout << "execvp executes" << endl;
int pid = fork();
if(pid == -1){
perror("fork");
exit(1);
}
if(pid == 0){
parse(pch, cmd);
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("execvp");
exit(1);
}
}
else{
waitpid(-1, &status, 0);
//cout << status << endl;
if(status > 0){
sucs = false;
}
else{
sucs = true;
}
cmd.clear();
if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){
pch = strtok(NULL, connector.c_str());
}
else{
return true;
}
if(pch != NULL && isExit(pch)){
exit(0);
}
}
}
return true;
}
int main(){
bool goon = true;
while(goon){
string input;
cout << "$ ";
getline(cin, input);
char str[input.size()+1];
strcpy(str, input.c_str());
goon = run(str);
}
return 0;
}
<commit_msg>added comments<commit_after>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
void parse(char x[], vector<string> &v){
//cout << "parse executes" << endl;
char* tmp;
tmp = strtok(x, " ");
while(tmp != NULL){
v.push_back(tmp);
//cout << tmp << endl;
tmp = strtok(NULL, " ");
}
}
bool isExit(char x[]){
string tmp = x;
string ext = "exit";
int e = tmp.find('e');
int t = tmp.find('t', e);
if(e == -1 || t == -1){
return false;
}
int k = 0;
for(int i = e; i < t + 1; i++){
if(tmp.at(i) != ext.at(k)){
return false;
}
k++;
}
return true;
}
string commentRemoval(string x){
int comm = x.find('#');
if(comm == -1){
return x;
}
else if(comm == 0){
return "";
}
else{
return x.substr(0, comm);
}
}
bool run(char str[]){
char* pch;
bool sucs = true;
int status = 0;
string ext = "exit";
string connector;
string strz = str;
vector<string> cmd;
pch = strtok(str, ";");
if(pch==NULL){
return true;
}
else if(pch != strz){
connector = ";";
}
if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "&&";
}
}
if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "||";
}
}
if(pch != NULL && isExit(pch)){
exit(0);
}
while(pch != NULL){
//cout << "execvp executes" << endl;
int pid = fork();
if(pid == -1){
exit(1);
}
else if(pid == 0){
parse(pch, cmd);
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("execvp");
exit(1);
}
}
else{
waitpid(-1, &status, 0);
//cout << status << endl;
if(status > 0){
sucs = false;
}
else{
sucs = true;
}
cmd.clear();
if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){
pch = strtok(NULL, connector.c_str());
}
else{
return true;
}
if(pch != NULL && isExit(pch)){
exit(0);
}
}
}
return true;
}
int main(){
bool goon = true;
while(goon){
string input;
cout << "$ ";
getline(cin, input);
input = commentRemoval(input);
char str[input.size()+1];
strcpy(str, input.c_str());
goon = run(str);
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "value.hh"
#include "object.hh"
#include "chunk.hh"
namespace nyx {
int Chunk::write(u8_t byte, int line) {
codes_.push_back(byte);
lines_.push_back(line);
return static_cast<int>(codes_.size() - 1);
}
int Chunk::add_constant(const Value& v) {
constants_.push_back(v);
return static_cast<int>(constants_.size() - 1);
}
void Chunk::disassemble(const str_t& name) {
std::cout << "=== " << name << " ===" << std::endl;
for (int i = 0; i < static_cast<int>(codes_.size());)
i = disassemble_instruction(i);
}
int Chunk::disassemble_instruction(int i) {
static auto simple_instruction = [](const char* name) {
std::cout << name << std::endl;
};
static auto simple_instructionN = [](const char* name, int n) {
std::cout << name << n << std::endl;
};
static auto code_instruction = [](Chunk& c, int i, const char* name) -> int {
u8_t slot = c.get_code(i++);
fprintf(stdout, "%-16s %4d\n", name, slot);
return i;
};
static auto const_instruction = [](Chunk& c, int i, const char* name) -> int {
u8_t constant = c.get_code(i);
fprintf(stdout, "%-16s %4d ", name, constant);
std::cout << "`" << c.get_constant(constant) << "`" << std::endl;
return i;
};
static auto const_instructionN = [](
Chunk& c, int i, const char* name, int n) -> int {
u8_t constant = c.get_code(i);
fprintf(stdout, "%s%-*d %4d ",
name, 15 - static_cast<int>(strlen(name)), n, constant);
std::cout << "`" << c.get_constant(constant) << "`" << std::endl;
return i;
};
static auto jump_instruction = [](
Chunk& c, int i, const char* name, int sign = 1) -> int {
u16_t offset = static_cast<u16_t>(c.get_code(i++) << 8);
offset |= c.get_code(i++);
fprintf(stdout, "%-16s %4d -> %d\n", name, offset, i + offset * sign);
return i;
};
fprintf(stdout, "%04d ", i);
if (i > 1 && lines_[i] == lines_[i - 1])
std::cout << " | ";
else
fprintf(stdout, "%4d ", lines_[i]);
const u8_t* codes = codes_.data();
switch (auto instruction = codes[i++]; instruction) {
case OpCode::OP_CONSTANT:
i = const_instruction(*this, i, "OP_CONSTANT"); break;
case OpCode::OP_NIL: simple_instruction("OP_NIL"); break;
case OpCode::OP_TRUE: simple_instruction("OP_TRUE"); break;
case OpCode::OP_FALSE: simple_instruction("OP_FALSE"); break;
case OpCode::OP_POP: simple_instruction("OP_POP"); break;
case OpCode::OP_GET_LOCAL:
i = code_instruction(*this, i, "OP_GET_LOCAL"); break;
case OpCode::OP_SET_LOCAL:
i = code_instruction(*this, i, "OP_SET_LOCAL"); break;
case OpCode::OP_DEF_GLOBAL:
i = const_instruction(*this, i, "OP_DEF_GLOBAL"); break;
case OpCode::OP_GET_GLOBAL:
i = const_instruction(*this, i, "OP_GET_GLOBAL"); break;
case OpCode::OP_SET_GLOBAL:
i = const_instruction(*this, i, "OP_SET_GLOBAL"); break;
case OpCode::OP_GET_UPVALUE:
i = code_instruction(*this, i, "OP_GET_UPVALUE"); break;
case OpCode::OP_SET_UPVALUE:
i = code_instruction(*this, i, "OP_SET_UPVALUE"); break;
case OpCode::OP_GET_FIELD:
i = const_instruction(*this, i, "OP_GET_FIELD"); break;
case OpCode::OP_SET_FIELD:
i = const_instruction(*this, i, "OP_SET_FIELD"); break;
case OpCode::OP_GET_SUPER:
i = const_instruction(*this, i, "OP_GET_SUPER"); break;
case OpCode::OP_EQ: simple_instruction("OP_EQ"); break;
case OpCode::OP_NE: simple_instruction("OP_NE"); break;
case OpCode::OP_GT: simple_instruction("OP_GT"); break;
case OpCode::OP_GE: simple_instruction("OP_GE"); break;
case OpCode::OP_LT: simple_instruction("OP_LT"); break;
case OpCode::OP_LE: simple_instruction("OP_LE"); break;
case OpCode::OP_ADD: simple_instruction("OP_ADD"); break;
case OpCode::OP_SUB: simple_instruction("OP_SUB"); break;
case OpCode::OP_MUL: simple_instruction("OP_MUL"); break;
case OpCode::OP_DIV: simple_instruction("OP_DIV"); break;
case OpCode::OP_NOT: simple_instruction("OP_NOT"); break;
case OpCode::OP_NEG: simple_instruction("OP_NEG"); break;
case OpCode::OP_JUMP:
i = jump_instruction(*this, i, "OP_JUMP"); break;
case OpCode::OP_JUMP_IF_FALSE:
i = jump_instruction(*this, i, "OP_JUMP_IF_FALSE"); break;
case OpCode::OP_LOOP:
i = jump_instruction(*this, i, "OP_LOOP", -1); break;
case OpCode::OP_CALL_0:
case OpCode::OP_CALL_1:
case OpCode::OP_CALL_2:
case OpCode::OP_CALL_3:
case OpCode::OP_CALL_4:
case OpCode::OP_CALL_5:
case OpCode::OP_CALL_6:
case OpCode::OP_CALL_7:
case OpCode::OP_CALL_8:
simple_instructionN("OP_CALL_", instruction - OpCode::OP_CALL_0); break;
case OpCode::OP_INVOKE_0:
case OpCode::OP_INVOKE_1:
case OpCode::OP_INVOKE_2:
case OpCode::OP_INVOKE_3:
case OpCode::OP_INVOKE_4:
case OpCode::OP_INVOKE_5:
case OpCode::OP_INVOKE_6:
case OpCode::OP_INVOKE_7:
case OpCode::OP_INVOKE_8:
i = const_instructionN(*this, i, "OP_INVOKE_", instruction - OpCode::OP_INVOKE_0);
break;
case OpCode::OP_SUPER_0:
case OpCode::OP_SUPER_1:
case OpCode::OP_SUPER_2:
case OpCode::OP_SUPER_3:
case OpCode::OP_SUPER_4:
case OpCode::OP_SUPER_5:
case OpCode::OP_SUPER_6:
case OpCode::OP_SUPER_7:
case OpCode::OP_SUPER_8:
i = const_instructionN(*this, i, "OP_SUPER_", instruction - OpCode::OP_SUPER_0);
break;
case OpCode::OP_CLOSURE:
{
u8_t constant = codes[i++];
fprintf(stdout, "%-16s %4d ", "OP_CLOSURE", constant);
Value constant_val = constants_[constant];
std::cout << "`" << constant_val << "`" << std::endl;
FunctionObject* closed_fn = constant_val.as_function();
for (int j = 0; j < closed_fn->upvalues_count(); ++j) {
int is_local = codes[i++];
int index = codes[i++];
fprintf(stdout, "%04d | %s %d\n",
i - 2, is_local ? "local" : "upvalue", index);
}
} break;
case OpCode::OP_CLOSE_UPVALUE: simple_instruction("OP_CLOSE_UPVALUE"); break;
case OpCode::OP_RETURN: simple_instruction("OP_RETURN"); break;
case OpCode::OP_CLASS:
i = const_instruction(*this, i, "OP_CLASS"); break;
case OpCode::OP_SUBCLASS:
i = const_instruction(*this, i, "OP_SUBCLASS"); break;
case OpCode::OP_METHOD:
i = const_instruction(*this, i, "OP_METHOD"); break;
}
return i;
}
}
<commit_msg>:construction: chore(chunk): updated the chunk disassemble<commit_after>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "value.hh"
#include "object.hh"
#include "chunk.hh"
namespace nyx {
int Chunk::write(u8_t byte, int line) {
codes_.push_back(byte);
lines_.push_back(line);
return static_cast<int>(codes_.size() - 1);
}
int Chunk::add_constant(const Value& v) {
constants_.push_back(v);
return static_cast<int>(constants_.size() - 1);
}
void Chunk::disassemble(const str_t& name) {
std::cout << "=== " << name << " ===" << std::endl;
for (int i = 0; i < static_cast<int>(codes_.size());)
i = disassemble_instruction(i);
}
int Chunk::disassemble_instruction(int i) {
static auto simple_instruction = [](int i, const char* name) -> int {
std::cout << name << std::endl;
return i;
};
static auto simple_instructionN = [](int i, const char* name, int n) -> int {
std::cout << name << n << std::endl;
return i;
};
static auto code_instruction = [](Chunk& c, int i, const char* name) -> int {
u8_t slot = c.get_code(i);
fprintf(stdout, "%-16s %4d\n", name, slot);
return i + 1;
};
static auto const_instruction = [](Chunk& c, int i, const char* name) -> int {
u8_t constant = c.get_code(i);
fprintf(stdout, "%-16s %4d ", name, constant);
std::cout << "`" << c.get_constant(constant) << "`" << std::endl;
return i + 1;
};
static auto const_instructionN = [](
Chunk& c, int i, const char* name, int n) -> int {
u8_t constant = c.get_code(i);
fprintf(stdout, "%s%-*d %4d ",
name, 15 - static_cast<int>(strlen(name)), n, constant);
std::cout << "`" << c.get_constant(constant) << "`" << std::endl;
return i + 1;
};
static auto jump_instruction = [](
Chunk& c, int i, const char* name, int sign = 1) -> int {
u16_t offset = static_cast<u16_t>(c.get_code(i) << 8);
offset |= c.get_code(i + 1);
fprintf(stdout, "%-16s %4d -> %d\n", name, offset, i + offset * sign);
return i + 2;
};
fprintf(stdout, "%04d ", i);
if (i > 1 && lines_[i] == lines_[i - 1])
std::cout << " | ";
else
fprintf(stdout, "%4d ", lines_[i]);
const u8_t* codes = codes_.data();
switch (auto instruction = codes[i++]; instruction) {
case OpCode::OP_CONSTANT: return const_instruction(*this, i, "OP_CONSTANT");
case OpCode::OP_NIL: return simple_instruction(i, "OP_NIL");
case OpCode::OP_TRUE: return simple_instruction(i, "OP_TRUE");
case OpCode::OP_FALSE: return simple_instruction(i, "OP_FALSE");
case OpCode::OP_POP: return simple_instruction(i, "OP_POP");
case OpCode::OP_GET_LOCAL: return code_instruction(*this, i, "OP_GET_LOCAL");
case OpCode::OP_SET_LOCAL: return code_instruction(*this, i, "OP_SET_LOCAL");
case OpCode::OP_DEF_GLOBAL: return const_instruction(*this, i, "OP_DEF_GLOBAL");
case OpCode::OP_GET_GLOBAL: return const_instruction(*this, i, "OP_GET_GLOBAL");
case OpCode::OP_SET_GLOBAL: return const_instruction(*this, i, "OP_SET_GLOBAL");
case OpCode::OP_GET_UPVALUE: return code_instruction(*this, i, "OP_GET_UPVALUE");
case OpCode::OP_SET_UPVALUE: return code_instruction(*this, i, "OP_SET_UPVALUE");
case OpCode::OP_GET_FIELD: return const_instruction(*this, i, "OP_GET_FIELD");
case OpCode::OP_SET_FIELD: return const_instruction(*this, i, "OP_SET_FIELD");
case OpCode::OP_GET_SUPER: return const_instruction(*this, i, "OP_GET_SUPER");
case OpCode::OP_EQ: return simple_instruction(i, "OP_EQ");
case OpCode::OP_NE: return simple_instruction(i, "OP_NE");
case OpCode::OP_GT: return simple_instruction(i, "OP_GT");
case OpCode::OP_GE: return simple_instruction(i, "OP_GE");
case OpCode::OP_LT: return simple_instruction(i, "OP_LT");
case OpCode::OP_LE: return simple_instruction(i, "OP_LE");
case OpCode::OP_ADD: return simple_instruction(i, "OP_ADD");
case OpCode::OP_SUB: return simple_instruction(i, "OP_SUB");
case OpCode::OP_MUL: return simple_instruction(i, "OP_MUL");
case OpCode::OP_DIV: return simple_instruction(i, "OP_DIV");
case OpCode::OP_NOT: return simple_instruction(i, "OP_NOT");
case OpCode::OP_NEG: return simple_instruction(i, "OP_NEG");
case OpCode::OP_JUMP: return jump_instruction(*this, i, "OP_JUMP");
case OpCode::OP_JUMP_IF_FALSE: return jump_instruction(*this, i, "OP_JUMP_IF_FALSE");
case OpCode::OP_LOOP: return jump_instruction(*this, i, "OP_LOOP", -1);
case OpCode::OP_CALL_0:
case OpCode::OP_CALL_1:
case OpCode::OP_CALL_2:
case OpCode::OP_CALL_3:
case OpCode::OP_CALL_4:
case OpCode::OP_CALL_5:
case OpCode::OP_CALL_6:
case OpCode::OP_CALL_7:
case OpCode::OP_CALL_8:
return simple_instructionN(i, "OP_CALL_", instruction - OpCode::OP_CALL_0);
case OpCode::OP_INVOKE_0:
case OpCode::OP_INVOKE_1:
case OpCode::OP_INVOKE_2:
case OpCode::OP_INVOKE_3:
case OpCode::OP_INVOKE_4:
case OpCode::OP_INVOKE_5:
case OpCode::OP_INVOKE_6:
case OpCode::OP_INVOKE_7:
case OpCode::OP_INVOKE_8:
return const_instructionN(*this, i, "OP_INVOKE_", instruction - OpCode::OP_INVOKE_0);
case OpCode::OP_SUPER_0:
case OpCode::OP_SUPER_1:
case OpCode::OP_SUPER_2:
case OpCode::OP_SUPER_3:
case OpCode::OP_SUPER_4:
case OpCode::OP_SUPER_5:
case OpCode::OP_SUPER_6:
case OpCode::OP_SUPER_7:
case OpCode::OP_SUPER_8:
return const_instructionN(*this, i, "OP_SUPER_", instruction - OpCode::OP_SUPER_0);
case OpCode::OP_CLOSURE:
{
u8_t constant = codes[i++];
fprintf(stdout, "%-16s %4d ", "OP_CLOSURE", constant);
Value constant_val = constants_[constant];
std::cout << "`" << constant_val << "`" << std::endl;
FunctionObject* closed_fn = constant_val.as_function();
for (int j = 0; j < closed_fn->upvalues_count(); ++j) {
int is_local = codes[i++];
int index = codes[i++];
fprintf(stdout, "%04d | %s %d\n",
i - 2, is_local ? "local" : "upvalue", index);
}
} break;
case OpCode::OP_CLOSE_UPVALUE: return simple_instruction(i, "OP_CLOSE_UPVALUE");
case OpCode::OP_RETURN: return simple_instruction(i, "OP_RETURN");
case OpCode::OP_CLASS: return const_instruction(*this, i, "OP_CLASS");
case OpCode::OP_SUBCLASS: return const_instruction(*this, i, "OP_SUBCLASS");
case OpCode::OP_METHOD: return const_instruction(*this, i, "OP_METHOD");
}
return 0;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <immintrin.h>
#include "ch_frb_io_internals.hpp"
using namespace std;
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode!
#endif
assembled_chunk::assembled_chunk(int beam_id_, int nupfreq_, int nt_per_packet_, int fpga_counts_per_sample_, uint64_t chunk_t0_)
: beam_id(beam_id_),
nupfreq(nupfreq_),
nt_per_packet(nt_per_packet_),
fpga_counts_per_sample(fpga_counts_per_sample_),
chunk_t0(chunk_t0_),
chunk_t1(chunk_t0_ + constants::nt_per_assembled_chunk)
{
if ((beam_id < 0) || (beam_id > constants::max_allowed_beam_id))
throw runtime_error("assembled_chunk constructor: bad beam_id argument");
if ((nupfreq <= 0) || (nupfreq > constants::max_allowed_nupfreq))
throw runtime_error("assembled_chunk constructor: bad nupfreq argument");
if ((nt_per_packet <= 0) || !is_power_of_two(nt_per_packet) || (nt_per_packet > constants::nt_per_assembled_chunk))
throw runtime_error("assembled_chunk constructor: bad nt_per_packet argument");
if ((fpga_counts_per_sample <= 0) || (fpga_counts_per_sample > constants::max_allowed_fpga_counts_per_sample))
throw runtime_error("assembled_chunk constructor: bad fpga_counts_per_sample argument");
this->data = aligned_alloc<uint8_t> (constants::nfreq_coarse * nupfreq * constants::nt_per_assembled_chunk);
this->nt_coarse = constants::nt_per_assembled_chunk / nt_per_packet;
this->scales = aligned_alloc<float> (constants::nfreq_coarse * nt_coarse);
this->offsets = aligned_alloc<float> (constants::nfreq_coarse * nt_coarse);
}
assembled_chunk::~assembled_chunk()
{
free(data);
free(scales);
free(offsets);
}
void assembled_chunk::add_packet(const intensity_packet &packet)
{
// Offset relative to beginning of packet
int t0 = packet.fpga_count / uint64_t(fpga_counts_per_sample) - chunk_t0;
#if 1
// FIXME remove later?
bool bad = ((packet.nbeams != 1) ||
(packet.nupfreq != this->nupfreq) ||
(packet.ntsamp != this->nt_per_packet) ||
(packet.fpga_counts_per_sample != this->fpga_counts_per_sample) ||
(packet.fpga_count % (fpga_counts_per_sample * nt_per_packet)) ||
(packet.beam_ids[0] != this->beam_id) ||
(t0 < 0) ||
(t0 + nt_per_packet > constants::nt_per_assembled_chunk));
if (_unlikely(bad))
throw runtime_error("ch_frb_io: internal error in assembled_chunk::add_packet()");
#endif
for (int f = 0; f < packet.nfreq_coarse; f++) {
int coarse_freq_id = packet.freq_ids[f];
this->scales[coarse_freq_id*nt_coarse + (t0/nt_per_packet)] = packet.scales[f];
this->offsets[coarse_freq_id*nt_coarse + (t0/nt_per_packet)] = packet.offsets[f];
for (int u = 0; u < nupfreq; u++) {
memcpy(data + (coarse_freq_id*nupfreq + u) * constants::nt_per_assembled_chunk + t0,
packet.data + (f*nupfreq + u) * nt_per_packet,
nt_per_packet);
}
}
}
#if 0
void assembled_chunk::decode(float *intensity, float *weights, int stride) const
{
if (stride < constants::nt_per_assembled_chunk)
throw runtime_error("ch_frb_io: bad stride passed to assembled_chunk::decode()");
for (int if_coarse = 0; if_coarse < constants::nfreq_coarse; if_coarse++) {
const float *scales_f = this->scales + if_coarse * nt_coarse;
const float *offsets_f = this->offsets + if_coarse * nt_coarse;
for (int if_fine = if_coarse*nupfreq; if_fine < (if_coarse+1)*nupfreq; if_fine++) {
const uint8_t *src_f = this->data + if_fine * constants::nt_per_assembled_chunk;
float *int_f = intensity + if_fine * stride;
float *wt_f = weights + if_fine * stride;
for (int it_coarse = 0; it_coarse < nt_coarse; it_coarse++) {
float scale = scales_f[it_coarse];
float offset = offsets_f[it_coarse];
for (int it_fine = it_coarse*nt_per_packet; it_fine < (it_coarse+1)*nt_per_packet; it_fine++) {
float x = float(src_f[it_fine]);
int_f[it_fine] = scale*x + offset;
wt_f[it_fine] = ((x*(255.-x)) > 0.5) ? 1.0 : 0.0; // FIXME ugh
}
}
}
}
}
#endif
inline void _unpack(__m256i &out0, __m256i &out1, __m256i &out2, __m256i &out3, __m256i x)
{
// FIXME is there a better way to initialize this?
static const __m256i ctl0 = _mm256_set_epi8(15,11,7,3,14,10,6,2,13,9,5,1,12,8,4,0,
15,11,7,3,14,10,6,2,13,9,5,1,12,8,4,0);
// 4-by-4 transpose within each 128-bit lane
x = _mm256_shuffle_epi8(x, ctl0);
__m256i y0 = _mm256_and_si256(x, _mm256_set1_epi32(0xff));
__m256i y1 = _mm256_and_si256(x, _mm256_set1_epi32(0xff00));
__m256i y2 = _mm256_and_si256(x, _mm256_set1_epi32(0xff0000));
__m256i y3 = _mm256_and_si256(x, _mm256_set1_epi32(0xff000000));
y1 = _mm256_srli_epi32(y1, 8);
y2 = _mm256_srli_epi32(y2, 16);
y3 = _mm256_srli_epi32(y3, 24);
out0 = _mm256_permute2f128_ps(y0, y1, 0x20);
out1 = _mm256_permute2f128_ps(y2, y3, 0x20);
out2 = _mm256_permute2f128_ps(y0, y1, 0x31);
out3 = _mm256_permute2f128_ps(y2, y3, 0x31);
}
inline void _kernel32(float *intp, float *wtp, __m256i data, __m256 scale0, __m256 scale1, __m256 offset0, __m256 offset1)
{
__m256i in0, in1, in2, in3;
_unpack(in0, in1, in2, in3, data);
_mm256_storeu_ps(intp, scale0 * _mm256_cvtepi32_ps(in0) + offset0);
_mm256_storeu_ps(intp+8, scale0 * _mm256_cvtepi32_ps(in1) + offset0);
_mm256_storeu_ps(intp+16, scale1 * _mm256_cvtepi32_ps(in2) + offset1);
_mm256_storeu_ps(intp+24, scale1 * _mm256_cvtepi32_ps(in3) + offset1);
// XXX placeholder for weights
__m256 w = _mm256_set1_ps(1.0);
_mm256_storeu_ps(wtp, w);
_mm256_storeu_ps(wtp+8, w);
_mm256_storeu_ps(wtp+16, w);
_mm256_storeu_ps(wtp+25, w);
}
inline void _kernel128(float *intp, float *wtp, const uint8_t *src, const float *scalep, const float *offsetp)
{
__m256 scale = _mm256_loadu_ps(scalep);
__m256 offset = _mm256_loadu_ps(offsetp);
__m256 scale0, offset0;
scale0 = _mm256_permute2f128_ps(scale, scale, 0x00);
offset0 = _mm256_permute2f128_ps(offset, offset, 0x00);
_kernel32(intp, wtp,
_mm256_loadu_si256((const __m256i *) (src)),
_mm256_shuffle_ps(scale0, scale0, 0x00),
_mm256_shuffle_ps(scale0, scale0, 0x55),
_mm256_shuffle_ps(offset0, offset0, 0x00),
_mm256_shuffle_ps(offset0, offset0, 0x55));
_kernel32(intp + 32, wtp + 32,
_mm256_loadu_si256((const __m256i *) (src + 32)),
_mm256_shuffle_ps(scale0, scale0, 0xaa),
_mm256_shuffle_ps(scale0, scale0, 0xff),
_mm256_shuffle_ps(offset0, offset0, 0xaa),
_mm256_shuffle_ps(offset0, offset0, 0xff));
scale0 = _mm256_permute2f128_ps(scale, scale, 0x11);
offset0 = _mm256_permute2f128_ps(offset, offset, 0x11);
_kernel32(intp + 64, wtp + 64,
_mm256_loadu_si256((const __m256i *) (src + 64)),
_mm256_shuffle_ps(scale0, scale0, 0x00),
_mm256_shuffle_ps(scale0, scale0, 0x55),
_mm256_shuffle_ps(offset0, offset0, 0x00),
_mm256_shuffle_ps(offset0, offset0, 0x55));
_kernel32(intp + 96, wtp + 96,
_mm256_loadu_si256((const __m256i *) (src + 96)),
_mm256_shuffle_ps(scale0, scale0, 0xaa),
_mm256_shuffle_ps(scale0, scale0, 0xff),
_mm256_shuffle_ps(offset0, offset0, 0xaa),
_mm256_shuffle_ps(offset0, offset0, 0xff));
}
inline void _kernel(float *intp, float *wtp, const uint8_t *src, const float *scalep, const float *offsetp)
{
constexpr int n = constants::nt_per_assembled_chunk / 128;
for (int i = 0; i < n; i++)
_kernel128(intp + i*128, wtp + i*128, src + i*128, scalep + i*8, offsetp + i*8);
}
void assembled_chunk::decode(float *intensity, float *weights, int stride) const
{
if ((nt_per_packet != 16) || (constants::nt_per_assembled_chunk % 128))
throw runtime_error("ch_frb_io: can't use this kernel");
if (stride < constants::nt_per_assembled_chunk)
throw runtime_error("ch_frb_io: bad stride passed to assembled_chunk::decode()");
for (int if_coarse = 0; if_coarse < constants::nfreq_coarse; if_coarse++) {
const float *scales_f = this->scales + if_coarse * nt_coarse;
const float *offsets_f = this->offsets + if_coarse * nt_coarse;
for (int if_fine = if_coarse*nupfreq; if_fine < (if_coarse+1)*nupfreq; if_fine++) {
const uint8_t *src_f = this->data + if_fine * constants::nt_per_assembled_chunk;
float *int_f = intensity + if_fine * stride;
float *wt_f = weights + if_fine * stride;
for (int it_coarse = 0; it_coarse < nt_coarse; it_coarse++)
_kernel(int_f, wt_f, src_f, scales_f, offsets_f);
}
}
}
} // namespace ch_frb_io
<commit_msg>fix some bugs in decode kernel (not fully tested yet)<commit_after>#include <iostream>
#include <immintrin.h>
#include "ch_frb_io_internals.hpp"
using namespace std;
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode!
#endif
assembled_chunk::assembled_chunk(int beam_id_, int nupfreq_, int nt_per_packet_, int fpga_counts_per_sample_, uint64_t chunk_t0_)
: beam_id(beam_id_),
nupfreq(nupfreq_),
nt_per_packet(nt_per_packet_),
fpga_counts_per_sample(fpga_counts_per_sample_),
chunk_t0(chunk_t0_),
chunk_t1(chunk_t0_ + constants::nt_per_assembled_chunk)
{
if ((beam_id < 0) || (beam_id > constants::max_allowed_beam_id))
throw runtime_error("assembled_chunk constructor: bad beam_id argument");
if ((nupfreq <= 0) || (nupfreq > constants::max_allowed_nupfreq))
throw runtime_error("assembled_chunk constructor: bad nupfreq argument");
if ((nt_per_packet <= 0) || !is_power_of_two(nt_per_packet) || (nt_per_packet > constants::nt_per_assembled_chunk))
throw runtime_error("assembled_chunk constructor: bad nt_per_packet argument");
if ((fpga_counts_per_sample <= 0) || (fpga_counts_per_sample > constants::max_allowed_fpga_counts_per_sample))
throw runtime_error("assembled_chunk constructor: bad fpga_counts_per_sample argument");
this->data = aligned_alloc<uint8_t> (constants::nfreq_coarse * nupfreq * constants::nt_per_assembled_chunk);
this->nt_coarse = constants::nt_per_assembled_chunk / nt_per_packet;
this->scales = aligned_alloc<float> (constants::nfreq_coarse * nt_coarse);
this->offsets = aligned_alloc<float> (constants::nfreq_coarse * nt_coarse);
}
assembled_chunk::~assembled_chunk()
{
free(data);
free(scales);
free(offsets);
}
void assembled_chunk::add_packet(const intensity_packet &packet)
{
// Offset relative to beginning of packet
int t0 = packet.fpga_count / uint64_t(fpga_counts_per_sample) - chunk_t0;
#if 1
// FIXME remove later?
bool bad = ((packet.nbeams != 1) ||
(packet.nupfreq != this->nupfreq) ||
(packet.ntsamp != this->nt_per_packet) ||
(packet.fpga_counts_per_sample != this->fpga_counts_per_sample) ||
(packet.fpga_count % (fpga_counts_per_sample * nt_per_packet)) ||
(packet.beam_ids[0] != this->beam_id) ||
(t0 < 0) ||
(t0 + nt_per_packet > constants::nt_per_assembled_chunk));
if (_unlikely(bad))
throw runtime_error("ch_frb_io: internal error in assembled_chunk::add_packet()");
#endif
for (int f = 0; f < packet.nfreq_coarse; f++) {
int coarse_freq_id = packet.freq_ids[f];
this->scales[coarse_freq_id*nt_coarse + (t0/nt_per_packet)] = packet.scales[f];
this->offsets[coarse_freq_id*nt_coarse + (t0/nt_per_packet)] = packet.offsets[f];
for (int u = 0; u < nupfreq; u++) {
memcpy(data + (coarse_freq_id*nupfreq + u) * constants::nt_per_assembled_chunk + t0,
packet.data + (f*nupfreq + u) * nt_per_packet,
nt_per_packet);
}
}
}
#if 0
void assembled_chunk::decode(float *intensity, float *weights, int stride) const
{
if (stride < constants::nt_per_assembled_chunk)
throw runtime_error("ch_frb_io: bad stride passed to assembled_chunk::decode()");
for (int if_coarse = 0; if_coarse < constants::nfreq_coarse; if_coarse++) {
const float *scales_f = this->scales + if_coarse * nt_coarse;
const float *offsets_f = this->offsets + if_coarse * nt_coarse;
for (int if_fine = if_coarse*nupfreq; if_fine < (if_coarse+1)*nupfreq; if_fine++) {
const uint8_t *src_f = this->data + if_fine * constants::nt_per_assembled_chunk;
float *int_f = intensity + if_fine * stride;
float *wt_f = weights + if_fine * stride;
for (int it_coarse = 0; it_coarse < nt_coarse; it_coarse++) {
float scale = scales_f[it_coarse];
float offset = offsets_f[it_coarse];
for (int it_fine = it_coarse*nt_per_packet; it_fine < (it_coarse+1)*nt_per_packet; it_fine++) {
float x = float(src_f[it_fine]);
int_f[it_fine] = scale*x + offset;
wt_f[it_fine] = ((x*(255.-x)) > 0.5) ? 1.0 : 0.0; // FIXME ugh
}
}
}
}
}
#endif
#if 1
inline void _unpack(__m256i &out0, __m256i &out1, __m256i &out2, __m256i &out3, __m256i x)
{
// FIXME is there a better way to initialize this?
static const __m256i ctl0 = _mm256_set_epi8(15,11,7,3,14,10,6,2,13,9,5,1,12,8,4,0,
15,11,7,3,14,10,6,2,13,9,5,1,12,8,4,0);
// 4-by-4 transpose within each 128-bit lane
x = _mm256_shuffle_epi8(x, ctl0);
__m256i y0 = _mm256_and_si256(x, _mm256_set1_epi32(0xff));
__m256i y1 = _mm256_and_si256(x, _mm256_set1_epi32(0xff00));
__m256i y2 = _mm256_and_si256(x, _mm256_set1_epi32(0xff0000));
__m256i y3 = _mm256_and_si256(x, _mm256_set1_epi32(0xff000000));
y1 = _mm256_srli_epi32(y1, 8);
y2 = _mm256_srli_epi32(y2, 16);
y3 = _mm256_srli_epi32(y3, 24);
out0 = _mm256_permute2f128_si256(y0, y1, 0x20);
out1 = _mm256_permute2f128_si256(y2, y3, 0x20);
out2 = _mm256_permute2f128_si256(y0, y1, 0x31);
out3 = _mm256_permute2f128_si256(y2, y3, 0x31);
}
inline void _kernel32(float *intp, float *wtp, __m256i data, __m256 scale0, __m256 scale1, __m256 offset0, __m256 offset1)
{
__m256i in0, in1, in2, in3;
_unpack(in0, in1, in2, in3, data);
_mm256_storeu_ps(intp, scale0 * _mm256_cvtepi32_ps(in0) + offset0);
_mm256_storeu_ps(intp+8, scale0 * _mm256_cvtepi32_ps(in1) + offset0);
_mm256_storeu_ps(intp+16, scale1 * _mm256_cvtepi32_ps(in2) + offset1);
_mm256_storeu_ps(intp+24, scale1 * _mm256_cvtepi32_ps(in3) + offset1);
// XXX placeholder for weights
__m256 w = _mm256_set1_ps(1.0);
_mm256_storeu_ps(wtp, w);
_mm256_storeu_ps(wtp+8, w);
_mm256_storeu_ps(wtp+16, w);
_mm256_storeu_ps(wtp+24, w);
}
inline void _kernel128(float *intp, float *wtp, const uint8_t *src, const float *scalep, const float *offsetp)
{
__m256 scale = _mm256_loadu_ps(scalep);
__m256 offset = _mm256_loadu_ps(offsetp);
__m256 scale0, offset0;
scale0 = _mm256_permute2f128_ps(scale, scale, 0x00);
offset0 = _mm256_permute2f128_ps(offset, offset, 0x00);
_kernel32(intp, wtp,
_mm256_loadu_si256((const __m256i *) (src)),
_mm256_shuffle_ps(scale0, scale0, 0x00),
_mm256_shuffle_ps(scale0, scale0, 0x55),
_mm256_shuffle_ps(offset0, offset0, 0x00),
_mm256_shuffle_ps(offset0, offset0, 0x55));
_kernel32(intp + 32, wtp + 32,
_mm256_loadu_si256((const __m256i *) (src + 32)),
_mm256_shuffle_ps(scale0, scale0, 0xaa),
_mm256_shuffle_ps(scale0, scale0, 0xff),
_mm256_shuffle_ps(offset0, offset0, 0xaa),
_mm256_shuffle_ps(offset0, offset0, 0xff));
scale0 = _mm256_permute2f128_ps(scale, scale, 0x11);
offset0 = _mm256_permute2f128_ps(offset, offset, 0x11);
_kernel32(intp + 64, wtp + 64,
_mm256_loadu_si256((const __m256i *) (src + 64)),
_mm256_shuffle_ps(scale0, scale0, 0x00),
_mm256_shuffle_ps(scale0, scale0, 0x55),
_mm256_shuffle_ps(offset0, offset0, 0x00),
_mm256_shuffle_ps(offset0, offset0, 0x55));
_kernel32(intp + 96, wtp + 96,
_mm256_loadu_si256((const __m256i *) (src + 96)),
_mm256_shuffle_ps(scale0, scale0, 0xaa),
_mm256_shuffle_ps(scale0, scale0, 0xff),
_mm256_shuffle_ps(offset0, offset0, 0xaa),
_mm256_shuffle_ps(offset0, offset0, 0xff));
}
inline void _kernel(float *intp, float *wtp, const uint8_t *src, const float *scalep, const float *offsetp)
{
constexpr int n = constants::nt_per_assembled_chunk / 128;
for (int i = 0; i < n; i++)
_kernel128(intp + i*128, wtp + i*128, src + i*128, scalep + i*8, offsetp + i*8);
}
void assembled_chunk::decode(float *intensity, float *weights, int stride) const
{
if ((nt_per_packet != 16) || (constants::nt_per_assembled_chunk % 128))
throw runtime_error("ch_frb_io: can't use this kernel");
if (stride < constants::nt_per_assembled_chunk)
throw runtime_error("ch_frb_io: bad stride passed to assembled_chunk::decode()");
for (int if_coarse = 0; if_coarse < constants::nfreq_coarse; if_coarse++) {
const float *scales_f = this->scales + if_coarse * nt_coarse;
const float *offsets_f = this->offsets + if_coarse * nt_coarse;
for (int if_fine = if_coarse*nupfreq; if_fine < (if_coarse+1)*nupfreq; if_fine++) {
const uint8_t *src_f = this->data + if_fine * constants::nt_per_assembled_chunk;
float *int_f = intensity + if_fine * stride;
float *wt_f = weights + if_fine * stride;
_kernel(int_f, wt_f, src_f, scales_f, offsets_f);
}
}
}
#endif
} // namespace ch_frb_io
<|endoftext|> |
<commit_before>#include "../config.h"
#include "horde3dwindow.h"
#include "cameranodeobject.h"
#include <Horde3DUtils.h>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/QScreen>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#include <GL/gl.h>
static const bool USE_SEPARATE_CONTEXT = false;
Horde3DWindow::Horde3DWindow(QWindow *parent) :
QQuickWindow(parent),
m_samples(0),
m_initialized(false),
m_dirtyView(false),
m_animTime(0.0f),
m_qtContext(NULL),
m_h3dContext(NULL)
{
connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
connect(this, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
} // end Horde3DWindow
Horde3DWindow::~Horde3DWindow()
{
if(m_h3dContext)
{
m_h3dContext->deleteLater();
m_h3dContext = NULL;
} // end if
} // end ~Horde3DWindow
void Horde3DWindow::renderHorde()
{
m_animTime += 0.4f;
// Do animation blending
h3dSetModelAnimParams(m_knight, 0, m_animTime, 0.5f);
h3dSetModelAnimParams(m_knight, 1, m_animTime, 0.5f);
h3dUpdateModel(m_knight, H3DModelUpdateFlags::Animation | H3DModelUpdateFlags::Geometry);
if(m_camera)
{
if(!USE_SEPARATE_CONTEXT || (m_qtContext && m_h3dContext))
{
restoreH3DState();
h3dRender(m_camera);
h3dFinalizeFrame();
saveH3DState();
} // end if
} // end if
} // end renderHorde
void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << "); devicePixelRatio:" << screen()->devicePixelRatio();
if(event->size() != event->oldSize())
{
m_size = event->size() * screen()->devicePixelRatio();
m_dirtyView = true;
} // end if
QQuickWindow::resizeEvent(event);
} // end geometryChanged
void Horde3DWindow::printHordeMessages()
{
int msgLevel;
float msgTime;
const char* message;
while((message = h3dGetMessage(&msgLevel, &msgTime)) && strlen(message) > 0)
{
qDebug() << msgLevel << "message from Horde3D at" << msgTime << ":" << message;
} // end while
} // end printHordeMessages
void Horde3DWindow::restoreH3DState()
{
if(USE_SEPARATE_CONTEXT)
{
m_qtContext->doneCurrent();
m_h3dContext->makeCurrent(this);
}
else
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
} // end if
QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
glFunctions.glUseProgram(0);
if(renderTarget())
{
renderTarget()->bind();
} // end if
} // end restoreH3DState
void Horde3DWindow::saveH3DState()
{
if(renderTarget())
{
renderTarget()->release();
} // end if
if(USE_SEPARATE_CONTEXT)
{
m_h3dContext->doneCurrent();
m_qtContext->makeCurrent(this);
}
else
{
glPopAttrib();
} // end if
} // end saveH3DState
void Horde3DWindow::updateView()
{
if(m_initialized)
{
qDebug() << "Horde3DWindow::updateView()";
int deviceWidth = m_size.width();
int deviceHeight = m_size.height();
// Resize viewport
h3dSetNodeParamI(m_camera, H3DCamera::ViewportXI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportYI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportWidthI, deviceWidth);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportHeightI, deviceHeight);
// Set virtual camera parameters
float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
h3dSetupCameraView(m_camera, 45.0f, aspectRatio, 0.1f, 1000.0f);
h3dSetNodeTransform(m_camera,
0, 40, -40,
//-40, 40, -70,
23, -166, 180,
1, 1, 1
);
H3DRes cameraPipeRes = h3dGetNodeParamI(m_camera, H3DCamera::PipeResI);
h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);
m_dirtyView = false;
} // end if
} // end updateView
void Horde3DWindow::timerEvent(QTimerEvent *)
{
update();
} // end timerEvent
void Horde3DWindow::onBeforeRendering()
{
if(!m_initialized)
{
init();
} // end if
if(m_dirtyView)
{
updateView();
} // end if
if(USE_SEPARATE_CONTEXT)
{
if(m_h3dContext && (m_h3dContext->format() != m_qtContext->format()))
{
m_h3dContext->deleteLater();
m_h3dContext = NULL;
} // end if
if(!m_h3dContext)
{
qDebug() << "Creating new OpenGL context.";
// Create a new shared OpenGL context to be used exclusively by Horde3D
m_h3dContext = new QOpenGLContext();
m_h3dContext->setFormat(requestedFormat());
m_h3dContext->setShareContext(m_qtContext);
m_h3dContext->create();
} // end if
} // end if
renderHorde();
printHordeMessages();
} // end onBeforeRendering
void Horde3DWindow::onInitFinished()
{
startTimer(16);
} // end onInitFinished
void Horde3DWindow::init()
{
qDebug() << "Horde3DWindow::init()";
m_qtContext = openglContext();
m_samples = m_qtContext->format().samples();
if(!h3dInit())
{
qCritical() << "h3dInit failed";
} // end if
int textureAnisotropy = 8;
if(!h3dSetOption(H3DOptions::MaxAnisotropy, textureAnisotropy))
{
qDebug() << "Couldn't set texture anisotropy to" << textureAnisotropy << "!";
} // end if
if(!h3dSetOption(H3DOptions::SampleCount, m_samples))
{
qDebug() << "Couldn't set antialiasing samples to" << m_samples << "!";
} // end if
H3DRes pipeline = h3dAddResource(H3DResTypes::Pipeline, "pipelines/forward.pipeline.xml", 0);
H3DRes knight = h3dAddResource(H3DResTypes::SceneGraph, "models/knight/knight.scene.xml", 0);
H3DRes knightAnim1Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_order.anim", 0 );
H3DRes knightAnim2Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_attack.anim", 0 );
h3dutLoadResourcesFromDisk("Content");
m_knight = h3dAddNodes(H3DRootNode, knight);
h3dSetNodeTransform(m_knight,
0, 0, 0,
0, 0, 0,
1, 1, 1
);
h3dSetupModelAnimStage(m_knight, 0, knightAnim1Res, 0, "", false);
h3dSetupModelAnimStage(m_knight, 1, knightAnim2Res, 0, "", false);
m_camera = h3dAddCameraNode(H3DRootNode, "cam", pipeline);
h3dSetNodeParamF(m_camera, H3DCamera::FarPlaneF, 0, 100000);
m_cameraObject = new CameraNodeObject(m_camera);
m_cameraQObject = static_cast<QObject *>(m_cameraObject);
setClearBeforeRendering(false);
printHordeMessages();
qDebug() << "--------- Initialization Finished ---------";
m_initialized = true;
emit initFinished();
} // end init
<commit_msg>Set m_size at initialization time, and schedule a view update. Should fix render sizing issues at startup.<commit_after>#include "../config.h"
#include "horde3dwindow.h"
#include "cameranodeobject.h"
#include <Horde3DUtils.h>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/QScreen>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#include <GL/gl.h>
static const bool USE_SEPARATE_CONTEXT = false;
Horde3DWindow::Horde3DWindow(QWindow *parent) :
QQuickWindow(parent),
m_samples(0),
m_initialized(false),
m_dirtyView(false),
m_animTime(0.0f),
m_qtContext(NULL),
m_h3dContext(NULL)
{
connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
connect(this, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
} // end Horde3DWindow
Horde3DWindow::~Horde3DWindow()
{
if(m_h3dContext)
{
m_h3dContext->deleteLater();
m_h3dContext = NULL;
} // end if
} // end ~Horde3DWindow
void Horde3DWindow::renderHorde()
{
m_animTime += 0.4f;
// Do animation blending
h3dSetModelAnimParams(m_knight, 0, m_animTime, 0.5f);
h3dSetModelAnimParams(m_knight, 1, m_animTime, 0.5f);
h3dUpdateModel(m_knight, H3DModelUpdateFlags::Animation | H3DModelUpdateFlags::Geometry);
if(m_camera)
{
if(!USE_SEPARATE_CONTEXT || (m_qtContext && m_h3dContext))
{
restoreH3DState();
h3dRender(m_camera);
h3dFinalizeFrame();
saveH3DState();
} // end if
} // end if
} // end renderHorde
void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << "); devicePixelRatio:" << screen()->devicePixelRatio();
if(event->size() != event->oldSize())
{
m_size = event->size() * screen()->devicePixelRatio();
m_dirtyView = true;
} // end if
QQuickWindow::resizeEvent(event);
} // end geometryChanged
void Horde3DWindow::printHordeMessages()
{
int msgLevel;
float msgTime;
const char* message;
while((message = h3dGetMessage(&msgLevel, &msgTime)) && strlen(message) > 0)
{
qDebug() << msgLevel << "message from Horde3D at" << msgTime << ":" << message;
} // end while
} // end printHordeMessages
void Horde3DWindow::restoreH3DState()
{
if(USE_SEPARATE_CONTEXT)
{
m_qtContext->doneCurrent();
m_h3dContext->makeCurrent(this);
}
else
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
} // end if
QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
glFunctions.glUseProgram(0);
if(renderTarget())
{
renderTarget()->bind();
} // end if
} // end restoreH3DState
void Horde3DWindow::saveH3DState()
{
if(renderTarget())
{
renderTarget()->release();
} // end if
if(USE_SEPARATE_CONTEXT)
{
m_h3dContext->doneCurrent();
m_qtContext->makeCurrent(this);
}
else
{
glPopAttrib();
} // end if
} // end saveH3DState
void Horde3DWindow::updateView()
{
if(m_initialized)
{
qDebug() << "Horde3DWindow::updateView()";
int deviceWidth = m_size.width();
int deviceHeight = m_size.height();
// Resize viewport
h3dSetNodeParamI(m_camera, H3DCamera::ViewportXI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportYI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportWidthI, deviceWidth);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportHeightI, deviceHeight);
// Set virtual camera parameters
float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
h3dSetupCameraView(m_camera, 45.0f, aspectRatio, 0.1f, 1000.0f);
h3dSetNodeTransform(m_camera,
0, 40, -40,
//-40, 40, -70,
23, -166, 180,
1, 1, 1
);
H3DRes cameraPipeRes = h3dGetNodeParamI(m_camera, H3DCamera::PipeResI);
h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);
m_dirtyView = false;
} // end if
} // end updateView
void Horde3DWindow::timerEvent(QTimerEvent *)
{
update();
} // end timerEvent
void Horde3DWindow::onBeforeRendering()
{
if(!m_initialized)
{
init();
} // end if
if(m_dirtyView)
{
updateView();
} // end if
if(USE_SEPARATE_CONTEXT)
{
if(m_h3dContext && (m_h3dContext->format() != m_qtContext->format()))
{
m_h3dContext->deleteLater();
m_h3dContext = NULL;
} // end if
if(!m_h3dContext)
{
qDebug() << "Creating new OpenGL context.";
// Create a new shared OpenGL context to be used exclusively by Horde3D
m_h3dContext = new QOpenGLContext();
m_h3dContext->setFormat(requestedFormat());
m_h3dContext->setShareContext(m_qtContext);
m_h3dContext->create();
} // end if
} // end if
renderHorde();
printHordeMessages();
} // end onBeforeRendering
void Horde3DWindow::onInitFinished()
{
startTimer(16);
} // end onInitFinished
void Horde3DWindow::init()
{
qDebug() << "Horde3DWindow::init()";
m_qtContext = openglContext();
m_samples = m_qtContext->format().samples();
if(!h3dInit())
{
qCritical() << "h3dInit failed";
} // end if
int textureAnisotropy = 8;
if(!h3dSetOption(H3DOptions::MaxAnisotropy, textureAnisotropy))
{
qDebug() << "Couldn't set texture anisotropy to" << textureAnisotropy << "!";
} // end if
if(!h3dSetOption(H3DOptions::SampleCount, m_samples))
{
qDebug() << "Couldn't set antialiasing samples to" << m_samples << "!";
} // end if
H3DRes pipeline = h3dAddResource(H3DResTypes::Pipeline, "pipelines/forward.pipeline.xml", 0);
H3DRes knight = h3dAddResource(H3DResTypes::SceneGraph, "models/knight/knight.scene.xml", 0);
H3DRes knightAnim1Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_order.anim", 0 );
H3DRes knightAnim2Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_attack.anim", 0 );
h3dutLoadResourcesFromDisk("Content");
m_knight = h3dAddNodes(H3DRootNode, knight);
h3dSetNodeTransform(m_knight,
0, 0, 0,
0, 0, 0,
1, 1, 1
);
h3dSetupModelAnimStage(m_knight, 0, knightAnim1Res, 0, "", false);
h3dSetupModelAnimStage(m_knight, 1, knightAnim2Res, 0, "", false);
m_camera = h3dAddCameraNode(H3DRootNode, "cam", pipeline);
h3dSetNodeParamF(m_camera, H3DCamera::FarPlaneF, 0, 100000);
m_cameraObject = new CameraNodeObject(m_camera);
m_cameraQObject = static_cast<QObject *>(m_cameraObject);
setClearBeforeRendering(false);
printHordeMessages();
qDebug() << "--------- Initialization Finished ---------";
m_size = size() * screen()->devicePixelRatio();
m_dirtyView = true;
m_initialized = true;
emit initFinished();
} // end init
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------------*/
/* Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------*/
#include <limits.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "HostShare.h"
using namespace std;
/* ************************************************************************ */
/* HostSharePCI */
/* ************************************************************************ */
int HostSharePCI::from_xml_node(const xmlNodePtr node)
{
int rc = Template::from_xml_node(node);
if (rc != 0)
{
return -1;
}
return init();
}
int HostSharePCI::init()
{
vector<Attribute *> devices;
int num_devs = get("PCI", devices);
for (int i=0; i < num_devs; i++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(devices[i]);
if (pci == 0)
{
return -1;
}
PCIDevice * pcidev = new PCIDevice(pci);
pci_devices.insert(make_pair(pcidev->address, pcidev));
}
return 0;
}
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
bool HostSharePCI::test_set(unsigned int vendor_id, unsigned int device_id,
unsigned int class_id, VectorAttribute * devreq, int vmid,
std::set<string>& assigned)
{
map<string, PCIDevice *>::iterator it;
for (it=pci_devices.begin(); it!=pci_devices.end(); it++)
{
PCIDevice * dev = it->second;
if (dev->class_id == class_id &&
dev->vendor_id == vendor_id &&
dev->device_id == device_id &&
dev->vmid == -1 &&
assigned.find(dev->address) == assigned.end())
{
assigned.insert(dev->address);
if (vmid != -1)
{
dev->vmid = vmid;
dev->attrs->replace("VMID", vmid);
devreq->replace("DOMAIN",dev->attrs->vector_value("DOMAIN"));
devreq->replace("BUS",dev->attrs->vector_value("BUS"));
devreq->replace("SLOT",dev->attrs->vector_value("SLOT"));
devreq->replace("FUNCTION",dev->attrs->vector_value("FUNCTION"));
devreq->replace("ADDRESS",dev->attrs->vector_value("ADDRESS"));
}
return true;
}
}
return false;
}
/* ------------------------------------------------------------------------*/
bool HostSharePCI::test_set(vector<Attribute *> &devs, int vmid)
{
vector<Attribute *>::iterator it;
std::set<string> assigned;
unsigned int vendor_id, device_id, class_id;
for ( it=devs.begin(); it!= devs.end(); it++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(*it);
if ( pci == 0 )
{
return false;
}
vendor_id = get_pci_value("VENDOR", pci);
device_id = get_pci_value("DEVICE", pci);
class_id = get_pci_value("CLASS", pci);
if (!test_set(vendor_id, device_id, class_id, pci, vmid, assigned))
{
return false;
}
}
return true;
}
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
void HostSharePCI::del(const vector<Attribute *> &devs)
{
vector<Attribute *>::const_iterator it;
map<string, PCIDevice *>::iterator pci_it;
for ( it=devs.begin(); it!= devs.end(); it++)
{
const VectorAttribute * pci = dynamic_cast<const VectorAttribute *>(*it);
if ( pci == 0 )
{
continue;
}
pci_it = pci_devices.find(pci->vector_value("ADDRESS"));
if (pci_it != pci_devices.end())
{
pci_it->second->vmid = -1;
pci_it->second->attrs->replace("VMID",-1);
}
}
};
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
void HostSharePCI::set_monitorization(vector<Attribute*> &pci_att)
{
vector<Attribute*>::iterator it;
map<string, PCIDevice*>::iterator pci_it;
string address;
for (it = pci_att.begin(); it != pci_att.end(); it++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(*it);
if ( pci == 0 )
{
continue;
}
address = pci->vector_value("ADDRESS");
if (address.empty())
{
delete pci;
continue;
}
pci_it = pci_devices.find(address);
if (pci_it != pci_devices.end())
{
delete pci;
continue;
}
PCIDevice * dev = new PCIDevice(pci);
pci_devices.insert(make_pair(address, dev));
set(pci);
}
};
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
unsigned int HostSharePCI::get_pci_value(const char * name,
const VectorAttribute * pci_device)
{
string temp;
temp = pci_device->vector_value(name);
if (temp.empty())
{
return 0;
}
unsigned int pci_value;
istringstream iss(temp);
iss >> hex >> pci_value;
if (iss.fail() || !iss.eof())
{
return 0;
}
return pci_value;
}
HostSharePCI::PCIDevice::PCIDevice(VectorAttribute * _attrs)
: vmid(-1), attrs(_attrs)
{
vendor_id = get_pci_value("VENDOR", attrs);
device_id = get_pci_value("DEVICE", attrs);
class_id = get_pci_value("CLASS", attrs);
attrs->vector_value("VMID", vmid);
attrs->vector_value("ADDRESS", address);
};
/* ************************************************************************ */
/* HostShare :: Constructor/Destructor */
/* ************************************************************************ */
HostShare::HostShare(long long _max_disk,long long _max_mem,long long _max_cpu):
ObjectXML(),
disk_usage(0),
mem_usage(0),
cpu_usage(0),
max_disk(_max_disk),
max_mem(_max_mem),
max_cpu(_max_cpu),
free_disk(0),
free_mem(0),
free_cpu(0),
used_disk(0),
used_mem(0),
used_cpu(0),
running_vms(0),
ds(),
pci(){};
ostream& operator<<(ostream& os, HostShare& hs)
{
string str;
os << hs.to_xml(str);
return os;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& HostShare::to_xml(string& xml) const
{
string ds_xml, pci_xml;
ostringstream oss;
oss << "<HOST_SHARE>"
<< "<DISK_USAGE>" << disk_usage << "</DISK_USAGE>"
<< "<MEM_USAGE>" << mem_usage << "</MEM_USAGE>"
<< "<CPU_USAGE>" << cpu_usage << "</CPU_USAGE>"
<< "<MAX_DISK>" << max_disk << "</MAX_DISK>"
<< "<MAX_MEM>" << max_mem << "</MAX_MEM>"
<< "<MAX_CPU>" << max_cpu << "</MAX_CPU>"
<< "<FREE_DISK>" << free_disk << "</FREE_DISK>"
<< "<FREE_MEM>" << free_mem << "</FREE_MEM>"
<< "<FREE_CPU>" << free_cpu << "</FREE_CPU>"
<< "<USED_DISK>" << used_disk << "</USED_DISK>"
<< "<USED_MEM>" << used_mem << "</USED_MEM>"
<< "<USED_CPU>" << used_cpu << "</USED_CPU>"
<< "<RUNNING_VMS>"<<running_vms <<"</RUNNING_VMS>"
<< ds.to_xml(ds_xml)
<< pci.to_xml(pci_xml)
<< "</HOST_SHARE>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int HostShare::from_xml_node(const xmlNodePtr node)
{
vector<xmlNodePtr> content;
int rc = 0;
// Initialize the internal XML object
ObjectXML::update_from_node(node);
rc += xpath(disk_usage, "/HOST_SHARE/DISK_USAGE", -1);
rc += xpath(mem_usage, "/HOST_SHARE/MEM_USAGE", -1);
rc += xpath(cpu_usage, "/HOST_SHARE/CPU_USAGE", -1);
rc += xpath(max_disk, "/HOST_SHARE/MAX_DISK", -1);
rc += xpath(max_mem , "/HOST_SHARE/MAX_MEM", -1);
rc += xpath(max_cpu , "/HOST_SHARE/MAX_CPU", -1);
rc += xpath(free_disk, "/HOST_SHARE/FREE_DISK", -1);
rc += xpath(free_mem , "/HOST_SHARE/FREE_MEM", -1);
rc += xpath(free_cpu , "/HOST_SHARE/FREE_CPU", -1);
rc += xpath(used_disk, "/HOST_SHARE/USED_DISK", -1);
rc += xpath(used_mem , "/HOST_SHARE/USED_MEM", -1);
rc += xpath(used_cpu , "/HOST_SHARE/USED_CPU", -1);
rc += xpath(running_vms,"/HOST_SHARE/RUNNING_VMS",-1);
// ------------ DS Template ---------------
ObjectXML::get_nodes("/HOST_SHARE/DATASTORES", content);
if( content.empty())
{
return -1;
}
rc += ds.from_xml_node( content[0] );
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
// ------------ DS Template ---------------
ObjectXML::get_nodes("/HOST_SHARE/PCI_DEVICES", content);
if( content.empty())
{
return -1;
}
rc += pci.from_xml_node( content[0] );
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
void HostShare::set_ds_monitorization(const vector<Attribute*> &ds_att)
{
vector<Attribute*>::const_iterator it;
ds.erase("DS");
for (it = ds_att.begin(); it != ds_att.end(); it++)
{
ds.set(*it);
}
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<commit_msg>feature #3028: Fix PCI device assignment<commit_after>/* ------------------------------------------------------------------------*/
/* Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------*/
#include <limits.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "HostShare.h"
using namespace std;
/* ************************************************************************ */
/* HostSharePCI */
/* ************************************************************************ */
int HostSharePCI::from_xml_node(const xmlNodePtr node)
{
int rc = Template::from_xml_node(node);
if (rc != 0)
{
return -1;
}
return init();
}
int HostSharePCI::init()
{
vector<Attribute *> devices;
int num_devs = get("PCI", devices);
for (int i=0; i < num_devs; i++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(devices[i]);
if (pci == 0)
{
return -1;
}
PCIDevice * pcidev = new PCIDevice(pci);
pci_devices.insert(make_pair(pcidev->address, pcidev));
}
return 0;
}
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
bool HostSharePCI::test_set(unsigned int vendor_id, unsigned int device_id,
unsigned int class_id, VectorAttribute * devreq, int vmid,
std::set<string>& assigned)
{
map<string, PCIDevice *>::iterator it;
for (it=pci_devices.begin(); it!=pci_devices.end(); it++)
{
PCIDevice * dev = it->second;
if ((class_id == 0 || dev->class_id == class_id) &&
(vendor_id == 0 || dev->vendor_id == vendor_id) &&
(device_id == 0 || dev->device_id == device_id) &&
dev->vmid == -1 &&
assigned.find(dev->address) == assigned.end())
{
assigned.insert(dev->address);
if (vmid != -1)
{
dev->vmid = vmid;
dev->attrs->replace("VMID", vmid);
devreq->replace("DOMAIN",dev->attrs->vector_value("DOMAIN"));
devreq->replace("BUS",dev->attrs->vector_value("BUS"));
devreq->replace("SLOT",dev->attrs->vector_value("SLOT"));
devreq->replace("FUNCTION",dev->attrs->vector_value("FUNCTION"));
devreq->replace("ADDRESS",dev->attrs->vector_value("ADDRESS"));
}
return true;
}
}
return false;
}
/* ------------------------------------------------------------------------*/
bool HostSharePCI::test_set(vector<Attribute *> &devs, int vmid)
{
vector<Attribute *>::iterator it;
std::set<string> assigned;
unsigned int vendor_id, device_id, class_id;
for ( it=devs.begin(); it!= devs.end(); it++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(*it);
if ( pci == 0 )
{
return false;
}
vendor_id = get_pci_value("VENDOR", pci);
device_id = get_pci_value("DEVICE", pci);
class_id = get_pci_value("CLASS", pci);
if (!test_set(vendor_id, device_id, class_id, pci, vmid, assigned))
{
return false;
}
}
return true;
}
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
void HostSharePCI::del(const vector<Attribute *> &devs)
{
vector<Attribute *>::const_iterator it;
map<string, PCIDevice *>::iterator pci_it;
for ( it=devs.begin(); it!= devs.end(); it++)
{
const VectorAttribute * pci = dynamic_cast<const VectorAttribute *>(*it);
if ( pci == 0 )
{
continue;
}
pci_it = pci_devices.find(pci->vector_value("ADDRESS"));
if (pci_it != pci_devices.end())
{
pci_it->second->vmid = -1;
pci_it->second->attrs->replace("VMID",-1);
}
}
};
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
void HostSharePCI::set_monitorization(vector<Attribute*> &pci_att)
{
vector<Attribute*>::iterator it;
map<string, PCIDevice*>::iterator pci_it;
string address;
for (it = pci_att.begin(); it != pci_att.end(); it++)
{
VectorAttribute * pci = dynamic_cast<VectorAttribute *>(*it);
if ( pci == 0 )
{
continue;
}
address = pci->vector_value("ADDRESS");
if (address.empty())
{
delete pci;
continue;
}
pci_it = pci_devices.find(address);
if (pci_it != pci_devices.end())
{
delete pci;
continue;
}
PCIDevice * dev = new PCIDevice(pci);
pci_devices.insert(make_pair(address, dev));
set(pci);
}
};
/* ------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------*/
unsigned int HostSharePCI::get_pci_value(const char * name,
const VectorAttribute * pci_device)
{
string temp;
temp = pci_device->vector_value(name);
if (temp.empty())
{
return 0;
}
unsigned int pci_value;
istringstream iss(temp);
iss >> hex >> pci_value;
if (iss.fail() || !iss.eof())
{
return 0;
}
return pci_value;
}
HostSharePCI::PCIDevice::PCIDevice(VectorAttribute * _attrs)
: vmid(-1), attrs(_attrs)
{
vendor_id = get_pci_value("VENDOR", attrs);
device_id = get_pci_value("DEVICE", attrs);
class_id = get_pci_value("CLASS", attrs);
attrs->vector_value("VMID", vmid);
attrs->vector_value("ADDRESS", address);
};
/* ************************************************************************ */
/* HostShare :: Constructor/Destructor */
/* ************************************************************************ */
HostShare::HostShare(long long _max_disk,long long _max_mem,long long _max_cpu):
ObjectXML(),
disk_usage(0),
mem_usage(0),
cpu_usage(0),
max_disk(_max_disk),
max_mem(_max_mem),
max_cpu(_max_cpu),
free_disk(0),
free_mem(0),
free_cpu(0),
used_disk(0),
used_mem(0),
used_cpu(0),
running_vms(0),
ds(),
pci(){};
ostream& operator<<(ostream& os, HostShare& hs)
{
string str;
os << hs.to_xml(str);
return os;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& HostShare::to_xml(string& xml) const
{
string ds_xml, pci_xml;
ostringstream oss;
oss << "<HOST_SHARE>"
<< "<DISK_USAGE>" << disk_usage << "</DISK_USAGE>"
<< "<MEM_USAGE>" << mem_usage << "</MEM_USAGE>"
<< "<CPU_USAGE>" << cpu_usage << "</CPU_USAGE>"
<< "<MAX_DISK>" << max_disk << "</MAX_DISK>"
<< "<MAX_MEM>" << max_mem << "</MAX_MEM>"
<< "<MAX_CPU>" << max_cpu << "</MAX_CPU>"
<< "<FREE_DISK>" << free_disk << "</FREE_DISK>"
<< "<FREE_MEM>" << free_mem << "</FREE_MEM>"
<< "<FREE_CPU>" << free_cpu << "</FREE_CPU>"
<< "<USED_DISK>" << used_disk << "</USED_DISK>"
<< "<USED_MEM>" << used_mem << "</USED_MEM>"
<< "<USED_CPU>" << used_cpu << "</USED_CPU>"
<< "<RUNNING_VMS>"<<running_vms <<"</RUNNING_VMS>"
<< ds.to_xml(ds_xml)
<< pci.to_xml(pci_xml)
<< "</HOST_SHARE>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int HostShare::from_xml_node(const xmlNodePtr node)
{
vector<xmlNodePtr> content;
int rc = 0;
// Initialize the internal XML object
ObjectXML::update_from_node(node);
rc += xpath(disk_usage, "/HOST_SHARE/DISK_USAGE", -1);
rc += xpath(mem_usage, "/HOST_SHARE/MEM_USAGE", -1);
rc += xpath(cpu_usage, "/HOST_SHARE/CPU_USAGE", -1);
rc += xpath(max_disk, "/HOST_SHARE/MAX_DISK", -1);
rc += xpath(max_mem , "/HOST_SHARE/MAX_MEM", -1);
rc += xpath(max_cpu , "/HOST_SHARE/MAX_CPU", -1);
rc += xpath(free_disk, "/HOST_SHARE/FREE_DISK", -1);
rc += xpath(free_mem , "/HOST_SHARE/FREE_MEM", -1);
rc += xpath(free_cpu , "/HOST_SHARE/FREE_CPU", -1);
rc += xpath(used_disk, "/HOST_SHARE/USED_DISK", -1);
rc += xpath(used_mem , "/HOST_SHARE/USED_MEM", -1);
rc += xpath(used_cpu , "/HOST_SHARE/USED_CPU", -1);
rc += xpath(running_vms,"/HOST_SHARE/RUNNING_VMS",-1);
// ------------ DS Template ---------------
ObjectXML::get_nodes("/HOST_SHARE/DATASTORES", content);
if( content.empty())
{
return -1;
}
rc += ds.from_xml_node( content[0] );
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
// ------------ DS Template ---------------
ObjectXML::get_nodes("/HOST_SHARE/PCI_DEVICES", content);
if( content.empty())
{
return -1;
}
rc += pci.from_xml_node( content[0] );
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
void HostShare::set_ds_monitorization(const vector<Attribute*> &ds_att)
{
vector<Attribute*>::const_iterator it;
ds.erase("DS");
for (it = ds_att.begin(); it != ds_att.end(); it++)
{
ds.set(*it);
}
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<|endoftext|> |
<commit_before>/* Given a funnel and a description of obstacles (in terms of vertices), check if the funnel is collision free when executed beginning at state x.
Inputs:
x: state from which funnel is executed (only the cyclic dimensions matter, really)
forest: cell array containing vertices of obstacles
funnelLibrary: struct containing funnel library
funnelLibrary(*).xyz: xyz positions at time points (double 3 X N)
funnelLibrary(*).cS: cholesky factorization of projection of S matrix (cell array)
funnelIdx: index of funnel to be checked
Output: Whether funnel is collision free (boolean)
Author: Anirudha Majumdar
Date: Nov 12 2013
*/
// Mex stuff
#include <mex.h>
#include <math.h>
#include <matrix.h>
// Timer functions
// #include <chrono>
// #include <ctime>
// #include <time.h>
// Internal access to bullet
#include "LinearMath/btTransform.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btConvexHullShape.h"
// #include <iostream>
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPointCollector.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "LinearMath/btTransformUtil.h"
using namespace std;
// Set solvers for bullet
static btVoronoiSimplexSolver sGjkSimplexSolver;
static btGjkEpaPenetrationDepthSolver epaSolver;
/*Sphere of radius r representing the point.
We could probably make the radius 0 and be ok, but I'm not sure if bullet expects things to be non-degenrate.
*/
static const double g_radius = 1.0; // Don't change: leave at 1.0
static btSphereShape* g_point = new btSphereShape(g_radius);
double ptToPolyBullet(double *vertsPr, size_t nRows, size_t nCols){
// Initialize polytope object with single point
btConvexHullShape polytope(btVector3(vertsPr[0],vertsPr[1],vertsPr[2]), 1);
// Add rest of the points (note the indexing starts from 1 on the loop)
for(int i=1;i<nCols;i++){
polytope.addPoint(btVector3(vertsPr[i*nRows],vertsPr[i*nRows+1],vertsPr[i*nRows+2]));
}
// Assign elements of verts (input) to polytope
btTransform tr;
btGjkPairDetector::ClosestPointInput input;
tr.setIdentity();
input.m_transformA = tr;
input.m_transformB = tr;
btGjkPairDetector convexConvex(g_point,&polytope,&sGjkSimplexSolver,&epaSolver);
// Output
btPointCollector gjkOutput;
convexConvex.getClosestPoints(input, gjkOutput, 0);
return gjkOutput.m_distance + g_radius + CONVEX_DISTANCE_MARGIN;
}
/* Shift and transform vertices
*/
double *shiftAndTransform(double *verts, double *vertsT, const mxArray *x, mxArray *x0, int k, mxArray *cSk, size_t nRows, size_t nCols)
{
/* This can and maybe should be sped up. For example, we know that cSk is upper triangular.*/
double *dcSk = mxGetPr(cSk);
double *dx0 = mxGetPr(x0);
double *dx = mxGetPr(x);
for(int i=0;i<nRows;i++){
for(int j=0;j<nCols;j++){
vertsT[j*nRows+i] = dcSk[i]*(verts[j*nRows+0]-dx0[k*nRows+0]-dx[0]) + dcSk[nRows+i]*(verts[j*nRows+1]-dx0[k*nRows+1]-dx[1]) + dcSk[2*nRows+i]*(verts[j*nRows+2]-dx0[k*nRows+2]-dx[2]);
// mexPrintf("i: %d, j: %d, val: %f\n", i, j, vertsT[j*nRows+i]);
}
}
return vertsT;
}
/* Checks if a given funnel number funnelIdx is collision free if executed beginning at state x. Returns a boolean (true if collision free, false if not).
*/
bool isCollisionFree(int funnelIdx, const mxArray *x, const mxArray *funnelLibrary, const mxArray *forest, mwSize numObs, double *min_dist)
{
// Initialize some variables
double *verts; // cell element (i.e. vertices)
mxArray *x0 = mxGetField(funnelLibrary, funnelIdx, "xyz"); // all points on trajectory
mxArray *obstacle;
mxArray *cS = mxGetField(funnelLibrary, funnelIdx, "cS");
mxArray *cSk;
size_t nCols;
size_t nRows;
double distance;
// Get number of time samples
mwSize N = mxGetNumberOfElements(mxGetField(funnelLibrary, funnelIdx, "cS"));
// Initialize collFree to true
bool collFree = true;
// For each time sample, we need to check if we are collision free
// mxArray *collisions = mxCreateLogicalMatrix(numObs,N);
for(int k=0;k<N;k++)
{
// Get pointer to cholesky factorization of S at this time
cSk = mxGetCell(cS,k);
for(mwIndex jForest=0;jForest<numObs;jForest++)
{
// Get vertices of this obstacle
obstacle = mxGetCell(forest, jForest);
verts = mxGetPr(mxGetCell(forest, jForest)); // Get vertices
nCols = mxGetN(obstacle);
nRows = mxGetM(obstacle);
double *vertsT = mxGetPr(mxCreateDoubleMatrix(nRows, nCols, mxREAL));
// Shift vertices so that point on trajectory is at origin and transform by cholesky of S
vertsT = shiftAndTransform(verts, vertsT, x, x0, k, cSk, nRows, nCols);
// Call bullet to do point to polytope distance computation
distance = ptToPolyBullet(vertsT, nRows, nCols);
// Update min_dist
if(distance < *min_dist){
*min_dist = distance;
}
// mexPrintf("distance: %f\n", distance);
// Check if distance is less than 1 (i.e. not collision free). If so, return
//if(distance < 1){
//collFree = false;
// return collFree;
//}
}
}
if(*min_dist < 1){
collFree = false;
}
return collFree;
}
/* Main mex funtion*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Get x (state) from which funnel is to be executed
const mxArray *x;
x = prhs[0];
// x = mxGetPr(prhs[0]);
// Deal with forest cell (second input)
const mxArray *forest; // Cell array containing forest (pointer)
forest = prhs[1]; // Get forest cell (second input)
mwSize numObs = mxGetNumberOfElements(forest); // Number of obstacles
// Now deal with funnel library object (third input)
const mxArray *funnelLibrary; // Funnel library (pointer)
funnelLibrary = prhs[2]; // Get funnel library (third input)
// Get funnelIdx (subtract 1 since index is coming from matlab)
int funnelIdx;
funnelIdx = (int )mxGetScalar(prhs[3]);
funnelIdx = funnelIdx-1;
// Initialize min_dist
// double min_dist_init = 1000000.0;
double min_dist = 1000000.0;
/*// Return min_dist if asked for
if (nlhs > 1){
plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
min_dist = mxGetPr(plhs[1]);
}*/
// &min_dist = &min_dist_init;
// mexPrintf("min_dist: %f", min_dist);
// Initialize next funnel (output of this function)
bool collFree = isCollisionFree(funnelIdx, x, funnelLibrary, forest, numObs, &min_dist);
// Return collFree
plhs[0] = mxCreateLogicalScalar(collFree);
// mexPrintf("min_dist: %f", min_dist);
// Return min_dist if asked for
if (nlhs > 1){
plhs[1] = mxCreateDoubleScalar(min_dist);
}
return;
}
<commit_msg>cleaned up comments in isCollisionFree_mex<commit_after>/* Given a funnel and a description of obstacles (in terms of vertices), check if the funnel is collision free when executed beginning at state x.
Inputs:
x: state from which funnel is executed (only the cyclic dimensions matter, really)
forest: cell array containing vertices of obstacles
funnelLibrary: struct containing funnel library
funnelLibrary(*).xyz: xyz positions at time points (double 3 X N)
funnelLibrary(*).cS: cholesky factorization of projection of S matrix (cell array)
funnelIdx: index of funnel to be checked
Output: Whether funnel is collision free (boolean)
Author: Anirudha Majumdar
Date: Nov 12 2013
*/
// Mex stuff
#include <mex.h>
#include <math.h>
#include <matrix.h>
// Internal access to bullet
#include "LinearMath/btTransform.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btConvexHullShape.h"
// #include <iostream>
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPointCollector.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "LinearMath/btTransformUtil.h"
using namespace std;
// Set solvers for bullet
static btVoronoiSimplexSolver sGjkSimplexSolver;
static btGjkEpaPenetrationDepthSolver epaSolver;
/*Sphere of radius r representing the point.
We could probably make the radius 0 and be ok, but I'm not sure if bullet expects things to be non-degenrate.
*/
static const double g_radius = 1.0; // Don't change: leave at 1.0
static btSphereShape* g_point = new btSphereShape(g_radius);
double ptToPolyBullet(double *vertsPr, size_t nRows, size_t nCols){
// Initialize polytope object with single point
btConvexHullShape polytope(btVector3(vertsPr[0],vertsPr[1],vertsPr[2]), 1);
// Add rest of the points (note the indexing starts from 1 on the loop)
for(int i=1;i<nCols;i++){
polytope.addPoint(btVector3(vertsPr[i*nRows],vertsPr[i*nRows+1],vertsPr[i*nRows+2]));
}
// Assign elements of verts (input) to polytope
btTransform tr;
btGjkPairDetector::ClosestPointInput input;
tr.setIdentity();
input.m_transformA = tr;
input.m_transformB = tr;
btGjkPairDetector convexConvex(g_point,&polytope,&sGjkSimplexSolver,&epaSolver);
// Output
btPointCollector gjkOutput;
convexConvex.getClosestPoints(input, gjkOutput, 0);
return gjkOutput.m_distance + g_radius + CONVEX_DISTANCE_MARGIN;
}
/* Shift and transform vertices
*/
double *shiftAndTransform(double *verts, double *vertsT, const mxArray *x, mxArray *x0, int k, mxArray *cSk, size_t nRows, size_t nCols)
{
/* This can and maybe should be sped up. For example, we know that cSk is upper triangular.*/
double *dcSk = mxGetPr(cSk);
double *dx0 = mxGetPr(x0);
double *dx = mxGetPr(x);
for(int i=0;i<nRows;i++){
for(int j=0;j<nCols;j++){
vertsT[j*nRows+i] = dcSk[i]*(verts[j*nRows+0]-dx0[k*nRows+0]-dx[0]) + dcSk[nRows+i]*(verts[j*nRows+1]-dx0[k*nRows+1]-dx[1]) + dcSk[2*nRows+i]*(verts[j*nRows+2]-dx0[k*nRows+2]-dx[2]);
}
}
return vertsT;
}
/* Checks if a given funnel number funnelIdx is collision free if executed beginning at state x. Returns a boolean (true if collision free, false if not).
*/
bool isCollisionFree(int funnelIdx, const mxArray *x, const mxArray *funnelLibrary, const mxArray *forest, mwSize numObs, double *min_dist)
{
// Initialize some variables
double *verts; // cell element (i.e. vertices)
mxArray *x0 = mxGetField(funnelLibrary, funnelIdx, "xyz"); // all points on trajectory
mxArray *obstacle;
mxArray *cS = mxGetField(funnelLibrary, funnelIdx, "cS");
mxArray *cSk;
size_t nCols;
size_t nRows;
double distance;
// Get number of time samples
mwSize N = mxGetNumberOfElements(mxGetField(funnelLibrary, funnelIdx, "cS"));
// Initialize collFree to true
bool collFree = true;
// For each time sample, we need to check if we are collision free
for(int k=0;k<N;k++)
{
// Get pointer to cholesky factorization of S at this time
cSk = mxGetCell(cS,k);
for(mwIndex jForest=0;jForest<numObs;jForest++)
{
// Get vertices of this obstacle
obstacle = mxGetCell(forest, jForest);
verts = mxGetPr(mxGetCell(forest, jForest)); // Get vertices
nCols = mxGetN(obstacle);
nRows = mxGetM(obstacle);
double *vertsT = mxGetPr(mxCreateDoubleMatrix(nRows, nCols, mxREAL));
// Shift vertices so that point on trajectory is at origin and transform by cholesky of S
vertsT = shiftAndTransform(verts, vertsT, x, x0, k, cSk, nRows, nCols);
// Call bullet to do point to polytope distance computation
distance = ptToPolyBullet(vertsT, nRows, nCols);
// Update min_dist
if(distance < *min_dist){
*min_dist = distance;
}
}
}
if(*min_dist < 1){
collFree = false;
}
return collFree;
}
/* Main mex funtion*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Get x (state) from which funnel is to be executed
const mxArray *x;
x = prhs[0];
// Deal with forest cell (second input)
const mxArray *forest; // Cell array containing forest (pointer)
forest = prhs[1]; // Get forest cell (second input)
mwSize numObs = mxGetNumberOfElements(forest); // Number of obstacles
// Now deal with funnel library object (third input)
const mxArray *funnelLibrary; // Funnel library (pointer)
funnelLibrary = prhs[2]; // Get funnel library (third input)
// Get funnelIdx (subtract 1 since index is coming from matlab)
int funnelIdx;
funnelIdx = (int )mxGetScalar(prhs[3]);
funnelIdx = funnelIdx-1;
// Initialize min_dist
double min_dist = 1000000.0;
// Initialize next funnel (output of this function)
bool collFree = isCollisionFree(funnelIdx, x, funnelLibrary, forest, numObs, &min_dist);
plhs[0] = mxCreateLogicalScalar(collFree);
// Return min_dist if asked for
if (nlhs > 1) {
plhs[1] = mxCreateDoubleScalar(min_dist);
}
return;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <functional>
#include <utility>
#include "lhef.h"
namespace lhef {
Particles SelectParticlesBy(std::function<bool(const Particle&)> pred,
const LHEFEvent& lhe) {
Particles ps;
auto entry = lhe.particle_entries();
std::for_each(entry.cbegin(), entry.cend(),
[&] (const std::pair<int, Particle>& pmap) {
Particle p = pmap.second;
if (pred(p)) {
ps.push_back(p);
}});
return ps;
}
Particles InitialStates(const LHEFEvent& lhe) {
auto pred = [] (const Particle& p) {
return p.mothup.first == 1;
};
return SelectParticlesBy(pred, lhe);
}
Particles FinalStates(const LHEFEvent& lhe) {
auto pred = [] (const Particle& p) {
return p.istup == 1;
};
return SelectParticlesBy(pred, lhe);
}
bool ParticleExists(const ParticleID& pid, const Particle& p) {
return std::any_of(pid.cbegin(), pid.cend(),
[&] (const int& id) {
return id == p.idup;
});
}
Particles ParticlesOf(const ParticleID& pid, const LHEFEvent& lhe) {
auto pred = [&] (const Particle& p) {
return ParticleExists(pid, p);
};
return SelectParticlesBy(pred, lhe);
}
ParticleLines ParticleLinesOf(const ParticleID& pid, const LHEFEvent& lhe) {
ParticleLines line;
auto entry = lhe.particle_entries();
for (const auto& e : entry) {
Particle p = e.second;
if (ParticleExists(pid, p)) {
line.push_back(e.first);
}
}
return line;
}
Particle Mother(const Particle& p, const LHEFEvent& lhe) {
int mo_line = p.mothup.first;
auto entry = lhe.particle_entries();
auto mo_pos = entry.find(mo_line);
if (mo_pos == entry.end()) { // mother particle not found
return entry.at(1);
} else {
return entry.at(mo_line);
}
}
Particle Ancestor(const Particle& p, const LHEFEvent& lhe) {
Particle mother = Mother(p, lhe);
return mother.mothup.first == 1? mother : Ancestor(mother, lhe);
}
Particles Daughters(int pline, const LHEFEvent& lhe) {
auto pred = [&] (const Particle& p) {
return p.mothup.first == pline;
};
return SelectParticlesBy(pred, lhe);
}
bool IsInMotherLine(int pline, const Particle& p, const LHEFEvent& lhe) {
if (p.mothup.first == 1) {
return false;
} else if (p.mothup.first == pline) {
return true;
} else {
Particle direct_mother = Mother(p, lhe);
return IsInMotherLine(pline, direct_mother, lhe);
}
}
Particles FinalDaughters(int pline, const LHEFEvent& lhe) {
Particles finalstates = FinalStates(lhe);
auto pos = std::remove_if(finalstates.begin(), finalstates.end(),
[&] (const Particle& p) {
return !IsInMotherLine(pline, p, lhe);
});
finalstates.erase(pos, finalstates.end());
return finalstates;
}
} // namespace lhef
<commit_msg>Modify SelectParticlesBy function, remove unnecessary header<commit_after>#include "lhef.h"
#include <algorithm>
#include <functional>
namespace lhef {
Particles SelectParticlesBy(std::function<bool(const Particle&)> pred,
const LHEFEvent& lhe) {
Particles ps;
auto entry = lhe.particle_entries();
std::for_each(entry.cbegin(), entry.cend(),
[&] (const EventEntry::value_type& pmap) {
auto p = pmap.second;
if (pred(p)) {
ps.push_back(p);
}});
return ps;
}
Particles InitialStates(const LHEFEvent& lhe) {
auto pred = [] (const Particle& p) {
return p.mothup.first == 1;
};
return SelectParticlesBy(pred, lhe);
}
Particles FinalStates(const LHEFEvent& lhe) {
auto pred = [] (const Particle& p) {
return p.istup == 1;
};
return SelectParticlesBy(pred, lhe);
}
bool ParticleExists(const ParticleID& pid, const Particle& p) {
return std::any_of(pid.cbegin(), pid.cend(),
[&] (const int& id) {
return id == p.idup;
});
}
Particles ParticlesOf(const ParticleID& pid, const LHEFEvent& lhe) {
auto pred = [&] (const Particle& p) {
return ParticleExists(pid, p);
};
return SelectParticlesBy(pred, lhe);
}
ParticleLines ParticleLinesOf(const ParticleID& pid, const LHEFEvent& lhe) {
ParticleLines line;
auto entry = lhe.particle_entries();
for (const auto& e : entry) {
auto p = e.second;
if (ParticleExists(pid, p)) {
line.push_back(e.first);
}
}
return line;
}
Particle Mother(const Particle& p, const LHEFEvent& lhe) {
int mo_line = p.mothup.first;
auto entry = lhe.particle_entries();
auto mo_pos = entry.find(mo_line);
if (mo_pos == entry.end()) { // mother particle not found
return entry.at(1);
} else {
return entry.at(mo_line);
}
}
Particle Ancestor(const Particle& p, const LHEFEvent& lhe) {
Particle mother = Mother(p, lhe);
return mother.mothup.first == 1? mother : Ancestor(mother, lhe);
}
Particles Daughters(int pline, const LHEFEvent& lhe) {
auto pred = [&] (const Particle& p) {
return p.mothup.first == pline;
};
return SelectParticlesBy(pred, lhe);
}
bool IsInMotherLine(int pline, const Particle& p, const LHEFEvent& lhe) {
if (p.mothup.first == 1) {
return false;
} else if (p.mothup.first == pline) {
return true;
} else {
Particle direct_mother = Mother(p, lhe);
return IsInMotherLine(pline, direct_mother, lhe);
}
}
Particles FinalDaughters(int pline, const LHEFEvent& lhe) {
Particles finalstates = FinalStates(lhe);
auto pos = std::remove_if(finalstates.begin(), finalstates.end(),
[&] (const Particle& p) {
return !IsInMotherLine(pline, p, lhe);
});
finalstates.erase(pos, finalstates.end());
return finalstates;
}
} // namespace lhef
<|endoftext|> |
<commit_before>#ifndef _ctoolhu_typesafe_id_included_
#define _ctoolhu_typesafe_id_included_
#include <iosfwd>
namespace Ctoolhu {
namespace TypeSafe {
//stores a value (id) and exposes some typical operations usually performed on ids
template <typename IdType>
class Storage {
typedef Storage<IdType> self_type;
public:
bool operator ==(const self_type &comp) const
{
return _id == comp._id;
}
bool operator !=(const self_type &comp) const
{
return _id != comp._id;
}
bool operator <(const self_type &comp) const
{
return _id < comp._id;
}
bool operator >(const self_type &comp) const
{
return _id > comp._id;
}
bool operator <=(const self_type &comp) const
{
return _id <= comp._id;
}
bool operator >=(const self_type &comp) const
{
return _id >= comp._id;
}
friend std::ostream &operator <<(std::ostream &out, const self_type &storage)
{
out << storage._id;
return out;
}
protected:
Storage() = default;
IdType _id;
};
//policy defining that the conversion to stored id type is implicit
template <typename IdType>
class ImplicitConversion : public Storage<IdType> {
public:
operator IdType() const
{
return _id;
}
protected:
ImplicitConversion() = default;
};
//policy defining that the conversion to stored id type is explicit so that it cannot be mistakenly juxtaposed for the underlying type
template <typename IdType>
class ExplicitConversion : public Storage<IdType> {
public:
explicit operator IdType() const
{
return _id;
}
protected:
ExplicitConversion() = default;
};
//Tool for preventing mix-up of ids of different objects by means of
//distinguishing their id types and disallowing conversion between them.
//The conversions to the underlying type are based on the chosen policy.
//
//e.g. for lesson ID use (inside class Lesson)
//
// Id<Lesson> _id;
//
//instead of
//
// int _id;
//
template <
class RequestingObject, //type of the object which will have this id
typename IdType = int, //type of the id that would normally be used
template <typename> class ConversionPolicy = ImplicitConversion
>
class Id : public ConversionPolicy<IdType> {
public:
typedef RequestingObject object_type;
typedef IdType id_type;
explicit Id(IdType id)
#ifdef _DEBUG
: _val(_id)
#endif
{
_id = id;
}
#ifdef _DEBUG
Id(const Id &src)
: _val(_id)
{
_id = src._id;
}
Id &operator =(const Id &src)
{
_id = src._id;
return *this;
}
private:
const IdType &_val; //so that we can see the value readily in watch window of the debugger
#endif
};
} //ns TypeSafe
} //ns Ctoolhu
#endif //file guard
<commit_msg>simplified operator << (no change in semantics)<commit_after>#ifndef _ctoolhu_typesafe_id_included_
#define _ctoolhu_typesafe_id_included_
#include <iosfwd>
namespace Ctoolhu {
namespace TypeSafe {
//stores a value (id) and exposes some typical operations usually performed on ids
template <typename IdType>
class Storage {
typedef Storage<IdType> self_type;
public:
bool operator ==(const self_type &comp) const
{
return _id == comp._id;
}
bool operator !=(const self_type &comp) const
{
return _id != comp._id;
}
bool operator <(const self_type &comp) const
{
return _id < comp._id;
}
bool operator >(const self_type &comp) const
{
return _id > comp._id;
}
bool operator <=(const self_type &comp) const
{
return _id <= comp._id;
}
bool operator >=(const self_type &comp) const
{
return _id >= comp._id;
}
friend std::ostream &operator <<(std::ostream &out, const self_type &storage)
{
return out << storage._id;
}
protected:
Storage() = default;
IdType _id;
};
//policy defining that the conversion to stored id type is implicit
template <typename IdType>
class ImplicitConversion : public Storage<IdType> {
public:
operator IdType() const
{
return _id;
}
protected:
ImplicitConversion() = default;
};
//policy defining that the conversion to stored id type is explicit so that it cannot be mistakenly juxtaposed for the underlying type
template <typename IdType>
class ExplicitConversion : public Storage<IdType> {
public:
explicit operator IdType() const
{
return _id;
}
protected:
ExplicitConversion() = default;
};
//Tool for preventing mix-up of ids of different objects by means of
//distinguishing their id types and disallowing conversion between them.
//The conversions to the underlying type are based on the chosen policy.
//
//e.g. for lesson ID use (inside class Lesson)
//
// Id<Lesson> _id;
//
//instead of
//
// int _id;
//
template <
class RequestingObject, //type of the object which will have this id
typename IdType = int, //type of the id that would normally be used
template <typename> class ConversionPolicy = ImplicitConversion
>
class Id : public ConversionPolicy<IdType> {
public:
typedef RequestingObject object_type;
typedef IdType id_type;
explicit Id(IdType id)
#ifdef _DEBUG
: _val(_id)
#endif
{
_id = id;
}
#ifdef _DEBUG
Id(const Id &src)
: _val(_id)
{
_id = src._id;
}
Id &operator =(const Id &src)
{
_id = src._id;
return *this;
}
private:
const IdType &_val; //so that we can see the value readily in watch window of the debugger
#endif
};
} //ns TypeSafe
} //ns Ctoolhu
#endif //file guard
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/io/file_class.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include <boost/scoped_array.hpp>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace flusspferd;
using namespace flusspferd::io;
class file_class::impl {
public:
std::fstream stream;
static void create(char const *name, boost::optional<int> mode);
};
file_class::file_class(object const &obj, call_context &x)
: stream_base(obj, 0), p(new impl)
{
set_streambuf(p->stream.rdbuf());
if (!x.arg.empty()) {
string name = x.arg[0].to_string();
open(name.c_str());
}
register_native_method("open", &file_class::open);
register_native_method("close", &file_class::close);
}
file_class::~file_class()
{}
void file_class::class_info::augment_constructor(object constructor) {
create_native_function(constructor, "create", &impl::create);
}
object file_class::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object(flusspferd::get_prototype<stream_base>());
create_native_method(proto, "open", 1);
create_native_method(proto, "close", 0);
return proto;
}
void file_class::open(char const *name) {
security &sec = security::get();
if (!sec.check_path(name, security::READ_WRITE))
throw exception("Could not open file (security)");
p->stream.open(name);
if (!p->stream)
throw exception("Could not open file");
}
void file_class::close() {
p->stream.close();
}
void file_class::impl::create(char const *name, boost::optional<int> mode) {
security &sec = security::get();
if (!sec.check_path(name, security::CREATE))
throw exception("Could not create file (security)");
if (creat(name, mode.get_value_or(0666)) < 0)
throw exception("Could not create file");
}
<commit_msg>IO/File: Add exists constructor method<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld, Ash Berlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/io/file_class.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include <boost/scoped_array.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace flusspferd;
using namespace flusspferd::io;
class file_class::impl {
public:
std::fstream stream;
static void create(char const *name, boost::optional<int> mode);
static bool exists(char const *name);
};
file_class::file_class(object const &obj, call_context &x)
: stream_base(obj, 0), p(new impl)
{
set_streambuf(p->stream.rdbuf());
if (!x.arg.empty()) {
string name = x.arg[0].to_string();
open(name.c_str());
}
register_native_method("open", &file_class::open);
register_native_method("close", &file_class::close);
}
file_class::~file_class()
{}
void file_class::class_info::augment_constructor(object constructor) {
create_native_function(constructor, "create", &impl::create);
create_native_function(constructor, "exists", &impl::exists);
}
object file_class::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object(flusspferd::get_prototype<stream_base>());
create_native_method(proto, "open", 1);
create_native_method(proto, "close", 0);
create_native_method(proto, "exists", 0);
return proto;
}
void file_class::open(char const *name) {
security &sec = security::get();
if (!sec.check_path(name, security::READ_WRITE))
throw exception("Could not open file (security)");
p->stream.open(name);
define_property("fileName", string(name),
permanent_property | read_only_property );
if (!p->stream)
// TODO: Include some sort of system error message here
throw exception("Could not open file");
}
void file_class::close() {
p->stream.close();
delete_property("fileName");
}
void file_class::impl::create(char const *name, boost::optional<int> mode) {
security &sec = security::get();
if (!sec.check_path(name, security::CREATE))
throw exception("Could not create file (security)");
if (creat(name, mode.get_value_or(0666)) < 0)
throw exception("Could not create file");
}
bool file_class::impl::exists(char const *name) {
return boost::filesystem::exists(name);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include "stream_iterator.hpp"
#include "templateio.hpp"
#include "profile.hpp"
using namespace std;
//============================================================================
// Logic Language Parser.
//----------------------------------------------------------------------------
// Syntactic Structure.
using name_t = set<string>::const_iterator;
struct type_expression {
virtual ostream& operator<< (ostream& out) const = 0;
};
struct type_variable : public type_expression {
name_t const name;
type_variable(name_t n) : name(n) {}
virtual ostream& operator<< (ostream& out) const override {
out << *name;
return out;
}
};
struct type_struct : public type_expression {
name_t const name;
vector<type_expression*> const args;
template <typename As>
type_struct(name_t n, As&& as) : name(n), args(forward<As>(as)) {}
ostream& operator<< (ostream& out) const override {
out << *name << "(";
for (auto i = args.cbegin(); i != args.cend(); ++i) {
(*i)->operator<<(out);
auto j = i;
if (++j != args.end()) {
out << ", ";
}
}
out << ")";
return out;
}
};
ostream& operator<< (ostream& out, type_expression* exp) {
exp->operator<<(out);
return out;
}
struct clause {
type_struct* const head;
vector<type_struct*> const impl;
set<type_variable*> const reps;
template <typename Is, typename Rs>
clause(type_struct* h, Is&& is, Rs&& rs) : head(h), impl(forward<Is>(is)),
reps(forward<Rs>(rs)) {}
};
ostream& operator<< (ostream& out, clause* cls) {
cls->head->operator<<(out);
auto f = cls->impl.cbegin();
auto const l = cls->impl.cend();
if (f != l) {
out << " :-" << endl;
for (auto i = f; i != l; ++i) {
out << "\t";
(*i)->operator<<(out);
auto j = i;
if (++j != l) {
out << "," << endl;
}
}
}
out << ".";
auto g = cls->reps.cbegin();
auto const m = cls->reps.cend();
if (g != m) {
out << " [";
for (auto i = g; i != m; ++i) {
(*i)->operator<<(out);
auto j = i;
if (++j != m) {
out << ", ";
}
}
out << "]";
}
out << endl;
return out;
}
//----------------------------------------------------------------------------
// Parser State
using var_t = map<string const*, type_variable*>::const_iterator;
struct parser_state {
set<string> names; // global name table
map<string const*, type_variable*> variables;
set<type_variable*> repeated;
set<type_variable*> repeated_in_goal;
parser_state() {};
parser_state(parser_state const&) = delete;
parser_state& operator= (parser_state const&) = delete;
name_t get_name(string const& name) {
name_t const n = names.find(name);
if (n == names.end()) {
return names.insert(name).first;
} else {
return n;
}
}
};
//----------------------------------------------------------------------------
// Grammar
class return_variable {
public:
return_variable() {}
void operator() (type_variable** res, string const& name, parser_state* st) const {
name_t const n = st->get_name(name);
var_t i = st->variables.find(&(*n));
if (i == st->variables.end()) {
type_variable* const var = new type_variable(n);
st->variables.insert(make_pair(&(*n), var));
*res = var;
} else {
st->repeated.insert(i->second);
*res = i->second;
}
}
} const return_variable;
struct return_args {
return_args() {}
void operator() (vector<type_expression*>* res, int n, type_variable* var, type_struct* str, parser_state*) const {
switch(n) {
case 0:
res->push_back(var);
break;
case 1:
res->push_back(str);
break;
}
}
} const return_args;
struct return_struct {
return_struct() {}
void operator() (type_struct** res, string const& name, vector<type_expression*>& args, parser_state* st) const {
name_t n = st->get_name(name);
*res = new type_struct(n, args);
}
} const return_struct;
struct return_goal {
return_goal() {}
void operator() (type_struct** res, type_struct* str, parser_state* st) const {
*res = str;
st->repeated_in_goal = st->repeated;
}
} const return_goal;
struct return_impl {
return_impl() {}
void operator() (vector<type_struct*>* res, type_struct* impl, parser_state*) const {
res->push_back(impl);
}
} const return_impl;
struct return_clause {
return_clause() {}
void operator() (vector<clause*>* res, type_struct* head, vector<type_struct*>& impl, parser_state* st) const {
res->push_back(new clause(head, impl, st->repeated_in_goal));
st->variables.clear();
st->repeated.clear();
st->repeated_in_goal.clear();
}
} const return_clause;
struct return_clause2 {
return_clause2() {}
void operator() (vector<clause*>* res, vector<type_struct*>& impl, parser_state* st) const {
vector<type_expression*> vars;
for (auto v : st->variables) {
vars.push_back(v.second);
}
res->push_back(new clause(
new type_struct(st->get_name("goal"), vars), impl, set<type_variable*> {}
));
st->variables.clear();
st->repeated.clear();
st->repeated_in_goal.clear();
}
} const return_clause2;
//----------------------------------------------------------------------------
// Parser
using expression_handle = pstream_handle<string, parser_state>;
auto const atom_tok = tokenise(some(accept(is_lower)) && many(accept(is_alnum || is_char('_'))));
auto const var_tok = tokenise(some(accept(is_upper || is_char('_'))) && many(accept(is_alnum)));
auto const open_tok = tokenise(accept(is_char('(')));
auto const close_tok = tokenise(accept(is_char(')')));
auto const sep_tok = tokenise(accept(is_char(',')));
auto const impl_tok = tokenise(accept_str(":-"));
auto const end_tok = tokenise(accept(is_char('.')));
auto const comment_tok = tokenise(accept(is_char('#')) && many(accept(is_print)) && accept(is_char('\n')));
pstream_handle<type_struct*, parser_state> const structure(pstream_handle<type_struct*, parser_state> const s) {
return all(return_struct, atom_tok,
option(discard(open_tok)
&& sep_by(any(return_args, all(return_variable, var_tok), s), discard(sep_tok))
&& discard(close_tok)));
}
pstream_handle<type_struct*, parser_state> const goal = structure(reference("structure", goal));
auto const clause = all(return_clause, all(return_goal, goal),
option(discard(impl_tok) && sep_by(all(return_impl, goal), discard(sep_tok))) && discard(end_tok))
|| discard(impl_tok) && all(return_clause2, sep_by(all(return_impl, goal), discard(sep_tok)) && discard(end_tok))
|| discard(comment_tok);
struct expression_parser;
template <typename Range>
int parse(Range const &r) {
auto const parser = first_token && some(clause);
decltype(parser)::result_type a {};
typename Range::iterator i = r.first;
parser_state st;
profile<expression_parser> p;
if (parser(i, r, &a, &st)) {
cout << "OK" << endl;
} else {
cout << "FAIL" << endl;
}
cout << a << endl;
return i - r.first;
}
//----------------------------------------------------------------------------
int main(int const argc, char const *argv[]) {
if (argc < 1) {
cerr << "no input files" << endl;
} else {
for (int i = 1; i < argc; ++i) {
profile<expression_parser>::reset();
stream_range in(argv[i]);
cout << argv[i] << endl;
int const chars_read = parse(in);
double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<expression_parser>::report());
cout << "parsed: " << mb_per_s << "MB/s" << endl;
}
}
}
<commit_msg>tidy and rename some objects<commit_after>#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include "stream_iterator.hpp"
#include "templateio.hpp"
#include "profile.hpp"
using namespace std;
//============================================================================
// Logic Language Parser.
//----------------------------------------------------------------------------
// Syntactic Structure.
using name_t = set<string>::const_iterator;
struct type_expression {
virtual ostream& operator<< (ostream& out) const = 0;
};
struct type_variable : public type_expression {
name_t const name;
type_variable(name_t n) : name(n) {}
virtual ostream& operator<< (ostream& out) const override {
out << *name;
return out;
}
};
struct type_struct : public type_expression {
name_t const name;
vector<type_expression*> const args;
template <typename As>
type_struct(name_t n, As&& as) : name(n), args(forward<As>(as)) {}
ostream& operator<< (ostream& out) const override {
out << *name << "(";
for (auto i = args.cbegin(); i != args.cend(); ++i) {
(*i)->operator<<(out);
auto j = i;
if (++j != args.end()) {
out << ", ";
}
}
out << ")";
return out;
}
};
ostream& operator<< (ostream& out, type_expression* exp) {
exp->operator<<(out);
return out;
}
struct clause {
type_struct* const head;
vector<type_struct*> const impl;
set<type_variable*> const reps;
template <typename Is, typename Rs>
clause(type_struct* h, Is&& is, Rs&& rs) : head(h), impl(forward<Is>(is)),
reps(forward<Rs>(rs)) {}
};
ostream& operator<< (ostream& out, clause* cls) {
cls->head->operator<<(out);
auto f = cls->impl.cbegin();
auto const l = cls->impl.cend();
if (f != l) {
out << " :-" << endl;
for (auto i = f; i != l; ++i) {
out << "\t";
(*i)->operator<<(out);
auto j = i;
if (++j != l) {
out << "," << endl;
}
}
}
out << ".";
auto g = cls->reps.cbegin();
auto const m = cls->reps.cend();
if (g != m) {
out << " [";
for (auto i = g; i != m; ++i) {
(*i)->operator<<(out);
auto j = i;
if (++j != m) {
out << ", ";
}
}
out << "]";
}
out << endl;
return out;
}
//----------------------------------------------------------------------------
// Parser State
using var_t = map<string const*, type_variable*>::const_iterator;
struct parser_state {
set<string> names; // global name table
map<string const*, type_variable*> variables;
set<type_variable*> repeated;
set<type_variable*> repeated_in_goal;
parser_state() {};
parser_state(parser_state const&) = delete;
parser_state& operator= (parser_state const&) = delete;
name_t get_name(string const& name) {
name_t const n = names.find(name);
if (n == names.end()) {
return names.insert(name).first;
} else {
return n;
}
}
};
//----------------------------------------------------------------------------
// Grammar
struct return_variable {
return_variable() {}
void operator() (type_variable** res, string const& name, parser_state* st) const {
name_t const n = st->get_name(name);
var_t i = st->variables.find(&(*n));
if (i == st->variables.end()) {
type_variable* const var = new type_variable(n);
st->variables.insert(make_pair(&(*n), var));
*res = var;
} else {
st->repeated.insert(i->second);
*res = i->second;
}
}
} const return_variable;
struct return_args {
return_args() {}
void operator() (vector<type_expression*>* res, int n, type_variable* var, type_struct* str, parser_state*) const {
switch(n) {
case 0:
res->push_back(var);
break;
case 1:
res->push_back(str);
break;
}
}
} const return_args;
struct return_struct {
return_struct() {}
void operator() (type_struct** res, string const& name, vector<type_expression*>& args, parser_state* st) const {
name_t n = st->get_name(name);
*res = new type_struct(n, args);
}
} const return_struct;
struct return_head {
return_head() {}
void operator() (type_struct** res, type_struct* str, parser_state* st) const {
*res = str;
st->repeated_in_goal = st->repeated;
}
} const return_head;
struct return_goal {
return_goal() {}
void operator() (vector<type_struct*>* res, type_struct* impl, parser_state*) const {
res->push_back(impl);
}
} const return_goal;
struct return_clause {
return_clause() {}
void operator() (vector<clause*>* res, type_struct* head, vector<type_struct*>& impl, parser_state* st) const {
res->push_back(new clause(head, impl, st->repeated_in_goal));
st->variables.clear();
st->repeated.clear();
st->repeated_in_goal.clear();
}
} const return_clause;
struct return_goals {
return_goals() {}
void operator() (vector<clause*>* res, vector<type_struct*>& impl, parser_state* st) const {
vector<type_expression*> vars;
for (auto v : st->variables) {
vars.push_back(v.second);
}
res->push_back(new clause(
new type_struct(st->get_name("goal"), vars), impl, set<type_variable*> {}
));
st->variables.clear();
st->repeated.clear();
st->repeated_in_goal.clear();
}
} const return_goals;
//----------------------------------------------------------------------------
// Parser
using expression_handle = pstream_handle<string, parser_state>;
auto const atom_tok = tokenise(some(accept(is_lower)) && many(accept(is_alnum || is_char('_'))));
auto const var_tok = tokenise(some(accept(is_upper || is_char('_'))) && many(accept(is_alnum)));
auto const open_tok = tokenise(accept(is_char('(')));
auto const close_tok = tokenise(accept(is_char(')')));
auto const sep_tok = tokenise(accept(is_char(',')));
auto const impl_tok = tokenise(accept_str(":-"));
auto const end_tok = tokenise(accept(is_char('.')));
auto const comment_tok = tokenise(accept(is_char('#')) && many(accept(is_print)) && accept(is_char('\n')));
pstream_handle<type_struct*, parser_state> const structure(pstream_handle<type_struct*, parser_state> const s) {
return all(return_struct, atom_tok,
option(discard(open_tok)
&& sep_by(any(return_args, all(return_variable, var_tok), s), discard(sep_tok))
&& discard(close_tok)));
}
pstream_handle<type_struct*, parser_state> const goal = structure(reference("structure", goal));
auto const clause = all(return_clause, all(return_head, goal),
option(discard(impl_tok) && sep_by(all(return_goal, goal), discard(sep_tok))) && discard(end_tok))
|| discard(impl_tok) && all(return_goals, sep_by(all(return_goal, goal), discard(sep_tok)) && discard(end_tok))
|| discard(comment_tok);
struct expression_parser;
template <typename Range>
int parse(Range const &r) {
auto const parser = first_token && some(clause);
decltype(parser)::result_type a {};
typename Range::iterator i = r.first;
parser_state st;
profile<expression_parser> p;
if (parser(i, r, &a, &st)) {
cout << "OK" << endl;
} else {
cout << "FAIL" << endl;
}
cout << a << endl;
return i - r.first;
}
//----------------------------------------------------------------------------
int main(int const argc, char const *argv[]) {
if (argc < 1) {
cerr << "no input files" << endl;
} else {
for (int i = 1; i < argc; ++i) {
profile<expression_parser>::reset();
stream_range in(argv[i]);
cout << argv[i] << endl;
int const chars_read = parse(in);
double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<expression_parser>::report());
cout << "parsed: " << mb_per_s << "MB/s" << endl;
}
}
}
<|endoftext|> |
<commit_before>#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <uv.h>
#include "log.h"
using std::cerr;
using std::cout;
using std::dec;
using std::endl;
using std::ofstream;
using std::ostream;
using std::ostringstream;
using std::setw;
using std::strerror;
using std::string;
using std::to_string;
using std::chrono::steady_clock;
class NullLogger : public Logger
{
public:
NullLogger() = default;
Logger *prefix(const char * /*file*/, int /*line*/) override { return this; }
ostream &stream() override { return unopened; }
private:
ofstream unopened;
};
class FileLogger : public Logger
{
public:
FileLogger(const char *filename) : log_stream{filename, std::ios::out | std::ios::app}
{
if (!log_stream) {
int stream_errno = errno;
ostringstream msg;
msg << "Unable to log to " << filename << ": " << strerror(stream_errno);
err = msg.str();
}
FileLogger::prefix(__FILE__, __LINE__);
log_stream << "FileLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
log_stream << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return log_stream; }
string get_error() const override { return err; }
private:
ofstream log_stream;
string err;
};
class StderrLogger : public Logger
{
public:
StderrLogger()
{
StderrLogger::prefix(__FILE__, __LINE__);
cerr << "StderrLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cerr << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cerr; }
string get_error() const override
{
if (!cerr) {
return "Unable to log to stderr";
}
return "";
}
};
class StdoutLogger : public Logger
{
public:
StdoutLogger()
{
StdoutLogger::prefix(__FILE__, __LINE__);
cout << "StdoutLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cout << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cout; }
string get_error() const override
{
if (!cout) {
return "Unable to log to stdout";
}
return "";
}
};
static uv_key_t current_logger_key;
static NullLogger the_null_logger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger *Logger::current()
{
uv_once(&make_key_once, &make_key);
auto *logger = static_cast<Logger *>(uv_key_get(¤t_logger_key));
if (logger == nullptr) {
uv_key_set(¤t_logger_key, static_cast<void *>(&the_null_logger));
logger = &the_null_logger;
}
return logger;
}
string replace_logger(const Logger *new_logger)
{
if (new_logger != &the_null_logger) {
string r = new_logger->get_error();
if (!r.empty()) {
delete new_logger;
}
return r;
}
Logger *prior = Logger::current();
if (prior != &the_null_logger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void *) new_logger);
return "";
}
string Logger::to_file(const char *filename)
{
return replace_logger(new FileLogger(filename));
}
string Logger::to_stderr()
{
return replace_logger(new StderrLogger());
}
string Logger::to_stdout()
{
return replace_logger(new StdoutLogger());
}
string Logger::disable()
{
return replace_logger(&the_null_logger);
}
string Logger::from_env(const char *varname)
{
const char *value = std::getenv(varname);
if (value == nullptr) {
return replace_logger(&the_null_logger);
}
if (std::strcmp("stdout", value) == 0) {
return to_stdout();
}
if (std::strcmp("stderr", value) == 0) {
return to_stderr();
}
return to_file(value);
}
string plural(long quantity, const string &singular_form, const string &plural_form)
{
string result;
result += to_string(quantity);
result += " ";
if (quantity == 1) {
result += singular_form;
} else {
result += plural_form;
}
return result;
}
string plural(long quantity, const string &singular_form)
{
string plural_form(singular_form + "s");
return plural(quantity, singular_form, plural_form);
}
Timer::Timer() : start{steady_clock::now()}, duration{0}
{
//
}
void Timer::stop()
{
duration = measure_duration();
}
string Timer::format_duration() const
{
size_t total = duration;
if (total == 0) {
total = measure_duration();
}
size_t milliseconds = total;
size_t seconds = milliseconds / 1000;
milliseconds -= (seconds * 1000);
size_t minutes = seconds / 60;
seconds -= (minutes * 60);
size_t hours = minutes / 60;
minutes -= (hours * 60);
ostringstream out;
if (hours > 0) out << plural(hours, "hour") << ' ';
if (minutes > 0) out << plural(minutes, "minute") << ' ';
if (seconds > 0) out << plural(seconds, "second") << ' ';
out << plural(milliseconds, "millisecond") << " (" << total << "ms)";
return out.str();
}
<commit_msg>Shhhh, linter<commit_after>#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <uv.h>
#include "log.h"
using std::cerr;
using std::cout;
using std::dec;
using std::endl;
using std::ofstream;
using std::ostream;
using std::ostringstream;
using std::setw;
using std::strerror;
using std::string;
using std::to_string;
using std::chrono::steady_clock;
class NullLogger : public Logger
{
public:
NullLogger() = default;
Logger *prefix(const char * /*file*/, int /*line*/) override { return this; }
ostream &stream() override { return unopened; }
private:
ofstream unopened;
};
class FileLogger : public Logger
{
public:
FileLogger(const char *filename) : log_stream{filename, std::ios::out | std::ios::app}
{
if (!log_stream) {
int stream_errno = errno;
ostringstream msg;
msg << "Unable to log to " << filename << ": " << strerror(stream_errno);
err = msg.str();
}
FileLogger::prefix(__FILE__, __LINE__);
log_stream << "FileLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
log_stream << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return log_stream; }
string get_error() const override { return err; }
private:
ofstream log_stream;
string err;
};
class StderrLogger : public Logger
{
public:
StderrLogger()
{
StderrLogger::prefix(__FILE__, __LINE__);
cerr << "StderrLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cerr << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cerr; }
string get_error() const override
{
if (!cerr) {
return "Unable to log to stderr";
}
return "";
}
};
class StdoutLogger : public Logger
{
public:
StdoutLogger()
{
StdoutLogger::prefix(__FILE__, __LINE__);
cout << "StdoutLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cout << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cout; }
string get_error() const override
{
if (!cout) {
return "Unable to log to stdout";
}
return "";
}
};
static uv_key_t current_logger_key;
static NullLogger the_null_logger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger *Logger::current()
{
uv_once(&make_key_once, &make_key);
auto *logger = static_cast<Logger *>(uv_key_get(¤t_logger_key));
if (logger == nullptr) {
uv_key_set(¤t_logger_key, static_cast<void *>(&the_null_logger));
logger = &the_null_logger;
}
return logger;
}
string replace_logger(const Logger *new_logger)
{
if (new_logger != &the_null_logger) {
string r = new_logger->get_error();
if (!r.empty()) {
delete new_logger;
}
return r;
}
Logger *prior = Logger::current();
if (prior != &the_null_logger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void *) new_logger);
return "";
}
string Logger::to_file(const char *filename)
{
return replace_logger(new FileLogger(filename)); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
}
string Logger::to_stderr()
{
return replace_logger(new StderrLogger()); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
}
string Logger::to_stdout()
{
return replace_logger(new StdoutLogger()); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
}
string Logger::disable()
{
return replace_logger(&the_null_logger);
}
string Logger::from_env(const char *varname)
{
const char *value = std::getenv(varname);
if (value == nullptr) {
return replace_logger(&the_null_logger);
}
if (std::strcmp("stdout", value) == 0) {
return to_stdout();
}
if (std::strcmp("stderr", value) == 0) {
return to_stderr();
}
return to_file(value);
}
string plural(long quantity, const string &singular_form, const string &plural_form)
{
string result;
result += to_string(quantity);
result += " ";
if (quantity == 1) {
result += singular_form;
} else {
result += plural_form;
}
return result;
}
string plural(long quantity, const string &singular_form)
{
string plural_form(singular_form + "s");
return plural(quantity, singular_form, plural_form);
}
Timer::Timer() : start{steady_clock::now()}, duration{0}
{
//
}
void Timer::stop()
{
duration = measure_duration();
}
string Timer::format_duration() const
{
size_t total = duration;
if (total == 0) {
total = measure_duration();
}
size_t milliseconds = total;
size_t seconds = milliseconds / 1000;
milliseconds -= (seconds * 1000);
size_t minutes = seconds / 60;
seconds -= (minutes * 60);
size_t hours = minutes / 60;
minutes -= (hours * 60);
ostringstream out;
if (hours > 0) out << plural(hours, "hour") << ' ';
if (minutes > 0) out << plural(minutes, "minute") << ' ';
if (seconds > 0) out << plural(seconds, "second") << ' ';
out << plural(milliseconds, "millisecond") << " (" << total << "ms)";
return out.str();
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2016 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Python/PythonInterfaceParser.h>
#include <Modules/Python/InterfaceWithPython.h>
#include <Core/Logging/Log.h>
// ReSharper disable once CppUnusedIncludeDirective
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
using namespace SCIRun::Modules::Python;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;
PythonInterfaceParser::PythonInterfaceParser(const std::string& moduleId,
const ModuleStateHandle& state,
const std::vector<std::string>& portIds)
: moduleId_(moduleId), state_(state), portIds_(portIds)
{
}
std::string PythonInterfaceParser::convertOutputSyntax(const std::string& line) const
{
auto outputVarsToCheck = InterfaceWithPython::outputNameParameters();
for (const auto& var : outputVarsToCheck)
{
auto varName = state_->getValue(var).toString();
auto regexString = "(\\h*)" + varName + " = (.+)";
//std::cout << "REGEX STRING " << regexString << std::endl;
boost::regex outputRegex(regexString);
boost::smatch what;
if (regex_match(line, what, outputRegex))
{
int rhsIndex = what.size() > 2 ? 2 : 1;
auto whitespace = what.size() > 2 ? boost::lexical_cast<std::string>(what[1]) : "";
auto rhs = boost::lexical_cast<std::string>(what[rhsIndex]);
auto converted = whitespace + "scirun_set_module_transient_state(\"" +
moduleId_ + "\",\"" + varName + "\"," + rhs + ")";
//std::cout << "CONVERTED TO " << converted << std::endl;
return converted;
}
}
return line;
}
std::string PythonInterfaceParser::convertInputSyntax(const std::string& line) const
{
for (const auto& portId : portIds_)
{
auto inputName = state_->getValue(Name(portId)).toString();
//std::cout << "FOUND INPUT VARIABLE NAME: " << inputName << " for port " << portId << std::endl;
//std::cout << "NEED TO REPLACE " << inputName << " with\n\t" << "scirun_get_module_input_value(\"" << moduleId_ << "\", \"" << portId << "\")" << std::endl;
auto index = line.find(inputName);
if (index != std::string::npos)
{
auto codeCopy = line;
return codeCopy.replace(index, inputName.length(),
"scirun_get_module_input_value(\"" + moduleId_ + "\", \"" + portId + "\")");
}
}
return line;
}
std::string PythonInterfaceParser::convertStandardCodeBlock(const PythonCodeBlock& block) const
{
if (block.isMatlab)
throw std::invalid_argument("Cannot process matlab block");
std::ostringstream convertedCode;
std::vector<std::string> lines;
boost::split(lines, block.code, boost::is_any_of("\n"));
for (const auto& line : lines)
{
convertedCode << convertInputSyntax(convertOutputSyntax(line)) << "\n";
}
return convertedCode.str();
}
PythonCode PythonInterfaceParser::extractSpecialBlocks(const std::string& code) const
{
PythonCode blocks;
static boost::regex matlabBlock("(.*)%%\\n(.*)\\n%%(.*)");
boost::smatch what;
if (regex_match(code, what, matlabBlock))
{
auto firstPart = std::string(what[1]);
boost::trim(firstPart);
auto matlabPart = std::string(what[2]);
boost::trim(matlabPart);
auto secondPart = std::string(what[3]);
boost::trim(secondPart);
parsePart(blocks, firstPart);
if (!matlabPart.empty())
blocks.push_back({matlabPart, true});
parsePart(blocks, secondPart);
}
else
{
return {{code, false}};
}
return blocks;
}
void PythonInterfaceParser::parsePart(PythonCode& blocks, const std::string& part) const
{
if (!part.empty())
{
if (part.find("%%") != std::string::npos)
{
auto rec = extractSpecialBlocks(part);
blocks.insert(blocks.begin(), rec.begin(), rec.end());
}
else
blocks.push_back({part, false});
}
}
PythonCodeBlock PythonInterfaceParser::concatenateNormalBlocks(const PythonCode& codeList) const
{
std::ostringstream ostr;
for (const auto& block : codeList)
{
if (!block.isMatlab)
{
ostr << block.code << '\n';
}
}
return {ostr.str(), false };
}
<commit_msg>Refactor<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2016 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Python/PythonInterfaceParser.h>
#include <Modules/Python/InterfaceWithPython.h>
#include <Core/Logging/Log.h>
// ReSharper disable once CppUnusedIncludeDirective
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
using namespace SCIRun::Modules::Python;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;
PythonInterfaceParser::PythonInterfaceParser(const std::string& moduleId,
const ModuleStateHandle& state,
const std::vector<std::string>& portIds)
: moduleId_(moduleId), state_(state), portIds_(portIds)
{
}
std::string PythonInterfaceParser::convertOutputSyntax(const std::string& line) const
{
auto outputVarsToCheck = InterfaceWithPython::outputNameParameters();
for (const auto& var : outputVarsToCheck)
{
auto varName = state_->getValue(var).toString();
auto regexString = "(\\h*)" + varName + " = (.+)";
//std::cout << "REGEX STRING " << regexString << std::endl;
boost::regex outputRegex(regexString);
boost::smatch what;
if (regex_match(line, what, outputRegex))
{
int rhsIndex = what.size() > 2 ? 2 : 1;
auto whitespace = what.size() > 2 ? boost::lexical_cast<std::string>(what[1]) : "";
auto rhs = boost::lexical_cast<std::string>(what[rhsIndex]);
auto converted = whitespace + "scirun_set_module_transient_state(\"" +
moduleId_ + "\",\"" + varName + "\"," + rhs + ")";
//std::cout << "CONVERTED TO " << converted << std::endl;
return converted;
}
}
return line;
}
std::string PythonInterfaceParser::convertInputSyntax(const std::string& line) const
{
for (const auto& portId : portIds_)
{
auto inputName = state_->getValue(Name(portId)).toString();
//std::cout << "FOUND INPUT VARIABLE NAME: " << inputName << " for port " << portId << std::endl;
//std::cout << "NEED TO REPLACE " << inputName << " with\n\t" << "scirun_get_module_input_value(\"" << moduleId_ << "\", \"" << portId << "\")" << std::endl;
auto index = line.find(inputName);
if (index != std::string::npos)
{
auto codeCopy = line;
return codeCopy.replace(index, inputName.length(),
"scirun_get_module_input_value(\"" + moduleId_ + "\", \"" + portId + "\")");
}
}
return line;
}
std::string PythonInterfaceParser::convertStandardCodeBlock(const PythonCodeBlock& block) const
{
if (block.isMatlab)
throw std::invalid_argument("Cannot process matlab block");
std::ostringstream convertedCode;
std::vector<std::string> lines;
boost::split(lines, block.code, boost::is_any_of("\n"));
for (const auto& line : lines)
{
convertedCode << convertInputSyntax(convertOutputSyntax(line)) << "\n";
}
return convertedCode.str();
}
PythonCode PythonInterfaceParser::extractSpecialBlocks(const std::string& code) const
{
PythonCode blocks;
static std::string matlabBlockRegex = std::string("(.*)") + PythonCodeBlock::delimiter
+ "\\n(.*)\\n" + PythonCodeBlock::delimiter + "(.*)";
static boost::regex matlabBlock(matlabBlockRegex);
boost::smatch what;
if (regex_match(code, what, matlabBlock))
{
auto firstPart = std::string(what[1]);
boost::trim(firstPart);
auto matlabPart = std::string(what[2]);
boost::trim(matlabPart);
auto secondPart = std::string(what[3]);
boost::trim(secondPart);
parsePart(blocks, firstPart);
if (!matlabPart.empty())
blocks.push_back({matlabPart, true});
parsePart(blocks, secondPart);
}
else
{
return {{code, false}};
}
return blocks;
}
void PythonInterfaceParser::parsePart(PythonCode& blocks, const std::string& part) const
{
if (!part.empty())
{
if (part.find(PythonCodeBlock::delimiter) != std::string::npos)
{
auto rec = extractSpecialBlocks(part);
blocks.insert(blocks.begin(), rec.begin(), rec.end());
}
else
blocks.push_back({part, false});
}
}
PythonCodeBlock PythonInterfaceParser::concatenateNormalBlocks(const PythonCode& codeList) const
{
std::ostringstream ostr;
for (const auto& block : codeList)
{
if (!block.isMatlab)
{
ostr << block.code << '\n';
}
}
return {ostr.str(), false };
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
int main(){
char HOSTNAME[128];
gethostname(HOSTNAME, sizeof HOSTNAME);
bool REPEAT = true;
while (REPEAT){
string input;
cout << getlogin() << "@" << HOSTNAME << "$ ";
getline(cin, input);
cout << input << endl;
}
}
<commit_msg>hello<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main(){
char HOSTNAME[128];
gethostname(HOSTNAME, sizeof HOSTNAME);
bool REPEAT = true;
while (REPEAT){
string input;
cout << getlogin() << "@" << HOSTNAME << "$ ";
getline(cin, input);
if (input == "exit"){
REPEAT = false;
}
}
}
<|endoftext|> |
<commit_before>/*
* $File: main.cc
* $Date: Tue Dec 10 16:43:56 2013 +0800
* $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>
*/
#include <cstdio>
#include <fstream>
#include "gmm.hh"
#include "datamanip.hh"
#include "common.hh"
#include "tclap/CmdLine.h"
using namespace std;
using namespace TCLAP;
typedef std::vector<std::vector<real_t>> DenseDataset;
static void svm2vec(const std::vector<std::pair<int, real_t>> &input,
std::vector<real_t> &output, int dim) {
output = std::vector<real_t>(dim, 0);
for (auto &item: input) {
if (item.first > dim) // ignore out bounded values
continue;
output[item.first] = item.second;
}
}
vector<real_t> string_to_double_vector(string line) {
vector<real_t> x;
int begin = 0, end = 0;
int len = line.size();
while (true) {
while (end < len && line[end] != ' ' && line[end] != '\n')
end ++;
x.push_back(atof(line.substr(begin, end - begin).c_str()));
if (end == len - 1 || line[end] == '\n' || (end == len - 2 && line[end] == ' ' && line[end] == '\n'))
break;
begin = end + 1;
end = begin;
}
return x;
}
void Dataset2DenseDataset(Dataset &X0, DenseDataset &X1) {
int n, m;
get_data_metric(X0, n, m);
X1.resize(X0.size());
for (size_t i = 0; i < X0.size(); i ++)
svm2vec(X0[i], X1[i], m);
}
struct Args {
int concurrency;
int K;
string input_file;
string output_file;
};
Args parse_args(int argc, char *argv[]) {
Args args;
try {
CmdLine cmd("Gaussian Mixture Model (GMM)", ' ', "0.0.1");
ValueArg<int> arg_concurrency("w", "concurrency", "number of workers", false, 1, "NUMBER");
ValueArg<int> arg_K("k", "K", "number of gaussians", true, 10, "NUMBER");
ValueArg<string> arg_input_file("i", "input", "intput file", true, "", "FILE");
ValueArg<string> arg_output_file("o", "output", "intput file", true, "", "FILE");
cmd.add(arg_concurrency);
cmd.add(arg_K);
cmd.add(arg_input_file);
cmd.add(arg_output_file);
cmd.parse(argc, argv);
#define GET_VALUE(name) args.name = arg_##name.getValue();
GET_VALUE(concurrency);
GET_VALUE(K);
GET_VALUE(input_file);
GET_VALUE(output_file);
} catch (ArgException &e) {
cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
}
return args;
}
void read_dense_dataset(DenseDataset &X, const char *fname) {
ifstream fin(fname);
string line;
while (getline(fin, line)) {
X.push_back(string_to_double_vector(line));
}
}
void write_dense_dataset(DenseDataset &X, const char *fname) {
ofstream fout(fname);
for (auto &x: X) {
for (auto &v: x)
fout << v << ' ';
fout << endl;
}
}
void fill_gaussian(DenseDataset &X, Gaussian *gaussian, int nr_point) {
for (int i = 0; i < nr_point; i ++)
X.push_back(gaussian->sample());
}
static vector<real_t> random_vector(int dim, real_t range, Random &random) {
vector<real_t> vec(dim);
for (auto &v: vec) v = random.rand_real() * range;
return vec;
}
void gen_high_dim_gaussian_mixture(DenseDataset &X, int dim, int nr_gaussian, int nr_point_per_gaussian) {
Random random;
for (int i = 0; i < nr_gaussian; i ++) {
Gaussian g(dim);
g.mean = random_vector(dim, 1, random);
g.sigma = random_vector(dim, 0.05 + random.rand_real() * 0.1, random);
fill_gaussian(X, &g, nr_point_per_gaussian);
}
}
void gen_gaussian_mixture(DenseDataset &X, int nr_point_per_gaussian = 1000) {
int nr_gaussian = 3;
Gaussian g0(2);
g0.mean = {0, 0};
g0.sigma = {0.1, 0.1};
Gaussian g1(2);
g1.mean = {1, 1};
g1.sigma = {0.1, 0.1};
Gaussian g2(2);
g2.mean = {2, 1};
g2.sigma = {0.2, 0.2};
fill_gaussian(X, &g0, nr_point_per_gaussian);
fill_gaussian(X, &g1, nr_point_per_gaussian);
fill_gaussian(X, &g2, nr_point_per_gaussian);
}
int main(int argc, char *argv[]) {
srand(42); // Answer to The Ultimate Question of Life, the Universe, and Everything
// Args args = parse_args(argc, argv);
DenseDataset X;
// read_dense_dataset(X, "test.data");
gen_gaussian_mixture(X, 100);
// gen_high_dim_gaussian_mixture(X, 13, 10, 68000);
write_dense_dataset(X, "test.data");
int concurrency = 4;
int nr_mixture = 3;
GMMTrainerBaseline trainer(1, 1e-3, concurrency);
GMM gmm(nr_mixture, COVTYPE_DIAGONAL, &trainer);
printf("start training ...\n"); fflush(stdout);
gmm.fit(X);
ofstream fout("gmm-test.model");
gmm.dump(fout);
return 0;
}
/**
* vim: syntax=cpp11 foldmethod=marker
*/
<commit_msg>add commandline support<commit_after>/*
* $File: main.cc
* $Date: Tue Dec 10 18:20:51 2013 +0800
* $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>
*/
#include <cstdio>
#include <fstream>
#include "gmm.hh"
#include "datamanip.hh"
#include "common.hh"
#include "tclap/CmdLine.h"
using namespace std;
using namespace TCLAP;
typedef std::vector<std::vector<real_t>> DenseDataset;
vector<real_t> string_to_double_vector(string line) {
vector<real_t> x;
int begin = 0, end = 0;
int len = line.size();
while (true) {
while (end < len && line[end] != ' ' && line[end] != '\n')
end ++;
x.push_back(atof(line.substr(begin, end - begin).c_str()));
if (end == len - 1 || line[end] == '\n' || (end == len - 2 && line[end] == ' ' && line[end] == '\n'))
break;
begin = end + 1;
end = begin;
}
return x;
}
struct Args {
int concurrency;
int K;
int iteration;
real_t min_covar = 1e-3;
string input_file;
string model_file;
};
Args parse_args(int argc, char *argv[]) {
Args args;
try {
CmdLine cmd("Gaussian Mixture Model (GMM)", ' ', "0.0.1");
ValueArg<int> arg_concurrency("w", "concurrency", "number of workers", false, 1, "NUMBER");
ValueArg<int> arg_K("k", "K", "number of gaussians", true, 10, "NUMBER");
ValueArg<double> arg_min_covar("c", "mincovar", "minimum covariance to avoid overfitting, default 1e-3.", false, 1e-3, "FLOAT");
ValueArg<string> arg_input_file("i", "input", "intput file", true, "", "FILE");
ValueArg<string> arg_model_file("m", "model", "model file", true, "", "FILE");
ValueArg<int> arg_iteration("r", "iteration", "number of iterations",
false, 200, "NUMBER");
cmd.add(arg_concurrency);
cmd.add(arg_K);
cmd.add(arg_min_covar);
cmd.add(arg_input_file);
cmd.add(arg_model_file);
cmd.add(arg_iteration);
cmd.parse(argc, argv);
#define GET_VALUE(name) args.name = arg_##name.getValue();
GET_VALUE(concurrency);
GET_VALUE(K);
GET_VALUE(min_covar);
GET_VALUE(input_file);
GET_VALUE(model_file);
GET_VALUE(iteration);
} catch (ArgException &e) {
cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
}
return args;
}
void read_dense_dataset(DenseDataset &X, const char *fname) {
ifstream fin(fname);
string line;
while (getline(fin, line)) {
X.push_back(string_to_double_vector(line));
}
}
void write_dense_dataset(DenseDataset &X, const char *fname) {
ofstream fout(fname);
for (auto &x: X) {
for (auto &v: x)
fout << v << ' ';
fout << endl;
}
}
int main(int argc, char *argv[]) {
// srand(42); // Answer to The Ultimate Question of Life, the Universe, and Everything
Args args = parse_args(argc, argv);
DenseDataset X;
read_dense_dataset(X, args.input_file.c_str());
GMMTrainerBaseline trainer(args.iteration, args.min_covar, args.concurrency);
GMM gmm(args.K, COVTYPE_DIAGONAL, &trainer);
printf("start training ...\n"); fflush(stdout);
gmm.fit(X);
ofstream fout(args.model_file);
gmm.dump(fout);
return 0;
}
/**
* vim: syntax=cpp11 foldmethod=marker
*/
<|endoftext|> |
<commit_before>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#include <string>
#include <triton/astContext.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverModel.hpp>
#include <triton/symbolicVariable.hpp>
#include <triton/tritonToZ3Ast.hpp>
#include <triton/tritonTypes.hpp>
#include <triton/z3Solver.hpp>
#include <triton/z3ToTritonAst.hpp>
namespace triton {
namespace engines {
namespace solver {
//! Wrapper to handle variadict number of arguments or'd togethers
z3::expr mk_or(z3::expr_vector args) {
std::vector<Z3_ast> array;
for (triton::uint32 i = 0; i < args.size(); i++)
array.push_back(args[i]);
return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
}
Z3Solver::Z3Solver() {
this->timeout = 0;
this->memoryLimit = 0;
}
std::vector<std::unordered_map<triton::usize, SolverModel>> Z3Solver::getModels(const triton::ast::SharedAbstractNode& node, triton::uint32 limit, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::vector<std::unordered_map<triton::usize, SolverModel>> ret;
triton::ast::SharedAbstractNode onode = node;
triton::ast::TritonToZ3Ast z3Ast{false};
try {
if (onode == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): node cannot be null.");
/* Z3 does not need an assert() as root node */
if (node->getType() == triton::ast::ASSERT_NODE)
onode = node->getChildren()[0];
if (onode->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): Must be a logical node.");
z3::expr expr = z3Ast.convert(onode);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
/* Get first model */
z3::check_result res = solver.check();
/* Write back the status code of the first constraint */
this->writeBackStatus(solver, res, status);
/* Check if it is sat */
for (; res == z3::sat && limit >= 1; res = solver.check()) {
/* Get model */
z3::model m = solver.get_model();
/* Traversing the model */
std::unordered_map<triton::usize, SolverModel> smodel;
z3::expr_vector args(ctx);
for (triton::uint32 i = 0; i < m.size(); i++) {
/* Get the z3 variable */
z3::func_decl z3Variable = m[i];
/* Get the name as std::string from a z3 variable */
std::string varName = z3Variable.name().str();
/* Get z3 expr */
z3::expr exp = m.get_const_interp(z3Variable);
/* Get the size of a z3 expr */
triton::uint32 bvSize = exp.get_sort().bv_size();
/* Get the value of a z3 expr */
std::string svalue = Z3_get_numeral_string(ctx, exp);
/* Convert a string value to a integer value */
triton::uint512 value = triton::uint512(svalue);
/* Create a triton model */
SolverModel trionModel = SolverModel(z3Ast.variables[varName], value);
/* Map the result */
smodel[trionModel.getId()] = trionModel;
/* Uniq result */
if (exp.get_sort().is_bv())
args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));
}
/* Escape last models */
solver.add(triton::engines::solver::mk_or(args));
/* If there is model available */
if (smodel.size() > 0)
ret.push_back(smodel);
/* Decrement the limit */
limit--;
}
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::getModels(): ") + e.msg());
}
return ret;
}
bool Z3Solver::isSat(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
triton::ast::TritonToZ3Ast z3Ast{false};
if (node == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): node cannot be null.");
if (node->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): Must be a logical node.");
try {
z3::expr expr = z3Ast.convert(node);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
z3::check_result res = solver.check();
this->writeBackStatus(solver, res, status);
return res == z3::sat;
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::isSat(): ") + e.msg());
}
}
std::unordered_map<triton::usize, SolverModel> Z3Solver::getModel(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::unordered_map<triton::usize, SolverModel> ret;
std::vector<std::unordered_map<triton::usize, SolverModel>> allModels;
allModels = this->getModels(node, 1, status, timeout);
if (allModels.size() > 0)
ret = allModels.front();
return ret;
}
triton::ast::SharedAbstractNode Z3Solver::simplify(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3Ast{false};
triton::ast::Z3ToTritonAst tritonAst{node->getContext()};
/* From Triton to Z3 */
z3::expr expr = z3Ast.convert(node);
/* Simplify and back to Triton's AST */
auto snode = tritonAst.convert(expr.simplify());
return snode;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
triton::uint512 Z3Solver::evaluate(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3ast{true};
/* From Triton to Z3 */
z3::expr expr = z3ast.convert(node);
/* Simplify the expression to get a constant */
expr = expr.simplify();
triton::uint512 res = 0;
if (expr.get_sort().is_bool())
res = Z3_get_bool_value(expr.ctx(), expr) == Z3_L_TRUE ? true : false;
else
res = triton::uint512{Z3_get_numeral_string(expr.ctx(), expr)};
return res;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
void Z3Solver::writeBackStatus(z3::solver& solver, z3::check_result res, triton::engines::solver::status_e* status) const {
if (status != nullptr) {
switch (res) {
case z3::sat:
*status = triton::engines::solver::SAT;
break;
case z3::unsat:
*status = triton::engines::solver::UNSAT;
break;
case z3::unknown:
if (solver.reason_unknown() == "timeout") {
*status = triton::engines::solver::TIMEOUT;
}
else if (solver.reason_unknown() == "max. memory exceeded")
{
*status = triton::engines::solver::OUTOFMEM;
}
else {
*status = triton::engines::solver::UNKNOWN;
}
break;
}
}
}
std::string Z3Solver::getName(void) const {
return "z3";
}
void Z3Solver::setTimeout(triton::uint32 ms) {
this->timeout = ms;
}
void Z3Solver::setMemoryLimit(triton::uint32 limit) {
this->memoryLimit = limit;
}
};
};
};
<commit_msg>Fix double z3 solver check call<commit_after>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#include <string>
#include <triton/astContext.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverModel.hpp>
#include <triton/symbolicVariable.hpp>
#include <triton/tritonToZ3Ast.hpp>
#include <triton/tritonTypes.hpp>
#include <triton/z3Solver.hpp>
#include <triton/z3ToTritonAst.hpp>
namespace triton {
namespace engines {
namespace solver {
//! Wrapper to handle variadict number of arguments or'd togethers
z3::expr mk_or(z3::expr_vector args) {
std::vector<Z3_ast> array;
for (triton::uint32 i = 0; i < args.size(); i++)
array.push_back(args[i]);
return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
}
Z3Solver::Z3Solver() {
this->timeout = 0;
this->memoryLimit = 0;
}
std::vector<std::unordered_map<triton::usize, SolverModel>> Z3Solver::getModels(const triton::ast::SharedAbstractNode& node, triton::uint32 limit, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::vector<std::unordered_map<triton::usize, SolverModel>> ret;
triton::ast::SharedAbstractNode onode = node;
triton::ast::TritonToZ3Ast z3Ast{false};
try {
if (onode == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): node cannot be null.");
/* Z3 does not need an assert() as root node */
if (node->getType() == triton::ast::ASSERT_NODE)
onode = node->getChildren()[0];
if (onode->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): Must be a logical node.");
z3::expr expr = z3Ast.convert(onode);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
/* Get first model */
z3::check_result res = solver.check();
/* Write back the status code of the first constraint */
this->writeBackStatus(solver, res, status);
/* Check if it is sat */
while (res == z3::sat && limit >= 1) {
/* Get model */
z3::model m = solver.get_model();
/* Traversing the model */
std::unordered_map<triton::usize, SolverModel> smodel;
z3::expr_vector args(ctx);
for (triton::uint32 i = 0; i < m.size(); i++) {
/* Get the z3 variable */
z3::func_decl z3Variable = m[i];
/* Get the name as std::string from a z3 variable */
std::string varName = z3Variable.name().str();
/* Get z3 expr */
z3::expr exp = m.get_const_interp(z3Variable);
/* Get the size of a z3 expr */
triton::uint32 bvSize = exp.get_sort().bv_size();
/* Get the value of a z3 expr */
std::string svalue = Z3_get_numeral_string(ctx, exp);
/* Convert a string value to a integer value */
triton::uint512 value = triton::uint512(svalue);
/* Create a triton model */
SolverModel trionModel = SolverModel(z3Ast.variables[varName], value);
/* Map the result */
smodel[trionModel.getId()] = trionModel;
/* Uniq result */
if (exp.get_sort().is_bv())
args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));
}
/* Check that model is available */
if (smodel.empty())
break;
/* Push model */
ret.push_back(smodel);
if (--limit) {
/* Escape last models */
solver.add(triton::engines::solver::mk_or(args));
/* Get next model */
res = solver.check();
}
}
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::getModels(): ") + e.msg());
}
return ret;
}
bool Z3Solver::isSat(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
triton::ast::TritonToZ3Ast z3Ast{false};
if (node == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): node cannot be null.");
if (node->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): Must be a logical node.");
try {
z3::expr expr = z3Ast.convert(node);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
z3::check_result res = solver.check();
this->writeBackStatus(solver, res, status);
return res == z3::sat;
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::isSat(): ") + e.msg());
}
}
std::unordered_map<triton::usize, SolverModel> Z3Solver::getModel(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::unordered_map<triton::usize, SolverModel> ret;
std::vector<std::unordered_map<triton::usize, SolverModel>> allModels;
allModels = this->getModels(node, 1, status, timeout);
if (allModels.size() > 0)
ret = allModels.front();
return ret;
}
triton::ast::SharedAbstractNode Z3Solver::simplify(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3Ast{false};
triton::ast::Z3ToTritonAst tritonAst{node->getContext()};
/* From Triton to Z3 */
z3::expr expr = z3Ast.convert(node);
/* Simplify and back to Triton's AST */
auto snode = tritonAst.convert(expr.simplify());
return snode;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
triton::uint512 Z3Solver::evaluate(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3ast{true};
/* From Triton to Z3 */
z3::expr expr = z3ast.convert(node);
/* Simplify the expression to get a constant */
expr = expr.simplify();
triton::uint512 res = 0;
if (expr.get_sort().is_bool())
res = Z3_get_bool_value(expr.ctx(), expr) == Z3_L_TRUE ? true : false;
else
res = triton::uint512{Z3_get_numeral_string(expr.ctx(), expr)};
return res;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
void Z3Solver::writeBackStatus(z3::solver& solver, z3::check_result res, triton::engines::solver::status_e* status) const {
if (status != nullptr) {
switch (res) {
case z3::sat:
*status = triton::engines::solver::SAT;
break;
case z3::unsat:
*status = triton::engines::solver::UNSAT;
break;
case z3::unknown:
if (solver.reason_unknown() == "timeout") {
*status = triton::engines::solver::TIMEOUT;
}
else if (solver.reason_unknown() == "max. memory exceeded")
{
*status = triton::engines::solver::OUTOFMEM;
}
else {
*status = triton::engines::solver::UNKNOWN;
}
break;
}
}
}
std::string Z3Solver::getName(void) const {
return "z3";
}
void Z3Solver::setTimeout(triton::uint32 ms) {
this->timeout = ms;
}
void Z3Solver::setMemoryLimit(triton::uint32 limit) {
this->memoryLimit = limit;
}
};
};
};
<|endoftext|> |
<commit_before>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/Loaders/Mesh.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Renderer/Material.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <memory>
#include <Nazara/Graphics/Debug.hpp>
namespace
{
nzTernary Check(NzInputStream& stream, const NzModelParameters& parameters)
{
NazaraUnused(stream);
NazaraUnused(parameters);
return nzTernary_Unknown;
}
bool Load(NzModel* model, NzInputStream& stream, const NzModelParameters& parameters)
{
NazaraUnused(parameters);
std::unique_ptr<NzMesh> mesh(new NzMesh);
mesh->SetPersistent(false);
if (!mesh->LoadFromStream(stream))
{
NazaraError("Failed to load model mesh");
return false;
}
// Nous ne pouvons plus avoir recours au smart pointeur à partir d'ici si nous voulons être exception-safe
NzMesh* meshPtr = mesh.get();
model->Reset();
model->SetMesh(meshPtr);
mesh.release();
if (parameters.loadAnimation && meshPtr->IsAnimable())
{
NzString animationPath = meshPtr->GetAnimation();
if (!animationPath.IsEmpty())
{
std::unique_ptr<NzAnimation> animation(new NzAnimation);
animation->SetPersistent(false);
if (animation->LoadFromFile(animationPath, parameters.animation) && model->SetAnimation(animation.get()))
animation.release();
else
NazaraWarning("Failed to load animation");
}
}
if (parameters.loadMaterials)
{
unsigned int matCount = model->GetMaterialCount();
for (unsigned int i = 0; i < matCount; ++i)
{
NzString mat = meshPtr->GetMaterial(i);
if (!mat.IsEmpty())
{
std::unique_ptr<NzMaterial> material(new NzMaterial);
material->SetPersistent(false);
if (material->LoadFromFile(mat, parameters.material))
{
model->SetMaterial(i, material.get());
material.release();
}
else
NazaraWarning("Failed to load material #" + NzString::Number(i));
}
}
}
return true;
}
}
void NzLoaders_Mesh_Register()
{
NzModelLoader::RegisterLoader(NzMeshLoader::IsExtensionSupported, Check, Load);
}
void NzLoaders_Mesh_Unregister()
{
NzModelLoader::UnregisterLoader(NzMeshLoader::IsExtensionSupported, Check, Load);
}
<commit_msg>Fixed Model "Mesh" loader not using mesh parameters<commit_after>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/Loaders/Mesh.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Renderer/Material.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <memory>
#include <Nazara/Graphics/Debug.hpp>
namespace
{
nzTernary Check(NzInputStream& stream, const NzModelParameters& parameters)
{
NazaraUnused(stream);
NazaraUnused(parameters);
return nzTernary_Unknown;
}
bool Load(NzModel* model, NzInputStream& stream, const NzModelParameters& parameters)
{
NazaraUnused(parameters);
std::unique_ptr<NzMesh> mesh(new NzMesh);
mesh->SetPersistent(false);
if (!mesh->LoadFromStream(stream, parameters.mesh))
{
NazaraError("Failed to load model mesh");
return false;
}
// Nous ne pouvons plus avoir recours au smart pointeur à partir d'ici si nous voulons être exception-safe
NzMesh* meshPtr = mesh.get();
model->Reset();
model->SetMesh(meshPtr);
mesh.release();
if (parameters.loadAnimation && meshPtr->IsAnimable())
{
NzString animationPath = meshPtr->GetAnimation();
if (!animationPath.IsEmpty())
{
std::unique_ptr<NzAnimation> animation(new NzAnimation);
animation->SetPersistent(false);
if (animation->LoadFromFile(animationPath, parameters.animation) && model->SetAnimation(animation.get()))
animation.release();
else
NazaraWarning("Failed to load animation");
}
}
if (parameters.loadMaterials)
{
unsigned int matCount = model->GetMaterialCount();
for (unsigned int i = 0; i < matCount; ++i)
{
NzString mat = meshPtr->GetMaterial(i);
if (!mat.IsEmpty())
{
std::unique_ptr<NzMaterial> material(new NzMaterial);
material->SetPersistent(false);
if (material->LoadFromFile(mat, parameters.material))
{
model->SetMaterial(i, material.get());
material.release();
}
else
NazaraWarning("Failed to load material #" + NzString::Number(i));
}
}
}
return true;
}
}
void NzLoaders_Mesh_Register()
{
NzModelLoader::RegisterLoader(NzMeshLoader::IsExtensionSupported, Check, Load);
}
void NzLoaders_Mesh_Unregister()
{
NzModelLoader::UnregisterLoader(NzMeshLoader::IsExtensionSupported, Check, Load);
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <tuple>
#include <vector>
#include <openssl/sha.h>
#include <ecdsa/base58.h>
#include <ecdsa/key.h>
#include "args.h"
#include "btcaddr.h"
#include "btcwif.h"
#define BUFF_SIZE 1024
/**
* Show help document.
*
* @param args The argument manager
*/
void ShowHelp(const Args &args) {
std::cout << "BTCAddr(ess)Gen(erator)" << std::endl
<< " An easy to use Bitcoin Address offline generator."
<< std::endl
<< std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " ./btcaddrgen [arguments...]" << std::endl << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << args.GetArgsHelpString() << std::endl;
}
std::tuple<std::vector<uint8_t>, bool> HashFile(const std::string &path) {
std::vector<uint8_t> md;
std::ifstream input(path, std::ios::binary);
if (!input.is_open()) {
std::cerr << "Cannot open file " << path << std::endl;
return std::make_tuple(md, false);
}
// Hash file contents
SHA512_CTX ctx;
SHA512_Init(&ctx);
// Reading...
char buff[BUFF_SIZE];
while (!input.eof()) {
input.read(buff, BUFF_SIZE);
size_t buff_size = input.gcount();
SHA512_Update(&ctx, buff, buff_size);
}
// Get md buffer.
md.resize(SHA512_DIGEST_LENGTH);
SHA512_Final(md.data(), &ctx);
return std::make_tuple(md, true);
}
std::tuple<std::vector<uint8_t>, bool> Signing(std::shared_ptr<ecdsa::Key> pkey,
const std::string &path) {
std::vector<uint8_t> signature;
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (!succ) {
return std::make_tuple(signature, false);
}
std::tie(signature, succ) = pkey->Sign(md);
if (!succ) {
std::cerr << "Cannot signing file!" << std::endl;
return std::make_tuple(signature, false);
}
return std::make_tuple(signature, true);
}
bool Verifying(const ecdsa::PubKey &pub_key, const std::string &path,
const std::vector<uint8_t> &signature) {
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (succ) {
return pub_key.Verify(md, signature);
}
return false;
}
std::string BinaryToHexString(const unsigned char *bin_data, size_t size) {
std::stringstream ss_hex;
for (unsigned int i = 0; i < size; ++i) {
ss_hex << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(bin_data[i]);
}
return ss_hex.str();
}
void ShowKeyInfo(std::shared_ptr<ecdsa::Key> pkey, unsigned char prefix_char) {
auto pub_key = pkey->CreatePubKey();
unsigned char hash160[20];
auto addr = btc::Address::FromPublicKey(pub_key.get_pub_key_data(),
prefix_char, hash160);
std::cout << "Address: " << addr.ToString() << std::endl;
std::cout << "Hash160: " << BinaryToHexString(hash160, 20) << std::endl;
std::cout << "Public key: " << base58::EncodeBase58(pkey->get_pub_key_data())
<< std::endl;
std::cout << "Private key: "
<< base58::EncodeBase58(pkey->get_priv_key_data()) << std::endl;
std::cout << "Private key(WIF): "
<< btc::wif::PrivateKeyToWif(pkey->get_priv_key_data())
<< std::endl;
}
/// Main program.
int main(int argc, const char *argv[]) {
try {
Args args(argc, argv);
if (args.is_help()) {
ShowHelp(args);
return 0;
}
if (args.is_generate_new_key()) {
ShowKeyInfo(std::make_shared<ecdsa::Key>(), args.get_prefix_char());
return 0;
}
// Import key.
std::shared_ptr<ecdsa::Key> pkey;
std::string priv_key_b58 = args.get_import_priv_key();
if (!priv_key_b58.empty()) {
std::vector<uint8_t> priv_key;
// Checking WIF format.
if (btc::wif::VerifyWifString(priv_key_b58)) {
// Decoding private key in WIF format.
priv_key = btc::wif::WifToPrivateKey(priv_key_b58);
} else {
// Decoding private key in plain base58 data.
bool succ = base58::DecodeBase58(priv_key_b58.c_str(), priv_key);
if (!succ) {
std::cerr << "Failed to decode base58!" << std::endl;
return 1;
}
}
pkey = std::make_shared<ecdsa::Key>(priv_key);
ShowKeyInfo(pkey, args.get_prefix_char());
}
// Signing file?
if (!args.get_signing_file().empty()) {
if (pkey == nullptr) {
pkey = std::make_shared<ecdsa::Key>();
ShowKeyInfo(pkey, args.get_prefix_char());
}
std::vector<uint8_t> signature;
bool succ;
std::tie(signature, succ) = Signing(pkey, args.get_signing_file());
if (succ) {
std::string signature_b58 = base58::EncodeBase58(signature);
std::cout << "Signature: " << signature_b58 << std::endl;
return 0;
}
return 1;
}
// Verifying
if (!args.get_import_pub_key().empty() &&
!args.get_verifying_file().empty() && !args.get_signature().empty()) {
// Verifying
std::vector<uint8_t> pub_key_data;
bool succ = base58::DecodeBase58(args.get_import_pub_key(), pub_key_data);
if (!succ) {
std::cerr << "Cannot decode public key from base58 string."
<< std::endl;
return 1;
}
std::vector<uint8_t> signature;
succ = base58::DecodeBase58(args.get_signature(), signature);
if (!succ) {
std::cerr << "Cannot decode signature from base58 string." << std::endl;
return 1;
}
ecdsa::PubKey pub_key(pub_key_data);
succ = Verifying(pub_key, args.get_verifying_file(), signature);
if (succ) {
std::cout << "Verified OK." << std::endl;
return 0;
}
return 1;
}
if (priv_key_b58.empty()) {
std::cerr << "No argument, -h to show help." << std::endl;
}
return 1;
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>Little-endian hex encoding.<commit_after>#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <tuple>
#include <vector>
#include <openssl/sha.h>
#include <ecdsa/base58.h>
#include <ecdsa/key.h>
#include "args.h"
#include "btcaddr.h"
#include "btcwif.h"
#define BUFF_SIZE 1024
/**
* Show help document.
*
* @param args The argument manager
*/
void ShowHelp(const Args &args) {
std::cout << "BTCAddr(ess)Gen(erator)" << std::endl
<< " An easy to use Bitcoin Address offline generator."
<< std::endl
<< std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " ./btcaddrgen [arguments...]" << std::endl << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << args.GetArgsHelpString() << std::endl;
}
std::tuple<std::vector<uint8_t>, bool> HashFile(const std::string &path) {
std::vector<uint8_t> md;
std::ifstream input(path, std::ios::binary);
if (!input.is_open()) {
std::cerr << "Cannot open file " << path << std::endl;
return std::make_tuple(md, false);
}
// Hash file contents
SHA512_CTX ctx;
SHA512_Init(&ctx);
// Reading...
char buff[BUFF_SIZE];
while (!input.eof()) {
input.read(buff, BUFF_SIZE);
size_t buff_size = input.gcount();
SHA512_Update(&ctx, buff, buff_size);
}
// Get md buffer.
md.resize(SHA512_DIGEST_LENGTH);
SHA512_Final(md.data(), &ctx);
return std::make_tuple(md, true);
}
std::tuple<std::vector<uint8_t>, bool> Signing(std::shared_ptr<ecdsa::Key> pkey,
const std::string &path) {
std::vector<uint8_t> signature;
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (!succ) {
return std::make_tuple(signature, false);
}
std::tie(signature, succ) = pkey->Sign(md);
if (!succ) {
std::cerr << "Cannot signing file!" << std::endl;
return std::make_tuple(signature, false);
}
return std::make_tuple(signature, true);
}
bool Verifying(const ecdsa::PubKey &pub_key, const std::string &path,
const std::vector<uint8_t> &signature) {
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (succ) {
return pub_key.Verify(md, signature);
}
return false;
}
std::string BinaryToHexString(const unsigned char *bin_data, size_t size) {
std::stringstream ss_hex;
for (unsigned int i = size - 1; i > 0; --i) {
ss_hex << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(bin_data[i]);
}
return ss_hex.str();
}
void ShowKeyInfo(std::shared_ptr<ecdsa::Key> pkey, unsigned char prefix_char) {
auto pub_key = pkey->CreatePubKey();
unsigned char hash160[20];
auto addr = btc::Address::FromPublicKey(pub_key.get_pub_key_data(),
prefix_char, hash160);
std::cout << "Address: " << addr.ToString() << std::endl;
std::cout << "Hash160: " << BinaryToHexString(hash160, 20) << std::endl;
std::cout << "Public key: " << base58::EncodeBase58(pkey->get_pub_key_data())
<< std::endl;
std::cout << "Private key: "
<< base58::EncodeBase58(pkey->get_priv_key_data()) << std::endl;
std::cout << "Private key(WIF): "
<< btc::wif::PrivateKeyToWif(pkey->get_priv_key_data())
<< std::endl;
}
/// Main program.
int main(int argc, const char *argv[]) {
try {
Args args(argc, argv);
if (args.is_help()) {
ShowHelp(args);
return 0;
}
if (args.is_generate_new_key()) {
ShowKeyInfo(std::make_shared<ecdsa::Key>(), args.get_prefix_char());
return 0;
}
// Import key.
std::shared_ptr<ecdsa::Key> pkey;
std::string priv_key_b58 = args.get_import_priv_key();
if (!priv_key_b58.empty()) {
std::vector<uint8_t> priv_key;
// Checking WIF format.
if (btc::wif::VerifyWifString(priv_key_b58)) {
// Decoding private key in WIF format.
priv_key = btc::wif::WifToPrivateKey(priv_key_b58);
} else {
// Decoding private key in plain base58 data.
bool succ = base58::DecodeBase58(priv_key_b58.c_str(), priv_key);
if (!succ) {
std::cerr << "Failed to decode base58!" << std::endl;
return 1;
}
}
pkey = std::make_shared<ecdsa::Key>(priv_key);
ShowKeyInfo(pkey, args.get_prefix_char());
}
// Signing file?
if (!args.get_signing_file().empty()) {
if (pkey == nullptr) {
pkey = std::make_shared<ecdsa::Key>();
ShowKeyInfo(pkey, args.get_prefix_char());
}
std::vector<uint8_t> signature;
bool succ;
std::tie(signature, succ) = Signing(pkey, args.get_signing_file());
if (succ) {
std::string signature_b58 = base58::EncodeBase58(signature);
std::cout << "Signature: " << signature_b58 << std::endl;
return 0;
}
return 1;
}
// Verifying
if (!args.get_import_pub_key().empty() &&
!args.get_verifying_file().empty() && !args.get_signature().empty()) {
// Verifying
std::vector<uint8_t> pub_key_data;
bool succ = base58::DecodeBase58(args.get_import_pub_key(), pub_key_data);
if (!succ) {
std::cerr << "Cannot decode public key from base58 string."
<< std::endl;
return 1;
}
std::vector<uint8_t> signature;
succ = base58::DecodeBase58(args.get_signature(), signature);
if (!succ) {
std::cerr << "Cannot decode signature from base58 string." << std::endl;
return 1;
}
ecdsa::PubKey pub_key(pub_key_data);
succ = Verifying(pub_key, args.get_verifying_file(), signature);
if (succ) {
std::cout << "Verified OK." << std::endl;
return 0;
}
return 1;
}
if (priv_key_b58.empty()) {
std::cerr << "No argument, -h to show help." << std::endl;
}
return 1;
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <limits>
// ospray
#include "volume/DataDistributedBlockedVolume.h"
#include "volume/GhostBlockBrickedVolume.h"
#include "common/Core.h"
#include "transferFunction/TransferFunction.h"
#include "volume/GhostBlockBrickedVolume.h"
#if EXP_DATA_PARALLEL
#include "mpi/MPICommon.h"
#endif
// ispc exports:
#include "DataDistributedBlockedVolume_ispc.h"
namespace ospray {
#if EXP_DATA_PARALLEL
//! Allocate storage and populate the volume, called through the OSPRay API.
void DataDistributedBlockedVolume::commit()
{
// IW: do NOT call parent commit here - this would try to build
// the parent acceleration strucutre, which doesn't make sense on
// blocks that do not exist!!!!
updateEditableParameters();//
StructuredVolume::commit();
for (uint32_t i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
block->cppVolume->commit();
}
}
DataDistributedBlockedVolume::DataDistributedBlockedVolume() :
numDDBlocks(0),
ddBlock(NULL)
{
PING;
}
void DataDistributedBlockedVolume::updateEditableParameters()
{
StructuredVolume::updateEditableParameters();
for (uint32_t i = 0; i < numDDBlocks; i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
Ref<TransferFunction> transferFunction
= (TransferFunction *)getParamObject("transferFunction", NULL);
auto &cppVolume = block->cppVolume;
cppVolume->findParam("transferFunction",1)->set(transferFunction.ptr);
cppVolume->findParam("samplingRate",1)->set(getParam1f("samplingRate",
1.f));
cppVolume->findParam("gradientShadingEnabled",
1)->set(getParam1i("gradientShadingEnabled", 0));
cppVolume.ptr->updateEditableParameters();
}
}
bool DataDistributedBlockedVolume::isDataDistributed() const
{
return true;
}
void DataDistributedBlockedVolume::buildAccelerator()
{
std::cout << "intentionally SKIP building an accelerator for data parallel "
<< "volume (this'll be done on the brick level)" << std::endl;
}
std::string DataDistributedBlockedVolume::toString() const
{
return("ospray::DataDistributedBlockedVolume<" + voxelType + ">");
}
//! Copy voxels into the volume at the given index (non-zero return value
//! indicates success).
int DataDistributedBlockedVolume::setRegion(
/* points to the first voxel to be copies. The
voxels at 'soruce' MUST have dimensions
'regionSize', must be organized in 3D-array
order, and must have the same voxel type as the
volume.*/
const void *source,
/*! coordinates of the lower,
left, front corner of the target
region.*/
const vec3i ®ionCoords,
/*! size of the region that we're writing to; MUST
be the same as the dimensions of source[][][] */
const vec3i ®ionSize)
{
// Create the equivalent ISPC volume container and allocate memory for voxel
// data.
if (ispcEquivalent == NULL) createEquivalentISPC();
// The block domains are in terms of the scaled regions so we must check
// if the data is for the block in the scaled volume
vec3i finalRegionCoords(vec3f(regionCoords) * scaleFactor);
vec3i finalRegionSize(vec3f(regionSize) * scaleFactor);
if (scaleFactor != vec3f(-1.f)) {
finalRegionCoords = vec3i(vec3f(regionCoords) * scaleFactor);
finalRegionSize = vec3i(vec3f(regionSize) * scaleFactor);
} else {
finalRegionCoords = regionCoords;
finalRegionSize = regionSize;
}
for (uint32_t i = 0; i < numDDBlocks; i++) {
// that block isn't mine, I shouldn't care ...
if (!ddBlock[i].isMine) continue;
// first, do some culling to make sure we only do setrgion
// calls on blocks that actually map to this block
if (ddBlock[i].domain.lower.x >= finalRegionCoords.x+finalRegionSize.x) continue;
if (ddBlock[i].domain.lower.y >= finalRegionCoords.y+finalRegionSize.y) continue;
if (ddBlock[i].domain.lower.z >= finalRegionCoords.z+finalRegionSize.z) continue;
if (ddBlock[i].domain.upper.x+finalRegionSize.x < finalRegionCoords.x) continue;
if (ddBlock[i].domain.upper.y+finalRegionSize.y < finalRegionCoords.y) continue;
if (ddBlock[i].domain.upper.z+finalRegionSize.z < finalRegionCoords.z) continue;
vec3i setRegionCoords = finalRegionCoords - ddBlock[i].domain.lower;
if (scaleFactor != vec3f(-1.f)) {
setRegionCoords = vec3i(vec3f(setRegionCoords) / scaleFactor);
}
ddBlock[i].cppVolume->setRegion(source, setRegionCoords, regionSize);
ddBlock[i].ispcVolume = ddBlock[i].cppVolume->getIE();
#ifndef OSPRAY_VOLUME_VOXELRANGE_IN_APP
ManagedObject::Param *param = ddBlock[i].cppVolume->findParam("voxelRange");
if (param != NULL && param->type == OSP_FLOAT2){
vec2f blockRange = ((vec2f*)param->f)[0];
voxelRange.x = std::min(voxelRange.x, blockRange.x);
voxelRange.y = std::max(voxelRange.y, blockRange.y);
}
#endif
}
#ifndef OSPRAY_VOLUME_VOXELRANGE_IN_APP
// Do a reduction here to worker 0 since it will be queried for the voxel range by the display node
vec2f globalVoxelRange = voxelRange;
MPI_CALL(Reduce(&voxelRange.x, &globalVoxelRange.x, 1, MPI_FLOAT, MPI_MIN, 0, mpi::worker.comm));
MPI_CALL(Reduce(&voxelRange.y, &globalVoxelRange.y, 1, MPI_FLOAT, MPI_MAX, 0, mpi::worker.comm));
set("voxelRange", globalVoxelRange);
#endif
return 0;
}
void DataDistributedBlockedVolume::createEquivalentISPC()
{
if (ispcEquivalent != NULL) return;
// Get the voxel type.
voxelType = getParamString("voxelType", "unspecified");
exitOnCondition(getVoxelType() == OSP_UNKNOWN,
"unrecognized voxel type (must be set before calling "
"ospSetRegion())");
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions (must be set before calling "
"ospSetRegion())");
ddBlocks = getParam3i("num_dp_blocks",vec3i(4,4,4));
blockSize = divRoundUp(dimensions,ddBlocks);
std::cout << "#osp:dp: using data parallel volume of " << ddBlocks
<< " blocks, blockSize is " << blockSize << std::endl;
// Set the grid origin, default to (0,0,0).
this->gridOrigin = getParam3f("gridOrigin", vec3f(0.f));
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions");
// Set the grid spacing, default to (1,1,1).
this->gridSpacing = getParam3f("gridSpacing", vec3f(1.f));
this->scaleFactor = getParam3f("scaleFactor", vec3f(-1.f));
numDDBlocks = ospcommon::reduce_mul(ddBlocks);
ddBlock = new DDBlock[numDDBlocks];
printf("=======================================================\n");
printf("created %ix%ix%i data distributed volume blocks\n",
ddBlocks.x,ddBlocks.y,ddBlocks.z);
printf("=======================================================\n");
if (!ospray::core::isMpiParallel()) {
throw std::runtime_error("data parallel volume, but not in mpi parallel "
"mode...");
}
uint64_t numWorkers = ospray::core::getWorkerCount();
// PRINT(numDDBlocks);
// PRINT(numWorkers);
voxelType = getParamString("voxelType", "unspecified");
// if (numDDBlocks >= numWorkers) {
// we have more workers than blocks - use one owner per block,
// meaning we'll end up with multiple blocks per worker
int blockID = 0;
for (int iz=0;iz<ddBlocks.z;iz++)
for (int iy=0;iy<ddBlocks.y;iy++)
for (int ix=0;ix<ddBlocks.x;ix++, blockID++) {
DDBlock *block = &ddBlock[blockID];
if (numDDBlocks >= numWorkers) {
block->firstOwner = blockID % numWorkers;
block->numOwners = 1;
} else {
block->firstOwner = (blockID * numWorkers) / numDDBlocks;
int nextBlockFirstOwner = ((blockID+1)*numWorkers) / numDDBlocks;
block->numOwners = nextBlockFirstOwner - block->firstOwner; // + 1;
}
block->isMine
= (ospray::core::getWorkerRank() >= block->firstOwner)
&& (ospray::core::getWorkerRank() <
(block->firstOwner + block->numOwners));
block->domain.lower = vec3i(ix,iy,iz) * blockSize;
block->domain.upper = min(block->domain.lower+blockSize,dimensions);
block->bounds.lower = gridOrigin +
(gridSpacing * vec3f(block->domain.lower));
block->bounds.upper = gridOrigin +
(gridSpacing * vec3f(block->domain.upper));
// iw: add one voxel overlap, so we can properly interpolate
// even across block boundaries (we need the full *cell* on
// the right side, not just the last *voxel*!)
block->domain.upper = min(block->domain.upper+vec3i(1),dimensions);
if (block->isMine) {
#ifdef EXP_NEW_BB_VOLUME_KERNELS
Ref<Volume> volume = new GhostBlockBrickedVolume;
#else
Ref<Volume> volume = new BlockBrickedVolume;
#endif
vec3i blockDims = block->domain.upper - block->domain.lower;
volume->findParam("dimensions",1)->set(blockDims);
volume->findParam("gridOrigin",1)->set(block->bounds.lower);
volume->findParam("gridSpacing",1)->set(gridSpacing);
volume->findParam("voxelType",1)->set(voxelType.c_str());
if (scaleFactor != vec3f(-1.f)) {
volume->findParam("scaleFactor",1)->set(scaleFactor);
}
printf("rank %li owns block %i,%i,%i (ID %i), dims %i %i %i\n",
(size_t)core::getWorkerRank(),ix,iy,iz,
blockID,blockDims.x,blockDims.y,blockDims.z);
block->cppVolume = volume;
block->ispcVolume = NULL; //volume->getIE();
} else {
block->ispcVolume = NULL;
block->cppVolume = NULL;
}
}
// Create an ISPC BlockBrickedVolume object and assign type-specific
// function pointers.
ispcEquivalent = ispc::DDBVolume_create(this,
(int)getVoxelType(),
(const ispc::vec3i&)dimensions,
(const ispc::vec3i&)ddBlocks,
(const ispc::vec3i&)blockSize,
ddBlock);
if (!ispcEquivalent) {
throw std::runtime_error("could not create create data distributed "
"volume");
}
}
// A volume type with internal data-distribution. needs a renderer
// that is capable of data-parallel rendering!
OSP_REGISTER_VOLUME(DataDistributedBlockedVolume, data_distributed_volume);
#endif
} // ::ospray
<commit_msg>Datadistrib volume would return 0 to indicate success which is wrong<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <limits>
// ospray
#include "volume/DataDistributedBlockedVolume.h"
#include "volume/GhostBlockBrickedVolume.h"
#include "common/Core.h"
#include "transferFunction/TransferFunction.h"
#include "volume/GhostBlockBrickedVolume.h"
#if EXP_DATA_PARALLEL
#include "mpi/MPICommon.h"
#endif
// ispc exports:
#include "DataDistributedBlockedVolume_ispc.h"
namespace ospray {
#if EXP_DATA_PARALLEL
//! Allocate storage and populate the volume, called through the OSPRay API.
void DataDistributedBlockedVolume::commit()
{
// IW: do NOT call parent commit here - this would try to build
// the parent acceleration strucutre, which doesn't make sense on
// blocks that do not exist!!!!
updateEditableParameters();//
StructuredVolume::commit();
for (uint32_t i=0;i<numDDBlocks;i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
block->cppVolume->commit();
}
}
DataDistributedBlockedVolume::DataDistributedBlockedVolume() :
numDDBlocks(0),
ddBlock(NULL)
{
PING;
}
void DataDistributedBlockedVolume::updateEditableParameters()
{
StructuredVolume::updateEditableParameters();
for (uint32_t i = 0; i < numDDBlocks; i++) {
DDBlock *block = ddBlock+i;
if (!block->isMine) {
continue;
}
Ref<TransferFunction> transferFunction
= (TransferFunction *)getParamObject("transferFunction", NULL);
auto &cppVolume = block->cppVolume;
cppVolume->findParam("transferFunction",1)->set(transferFunction.ptr);
cppVolume->findParam("samplingRate",1)->set(getParam1f("samplingRate",
1.f));
cppVolume->findParam("gradientShadingEnabled",
1)->set(getParam1i("gradientShadingEnabled", 0));
cppVolume.ptr->updateEditableParameters();
}
}
bool DataDistributedBlockedVolume::isDataDistributed() const
{
return true;
}
void DataDistributedBlockedVolume::buildAccelerator()
{
std::cout << "intentionally SKIP building an accelerator for data parallel "
<< "volume (this'll be done on the brick level)" << std::endl;
}
std::string DataDistributedBlockedVolume::toString() const
{
return("ospray::DataDistributedBlockedVolume<" + voxelType + ">");
}
//! Copy voxels into the volume at the given index (non-zero return value
//! indicates success).
int DataDistributedBlockedVolume::setRegion(
/* points to the first voxel to be copies. The
voxels at 'soruce' MUST have dimensions
'regionSize', must be organized in 3D-array
order, and must have the same voxel type as the
volume.*/
const void *source,
/*! coordinates of the lower,
left, front corner of the target
region.*/
const vec3i ®ionCoords,
/*! size of the region that we're writing to; MUST
be the same as the dimensions of source[][][] */
const vec3i ®ionSize)
{
// Create the equivalent ISPC volume container and allocate memory for voxel
// data.
if (ispcEquivalent == NULL) createEquivalentISPC();
// The block domains are in terms of the scaled regions so we must check
// if the data is for the block in the scaled volume
vec3i finalRegionCoords(vec3f(regionCoords) * scaleFactor);
vec3i finalRegionSize(vec3f(regionSize) * scaleFactor);
if (scaleFactor != vec3f(-1.f)) {
finalRegionCoords = vec3i(vec3f(regionCoords) * scaleFactor);
finalRegionSize = vec3i(vec3f(regionSize) * scaleFactor);
} else {
finalRegionCoords = regionCoords;
finalRegionSize = regionSize;
}
for (uint32_t i = 0; i < numDDBlocks; i++) {
// that block isn't mine, I shouldn't care ...
if (!ddBlock[i].isMine) continue;
// first, do some culling to make sure we only do setrgion
// calls on blocks that actually map to this block
if (ddBlock[i].domain.lower.x >= finalRegionCoords.x+finalRegionSize.x) continue;
if (ddBlock[i].domain.lower.y >= finalRegionCoords.y+finalRegionSize.y) continue;
if (ddBlock[i].domain.lower.z >= finalRegionCoords.z+finalRegionSize.z) continue;
if (ddBlock[i].domain.upper.x+finalRegionSize.x < finalRegionCoords.x) continue;
if (ddBlock[i].domain.upper.y+finalRegionSize.y < finalRegionCoords.y) continue;
if (ddBlock[i].domain.upper.z+finalRegionSize.z < finalRegionCoords.z) continue;
vec3i setRegionCoords = finalRegionCoords - ddBlock[i].domain.lower;
if (scaleFactor != vec3f(-1.f)) {
setRegionCoords = vec3i(vec3f(setRegionCoords) / scaleFactor);
}
ddBlock[i].cppVolume->setRegion(source, setRegionCoords, regionSize);
ddBlock[i].ispcVolume = ddBlock[i].cppVolume->getIE();
#ifndef OSPRAY_VOLUME_VOXELRANGE_IN_APP
ManagedObject::Param *param = ddBlock[i].cppVolume->findParam("voxelRange");
if (param != NULL && param->type == OSP_FLOAT2){
vec2f blockRange = ((vec2f*)param->f)[0];
voxelRange.x = std::min(voxelRange.x, blockRange.x);
voxelRange.y = std::max(voxelRange.y, blockRange.y);
}
#endif
}
#ifndef OSPRAY_VOLUME_VOXELRANGE_IN_APP
// Do a reduction here to worker 0 since it will be queried for the voxel range by the display node
vec2f globalVoxelRange = voxelRange;
MPI_CALL(Reduce(&voxelRange.x, &globalVoxelRange.x, 1, MPI_FLOAT, MPI_MIN, 0, mpi::worker.comm));
MPI_CALL(Reduce(&voxelRange.y, &globalVoxelRange.y, 1, MPI_FLOAT, MPI_MAX, 0, mpi::worker.comm));
set("voxelRange", globalVoxelRange);
#endif
return true;
}
void DataDistributedBlockedVolume::createEquivalentISPC()
{
if (ispcEquivalent != NULL) return;
// Get the voxel type.
voxelType = getParamString("voxelType", "unspecified");
exitOnCondition(getVoxelType() == OSP_UNKNOWN,
"unrecognized voxel type (must be set before calling "
"ospSetRegion())");
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions (must be set before calling "
"ospSetRegion())");
ddBlocks = getParam3i("num_dp_blocks",vec3i(4,4,4));
blockSize = divRoundUp(dimensions,ddBlocks);
std::cout << "#osp:dp: using data parallel volume of " << ddBlocks
<< " blocks, blockSize is " << blockSize << std::endl;
// Set the grid origin, default to (0,0,0).
this->gridOrigin = getParam3f("gridOrigin", vec3f(0.f));
// Get the volume dimensions.
this->dimensions = getParam3i("dimensions", vec3i(0));
exitOnCondition(reduce_min(this->dimensions) <= 0,
"invalid volume dimensions");
// Set the grid spacing, default to (1,1,1).
this->gridSpacing = getParam3f("gridSpacing", vec3f(1.f));
this->scaleFactor = getParam3f("scaleFactor", vec3f(-1.f));
numDDBlocks = ospcommon::reduce_mul(ddBlocks);
ddBlock = new DDBlock[numDDBlocks];
printf("=======================================================\n");
printf("created %ix%ix%i data distributed volume blocks\n",
ddBlocks.x,ddBlocks.y,ddBlocks.z);
printf("=======================================================\n");
if (!ospray::core::isMpiParallel()) {
throw std::runtime_error("data parallel volume, but not in mpi parallel "
"mode...");
}
uint64_t numWorkers = ospray::core::getWorkerCount();
// PRINT(numDDBlocks);
// PRINT(numWorkers);
voxelType = getParamString("voxelType", "unspecified");
// if (numDDBlocks >= numWorkers) {
// we have more workers than blocks - use one owner per block,
// meaning we'll end up with multiple blocks per worker
int blockID = 0;
for (int iz=0;iz<ddBlocks.z;iz++)
for (int iy=0;iy<ddBlocks.y;iy++)
for (int ix=0;ix<ddBlocks.x;ix++, blockID++) {
DDBlock *block = &ddBlock[blockID];
if (numDDBlocks >= numWorkers) {
block->firstOwner = blockID % numWorkers;
block->numOwners = 1;
} else {
block->firstOwner = (blockID * numWorkers) / numDDBlocks;
int nextBlockFirstOwner = ((blockID+1)*numWorkers) / numDDBlocks;
block->numOwners = nextBlockFirstOwner - block->firstOwner; // + 1;
}
block->isMine
= (ospray::core::getWorkerRank() >= block->firstOwner)
&& (ospray::core::getWorkerRank() <
(block->firstOwner + block->numOwners));
block->domain.lower = vec3i(ix,iy,iz) * blockSize;
block->domain.upper = min(block->domain.lower+blockSize,dimensions);
block->bounds.lower = gridOrigin +
(gridSpacing * vec3f(block->domain.lower));
block->bounds.upper = gridOrigin +
(gridSpacing * vec3f(block->domain.upper));
// iw: add one voxel overlap, so we can properly interpolate
// even across block boundaries (we need the full *cell* on
// the right side, not just the last *voxel*!)
block->domain.upper = min(block->domain.upper+vec3i(1),dimensions);
if (block->isMine) {
#ifdef EXP_NEW_BB_VOLUME_KERNELS
Ref<Volume> volume = new GhostBlockBrickedVolume;
#else
Ref<Volume> volume = new BlockBrickedVolume;
#endif
vec3i blockDims = block->domain.upper - block->domain.lower;
volume->findParam("dimensions",1)->set(blockDims);
volume->findParam("gridOrigin",1)->set(block->bounds.lower);
volume->findParam("gridSpacing",1)->set(gridSpacing);
volume->findParam("voxelType",1)->set(voxelType.c_str());
if (scaleFactor != vec3f(-1.f)) {
volume->findParam("scaleFactor",1)->set(scaleFactor);
}
printf("worker rank %li owns block %i,%i,%i (ID %i), dims %i %i %i\n",
(size_t)core::getWorkerRank(),ix,iy,iz,
blockID,blockDims.x,blockDims.y,blockDims.z);
block->cppVolume = volume;
block->ispcVolume = NULL; //volume->getIE();
} else {
block->ispcVolume = NULL;
block->cppVolume = NULL;
}
}
// Create an ISPC BlockBrickedVolume object and assign type-specific
// function pointers.
ispcEquivalent = ispc::DDBVolume_create(this,
(int)getVoxelType(),
(const ispc::vec3i&)dimensions,
(const ispc::vec3i&)ddBlocks,
(const ispc::vec3i&)blockSize,
ddBlock);
if (!ispcEquivalent) {
throw std::runtime_error("could not create create data distributed "
"volume");
}
}
// A volume type with internal data-distribution. needs a renderer
// that is capable of data-parallel rendering!
OSP_REGISTER_VOLUME(DataDistributedBlockedVolume, data_distributed_volume);
#endif
} // ::ospray
<|endoftext|> |
<commit_before>#include "agent.h"
#include "environment.h"
#include "errors.h"
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <cassert>
Strategy ConvertToStrategy(const std::string& identifier) {
if(identifier.size() == 1) {
switch(identifier[0]) {
case 'L': return BreadthFirstStrategy;
case 'P': return LimitedDepthFirstStrategy;
case 'A': throw input_error("Strategy not yet implemented.");
default:
/* Nothing */;
}
}
throw input_error("Unknown strategy: '" + identifier + "'");
return Strategy();
}
void openFile(const std::string& filename, MapMatrix& matrix, std::set<Position>& gold_locations) {
std::ifstream input(filename);
if(!input.is_open())
throw input_error("Unable to open file '" + filename + "'.");
matrix.clear();
gold_locations.clear();
std::string line;
getline(input, line);
int size;
try {
size = stoi(line);
} catch(const std::invalid_argument&) {
throw input_error("'" + line + "' is not an int.");
} catch(const std::out_of_range&) {
throw input_error("'" + line + "' is out of range, doesn't fit in an int.");
}
if(size < 1 || size > 50)
throw input_error("Invalid size, size must be in range [1, 50].");
matrix.resize(size);
for (int j = 0; j < matrix.size(); ++j) {
auto& matrix_line = matrix[j];
getline(input, line);
if(line.size() != matrix_line.size())
throw input_error("'" + line + "' size doesn't match declared size.");
for (std::string::size_type i = 0; i < line.size(); ++i) {
switch (line[i]) {
case '*':
gold_locations.insert(Position(static_cast<int>(i),
static_cast<int>(j)));
// No break on purpose.
case '0':
matrix_line[i] = false; break;
case '1':
matrix_line[i] = true; break;
default:
throw input_error(std::string("Unknown character '") + line[i] + "' on line ");
}
}
}
if (static_cast<int>(gold_locations.size()) != matrix.size() / 2)
throw input_error("Wrong ammount of gold locations. Expected "
+ std::to_string(matrix.size() / 2)
+ " got " + std::to_string(gold_locations.size()));
assert(matrix.size() == size);
}
int main(int argc, char* argv[])
try {
if(argc != 3) {
fprintf(stderr, "Usage: %s <map-file-path> <search-type>\n", argv[0]);
return EXIT_SUCCESS;
}
Environment env;
openFile(argv[1], env.data().matrix_, env.data().gold_locations_);
env.set_agent(std::unique_ptr<Agent>(new Agent(ConvertToStrategy(argv[2]))));
auto result = env.Run();
printf("%d pontos\n", env.data().CalculateScore(*result));
return 0;
} catch(const input_error& err) {
fprintf(stderr, "Input error: %s\n", err.what());
return EXIT_FAILURE;
}
<commit_msg>Print the result path.<commit_after>#include "agent.h"
#include "environment.h"
#include "errors.h"
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <cassert>
char ActionToChar(Action a) {
switch (a) {
case Action::MOVE_LEFT: return 'E';
case Action::MOVE_UP: return 'C';
case Action::MOVE_RIGHT: return 'D';
case Action::MOVE_DOWN: return 'B';
case Action::PICK_GOLD: return 'P';
default: break;
}
throw input_error("Converting Action with no textual representation.");
return '\0';
}
Strategy ConvertToStrategy(const std::string& identifier) {
if(identifier.size() == 1) {
switch(identifier[0]) {
case 'L': return BreadthFirstStrategy;
case 'P': return LimitedDepthFirstStrategy;
case 'A': throw input_error("Strategy not yet implemented.");
default:
/* Nothing */;
}
}
throw input_error("Unknown strategy: '" + identifier + "'");
return Strategy();
}
void openFile(const std::string& filename, MapMatrix& matrix, std::set<Position>& gold_locations) {
std::ifstream input(filename);
if(!input.is_open())
throw input_error("Unable to open file '" + filename + "'.");
matrix.clear();
gold_locations.clear();
std::string line;
getline(input, line);
int size;
try {
size = stoi(line);
} catch(const std::invalid_argument&) {
throw input_error("'" + line + "' is not an int.");
} catch(const std::out_of_range&) {
throw input_error("'" + line + "' is out of range, doesn't fit in an int.");
}
if(size < 1 || size > 50)
throw input_error("Invalid size, size must be in range [1, 50].");
matrix.resize(size);
for (int j = 0; j < matrix.size(); ++j) {
auto& matrix_line = matrix[j];
getline(input, line);
if(line.size() != matrix_line.size())
throw input_error("'" + line + "' size doesn't match declared size.");
for (std::string::size_type i = 0; i < line.size(); ++i) {
switch (line[i]) {
case '*':
gold_locations.insert(Position(static_cast<int>(i),
static_cast<int>(j)));
// No break on purpose.
case '0':
matrix_line[i] = false; break;
case '1':
matrix_line[i] = true; break;
default:
throw input_error(std::string("Unknown character '") + line[i] + "' on line ");
}
}
}
if (static_cast<int>(gold_locations.size()) != matrix.size() / 2)
throw input_error("Wrong ammount of gold locations. Expected "
+ std::to_string(matrix.size() / 2)
+ " got " + std::to_string(gold_locations.size()));
assert(matrix.size() == size);
}
int main(int argc, char* argv[])
try {
if(argc != 3) {
fprintf(stderr, "Usage: %s <map-file-path> <search-type>\n", argv[0]);
return EXIT_SUCCESS;
}
Environment env;
openFile(argv[1], env.data().matrix_, env.data().gold_locations_);
env.set_agent(std::unique_ptr<Agent>(new Agent(ConvertToStrategy(argv[2]))));
auto result = env.Run();
printf("%d pontos\n", env.data().CalculateScore(*result));
for (Action a : result->CreateActionList())
printf("%c ", ActionToChar(a));
puts("");
return 0;
} catch(const input_error& err) {
fprintf(stderr, "Input error: %s\n", err.what());
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <boost/algorithm/string.hpp>
#include <osquery/flags.h>
#include <osquery/logger.h>
#include "osquery/core/conversions.h"
#include "osquery/events/linux/auditeventpublisher.h"
#include "osquery/tables/events/linux/selinux_events.h"
namespace osquery {
FLAG(bool,
audit_allow_selinux_events,
false,
"Allow the audit publisher to process audit events");
REGISTER(SELinuxEventSubscriber, "event_subscriber", "selinux_events");
// Depend on the external getUptime table method.
namespace tables {
extern long getUptime();
}
Status SELinuxEventSubscriber::init() {
if (!FLAGS_audit_allow_selinux_events) {
return Status(1, "Subscriber disabled via configuration");
}
auto sc = createSubscriptionContext();
subscribe(&SELinuxEventSubscriber::Callback, sc);
return Status(0, "OK");
}
Status SELinuxEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
std::vector<Row> emitted_row_list;
auto status = ProcessEvents(emitted_row_list, ec->audit_events);
if (!status.ok()) {
return status;
}
for (auto& row : emitted_row_list) {
add(row);
}
return Status(0, "Ok");
}
Status SELinuxEventSubscriber::ProcessEvents(
std::vector<Row>& emitted_row_list,
const std::vector<AuditEvent>& event_list) noexcept {
emitted_row_list.clear();
for (const auto& event : event_list) {
if (event.type != AuditEvent::Type::SELinux) {
continue;
}
for (const auto& record : event.record_list) {
Row r;
auto record_pretty_name_it = kSELinuxRecordLabels.find(record.type);
if (record_pretty_name_it == kSELinuxRecordLabels.end()) {
r["type"] = std::to_string(record.type);
} else {
r["type"] = record_pretty_name_it->second;
}
r["message"] = record.raw_data;
r["uptime"] = std::to_string(tables::getUptime());
emitted_row_list.push_back(r);
}
}
return Status(0, "Ok");
}
const std::set<int>& SELinuxEventSubscriber::GetEventSet() noexcept {
return kSELinuxEventList;
}
} // namespace osquery
<commit_msg>bug: Fix SELinux events rebase (#4684)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <boost/algorithm/string.hpp>
#include <osquery/flags.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include "osquery/core/conversions.h"
#include "osquery/events/linux/auditeventpublisher.h"
#include "osquery/tables/events/linux/selinux_events.h"
namespace osquery {
FLAG(bool,
audit_allow_selinux_events,
false,
"Allow the audit publisher to process audit events");
REGISTER(SELinuxEventSubscriber, "event_subscriber", "selinux_events");
// Depend on the external getUptime table method.
namespace tables {
extern long getUptime();
}
Status SELinuxEventSubscriber::init() {
if (!FLAGS_audit_allow_selinux_events) {
return Status(1, "Subscriber disabled via configuration");
}
auto sc = createSubscriptionContext();
subscribe(&SELinuxEventSubscriber::Callback, sc);
return Status(0, "OK");
}
Status SELinuxEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
std::vector<Row> emitted_row_list;
auto status = ProcessEvents(emitted_row_list, ec->audit_events);
if (!status.ok()) {
return status;
}
for (auto& row : emitted_row_list) {
add(row);
}
return Status(0, "Ok");
}
Status SELinuxEventSubscriber::ProcessEvents(
std::vector<Row>& emitted_row_list,
const std::vector<AuditEvent>& event_list) noexcept {
emitted_row_list.clear();
for (const auto& event : event_list) {
if (event.type != AuditEvent::Type::SELinux) {
continue;
}
for (const auto& record : event.record_list) {
Row r;
auto record_pretty_name_it = kSELinuxRecordLabels.find(record.type);
if (record_pretty_name_it == kSELinuxRecordLabels.end()) {
r["type"] = std::to_string(record.type);
} else {
r["type"] = record_pretty_name_it->second;
}
r["message"] = record.raw_data;
r["uptime"] = std::to_string(tables::getUptime());
emitted_row_list.push_back(r);
}
}
return Status(0, "Ok");
}
const std::set<int>& SELinuxEventSubscriber::GetEventSet() noexcept {
return kSELinuxEventList;
}
} // namespace osquery
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/regex.hpp>
#include <osquery/tables/system/system_utils.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/tables.h>
#include <osquery/utils/conversions/split.h>
namespace fs = boost::filesystem;
namespace alg = boost::algorithm;
namespace osquery {
namespace tables {
/// Location of the kernel panic crash logs in OS X
const std::string kDiagnosticReportsPath = "/Library/Logs/DiagnosticReports";
/// List of all register values we wish to catch
const std::set<std::string> kKernelRegisters = {
"CR0",
"RAX",
"RSP",
"R8",
"R12",
"RFL",
};
/// List of the days of the Week, used to grab our timestamp.
const std::set<std::string> kDays = {"Mon", "Tue", "Wed", "Thu", "Fri"};
/// Map of the values we currently parse out of the log file
const std::map<std::string, std::string> kKernelPanicKeys = {
{"dependency", "dependencies"},
{"BSD process name corresponding to current thread", "name"},
{"System model name", "system_model"},
{"System uptime in nanoseconds", "uptime"},
};
void readKernelPanic(const std::string& appLog, QueryData& results) {
Row r;
r["path"] = appLog;
std::string content;
if (!readFile(appLog, content).ok()) {
return;
}
boost::regex rxSpaces("\\s+");
auto lines = osquery::split(content, "\n");
for (auto it = lines.begin(); it != lines.end(); it++) {
auto line = *it;
boost::trim(line);
auto toks = osquery::split(line, ":");
if (toks.size() == 0) {
continue;
}
auto timeTokens = osquery::split(toks[0], " ");
if (timeTokens.size() >= 1 && kDays.count(timeTokens[0]) > 0) {
r["time"] = line;
}
if (kKernelRegisters.count(toks[0]) > 0) {
auto registerTokens = osquery::split(line, ",");
if (registerTokens.size() == 0) {
continue;
}
for (auto& tok_ : registerTokens) {
auto regHolder = osquery::split(tok_, ":");
if (regHolder.size() != 2) {
continue;
}
auto reg = std::move(regHolder[0]);
auto val = std::move(regHolder[1]);
if (reg.size() > 0 && val.size() > 0) {
std::string regLine = reg + ":" + val;
r["registers"] += (r["registers"].empty()) ? std::move(regLine)
: " " + std::move(regLine);
}
}
} else if (boost::starts_with(toks[0], "last loaded kext at") &&
toks.size() == 2) {
r["last_loaded"] = boost::regex_replace(toks[1], rxSpaces, " ");
} else if (boost::starts_with(toks[0], "last unloaded kext at") &&
toks.size() == 2) {
r["last_unloaded"] = boost::regex_replace(toks[1], rxSpaces, " ");
} else if (boost::starts_with(toks[0], "Backtrace") &&
std::next(it) != lines.end()) {
r["frame_backtrace"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Kernel Extensions in backtrace") &&
std::next(it) != lines.end()) {
r["module_backtrace"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Mac OS version") &&
std::next(it) != lines.end()) {
r["os_version"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Kernel version") &&
std::next(it) != lines.end()) {
r["kernel_version"] = *(std::next(it));
} else if (kKernelPanicKeys.count(toks[0]) != 0 && toks.size() == 2) {
r[kKernelPanicKeys.at(toks[0])] = toks[1];
}
}
results.push_back(r);
}
QueryData genKernelPanics(QueryContext& context) {
QueryData results;
if (context.constraints["uid"].notExistsOrMatches("0")) {
std::vector<std::string> files;
if (listFilesInDirectory(kDiagnosticReportsPath, files)) {
for (const auto& lf : files) {
if (alg::ends_with(lf, ".panic")) {
readKernelPanic(lf, results);
}
}
}
}
return results;
}
}
}
<commit_msg>Include weekends on the kernel_panics table (#5298)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/regex.hpp>
#include <osquery/tables/system/system_utils.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/tables.h>
#include <osquery/utils/conversions/split.h>
namespace fs = boost::filesystem;
namespace alg = boost::algorithm;
namespace osquery {
namespace tables {
/// Location of the kernel panic crash logs in OS X
const std::string kDiagnosticReportsPath = "/Library/Logs/DiagnosticReports";
/// List of all register values we wish to catch
const std::set<std::string> kKernelRegisters = {
"CR0",
"RAX",
"RSP",
"R8",
"R12",
"RFL",
};
/// List of the days of the Week, used to grab our timestamp.
const std::set<std::string> kDays = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
/// Map of the values we currently parse out of the log file
const std::map<std::string, std::string> kKernelPanicKeys = {
{"dependency", "dependencies"},
{"BSD process name corresponding to current thread", "name"},
{"System model name", "system_model"},
{"System uptime in nanoseconds", "uptime"},
};
void readKernelPanic(const std::string& appLog, QueryData& results) {
Row r;
r["path"] = appLog;
std::string content;
if (!readFile(appLog, content).ok()) {
return;
}
boost::regex rxSpaces("\\s+");
auto lines = osquery::split(content, "\n");
for (auto it = lines.begin(); it != lines.end(); it++) {
auto line = *it;
boost::trim(line);
auto toks = osquery::split(line, ":");
if (toks.size() == 0) {
continue;
}
auto timeTokens = osquery::split(toks[0], " ");
if (timeTokens.size() >= 1 && kDays.count(timeTokens[0]) > 0) {
r["time"] = line;
}
if (kKernelRegisters.count(toks[0]) > 0) {
auto registerTokens = osquery::split(line, ",");
if (registerTokens.size() == 0) {
continue;
}
for (auto& tok_ : registerTokens) {
auto regHolder = osquery::split(tok_, ":");
if (regHolder.size() != 2) {
continue;
}
auto reg = std::move(regHolder[0]);
auto val = std::move(regHolder[1]);
if (reg.size() > 0 && val.size() > 0) {
std::string regLine = reg + ":" + val;
r["registers"] += (r["registers"].empty()) ? std::move(regLine)
: " " + std::move(regLine);
}
}
} else if (boost::starts_with(toks[0], "last loaded kext at") &&
toks.size() == 2) {
r["last_loaded"] = boost::regex_replace(toks[1], rxSpaces, " ");
} else if (boost::starts_with(toks[0], "last unloaded kext at") &&
toks.size() == 2) {
r["last_unloaded"] = boost::regex_replace(toks[1], rxSpaces, " ");
} else if (boost::starts_with(toks[0], "Backtrace") &&
std::next(it) != lines.end()) {
r["frame_backtrace"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Kernel Extensions in backtrace") &&
std::next(it) != lines.end()) {
r["module_backtrace"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Mac OS version") &&
std::next(it) != lines.end()) {
r["os_version"] = *(std::next(it));
} else if (boost::starts_with(toks[0], "Kernel version") &&
std::next(it) != lines.end()) {
r["kernel_version"] = *(std::next(it));
} else if (kKernelPanicKeys.count(toks[0]) != 0 && toks.size() == 2) {
r[kKernelPanicKeys.at(toks[0])] = toks[1];
}
}
results.push_back(r);
}
QueryData genKernelPanics(QueryContext& context) {
QueryData results;
if (context.constraints["uid"].notExistsOrMatches("0")) {
std::vector<std::string> files;
if (listFilesInDirectory(kDiagnosticReportsPath, files)) {
for (const auto& lf : files) {
if (alg::ends_with(lf, ".panic")) {
readKernelPanic(lf, results);
}
}
}
}
return results;
}
}
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Main executable
* @author Lorenz Meier <[email protected]>
*
*/
#include <QtGlobal>
#include <QApplication>
#include <QSslSocket>
#include <QProcessEnvironment>
#include "QGCApplication.h"
#define SINGLE_INSTANCE_PORT 14499
#ifndef __mobile__
#include "QGCSerialPortInfo.h"
#endif
#ifdef QT_DEBUG
#ifndef __mobile__
#include "UnitTest.h"
#endif
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif
#ifdef QGC_ENABLE_BLUETOOTH
#include <QtBluetooth/QBluetoothSocket>
#endif
#include <iostream>
/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif
#ifndef __mobile__
Q_DECLARE_METATYPE(QGCSerialPortInfo)
#endif
#ifdef Q_OS_WIN
/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] at %2:%3 - \"%4\"").arg(symbols[type]).arg(context.file).arg(context.line).arg(msg);
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
Q_UNUSED(reportType);
std::cerr << message << std::endl; // Output message to stderr
*returnValue = 0; // Don't break into debugger
return true; // We handled this fully ourselves
}
#endif
#ifdef __android__
#include <jni.h>
#include "qserialport.h"
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
Q_UNUSED(reserved);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
QSerialPort::setNativeMethods();
return JNI_VERSION_1_6;
}
#endif
/**
* @brief Starts the application
*
* @param argc Number of commandline arguments
* @param argv Commandline arguments
* @return exit code, 0 for normal exit and !=0 for error cases
*/
int main(int argc, char *argv[])
{
#ifndef __mobile__
//-- Test for another instance already running. If that's the case, we simply exit.
QHostAddress host("127.0.0.1");
QUdpSocket socket;
if(!socket.bind(host, SINGLE_INSTANCE_PORT, QAbstractSocket::DontShareAddress)) {
qWarning() << "Another instance already running. Exiting.";
exit(-1);
}
#endif
#ifdef Q_OS_MAC
#ifndef __ios__
// Prevent Apple's app nap from screwing us over
// tip: the domain can be cross-checked on the command line with <defaults domains>
QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES");
#endif
#endif
#ifdef Q_OS_WIN
// install the message handler
qInstallMessageHandler(msgHandler);
// Set our own OpenGL buglist
qputenv("QT_OPENGL_BUGLIST", ":/opengl/resources/opengl/buglist.json");
if (QCoreApplication::arguments().contains(QStringLiteral("-angle"))) {
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
} else if (QCoreApplication::arguments().contains(QStringLiteral("-swrast"))) {
QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
}
#endif
// The following calls to qRegisterMetaType are done to silence debug output which warns
// that we use these types in signals, and without calling qRegisterMetaType we can't queue
// these signals. In general we don't queue these signals, but we do what the warning says
// anyway to silence the debug output.
#ifndef __ios__
qRegisterMetaType<QSerialPort::SerialPortError>();
#endif
#ifdef QGC_ENABLE_BLUETOOTH
qRegisterMetaType<QBluetoothSocket::SocketError>();
qRegisterMetaType<QBluetoothServiceInfo>();
#endif
qRegisterMetaType<QAbstractSocket::SocketError>();
#ifndef __mobile__
qRegisterMetaType<QGCSerialPortInfo>();
#endif
// We statically link our own QtLocation plugin
#ifdef Q_OS_WIN
// In Windows, the compiler doesn't see the use of the class created by Q_IMPORT_PLUGIN
#pragma warning( disable : 4930 4101 )
#endif
Q_IMPORT_PLUGIN(QGeoServiceProviderFactoryQGC)
bool runUnitTests = false; // Run unit tests
#ifdef QT_DEBUG
// We parse a small set of command line options here prior to QGCApplication in order to handle the ones
// which need to be handled before a QApplication object is started.
bool stressUnitTests = false; // Stress test unit tests
bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes
QString unitTestOptions;
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--unittest", &runUnitTests, &unitTestOptions },
{ "--unittest-stress", &stressUnitTests, &unitTestOptions },
{ "--no-windows-assert-ui", &quietWindowsAsserts, NULL },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
if (stressUnitTests) {
runUnitTests = true;
}
if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
_CrtSetReportHook(WindowsCrtReportHook);
#endif
}
#ifdef Q_OS_WIN
if (runUnitTests) {
// Don't pop up Windows Error Reporting dialog when app crashes. This prevents TeamCity from
// hanging.
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
}
#endif
#endif // QT_DEBUG
QGCApplication* app = new QGCApplication(argc, argv, runUnitTests);
Q_CHECK_PTR(app);
// There appears to be a threading issue in qRegisterMetaType which can cause it to throw a qWarning
// about duplicate type converters. This is caused by a race condition in the Qt code. Still working
// with them on tracking down the bug. For now we register the type which is giving us problems here
// while we only have the main thread. That should prevent it from hitting the race condition later
// on in the code.
qRegisterMetaType<QList<QPair<QByteArray,QByteArray> > >();
app->_initCommon();
int exitCode = 0;
#ifndef __mobile__
#ifdef QT_DEBUG
if (runUnitTests) {
for (int i=0; i < (stressUnitTests ? 20 : 1); i++) {
if (!app->_initForUnitTests()) {
return -1;
}
// Run the test
int failures = UnitTest::run(unitTestOptions);
if (failures == 0) {
qDebug() << "ALL TESTS PASSED";
exitCode = 0;
} else {
qDebug() << failures << " TESTS FAILED!";
exitCode = -failures;
break;
}
}
} else
#endif
#endif
{
if (!app->_initForNormalAppBoot()) {
return -1;
}
exitCode = app->exec();
}
delete app;
qDebug() << "After app delete";
return exitCode;
}
<commit_msg>Don't try to use QCoreApplication::arguments before an app is created<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Main executable
* @author Lorenz Meier <[email protected]>
*
*/
#include <QtGlobal>
#include <QApplication>
#include <QSslSocket>
#include <QProcessEnvironment>
#include "QGCApplication.h"
#define SINGLE_INSTANCE_PORT 14499
#ifndef __mobile__
#include "QGCSerialPortInfo.h"
#endif
#ifdef QT_DEBUG
#ifndef __mobile__
#include "UnitTest.h"
#endif
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif
#ifdef QGC_ENABLE_BLUETOOTH
#include <QtBluetooth/QBluetoothSocket>
#endif
#include <iostream>
/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif
#ifndef __mobile__
Q_DECLARE_METATYPE(QGCSerialPortInfo)
#endif
#ifdef Q_OS_WIN
/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] at %2:%3 - \"%4\"").arg(symbols[type]).arg(context.file).arg(context.line).arg(msg);
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
Q_UNUSED(reportType);
std::cerr << message << std::endl; // Output message to stderr
*returnValue = 0; // Don't break into debugger
return true; // We handled this fully ourselves
}
#endif
#ifdef __android__
#include <jni.h>
#include "qserialport.h"
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
Q_UNUSED(reserved);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
QSerialPort::setNativeMethods();
return JNI_VERSION_1_6;
}
#endif
/**
* @brief Starts the application
*
* @param argc Number of commandline arguments
* @param argv Commandline arguments
* @return exit code, 0 for normal exit and !=0 for error cases
*/
int main(int argc, char *argv[])
{
#ifndef __mobile__
//-- Test for another instance already running. If that's the case, we simply exit.
QHostAddress host("127.0.0.1");
QUdpSocket socket;
if(!socket.bind(host, SINGLE_INSTANCE_PORT, QAbstractSocket::DontShareAddress)) {
qWarning() << "Another instance already running. Exiting.";
exit(-1);
}
#endif
#ifdef Q_OS_MAC
#ifndef __ios__
// Prevent Apple's app nap from screwing us over
// tip: the domain can be cross-checked on the command line with <defaults domains>
QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES");
#endif
#endif
#ifdef Q_OS_WIN
// install the message handler
qInstallMessageHandler(msgHandler);
// Set our own OpenGL buglist
qputenv("QT_OPENGL_BUGLIST", ":/opengl/resources/opengl/buglist.json");
// Allow for command line override of renderer
for (int i = 0; i < argc; i++) {
const QString arg(argv[i]);
if (arg == QStringLiteral("-angle")) {
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
break;
} else if (arg == QStringLiteral("-swrast")) {
QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
break;
}
}
#endif
// The following calls to qRegisterMetaType are done to silence debug output which warns
// that we use these types in signals, and without calling qRegisterMetaType we can't queue
// these signals. In general we don't queue these signals, but we do what the warning says
// anyway to silence the debug output.
#ifndef __ios__
qRegisterMetaType<QSerialPort::SerialPortError>();
#endif
#ifdef QGC_ENABLE_BLUETOOTH
qRegisterMetaType<QBluetoothSocket::SocketError>();
qRegisterMetaType<QBluetoothServiceInfo>();
#endif
qRegisterMetaType<QAbstractSocket::SocketError>();
#ifndef __mobile__
qRegisterMetaType<QGCSerialPortInfo>();
#endif
// We statically link our own QtLocation plugin
#ifdef Q_OS_WIN
// In Windows, the compiler doesn't see the use of the class created by Q_IMPORT_PLUGIN
#pragma warning( disable : 4930 4101 )
#endif
Q_IMPORT_PLUGIN(QGeoServiceProviderFactoryQGC)
bool runUnitTests = false; // Run unit tests
#ifdef QT_DEBUG
// We parse a small set of command line options here prior to QGCApplication in order to handle the ones
// which need to be handled before a QApplication object is started.
bool stressUnitTests = false; // Stress test unit tests
bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes
QString unitTestOptions;
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--unittest", &runUnitTests, &unitTestOptions },
{ "--unittest-stress", &stressUnitTests, &unitTestOptions },
{ "--no-windows-assert-ui", &quietWindowsAsserts, NULL },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
if (stressUnitTests) {
runUnitTests = true;
}
if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
_CrtSetReportHook(WindowsCrtReportHook);
#endif
}
#ifdef Q_OS_WIN
if (runUnitTests) {
// Don't pop up Windows Error Reporting dialog when app crashes. This prevents TeamCity from
// hanging.
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
}
#endif
#endif // QT_DEBUG
QGCApplication* app = new QGCApplication(argc, argv, runUnitTests);
Q_CHECK_PTR(app);
// There appears to be a threading issue in qRegisterMetaType which can cause it to throw a qWarning
// about duplicate type converters. This is caused by a race condition in the Qt code. Still working
// with them on tracking down the bug. For now we register the type which is giving us problems here
// while we only have the main thread. That should prevent it from hitting the race condition later
// on in the code.
qRegisterMetaType<QList<QPair<QByteArray,QByteArray> > >();
app->_initCommon();
int exitCode = 0;
#ifndef __mobile__
#ifdef QT_DEBUG
if (runUnitTests) {
for (int i=0; i < (stressUnitTests ? 20 : 1); i++) {
if (!app->_initForUnitTests()) {
return -1;
}
// Run the test
int failures = UnitTest::run(unitTestOptions);
if (failures == 0) {
qDebug() << "ALL TESTS PASSED";
exitCode = 0;
} else {
qDebug() << failures << " TESTS FAILED!";
exitCode = -failures;
break;
}
}
} else
#endif
#endif
{
if (!app->_initForNormalAppBoot()) {
return -1;
}
exitCode = app->exec();
}
delete app;
qDebug() << "After app delete";
return exitCode;
}
<|endoftext|> |
<commit_before>#include <libnova/libnova.h>
#include <deque>
#include <fstream>
#include <iostream>
#include <sstream>
#include "config.hh"
#include "drawer.hh"
#include "exceptions.hh"
#include "projection.hh"
#include "scene_storage.hh"
#include "stars.hh"
#include "svg_painter.hh"
#include "types.hh"
/*
struct ScenePrinter
: boost::static_visitor<>
{
void operator()(const scene::Object & o)
{
// std::cout << '{' << o.pos.x << ',' << o.pos.y << '}';
}
void operator()(const scene::Group & g)
{
std::cout << "g(" << g.id << "){";
for_each(g.elements.begin(), g.elements.end(),
boost::apply_visitor(*this));
std::cout << "}";
}
void operator()(const scene::Rectangle &)
{
}
void operator()(const scene::Line &)
{}
void operator()(const scene::Path & p)
{
std::cout << p.path.size() << ',';
}
void operator()(const scene::Text &)
{}
};
*/
int main(int arc, char * arv[])
{
try
{
std::cout << "Processing configs... " << std::flush;
Config config(arc, arv);
std::cout << "done." << std::endl;
// return 0;
ln_lnlat_posn observer(config.location());
const double t(config.t());
CanvasPoint canvas(config.canvas_dimensions());
ln_equ_posn apparent_canvas(config.projection_dimensions()),
center(config.projection_centre());
std::shared_ptr<Projection> projection(ProjectionFactory::create(config.projection_type(),
canvas, apparent_canvas, center));
if (config.projection_level() == "horizon")
{
ln_hrz_posn hor;
ln_get_hrz_from_equ(¢er, &observer, t, &hor);
ln_hrz_posn hor2(hor);
hor2.az += 1.0;
ln_equ_posn equ;
ln_get_equ_from_hrz(&hor2, &observer, t, &equ);
CanvasPoint cp(equ.ra - center.ra, equ.dec - center.dec);
if (cp.x > 180.)
cp.x -= 360.;
std::cout << cp.x << ", " << cp.y << std::endl;
projection->rotate_to_level(cp);
}
std::string style;
if (! config.stylesheet().empty())
{
std::ifstream f(config.stylesheet());
if (! f)
throw ConfigError("Stylesheet '" + config.stylesheet() + "' couldn't be opened.");
std::stringstream buf;
buf << f.rdbuf();
style = buf.str();
}
Drawer drawer(canvas, config.canvas_margin(), style);
drawer.set_projection(projection);
scene::Storage scn(projection);
{
scene::Group gr{"rectangle", "background", {}};
gr.elements.push_back(scene::Rectangle{CanvasPoint(-canvas.x / 2., -canvas.y / 2.),
CanvasPoint(canvas.x, canvas.y)});
scn.add_group(std::move(gr));
}
std::cout << "Loading catalogues... " << std::flush;
for (auto c(config.begin_catalogues()), c_end(config.end_catalogues());
c != c_end; ++c)
{
std::cout << c->path() << ", " << std::flush;
c->load();
std::deque<Star> stars;
std::copy(c->begin_stars(), c->end_stars(), std::back_inserter(stars));
drawer.draw(stars, c->path());
{
std::deque<scene::Element> objs;
for (auto const & star : stars)
{
objs.push_back(scene::Object{projection->project(star.pos_), star.vmag_});
}
scn.add_group(scene::Group{"catalog", c->path(), std::move(objs)});
}
}
std::cout << "done." << std::endl;
std::cout << "Loading solar objects..." << std::flush;
SolarObjectManager solar_manager;
{
std::deque<std::shared_ptr<const SolarObject>> planets;
auto planet_names(config.planets());
for (auto const & p : planet_names)
{
planets.push_back(solar_manager.get(p));
}
drawer.draw(planets, config.t(), "planets", Drawer::magnitudo, config.planets_labels());
{
std::deque<scene::Element> objs;
for (auto const & planet : planets)
{
objs.push_back(scene::Object{projection->project(planet->get_equ_coords(t)), planet->get_magnitude(t)});
}
scn.add_group(scene::Group{"solar_system", "planets", std::move(objs)});
}
}
if (config.moon())
{
auto const & moon{*solar_manager.get("moon")};
drawer.draw(moon, config.t(), Drawer::sdiam, true);
std::deque<scene::Element> obj;
obj.push_back(scene::Object{projection->project(moon.get_equ_coords(t)), moon.get_magnitude(t)});
scn.add_group(scene::Group{"solar_system", "moon",
std::move(obj)
});
}
if (config.sun())
{
auto const & sun{*solar_manager.get("sun")};
drawer.draw(sun, config.t(), Drawer::sdiam, true);
std::deque<scene::Element> obj;
obj.push_back(scene::Object{projection->project(sun.get_equ_coords(t)), sun.get_magnitude(t)});
scn.add_group(scene::Group{"solar_system", "sun",
std::move(obj)
});
}
std::cout << "done." << std::endl;
{
std::cout << "Drawing tracks... " << std::flush;
scene::Group tracks{"tracks", "track_container", {}};
for (auto track(config.begin_tracks()), track_end(config.end_tracks());
track != track_end; ++track)
{
std::cout << track->name << " " << std::flush;
drawer.draw(*track, solar_manager.get(track->name));
auto beziers(create_bezier_from_track(projection, *track, solar_manager.get(track->name)));
for (auto const & b : beziers)
{
tracks.elements.push_back(scene::Path{b});
}
}
scn.add_group(std::move(tracks));
std::cout << "done." << std::endl;
}
{
scene::Group meridians{"meridians", "meridians_container", {}};
for (double x(0); x < 360.1; x += 15.)
{
std::vector<ln_equ_posn> path;
for (double y(-88.); y < 88.1; y += 2.)
{
path.push_back({x, y});
}
drawer.draw(path);
drawer.draw(stringify(angle{x}, as_hour), {x, 0.});
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
meridians.elements.push_back(scene::Path{b});
}
meridians.elements.push_back(scene::Text{stringify(angle{x}, as_hour), projection->project({x, 0})});
}
scn.add_group(std::move(meridians));
}
{
scene::Group parallels{"parallels", "parallels_container", {}};
for (double y(-60); y < 60.1; y += 10.)
{
std::vector<ln_equ_posn> path;
for (double x(0.); x < 360.1; x += 2.)
{
path.push_back({x, y});
}
drawer.draw(path);
drawer.draw(stringify(angle{y}, as_degree), {0., y});
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
parallels.elements.push_back(scene::Path{b});
}
parallels.elements.push_back(scene::Text{stringify(angle{y}, as_degree), projection->project({0., y})});
}
scn.add_group(std::move(parallels));
}
// ecliptic
{
std::vector<ln_equ_posn> path;
double t(config.t());
for (double x(0); x < 360.1; x += 2.)
{
ln_lnlat_posn in{x, 0.};
ln_equ_posn out;
ln_get_equ_from_ecl(&in, t, &out);
path.push_back(out);
}
drawer.draw(path, 0.2);
scene::Group ecliptic{"ecliptic", "ecliptic_container", {}};
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
ecliptic.elements.push_back(scene::Path{b});
}
scn.add_group(std::move(ecliptic));
}
// horizon
{
std::vector<ln_equ_posn> path;
for (double x(0); x < 360.1; x += 2.)
{
ln_hrz_posn in{x, 0.};
ln_equ_posn out;
ln_get_equ_from_hrz(&in, &observer, t, &out);
path.push_back(out);
}
drawer.draw(path, 0.3);
scene::Group horizon{"horizon", "horizon_container", {}};
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
horizon.elements.push_back(scene::Path{b});
}
scn.add_group(std::move(horizon));
}
drawer.store(config.output().c_str());
std::ofstream of("test-2.svg");
if (! of)
throw std::runtime_error("Can't open file '" + std::string("test-2.svg") + "' for writing " + std::strerror(errno));
SvgPainter painter(of, canvas, config.canvas_margin(), style);
boost::apply_visitor(painter, scn);
}
catch (const ConfigError & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e)
{
std::cerr << "Uncaught std::exception:\n\t" << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>update classes and ids<commit_after>#include <libnova/libnova.h>
#include <deque>
#include <fstream>
#include <iostream>
#include <sstream>
#include "config.hh"
#include "drawer.hh"
#include "exceptions.hh"
#include "projection.hh"
#include "scene_storage.hh"
#include "stars.hh"
#include "svg_painter.hh"
#include "types.hh"
/*
struct ScenePrinter
: boost::static_visitor<>
{
void operator()(const scene::Object & o)
{
// std::cout << '{' << o.pos.x << ',' << o.pos.y << '}';
}
void operator()(const scene::Group & g)
{
std::cout << "g(" << g.id << "){";
for_each(g.elements.begin(), g.elements.end(),
boost::apply_visitor(*this));
std::cout << "}";
}
void operator()(const scene::Rectangle &)
{
}
void operator()(const scene::Line &)
{}
void operator()(const scene::Path & p)
{
std::cout << p.path.size() << ',';
}
void operator()(const scene::Text &)
{}
};
*/
int main(int arc, char * arv[])
{
try
{
std::cout << "Processing configs... " << std::flush;
Config config(arc, arv);
std::cout << "done." << std::endl;
// return 0;
ln_lnlat_posn observer(config.location());
const double t(config.t());
CanvasPoint canvas(config.canvas_dimensions());
ln_equ_posn apparent_canvas(config.projection_dimensions()),
center(config.projection_centre());
std::shared_ptr<Projection> projection(ProjectionFactory::create(config.projection_type(),
canvas, apparent_canvas, center));
if (config.projection_level() == "horizon")
{
ln_hrz_posn hor;
ln_get_hrz_from_equ(¢er, &observer, t, &hor);
ln_hrz_posn hor2(hor);
hor2.az += 1.0;
ln_equ_posn equ;
ln_get_equ_from_hrz(&hor2, &observer, t, &equ);
CanvasPoint cp(equ.ra - center.ra, equ.dec - center.dec);
if (cp.x > 180.)
cp.x -= 360.;
std::cout << cp.x << ", " << cp.y << std::endl;
projection->rotate_to_level(cp);
}
std::string style;
if (! config.stylesheet().empty())
{
std::ifstream f(config.stylesheet());
if (! f)
throw ConfigError("Stylesheet '" + config.stylesheet() + "' couldn't be opened.");
std::stringstream buf;
buf << f.rdbuf();
style = buf.str();
}
Drawer drawer(canvas, config.canvas_margin(), style);
drawer.set_projection(projection);
scene::Storage scn(projection);
{
scene::Group gr{"rectangle", "background", {}};
gr.elements.push_back(scene::Rectangle{CanvasPoint(-canvas.x / 2., -canvas.y / 2.),
CanvasPoint(canvas.x, canvas.y)});
scn.add_group(std::move(gr));
}
std::cout << "Loading catalogues... " << std::flush;
for (auto c(config.begin_catalogues()), c_end(config.end_catalogues());
c != c_end; ++c)
{
std::cout << c->path() << ", " << std::flush;
c->load();
std::deque<Star> stars;
std::copy(c->begin_stars(), c->end_stars(), std::back_inserter(stars));
drawer.draw(stars, c->path());
{
std::deque<scene::Element> objs;
for (auto const & star : stars)
{
objs.push_back(scene::Object{projection->project(star.pos_), star.vmag_});
}
scn.add_group(scene::Group{"catalog", c->path(), std::move(objs)});
}
}
std::cout << "done." << std::endl;
std::cout << "Loading solar objects..." << std::flush;
SolarObjectManager solar_manager;
{
std::deque<std::shared_ptr<const SolarObject>> planets;
auto planet_names(config.planets());
for (auto const & p : planet_names)
{
planets.push_back(solar_manager.get(p));
}
drawer.draw(planets, config.t(), "planets", Drawer::magnitudo, config.planets_labels());
{
std::deque<scene::Element> objs;
for (auto const & planet : planets)
{
objs.push_back(scene::Object{projection->project(planet->get_equ_coords(t)), planet->get_magnitude(t)});
}
scn.add_group(scene::Group{"solar_system", "planets", std::move(objs)});
}
}
if (config.moon())
{
auto const & moon{*solar_manager.get("moon")};
drawer.draw(moon, config.t(), Drawer::sdiam, true);
std::deque<scene::Element> obj;
obj.push_back(scene::Object{projection->project(moon.get_equ_coords(t)), moon.get_magnitude(t)});
scn.add_group(scene::Group{"solar_system", "moon",
std::move(obj)
});
}
if (config.sun())
{
auto const & sun{*solar_manager.get("sun")};
drawer.draw(sun, config.t(), Drawer::sdiam, true);
std::deque<scene::Element> obj;
obj.push_back(scene::Object{projection->project(sun.get_equ_coords(t)), sun.get_magnitude(t)});
scn.add_group(scene::Group{"solar_system", "sun",
std::move(obj)
});
}
std::cout << "done." << std::endl;
{
std::cout << "Drawing tracks... " << std::flush;
scene::Group tracks{"tracks", "track_container", {}};
for (auto track(config.begin_tracks()), track_end(config.end_tracks());
track != track_end; ++track)
{
std::cout << track->name << " " << std::flush;
drawer.draw(*track, solar_manager.get(track->name));
auto beziers(create_bezier_from_track(projection, *track, solar_manager.get(track->name)));
for (auto const & b : beziers)
{
tracks.elements.push_back(scene::Path{b});
}
}
scn.add_group(std::move(tracks));
std::cout << "done." << std::endl;
}
{
scene::Group meridians{"grid", "meridians", {}};
for (double x(0); x < 360.1; x += 15.)
{
std::vector<ln_equ_posn> path;
for (double y(-88.); y < 88.1; y += 2.)
{
path.push_back({x, y});
}
drawer.draw(path);
drawer.draw(stringify(angle{x}, as_hour), {x, 0.});
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
meridians.elements.push_back(scene::Path{b});
}
meridians.elements.push_back(scene::Text{stringify(angle{x}, as_hour), projection->project({x, 0})});
}
scn.add_group(std::move(meridians));
}
{
scene::Group parallels{"grid", "parallels", {}};
for (double y(-60); y < 60.1; y += 10.)
{
std::vector<ln_equ_posn> path;
for (double x(0.); x < 360.1; x += 2.)
{
path.push_back({x, y});
}
drawer.draw(path);
drawer.draw(stringify(angle{y}, as_degree), {0., y});
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
parallels.elements.push_back(scene::Path{b});
}
parallels.elements.push_back(scene::Text{stringify(angle{y}, as_degree), projection->project({0., y})});
}
scn.add_group(std::move(parallels));
}
// ecliptic
{
std::vector<ln_equ_posn> path;
double t(config.t());
for (double x(0); x < 360.1; x += 2.)
{
ln_lnlat_posn in{x, 0.};
ln_equ_posn out;
ln_get_equ_from_ecl(&in, t, &out);
path.push_back(out);
}
drawer.draw(path, 0.2);
scene::Group ecliptic{"grid", "ecliptic", {}};
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
ecliptic.elements.push_back(scene::Path{b});
}
scn.add_group(std::move(ecliptic));
}
// horizon
{
std::vector<ln_equ_posn> path;
for (double x(0); x < 360.1; x += 2.)
{
ln_hrz_posn in{x, 0.};
ln_equ_posn out;
ln_get_equ_from_hrz(&in, &observer, t, &out);
path.push_back(out);
}
drawer.draw(path, 0.3);
scene::Group horizon{"grid", "horizon", {}};
auto bezier{create_bezier_from_path(projection, path)};
for (auto const b : bezier)
{
horizon.elements.push_back(scene::Path{b});
}
scn.add_group(std::move(horizon));
}
drawer.store(config.output().c_str());
std::ofstream of("test-2.svg");
if (! of)
throw std::runtime_error("Can't open file '" + std::string("test-2.svg") + "' for writing " + std::strerror(errno));
SvgPainter painter(of, canvas, config.canvas_margin(), style);
boost::apply_visitor(painter, scn);
}
catch (const ConfigError & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e)
{
std::cerr << "Uncaught std::exception:\n\t" << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
extern "C" {
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <curl/curl.h>
#include <errno.h>
#include <sqlite3.h>
#include <getopt.h>
#include <libxml/xmlmemory.h>
#include "help.h"
#include "logger.h"
}
#include "localFileList.h"
#include "fileListStorage.h"
#include "amazonCredentials.h"
#include "remoteListOfFiles.h"
#include "upload.h"
#include "filePattern.h"
static char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) "s3.amazonaws.com",
*source=NULL, *databasePath=NULL, *databaseFilename= (char *)".files.sqlite3";
static int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0,
connectTimeout = 0, networkTimeout = 0, uploadThreads = 0;
FilePattern *excludeFilePattern;
FILE *logStream;
int logLevel = LOG_ERR;
int rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {
int res = remoteListOfFiles->downloadList();
if (res==LIST_FAILED) {
return LIST_FAILED;
}
LOG(LOG_INFO, "[MetaUpdate] Got %d files, updating meta information", remoteListOfFiles->count);
res = remoteListOfFiles->resolveMtimes();
if (res==LIST_FAILED) {
return LIST_FAILED;
}
if (dryRun) {
LOG(LOG_INFO, "[MetaUpdate] [dry] Skipped storing list of files");
return LIST_SUCCESS;
}
if (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {
LOG(LOG_FATAL, "[MetaUpdate] Failed to store list of files");
return LIST_FAILED;
} else {
return LIST_SUCCESS;
}
}
static char *endPoints[] = {
(char *) "s3.amazonaws.com",
(char *) "s3-us-west-2.amazonaws.com",
(char *) "s3-us-west-1.amazonaws.com",
(char *) "s3-eu-west-1.amazonaws.com",
(char *) "s3-ap-southeast-1.amazonaws.com",
(char *) "s3-ap-northeast-1.amazonaws.com",
(char *) "s3-sa-east-1.amazonaws.com",
NULL
};
int validateEndpoint(char *endPoint) {
int i=0;
while (char *e=endPoints[i++]) {
if (e && strcmp(e, endPoint)==0) {
return 1;
}
}
#ifdef TEST
if (strcmp(endPoint, "local")==0) {
printf("EndPoint for testing purposes engaged.\n");
return 1;
}
#endif
printf("--endPoint %s not valid, use one of:\n", endPoint);
i=0;
while (char *e=endPoints[i++]) {
printf("\t%s\n", e);
}
return 0;
}
char *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {
uint64_t len = strlen(databasePath)+strlen(databaseFilename)+2;
char *databaseFilePath = (char *) malloc(len);
databaseFilePath[0]=0;
strcat(databaseFilePath, databasePath);
strcat(databaseFilePath, "/");
strcat(databaseFilePath, databaseFilename);
return databaseFilePath;
}
void showVersion() {
printf("clarc version " VERSION " (c) 2012 Egor Egorov <[email protected]>\nMIT License | http://egorfine.com/clarc/\n");
}
int parseCommandline(int argc, char *argv[]) {
if (argc==1) {
showVersion();
printf("Perhaps, ask --help?\n");
exit(0);
}
static struct option longOpts[] = {
{ "accessKeyId", required_argument, NULL, 0 },
{ "secretAccessKey", required_argument, NULL, 0 },
{ "bucket", required_argument, NULL, 0 },
{ "endPoint", required_argument, NULL, 0 },
{ "public", no_argument, NULL, 0 },
{ "rrs", no_argument, NULL, 0 },
{ "rss", no_argument, NULL, 0 }, // common typo
{ "skipSsl", no_argument, NULL, 0 },
{ "connectTimeout", required_argument, NULL, 0 },
{ "networkTimeout", required_argument, NULL, 0 },
{ "uploadThreads", required_argument, NULL, 0 },
{ "source", required_argument, NULL, 0 },
{ "ddbPath", required_argument, NULL, 0 },
{ "dbFilename", required_argument, NULL, 0 },
{ "exclude", required_argument, NULL, 0 },
{ "excludeFromFile", required_argument, NULL, 0 },
{ "progress", no_argument, NULL, 0 },
{ "logLevel", required_argument, NULL, 0 },
{ "dryRun", no_argument, NULL, 0 },
{ "rebuild", no_argument, NULL, 0 },
{ "upload", no_argument, NULL, 0 },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
int ch, longIndex;
while ((ch = getopt_long(argc, argv, "Vh", longOpts, &longIndex)) != -1) {
if (ch=='V') {
showVersion();
exit(0);
} else if (ch=='h') {
showHelp();
exit(0);
}
if (ch!=0) {
continue;
}
const char *longName = longOpts[longIndex].name;
if (strcmp(longName, "accessKeyId")==0) {
accessKeyId = strdup(optarg);
} else if (strcmp(longName, "secretAccessKey")==0) {
secretAccessKey = strdup(optarg);
} else if (strcmp(longName, "bucket")==0) {
bucket = strdup(optarg);
} else if (strcmp(longName, "endPoint")==0) {
endPoint = strdup(optarg);
} else if (strcmp(longName, "networkTimeout")==0) {
networkTimeout = atoi(optarg);
if (networkTimeout<=0 || networkTimeout>=600) {
printf("Network timeout invalid (must be 1..600 seconds)\n");
exit(1);
}
} else if (strcmp(longName, "uploadThreads")==0) {
uploadThreads = atoi(optarg);
if (uploadThreads<=0 || uploadThreads>=100) {
printf("Upload threads count invalid (must be 1..100)\n");
exit(1);
}
} else if (strcmp(longName, "connectTimeout")==0) {
connectTimeout = atoi(optarg);
if (connectTimeout<=0 || connectTimeout>=600) {
printf("Connect timeout invalid (must be 1..600 seconds)\n");
exit(1);
}
} else if (strcmp(longName, "public")==0) {
makeAllPublic = 1;
} else if (strcmp(longName, "skipSsl")==0) {
skipSsl = 1;
} else if (strcmp(longName, "rrs")==0) {
useRrs = 1;
} else if (strcmp(longName, "rss")==0) {
printf("Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\n");
useRrs = 1;
} else if (strcmp(longName, "dryRun")==0) {
dryRun = 1;
} else if (strcmp(longName, "progress")==0) {
showProgress = 1;
} else if (strcmp(longName, "logLevel")==0) {
logLevel = atoi(optarg);
if (logLevel <= 0 || logLevel > 5) {
printf("--logLevel must be 1..5\n");
exit(1);
}
} else if (strcmp(longName, "source")==0) {
source = strdup(optarg);
} else if (strcmp(longName, "dbPath")==0) {
databasePath = strdup(optarg);
} else if (strcmp(longName, "dbFilename")==0) {
databaseFilename = strdup(optarg);
} else if (strcmp(longName, "rebuild")==0) {
performRebuild=1;
} else if (strcmp(longName, "upload")==0) {
performUpload=1;
} else if (strcmp(longName, "exclude")==0) {
if (!excludeFilePattern->add(optarg)) {
printf("Pattern `%s' is not valid.\n", optarg);
exit(1);
}
} else if (strcmp(longName, "excludeFromFile")==0) {
if (!excludeFilePattern->readFile(optarg)) {
printf("Cannot read or parse patterns in %s\n", optarg);
exit(1);
}
}
}
int failed = 0;
if (!source) {
printf("Specify --source.\n");
failed = 1;
}
if (source && source[0]!='/') {
printf("--source must be absolute path.\n");
failed=1;
}
if (!accessKeyId) {
printf("Specify --accessKeyId.\n");
failed = 1;
}
if (!secretAccessKey) {
printf("Specify --secretAccessKey.\n");
failed = 1;
}
if (!bucket) {
printf("Specify --bucket.\n");
failed = 1;
}
if (!validateEndpoint(endPoint)) {
failed = 1;
}
if (!performRebuild && !performUpload) {
printf("What shall I do? Say --rebuild and/or --upload!\n");
failed = 1;
}
if (failed) {
return 0;
}
while (source[strlen(source)-1]=='/') {
source[strlen(source)-1]=0;
}
if (!databasePath) {
databasePath = source;
} else {
while (databasePath[strlen(databasePath)-1]=='/') {
databasePath[strlen(databasePath)-1]=0;
}
}
return 1;
}
int verifySource(char *source) {
struct stat fileInfo;
if (lstat(source, &fileInfo)<0) {
printf("%s doesn't exists.\n", source);
return 0;
}
if (!(fileInfo.st_mode & S_IFDIR)) {
printf("%s isn't a directory.\n", source);
return 0;
}
return 1;
}
int main(int argc, char *argv[]) {
int res;
curl_global_init(CURL_GLOBAL_ALL);
xmlInitParser();
logStream = stdout;
logLevel = LOG_DBG;
excludeFilePattern = new FilePattern();
if (!parseCommandline(argc, argv)) {
exit(1);
}
if (!verifySource(source)) {
exit(1);
}
AmazonCredentials *amazonCredentials = new AmazonCredentials(
accessKeyId,
secretAccessKey,
bucket, endPoint
);
RemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);
remoteListOfFiles->showProgress = showProgress;
if (skipSsl) {
remoteListOfFiles->useSsl=0;
}
if (networkTimeout) {
remoteListOfFiles->networkTimeout = networkTimeout;
}
if (connectTimeout) {
remoteListOfFiles->connectTimeout = connectTimeout;
}
res = remoteListOfFiles->checkAuth();
if (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {
LOG(LOG_FATAL, "[Auth] Failed: bucket doesn't exists, exit");
exit(1);
} else if (res == AUTH_FAILED) {
LOG(LOG_FATAL, "[Auth] FAIL, exit");
exit(1);
}
LOG(LOG_INFO, "[Auth] Success");
char *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);
LOG(LOG_DBG, "[Storage] Database path = %s", databaseFilePath);
char errorResult[1024*100];
FileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);
if (strlen(errorResult)>0) {
LOG(LOG_FATAL, "[Storage] FAIL: %s, exit", errorResult);
exit(1);
}
if (performRebuild) {
if (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {
exit(1);
}
}
if (performUpload) {
if (excludeFilePattern->count==0) {
delete excludeFilePattern;
excludeFilePattern=NULL;
}
Uploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);
uploader->useRrs = useRrs;
uploader->makeAllPublic = makeAllPublic;
uploader->showProgress = showProgress;
if (skipSsl) {
uploader->useSsl=0;
}
if (networkTimeout) {
uploader->networkTimeout = networkTimeout;
}
if (connectTimeout) {
uploader->connectTimeout = connectTimeout;
}
if (uploadThreads) {
uploader->uploadThreads = uploadThreads;
}
uploader->dryRun = dryRun;
#ifdef TEST
do {
#endif
res = uploader->uploadFiles(fileListStorage, source);
if (res==UPLOAD_FAILED) {
exit(1);
}
#ifdef TEST
fileListStorage->truncate();
} while (true);
#endif
res = uploader->uploadDatabase(databaseFilePath, databaseFilename);
if (res==UPLOAD_FAILED) {
exit(1);
}
delete uploader;
}
free(databaseFilePath);
delete fileListStorage;
delete amazonCredentials;
exit(0);
}
<commit_msg>correct -v<commit_after>#include <iostream>
using namespace std;
extern "C" {
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <curl/curl.h>
#include <errno.h>
#include <sqlite3.h>
#include <getopt.h>
#include <libxml/xmlmemory.h>
#include "help.h"
#include "logger.h"
}
#include "localFileList.h"
#include "fileListStorage.h"
#include "amazonCredentials.h"
#include "remoteListOfFiles.h"
#include "upload.h"
#include "filePattern.h"
static char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) "s3.amazonaws.com",
*source=NULL, *databasePath=NULL, *databaseFilename= (char *)".files.sqlite3";
static int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0,
connectTimeout = 0, networkTimeout = 0, uploadThreads = 0;
FilePattern *excludeFilePattern;
FILE *logStream;
int logLevel = LOG_ERR;
int rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {
int res = remoteListOfFiles->downloadList();
if (res==LIST_FAILED) {
return LIST_FAILED;
}
LOG(LOG_INFO, "[MetaUpdate] Got %d files, updating meta information", remoteListOfFiles->count);
res = remoteListOfFiles->resolveMtimes();
if (res==LIST_FAILED) {
return LIST_FAILED;
}
if (dryRun) {
LOG(LOG_INFO, "[MetaUpdate] [dry] Skipped storing list of files");
return LIST_SUCCESS;
}
if (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {
LOG(LOG_FATAL, "[MetaUpdate] Failed to store list of files");
return LIST_FAILED;
} else {
return LIST_SUCCESS;
}
}
static char *endPoints[] = {
(char *) "s3.amazonaws.com",
(char *) "s3-us-west-2.amazonaws.com",
(char *) "s3-us-west-1.amazonaws.com",
(char *) "s3-eu-west-1.amazonaws.com",
(char *) "s3-ap-southeast-1.amazonaws.com",
(char *) "s3-ap-northeast-1.amazonaws.com",
(char *) "s3-sa-east-1.amazonaws.com",
NULL
};
int validateEndpoint(char *endPoint) {
int i=0;
while (char *e=endPoints[i++]) {
if (e && strcmp(e, endPoint)==0) {
return 1;
}
}
#ifdef TEST
if (strcmp(endPoint, "local")==0) {
printf("EndPoint for testing purposes engaged.\n");
return 1;
}
#endif
printf("--endPoint %s not valid, use one of:\n", endPoint);
i=0;
while (char *e=endPoints[i++]) {
printf("\t%s\n", e);
}
return 0;
}
char *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {
uint64_t len = strlen(databasePath)+strlen(databaseFilename)+2;
char *databaseFilePath = (char *) malloc(len);
databaseFilePath[0]=0;
strcat(databaseFilePath, databasePath);
strcat(databaseFilePath, "/");
strcat(databaseFilePath, databaseFilename);
return databaseFilePath;
}
void showVersion() {
printf("clarc version " VERSION " (c) 2012 Egor Egorov <[email protected]>\nMIT License | http://egorfine.com/clarc/\n");
}
int parseCommandline(int argc, char *argv[]) {
if (argc==1) {
showVersion();
printf("Perhaps, ask --help?\n");
exit(0);
}
static struct option longOpts[] = {
{ "accessKeyId", required_argument, NULL, 0 },
{ "secretAccessKey", required_argument, NULL, 0 },
{ "bucket", required_argument, NULL, 0 },
{ "endPoint", required_argument, NULL, 0 },
{ "public", no_argument, NULL, 0 },
{ "rrs", no_argument, NULL, 0 },
{ "rss", no_argument, NULL, 0 }, // common typo
{ "skipSsl", no_argument, NULL, 0 },
{ "connectTimeout", required_argument, NULL, 0 },
{ "networkTimeout", required_argument, NULL, 0 },
{ "uploadThreads", required_argument, NULL, 0 },
{ "source", required_argument, NULL, 0 },
{ "ddbPath", required_argument, NULL, 0 },
{ "dbFilename", required_argument, NULL, 0 },
{ "exclude", required_argument, NULL, 0 },
{ "excludeFromFile", required_argument, NULL, 0 },
{ "progress", no_argument, NULL, 0 },
{ "logLevel", required_argument, NULL, 0 },
{ "dryRun", no_argument, NULL, 0 },
{ "rebuild", no_argument, NULL, 0 },
{ "upload", no_argument, NULL, 0 },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
int ch, longIndex;
while ((ch = getopt_long(argc, argv, "vh", longOpts, &longIndex)) != -1) {
if (ch=='v') {
showVersion();
exit(0);
} else if (ch=='h') {
showHelp();
exit(0);
}
if (ch!=0) {
continue;
}
const char *longName = longOpts[longIndex].name;
if (strcmp(longName, "accessKeyId")==0) {
accessKeyId = strdup(optarg);
} else if (strcmp(longName, "secretAccessKey")==0) {
secretAccessKey = strdup(optarg);
} else if (strcmp(longName, "bucket")==0) {
bucket = strdup(optarg);
} else if (strcmp(longName, "endPoint")==0) {
endPoint = strdup(optarg);
} else if (strcmp(longName, "networkTimeout")==0) {
networkTimeout = atoi(optarg);
if (networkTimeout<=0 || networkTimeout>=600) {
printf("Network timeout invalid (must be 1..600 seconds)\n");
exit(1);
}
} else if (strcmp(longName, "uploadThreads")==0) {
uploadThreads = atoi(optarg);
if (uploadThreads<=0 || uploadThreads>=100) {
printf("Upload threads count invalid (must be 1..100)\n");
exit(1);
}
} else if (strcmp(longName, "connectTimeout")==0) {
connectTimeout = atoi(optarg);
if (connectTimeout<=0 || connectTimeout>=600) {
printf("Connect timeout invalid (must be 1..600 seconds)\n");
exit(1);
}
} else if (strcmp(longName, "public")==0) {
makeAllPublic = 1;
} else if (strcmp(longName, "skipSsl")==0) {
skipSsl = 1;
} else if (strcmp(longName, "rrs")==0) {
useRrs = 1;
} else if (strcmp(longName, "rss")==0) {
printf("Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\n");
useRrs = 1;
} else if (strcmp(longName, "dryRun")==0) {
dryRun = 1;
} else if (strcmp(longName, "progress")==0) {
showProgress = 1;
} else if (strcmp(longName, "logLevel")==0) {
logLevel = atoi(optarg);
if (logLevel <= 0 || logLevel > 5) {
printf("--logLevel must be 1..5\n");
exit(1);
}
} else if (strcmp(longName, "source")==0) {
source = strdup(optarg);
} else if (strcmp(longName, "dbPath")==0) {
databasePath = strdup(optarg);
} else if (strcmp(longName, "dbFilename")==0) {
databaseFilename = strdup(optarg);
} else if (strcmp(longName, "rebuild")==0) {
performRebuild=1;
} else if (strcmp(longName, "upload")==0) {
performUpload=1;
} else if (strcmp(longName, "exclude")==0) {
if (!excludeFilePattern->add(optarg)) {
printf("Pattern `%s' is not valid.\n", optarg);
exit(1);
}
} else if (strcmp(longName, "excludeFromFile")==0) {
if (!excludeFilePattern->readFile(optarg)) {
printf("Cannot read or parse patterns in %s\n", optarg);
exit(1);
}
}
}
int failed = 0;
if (!source) {
printf("Specify --source.\n");
failed = 1;
}
if (source && source[0]!='/') {
printf("--source must be absolute path.\n");
failed=1;
}
if (!accessKeyId) {
printf("Specify --accessKeyId.\n");
failed = 1;
}
if (!secretAccessKey) {
printf("Specify --secretAccessKey.\n");
failed = 1;
}
if (!bucket) {
printf("Specify --bucket.\n");
failed = 1;
}
if (!validateEndpoint(endPoint)) {
failed = 1;
}
if (!performRebuild && !performUpload) {
printf("What shall I do? Say --rebuild and/or --upload!\n");
failed = 1;
}
if (failed) {
return 0;
}
while (source[strlen(source)-1]=='/') {
source[strlen(source)-1]=0;
}
if (!databasePath) {
databasePath = source;
} else {
while (databasePath[strlen(databasePath)-1]=='/') {
databasePath[strlen(databasePath)-1]=0;
}
}
return 1;
}
int verifySource(char *source) {
struct stat fileInfo;
if (lstat(source, &fileInfo)<0) {
printf("%s doesn't exists.\n", source);
return 0;
}
if (!(fileInfo.st_mode & S_IFDIR)) {
printf("%s isn't a directory.\n", source);
return 0;
}
return 1;
}
int main(int argc, char *argv[]) {
int res;
curl_global_init(CURL_GLOBAL_ALL);
xmlInitParser();
logStream = stdout;
logLevel = LOG_DBG;
excludeFilePattern = new FilePattern();
if (!parseCommandline(argc, argv)) {
exit(1);
}
if (!verifySource(source)) {
exit(1);
}
AmazonCredentials *amazonCredentials = new AmazonCredentials(
accessKeyId,
secretAccessKey,
bucket, endPoint
);
RemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);
remoteListOfFiles->showProgress = showProgress;
if (skipSsl) {
remoteListOfFiles->useSsl=0;
}
if (networkTimeout) {
remoteListOfFiles->networkTimeout = networkTimeout;
}
if (connectTimeout) {
remoteListOfFiles->connectTimeout = connectTimeout;
}
res = remoteListOfFiles->checkAuth();
if (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {
LOG(LOG_FATAL, "[Auth] Failed: bucket doesn't exists, exit");
exit(1);
} else if (res == AUTH_FAILED) {
LOG(LOG_FATAL, "[Auth] FAIL, exit");
exit(1);
}
LOG(LOG_INFO, "[Auth] Success");
char *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);
LOG(LOG_DBG, "[Storage] Database path = %s", databaseFilePath);
char errorResult[1024*100];
FileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);
if (strlen(errorResult)>0) {
LOG(LOG_FATAL, "[Storage] FAIL: %s, exit", errorResult);
exit(1);
}
if (performRebuild) {
if (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {
exit(1);
}
}
if (performUpload) {
if (excludeFilePattern->count==0) {
delete excludeFilePattern;
excludeFilePattern=NULL;
}
Uploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);
uploader->useRrs = useRrs;
uploader->makeAllPublic = makeAllPublic;
uploader->showProgress = showProgress;
if (skipSsl) {
uploader->useSsl=0;
}
if (networkTimeout) {
uploader->networkTimeout = networkTimeout;
}
if (connectTimeout) {
uploader->connectTimeout = connectTimeout;
}
if (uploadThreads) {
uploader->uploadThreads = uploadThreads;
}
uploader->dryRun = dryRun;
#ifdef TEST
do {
#endif
res = uploader->uploadFiles(fileListStorage, source);
if (res==UPLOAD_FAILED) {
exit(1);
}
#ifdef TEST
fileListStorage->truncate();
} while (true);
#endif
res = uploader->uploadDatabase(databaseFilePath, databaseFilename);
if (res==UPLOAD_FAILED) {
exit(1);
}
delete uploader;
}
free(databaseFilePath);
delete fileListStorage;
delete amazonCredentials;
exit(0);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/PageScriptDebugServer.h"
#include "V8Window.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptSourceCode.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ScriptRunner.h"
#include "bindings/v8/V8WindowShell.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/ScriptDebugListener.h"
#include "core/frame/Frame.h"
#include "core/frame/FrameHost.h"
#include "core/page/Page.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TemporaryChange.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
static Frame* retrieveFrameWithGlobalObjectCheck(v8::Handle<v8::Context> context)
{
if (context.IsEmpty())
return 0;
// Test that context has associated global dom window object.
v8::Handle<v8::Object> global = context->Global();
if (global.IsEmpty())
return 0;
global = global->FindInstanceInPrototypeChain(V8Window::domTemplate(context->GetIsolate(), worldTypeInMainThread(context->GetIsolate())));
if (global.IsEmpty())
return 0;
return toFrameIfNotDetached(context);
}
void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource)
{
if (preprocessorSource.isEmpty())
m_preprocessorSourceCode.clear();
else
m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource));
m_scriptPreprocessor.clear();
}
PageScriptDebugServer& PageScriptDebugServer::shared()
{
DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
return server;
}
PageScriptDebugServer::PageScriptDebugServer()
: ScriptDebugServer(v8::Isolate::GetCurrent())
, m_pausedPage(0)
{
}
void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
{
ScriptController& scriptController = page->mainFrame()->script();
if (!scriptController.canExecuteScripts(NotAboutToExecuteScript))
return;
v8::HandleScope scope(m_isolate);
v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
v8::Context::Scope contextScope(debuggerContext);
v8::Local<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
if (!m_listenersMap.size()) {
ensureDebuggerScriptCompiled();
ASSERT(!debuggerScript->IsUndefined());
v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this));
}
m_listenersMap.set(page, listener);
V8WindowShell* shell = scriptController.existingWindowShell(DOMWrapperWorld::mainWorld());
if (!shell || !shell->isContextInitialized())
return;
v8::Local<v8::Context> context = shell->context();
v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts")));
v8::Handle<v8::Value> argv[] = { context->GetEmbedderData(0) };
v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
if (value.IsEmpty())
return;
ASSERT(!value->IsUndefined() && value->IsArray());
v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value);
for (unsigned i = 0; i < scriptsArray->Length(); ++i)
dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i))));
}
void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
{
if (!m_listenersMap.contains(page))
return;
if (m_pausedPage == page)
continueProgram();
m_listenersMap.remove(page);
if (m_listenersMap.isEmpty())
v8::Debug::SetDebugEventListener2(0);
// FIXME: Remove all breakpoints set by the agent.
}
void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
{
m_clientMessageLoop = clientMessageLoop;
}
void PageScriptDebugServer::compileScript(ScriptState* state, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
{
ExecutionContext* executionContext = state->executionContext();
RefPtr<Frame> protect = toDocument(executionContext)->frame();
ScriptDebugServer::compileScript(state, expression, sourceURL, scriptId, exceptionMessage);
if (!scriptId->isNull())
m_compiledScriptURLs.set(*scriptId, sourceURL);
}
void PageScriptDebugServer::clearCompiledScripts()
{
ScriptDebugServer::clearCompiledScripts();
m_compiledScriptURLs.clear();
}
void PageScriptDebugServer::runScript(ScriptState* state, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
{
String sourceURL = m_compiledScriptURLs.take(scriptId);
ExecutionContext* executionContext = state->executionContext();
Frame* frame = toDocument(executionContext)->frame();
InspectorInstrumentationCookie cookie;
if (frame)
cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt());
RefPtr<Frame> protect = frame;
ScriptDebugServer::runScript(state, scriptId, result, wasThrown, exceptionMessage);
if (frame)
InspectorInstrumentation::didEvaluateScript(cookie);
}
ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(m_isolate);
Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
if (!frame)
return 0;
return m_listenersMap.get(frame->page());
}
void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(m_isolate);
Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
m_pausedPage = frame->page();
// Wait for continue or step command.
m_clientMessageLoop->run(m_pausedPage);
// The listener may have been removed in the nested loop.
if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
listener->didContinue();
m_pausedPage = 0;
}
void PageScriptDebugServer::quitMessageLoopOnPause()
{
m_clientMessageLoop->quitNow();
}
void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails)
{
v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
Frame* frame = retrieveFrameWithGlobalObjectCheck(eventContext);
if (!frame)
return;
if (!canPreprocess(frame))
return;
v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext();
v8::Context::Scope contextScope(debugContext);
v8::TryCatch tryCatch;
// <script> tag source and attribute value source are preprocessed before we enter V8.
// Avoid preprocessing any internal scripts by processing only eval source in this V8 event handler.
v8::Handle<v8::Value> argvEventData[] = { eventData };
v8::Handle<v8::Value> v8Value = callDebuggerMethod("isEvalCompilation", WTF_ARRAY_LENGTH(argvEventData), argvEventData);
if (v8Value.IsEmpty() || !v8Value->ToBoolean()->Value())
return;
// The name and source are in the JS event data.
String scriptName = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptName", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
String script = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptSource", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(script, scriptName);
v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) };
callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript);
}
static bool isCreatingPreprocessor = false;
bool PageScriptDebugServer::canPreprocess(Frame* frame)
{
ASSERT(frame);
if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor)
return false;
// We delay the creation of the preprocessor until just before the first JS from the
// Web page to ensure that the debugger's console initialization code has completed.
if (!m_scriptPreprocessor) {
TemporaryChange<bool> isPreprocessing(isCreatingPreprocessor, true);
m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(*m_preprocessorSourceCode.get(), frame));
}
if (m_scriptPreprocessor->isValid())
return true;
m_scriptPreprocessor.clear();
// Don't retry the compile if we fail one time.
m_preprocessorSourceCode.clear();
return false;
}
// Source to Source processing iff debugger enabled and it has loaded a preprocessor.
PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
{
if (!canPreprocess(frame))
return PassOwnPtr<ScriptSourceCode>();
String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url());
return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url()));
}
String PageScriptDebugServer::preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
{
if (!canPreprocess(frame))
return source;
return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName);
}
} // namespace WebCore
<commit_msg>retrieveFrameWithGlobalObjectCheck should check contextHasCorrectPrototype()<commit_after>/*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/PageScriptDebugServer.h"
#include "V8Window.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptSourceCode.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ScriptRunner.h"
#include "bindings/v8/V8WindowShell.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/ScriptDebugListener.h"
#include "core/frame/Frame.h"
#include "core/frame/FrameHost.h"
#include "core/page/Page.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TemporaryChange.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
static Frame* retrieveFrameWithGlobalObjectCheck(v8::Handle<v8::Context> context)
{
if (context.IsEmpty())
return 0;
// Test that context has associated global dom window object.
if (!V8WindowShell::contextHasCorrectPrototype(context))
return 0;
v8::Handle<v8::Value> global = context->Global()->FindInstanceInPrototypeChain(V8Window::domTemplate(context->GetIsolate(), worldTypeInMainThread(context->GetIsolate())));
if (global.IsEmpty())
return 0;
return toFrameIfNotDetached(context);
}
void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource)
{
if (preprocessorSource.isEmpty())
m_preprocessorSourceCode.clear();
else
m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource));
m_scriptPreprocessor.clear();
}
PageScriptDebugServer& PageScriptDebugServer::shared()
{
DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
return server;
}
PageScriptDebugServer::PageScriptDebugServer()
: ScriptDebugServer(v8::Isolate::GetCurrent())
, m_pausedPage(0)
{
}
void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
{
ScriptController& scriptController = page->mainFrame()->script();
if (!scriptController.canExecuteScripts(NotAboutToExecuteScript))
return;
v8::HandleScope scope(m_isolate);
v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
v8::Context::Scope contextScope(debuggerContext);
v8::Local<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
if (!m_listenersMap.size()) {
ensureDebuggerScriptCompiled();
ASSERT(!debuggerScript->IsUndefined());
v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this));
}
m_listenersMap.set(page, listener);
V8WindowShell* shell = scriptController.existingWindowShell(DOMWrapperWorld::mainWorld());
if (!shell || !shell->isContextInitialized())
return;
v8::Local<v8::Context> context = shell->context();
v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts")));
v8::Handle<v8::Value> argv[] = { context->GetEmbedderData(0) };
v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
if (value.IsEmpty())
return;
ASSERT(!value->IsUndefined() && value->IsArray());
v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value);
for (unsigned i = 0; i < scriptsArray->Length(); ++i)
dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i))));
}
void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
{
if (!m_listenersMap.contains(page))
return;
if (m_pausedPage == page)
continueProgram();
m_listenersMap.remove(page);
if (m_listenersMap.isEmpty())
v8::Debug::SetDebugEventListener2(0);
// FIXME: Remove all breakpoints set by the agent.
}
void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
{
m_clientMessageLoop = clientMessageLoop;
}
void PageScriptDebugServer::compileScript(ScriptState* state, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
{
ExecutionContext* executionContext = state->executionContext();
RefPtr<Frame> protect = toDocument(executionContext)->frame();
ScriptDebugServer::compileScript(state, expression, sourceURL, scriptId, exceptionMessage);
if (!scriptId->isNull())
m_compiledScriptURLs.set(*scriptId, sourceURL);
}
void PageScriptDebugServer::clearCompiledScripts()
{
ScriptDebugServer::clearCompiledScripts();
m_compiledScriptURLs.clear();
}
void PageScriptDebugServer::runScript(ScriptState* state, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
{
String sourceURL = m_compiledScriptURLs.take(scriptId);
ExecutionContext* executionContext = state->executionContext();
Frame* frame = toDocument(executionContext)->frame();
InspectorInstrumentationCookie cookie;
if (frame)
cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt());
RefPtr<Frame> protect = frame;
ScriptDebugServer::runScript(state, scriptId, result, wasThrown, exceptionMessage);
if (frame)
InspectorInstrumentation::didEvaluateScript(cookie);
}
ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(m_isolate);
Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
if (!frame)
return 0;
return m_listenersMap.get(frame->page());
}
void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(m_isolate);
Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
m_pausedPage = frame->page();
// Wait for continue or step command.
m_clientMessageLoop->run(m_pausedPage);
// The listener may have been removed in the nested loop.
if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
listener->didContinue();
m_pausedPage = 0;
}
void PageScriptDebugServer::quitMessageLoopOnPause()
{
m_clientMessageLoop->quitNow();
}
void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails)
{
v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
Frame* frame = retrieveFrameWithGlobalObjectCheck(eventContext);
if (!frame)
return;
if (!canPreprocess(frame))
return;
v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext();
v8::Context::Scope contextScope(debugContext);
v8::TryCatch tryCatch;
// <script> tag source and attribute value source are preprocessed before we enter V8.
// Avoid preprocessing any internal scripts by processing only eval source in this V8 event handler.
v8::Handle<v8::Value> argvEventData[] = { eventData };
v8::Handle<v8::Value> v8Value = callDebuggerMethod("isEvalCompilation", WTF_ARRAY_LENGTH(argvEventData), argvEventData);
if (v8Value.IsEmpty() || !v8Value->ToBoolean()->Value())
return;
// The name and source are in the JS event data.
String scriptName = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptName", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
String script = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptSource", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(script, scriptName);
v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) };
callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript);
}
static bool isCreatingPreprocessor = false;
bool PageScriptDebugServer::canPreprocess(Frame* frame)
{
ASSERT(frame);
if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor)
return false;
// We delay the creation of the preprocessor until just before the first JS from the
// Web page to ensure that the debugger's console initialization code has completed.
if (!m_scriptPreprocessor) {
TemporaryChange<bool> isPreprocessing(isCreatingPreprocessor, true);
m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(*m_preprocessorSourceCode.get(), frame));
}
if (m_scriptPreprocessor->isValid())
return true;
m_scriptPreprocessor.clear();
// Don't retry the compile if we fail one time.
m_preprocessorSourceCode.clear();
return false;
}
// Source to Source processing iff debugger enabled and it has loaded a preprocessor.
PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
{
if (!canPreprocess(frame))
return PassOwnPtr<ScriptSourceCode>();
String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url());
return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url()));
}
String PageScriptDebugServer::preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
{
if (!canPreprocess(frame))
return source;
return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief LTC2348-16 ドライバー @n
LTC2348/16 bits A/D コンバーター @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/delay.hpp"
#include "common/format.hpp"
/// F_ICK は速度パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_ICK
# error "LTC2348_16.hpp requires F_ICK to be defined"
#endif
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief LTC2348-16 データ出力定義
@param[in] CK SCKO 定義
@param[in] O0 SDO0 定義
@param[in] O2 SDO2 定義
@param[in] O4 SDO4 定義
@param[in] O5 SDO6 定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CK, class O0, class O2, class O4, class O6>
struct LTC2348_SDO_t {
typedef CK SCKO;
typedef O0 SDO0;
typedef O2 SDO2;
typedef O4 SDO4;
typedef O6 SDO6;
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief LTC2348-16 テンプレートクラス
@param[in] CSN デバイス選択
@param[in] CNV コンバート制御
@param[in] BUSY ビジー信号
@param[in] PD パワーダウン制御(1: PowerDown)
@param[in] SDI 制御データ
@param[in] SCKI 制御クロック
@param[in] SDO データ出力定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSN, class CNV, class BUSY, class PD, class SDI, class SCKI, class SDO>
class LTC2348_16 {
uint32_t span_;
uint32_t data_[8];
uint16_t busy_loop_;
uint16_t clk_loop_;
uint16_t cnv_loop_;
bool device_;
void get_data_loop_(uint32_t ofs, uint32_t span)
{
SDI::P = 0;
uint32_t mask = 0x00800000;
uint32_t d0 = 0;
uint32_t d1 = 0;
uint32_t d2 = 0;
uint32_t d3 = 0;
volatile uint16_t ll = clk_loop_ >> 1;
if(ll > 10) ll -= 10; else ll = 0;
while(mask > 0) {
d0 <<= 1;
d0 |= SDO::SDO0::P();
d1 <<= 1;
d1 |= SDO::SDO2::P();
d2 <<= 1;
d2 |= SDO::SDO4::P();
d3 <<= 1;
d3 |= SDO::SDO6::P();
volatile uint16_t l = ll;
while(l > 0) { --l; }
SCKI::P = 0;
if(span & mask) {
SDI::P = 1;
} else {
SDI::P = 0;
}
mask >>= 1;
volatile uint16_t h = clk_loop_ >> 1;
while(h > 0) { --h; }
SCKI::P = 1;
}
data_[0 + ofs] = d0;
data_[2 + ofs] = d1;
data_[4 + ofs] = d2;
data_[6 + ofs] = d3;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
LTC2348_16() : span_(0), busy_loop_(0), clk_loop_(0), cnv_loop_(0), device_(false) { }
//-----------------------------------------------------------------//
/*!
@brief スパンデータの取得
@return スパンデータ
*/
//-----------------------------------------------------------------//
uint32_t get_span() const { return span_; }
//-----------------------------------------------------------------//
/*!
@brief デバイスの開始 @n
制御線を初期化して、デバイスのゆ有無を確認
@param[in] speed 制御クロック速度
@param[in] span 変換スパン
@return デバイスが有効なら「true」
*/
//-----------------------------------------------------------------//
bool start(uint32_t speed, uint8_t span)
{
{
uint32_t cnt = static_cast<uint32_t>(F_ICK) / speed;
float a = static_cast<float>(cnt);
a /= 10.974f;
cnt = static_cast<uint32_t>(a);
if(cnt > 65535) return false;
clk_loop_ = cnt;
}
{ // BUSY loop 200ns (5MHz)
uint32_t cnt = static_cast<uint32_t>(F_ICK) / 5000000;
if(cnt > 65535) return false;
busy_loop_ = cnt;
}
{ // tCONV: 500ns/ch 200ksps
uint32_t cnt = static_cast<uint32_t>(F_ICK) / 200000;
if(cnt > 65535) return false;
cnv_loop_ = cnt;
}
uint32_t ss = 0;
for(int i = 0; i < 8; ++i) {
ss <<= 3;
ss |= static_cast<uint32_t>(span & 7);
}
span_ = ss;
CSN::DIR = 1;
CSN::P = 1;
CNV::DIR = 1;
CNV::P = 0;
BUSY::DIR = 0;
PD::DIR = 1;
PD::P = 0;
SDI::DIR = 1;
SDI::P = 0;
SCKI::DIR = 1;
SCKI::P = 0;
SDO::SCKO::DIR = 0;
SDO::SDO0::DIR = 0;
SDO::SDO2::DIR = 0;
SDO::SDO4::DIR = 0;
SDO::SDO6::DIR = 0;
utils::delay::milli_second(1);
device_ = convert();
return device_;
}
//-----------------------------------------------------------------//
/*!
@brief デバイスの応答確認
@return デバイスが接続されている場合「true」
*/
//-----------------------------------------------------------------//
bool probe() const {
return device_;
}
//-----------------------------------------------------------------//
/*!
@brief 変換を開始
@return 変換正常終了なら「true」
*/
//-----------------------------------------------------------------//
bool convert()
{
SCKI::P = 0;
SDI::P = 0;
if(BUSY::P() != 0) {
return false;
}
// tBUSYLH: CNV=1 で BUSY が応答する最大時間 (max 30ns) @n
// tCNVH: CNV 要求パルス (min 40ns)
{
CNV::P = 1;
uint16_t n = busy_loop_;
while(n > 0) {
if(BUSY::P() == 1) {
break;
}
--n;
}
if(n == 0) {
CNV::P = 0;
CSN::P = 1;
return false;
}
}
CSN::P = 0;
// 変換待ち 最大 500ns
{
uint16_t n = cnv_loop_;
while(n > 0) {
if(BUSY::P() == 0) break;
--n;
}
/// utils::format("Conversion count: %d\n") % static_cast<int>(cnv_loop_ - n);
CNV::P = 0;
if(n == 0) {
CSN::P = 1;
return false;
}
}
get_data_loop_(0, span_);
get_data_loop_(1, 0x000000);
CSN::P = 1;
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 変換値を取得
@param[in] ch チャネル(0~7)
@return 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_value(uint8_t ch) const {
return data_[ch & 7] >> 8;
}
//-----------------------------------------------------------------//
/*!
@brief 変換値を取得
@param[in] ch チャネル(0~7)
@return 変換値
*/
//-----------------------------------------------------------------//
uint32_t get_data(uint8_t ch) const {
return data_[ch & 7];
}
//-----------------------------------------------------------------//
/*!
@brief 変換電圧を取得
@param[in] ch チャネル(0~7)
@return 変換電圧
*/
//-----------------------------------------------------------------//
float get_voltage(uint8_t ch) const {
float gain = 5.12f;
return static_cast<float>(data_[ch & 7]) / 65535.0f * gain;
}
};
}
<commit_msg>update<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief LTC2348-16 ドライバー @n
LTC2348/16 bits A/D コンバーター @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/delay.hpp"
#include "common/format.hpp"
/// F_ICK は速度パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_ICK
# error "LTC2348_16.hpp requires F_ICK to be defined"
#endif
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief LTC2348-16 データ出力定義
@param[in] CK SCKO 定義
@param[in] O0 SDO0 定義
@param[in] O2 SDO2 定義
@param[in] O4 SDO4 定義
@param[in] O5 SDO6 定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CK, class O0, class O2, class O4, class O6>
struct LTC2348_SDO_t {
typedef CK SCKO;
typedef O0 SDO0;
typedef O2 SDO2;
typedef O4 SDO4;
typedef O6 SDO6;
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief LTC2348-16 テンプレートクラス
@param[in] CSN デバイス選択
@param[in] CNV コンバート制御
@param[in] BUSY ビジー信号
@param[in] PD パワーダウン制御(1: PowerDown)
@param[in] SDI 制御データ
@param[in] SCKI 制御クロック
@param[in] SDO データ出力定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSN, class CNV, class BUSY, class PD, class SDI, class SCKI, class SDO>
class LTC2348_16 {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ソフト・スパン種別 @n
Internal VREFBUF: 4.096V
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class span_type : uint8_t {
DISABLE, ///< 000, Chanel Disable
P5_12, ///< 001, 1.25 * VREFBUF (+0 to +5.12V)
M5P5, ///< 010, 2.5 * VREFBUF / 1.024 (-5V to +5V)
P5_12M5_12, ///< 011, 2.5 * VREFBUF (-5.12V to +5.12V)
P10, ///< 100, 2.5 * VREFBUF / 1.024 (+0 to +10V)
P10_24, ///< 101, 2.5 * VREFBUF (+0 to +10.24V)
M10P10, ///< 110, 5.0 * VREFBUF / 1.024 (-10V to +10V)
M10_24P10_24, ///< 111, 5.0 * VREFBUF (-10.24V to +10.24V)
};
private:
uint32_t span_;
uint32_t data_[8];
uint16_t busy_loop_;
uint16_t clk_loop_;
uint16_t cnv_loop_;
bool device_;
void get_data_loop_(uint32_t ofs, uint32_t span)
{
SDI::P = 0;
uint32_t mask = 0x00800000;
uint32_t d0 = 0;
uint32_t d1 = 0;
uint32_t d2 = 0;
uint32_t d3 = 0;
volatile uint16_t ll = clk_loop_ >> 1;
if(ll > 10) ll -= 10; else ll = 0;
while(mask > 0) {
d0 <<= 1;
d0 |= SDO::SDO0::P();
d1 <<= 1;
d1 |= SDO::SDO2::P();
d2 <<= 1;
d2 |= SDO::SDO4::P();
d3 <<= 1;
d3 |= SDO::SDO6::P();
volatile uint16_t l = ll;
while(l > 0) { --l; }
SCKI::P = 0;
if(span & mask) {
SDI::P = 1;
} else {
SDI::P = 0;
}
mask >>= 1;
volatile uint16_t h = clk_loop_ >> 1;
while(h > 0) { --h; }
SCKI::P = 1;
}
data_[0 + ofs] = d0;
data_[2 + ofs] = d1;
data_[4 + ofs] = d2;
data_[6 + ofs] = d3;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
LTC2348_16() : span_(0), busy_loop_(0), clk_loop_(0), cnv_loop_(0), device_(false) { }
//-----------------------------------------------------------------//
/*!
@brief デバイスの開始 @n
制御線を初期化して、デバイスのゆ有無を確認
@param[in] speed 制御クロック速度(ソフトループなので正確ではない)
@param[in] span 変換スパン種別(全てのチャネルに同一のスパンが設定される)
@return デバイスが有効なら「true」
*/
//-----------------------------------------------------------------//
bool start(uint32_t speed, span_type span)
{
{
uint32_t cnt = static_cast<uint32_t>(F_ICK) / speed;
float a = static_cast<float>(cnt);
a /= 10.974f;
cnt = static_cast<uint32_t>(a);
if(cnt > 65535) return false;
clk_loop_ = cnt;
}
{ // BUSY loop 200ns (5MHz)
uint32_t cnt = static_cast<uint32_t>(F_ICK) / 5000000;
if(cnt > 65535) return false;
busy_loop_ = cnt;
}
{ // tCONV: 500ns/ch 200ksps
uint32_t cnt = static_cast<uint32_t>(F_ICK) / 200000;
if(cnt > 65535) return false;
cnv_loop_ = cnt;
}
uint32_t ss = 0;
for(int i = 0; i < 8; ++i) {
ss <<= 3;
ss |= static_cast<uint32_t>(span);
}
span_ = ss;
CSN::DIR = 1;
CSN::P = 1;
CNV::DIR = 1;
CNV::P = 0;
BUSY::DIR = 0;
PD::DIR = 1;
PD::P = 0;
SDI::DIR = 1;
SDI::P = 0;
SCKI::DIR = 1;
SCKI::P = 0;
SDO::SCKO::DIR = 0;
SDO::SDO0::DIR = 0;
SDO::SDO2::DIR = 0;
SDO::SDO4::DIR = 0;
SDO::SDO6::DIR = 0;
utils::delay::milli_second(1);
device_ = convert();
return device_;
}
//-----------------------------------------------------------------//
/*!
@brief デバイスの応答確認
@return デバイスが接続されている場合「true」
*/
//-----------------------------------------------------------------//
bool probe() const {
return device_;
}
//-----------------------------------------------------------------//
/*!
@brief チャネルにスパン種別を設定
@param[in] ch チャネル
@param[in] span スパン種別
*/
//-----------------------------------------------------------------//
void set_span(uint8_t ch, span_type span)
{
span_ &= ~(0b111 << (ch * 3));
span_ |= static_cast<uint32_t>(span) << (ch * 3);
}
//-----------------------------------------------------------------//
/*!
@brief チャネルのスパン種別を取得
@param[in] ch チャネル
@return スパン種別
*/
//-----------------------------------------------------------------//
span_type get_span(uint8_t ch) const
{
return static_cast<span_type>((span_ >> (ch * 3)) & 0b111);
}
//-----------------------------------------------------------------//
/*!
@brief 変換を開始
@return 変換正常終了なら「true」
*/
//-----------------------------------------------------------------//
bool convert()
{
SCKI::P = 0;
SDI::P = 0;
if(BUSY::P() != 0) {
return false;
}
// tBUSYLH: CNV=1 で BUSY が応答する最大時間 (max 30ns) @n
// tCNVH: CNV 要求パルス (min 40ns)
{
CNV::P = 1;
uint16_t n = busy_loop_;
while(n > 0) {
if(BUSY::P() == 1) {
break;
}
--n;
}
if(n == 0) {
CNV::P = 0;
CSN::P = 1;
return false;
}
}
CSN::P = 0;
// 変換待ち 最大 500ns
{
uint16_t n = cnv_loop_;
while(n > 0) {
if(BUSY::P() == 0) break;
--n;
}
/// utils::format("Conversion count: %d\n") % static_cast<int>(cnv_loop_ - n);
CNV::P = 0;
if(n == 0) {
CSN::P = 1;
return false;
}
}
get_data_loop_(0, span_);
get_data_loop_(1, 0x000000);
CSN::P = 1;
return true;
}
//-----------------------------------------------------------------//
/*!
@brief A/D変換値を取得(0~65535)
@param[in] ch チャネル(0~7)
@return 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_value(uint8_t ch) const {
return data_[ch & 7] >> 8;
}
//-----------------------------------------------------------------//
/*!
@brief 変換データ(24ビット生データ)を取得
@param[in] ch チャネル(0~7)
@return 変換値
*/
//-----------------------------------------------------------------//
uint32_t get_data(uint8_t ch) const {
return data_[ch & 7];
}
//-----------------------------------------------------------------//
/*!
@brief 変換電圧に変換して取得
@param[in] ch チャネル(0~7)
@return 変換電圧
*/
//-----------------------------------------------------------------//
float get_voltage(uint8_t ch) const {
uint32_t span = (span_ >> (ch * 3)) & 7;
float ofs = 0.0f;
if(span == 2 || span == 3 || span == 6 || span == 7) {
ofs = 0.5f;
}
static const float gain[8] = { 0.0f, 5.12f, 5.0f, 5.12f, 10.0f, 10.24f, 10.0f, 10.24f };
return ((static_cast<float>(data_[ch & 7] >> 8) / 65535.0f) - ofs) * gain[span];
}
};
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/bho.h"
#include <shlguid.h>
#include <shobjidl.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "chrome_tab.h" // NOLINT
#include "chrome_frame/extra_system_apis.h"
#include "chrome_frame/http_negotiate.h"
#include "chrome_frame/protocol_sink_wrap.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"
#include "net/http/http_util.h"
const wchar_t kPatchProtocols[] = L"PatchProtocols";
static const int kIBrowserServiceOnHttpEquivIndex = 30;
base::LazyInstance<base::ThreadLocalPointer<Bho> >
Bho::bho_current_thread_instance_(base::LINKER_INITIALIZED);
PatchHelper g_patch_helper;
BEGIN_VTABLE_PATCHES(IBrowserService)
VTABLE_PATCH_ENTRY(kIBrowserServiceOnHttpEquivIndex, Bho::OnHttpEquiv)
END_VTABLE_PATCHES()
_ATL_FUNC_INFO Bho::kBeforeNavigate2Info = {
CC_STDCALL, VT_EMPTY, 7, {
VT_DISPATCH,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_BOOL | VT_BYREF
}
};
Bho::Bho() {
}
STDMETHODIMP Bho::SetSite(IUnknown* site) {
HRESULT hr = S_OK;
if (site) {
ScopedComPtr<IWebBrowser2> web_browser2;
web_browser2.QueryFrom(site);
if (web_browser2) {
hr = DispEventAdvise(web_browser2, &DIID_DWebBrowserEvents2);
DCHECK(SUCCEEDED(hr)) << "DispEventAdvise failed. Error: " << hr;
}
if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
ScopedComPtr<IBrowserService> browser_service;
hr = DoQueryService(SID_SShellBrowser, site, browser_service.Receive());
DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed."
<< " Site: " << site << " Error: " << hr;
if (browser_service) {
g_patch_helper.PatchBrowserService(browser_service);
DCHECK(SUCCEEDED(hr)) << "vtable_patch::PatchInterfaceMethods failed."
<< " Site: " << site << " Error: " << hr;
}
}
// Save away our BHO instance in TLS which enables it to be referenced by
// our active document/activex instances to query referrer and other
// information for a URL.
AddRef();
bho_current_thread_instance_.Pointer()->Set(this);
} else {
bho_current_thread_instance_.Pointer()->Set(NULL);
Release();
}
return IObjectWithSiteImpl<Bho>::SetSite(site);
}
STDMETHODIMP Bho::BeforeNavigate2(IDispatch* dispatch, VARIANT* url,
VARIANT* flags, VARIANT* target_frame_name, VARIANT* post_data,
VARIANT* headers, VARIANT_BOOL* cancel) {
ScopedComPtr<IWebBrowser2> web_browser2;
if (dispatch)
web_browser2.QueryFrom(dispatch);
if (!web_browser2) {
NOTREACHED() << "Can't find WebBrowser2 with given dispatch";
return S_OK; // Return success, we operate on best effort basis.
}
DLOG(INFO) << "BeforeNavigate2: " << url->bstrVal;
if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
VARIANT_BOOL is_top_level = VARIANT_FALSE;
web_browser2->get_TopLevelContainer(&is_top_level);
std::wstring current_url;
bool is_chrome_protocol = false;
if (is_top_level && IsValidUrlScheme(url->bstrVal, false)) {
current_url.assign(url->bstrVal, SysStringLen(url->bstrVal));
is_chrome_protocol = StartsWith(current_url, kChromeProtocolPrefix,
false);
if (!is_chrome_protocol && IsOptInUrl(current_url.c_str())) {
DLOG(INFO) << "Opt-in URL. Switching to cf.";
ScopedComPtr<IBrowserService> browser_service;
DoQueryService(SID_SShellBrowser, web_browser2,
browser_service.Receive());
DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed.";
MarkBrowserOnThreadForCFNavigation(browser_service);
}
}
}
referrer_.clear();
// Save away the referrer in case our active document needs it to initiate
// navigation in chrome.
if (headers && V_VT(headers) == VT_BSTR && headers->bstrVal != NULL) {
std::string raw_headers_utf8 = WideToUTF8(headers->bstrVal);
std::string http_headers =
net::HttpUtil::AssembleRawHeaders(raw_headers_utf8.c_str(),
raw_headers_utf8.length());
net::HttpUtil::HeadersIterator it(http_headers.begin(), http_headers.end(),
"\r\n");
while (it.GetNext()) {
if (LowerCaseEqualsASCII(it.name(), "referer")) {
referrer_ = it.values();
break;
}
}
}
url_ = url->bstrVal;
return S_OK;
}
HRESULT Bho::FinalConstruct() {
return S_OK;
}
void Bho::FinalRelease() {
}
namespace {
// See comments in Bho::OnHttpEquiv for details.
void ClearDocumentContents(IUnknown* browser) {
ScopedComPtr<IWebBrowser2> web_browser2;
if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
web_browser2.Receive()))) {
ScopedComPtr<IDispatch> doc_disp;
web_browser2->get_Document(doc_disp.Receive());
ScopedComPtr<IHTMLDocument2> doc;
if (doc_disp && SUCCEEDED(doc.QueryFrom(doc_disp))) {
SAFEARRAY* sa = ::SafeArrayCreateVector(VT_UI1, 0, 0);
doc->write(sa);
::SafeArrayDestroy(sa);
}
}
}
// Returns true if the currently loaded document in the browser has
// any embedded items such as a frame or an iframe.
bool DocumentHasEmbeddedItems(IUnknown* browser) {
bool has_embedded_items = false;
ScopedComPtr<IWebBrowser2> web_browser2;
ScopedComPtr<IDispatch> document;
if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
web_browser2.Receive())) &&
SUCCEEDED(web_browser2->get_Document(document.Receive()))) {
ScopedComPtr<IOleContainer> container;
if (SUCCEEDED(container.QueryFrom(document))) {
ScopedComPtr<IEnumUnknown> enumerator;
container->EnumObjects(OLECONTF_EMBEDDINGS, enumerator.Receive());
if (enumerator) {
ScopedComPtr<IUnknown> unk;
DWORD fetched = 0;
enumerator->Next(1, unk.Receive(), &fetched);
has_embedded_items = (fetched != 0);
}
}
}
return has_embedded_items;
}
HRESULT DeletePreviousNavigationEntry(IBrowserService* browser) {
DCHECK(browser);
ScopedComPtr<ITravelLog> travel_log;
HRESULT hr = browser->GetTravelLog(travel_log.Receive());
DCHECK(travel_log);
if (travel_log) {
ScopedComPtr<ITravelLogEx> travel_log_ex;
if (SUCCEEDED(hr = travel_log_ex.QueryFrom(travel_log)) ||
SUCCEEDED(hr = travel_log.QueryInterface(__uuidof(IIEITravelLogEx),
reinterpret_cast<void**>(travel_log_ex.Receive())))) {
hr = travel_log_ex->DeleteIndexEntry(browser, -1);
} else {
NOTREACHED() << "ITravelLogEx";
}
}
return hr;
}
} // end namespace
HRESULT Bho::OnHttpEquiv(IBrowserService_OnHttpEquiv_Fn original_httpequiv,
IBrowserService* browser, IShellView* shell_view, BOOL done,
VARIANT* in_arg, VARIANT* out_arg) {
DLOG(INFO) << __FUNCTION__ << " done:" << done;
// OnHttpEquiv with 'done' set to TRUE is called for all pages.
// 0 or more calls with done set to FALSE are made.
// When done is FALSE, the current moniker may not represent the page
// being navigated to so we always have to wait for done to be TRUE
// before re-initiating the navigation.
if (done) {
if (CheckForCFNavigation(browser, false)) {
// TODO(tommi): See if we can't figure out a cleaner way to avoid this.
// For small documents we can hit a problem here. When we attempt to
// navigate the document again in CF, mshtml can "complete" the current
// navigation (if all data is available) and fire off script events such
// as onload and even render the page. This will happen inside
// NavigateBrowserToMoniker below.
// To work around this, we clear the contents of the document before
// opening it up in CF.
ClearDocumentContents(browser);
ScopedComPtr<IOleObject> mshtml_ole_object;
HRESULT hr = shell_view->GetItemObject(SVGIO_BACKGROUND, IID_IOleObject,
reinterpret_cast<void**>(mshtml_ole_object.Receive()));
DCHECK(FAILED(hr) || mshtml_ole_object != NULL);
if (mshtml_ole_object) {
ScopedComPtr<IMoniker> moniker;
hr = mshtml_ole_object->GetMoniker(OLEGETMONIKER_ONLYIFTHERE,
OLEWHICHMK_OBJFULL, moniker.Receive());
DCHECK(FAILED(hr) || moniker != NULL);
if (moniker) {
DLOG(INFO) << "Navigating in CF";
ScopedComPtr<IBindCtx> bind_context;
// This bind context will be discarded by IE and a new one
// constructed, so it's OK to create a sync bind context.
::CreateBindCtx(0, bind_context.Receive());
DCHECK(bind_context);
// If there's a referrer, preserve it.
std::wstring headers;
// Pass in URL fragments if applicable.
std::wstring fragment;
Bho* chrome_frame_bho = Bho::GetCurrentThreadBhoInstance();
if (chrome_frame_bho) {
if (!chrome_frame_bho->referrer().empty()) {
headers = StringPrintf(L"Referer: %ls\r\n\r\n",
ASCIIToWide(chrome_frame_bho->referrer()).c_str());
}
// If the original URL contains an anchor, then the URL queried
// from the moniker does not contain the anchor. To workaround
// this we retrieve the URL from our BHO.
std::wstring moniker_url = GetActualUrlFromMoniker(
moniker, NULL, chrome_frame_bho->url());
GURL parsed_moniker_url(moniker_url);
if (parsed_moniker_url.has_ref()) {
fragment = UTF8ToWide(parsed_moniker_url.ref());
}
}
hr = NavigateBrowserToMoniker(browser, moniker, headers.c_str(),
bind_context, fragment.c_str());
if (SUCCEEDED(hr)) {
// Now that we've reissued the request, we need to remove the
// original one from the travel log.
DeletePreviousNavigationEntry(browser);
}
} else {
DLOG(ERROR) << "Couldn't get the current moniker";
}
}
if (FAILED(hr)) {
NOTREACHED();
// Lower the flag.
CheckForCFNavigation(browser, true);
} else {
// The navigate-in-gcf flag will be cleared in
// HttpNegotiatePatch::ReportProgress when the mime type is reported.
}
}
} else if (in_arg && VT_BSTR == V_VT(in_arg)) {
if (StrStrI(V_BSTR(in_arg), kChromeContentPrefix)) {
// OnHttpEquiv is invoked for meta tags within sub frames as well.
// We want to switch renderers only for the top level frame.
// The theory here is that if there are any existing embedded items
// (frames or iframes) in the current document, then the http-equiv
// notification is coming from those and not the top level document.
// The embedded items should only be created once the top level
// doc has been created.
if (!DocumentHasEmbeddedItems(browser))
MarkBrowserOnThreadForCFNavigation(browser);
}
}
return original_httpequiv(browser, shell_view, done, in_arg, out_arg);
}
Bho* Bho::GetCurrentThreadBhoInstance() {
DCHECK(bho_current_thread_instance_.Pointer()->Get() != NULL);
return bho_current_thread_instance_.Pointer()->Get();
}
namespace {
// Utility function that prevents the current module from ever being unloaded.
void PinModule() {
FilePath module_path;
if (PathService::Get(base::FILE_MODULE, &module_path)) {
HMODULE unused;
if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_PIN,
module_path.value().c_str(), &unused)) {
NOTREACHED() << "Failed to pin module " << module_path.value().c_str()
<< " , last error: " << GetLastError();
}
} else {
NOTREACHED() << "Could not get module path.";
}
}
} // namespace
bool PatchHelper::InitializeAndPatchProtocolsIfNeeded() {
bool ret = false;
_pAtlModule->m_csStaticDataInitAndTypeInfo.Lock();
if (state_ == UNKNOWN) {
// If we're going to start patching things, we'd better make sure that we
// stick around for ever more:
PinModule();
HttpNegotiatePatch::Initialize();
bool patch_protocol = GetConfigBool(false, kPatchProtocols);
if (patch_protocol) {
ProtocolSinkWrap::PatchProtocolHandlers();
state_ = PATCH_PROTOCOL;
} else {
state_ = PATCH_IBROWSER;
}
ret = true;
}
_pAtlModule->m_csStaticDataInitAndTypeInfo.Unlock();
return ret;
}
void PatchHelper::PatchBrowserService(IBrowserService* browser_service) {
DCHECK(state_ == PATCH_IBROWSER);
vtable_patch::PatchInterfaceMethods(browser_service,
IBrowserService_PatchInfo);
}
void PatchHelper::UnpatchIfNeeded() {
if (state_ == PATCH_PROTOCOL) {
ProtocolSinkWrap::UnpatchProtocolHandlers();
} else if (state_ == PATCH_IBROWSER) {
vtable_patch::UnpatchInterfaceMethods(IBrowserService_PatchInfo);
}
HttpNegotiatePatch::Uninitialize();
state_ = UNKNOWN;
}
<commit_msg>Avoid a DCHECK. Check if the interface is already patched before patching.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/bho.h"
#include <shlguid.h>
#include <shobjidl.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "chrome_tab.h" // NOLINT
#include "chrome_frame/extra_system_apis.h"
#include "chrome_frame/http_negotiate.h"
#include "chrome_frame/protocol_sink_wrap.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"
#include "net/http/http_util.h"
const wchar_t kPatchProtocols[] = L"PatchProtocols";
static const int kIBrowserServiceOnHttpEquivIndex = 30;
base::LazyInstance<base::ThreadLocalPointer<Bho> >
Bho::bho_current_thread_instance_(base::LINKER_INITIALIZED);
PatchHelper g_patch_helper;
BEGIN_VTABLE_PATCHES(IBrowserService)
VTABLE_PATCH_ENTRY(kIBrowserServiceOnHttpEquivIndex, Bho::OnHttpEquiv)
END_VTABLE_PATCHES()
_ATL_FUNC_INFO Bho::kBeforeNavigate2Info = {
CC_STDCALL, VT_EMPTY, 7, {
VT_DISPATCH,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_BOOL | VT_BYREF
}
};
Bho::Bho() {
}
STDMETHODIMP Bho::SetSite(IUnknown* site) {
HRESULT hr = S_OK;
if (site) {
ScopedComPtr<IWebBrowser2> web_browser2;
web_browser2.QueryFrom(site);
if (web_browser2) {
hr = DispEventAdvise(web_browser2, &DIID_DWebBrowserEvents2);
DCHECK(SUCCEEDED(hr)) << "DispEventAdvise failed. Error: " << hr;
}
if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
ScopedComPtr<IBrowserService> browser_service;
hr = DoQueryService(SID_SShellBrowser, site, browser_service.Receive());
DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed."
<< " Site: " << site << " Error: " << hr;
if (browser_service) {
g_patch_helper.PatchBrowserService(browser_service);
DCHECK(SUCCEEDED(hr)) << "vtable_patch::PatchInterfaceMethods failed."
<< " Site: " << site << " Error: " << hr;
}
}
// Save away our BHO instance in TLS which enables it to be referenced by
// our active document/activex instances to query referrer and other
// information for a URL.
AddRef();
bho_current_thread_instance_.Pointer()->Set(this);
} else {
bho_current_thread_instance_.Pointer()->Set(NULL);
Release();
}
return IObjectWithSiteImpl<Bho>::SetSite(site);
}
STDMETHODIMP Bho::BeforeNavigate2(IDispatch* dispatch, VARIANT* url,
VARIANT* flags, VARIANT* target_frame_name, VARIANT* post_data,
VARIANT* headers, VARIANT_BOOL* cancel) {
ScopedComPtr<IWebBrowser2> web_browser2;
if (dispatch)
web_browser2.QueryFrom(dispatch);
if (!web_browser2) {
NOTREACHED() << "Can't find WebBrowser2 with given dispatch";
return S_OK; // Return success, we operate on best effort basis.
}
DLOG(INFO) << "BeforeNavigate2: " << url->bstrVal;
if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
VARIANT_BOOL is_top_level = VARIANT_FALSE;
web_browser2->get_TopLevelContainer(&is_top_level);
std::wstring current_url;
bool is_chrome_protocol = false;
if (is_top_level && IsValidUrlScheme(url->bstrVal, false)) {
current_url.assign(url->bstrVal, SysStringLen(url->bstrVal));
is_chrome_protocol = StartsWith(current_url, kChromeProtocolPrefix,
false);
if (!is_chrome_protocol && IsOptInUrl(current_url.c_str())) {
DLOG(INFO) << "Opt-in URL. Switching to cf.";
ScopedComPtr<IBrowserService> browser_service;
DoQueryService(SID_SShellBrowser, web_browser2,
browser_service.Receive());
DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed.";
MarkBrowserOnThreadForCFNavigation(browser_service);
}
}
}
referrer_.clear();
// Save away the referrer in case our active document needs it to initiate
// navigation in chrome.
if (headers && V_VT(headers) == VT_BSTR && headers->bstrVal != NULL) {
std::string raw_headers_utf8 = WideToUTF8(headers->bstrVal);
std::string http_headers =
net::HttpUtil::AssembleRawHeaders(raw_headers_utf8.c_str(),
raw_headers_utf8.length());
net::HttpUtil::HeadersIterator it(http_headers.begin(), http_headers.end(),
"\r\n");
while (it.GetNext()) {
if (LowerCaseEqualsASCII(it.name(), "referer")) {
referrer_ = it.values();
break;
}
}
}
url_ = url->bstrVal;
return S_OK;
}
HRESULT Bho::FinalConstruct() {
return S_OK;
}
void Bho::FinalRelease() {
}
namespace {
// See comments in Bho::OnHttpEquiv for details.
void ClearDocumentContents(IUnknown* browser) {
ScopedComPtr<IWebBrowser2> web_browser2;
if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
web_browser2.Receive()))) {
ScopedComPtr<IDispatch> doc_disp;
web_browser2->get_Document(doc_disp.Receive());
ScopedComPtr<IHTMLDocument2> doc;
if (doc_disp && SUCCEEDED(doc.QueryFrom(doc_disp))) {
SAFEARRAY* sa = ::SafeArrayCreateVector(VT_UI1, 0, 0);
doc->write(sa);
::SafeArrayDestroy(sa);
}
}
}
// Returns true if the currently loaded document in the browser has
// any embedded items such as a frame or an iframe.
bool DocumentHasEmbeddedItems(IUnknown* browser) {
bool has_embedded_items = false;
ScopedComPtr<IWebBrowser2> web_browser2;
ScopedComPtr<IDispatch> document;
if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
web_browser2.Receive())) &&
SUCCEEDED(web_browser2->get_Document(document.Receive()))) {
ScopedComPtr<IOleContainer> container;
if (SUCCEEDED(container.QueryFrom(document))) {
ScopedComPtr<IEnumUnknown> enumerator;
container->EnumObjects(OLECONTF_EMBEDDINGS, enumerator.Receive());
if (enumerator) {
ScopedComPtr<IUnknown> unk;
DWORD fetched = 0;
enumerator->Next(1, unk.Receive(), &fetched);
has_embedded_items = (fetched != 0);
}
}
}
return has_embedded_items;
}
HRESULT DeletePreviousNavigationEntry(IBrowserService* browser) {
DCHECK(browser);
ScopedComPtr<ITravelLog> travel_log;
HRESULT hr = browser->GetTravelLog(travel_log.Receive());
DCHECK(travel_log);
if (travel_log) {
ScopedComPtr<ITravelLogEx> travel_log_ex;
if (SUCCEEDED(hr = travel_log_ex.QueryFrom(travel_log)) ||
SUCCEEDED(hr = travel_log.QueryInterface(__uuidof(IIEITravelLogEx),
reinterpret_cast<void**>(travel_log_ex.Receive())))) {
hr = travel_log_ex->DeleteIndexEntry(browser, -1);
} else {
NOTREACHED() << "ITravelLogEx";
}
}
return hr;
}
} // end namespace
HRESULT Bho::OnHttpEquiv(IBrowserService_OnHttpEquiv_Fn original_httpequiv,
IBrowserService* browser, IShellView* shell_view, BOOL done,
VARIANT* in_arg, VARIANT* out_arg) {
DLOG(INFO) << __FUNCTION__ << " done:" << done;
// OnHttpEquiv with 'done' set to TRUE is called for all pages.
// 0 or more calls with done set to FALSE are made.
// When done is FALSE, the current moniker may not represent the page
// being navigated to so we always have to wait for done to be TRUE
// before re-initiating the navigation.
if (done) {
if (CheckForCFNavigation(browser, false)) {
// TODO(tommi): See if we can't figure out a cleaner way to avoid this.
// For small documents we can hit a problem here. When we attempt to
// navigate the document again in CF, mshtml can "complete" the current
// navigation (if all data is available) and fire off script events such
// as onload and even render the page. This will happen inside
// NavigateBrowserToMoniker below.
// To work around this, we clear the contents of the document before
// opening it up in CF.
ClearDocumentContents(browser);
ScopedComPtr<IOleObject> mshtml_ole_object;
HRESULT hr = shell_view->GetItemObject(SVGIO_BACKGROUND, IID_IOleObject,
reinterpret_cast<void**>(mshtml_ole_object.Receive()));
DCHECK(FAILED(hr) || mshtml_ole_object != NULL);
if (mshtml_ole_object) {
ScopedComPtr<IMoniker> moniker;
hr = mshtml_ole_object->GetMoniker(OLEGETMONIKER_ONLYIFTHERE,
OLEWHICHMK_OBJFULL, moniker.Receive());
DCHECK(FAILED(hr) || moniker != NULL);
if (moniker) {
DLOG(INFO) << "Navigating in CF";
ScopedComPtr<IBindCtx> bind_context;
// This bind context will be discarded by IE and a new one
// constructed, so it's OK to create a sync bind context.
::CreateBindCtx(0, bind_context.Receive());
DCHECK(bind_context);
// If there's a referrer, preserve it.
std::wstring headers;
// Pass in URL fragments if applicable.
std::wstring fragment;
Bho* chrome_frame_bho = Bho::GetCurrentThreadBhoInstance();
if (chrome_frame_bho) {
if (!chrome_frame_bho->referrer().empty()) {
headers = StringPrintf(L"Referer: %ls\r\n\r\n",
ASCIIToWide(chrome_frame_bho->referrer()).c_str());
}
// If the original URL contains an anchor, then the URL queried
// from the moniker does not contain the anchor. To workaround
// this we retrieve the URL from our BHO.
std::wstring moniker_url = GetActualUrlFromMoniker(
moniker, NULL, chrome_frame_bho->url());
GURL parsed_moniker_url(moniker_url);
if (parsed_moniker_url.has_ref()) {
fragment = UTF8ToWide(parsed_moniker_url.ref());
}
}
hr = NavigateBrowserToMoniker(browser, moniker, headers.c_str(),
bind_context, fragment.c_str());
if (SUCCEEDED(hr)) {
// Now that we've reissued the request, we need to remove the
// original one from the travel log.
DeletePreviousNavigationEntry(browser);
}
} else {
DLOG(ERROR) << "Couldn't get the current moniker";
}
}
if (FAILED(hr)) {
NOTREACHED();
// Lower the flag.
CheckForCFNavigation(browser, true);
} else {
// The navigate-in-gcf flag will be cleared in
// HttpNegotiatePatch::ReportProgress when the mime type is reported.
}
}
} else if (in_arg && VT_BSTR == V_VT(in_arg)) {
if (StrStrI(V_BSTR(in_arg), kChromeContentPrefix)) {
// OnHttpEquiv is invoked for meta tags within sub frames as well.
// We want to switch renderers only for the top level frame.
// The theory here is that if there are any existing embedded items
// (frames or iframes) in the current document, then the http-equiv
// notification is coming from those and not the top level document.
// The embedded items should only be created once the top level
// doc has been created.
if (!DocumentHasEmbeddedItems(browser))
MarkBrowserOnThreadForCFNavigation(browser);
}
}
return original_httpequiv(browser, shell_view, done, in_arg, out_arg);
}
Bho* Bho::GetCurrentThreadBhoInstance() {
DCHECK(bho_current_thread_instance_.Pointer()->Get() != NULL);
return bho_current_thread_instance_.Pointer()->Get();
}
namespace {
// Utility function that prevents the current module from ever being unloaded.
void PinModule() {
FilePath module_path;
if (PathService::Get(base::FILE_MODULE, &module_path)) {
HMODULE unused;
if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_PIN,
module_path.value().c_str(), &unused)) {
NOTREACHED() << "Failed to pin module " << module_path.value().c_str()
<< " , last error: " << GetLastError();
}
} else {
NOTREACHED() << "Could not get module path.";
}
}
} // namespace
bool PatchHelper::InitializeAndPatchProtocolsIfNeeded() {
bool ret = false;
_pAtlModule->m_csStaticDataInitAndTypeInfo.Lock();
if (state_ == UNKNOWN) {
// If we're going to start patching things, we'd better make sure that we
// stick around for ever more:
PinModule();
HttpNegotiatePatch::Initialize();
bool patch_protocol = GetConfigBool(false, kPatchProtocols);
if (patch_protocol) {
ProtocolSinkWrap::PatchProtocolHandlers();
state_ = PATCH_PROTOCOL;
} else {
state_ = PATCH_IBROWSER;
}
ret = true;
}
_pAtlModule->m_csStaticDataInitAndTypeInfo.Unlock();
return ret;
}
void PatchHelper::PatchBrowserService(IBrowserService* browser_service) {
DCHECK(state_ == PATCH_IBROWSER);
if (!IS_PATCHED(IBrowserService)) {
vtable_patch::PatchInterfaceMethods(browser_service,
IBrowserService_PatchInfo);
}
}
void PatchHelper::UnpatchIfNeeded() {
if (state_ == PATCH_PROTOCOL) {
ProtocolSinkWrap::UnpatchProtocolHandlers();
} else if (state_ == PATCH_IBROWSER) {
vtable_patch::UnpatchInterfaceMethods(IBrowserService_PatchInfo);
}
HttpNegotiatePatch::Uninitialize();
state_ = UNKNOWN;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if !OS(WIN) && !OS(ANDROID)
#include "SkFontConfigInterface.h"
#endif
#include "SkFontMgr.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "platform/NotImplemented.h"
#include "platform/fonts/AlternateFontFamily.h"
#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "public/platform/Platform.h"
#include "public/platform/linux/WebSandboxSupport.h"
#include "wtf/Assertions.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/CString.h"
#include <unicode/locid.h>
#if !OS(WIN) && !OS(ANDROID)
static SkStream* streamForFontconfigInterfaceId(int fontconfigInterfaceId)
{
SkAutoTUnref<SkFontConfigInterface> fci(SkFontConfigInterface::RefGlobal());
SkFontConfigInterface::FontIdentity fontIdentity;
fontIdentity.fID = fontconfigInterfaceId;
return fci->openStream(fontIdentity);
}
#endif
namespace WebCore {
void FontCache::platformInit()
{
}
PassRefPtr<SimpleFontData> FontCache::fallbackOnStandardFontStyle(
const FontDescription& fontDescription, UChar32 character)
{
FontDescription substituteDescription(fontDescription);
substituteDescription.setStyle(FontStyleNormal);
substituteDescription.setWeight(FontWeightNormal);
FontFaceCreationParams creationParams(substituteDescription.family().family());
FontPlatformData* substitutePlatformData = getFontPlatformData(substituteDescription, creationParams);
if (substitutePlatformData && substitutePlatformData->fontContainsCharacter(character)) {
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(fontDescription.weight() >= FontWeight600);
platformData.setSyntheticItalic(fontDescription.style() == FontStyleItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
return nullptr;
}
#if !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeight600) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, c);
if (fontData)
return fontData;
}
FontCache::PlatformFallbackFont fallbackFont;
FontCache::getFontForCharacter(c, "", &fallbackFont);
if (fallbackFont.name.isEmpty())
return nullptr;
FontFaceCreationParams creationParams;
creationParams = FontFaceCreationParams(fallbackFont.filename, fallbackFont.fontconfigInterfaceId, fallbackFont.ttcIndex);
// Changes weight and/or italic of given FontDescription depends on
// the result of fontconfig so that keeping the correct font mapping
// of the given character. See http://crbug.com/32109 for details.
bool shouldSetSyntheticBold = false;
bool shouldSetSyntheticItalic = false;
FontDescription description(fontDescription);
if (fallbackFont.isBold && description.weight() < FontWeightBold)
description.setWeight(FontWeightBold);
if (!fallbackFont.isBold && description.weight() >= FontWeightBold) {
shouldSetSyntheticBold = true;
description.setWeight(FontWeightNormal);
}
if (fallbackFont.isItalic && description.style() == FontStyleNormal)
description.setStyle(FontStyleItalic);
if (!fallbackFont.isItalic && description.style() == FontStyleItalic) {
shouldSetSyntheticItalic = true;
description.setStyle(FontStyleNormal);
}
FontPlatformData* substitutePlatformData = getFontPlatformData(description, creationParams);
if (!substitutePlatformData)
return nullptr;
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(shouldSetSyntheticBold);
platformData.setSyntheticItalic(shouldSetSyntheticItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
#endif // !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
{
const FontFaceCreationParams fallbackCreationParams(getFallbackFontFamily(description));
const FontPlatformData* fontPlatformData = getFontPlatformData(description, fallbackCreationParams);
// We should at least have Sans or Arial which is the last resort fallback of SkFontHost ports.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, sansCreationParams, (AtomicString("Sans", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, sansCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, arialCreationParams, (AtomicString("Arial", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, arialCreationParams);
}
ASSERT(fontPlatformData);
return fontDataFromFontPlatformData(fontPlatformData, shouldRetain);
}
PassRefPtr<SkTypeface> FontCache::createTypeface(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, CString& name)
{
#if !OS(WIN) && !OS(ANDROID)
if (creationParams.creationType() == CreateFontByFciIdAndTtcIndex) {
// TODO(dro): crbug.com/381620 Use creationParams.ttcIndex() after
// https://code.google.com/p/skia/issues/detail?id=1186 gets fixed.
SkTypeface* typeface = nullptr;
if (blink::Platform::current()->sandboxSupport())
typeface = SkTypeface::CreateFromStream(streamForFontconfigInterfaceId(creationParams.fontconfigInterfaceId()));
else
typeface = SkTypeface::CreateFromFile(creationParams.filename().data());
if (typeface)
return adoptRef(typeface);
}
#endif
AtomicString family = creationParams.family();
// If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
// the fallback name (like "monospace") that fontconfig understands.
if (!family.length() || family.startsWith("-webkit-")) {
name = getFallbackFontFamily(fontDescription).string().utf8();
} else {
// convert the name to utf8
name = family.utf8();
}
int style = SkTypeface::kNormal;
if (fontDescription.weight() >= FontWeight600)
style |= SkTypeface::kBold;
if (fontDescription.style())
style |= SkTypeface::kItalic;
#if OS(WIN)
if (s_sideloadedFonts) {
HashMap<String, SkTypeface*>::iterator sideloadedFont = s_sideloadedFonts->find(name.data());
if (sideloadedFont != s_sideloadedFonts->end()) {
return adoptRef(sideloadedFont->value);
}
}
// FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
if (m_fontManager)
return adoptRef(m_fontManager->legacyCreateTypeface(name.data(), style));
#endif
return adoptRef(SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style)));
}
#if !OS(WIN)
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
CString name;
RefPtr<SkTypeface> tf(createTypeface(fontDescription, creationParams, name));
if (!tf)
return 0;
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
(fontDescription.weight() >= FontWeight600 && !tf->isBold()) || fontDescription.isSyntheticBold(),
(fontDescription.style() && !tf->isItalic()) || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
fontDescription.useSubpixelPositioning());
return result;
}
#endif // !OS(WIN)
} // namespace WebCore
<commit_msg>Add more Windows-specific fonts to fallback path<commit_after>/*
* Copyright (c) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if !OS(WIN) && !OS(ANDROID)
#include "SkFontConfigInterface.h"
#endif
#include "SkFontMgr.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "platform/NotImplemented.h"
#include "platform/fonts/AlternateFontFamily.h"
#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "public/platform/Platform.h"
#include "public/platform/linux/WebSandboxSupport.h"
#include "wtf/Assertions.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/CString.h"
#include <unicode/locid.h>
#if !OS(WIN) && !OS(ANDROID)
static SkStream* streamForFontconfigInterfaceId(int fontconfigInterfaceId)
{
SkAutoTUnref<SkFontConfigInterface> fci(SkFontConfigInterface::RefGlobal());
SkFontConfigInterface::FontIdentity fontIdentity;
fontIdentity.fID = fontconfigInterfaceId;
return fci->openStream(fontIdentity);
}
#endif
namespace WebCore {
void FontCache::platformInit()
{
}
PassRefPtr<SimpleFontData> FontCache::fallbackOnStandardFontStyle(
const FontDescription& fontDescription, UChar32 character)
{
FontDescription substituteDescription(fontDescription);
substituteDescription.setStyle(FontStyleNormal);
substituteDescription.setWeight(FontWeightNormal);
FontFaceCreationParams creationParams(substituteDescription.family().family());
FontPlatformData* substitutePlatformData = getFontPlatformData(substituteDescription, creationParams);
if (substitutePlatformData && substitutePlatformData->fontContainsCharacter(character)) {
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(fontDescription.weight() >= FontWeight600);
platformData.setSyntheticItalic(fontDescription.style() == FontStyleItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
return nullptr;
}
#if !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeight600) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, c);
if (fontData)
return fontData;
}
FontCache::PlatformFallbackFont fallbackFont;
FontCache::getFontForCharacter(c, "", &fallbackFont);
if (fallbackFont.name.isEmpty())
return nullptr;
FontFaceCreationParams creationParams;
creationParams = FontFaceCreationParams(fallbackFont.filename, fallbackFont.fontconfigInterfaceId, fallbackFont.ttcIndex);
// Changes weight and/or italic of given FontDescription depends on
// the result of fontconfig so that keeping the correct font mapping
// of the given character. See http://crbug.com/32109 for details.
bool shouldSetSyntheticBold = false;
bool shouldSetSyntheticItalic = false;
FontDescription description(fontDescription);
if (fallbackFont.isBold && description.weight() < FontWeightBold)
description.setWeight(FontWeightBold);
if (!fallbackFont.isBold && description.weight() >= FontWeightBold) {
shouldSetSyntheticBold = true;
description.setWeight(FontWeightNormal);
}
if (fallbackFont.isItalic && description.style() == FontStyleNormal)
description.setStyle(FontStyleItalic);
if (!fallbackFont.isItalic && description.style() == FontStyleItalic) {
shouldSetSyntheticItalic = true;
description.setStyle(FontStyleNormal);
}
FontPlatformData* substitutePlatformData = getFontPlatformData(description, creationParams);
if (!substitutePlatformData)
return nullptr;
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(shouldSetSyntheticBold);
platformData.setSyntheticItalic(shouldSetSyntheticItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
#endif // !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
{
const FontFaceCreationParams fallbackCreationParams(getFallbackFontFamily(description));
const FontPlatformData* fontPlatformData = getFontPlatformData(description, fallbackCreationParams);
// We should at least have Sans or Arial which is the last resort fallback of SkFontHost ports.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, sansCreationParams, (AtomicString("Sans", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, sansCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, arialCreationParams, (AtomicString("Arial", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, arialCreationParams);
}
#if OS(WIN)
// Try some more Windows-specific fallbacks.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, msuigothicCreationParams, (AtomicString("MS UI Gothic", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, msuigothicCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, mssansserifCreationParams, (AtomicString("Microsoft Sans Serif", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, mssansserifCreationParams);
}
#endif
ASSERT(fontPlatformData);
return fontDataFromFontPlatformData(fontPlatformData, shouldRetain);
}
PassRefPtr<SkTypeface> FontCache::createTypeface(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, CString& name)
{
#if !OS(WIN) && !OS(ANDROID)
if (creationParams.creationType() == CreateFontByFciIdAndTtcIndex) {
// TODO(dro): crbug.com/381620 Use creationParams.ttcIndex() after
// https://code.google.com/p/skia/issues/detail?id=1186 gets fixed.
SkTypeface* typeface = nullptr;
if (blink::Platform::current()->sandboxSupport())
typeface = SkTypeface::CreateFromStream(streamForFontconfigInterfaceId(creationParams.fontconfigInterfaceId()));
else
typeface = SkTypeface::CreateFromFile(creationParams.filename().data());
if (typeface)
return adoptRef(typeface);
}
#endif
AtomicString family = creationParams.family();
// If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
// the fallback name (like "monospace") that fontconfig understands.
if (!family.length() || family.startsWith("-webkit-")) {
name = getFallbackFontFamily(fontDescription).string().utf8();
} else {
// convert the name to utf8
name = family.utf8();
}
int style = SkTypeface::kNormal;
if (fontDescription.weight() >= FontWeight600)
style |= SkTypeface::kBold;
if (fontDescription.style())
style |= SkTypeface::kItalic;
#if OS(WIN)
if (s_sideloadedFonts) {
HashMap<String, SkTypeface*>::iterator sideloadedFont = s_sideloadedFonts->find(name.data());
if (sideloadedFont != s_sideloadedFonts->end()) {
return adoptRef(sideloadedFont->value);
}
}
// FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
if (m_fontManager)
return adoptRef(m_fontManager->legacyCreateTypeface(name.data(), style));
#endif
return adoptRef(SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style)));
}
#if !OS(WIN)
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
CString name;
RefPtr<SkTypeface> tf(createTypeface(fontDescription, creationParams, name));
if (!tf)
return 0;
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
(fontDescription.weight() >= FontWeight600 && !tf->isBold()) || fontDescription.isSyntheticBold(),
(fontDescription.style() && !tf->isItalic()) || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
fontDescription.useSubpixelPositioning());
return result;
}
#endif // !OS(WIN)
} // namespace WebCore
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <os.hpp>
#include <kernel.hpp>
#include <kernel/rng.hpp>
#include <service>
#include <cstdio>
#include <cinttypes>
#include <util/fixed_vector.hpp>
#include <system_log>
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
using namespace util;
extern char _start;
extern char _end;
extern char _ELF_START_;
extern char _TEXT_START_;
extern char _LOAD_START_;
extern char _ELF_END_;
//uintptr_t OS::liveupdate_loc_ = 0;
kernel::State __kern_state;
kernel::State& kernel::state() noexcept {
return __kern_state;
}
util::KHz os::cpu_freq() {
return kernel::cpu_freq();
}
const uintptr_t elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
// stdout redirection
using Print_vec = Fixed_vector<os::print_func, 8>;
static Print_vec os_print_handlers(Fixedvector_Init::UNINIT);
// Plugins
struct Plugin_desc {
Plugin_desc(os::Plugin f, const char* n) : func{f}, name{n} {}
os::Plugin func;
const char* name;
};
static Fixed_vector<Plugin_desc, 16> plugins(Fixedvector_Init::UNINIT);
__attribute__((weak))
size_t kernel::liveupdate_phys_size(size_t /*phys_max*/) noexcept {
return 4096;
};
__attribute__((weak))
size_t kernel::liveupdate_phys_loc(size_t phys_max) noexcept {
return phys_max - liveupdate_phys_size(phys_max);
};
__attribute__((weak))
void kernel::setup_liveupdate(uintptr_t)
{
// without LiveUpdate: storage location is at the last page?
kernel::state().liveupdate_loc = kernel::heap_max() & ~(uintptr_t) 0xFFF;
}
const char* os::cmdline_args() noexcept {
return kernel::cmdline();
}
extern kernel::ctor_t __plugin_ctors_start;
extern kernel::ctor_t __plugin_ctors_end;
extern kernel::ctor_t __service_ctors_start;
extern kernel::ctor_t __service_ctors_end;
void os::register_plugin(Plugin delg, const char* name){
MYINFO("Registering plugin %s", name);
plugins.emplace_back(delg, name);
}
extern void __arch_reboot();
void os::reboot() noexcept
{
__arch_reboot();
}
void os::shutdown() noexcept
{
kernel::state().running = false;
}
void kernel::post_start()
{
// Enable timestamps (if present)
kernel::state().timestamps_ready = true;
// LiveUpdate needs some initialization, although only if present
kernel::setup_liveupdate();
// Initialize the system log if plugin is present.
// Dependent on the liveupdate location being set
SystemLog::initialize();
MYINFO("Initializing RNG");
PROFILE("RNG init");
RNG::get().init();
// Seed rand with 32 bits from RNG
srand(rng_extract_uint32());
// Custom initialization functions
MYINFO("Initializing plugins");
kernel::run_ctors(&__plugin_ctors_start, &__plugin_ctors_end);
// Run plugins
PROFILE("Plugins init");
for (auto plugin : plugins) {
INFO2("* Initializing %s", plugin.name);
plugin.func();
}
MYINFO("Running service constructors");
FILLINE('-');
// the boot sequence is over when we get to plugins/Service::start
kernel::state().boot_sequence_passed = true;
// Run service constructors
kernel::run_ctors(&__service_ctors_start, &__service_ctors_end);
PROFILE("Service::start");
// begin service start
FILLINE('=');
printf(" IncludeOS %s (%s / %u-bit)\n",
os::version(), os::arch(),
static_cast<unsigned>(sizeof(uintptr_t)) * 8);
printf(" +--> Running [ %s ]\n", Service::name());
FILLINE('~');
#if defined(LIBFUZZER_ENABLED) || defined(ARP_PASSTHROUGH) || defined(DISABLE_INET_CHECKSUMS)
printf(" +--> WARNiNG: Environment unsafe for production\n");
FILLINE('~');
#endif
Service::start();
}
void os::add_stdout(os::print_func func)
{
os_print_handlers.push_back(func);
}
__attribute__((weak))
bool os_enable_boot_logging = false;
__attribute__((weak))
bool os_default_stdout = false;
#include <isotime>
bool contains(const char* str, size_t len, char c)
{
for (size_t i = 0; i < len; i++) if (str[i] == c) return true;
return false;
}
void os::print(const char* str, const size_t len)
{
if (UNLIKELY(! kernel::libc_initialized())) {
kernel::default_stdout(str, len);
return;
}
/** TIMESTAMPING **/
if (kernel::timestamps() && kernel::timestamps_ready() && !kernel::is_panicking())
{
static bool apply_ts = true;
if (apply_ts)
{
std::string ts = "[" + isotime::now() + "] ";
for (const auto& callback : os_print_handlers) {
callback(ts.c_str(), ts.size());
}
apply_ts = false;
}
const bool has_newline = contains(str, len, '\n');
if (has_newline) apply_ts = true;
}
/** TIMESTAMPING **/
if (os_enable_boot_logging || kernel::is_booted() || kernel::is_panicking())
{
for (const auto& callback : os_print_handlers) {
callback(str, len);
}
}
}
void os::print_timestamps(const bool enabled)
{
kernel::state().timestamps = enabled;
}
<commit_msg>kernel: Disable plugin construction on MacOS<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <os.hpp>
#include <kernel.hpp>
#include <kernel/rng.hpp>
#include <service>
#include <cstdio>
#include <cinttypes>
#include <util/fixed_vector.hpp>
#include <system_log>
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
using namespace util;
extern char _start;
extern char _end;
extern char _ELF_START_;
extern char _TEXT_START_;
extern char _LOAD_START_;
extern char _ELF_END_;
//uintptr_t OS::liveupdate_loc_ = 0;
kernel::State __kern_state;
kernel::State& kernel::state() noexcept {
return __kern_state;
}
util::KHz os::cpu_freq() {
return kernel::cpu_freq();
}
const uintptr_t elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
// stdout redirection
using Print_vec = Fixed_vector<os::print_func, 8>;
static Print_vec os_print_handlers(Fixedvector_Init::UNINIT);
// Plugins
struct Plugin_desc {
Plugin_desc(os::Plugin f, const char* n) : func{f}, name{n} {}
os::Plugin func;
const char* name;
};
static Fixed_vector<Plugin_desc, 16> plugins(Fixedvector_Init::UNINIT);
__attribute__((weak))
size_t kernel::liveupdate_phys_size(size_t /*phys_max*/) noexcept {
return 4096;
};
__attribute__((weak))
size_t kernel::liveupdate_phys_loc(size_t phys_max) noexcept {
return phys_max - liveupdate_phys_size(phys_max);
};
__attribute__((weak))
void kernel::setup_liveupdate(uintptr_t)
{
// without LiveUpdate: storage location is at the last page?
kernel::state().liveupdate_loc = kernel::heap_max() & ~(uintptr_t) 0xFFF;
}
const char* os::cmdline_args() noexcept {
return kernel::cmdline();
}
extern kernel::ctor_t __plugin_ctors_start;
extern kernel::ctor_t __plugin_ctors_end;
extern kernel::ctor_t __service_ctors_start;
extern kernel::ctor_t __service_ctors_end;
void os::register_plugin(Plugin delg, const char* name){
MYINFO("Registering plugin %s", name);
plugins.emplace_back(delg, name);
}
extern void __arch_reboot();
void os::reboot() noexcept
{
__arch_reboot();
}
void os::shutdown() noexcept
{
kernel::state().running = false;
}
void kernel::post_start()
{
// Enable timestamps (if present)
kernel::state().timestamps_ready = true;
// LiveUpdate needs some initialization, although only if present
kernel::setup_liveupdate();
// Initialize the system log if plugin is present.
// Dependent on the liveupdate location being set
SystemLog::initialize();
MYINFO("Initializing RNG");
PROFILE("RNG init");
RNG::get().init();
// Seed rand with 32 bits from RNG
srand(rng_extract_uint32());
#ifndef __MACH__
// Custom initialization functions
MYINFO("Initializing plugins");
kernel::run_ctors(&__plugin_ctors_start, &__plugin_ctors_end);
#endif
// Run plugins
PROFILE("Plugins init");
for (auto plugin : plugins) {
INFO2("* Initializing %s", plugin.name);
plugin.func();
}
MYINFO("Running service constructors");
FILLINE('-');
// the boot sequence is over when we get to plugins/Service::start
kernel::state().boot_sequence_passed = true;
// Run service constructors
kernel::run_ctors(&__service_ctors_start, &__service_ctors_end);
PROFILE("Service::start");
// begin service start
FILLINE('=');
printf(" IncludeOS %s (%s / %u-bit)\n",
os::version(), os::arch(),
static_cast<unsigned>(sizeof(uintptr_t)) * 8);
printf(" +--> Running [ %s ]\n", Service::name());
FILLINE('~');
#if defined(LIBFUZZER_ENABLED) || defined(ARP_PASSTHROUGH) || defined(DISABLE_INET_CHECKSUMS)
printf(" +--> WARNiNG: Environment unsafe for production\n");
FILLINE('~');
#endif
Service::start();
}
void os::add_stdout(os::print_func func)
{
os_print_handlers.push_back(func);
}
__attribute__((weak))
bool os_enable_boot_logging = false;
__attribute__((weak))
bool os_default_stdout = false;
#include <isotime>
bool contains(const char* str, size_t len, char c)
{
for (size_t i = 0; i < len; i++) if (str[i] == c) return true;
return false;
}
void os::print(const char* str, const size_t len)
{
if (UNLIKELY(! kernel::libc_initialized())) {
kernel::default_stdout(str, len);
return;
}
/** TIMESTAMPING **/
if (kernel::timestamps() && kernel::timestamps_ready() && !kernel::is_panicking())
{
static bool apply_ts = true;
if (apply_ts)
{
std::string ts = "[" + isotime::now() + "] ";
for (const auto& callback : os_print_handlers) {
callback(ts.c_str(), ts.size());
}
apply_ts = false;
}
const bool has_newline = contains(str, len, '\n');
if (has_newline) apply_ts = true;
}
/** TIMESTAMPING **/
if (os_enable_boot_logging || kernel::is_booted() || kernel::is_panicking())
{
for (const auto& callback : os_print_handlers) {
callback(str, len);
}
}
}
void os::print_timestamps(const bool enabled)
{
kernel::state().timestamps = enabled;
}
<|endoftext|> |
<commit_before>// @(#)root/foam:$Name: $:$Id: TFoamMaxwt.cxx,v 1.4 2005/04/12 10:01:56 brun Exp $
// Author: S. Jadach <mailto:[email protected]>, P.Sawicki <mailto:[email protected]>
//____________________________________________________________________________
//
// Class TFoamMaxwt
// =================
// Small auxiliary class for controlling MC weight.
// It provides certain measure of the "maximum weight"
// depending on small user-parameter "epsilon".
// It creates and uses 2 histograms of the TH1D class.
// User defines no. of bins nBin, nBin=1000 is recommended
// wmax defines weight range (1,wmax), it is adjusted "manually"
//
//____________________________________________________________________________
#include "Riostream.h"
#include "TMath.h"
#include "TH1.h"
#include "TFoamMaxwt.h"
ClassImp(TFoamMaxwt);
//____________________________________________________________________________
TFoamMaxwt::TFoamMaxwt()
{
// Constructor for streamer
fNent = 0;
fnBin = 0;
fWtHst1 = 0;
fWtHst2 = 0;
}
//____________________________________________________________________________
TFoamMaxwt::TFoamMaxwt(Double_t wmax, const Int_t nBin)
{
// Principal user constructor
fNent = 0;
fnBin = nBin;
fwmax = wmax;
fWtHst1 = new TH1D("TFoamMaxwt_hst_Wt1","Histo of weight ",nBin,0.0,wmax);
fWtHst2 = new TH1D("TFoamMaxwt_hst_Wt2","Histo of weight**2",nBin,0.0,wmax);
fWtHst1->SetDirectory(0);// exclude from diskfile
fWtHst2->SetDirectory(0);// and enable deleting
}
//______________________________________________________________________________
TFoamMaxwt::TFoamMaxwt(TFoamMaxwt &From): TObject(From)
{
// Explicit COPY CONSTRUCTOR (unused, so far)
fnBin = From.fnBin;
fwmax = From.fwmax;
fWtHst1 = From.fWtHst1;
fWtHst2 = From.fWtHst2;
Error("TFoamMaxwt","COPY CONSTRUCTOR NOT TESTED!");
}
//_______________________________________________________________________________
TFoamMaxwt::~TFoamMaxwt()
{
// Destructor
delete fWtHst1; // For this SetDirectory(0) is needed!
delete fWtHst2; //
fWtHst1=0;
fWtHst2=0;
}
//_______________________________________________________________________________
void TFoamMaxwt::Reset()
{
// Reseting weight analysis
fNent = 0;
fWtHst1->Reset();
fWtHst2->Reset();
}
//_______________________________________________________________________________
TFoamMaxwt& TFoamMaxwt::operator =(TFoamMaxwt &From)
{
// substitution =
if (&From == this) return *this;
fnBin = From.fnBin;
fwmax = From.fwmax;
fWtHst1 = From.fWtHst1;
fWtHst2 = From.fWtHst2;
return *this;
}
//________________________________________________________________________________
void TFoamMaxwt::Fill(Double_t wt)
{
// Filling analysed weight
fNent = fNent+1.0;
fWtHst1->Fill(wt,1.0);
fWtHst2->Fill(wt,wt);
}
//________________________________________________________________________________
void TFoamMaxwt::Make(Double_t eps, Double_t &MCeff)
{
// Calculates Efficiency= AveWt/WtLim for a given tolerance level epsilon<<1
// To be called at the end of the MC run.
Double_t WtLim,AveWt;
GetMCeff(eps, MCeff, WtLim);
AveWt = MCeff*WtLim;
cout<< "00000000000000000000000000000000000000000000000000000000000000000000000"<<endl;
cout<< "00 -->WtLim: No_evt ="<<fNent<<" <Wt> = "<<AveWt<<" WtLim= "<<WtLim<<endl;
cout<< "00 -->WtLim: For eps = "<<eps <<" EFFICIENCY <Wt>/WtLim= "<<MCeff<<endl;
cout<< "00000000000000000000000000000000000000000000000000000000000000000000000"<<endl;
}
//_________________________________________________________________________________
void TFoamMaxwt::GetMCeff(Double_t eps, Double_t &MCeff, Double_t &WtLim)
{
// Calculates Efficiency= AveWt/WtLim for a given tolerance level epsilon<<1
// using information stored in two histograms.
// To be called at the end of the MC run.
Int_t ib,ibX;
Double_t LowEdge,Bin,Bin1;
Double_t AveWt, AveWt1;
fWtHst1->Print();
fWtHst2->Print();
// Convention on bin-numbering: nb=1 for 1-st bin, undeflow nb=0, overflow nb=Nb+1
Double_t sum = 0.0;
Double_t sumWt = 0.0;
for(ib=0;ib<=fnBin+1;ib++){
sum += fWtHst1->GetBinContent(ib);
sumWt += fWtHst2->GetBinContent(ib);
}
if( (sum == 0.0) || (sumWt == 0.0) ){
cout<<"TFoamMaxwt::Make: zero content of histogram !!!,sum,sumWt ="<<sum<<sumWt<<endl;
}
AveWt = sumWt/sum;
//--------------------------------------
for( ibX=fnBin+1; ibX>0; ibX--){
LowEdge = (ibX-1.0)*fwmax/fnBin;
sum = 0.0;
sumWt = 0.0;
for( ib=0; ib<=fnBin+1; ib++){
Bin = fWtHst1->GetBinContent(ib);
Bin1 = fWtHst2->GetBinContent(ib);
if(ib >= ibX) Bin1=LowEdge*Bin;
sum += Bin;
sumWt += Bin1;
}
AveWt1 = sumWt/sum;
if( TMath::Abs(1.0-AveWt1/AveWt) > eps ) break;
}
//---------------------------
if(ibX == (fnBin+1) ){
WtLim = 1.0e200;
MCeff = 0.0;
cout<< "+++++ WtLim undefined. Higher uper limit in histogram"<<endl;
}else if( ibX == 1){
WtLim = 0.0;
MCeff =-1.0;
cout<< "+++++ WtLim undefined. Lower uper limit or more bins "<<endl;
}else{
WtLim= (ibX)*fwmax/fnBin; // We over-estimate WtLim, under-estimate MCeff
MCeff = AveWt/WtLim;
}
}
///////////////////////////////////////////////////////////////////////////////
// //
// End of Class TFoamMaxwt //
// //
///////////////////////////////////////////////////////////////////////////////
<commit_msg>remove a const declaration in one constructor<commit_after>// @(#)root/foam:$Name: $:$Id: TFoamMaxwt.cxx,v 1.5 2005/04/12 12:31:39 brun Exp $
// Author: S. Jadach <mailto:[email protected]>, P.Sawicki <mailto:[email protected]>
//____________________________________________________________________________
//
// Class TFoamMaxwt
// =================
// Small auxiliary class for controlling MC weight.
// It provides certain measure of the "maximum weight"
// depending on small user-parameter "epsilon".
// It creates and uses 2 histograms of the TH1D class.
// User defines no. of bins nBin, nBin=1000 is recommended
// wmax defines weight range (1,wmax), it is adjusted "manually"
//
//____________________________________________________________________________
#include "Riostream.h"
#include "TMath.h"
#include "TH1.h"
#include "TFoamMaxwt.h"
ClassImp(TFoamMaxwt);
//____________________________________________________________________________
TFoamMaxwt::TFoamMaxwt()
{
// Constructor for streamer
fNent = 0;
fnBin = 0;
fWtHst1 = 0;
fWtHst2 = 0;
}
//____________________________________________________________________________
TFoamMaxwt::TFoamMaxwt(Double_t wmax, Int_t nBin)
{
// Principal user constructor
fNent = 0;
fnBin = nBin;
fwmax = wmax;
fWtHst1 = new TH1D("TFoamMaxwt_hst_Wt1","Histo of weight ",nBin,0.0,wmax);
fWtHst2 = new TH1D("TFoamMaxwt_hst_Wt2","Histo of weight**2",nBin,0.0,wmax);
fWtHst1->SetDirectory(0);// exclude from diskfile
fWtHst2->SetDirectory(0);// and enable deleting
}
//______________________________________________________________________________
TFoamMaxwt::TFoamMaxwt(TFoamMaxwt &From): TObject(From)
{
// Explicit COPY CONSTRUCTOR (unused, so far)
fnBin = From.fnBin;
fwmax = From.fwmax;
fWtHst1 = From.fWtHst1;
fWtHst2 = From.fWtHst2;
Error("TFoamMaxwt","COPY CONSTRUCTOR NOT TESTED!");
}
//_______________________________________________________________________________
TFoamMaxwt::~TFoamMaxwt()
{
// Destructor
delete fWtHst1; // For this SetDirectory(0) is needed!
delete fWtHst2; //
fWtHst1=0;
fWtHst2=0;
}
//_______________________________________________________________________________
void TFoamMaxwt::Reset()
{
// Reseting weight analysis
fNent = 0;
fWtHst1->Reset();
fWtHst2->Reset();
}
//_______________________________________________________________________________
TFoamMaxwt& TFoamMaxwt::operator =(TFoamMaxwt &From)
{
// substitution =
if (&From == this) return *this;
fnBin = From.fnBin;
fwmax = From.fwmax;
fWtHst1 = From.fWtHst1;
fWtHst2 = From.fWtHst2;
return *this;
}
//________________________________________________________________________________
void TFoamMaxwt::Fill(Double_t wt)
{
// Filling analysed weight
fNent = fNent+1.0;
fWtHst1->Fill(wt,1.0);
fWtHst2->Fill(wt,wt);
}
//________________________________________________________________________________
void TFoamMaxwt::Make(Double_t eps, Double_t &MCeff)
{
// Calculates Efficiency= AveWt/WtLim for a given tolerance level epsilon<<1
// To be called at the end of the MC run.
Double_t WtLim,AveWt;
GetMCeff(eps, MCeff, WtLim);
AveWt = MCeff*WtLim;
cout<< "00000000000000000000000000000000000000000000000000000000000000000000000"<<endl;
cout<< "00 -->WtLim: No_evt ="<<fNent<<" <Wt> = "<<AveWt<<" WtLim= "<<WtLim<<endl;
cout<< "00 -->WtLim: For eps = "<<eps <<" EFFICIENCY <Wt>/WtLim= "<<MCeff<<endl;
cout<< "00000000000000000000000000000000000000000000000000000000000000000000000"<<endl;
}
//_________________________________________________________________________________
void TFoamMaxwt::GetMCeff(Double_t eps, Double_t &MCeff, Double_t &WtLim)
{
// Calculates Efficiency= AveWt/WtLim for a given tolerance level epsilon<<1
// using information stored in two histograms.
// To be called at the end of the MC run.
Int_t ib,ibX;
Double_t LowEdge,Bin,Bin1;
Double_t AveWt, AveWt1;
fWtHst1->Print();
fWtHst2->Print();
// Convention on bin-numbering: nb=1 for 1-st bin, undeflow nb=0, overflow nb=Nb+1
Double_t sum = 0.0;
Double_t sumWt = 0.0;
for(ib=0;ib<=fnBin+1;ib++){
sum += fWtHst1->GetBinContent(ib);
sumWt += fWtHst2->GetBinContent(ib);
}
if( (sum == 0.0) || (sumWt == 0.0) ){
cout<<"TFoamMaxwt::Make: zero content of histogram !!!,sum,sumWt ="<<sum<<sumWt<<endl;
}
AveWt = sumWt/sum;
//--------------------------------------
for( ibX=fnBin+1; ibX>0; ibX--){
LowEdge = (ibX-1.0)*fwmax/fnBin;
sum = 0.0;
sumWt = 0.0;
for( ib=0; ib<=fnBin+1; ib++){
Bin = fWtHst1->GetBinContent(ib);
Bin1 = fWtHst2->GetBinContent(ib);
if(ib >= ibX) Bin1=LowEdge*Bin;
sum += Bin;
sumWt += Bin1;
}
AveWt1 = sumWt/sum;
if( TMath::Abs(1.0-AveWt1/AveWt) > eps ) break;
}
//---------------------------
if(ibX == (fnBin+1) ){
WtLim = 1.0e200;
MCeff = 0.0;
cout<< "+++++ WtLim undefined. Higher uper limit in histogram"<<endl;
}else if( ibX == 1){
WtLim = 0.0;
MCeff =-1.0;
cout<< "+++++ WtLim undefined. Lower uper limit or more bins "<<endl;
}else{
WtLim= (ibX)*fwmax/fnBin; // We over-estimate WtLim, under-estimate MCeff
MCeff = AveWt/WtLim;
}
}
///////////////////////////////////////////////////////////////////////////////
// //
// End of Class TFoamMaxwt //
// //
///////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "brawlmd5.h"
#include "brawlextract.h"
#include "find_children.h"
#include "usage.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Text::RegularExpressions;
using namespace BrawlLib::SSBB::ResourceNodes;
using BrawlLS::MD5;
int usage(String^ error_msg) {
if (error_msg->Length != 0) Console::Error->WriteLine(error_msg + "\n");
Console::Error->WriteLine(gcnew String(usage_line));
Console::Error->WriteLine(gcnew String(usage_help_line));
return 1;
}
enum class MDL0PrintType {
ALWAYS, NEVER, SELECTIVE
};
enum class ProgramBehavior {
UNDEFINED, NORMAL, EXTRACT_ALL
};
template < class T, class U >
Boolean isinst(U u) {
return dynamic_cast< T >(u) != nullptr;
}
void print_recursive(TextWriter^ outstream,
String^ format, String^ prefix, ResourceNode^ node,
MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth);
void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj);
void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node);
int brawlls(array<String^>^ args, TextWriter^ outwriter) {
if (args->Length == 0) {
return usage("");
}
String^ filename;
String^ nodepath;
String^ format;
MDL0PrintType modelsDeep = MDL0PrintType::SELECTIVE; // --mdl0, --no-mdl0
// affects printout only
bool recursive = false, // -R
stpmValues = true, // --stpm, --no-stpm
boneValues = true, // --bone, --no-bone
showtype = false, // -t
printSelf = false, // -d, --self
printMD5 = false, // -m
fullpath = false; // --full-path
// affects node search
bool searchChildren = false; // -c
ProgramBehavior behavior = ProgramBehavior::UNDEFINED;
List<String^> behavior_arguments; // arguments not otherwise defined that come after the behavior
for each(String^ argument in args) {
if (argument == "--help" || argument == "/?") {
Console::WriteLine(gcnew String(usage_line));
Console::WriteLine(gcnew String(usage_desc));
return 0;
}
if (argument == "--formathelp") {
Console::WriteLine(gcnew String(format_help));
return 0;
}
if (argument == "--xallhelp") {
Console::WriteLine(gcnew String(xall_help));
return 0;
}
if (argument == "--self") printSelf = true;
else if (argument == "--stpm") stpmValues = true;
else if (argument == "--no-stpm") stpmValues = false;
else if (argument == "--bone") boneValues = true;
else if (argument == "--no-bone") boneValues = false;
else if (argument == "--mdl0") modelsDeep = MDL0PrintType::ALWAYS;
else if (argument == "--no-mdl0") modelsDeep = MDL0PrintType::NEVER;
else if (argument == "--full-path") fullpath = true;
else if (argument->StartsWith("--format=")) format = argument->Substring(9);
else if (argument->StartsWith("-") && argument->Length > 1) {
for each(char c in argument->Substring(1)) {
if (c == 'd') printSelf = true;
else if (c == 'R') recursive = true;
else if (c == 't') showtype = true;
else if (c == 'm') printMD5 = true;
else if (c == 'c') searchChildren = true;
else {
return usage("Invalid argument: " + argument);
}
}
} else {
if (filename == nullptr) filename = argument;
else if (behavior == ProgramBehavior::UNDEFINED && argument == "xall") behavior = ProgramBehavior::EXTRACT_ALL;
else if (behavior != ProgramBehavior::UNDEFINED) behavior_arguments.Add(argument);
else if (nodepath == nullptr) nodepath = argument;
else return usage("Error: too many arguments: " + filename + " " + nodepath + " " + argument);
}
}
if (behavior == ProgramBehavior::UNDEFINED) behavior = ProgramBehavior::NORMAL;
if (filename == "-") {
String^ tmpfile = Path::GetTempFileName();
Stream^ stdin = Console::OpenStandardInput();
Stream^ outstream = gcnew FileStream(tmpfile, FileMode::Create, FileAccess::Write);
array<unsigned char>^ buffer = gcnew array<unsigned char>(2048);
int bytes;
while ((bytes = stdin->Read(buffer, 0, buffer->Length)) > 0) {
outstream->Write(buffer, 0, bytes);
}
outstream->Close();
filename = tmpfile;
}
if (filename == nullptr) return usage("Error: no filename given.");
if (!File::Exists(filename)) return usage("Error: file not found: " + filename);
if (format == nullptr) {
format = "%~+%i" +
(fullpath ? " %p" : " %n") +
(showtype ? " %t" : "") +
(boneValues ? " %b" : "") +
(printMD5 ? " %m" : "");
}
ResourceNode^ node = NodeFactory::FromFile(nullptr, filename);
List<ResourceNode^> matchingNodes;
find_children(node, nodepath, %matchingNodes, searchChildren);
if (matchingNodes.Count == 0) return usage("No nodes found matching path: " + nodepath);
if (behavior == ProgramBehavior::NORMAL && printSelf) {
for each(ResourceNode^ child in matchingNodes) {
printf_obj(outwriter, format, "", child);
}
} else if (matchingNodes.Count > 1) {
Console::Error->WriteLine("Search matched " + matchingNodes.Count + " nodes. Use -d or --self to list them.");
return 1;
} else if (behavior == ProgramBehavior::EXTRACT_ALL) {
if (behavior_arguments.Count == 0) {
Console::Error->WriteLine("Error: no output directory specified");
Console::Error->WriteLine(gcnew String(xall_help));
return 1;
}
return extract_all(matchingNodes[0], %behavior_arguments);
} else if (matchingNodes[0]->Children->Count == 0) {
Console::Error->WriteLine("The node " + matchingNodes[0]->Name + " does not have any children.");
return 0;
} else {
int maxdepth = recursive ? -1 : 1;
print_recursive(outwriter, format, "", matchingNodes[0], modelsDeep, stpmValues, true, maxdepth);
}
}
int main(array<String^>^ args) {
brawlls(args, Console::Out);
}
void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth) {
if (!isRoot) {
printf_obj(outstream, format, prefix, node);
prefix += " ";
}
if (maxdepth == 0) return;
if (isinst<STPMEntryNode^>(node) && stpmValues) {
print_properties(outstream, prefix, node);
} else {
if (isinst<MDL0Node^>(node)) {
if (modelsDeep == MDL0PrintType::NEVER) {
return;
} else if (modelsDeep == MDL0PrintType::SELECTIVE && !isRoot && !node->Name->EndsWith("osition")) {
return;
}
}
int newdepth = maxdepth < 0
? -1
: maxdepth - 1;
for each(ResourceNode^ child in node->Children) {
print_recursive(outstream, format, prefix, child, modelsDeep, stpmValues, false, newdepth);
}
}
delete node; // calls Dispose(). this may improve performance slightly, but we can't use these nodes later in the program
}
void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj) {
String^ name = obj == nullptr
? "null"
: obj->ToString();
String^ bone = "";
if (isinst<MDL0BoneNode^>(obj)) {
MDL0BoneNode^ b = (MDL0BoneNode^)obj;
bone = "T" + b->Translation;
bone += " R" + b->Rotation;
bone += " S" + b->Scale;
}
String^ index = "";
String^ md5 = "";
String^ size = "";
String^ path = "";
if (isinst<ResourceNode^>(obj)) {
ResourceNode^ node = (ResourceNode^)obj;
if (format->Contains("%m")) { // don't do this if we don't need the data - this does save some time
if (isinst<MDL0GroupNode^>(node) || isinst<BRESGroupNode^>(node)) {
// concat children data and use that instead
md5 = "Children:" + MD5::MD5Str(node->Children);
} else if (isinst<BRESEntryNode^>(node)) {
String^ tmp = Path::GetTempFileName();
node->Export(tmp);
md5 = "MD5(Ex):" + MD5::MD5Str(tmp);
File::Delete(tmp);
} else {
md5 = "MD5:" + MD5::MD5Str(node);
}
}
index = node->Index + "";
size = node->OriginalSource.Length + "";
while (node->Parent != nullptr) {
path = node->Name + "/" + path;
node = node->Parent;
}
if (path->EndsWith("/")) path = path->Substring(0, path->Length - 1);
}
String^ line = format
->Replace("%~", prefix)
->Replace("%n", name)
->Replace("%p", path)
->Replace("%i", index)
->Replace("%t", "(" + obj->GetType()->Name + ")")
->Replace("%b", bone)
->Replace("%m", md5)
->Replace("%s", size)
->Replace("%%", "%");
outstream->WriteLine(line);
}
void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node) {
for each(PropertyInfo^ entry in node->GetType()->GetProperties()) {
for each(Attribute^ attribute in entry->GetCustomAttributes(false)) {
if (isinst<CategoryAttribute^>(attribute)) {
Object^ val = entry->GetValue(node, nullptr);
String^ valstr = val == nullptr
? "null"
: val->ToString();
outstream->WriteLine(prefix + entry->Name + " " + valstr);
}
}
}
}
<commit_msg>Remove export behavior - no longer needed - leads to major speedup<commit_after>#include "brawlmd5.h"
#include "brawlextract.h"
#include "find_children.h"
#include "usage.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Text::RegularExpressions;
using namespace BrawlLib::SSBB::ResourceNodes;
using BrawlLS::MD5;
int usage(String^ error_msg) {
if (error_msg->Length != 0) Console::Error->WriteLine(error_msg + "\n");
Console::Error->WriteLine(gcnew String(usage_line));
Console::Error->WriteLine(gcnew String(usage_help_line));
return 1;
}
enum class MDL0PrintType {
ALWAYS, NEVER, SELECTIVE
};
enum class ProgramBehavior {
UNDEFINED, NORMAL, EXTRACT_ALL
};
template < class T, class U >
Boolean isinst(U u) {
return dynamic_cast< T >(u) != nullptr;
}
void print_recursive(TextWriter^ outstream,
String^ format, String^ prefix, ResourceNode^ node,
MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth);
void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj);
void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node);
int brawlls(array<String^>^ args, TextWriter^ outwriter) {
if (args->Length == 0) {
return usage("");
}
String^ filename;
String^ nodepath;
String^ format;
MDL0PrintType modelsDeep = MDL0PrintType::SELECTIVE; // --mdl0, --no-mdl0
// affects printout only
bool recursive = false, // -R
stpmValues = true, // --stpm, --no-stpm
boneValues = true, // --bone, --no-bone
showtype = false, // -t
printSelf = false, // -d, --self
printMD5 = false, // -m
fullpath = false; // --full-path
// affects node search
bool searchChildren = false; // -c
ProgramBehavior behavior = ProgramBehavior::UNDEFINED;
List<String^> behavior_arguments; // arguments not otherwise defined that come after the behavior
for each(String^ argument in args) {
if (argument == "--help" || argument == "/?") {
Console::WriteLine(gcnew String(usage_line));
Console::WriteLine(gcnew String(usage_desc));
return 0;
}
if (argument == "--formathelp") {
Console::WriteLine(gcnew String(format_help));
return 0;
}
if (argument == "--xallhelp") {
Console::WriteLine(gcnew String(xall_help));
return 0;
}
if (argument == "--self") printSelf = true;
else if (argument == "--stpm") stpmValues = true;
else if (argument == "--no-stpm") stpmValues = false;
else if (argument == "--bone") boneValues = true;
else if (argument == "--no-bone") boneValues = false;
else if (argument == "--mdl0") modelsDeep = MDL0PrintType::ALWAYS;
else if (argument == "--no-mdl0") modelsDeep = MDL0PrintType::NEVER;
else if (argument == "--full-path") fullpath = true;
else if (argument->StartsWith("--format=")) format = argument->Substring(9);
else if (argument->StartsWith("-") && argument->Length > 1) {
for each(char c in argument->Substring(1)) {
if (c == 'd') printSelf = true;
else if (c == 'R') recursive = true;
else if (c == 't') showtype = true;
else if (c == 'm') printMD5 = true;
else if (c == 'c') searchChildren = true;
else {
return usage("Invalid argument: " + argument);
}
}
} else {
if (filename == nullptr) filename = argument;
else if (behavior == ProgramBehavior::UNDEFINED && argument == "xall") behavior = ProgramBehavior::EXTRACT_ALL;
else if (behavior != ProgramBehavior::UNDEFINED) behavior_arguments.Add(argument);
else if (nodepath == nullptr) nodepath = argument;
else return usage("Error: too many arguments: " + filename + " " + nodepath + " " + argument);
}
}
if (behavior == ProgramBehavior::UNDEFINED) behavior = ProgramBehavior::NORMAL;
if (filename == "-") {
String^ tmpfile = Path::GetTempFileName();
Stream^ stdin = Console::OpenStandardInput();
Stream^ outstream = gcnew FileStream(tmpfile, FileMode::Create, FileAccess::Write);
array<unsigned char>^ buffer = gcnew array<unsigned char>(2048);
int bytes;
while ((bytes = stdin->Read(buffer, 0, buffer->Length)) > 0) {
outstream->Write(buffer, 0, bytes);
}
outstream->Close();
filename = tmpfile;
}
if (filename == nullptr) return usage("Error: no filename given.");
if (!File::Exists(filename)) return usage("Error: file not found: " + filename);
if (format == nullptr) {
format = "%~+%i" +
(fullpath ? " %p" : " %n") +
(showtype ? " %t" : "") +
(boneValues ? " %b" : "") +
(printMD5 ? " %m" : "");
}
ResourceNode^ node = NodeFactory::FromFile(nullptr, filename);
List<ResourceNode^> matchingNodes;
find_children(node, nodepath, %matchingNodes, searchChildren);
if (matchingNodes.Count == 0) return usage("No nodes found matching path: " + nodepath);
if (behavior == ProgramBehavior::NORMAL && printSelf) {
for each(ResourceNode^ child in matchingNodes) {
printf_obj(outwriter, format, "", child);
}
} else if (matchingNodes.Count > 1) {
Console::Error->WriteLine("Search matched " + matchingNodes.Count + " nodes. Use -d or --self to list them.");
return 1;
} else if (behavior == ProgramBehavior::EXTRACT_ALL) {
if (behavior_arguments.Count == 0) {
Console::Error->WriteLine("Error: no output directory specified");
Console::Error->WriteLine(gcnew String(xall_help));
return 1;
}
return extract_all(matchingNodes[0], %behavior_arguments);
} else if (matchingNodes[0]->Children->Count == 0) {
Console::Error->WriteLine("The node " + matchingNodes[0]->Name + " does not have any children.");
return 0;
} else {
int maxdepth = recursive ? -1 : 1;
print_recursive(outwriter, format, "", matchingNodes[0], modelsDeep, stpmValues, true, maxdepth);
}
}
int main(array<String^>^ args) {
brawlls(args, Console::Out);
}
void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth) {
if (!isRoot) {
printf_obj(outstream, format, prefix, node);
prefix += " ";
}
if (maxdepth == 0) return;
if (isinst<STPMEntryNode^>(node) && stpmValues) {
print_properties(outstream, prefix, node);
} else {
if (isinst<MDL0Node^>(node)) {
if (modelsDeep == MDL0PrintType::NEVER) {
return;
} else if (modelsDeep == MDL0PrintType::SELECTIVE && !isRoot && !node->Name->EndsWith("osition")) {
return;
}
}
int newdepth = maxdepth < 0
? -1
: maxdepth - 1;
for each(ResourceNode^ child in node->Children) {
print_recursive(outstream, format, prefix, child, modelsDeep, stpmValues, false, newdepth);
}
}
delete node; // calls Dispose(). this may improve performance slightly, but we can't use these nodes later in the program
}
void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj) {
String^ name = obj == nullptr
? "null"
: obj->ToString();
String^ bone = "";
if (isinst<MDL0BoneNode^>(obj)) {
MDL0BoneNode^ b = (MDL0BoneNode^)obj;
bone = "T" + b->Translation;
bone += " R" + b->Rotation;
bone += " S" + b->Scale;
}
String^ index = "";
String^ md5 = "";
String^ size = "";
String^ path = "";
if (isinst<ResourceNode^>(obj)) {
ResourceNode^ node = (ResourceNode^)obj;
if (format->Contains("%m")) { // don't do this if we don't need the data - this does save some time
if (isinst<MDL0GroupNode^>(node) || isinst<BRESGroupNode^>(node)) {
// concat children data and use that instead
md5 = "Children:" + MD5::MD5Str(node->Children);
} else {
md5 = "MD5:" + MD5::MD5Str(node);
}
}
index = node->Index + "";
size = node->OriginalSource.Length + "";
while (node->Parent != nullptr) {
path = node->Name + "/" + path;
node = node->Parent;
}
if (path->EndsWith("/")) path = path->Substring(0, path->Length - 1);
}
String^ line = format
->Replace("%~", prefix)
->Replace("%n", name)
->Replace("%p", path)
->Replace("%i", index)
->Replace("%t", "(" + obj->GetType()->Name + ")")
->Replace("%b", bone)
->Replace("%m", md5)
->Replace("%s", size)
->Replace("%%", "%");
outstream->WriteLine(line);
}
void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node) {
for each(PropertyInfo^ entry in node->GetType()->GetProperties()) {
for each(Attribute^ attribute in entry->GetCustomAttributes(false)) {
if (isinst<CategoryAttribute^>(attribute)) {
Object^ val = entry->GetValue(node, nullptr);
String^ valstr = val == nullptr
? "null"
: val->ToString();
outstream->WriteLine(prefix + entry->Name + " " + valstr);
}
}
}
}
<|endoftext|> |
<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|> |
<commit_before>#include "win32.h"
#include <time.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
#include <io.h>
#include <stdlib.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
// implementation from http://www.openasthra.com/c-tidbits/gettimeofday-function-for-windows/
namespace CVD {
long long get_time_of_day_ns()
{
FILETIME ft;
long long tmpres = 0;
static int tzflag;
//Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
//tempres is in 100ns increments
//Convert it to ns
tmpres *= 100
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS * (long long)1000;
return tmpres;
}
namespace Internal {
void * aligned_alloc(size_t count, size_t alignment){
return _aligned_malloc(count, alignment);
}
void aligned_free(void * memory){
_aligned_free(memory);
}
} // namespace Internal
// returns path component from a general path string
static std::string get_path( const std::string & p){
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char out[1024];
errno_t ret = _splitpath_s(p.c_str(), drive, _MAX_DRIVE, dir, _MAX_DIR, NULL, 0, NULL, 0);
assert(0 == ret);
_makepath(out, drive, dir, NULL, NULL);
return std::string(out);
}
// simple implementation of globlist after MSDN example for _findfirst
std::vector<std::string> globlist(const std::string& gl)
{
std::vector<std::string> ret;
struct _finddatai64_t c_file;
intptr_t hFile;
// get the path component to stick it to the front again
const std::string path = get_path(gl);
// Find first file in current directory
if( (hFile = _findfirsti64( gl.c_str(), &c_file )) != -1L ){
do {
ret.push_back(path + c_file.name);
} while( _findnexti64( hFile, &c_file ) == 0 );
_findclose( hFile );
}
std::sort(ret.begin(), ret.end());
return ret;
}
} // namespace CVD
<commit_msg>Fix minor compile error.<commit_after>#include "win32.h"
#include <time.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
#include <io.h>
#include <stdlib.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
// implementation from http://www.openasthra.com/c-tidbits/gettimeofday-function-for-windows/
namespace CVD {
long long get_time_of_day_ns()
{
FILETIME ft;
long long tmpres = 0;
static int tzflag;
//Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
//tempres is in 100ns increments
//Convert it to ns
tmpres *= 100;
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS * (long long)1000;
return tmpres;
}
namespace Internal {
void * aligned_alloc(size_t count, size_t alignment){
return _aligned_malloc(count, alignment);
}
void aligned_free(void * memory){
_aligned_free(memory);
}
} // namespace Internal
// returns path component from a general path string
static std::string get_path( const std::string & p){
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char out[1024];
errno_t ret = _splitpath_s(p.c_str(), drive, _MAX_DRIVE, dir, _MAX_DIR, NULL, 0, NULL, 0);
assert(0 == ret);
_makepath(out, drive, dir, NULL, NULL);
return std::string(out);
}
// simple implementation of globlist after MSDN example for _findfirst
std::vector<std::string> globlist(const std::string& gl)
{
std::vector<std::string> ret;
struct _finddatai64_t c_file;
intptr_t hFile;
// get the path component to stick it to the front again
const std::string path = get_path(gl);
// Find first file in current directory
if( (hFile = _findfirsti64( gl.c_str(), &c_file )) != -1L ){
do {
ret.push_back(path + c_file.name);
} while( _findnexti64( hFile, &c_file ) == 0 );
_findclose( hFile );
}
std::sort(ret.begin(), ret.end());
return ret;
}
} // namespace CVD
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "cmd_pub.h"
#include <fcntl.h>
#include <string>
#include <vector>
#include "download.h"
#include "manifest.h"
#include "notify/messages.h"
#include "notify/publisher_http.h"
#include "util/pointer.h"
#include "util/posix.h"
#include "util/string.h"
namespace {
const LogFacilities& kLogInfo = DefaultLogging::info;
const LogFacilities& kLogError = DefaultLogging::error;
const int kMaxPoolHandles = 1;
const bool kUseSystemPorxy = true;
const unsigned kDownloadTimeout = 60; // 1 minute
const unsigned kDownloadRetries = 1; // 2 attempts in total
} // namespace
namespace notify {
int DoPublish(const std::string& server_url, const std::string& repository_url,
bool verbose) {
const std::string repo_url = MakeCanonicalPath(repository_url);
LogCvmfs(kLogCvmfs, kLogInfo, "Parameters: ");
LogCvmfs(kLogCvmfs, kLogInfo, " CVMFS repository URL: %s",
repo_url.c_str());
LogCvmfs(kLogCvmfs, kLogInfo, " Notification server URL: %s",
server_url.c_str());
// Extract repository name from repository URL
const std::vector<std::string> repo_url_tokens = SplitString(repo_url, '/');
const std::string repository_name = repo_url_tokens.back();
// Download repository manifest
std::string manifest_contents;
const std::string manifest_url = repo_url + "/.cvmfspublished";
if (HasPrefix(repo_url, "http://", false)) {
perf::Statistics stats;
UniquePtr<download::DownloadManager> download_manager(
new download::DownloadManager());
assert(download_manager.IsValid());
download_manager->Init(kMaxPoolHandles, kUseSystemPorxy,
perf::StatisticsTemplate("download", &stats));
download_manager->SetTimeout(kDownloadTimeout, kDownloadTimeout);
download_manager->SetRetryParameters(kDownloadRetries, 500, 2000);
download::JobInfo download_manifest(&manifest_url, false, false, NULL);
download::Failures retval = download_manager->Fetch(&download_manifest);
if (retval != download::kFailOk) {
LogCvmfs(kLogCvmfs, kLogError, "Failed to download manifest (%d - %s)",
retval, download::Code2Ascii(retval));
return 6;
}
manifest_contents = std::string(download_manifest.destination_mem.data,
download_manifest.destination_mem.pos);
free(download_manifest.destination_mem.data);
} else {
int fd = open(manifest_url.c_str(), O_RDONLY);
if (fd == -1) {
LogCvmfs(kLogCvmfs, kLogInfo, "Could not open manifest file");
return 7;
}
if (!SafeReadToString(fd, &manifest_contents)) {
LogCvmfs(kLogCvmfs, kLogInfo, "Could not read manifest file");
close(fd);
return 8;
}
close(fd);
}
UniquePtr<manifest::Manifest> manifest(manifest::Manifest::LoadMem(
reinterpret_cast<const unsigned char*>(manifest_contents.data()),
manifest_contents.size()));
if (verbose) {
LogCvmfs(kLogCvmfs, kLogInfo, "Current repository manifest:\n%s",
manifest->ExportString().c_str());
}
// Publish message
UniquePtr<notify::Publisher> publisher(new notify::PublisherHTTP(server_url));
std::string msg_text;
notify::msg::Activity msg;
msg.version_ = 1;
msg.timestamp_ = StringifyTime(std::time(NULL), true);
msg.repository_ = repository_name;
msg.manifest_ = manifest_contents;
msg.ToJSONString(&msg_text);
if (!publisher->Publish(msg_text, repository_name)) {
LogCvmfs(kLogCvmfs, kLogError, "Could not publish notification");
return 9;
}
assert(publisher->Finalize());
return 0;
}
} // namespace notify
<commit_msg>Fix memory leak<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "cmd_pub.h"
#include <fcntl.h>
#include <string>
#include <vector>
#include "download.h"
#include "manifest.h"
#include "notify/messages.h"
#include "notify/publisher_http.h"
#include "util/pointer.h"
#include "util/posix.h"
#include "util/string.h"
namespace {
const LogFacilities& kLogInfo = DefaultLogging::info;
const LogFacilities& kLogError = DefaultLogging::error;
const int kMaxPoolHandles = 1;
const bool kUseSystemPorxy = true;
const unsigned kDownloadTimeout = 60; // 1 minute
const unsigned kDownloadRetries = 1; // 2 attempts in total
} // namespace
namespace notify {
int DoPublish(const std::string& server_url, const std::string& repository_url,
bool verbose) {
const std::string repo_url = MakeCanonicalPath(repository_url);
LogCvmfs(kLogCvmfs, kLogInfo, "Parameters: ");
LogCvmfs(kLogCvmfs, kLogInfo, " CVMFS repository URL: %s",
repo_url.c_str());
LogCvmfs(kLogCvmfs, kLogInfo, " Notification server URL: %s",
server_url.c_str());
// Extract repository name from repository URL
const std::vector<std::string> repo_url_tokens = SplitString(repo_url, '/');
const std::string repository_name = repo_url_tokens.back();
// Download repository manifest
std::string manifest_contents;
const std::string manifest_url = repo_url + "/.cvmfspublished";
if (HasPrefix(repo_url, "http://", false)) {
perf::Statistics stats;
UniquePtr<download::DownloadManager> download_manager(
new download::DownloadManager());
assert(download_manager.IsValid());
download_manager->Init(kMaxPoolHandles, kUseSystemPorxy,
perf::StatisticsTemplate("download", &stats));
download_manager->SetTimeout(kDownloadTimeout, kDownloadTimeout);
download_manager->SetRetryParameters(kDownloadRetries, 500, 2000);
download::JobInfo download_manifest(&manifest_url, false, false, NULL);
download::Failures retval = download_manager->Fetch(&download_manifest);
if (retval != download::kFailOk) {
LogCvmfs(kLogCvmfs, kLogError, "Failed to download manifest (%d - %s)",
retval, download::Code2Ascii(retval));
download_manager->Fini();
return 6;
}
manifest_contents = std::string(download_manifest.destination_mem.data,
download_manifest.destination_mem.pos);
free(download_manifest.destination_mem.data);
download_manager->Fini();
} else {
int fd = open(manifest_url.c_str(), O_RDONLY);
if (fd == -1) {
LogCvmfs(kLogCvmfs, kLogInfo, "Could not open manifest file");
return 7;
}
if (!SafeReadToString(fd, &manifest_contents)) {
LogCvmfs(kLogCvmfs, kLogInfo, "Could not read manifest file");
close(fd);
return 8;
}
close(fd);
}
UniquePtr<manifest::Manifest> manifest(manifest::Manifest::LoadMem(
reinterpret_cast<const unsigned char*>(manifest_contents.data()),
manifest_contents.size()));
if (verbose) {
LogCvmfs(kLogCvmfs, kLogInfo, "Current repository manifest:\n%s",
manifest->ExportString().c_str());
}
// Publish message
UniquePtr<notify::Publisher> publisher(new notify::PublisherHTTP(server_url));
std::string msg_text;
notify::msg::Activity msg;
msg.version_ = 1;
msg.timestamp_ = StringifyTime(std::time(NULL), true);
msg.repository_ = repository_name;
msg.manifest_ = manifest_contents;
msg.ToJSONString(&msg_text);
if (!publisher->Publish(msg_text, repository_name)) {
LogCvmfs(kLogCvmfs, kLogError, "Could not publish notification");
return 9;
}
assert(publisher->Finalize());
return 0;
}
} // namespace notify
<|endoftext|> |
<commit_before>#pragma once
#include "../errors.hpp"
#include "asio_types.hpp"
#include "message_header.hpp"
#include <asio/coroutine.hpp>
#include <asio/read.hpp>
#include <asio/write.hpp>
#include <asio/yield.hpp>
namespace asio_sodium {
namespace detail {
template <typename Resumable>
class message_writer final : asio::coroutine {
public:
explicit
message_writer(
gsl::span<byte> message
, socket_type& socket
, session_data& session
, Resumable&& resumable
)
: message_(message)
, socket_(socket)
, session_(session)
, resumable_(std::move(resumable))
{}
void
operator()(
std::error_code ec = std::error_code()
, std::size_t bytes = 0
) {
if (ec) {
resumable_(ec, bytes);
return;
}
reenter (this) {
ec = encrypt_message_in_place_and_write_header();
if (ec) {
resumable_(ec, bytes);
yield break;
}
yield send_header();
yield send_mac();
yield send_message_and_invoke_callback();
}
}
private:
std::error_code
encrypt_message_in_place_and_write_header()
noexcept {
message_header header(session_.header_buffer);
header.generate_data_nonce();
header.generate_followup_nonce();
header.set_message_length(message_.length());
auto data_nonce = header.data_nonce_span();
if (
crypto_box_detached(
&message_[0]
, &session_.mac[0]
, &message_[0]
, message_.size()
, &data_nonce[0]
, &session_.remote_public_key[0]
, &session_.local_private_key[0]
) != 0
) {
return error::message_encrypt;
}
if (
!header.encrypt_to(
session_.encrypt_nonce
, session_.remote_public_key
, session_.local_private_key
)
) {
return error::message_header_encrypt;
}
header.copy_followup_nonce(session_.encrypt_nonce);
return {};
}
void
send_header()
noexcept {
asio::async_write(
socket_
, asio::buffer(session_.header_buffer)
, std::move(*this)
);
}
void
send_mac()
noexcept {
asio::async_write(
socket_
, asio::buffer(session_.mac)
, std::move(*this)
);
}
void
send_message_and_invoke_callback()
noexcept {
asio::async_write(
socket_
, asio::buffer(&message_[0], message_.size())
, std::move(resumable_)
);
}
gsl::span<byte> message_;
socket_type& socket_;
session_data& session_;
Resumable resumable_;
};
}}
<commit_msg>Fix nonce bug<commit_after>#pragma once
#include "../errors.hpp"
#include "asio_types.hpp"
#include "message_header.hpp"
#include <asio/coroutine.hpp>
#include <asio/read.hpp>
#include <asio/write.hpp>
#include <asio/yield.hpp>
namespace asio_sodium {
namespace detail {
template <typename Resumable>
class message_writer final : asio::coroutine {
public:
explicit
message_writer(
gsl::span<byte> message
, socket_type& socket
, session_data& session
, Resumable&& resumable
)
: message_(message)
, socket_(socket)
, session_(session)
, resumable_(std::move(resumable))
{}
void
operator()(
std::error_code ec = std::error_code()
, std::size_t bytes = 0
) {
if (ec) {
resumable_(ec, bytes);
return;
}
reenter (this) {
ec = encrypt_message_in_place_and_write_header();
if (ec) {
resumable_(ec, bytes);
yield break;
}
yield send_header();
yield send_mac();
yield send_message_and_invoke_callback();
}
}
private:
std::error_code
encrypt_message_in_place_and_write_header()
noexcept {
message_header header(session_.header_buffer);
header.generate_data_nonce();
header.generate_followup_nonce();
header.set_message_length(message_.length());
auto data_nonce = header.data_nonce_span();
if (
crypto_box_detached(
&message_[0]
, &session_.mac[0]
, &message_[0]
, message_.size()
, &data_nonce[0]
, &session_.remote_public_key[0]
, &session_.local_private_key[0]
) != 0
) {
return error::message_encrypt;
}
nonce temp_followup_nonce;
header.copy_followup_nonce(temp_followup_nonce);
if (
!header.encrypt_to(
session_.encrypt_nonce
, session_.remote_public_key
, session_.local_private_key
)
) {
return error::message_header_encrypt;
}
std::copy(
temp_followup_nonce.begin()
, temp_followup_nonce.end()
, session_.encrypt_nonce.begin()
);
return {};
}
void
send_header()
noexcept {
asio::async_write(
socket_
, asio::buffer(session_.header_buffer)
, std::move(*this)
);
}
void
send_mac()
noexcept {
asio::async_write(
socket_
, asio::buffer(session_.mac)
, std::move(*this)
);
}
void
send_message_and_invoke_callback()
noexcept {
asio::async_write(
socket_
, asio::buffer(&message_[0], message_.size())
, std::move(resumable_)
);
}
gsl::span<byte> message_;
socket_type& socket_;
session_data& session_;
Resumable resumable_;
};
}}
<|endoftext|> |
<commit_before>#ifndef CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
#define CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
#include <algorithm>
#include <type_traits>
#include <vector>
#include <cppurses/system/events/key.hpp>
#include <cppurses/widget/pipe.hpp>
namespace cppurses::layout {
/// Adds 'Selected Child' concept to a layout.
/** Keyboard and mouse selecting ability, scrolls when selection is off screeen.
* Depends on the Child Widgets of Layout_t to have a select() and unselect()
* method. Inherit from this and override key_press_event to perform actions on
* the selected_child(). Scroll action also moves the selected child index. */
template <typename Layout_t, bool unselect_on_focus_out = true>
class Selecting : public Layout_t {
private:
using Key_codes = std::vector<Key::Code>;
public:
Selecting() { *this | pipe::strong_focus(); }
Selecting(Key_codes increment_selection_keys,
Key_codes decrement_selection_keys,
Key_codes increment_scroll_keys,
Key_codes decrement_scroll_keys)
: increment_selection_keys_{increment_selection_keys},
decrement_selection_keys_{decrement_selection_keys},
increment_scroll_keys_{increment_scroll_keys},
decrement_scroll_keys_{decrement_scroll_keys}
{
*this | pipe::strong_focus();
}
void set_increment_selection_keys(Key_codes keys)
{
increment_selection_keys_ = std::move(keys);
}
void set_decrement_selection_keys(Key_codes keys)
{
decrement_selection_keys_ = std::move(keys);
}
void set_increment_scroll_keys(Key_codes keys)
{
increment_scroll_keys_ = std::move(keys);
}
void set_decrement_scroll_keys(Key_codes keys)
{
decrement_scroll_keys_ = std::move(keys);
}
/// Return the currently selected child, UB if no children in Layout.
auto selected_child() const -> typename Layout_t::Child_t const&
{
return this->get_children()[selected_];
}
/// Return the currently selected child, UB if no children in Layout.
auto selected_child() -> typename Layout_t::Child_t&
{
return this->get_children()[selected_];
}
/// Return the index into get_children() corresponding to the selected child
auto selected_row() const -> std::size_t { return selected_; }
/// Erase first element that satisfies \p pred. Return true if erase happens
template <
typename Unary_predicate_t,
std::enable_if_t<std::is_invocable_v<Unary_predicate_t,
std::add_lvalue_reference_t<
typename Layout_t::Child_t>>,
int> = 0>
auto erase(Unary_predicate_t&& pred) -> bool
{
auto child =
this->get_children().find(std::forward<Unary_predicate_t>(pred));
if (child == nullptr)
return false;
this->erase(child);
return true;
}
/// Erase the given widget and reset selected to the Layout's offset.
void erase(Widget const* child)
{
auto const was_selected = &this->selected_child() == child;
this->Layout_t::erase(child);
if (was_selected && this->child_count() > 0)
this->set_selected(this->children_.get_offset());
}
/// Erase child at \p index and reset selected to the Layout's offset.
void erase(std::size_t index)
{
auto const was_selected = selected_ == index;
this->Layout_t::erase(index);
if (was_selected && this->child_count() > 0)
this->set_selected(this->children_.get_offset());
}
protected:
auto key_press_event(Key::State const& keyboard) -> bool override
{
if (contains(keyboard.key, increment_selection_keys_))
this->increment_selected_and_scroll_if_necessary();
else if (contains(keyboard.key, decrement_selection_keys_))
this->decrement_selected_and_scroll_if_necessary();
else if (contains(keyboard.key, increment_scroll_keys_))
this->increment_offset_and_increment_selected();
else if (contains(keyboard.key, decrement_scroll_keys_))
this->decrement_offset_and_decrement_selected();
return Layout_t::key_press_event(keyboard);
}
/// Reset the selected child if needed.
auto resize_event(cppurses::Area new_size, cppurses::Area old_size)
-> bool override
{
auto const base_result = Layout_t::resize_event(new_size, old_size);
this->reset_selected_if_necessary();
return base_result;
}
/// If selected_child is off the screen, select() the last displayed widget.
void reset_selected_if_necessary()
{
if (this->Layout_t::child_count() == 0 ||
this->selected_child().is_enabled()) {
return;
}
this->set_selected(this->find_bottom_row());
}
auto focus_in_event() -> bool override
{
this->reset_selected_if_necessary();
if (this->child_count() != 0)
this->selected_child().select();
return Layout_t::focus_in_event();
}
auto focus_out_event() -> bool override
{
if constexpr (unselect_on_focus_out) {
if (this->child_count() != 0)
this->selected_child().unselect();
}
return Layout_t::focus_out_event();
}
auto disable_event() -> bool override
{
if (this->child_count() != 0)
this->selected_child().unselect();
return Layout_t::disable_event();
}
auto enable_event() -> bool override
{
if (this->child_count() != 0 && System::focus_widget() == this)
this->selected_child().select();
return Layout_t::enable_event();
}
private:
std::size_t selected_ = 0uL;
Key_codes increment_selection_keys_;
Key_codes decrement_selection_keys_;
Key_codes increment_scroll_keys_;
Key_codes decrement_scroll_keys_;
private:
void increment_selected()
{
if (this->child_count() == 0 || selected_ + 1 == this->child_count())
return;
this->set_selected(selected_ + 1);
}
void increment_selected_and_scroll_if_necessary()
{
this->increment_selected();
if (!this->selected_child().is_enabled())
this->increment_offset();
}
void decrement_selected()
{
if (this->child_count() == 0 || selected_ == 0)
return;
this->set_selected(selected_ - 1);
}
void decrement_selected_and_scroll_if_necessary()
{
this->decrement_selected();
if (!this->selected_child().is_enabled())
this->decrement_offset();
}
/// Scroll down or right.
void increment_offset()
{
auto const child_n = this->child_count();
if (child_n == 0)
return;
if (auto const offset = this->child_offset(); offset + 1 != child_n)
this->set_offset(offset + 1);
}
void increment_offset_and_increment_selected()
{
this->increment_offset();
this->increment_selected();
}
/// Scroll up or left.
void decrement_offset()
{
if (this->child_count() == 0)
return;
if (auto const offset = this->child_offset(); offset != 0)
this->set_offset(offset - 1);
}
void decrement_offset_and_decrement_selected()
{
if (this->child_offset() == 0)
return;
this->decrement_offset();
this->decrement_selected();
}
/// unselect() the currently selected child, select() the child at \p index.
void set_selected(std::size_t index)
{
if (selected_ < this->child_count())
this->selected_child().unselect();
selected_ = index;
this->selected_child().select();
}
/// Find the child index of the last displayed Data_row.
/** Assumes child_count() > 0. Returns child_offset if all are disabled. */
auto find_bottom_row() const -> std::size_t
{
auto const children = this->Widget::get_children();
auto const count = this->child_count();
auto const offset = this->child_offset();
for (auto i = offset + 1; i < count; ++i) {
if (children[i].is_enabled())
continue;
return i - 1;
}
return offset;
}
/// Return true if \p codes contains the value \p key.
static auto contains(Key::Code key, Key_codes const& codes) -> bool
{
return std::any_of(std::begin(codes), std::end(codes),
[=](auto k) { return k == key; });
}
};
} // namespace cppurses::layout
#endif // CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
<commit_msg>Throw exception on out of bounds access in layout::Selecting<commit_after>#ifndef CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
#define CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
#include <algorithm>
#include <type_traits>
#include <vector>
#include <cppurses/system/events/key.hpp>
#include <cppurses/widget/pipe.hpp>
namespace cppurses::layout {
/// Adds 'Selected Child' concept to a layout.
/** Keyboard and mouse selecting ability, scrolls when selection is off screeen.
* Depends on the Child Widgets of Layout_t to have a select() and unselect()
* method. Inherit from this and override key_press_event to perform actions on
* the selected_child(). Scroll action also moves the selected child index. */
template <typename Layout_t, bool unselect_on_focus_out = true>
class Selecting : public Layout_t {
private:
using Key_codes = std::vector<Key::Code>;
public:
Selecting() { *this | pipe::strong_focus(); }
Selecting(Key_codes increment_selection_keys,
Key_codes decrement_selection_keys,
Key_codes increment_scroll_keys,
Key_codes decrement_scroll_keys)
: increment_selection_keys_{increment_selection_keys},
decrement_selection_keys_{decrement_selection_keys},
increment_scroll_keys_{increment_scroll_keys},
decrement_scroll_keys_{decrement_scroll_keys}
{
*this | pipe::strong_focus();
}
void set_increment_selection_keys(Key_codes keys)
{
increment_selection_keys_ = std::move(keys);
}
void set_decrement_selection_keys(Key_codes keys)
{
decrement_selection_keys_ = std::move(keys);
}
void set_increment_scroll_keys(Key_codes keys)
{
increment_scroll_keys_ = std::move(keys);
}
void set_decrement_scroll_keys(Key_codes keys)
{
decrement_scroll_keys_ = std::move(keys);
}
/// Return the currently selected child, UB if no children in Layout.
auto selected_child() const -> typename Layout_t::Child_t const&
{
return this->get_children()[selected_];
}
/// Return the currently selected child, UB if no children in Layout.
auto selected_child() -> typename Layout_t::Child_t&
{
if (selected_ >= this->child_count()) {
// Getting intermitent crash because of outside access.
throw std::runtime_error{
"Selecting::selected_child();" + std::to_string(selected_) +
">= " + std::to_string(this->child_count())};
}
return this->get_children()[selected_];
}
/// Return the index into get_children() corresponding to the selected child
auto selected_row() const -> std::size_t { return selected_; }
/// Erase first element that satisfies \p pred. Return true if erase happens
template <
typename Unary_predicate_t,
std::enable_if_t<std::is_invocable_v<Unary_predicate_t,
std::add_lvalue_reference_t<
typename Layout_t::Child_t>>,
int> = 0>
auto erase(Unary_predicate_t&& pred) -> bool
{
auto child =
this->get_children().find(std::forward<Unary_predicate_t>(pred));
if (child == nullptr)
return false;
this->erase(child);
return true;
}
/// Erase the given widget and reset selected to the Layout's offset.
void erase(Widget const* child)
{
auto const was_selected = &this->selected_child() == child;
this->Layout_t::erase(child);
if (was_selected && this->child_count() > 0)
this->set_selected(this->children_.get_offset());
}
/// Erase child at \p index and reset selected to the Layout's offset.
void erase(std::size_t index)
{
auto const was_selected = selected_ == index;
this->Layout_t::erase(index);
if (was_selected && this->child_count() > 0)
this->set_selected(this->children_.get_offset());
}
protected:
auto key_press_event(Key::State const& keyboard) -> bool override
{
if (contains(keyboard.key, increment_selection_keys_))
this->increment_selected_and_scroll_if_necessary();
else if (contains(keyboard.key, decrement_selection_keys_))
this->decrement_selected_and_scroll_if_necessary();
else if (contains(keyboard.key, increment_scroll_keys_))
this->increment_offset_and_increment_selected();
else if (contains(keyboard.key, decrement_scroll_keys_))
this->decrement_offset_and_decrement_selected();
return Layout_t::key_press_event(keyboard);
}
/// Reset the selected child if needed.
auto resize_event(cppurses::Area new_size, cppurses::Area old_size)
-> bool override
{
auto const base_result = Layout_t::resize_event(new_size, old_size);
this->reset_selected_if_necessary();
return base_result;
}
/// If selected_child is off the screen, select() the last displayed widget.
void reset_selected_if_necessary()
{
if (this->Layout_t::child_count() == 0 ||
this->selected_child().is_enabled()) {
return;
}
this->set_selected(this->find_bottom_row());
}
auto focus_in_event() -> bool override
{
this->reset_selected_if_necessary();
if (this->child_count() != 0)
this->selected_child().select();
return Layout_t::focus_in_event();
}
auto focus_out_event() -> bool override
{
if constexpr (unselect_on_focus_out) {
if (this->child_count() != 0)
this->selected_child().unselect();
}
return Layout_t::focus_out_event();
}
auto disable_event() -> bool override
{
if (this->child_count() != 0)
this->selected_child().unselect();
return Layout_t::disable_event();
}
auto enable_event() -> bool override
{
if (this->child_count() != 0 && System::focus_widget() == this)
this->selected_child().select();
return Layout_t::enable_event();
}
private:
std::size_t selected_ = 0uL;
Key_codes increment_selection_keys_;
Key_codes decrement_selection_keys_;
Key_codes increment_scroll_keys_;
Key_codes decrement_scroll_keys_;
private:
void increment_selected()
{
if (this->child_count() == 0 || selected_ + 1 == this->child_count())
return;
this->set_selected(selected_ + 1);
}
void increment_selected_and_scroll_if_necessary()
{
this->increment_selected();
if (!this->selected_child().is_enabled())
this->increment_offset();
}
void decrement_selected()
{
if (this->child_count() == 0 || selected_ == 0)
return;
this->set_selected(selected_ - 1);
}
void decrement_selected_and_scroll_if_necessary()
{
this->decrement_selected();
if (!this->selected_child().is_enabled())
this->decrement_offset();
}
/// Scroll down or right.
void increment_offset()
{
auto const child_n = this->child_count();
if (child_n == 0)
return;
if (auto const offset = this->child_offset(); offset + 1 != child_n)
this->set_offset(offset + 1);
}
void increment_offset_and_increment_selected()
{
this->increment_offset();
this->increment_selected();
}
/// Scroll up or left.
void decrement_offset()
{
if (this->child_count() == 0)
return;
if (auto const offset = this->child_offset(); offset != 0)
this->set_offset(offset - 1);
}
void decrement_offset_and_decrement_selected()
{
if (this->child_offset() == 0)
return;
this->decrement_offset();
this->decrement_selected();
}
/// unselect() the currently selected child, select() the child at \p index.
void set_selected(std::size_t index)
{
if (selected_ < this->child_count())
this->selected_child().unselect();
selected_ = index;
this->selected_child().select();
}
/// Find the child index of the last displayed Data_row.
/** Assumes child_count() > 0. Returns child_offset if all are disabled. */
auto find_bottom_row() const -> std::size_t
{
auto const children = this->Widget::get_children();
auto const count = this->child_count();
auto const offset = this->child_offset();
for (auto i = offset + 1; i < count; ++i) {
if (children[i].is_enabled())
continue;
return i - 1;
}
return offset;
}
/// Return true if \p codes contains the value \p key.
static auto contains(Key::Code key, Key_codes const& codes) -> bool
{
return std::any_of(std::begin(codes), std::end(codes),
[=](auto k) { return k == key; });
}
};
} // namespace cppurses::layout
#endif // CPPURSES_WIDGET_LAYOUTS_SELECTING_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MULTI_TYPE_MATRIX_BLOCK_FUNC_HPP__
#define __MULTI_TYPE_MATRIX_BLOCK_FUNC_HPP__
#include "multi_type_vector_types.hpp"
namespace mdds { namespace __mtm {
const mdds::mtv::element_t element_type_mtx_string = mdds::mtv::element_type_user_start;
template<typename _StringType>
struct trait
{
typedef _StringType string_type;
typedef mdds::mtv::default_element_block<element_type_mtx_string, string_type> string_cell_block;
static mdds::mtv::element_t mdds_mtv_get_element_type(const string_type&)
{
return element_type_mtx_string;
}
static void mdds_mtv_set_value(mtv::base_element_block& block, size_t pos, const string_type& val)
{
string_cell_block::set_value(block, pos, val);
}
static void mdds_mtv_get_value(const mtv::base_element_block& block, size_t pos, string_type& val)
{
string_cell_block::get_value(block, pos, val);
}
template<typename _Iter>
static void mdds_mtv_set_values(
mtv::base_element_block& block, size_t pos, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_cell_block::set_values(block, pos, it_begin, it_end);
}
static void mdds_mtv_append_value(mtv::base_element_block& block, const string_type& val)
{
string_cell_block::append_value(block, val);
}
static void mdds_mtv_prepend_value(mtv::base_element_block& block, const string_type& val)
{
string_cell_block::prepend_value(block, val);
}
template<typename _Iter>
static void mdds_mtv_prepend_values(mtv::base_element_block& block, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_cell_block::prepend_values(block, it_begin, it_end);
}
template<typename _Iter>
static void mdds_mtv_append_values(mtv::base_element_block& block, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_cell_block::append_values(block, it_begin, it_end);
}
template<typename _Iter>
static void mdds_mtv_assign_values(mtv::base_element_block& dest, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_cell_block::assign_values(dest, it_begin, it_end);
}
static void mdds_mtv_get_empty_value(string_type& val)
{
val = string_type();
}
template<typename _Iter>
static void mdds_mtv_insert_values(
mtv::base_element_block& block, size_t pos, string_type, const _Iter& it_begin, const _Iter& it_end)
{
string_cell_block::insert_values(block, pos, it_begin, it_end);
}
};
}}
#endif
<commit_msg>Define the rest of the block functions.<commit_after>/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MULTI_TYPE_MATRIX_BLOCK_FUNC_HPP__
#define __MULTI_TYPE_MATRIX_BLOCK_FUNC_HPP__
#include "multi_type_vector_types.hpp"
#include "multi_type_vector_trait.hpp"
namespace mdds { namespace __mtm {
const mdds::mtv::element_t element_type_mtx_string = mdds::mtv::element_type_user_start;
template<typename _StringType>
struct trait
{
typedef _StringType string_type;
typedef mdds::mtv::default_element_block<element_type_mtx_string, string_type> string_elem_block;
static mdds::mtv::element_t mdds_mtv_get_element_type(const string_type&)
{
return element_type_mtx_string;
}
static void mdds_mtv_set_value(mtv::base_element_block& block, size_t pos, const string_type& val)
{
string_elem_block::set_value(block, pos, val);
}
static void mdds_mtv_get_value(const mtv::base_element_block& block, size_t pos, string_type& val)
{
string_elem_block::get_value(block, pos, val);
}
template<typename _Iter>
static void mdds_mtv_set_values(
mtv::base_element_block& block, size_t pos, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_elem_block::set_values(block, pos, it_begin, it_end);
}
static void mdds_mtv_append_value(mtv::base_element_block& block, const string_type& val)
{
string_elem_block::append_value(block, val);
}
static void mdds_mtv_prepend_value(mtv::base_element_block& block, const string_type& val)
{
string_elem_block::prepend_value(block, val);
}
template<typename _Iter>
static void mdds_mtv_prepend_values(mtv::base_element_block& block, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_elem_block::prepend_values(block, it_begin, it_end);
}
template<typename _Iter>
static void mdds_mtv_append_values(mtv::base_element_block& block, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_elem_block::append_values(block, it_begin, it_end);
}
template<typename _Iter>
static void mdds_mtv_assign_values(mtv::base_element_block& dest, const string_type&, const _Iter& it_begin, const _Iter& it_end)
{
string_elem_block::assign_values(dest, it_begin, it_end);
}
static void mdds_mtv_get_empty_value(string_type& val)
{
val = string_type();
}
template<typename _Iter>
static void mdds_mtv_insert_values(
mtv::base_element_block& block, size_t pos, string_type, const _Iter& it_begin, const _Iter& it_end)
{
string_elem_block::insert_values(block, pos, it_begin, it_end);
}
struct elem_block_func
{
static mdds::mtv::base_element_block* create_new_block(
mdds::mtv::element_t type, size_t init_size)
{
switch (type)
{
case element_type_mtx_string:
return string_elem_block::create_block(init_size);
default:
return mdds::mtv::cell_block_func_base::create_new_block(type, init_size);
}
}
static mdds::mtv::base_element_block* clone_block(const mdds::mtv::base_element_block& block)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
return string_elem_block::clone_block(block);
default:
return mdds::mtv::cell_block_func_base::clone_block(block);
}
}
static void delete_block(mdds::mtv::base_element_block* p)
{
if (!p)
return;
switch (mtv::get_block_type(*p))
{
case element_type_mtx_string:
string_elem_block::delete_block(p);
break;
default:
mdds::mtv::cell_block_func_base::delete_block(p);
}
}
static void resize_block(mdds::mtv::base_element_block& block, size_t new_size)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
string_elem_block::resize_block(block, new_size);
break;
default:
mdds::mtv::cell_block_func_base::resize_block(block, new_size);
}
}
static void print_block(const mdds::mtv::base_element_block& block)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
string_elem_block::print_block(block);
break;
default:
mdds::mtv::cell_block_func_base::print_block(block);
}
}
static void erase(mdds::mtv::base_element_block& block, size_t pos)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
string_elem_block::erase_block(block, pos);
break;
default:
mdds::mtv::cell_block_func_base::erase(block, pos);
}
}
static void erase(mdds::mtv::base_element_block& block, size_t pos, size_t size)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
string_elem_block::erase_block(block, pos, size);
break;
default:
mdds::mtv::cell_block_func_base::erase(block, pos, size);
}
}
static void append_values_from_block(
mdds::mtv::base_element_block& dest, const mdds::mtv::base_element_block& src)
{
switch (mtv::get_block_type(dest))
{
case element_type_mtx_string:
string_elem_block::append_values_from_block(dest, src);
break;
default:
mdds::mtv::cell_block_func_base::append_values_from_block(dest, src);
}
}
static void append_values_from_block(
mdds::mtv::base_element_block& dest, const mdds::mtv::base_element_block& src,
size_t begin_pos, size_t len)
{
switch (mtv::get_block_type(dest))
{
case element_type_mtx_string:
string_elem_block::append_values_from_block(dest, src, begin_pos, len);
break;
default:
mdds::mtv::cell_block_func_base::append_values_from_block(dest, src, begin_pos, len);
}
}
static void assign_values_from_block(
mdds::mtv::base_element_block& dest, const mdds::mtv::base_element_block& src,
size_t begin_pos, size_t len)
{
switch (mtv::get_block_type(dest))
{
case element_type_mtx_string:
string_elem_block::assign_values_from_block(dest, src, begin_pos, len);
break;
default:
mdds::mtv::cell_block_func_base::assign_values_from_block(dest, src, begin_pos, len);
}
}
static bool equal_block(
const mdds::mtv::base_element_block& left, const mdds::mtv::base_element_block& right)
{
if (mtv::get_block_type(left) == element_type_mtx_string)
{
if (mtv::get_block_type(right) != element_type_mtx_string)
return false;
return string_elem_block::get(left) == string_elem_block::get(right);
}
else if (mtv::get_block_type(right) == element_type_mtx_string)
return false;
return mdds::mtv::cell_block_func_base::equal_block(left, right);
}
static void overwrite_values(mdds::mtv::base_element_block& block, size_t pos, size_t len)
{
switch (mtv::get_block_type(block))
{
case element_type_mtx_string:
// Do nothing. The client code manages the life cycle of these cells.
break;
default:
mdds::mtv::cell_block_func_base::overwrite_values(block, pos, len);
}
}
};
};
}}
#endif
<|endoftext|> |
<commit_before>// Fenwick Tree / Binary Indexed Tree
int bit[N];
void add(int p, int v) {
for (p+=2; p<N; p+=p&-p) bit[p] += v;
}
int query(int p) {
int r = 0;
for (p+=2; p; p-=p&-p) r += bit[p];
return r;
}
<commit_msg>Add binary search in bit in log(n)<commit_after>// Fenwick Tree / Binary Indexed Tree
int bit[N];
void add(int p, int v) {
for (p+=2; p<N; p+=p&-p) bit[p] += v;
}
int query(int p) {
int r = 0;
for (p+=2; p; p-=p&-p) r += bit[p];
return r;
}
// --- Binary Search in o(log(n)) ---
const int M = 20
const int N = 1 << M
int binary_search(int val){ //ans => first greater than x
int ans = 0, sum = 0;
for(int i = M - 1; i >= 0; i--){
int x = ans + (1 << i);
if(sum + bit[x] < val)
ans = x, sum += bit[x];
}
return ans + 1;
}
<|endoftext|> |
<commit_before>#include "o3d3xx_camera.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "gtest/gtest.h"
TEST(Camera_Tests, Ctor)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_EQ(cam->GetIP(), o3d3xx::DEFAULT_IP);
EXPECT_EQ(cam->GetXMLRPCPort(), o3d3xx::DEFAULT_XMLRPC_PORT);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.100"));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.100"));
EXPECT_EQ(cam->GetXMLRPCPort(), o3d3xx::DEFAULT_XMLRPC_PORT);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.101", 8080));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.101"));
EXPECT_EQ(cam->GetXMLRPCPort(), 8080);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.102", 8181, "foo"));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.102"));
EXPECT_EQ(cam->GetXMLRPCPort(), 8181);
EXPECT_EQ(cam->GetPassword(), std::string("foo"));
}
TEST(Camera_Tests, GetXMLRPCURLPrefix)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
cam->SetIP("192.168.0.100");
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.100"));
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
cam->SetXMLRPCPort(8080);
EXPECT_EQ(cam->GetXMLRPCPort(), 8080);
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
}
TEST(Camera_Tests, GetAllParameters)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> all_params;
EXPECT_NO_THROW(all_params = cam->GetAllParameters());
}
TEST(Camera_Tests, GetParameter)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> all_params;
EXPECT_NO_THROW(all_params = cam->GetAllParameters());
for (auto& kv : all_params)
{
// NOTE: we are not checking the values from the sensor vs. those stored
// in the hash table here b/c the hardware does not return consistent
// values. e.g., in some cases 'true' vs. '1'.
EXPECT_NO_THROW(cam->GetParameter(kv.first));
}
EXPECT_THROW(cam->GetParameter("Bogus Parameter"),
o3d3xx::error_t);
}
TEST(Camera_Tests, GetSWVersion)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> sw_version;
EXPECT_NO_THROW(sw_version = cam->GetSWVersion());
}
TEST(Camera_Tests, GetApplicationList)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::vector<o3d3xx::Camera::app_entry_t> apps;
EXPECT_NO_THROW(apps = cam->GetApplicationList());
}
TEST(Camera_Tests, RequestSession)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_EQ(cam->GetSessionID().size(), 32);
// camera dtor should cancel the session for us
}
TEST(Camera_Tests, CancelSession)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
// we have no session, so, CancelSession should not make the XMLRPC call
EXPECT_EQ("", cam->GetSessionID());
EXPECT_TRUE(cam->CancelSession());
// set a dummy session
cam->SetSessionID("ABC");
// session doesn't really exist, so, sensor should send back an error
// and the session id should still be the dummy above
EXPECT_FALSE(cam->CancelSession());
EXPECT_EQ("ABC", cam->GetSessionID());
cam->SetSessionID("");
// Get a real session and let the dtor cancel it
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_EQ(cam->GetSessionID().size(), 32);
}
TEST(Camera_Tests, Heartbeat)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
// Heartbeat w/o a session should throw
EXPECT_THROW(cam->Heartbeat(10), o3d3xx::error_t);
int timeout = std::stoi(cam->GetParameter("SessionTimeout"));
cam->RequestSession();
EXPECT_EQ(10, cam->Heartbeat(10));
// @bug The following test always fails (I think it is a bug in the sensor)
//EXPECT_EQ(10, std::stoi(cam->GetParameter("SessionTimeout")));
EXPECT_EQ(timeout, cam->Heartbeat(timeout));
}
TEST(Camera_Tests, SetOperatingMode)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
cam->RequestSession();
EXPECT_NO_THROW(cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT));
EXPECT_EQ(static_cast<int>(o3d3xx::Camera::operating_mode::EDIT),
std::stoi(cam->GetParameter("OperatingMode")));
// after session is cancelled (by dtor), camera automatically goes back
// into RUN mode.
}
TEST(Camera_Tests, GetDeviceConfig)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::unordered_map<std::string, std::string> params =
cam->GetAllParameters();
// for (auto& kv : params)
// {
// std::cout << kv.first << "=" << kv.second << std::endl;
// }
EXPECT_EQ(params.size(), 32);
EXPECT_EQ(params.at("Name"), dev->Name());
EXPECT_EQ(params.at("Description"), dev->Description());
EXPECT_EQ(std::stoi(params.at("ActiveApplication")),
dev->ActiveApplication());
EXPECT_EQ(o3d3xx::stob(params.at("PcicEipEnabled")),
dev->PcicEipEnabled());
EXPECT_EQ(std::stoi(params.at("PcicTcpPort")), dev->PcicTCPPort());
EXPECT_EQ(std::stoi(params.at("PcicProtocolVersion")),
dev->PcicProtocolVersion());
EXPECT_EQ(std::stoi(params.at("IOLogicType")), dev->IOLogicType());
EXPECT_EQ(o3d3xx::stob(params.at("IODebouncing")), dev->IODebouncing());
EXPECT_EQ(std::stoi(params.at("IOExternApplicationSwitch")),
dev->IOExternApplicationSwitch());
EXPECT_EQ(std::stoi(params.at("SessionTimeout")), dev->SessionTimeout());
EXPECT_EQ(std::stoi(params.at("ServiceReportPassedBuffer")),
dev->ServiceReportPassedBuffer());
EXPECT_EQ(std::stoi(params.at("ServiceReportFailedBuffer")),
dev->ServiceReportFailedBuffer());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransX")),
dev->ExtrinsicCalibTransX());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransY")),
dev->ExtrinsicCalibTransY());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransZ")),
dev->ExtrinsicCalibTransZ());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotX")),
dev->ExtrinsicCalibRotX());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotZ")),
dev->ExtrinsicCalibRotY());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotZ")),
dev->ExtrinsicCalibRotY());
EXPECT_EQ(std::stoi(params.at("EvaluationFinishedMinHoldTime")),
dev->EvaluationFinishedMinHoldTime());
EXPECT_EQ(o3d3xx::stob(params.at("SaveRestoreStatsOnApplSwitch")),
dev->SaveRestoreStatsOnApplSwitch());
}
TEST(Camera_Tests, ActivateDisablePassword)
{
std::string tmp_password = "foobar";
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_NO_THROW(cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT));
cam->SetPassword(tmp_password);
EXPECT_NO_THROW(cam->ActivatePassword());
//EXPECT_TRUE(cam->SaveDevice());
//o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
//EXPECT_TRUE(dev->PasswordActivated());
EXPECT_NO_THROW(cam->DisablePassword());
//EXPECT_TRUE(cam->SaveDevice());
//dev = cam->GetDeviceConfig();
//EXPECT_FALSE(dev->PasswordActivated());
}
TEST(Camera_Tests, SetDeviceConfig)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::string orig_name = dev->Name();
std::string tmp_name = "foobar";
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
dev->SetName(tmp_name);
EXPECT_NO_THROW(cam->SetDeviceConfig(dev.get()));
dev = cam->GetDeviceConfig();
EXPECT_EQ(tmp_name, dev->Name());
dev->SetName(orig_name);
EXPECT_NO_THROW(cam->SetDeviceConfig(dev.get()));
dev = cam->GetDeviceConfig();
EXPECT_EQ(orig_name, dev->Name());
}
TEST(Camera_Tests, DeviceConfig_JSON)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::string json = dev->ToJSON();
o3d3xx::DeviceConfig::Ptr dev2 =
o3d3xx::DeviceConfig::FromJSON(json);
EXPECT_EQ(dev->Name(), dev2->Name());
EXPECT_EQ(dev->Description(), dev2->Description());
EXPECT_EQ(dev->ActiveApplication(), dev2->ActiveApplication());
EXPECT_EQ(dev->PcicEipEnabled(), dev2->PcicEipEnabled());
EXPECT_EQ(dev->PcicTCPPort(), dev2->PcicTCPPort());
EXPECT_EQ(dev->PcicProtocolVersion(), dev2->PcicProtocolVersion());
EXPECT_EQ(dev->IOLogicType(), dev2->IOLogicType());
EXPECT_EQ(dev->IODebouncing(), dev2->IODebouncing());
EXPECT_EQ(dev->IOExternApplicationSwitch(),
dev2->IOExternApplicationSwitch());
EXPECT_EQ(dev->SessionTimeout(), dev2->SessionTimeout());
EXPECT_EQ(dev->ServiceReportPassedBuffer(),
dev2->ServiceReportPassedBuffer());
EXPECT_EQ(dev->ServiceReportFailedBuffer(),
dev2->ServiceReportFailedBuffer());
EXPECT_EQ(dev->ExtrinsicCalibTransX(), dev2->ExtrinsicCalibTransX());
EXPECT_EQ(dev->ExtrinsicCalibTransY(), dev2->ExtrinsicCalibTransY());
EXPECT_EQ(dev->ExtrinsicCalibTransZ(), dev2->ExtrinsicCalibTransZ());
EXPECT_EQ(dev->ExtrinsicCalibRotX(), dev2->ExtrinsicCalibRotX());
EXPECT_EQ(dev->ExtrinsicCalibRotY(), dev2->ExtrinsicCalibRotY());
EXPECT_EQ(dev->ExtrinsicCalibRotZ(), dev2->ExtrinsicCalibRotZ());
EXPECT_EQ(dev->EvaluationFinishedMinHoldTime(),
dev2->EvaluationFinishedMinHoldTime());
EXPECT_EQ(dev->SaveRestoreStatsOnApplSwitch(),
dev2->SaveRestoreStatsOnApplSwitch());
// we do not want to compare the read-only properties
}
TEST(Camera_Tests, GetNetParameters)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
std::unordered_map<std::string, std::string> params =
cam->GetNetParameters();
EXPECT_NO_THROW(params.at("MACAddress"));
EXPECT_NO_THROW(params.at("NetworkSpeed"));
EXPECT_NO_THROW(params.at("StaticIPv4Address"));
EXPECT_NO_THROW(params.at("StaticIPv4Gateway"));
EXPECT_NO_THROW(params.at("StaticIPv4SubNetMask"));
EXPECT_NO_THROW(params.at("UseDHCP"));
}
TEST(Camera_Tests, NetConfig)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
o3d3xx::NetConfig::Ptr net = cam->GetNetConfig();
bool has_changed = true;
cam->SetNetConfig(net.get(), &has_changed);
EXPECT_FALSE(has_changed);
}
TEST(Camera_Tests, NetConfig_JSON)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
o3d3xx::NetConfig::Ptr net = cam->GetNetConfig();
std::string json = net->ToJSON();
o3d3xx::NetConfig::Ptr net2 =
o3d3xx::NetConfig::FromJSON(json);
EXPECT_EQ(net->StaticIPv4Address(), net2->StaticIPv4Address());
EXPECT_EQ(net->StaticIPv4Gateway(), net2->StaticIPv4Gateway());
EXPECT_EQ(net->StaticIPv4SubNetMask(), net2->StaticIPv4SubNetMask());
EXPECT_EQ(net->UseDHCP(), net2->UseDHCP());
// we do not want to compare the read-only properties
}
<commit_msg>Fixed typo in camera unit tests<commit_after>#include "o3d3xx_camera.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "gtest/gtest.h"
TEST(Camera_Tests, Ctor)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_EQ(cam->GetIP(), o3d3xx::DEFAULT_IP);
EXPECT_EQ(cam->GetXMLRPCPort(), o3d3xx::DEFAULT_XMLRPC_PORT);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.100"));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.100"));
EXPECT_EQ(cam->GetXMLRPCPort(), o3d3xx::DEFAULT_XMLRPC_PORT);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.101", 8080));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.101"));
EXPECT_EQ(cam->GetXMLRPCPort(), 8080);
EXPECT_EQ(cam->GetPassword(), o3d3xx::DEFAULT_PASSWORD);
cam.reset(new o3d3xx::Camera("192.168.0.102", 8181, "foo"));
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.102"));
EXPECT_EQ(cam->GetXMLRPCPort(), 8181);
EXPECT_EQ(cam->GetPassword(), std::string("foo"));
}
TEST(Camera_Tests, GetXMLRPCURLPrefix)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
cam->SetIP("192.168.0.100");
EXPECT_EQ(cam->GetIP(), std::string("192.168.0.100"));
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
cam->SetXMLRPCPort(8080);
EXPECT_EQ(cam->GetXMLRPCPort(), 8080);
EXPECT_EQ(cam->GetXMLRPCURLPrefix(),
std::string("http://" + cam->GetIP() +
":" + std::to_string(cam->GetXMLRPCPort())));
}
TEST(Camera_Tests, GetAllParameters)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> all_params;
EXPECT_NO_THROW(all_params = cam->GetAllParameters());
}
TEST(Camera_Tests, GetParameter)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> all_params;
EXPECT_NO_THROW(all_params = cam->GetAllParameters());
for (auto& kv : all_params)
{
// NOTE: we are not checking the values from the sensor vs. those stored
// in the hash table here b/c the hardware does not return consistent
// values. e.g., in some cases 'true' vs. '1'.
EXPECT_NO_THROW(cam->GetParameter(kv.first));
}
EXPECT_THROW(cam->GetParameter("Bogus Parameter"),
o3d3xx::error_t);
}
TEST(Camera_Tests, GetSWVersion)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::unordered_map<std::string, std::string> sw_version;
EXPECT_NO_THROW(sw_version = cam->GetSWVersion());
}
TEST(Camera_Tests, GetApplicationList)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
std::vector<o3d3xx::Camera::app_entry_t> apps;
EXPECT_NO_THROW(apps = cam->GetApplicationList());
}
TEST(Camera_Tests, RequestSession)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_EQ(cam->GetSessionID().size(), 32);
// camera dtor should cancel the session for us
}
TEST(Camera_Tests, CancelSession)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
// we have no session, so, CancelSession should not make the XMLRPC call
EXPECT_EQ("", cam->GetSessionID());
EXPECT_TRUE(cam->CancelSession());
// set a dummy session
cam->SetSessionID("ABC");
// session doesn't really exist, so, sensor should send back an error
// and the session id should still be the dummy above
EXPECT_FALSE(cam->CancelSession());
EXPECT_EQ("ABC", cam->GetSessionID());
cam->SetSessionID("");
// Get a real session and let the dtor cancel it
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_EQ(cam->GetSessionID().size(), 32);
}
TEST(Camera_Tests, Heartbeat)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
// Heartbeat w/o a session should throw
EXPECT_THROW(cam->Heartbeat(10), o3d3xx::error_t);
int timeout = std::stoi(cam->GetParameter("SessionTimeout"));
cam->RequestSession();
EXPECT_EQ(10, cam->Heartbeat(10));
// @bug The following test always fails (I think it is a bug in the sensor)
//EXPECT_EQ(10, std::stoi(cam->GetParameter("SessionTimeout")));
EXPECT_EQ(timeout, cam->Heartbeat(timeout));
}
TEST(Camera_Tests, SetOperatingMode)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
cam->RequestSession();
EXPECT_NO_THROW(cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT));
EXPECT_EQ(static_cast<int>(o3d3xx::Camera::operating_mode::EDIT),
std::stoi(cam->GetParameter("OperatingMode")));
// after session is cancelled (by dtor), camera automatically goes back
// into RUN mode.
}
TEST(Camera_Tests, GetDeviceConfig)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::unordered_map<std::string, std::string> params =
cam->GetAllParameters();
// for (auto& kv : params)
// {
// std::cout << kv.first << "=" << kv.second << std::endl;
// }
EXPECT_EQ(params.size(), 32);
EXPECT_EQ(params.at("Name"), dev->Name());
EXPECT_EQ(params.at("Description"), dev->Description());
EXPECT_EQ(std::stoi(params.at("ActiveApplication")),
dev->ActiveApplication());
EXPECT_EQ(o3d3xx::stob(params.at("PcicEipEnabled")),
dev->PcicEipEnabled());
EXPECT_EQ(std::stoi(params.at("PcicTcpPort")), dev->PcicTCPPort());
EXPECT_EQ(std::stoi(params.at("PcicProtocolVersion")),
dev->PcicProtocolVersion());
EXPECT_EQ(std::stoi(params.at("IOLogicType")), dev->IOLogicType());
EXPECT_EQ(o3d3xx::stob(params.at("IODebouncing")), dev->IODebouncing());
EXPECT_EQ(std::stoi(params.at("IOExternApplicationSwitch")),
dev->IOExternApplicationSwitch());
EXPECT_EQ(std::stoi(params.at("SessionTimeout")), dev->SessionTimeout());
EXPECT_EQ(std::stoi(params.at("ServiceReportPassedBuffer")),
dev->ServiceReportPassedBuffer());
EXPECT_EQ(std::stoi(params.at("ServiceReportFailedBuffer")),
dev->ServiceReportFailedBuffer());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransX")),
dev->ExtrinsicCalibTransX());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransY")),
dev->ExtrinsicCalibTransY());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibTransZ")),
dev->ExtrinsicCalibTransZ());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotX")),
dev->ExtrinsicCalibRotX());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotY")),
dev->ExtrinsicCalibRotY());
EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotZ")),
dev->ExtrinsicCalibRotZ());
EXPECT_EQ(std::stoi(params.at("EvaluationFinishedMinHoldTime")),
dev->EvaluationFinishedMinHoldTime());
EXPECT_EQ(o3d3xx::stob(params.at("SaveRestoreStatsOnApplSwitch")),
dev->SaveRestoreStatsOnApplSwitch());
}
TEST(Camera_Tests, ActivateDisablePassword)
{
std::string tmp_password = "foobar";
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
EXPECT_NO_THROW(cam->RequestSession());
EXPECT_NO_THROW(cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT));
cam->SetPassword(tmp_password);
EXPECT_NO_THROW(cam->ActivatePassword());
//EXPECT_TRUE(cam->SaveDevice());
//o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
//EXPECT_TRUE(dev->PasswordActivated());
EXPECT_NO_THROW(cam->DisablePassword());
//EXPECT_TRUE(cam->SaveDevice());
//dev = cam->GetDeviceConfig();
//EXPECT_FALSE(dev->PasswordActivated());
}
TEST(Camera_Tests, SetDeviceConfig)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::string orig_name = dev->Name();
std::string tmp_name = "foobar";
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
dev->SetName(tmp_name);
EXPECT_NO_THROW(cam->SetDeviceConfig(dev.get()));
dev = cam->GetDeviceConfig();
EXPECT_EQ(tmp_name, dev->Name());
dev->SetName(orig_name);
EXPECT_NO_THROW(cam->SetDeviceConfig(dev.get()));
dev = cam->GetDeviceConfig();
EXPECT_EQ(orig_name, dev->Name());
}
TEST(Camera_Tests, DeviceConfig_JSON)
{
o3d3xx::Camera::Ptr cam =
o3d3xx::Camera::Ptr(new o3d3xx::Camera());
o3d3xx::DeviceConfig::Ptr dev = cam->GetDeviceConfig();
std::string json = dev->ToJSON();
o3d3xx::DeviceConfig::Ptr dev2 =
o3d3xx::DeviceConfig::FromJSON(json);
EXPECT_EQ(dev->Name(), dev2->Name());
EXPECT_EQ(dev->Description(), dev2->Description());
EXPECT_EQ(dev->ActiveApplication(), dev2->ActiveApplication());
EXPECT_EQ(dev->PcicEipEnabled(), dev2->PcicEipEnabled());
EXPECT_EQ(dev->PcicTCPPort(), dev2->PcicTCPPort());
EXPECT_EQ(dev->PcicProtocolVersion(), dev2->PcicProtocolVersion());
EXPECT_EQ(dev->IOLogicType(), dev2->IOLogicType());
EXPECT_EQ(dev->IODebouncing(), dev2->IODebouncing());
EXPECT_EQ(dev->IOExternApplicationSwitch(),
dev2->IOExternApplicationSwitch());
EXPECT_EQ(dev->SessionTimeout(), dev2->SessionTimeout());
EXPECT_EQ(dev->ServiceReportPassedBuffer(),
dev2->ServiceReportPassedBuffer());
EXPECT_EQ(dev->ServiceReportFailedBuffer(),
dev2->ServiceReportFailedBuffer());
EXPECT_EQ(dev->ExtrinsicCalibTransX(), dev2->ExtrinsicCalibTransX());
EXPECT_EQ(dev->ExtrinsicCalibTransY(), dev2->ExtrinsicCalibTransY());
EXPECT_EQ(dev->ExtrinsicCalibTransZ(), dev2->ExtrinsicCalibTransZ());
EXPECT_EQ(dev->ExtrinsicCalibRotX(), dev2->ExtrinsicCalibRotX());
EXPECT_EQ(dev->ExtrinsicCalibRotY(), dev2->ExtrinsicCalibRotY());
EXPECT_EQ(dev->ExtrinsicCalibRotZ(), dev2->ExtrinsicCalibRotZ());
EXPECT_EQ(dev->EvaluationFinishedMinHoldTime(),
dev2->EvaluationFinishedMinHoldTime());
EXPECT_EQ(dev->SaveRestoreStatsOnApplSwitch(),
dev2->SaveRestoreStatsOnApplSwitch());
// we do not want to compare the read-only properties
}
TEST(Camera_Tests, GetNetParameters)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
std::unordered_map<std::string, std::string> params =
cam->GetNetParameters();
EXPECT_NO_THROW(params.at("MACAddress"));
EXPECT_NO_THROW(params.at("NetworkSpeed"));
EXPECT_NO_THROW(params.at("StaticIPv4Address"));
EXPECT_NO_THROW(params.at("StaticIPv4Gateway"));
EXPECT_NO_THROW(params.at("StaticIPv4SubNetMask"));
EXPECT_NO_THROW(params.at("UseDHCP"));
}
TEST(Camera_Tests, NetConfig)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
o3d3xx::NetConfig::Ptr net = cam->GetNetConfig();
bool has_changed = true;
cam->SetNetConfig(net.get(), &has_changed);
EXPECT_FALSE(has_changed);
}
TEST(Camera_Tests, NetConfig_JSON)
{
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
cam->RequestSession();
cam->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT);
o3d3xx::NetConfig::Ptr net = cam->GetNetConfig();
std::string json = net->ToJSON();
o3d3xx::NetConfig::Ptr net2 =
o3d3xx::NetConfig::FromJSON(json);
EXPECT_EQ(net->StaticIPv4Address(), net2->StaticIPv4Address());
EXPECT_EQ(net->StaticIPv4Gateway(), net2->StaticIPv4Gateway());
EXPECT_EQ(net->StaticIPv4SubNetMask(), net2->StaticIPv4SubNetMask());
EXPECT_EQ(net->UseDHCP(), net2->UseDHCP());
// we do not want to compare the read-only properties
}
<|endoftext|> |
<commit_before>#include "config.h"
#include "shared.hh"
#include "globals.hh"
#include "store-api.hh"
#include "util.hh"
#include "misc.hh"
#include <iostream>
#include <cctype>
#include <exception>
#include <algorithm>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
extern char * * environ;
namespace nix {
volatile sig_atomic_t blockInt = 0;
static void sigintHandler(int signo)
{
if (!blockInt) {
_isInterrupted = 1;
blockInt = 1;
}
}
static bool gcWarning = true;
void printGCWarning()
{
if (!gcWarning) return;
static bool haveWarned = false;
warnOnce(haveWarned,
"you did not specify ‘--add-root’; "
"the result might be removed by the garbage collector");
}
void printMissing(StoreAPI & store, const PathSet & paths)
{
unsigned long long downloadSize, narSize;
PathSet willBuild, willSubstitute, unknown;
queryMissing(store, paths, willBuild, willSubstitute, unknown, downloadSize, narSize);
printMissing(willBuild, willSubstitute, unknown, downloadSize, narSize);
}
void printMissing(const PathSet & willBuild,
const PathSet & willSubstitute, const PathSet & unknown,
unsigned long long downloadSize, unsigned long long narSize)
{
if (!willBuild.empty()) {
printMsg(lvlInfo, format("these derivations will be built:"));
Paths sorted = topoSortPaths(*store, willBuild);
reverse(sorted.begin(), sorted.end());
for (auto & i : sorted)
printMsg(lvlInfo, format(" %1%") % i);
}
if (!willSubstitute.empty()) {
printMsg(lvlInfo, format("these paths will be fetched (%.2f MiB download, %.2f MiB unpacked):")
% (downloadSize / (1024.0 * 1024.0))
% (narSize / (1024.0 * 1024.0)));
for (auto & i : willSubstitute)
printMsg(lvlInfo, format(" %1%") % i);
}
if (!unknown.empty()) {
printMsg(lvlInfo, format("don't know how to build these paths%1%:")
% (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""));
for (auto & i : unknown)
printMsg(lvlInfo, format(" %1%") % i);
}
}
static void setLogType(string lt)
{
if (lt == "pretty") logType = ltPretty;
else if (lt == "escapes") logType = ltEscapes;
else if (lt == "flat") logType = ltFlat;
else throw UsageError("unknown log type");
}
string getArg(const string & opt,
Strings::iterator & i, const Strings::iterator & end)
{
++i;
if (i == end) throw UsageError(format("‘%1%’ requires an argument") % opt);
return *i;
}
void detectStackOverflow();
void initNix()
{
/* Turn on buffering for cerr. */
#if HAVE_PUBSETBUF
static char buf[1024];
std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf));
#endif
std::ios::sync_with_stdio(false);
settings.processEnvironment();
settings.loadConfFile();
/* Catch SIGINT. */
struct sigaction act;
act.sa_handler = sigintHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if (sigaction(SIGINT, &act, 0))
throw SysError("installing handler for SIGINT");
if (sigaction(SIGTERM, &act, 0))
throw SysError("installing handler for SIGTERM");
if (sigaction(SIGHUP, &act, 0))
throw SysError("installing handler for SIGHUP");
/* Ignore SIGPIPE. */
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
if (sigaction(SIGPIPE, &act, 0))
throw SysError("ignoring SIGPIPE");
/* Reset SIGCHLD to its default. */
act.sa_handler = SIG_DFL;
act.sa_flags = 0;
if (sigaction(SIGCHLD, &act, 0))
throw SysError("resetting SIGCHLD");
/* Register a SIGSEGV handler to detect stack overflows. */
detectStackOverflow();
/* There is no privacy in the Nix system ;-) At least not for
now. In particular, store objects should be readable by
everybody. */
umask(0022);
/* Initialise the PRNG. */
struct timeval tv;
gettimeofday(&tv, 0);
srandom(tv.tv_usec);
if (char *pack = getenv("_NIX_OPTIONS"))
settings.unpack(pack);
}
void parseCmdLine(int argc, char * * argv,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg)
{
/* Put the arguments in a vector. */
Strings args;
argc--; argv++;
while (argc--) args.push_back(*argv++);
/* Process default options. */
for (Strings::iterator i = args.begin(); i != args.end(); ++i) {
string arg = *i;
/* Expand compound dash options (i.e., `-qlf' -> `-q -l -f'). */
if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && isalpha(arg[1])) {
*i = (string) "-" + arg[1];
auto next = i; ++next;
for (unsigned int j = 2; j < arg.length(); j++)
if (isalpha(arg[j]))
args.insert(next, (string) "-" + arg[j]);
else {
args.insert(next, string(arg, j));
break;
}
arg = *i;
}
if (arg == "--verbose" || arg == "-v") verbosity = (Verbosity) (verbosity + 1);
else if (arg == "--quiet") verbosity = verbosity > lvlError ? (Verbosity) (verbosity - 1) : lvlError;
else if (arg == "--log-type") {
string s = getArg(arg, i, args.end());
setLogType(s);
}
else if (arg == "--no-build-output" || arg == "-Q")
settings.buildVerbosity = lvlVomit;
else if (arg == "--print-build-trace")
settings.printBuildTrace = true;
else if (arg == "--keep-failed" || arg == "-K")
settings.keepFailed = true;
else if (arg == "--keep-going" || arg == "-k")
settings.keepGoing = true;
else if (arg == "--fallback")
settings.set("build-fallback", "true");
else if (arg == "--max-jobs" || arg == "-j")
settings.set("build-max-jobs", getArg(arg, i, args.end()));
else if (arg == "--cores")
settings.set("build-cores", getArg(arg, i, args.end()));
else if (arg == "--readonly-mode")
settings.readOnlyMode = true;
else if (arg == "--max-silent-time")
settings.set("build-max-silent-time", getArg(arg, i, args.end()));
else if (arg == "--timeout")
settings.set("build-timeout", getArg(arg, i, args.end()));
else if (arg == "--no-build-hook")
settings.useBuildHook = false;
else if (arg == "--show-trace")
settings.showTrace = true;
else if (arg == "--no-gc-warning")
gcWarning = false;
else if (arg == "--option") {
++i; if (i == args.end()) throw UsageError("‘--option’ requires two arguments");
string name = *i;
++i; if (i == args.end()) throw UsageError("‘--option’ requires two arguments");
string value = *i;
settings.set(name, value);
}
else {
if (!parseArg(i, args.end()))
throw UsageError(format("unrecognised option ‘%1%’") % *i);
}
}
settings.update();
}
void printVersion(const string & programName)
{
std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl;
throw Exit();
}
void showManPage(const string & name)
{
restoreSIGPIPE();
execlp("man", "man", name.c_str(), NULL);
throw SysError(format("command ‘man %1%’ failed") % name.c_str());
}
int handleExceptions(const string & programName, std::function<void()> fun)
{
string error = ANSI_RED "error:" ANSI_NORMAL " ";
try {
try {
fun();
} catch (...) {
/* Subtle: we have to make sure that any `interrupted'
condition is discharged before we reach printMsg()
below, since otherwise it will throw an (uncaught)
exception. */
blockInt = 1; /* ignore further SIGINTs */
_isInterrupted = 0;
throw;
}
} catch (Exit & e) {
return e.status;
} catch (UsageError & e) {
printMsg(lvlError,
format(error + "%1%\nTry ‘%2% --help’ for more information.")
% e.what() % programName);
return 1;
} catch (BaseError & e) {
printMsg(lvlError, format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg());
if (e.prefix() != "" && !settings.showTrace)
printMsg(lvlError, "(use ‘--show-trace’ to show detailed location information)");
return e.status;
} catch (std::bad_alloc & e) {
printMsg(lvlError, error + "out of memory");
return 1;
} catch (std::exception & e) {
printMsg(lvlError, error + e.what());
return 1;
}
return 0;
}
RunPager::RunPager()
{
string pager = getEnv("PAGER");
if (!isatty(STDOUT_FILENO) || pager.empty()) return;
/* Ignore SIGINT. The pager will handle it (and we'll get
SIGPIPE). */
struct sigaction act;
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
if (sigaction(SIGINT, &act, 0)) throw SysError("ignoring SIGINT");
restoreSIGPIPE();
Pipe toPager;
toPager.create();
pid = startProcess([&]() {
if (dup2(toPager.readSide, STDIN_FILENO) == -1)
throw SysError("dupping stdin");
if (!getenv("LESS"))
setenv("LESS", "FRSXMK", 1);
execl("/bin/sh", "sh", "-c", pager.c_str(), NULL);
throw SysError(format("executing ‘%1%’") % pager);
});
if (dup2(toPager.writeSide, STDOUT_FILENO) == -1)
throw SysError("dupping stdout");
}
RunPager::~RunPager()
{
if (pid != -1) {
std::cout.flush();
close(STDOUT_FILENO);
pid.wait(true);
}
}
}
<commit_msg>Provide default pagers<commit_after>#include "config.h"
#include "shared.hh"
#include "globals.hh"
#include "store-api.hh"
#include "util.hh"
#include "misc.hh"
#include <iostream>
#include <cctype>
#include <exception>
#include <algorithm>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
extern char * * environ;
namespace nix {
volatile sig_atomic_t blockInt = 0;
static void sigintHandler(int signo)
{
if (!blockInt) {
_isInterrupted = 1;
blockInt = 1;
}
}
static bool gcWarning = true;
void printGCWarning()
{
if (!gcWarning) return;
static bool haveWarned = false;
warnOnce(haveWarned,
"you did not specify ‘--add-root’; "
"the result might be removed by the garbage collector");
}
void printMissing(StoreAPI & store, const PathSet & paths)
{
unsigned long long downloadSize, narSize;
PathSet willBuild, willSubstitute, unknown;
queryMissing(store, paths, willBuild, willSubstitute, unknown, downloadSize, narSize);
printMissing(willBuild, willSubstitute, unknown, downloadSize, narSize);
}
void printMissing(const PathSet & willBuild,
const PathSet & willSubstitute, const PathSet & unknown,
unsigned long long downloadSize, unsigned long long narSize)
{
if (!willBuild.empty()) {
printMsg(lvlInfo, format("these derivations will be built:"));
Paths sorted = topoSortPaths(*store, willBuild);
reverse(sorted.begin(), sorted.end());
for (auto & i : sorted)
printMsg(lvlInfo, format(" %1%") % i);
}
if (!willSubstitute.empty()) {
printMsg(lvlInfo, format("these paths will be fetched (%.2f MiB download, %.2f MiB unpacked):")
% (downloadSize / (1024.0 * 1024.0))
% (narSize / (1024.0 * 1024.0)));
for (auto & i : willSubstitute)
printMsg(lvlInfo, format(" %1%") % i);
}
if (!unknown.empty()) {
printMsg(lvlInfo, format("don't know how to build these paths%1%:")
% (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""));
for (auto & i : unknown)
printMsg(lvlInfo, format(" %1%") % i);
}
}
static void setLogType(string lt)
{
if (lt == "pretty") logType = ltPretty;
else if (lt == "escapes") logType = ltEscapes;
else if (lt == "flat") logType = ltFlat;
else throw UsageError("unknown log type");
}
string getArg(const string & opt,
Strings::iterator & i, const Strings::iterator & end)
{
++i;
if (i == end) throw UsageError(format("‘%1%’ requires an argument") % opt);
return *i;
}
void detectStackOverflow();
void initNix()
{
/* Turn on buffering for cerr. */
#if HAVE_PUBSETBUF
static char buf[1024];
std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf));
#endif
std::ios::sync_with_stdio(false);
settings.processEnvironment();
settings.loadConfFile();
/* Catch SIGINT. */
struct sigaction act;
act.sa_handler = sigintHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if (sigaction(SIGINT, &act, 0))
throw SysError("installing handler for SIGINT");
if (sigaction(SIGTERM, &act, 0))
throw SysError("installing handler for SIGTERM");
if (sigaction(SIGHUP, &act, 0))
throw SysError("installing handler for SIGHUP");
/* Ignore SIGPIPE. */
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
if (sigaction(SIGPIPE, &act, 0))
throw SysError("ignoring SIGPIPE");
/* Reset SIGCHLD to its default. */
act.sa_handler = SIG_DFL;
act.sa_flags = 0;
if (sigaction(SIGCHLD, &act, 0))
throw SysError("resetting SIGCHLD");
/* Register a SIGSEGV handler to detect stack overflows. */
detectStackOverflow();
/* There is no privacy in the Nix system ;-) At least not for
now. In particular, store objects should be readable by
everybody. */
umask(0022);
/* Initialise the PRNG. */
struct timeval tv;
gettimeofday(&tv, 0);
srandom(tv.tv_usec);
if (char *pack = getenv("_NIX_OPTIONS"))
settings.unpack(pack);
}
void parseCmdLine(int argc, char * * argv,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg)
{
/* Put the arguments in a vector. */
Strings args;
argc--; argv++;
while (argc--) args.push_back(*argv++);
/* Process default options. */
for (Strings::iterator i = args.begin(); i != args.end(); ++i) {
string arg = *i;
/* Expand compound dash options (i.e., `-qlf' -> `-q -l -f'). */
if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && isalpha(arg[1])) {
*i = (string) "-" + arg[1];
auto next = i; ++next;
for (unsigned int j = 2; j < arg.length(); j++)
if (isalpha(arg[j]))
args.insert(next, (string) "-" + arg[j]);
else {
args.insert(next, string(arg, j));
break;
}
arg = *i;
}
if (arg == "--verbose" || arg == "-v") verbosity = (Verbosity) (verbosity + 1);
else if (arg == "--quiet") verbosity = verbosity > lvlError ? (Verbosity) (verbosity - 1) : lvlError;
else if (arg == "--log-type") {
string s = getArg(arg, i, args.end());
setLogType(s);
}
else if (arg == "--no-build-output" || arg == "-Q")
settings.buildVerbosity = lvlVomit;
else if (arg == "--print-build-trace")
settings.printBuildTrace = true;
else if (arg == "--keep-failed" || arg == "-K")
settings.keepFailed = true;
else if (arg == "--keep-going" || arg == "-k")
settings.keepGoing = true;
else if (arg == "--fallback")
settings.set("build-fallback", "true");
else if (arg == "--max-jobs" || arg == "-j")
settings.set("build-max-jobs", getArg(arg, i, args.end()));
else if (arg == "--cores")
settings.set("build-cores", getArg(arg, i, args.end()));
else if (arg == "--readonly-mode")
settings.readOnlyMode = true;
else if (arg == "--max-silent-time")
settings.set("build-max-silent-time", getArg(arg, i, args.end()));
else if (arg == "--timeout")
settings.set("build-timeout", getArg(arg, i, args.end()));
else if (arg == "--no-build-hook")
settings.useBuildHook = false;
else if (arg == "--show-trace")
settings.showTrace = true;
else if (arg == "--no-gc-warning")
gcWarning = false;
else if (arg == "--option") {
++i; if (i == args.end()) throw UsageError("‘--option’ requires two arguments");
string name = *i;
++i; if (i == args.end()) throw UsageError("‘--option’ requires two arguments");
string value = *i;
settings.set(name, value);
}
else {
if (!parseArg(i, args.end()))
throw UsageError(format("unrecognised option ‘%1%’") % *i);
}
}
settings.update();
}
void printVersion(const string & programName)
{
std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl;
throw Exit();
}
void showManPage(const string & name)
{
restoreSIGPIPE();
execlp("man", "man", name.c_str(), NULL);
throw SysError(format("command ‘man %1%’ failed") % name.c_str());
}
int handleExceptions(const string & programName, std::function<void()> fun)
{
string error = ANSI_RED "error:" ANSI_NORMAL " ";
try {
try {
fun();
} catch (...) {
/* Subtle: we have to make sure that any `interrupted'
condition is discharged before we reach printMsg()
below, since otherwise it will throw an (uncaught)
exception. */
blockInt = 1; /* ignore further SIGINTs */
_isInterrupted = 0;
throw;
}
} catch (Exit & e) {
return e.status;
} catch (UsageError & e) {
printMsg(lvlError,
format(error + "%1%\nTry ‘%2% --help’ for more information.")
% e.what() % programName);
return 1;
} catch (BaseError & e) {
printMsg(lvlError, format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg());
if (e.prefix() != "" && !settings.showTrace)
printMsg(lvlError, "(use ‘--show-trace’ to show detailed location information)");
return e.status;
} catch (std::bad_alloc & e) {
printMsg(lvlError, error + "out of memory");
return 1;
} catch (std::exception & e) {
printMsg(lvlError, error + e.what());
return 1;
}
return 0;
}
RunPager::RunPager()
{
if (!isatty(STDOUT_FILENO)) return;
string pager = getEnv("PAGER", "default");
if (pager == "" || pager == "cat") return;
/* Ignore SIGINT. The pager will handle it (and we'll get
SIGPIPE). */
struct sigaction act;
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
if (sigaction(SIGINT, &act, 0)) throw SysError("ignoring SIGINT");
restoreSIGPIPE();
Pipe toPager;
toPager.create();
pid = startProcess([&]() {
if (dup2(toPager.readSide, STDIN_FILENO) == -1)
throw SysError("dupping stdin");
if (!getenv("LESS"))
setenv("LESS", "FRSXMK", 1);
if (pager != "default")
execl("/bin/sh", "sh", "-c", pager.c_str(), NULL);
execlp("pager", "pager", NULL);
execlp("less", "less", NULL);
execlp("more", "more", NULL);
throw SysError(format("executing ‘%1%’") % pager);
});
if (dup2(toPager.writeSide, STDOUT_FILENO) == -1)
throw SysError("dupping stdout");
}
RunPager::~RunPager()
{
if (pid != -1) {
std::cout.flush();
close(STDOUT_FILENO);
pid.wait(true);
}
}
}
<|endoftext|> |
<commit_before>/*
* HelloWorldApp.cpp
*
* Created on: Oct 10, 2010
* Author: rgreen
*/
#include "HelloWorldApp.h"
#include "AppContext.h"
#include <batterytech/primitives.h>
#include <batterytech/platform/platformgeneral.h>
#include <batterytech/Logger.h>
#include <batterytech/platform/platformgl.h>
#include <string.h>
Context* btAppCreateContext(GraphicsConfiguration *graphicsConfig) {
return new AppContext(graphicsConfig);
}
HelloWorldApp::HelloWorldApp(Context *context) {
this->context = context;
textRenderer = new TextRasterRenderer(context, context->appProperties->get("menu_font")->getValue(), 24.0f);
}
HelloWorldApp::~HelloWorldApp() {
logmsg("Releasing App");
initialized = FALSE;
context = NULL;
delete textRenderer;
textRenderer = NULL;
// context is freed by batterytech core
}
void HelloWorldApp::setupGL() {
if (context->gConfig->useShaders) {
} else {
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glShadeModel(GL_SMOOTH);
glEnable(GL_TEXTURE_2D);
}
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_DITHER);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, context->gConfig->viewportWidth, context->gConfig->viewportHeight);
}
void HelloWorldApp::update() {
if (!initialized || context->wasSuspended) {
logmsg("Initializing Renderers");
//context->worldRenderer->init(TRUE);
setupGL();
textRenderer->init(TRUE);
context->wasSuspended = FALSE;
initialized = TRUE;
}
}
void HelloWorldApp::render() {
if (initialized) {
glClear(GL_COLOR_BUFFER_BIT);
textRenderer->startText();
textRenderer->render("Hello World!", 300, 300, 1.0f);
textRenderer->finishText();
}
}
<commit_msg>BT 2.0 helloworld very close to working correctly now<commit_after>/*
* HelloWorldApp.cpp
*
* Created on: Oct 10, 2010
* Author: rgreen
*/
#include "HelloWorldApp.h"
#include "AppContext.h"
#include <batterytech/primitives.h>
#include <batterytech/platform/platformgeneral.h>
#include <batterytech/Logger.h>
#include <batterytech/platform/platformgl.h>
#include <batterytech/render/MenuRenderer.h>
#include <batterytech/render/RenderContext.h>
#include <string.h>
Context* btAppCreateContext(GraphicsConfiguration *graphicsConfig) {
return new AppContext(graphicsConfig);
}
HelloWorldApp::HelloWorldApp(Context *context) {
this->context = context;
textRenderer = new TextRasterRenderer(context, context->appProperties->get("menu_font")->getValue(), 24.0f);
}
HelloWorldApp::~HelloWorldApp() {
logmsg("Releasing App");
initialized = FALSE;
context = NULL;
delete textRenderer;
textRenderer = NULL;
// context is freed by batterytech core
}
void HelloWorldApp::setupGL() {
if (context->gConfig->useShaders) {
} else {
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glShadeModel(GL_SMOOTH);
glEnable(GL_TEXTURE_2D);
}
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_DITHER);
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, context->gConfig->viewportWidth, context->gConfig->viewportHeight);
}
void HelloWorldApp::update() {
if (!initialized || context->wasSuspended) {
logmsg("Initializing Renderers");
setupGL();
textRenderer->init(TRUE);
context->menuRenderer->init(TRUE);
context->wasSuspended = FALSE;
initialized = TRUE;
}
}
void HelloWorldApp::render() {
if (initialized) {
glClear(GL_COLOR_BUFFER_BIT);
context->renderContext->colorFilter = Vector4f(1, 1, 1, 1);
if (context->gConfig->useShaders) {
context->renderContext->projMatrix.identity();
context->renderContext->mvMatrix.identity();
context->renderContext->projMatrix.ortho(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
} else {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
textRenderer->startText();
textRenderer->render("Hello World!", 300, 300, 1.0f);
textRenderer->finishText();
}
}
<|endoftext|> |
<commit_before>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).
#include "org/xtreemfs/client/file.h"
#include "org/xtreemfs/client/mrc_proxy.h"
#include "org/xtreemfs/client/osd_proxy.h"
#include "org/xtreemfs/client/volume.h"
#include "multi_response_target.h"
using namespace org::xtreemfs::client;
#include <errno.h>
#ifdef _WIN32
#include <windows.h>
#pragma warning( push )
#pragma warning( disable: 4100 )
#else
#include <errno.h>
#endif
#include "org/xtreemfs/interfaces/osd_interface.h"
#ifdef _WIN32
#pragma warning( pop )
#endif
File::File( YIELD::auto_Object<Volume> parent_volume, YIELD::auto_Object<MRCProxy> mrc_proxy, const YIELD::Path& path, const org::xtreemfs::interfaces::FileCredentials& file_credentials )
: parent_volume( parent_volume ), mrc_proxy( mrc_proxy ), path( path ), file_credentials( file_credentials )
{ }
File::~File()
{
flush();
}
bool File::datasync()
{
flush();
return true;
}
bool File::close()
{
flush();
return true;
}
bool File::flush()
{
try
{
if ( !latest_osd_write_response.get_new_file_size().empty() )
{
mrc_proxy->xtreemfs_update_file_size( file_credentials.get_xcap(), latest_osd_write_response );
latest_osd_write_response.set_new_file_size( org::xtreemfs::interfaces::NewFileSize() );
}
return true;
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return false;
}
YIELD::auto_Stat File::getattr()
{
return parent_volume->getattr( path );
}
uint64_t File::get_size()
{
if ( !latest_osd_write_response.get_new_file_size().empty() )
return latest_osd_write_response.get_new_file_size()[0].get_size_in_bytes();
else
return YIELD::File::get_size();
}
bool File::getxattr( const std::string& name, std::string& out_value )
{
return parent_volume->getxattr( path, name, out_value );
}
bool File::listxattr( std::vector<std::string>& out_names )
{
return parent_volume->listxattr( path, out_names );
}
ssize_t File::read( void* rbuf, size_t size, uint64_t offset )
{
try
{
YIELD::auto_Log log = parent_volume->get_log();
char *rbuf_start = static_cast<char*>( rbuf ), *rbuf_p = static_cast<char*>( rbuf );
#define RBUF_REMAINING ( size - static_cast<size_t>( rbuf_p - rbuf_start ) )
uint32_t stripe_size = file_credentials.get_xlocs().get_replicas()[0].get_striping_policy().get_stripe_size() * 1024;
for ( ;; )
{
uint64_t object_number = offset / stripe_size;
uint32_t object_offset = offset % stripe_size;
uint64_t object_size = RBUF_REMAINING;
if ( object_offset + object_size > stripe_size )
object_size = stripe_size - object_offset;
log->getStream( YIELD::Log::LOG_INFO ) <<
"org::xtreemfs::client::File: reading " << object_size <<
" bytes from offset " << object_offset <<
" in object number " << object_number <<
" of file " << file_credentials.get_xcap().get_file_id() <<
", file offset = " << offset <<
", remaining buffer size = " << RBUF_REMAINING <<
".";
org::xtreemfs::interfaces::ObjectData object_data;
parent_volume->get_osd_proxy_mux()->read( file_credentials, file_credentials.get_xcap().get_file_id(), object_number, 0, object_offset, static_cast<uint32_t>( object_size ), object_data );
log->getStream( YIELD::Log::LOG_INFO ) <<
"org::xtreemfs::client::File: read " << object_data.get_data()->size() <<
" bytes from file " << file_credentials.get_xcap().get_file_id() <<
" with " << object_data.get_zero_padding() << " bytes of zero padding.";
YIELD::auto_Buffer data = object_data.get_data();
if ( !data->empty() )
{
if ( data->size() <= RBUF_REMAINING )
{
memcpy_s( rbuf_p, RBUF_REMAINING, static_cast<void*>( *data ), data->size() );
rbuf_p += data->size();
offset += data->size();
}
else
{
log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received data (size=" << data->size() << ") larger than available buffer space (" << RBUF_REMAINING << ")";
YIELD::ExceptionResponse::set_errno( EIO );
return -1;
}
}
uint32_t zero_padding = object_data.get_zero_padding();
if ( zero_padding > 0 )
{
if ( zero_padding <= RBUF_REMAINING )
{
memset( rbuf_p, 0, zero_padding );
rbuf_p += zero_padding;
offset += zero_padding;
}
else
{
log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received zero_padding (" << zero_padding << ") larger than available buffer space (" << ( size - static_cast<size_t>( rbuf_p - rbuf_start ) );
YIELD::ExceptionResponse::set_errno( EIO );
return -1;
}
}
if ( data->size() < object_size || RBUF_REMAINING == 0 )
break;
}
#ifdef _DEBUG
if ( static_cast<size_t>( rbuf_p - rbuf_start ) > size ) YIELD::DebugBreak();
#endif
return static_cast<ssize_t>( rbuf_p - rbuf_start );
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return -1;
}
bool File::removexattr( const std::string& name )
{
return parent_volume->removexattr( path, name );
}
bool File::setxattr( const std::string& name, const std::string& value, int flags )
{
return parent_volume->setxattr( path, name, value, flags );
}
bool File::sync()
{
flush();
return true;
}
bool File::truncate( uint64_t new_size )
{
try
{
org::xtreemfs::interfaces::XCap truncate_xcap;
mrc_proxy->ftruncate( file_credentials.get_xcap(), truncate_xcap );
file_credentials.set_xcap( truncate_xcap );
org::xtreemfs::interfaces::OSDWriteResponse osd_write_response;
parent_volume->get_osd_proxy_mux()->truncate( file_credentials, file_credentials.get_xcap().get_file_id(), new_size, osd_write_response );
if ( osd_write_response > latest_osd_write_response )
latest_osd_write_response = osd_write_response;
if ( ( parent_volume->get_flags() & Volume::VOLUME_FLAG_CACHE_METADATA ) != Volume::VOLUME_FLAG_CACHE_METADATA )
flush();
return true;
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return false;
}
ssize_t File::write( const void* buffer, size_t buffer_len, uint64_t offset )
{
try
{
YIELD::auto_Object< YIELD::OneSignalEventQueue<> > write_response_queue( new YIELD::OneSignalEventQueue<> );
const char* wbuf_p = static_cast<const char*>( buffer );
uint64_t file_offset = offset, file_offset_max = offset + buffer_len;
uint32_t stripe_size = file_credentials.get_xlocs().get_replicas()[0].get_striping_policy().get_stripe_size() * 1024;
size_t expected_write_response_count = 0;
while ( file_offset < file_offset_max )
{
uint64_t object_number = file_offset / stripe_size;
uint32_t object_offset = file_offset % stripe_size;
uint64_t object_size = file_offset_max - file_offset;
if ( object_offset + object_size > stripe_size )
object_size = stripe_size - object_offset;
org::xtreemfs::interfaces::ObjectData object_data( 0, false, 0, new YIELD::StringLiteralBuffer( wbuf_p, static_cast<uint32_t>( object_size ) ) );
org::xtreemfs::interfaces::OSDInterface::writeRequest* write_request = new org::xtreemfs::interfaces::OSDInterface::writeRequest( file_credentials, file_credentials.get_xcap().get_file_id(), object_number, 0, object_offset, 0, object_data );
write_request->set_response_target( write_response_queue->incRef() );
parent_volume->get_osd_proxy_mux()->send( *write_request );
expected_write_response_count++;
wbuf_p += object_size;
file_offset += object_size;
}
for ( size_t write_response_i = 0; write_response_i < expected_write_response_count; write_response_i++ )
{
org::xtreemfs::interfaces::OSDInterface::writeResponse& write_response = write_response_queue->dequeue_typed<org::xtreemfs::interfaces::OSDInterface::writeResponse>();
if ( write_response.get_osd_write_response() > latest_osd_write_response )
latest_osd_write_response = write_response.get_osd_write_response();
YIELD::Object::decRef( write_response );
}
if ( ( parent_volume->get_flags() & Volume::VOLUME_FLAG_CACHE_METADATA ) != Volume::VOLUME_FLAG_CACHE_METADATA )
flush();
return static_cast<ssize_t>( file_offset - offset );
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return -1;
}
ssize_t File::writev( const struct iovec* buffers, uint32_t buffers_count, uint64_t offset )
{
if ( buffers_count == 1 )
return write( buffers[0].iov_base, buffers[0].iov_len, offset );
else
{
#ifdef _WIN32
::SetLastError( ERROR_NOT_SUPPORTED );
#else
errno = ENOTSUP;
#endif
return -1;
}
}
<commit_msg>client: print more info on read errors<commit_after>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).
#include "org/xtreemfs/client/file.h"
#include "org/xtreemfs/client/mrc_proxy.h"
#include "org/xtreemfs/client/osd_proxy.h"
#include "org/xtreemfs/client/volume.h"
#include "multi_response_target.h"
using namespace org::xtreemfs::client;
#include <errno.h>
#ifdef _WIN32
#include <windows.h>
#pragma warning( push )
#pragma warning( disable: 4100 )
#else
#include <errno.h>
#endif
#include "org/xtreemfs/interfaces/osd_interface.h"
#ifdef _WIN32
#pragma warning( pop )
#endif
File::File( YIELD::auto_Object<Volume> parent_volume, YIELD::auto_Object<MRCProxy> mrc_proxy, const YIELD::Path& path, const org::xtreemfs::interfaces::FileCredentials& file_credentials )
: parent_volume( parent_volume ), mrc_proxy( mrc_proxy ), path( path ), file_credentials( file_credentials )
{ }
File::~File()
{
flush();
}
bool File::datasync()
{
flush();
return true;
}
bool File::close()
{
flush();
return true;
}
bool File::flush()
{
try
{
if ( !latest_osd_write_response.get_new_file_size().empty() )
{
mrc_proxy->xtreemfs_update_file_size( file_credentials.get_xcap(), latest_osd_write_response );
latest_osd_write_response.set_new_file_size( org::xtreemfs::interfaces::NewFileSize() );
}
return true;
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return false;
}
YIELD::auto_Stat File::getattr()
{
return parent_volume->getattr( path );
}
uint64_t File::get_size()
{
if ( !latest_osd_write_response.get_new_file_size().empty() )
return latest_osd_write_response.get_new_file_size()[0].get_size_in_bytes();
else
return YIELD::File::get_size();
}
bool File::getxattr( const std::string& name, std::string& out_value )
{
return parent_volume->getxattr( path, name, out_value );
}
bool File::listxattr( std::vector<std::string>& out_names )
{
return parent_volume->listxattr( path, out_names );
}
ssize_t File::read( void* rbuf, size_t size, uint64_t offset )
{
try
{
YIELD::auto_Log log = parent_volume->get_log();
char *rbuf_start = static_cast<char*>( rbuf ), *rbuf_p = static_cast<char*>( rbuf );
#define RBUF_REMAINING ( size - static_cast<size_t>( rbuf_p - rbuf_start ) )
uint32_t stripe_size = file_credentials.get_xlocs().get_replicas()[0].get_striping_policy().get_stripe_size() * 1024;
for ( ;; )
{
uint64_t object_number = offset / stripe_size;
uint32_t object_offset = offset % stripe_size;
uint64_t object_size = RBUF_REMAINING;
if ( object_offset + object_size > stripe_size )
object_size = stripe_size - object_offset;
log->getStream( YIELD::Log::LOG_INFO ) <<
"org::xtreemfs::client::File: reading " << object_size <<
" bytes from offset " << object_offset <<
" in object number " << object_number <<
" of file " << file_credentials.get_xcap().get_file_id() <<
", file offset = " << offset <<
", remaining buffer size = " << RBUF_REMAINING <<
".";
org::xtreemfs::interfaces::ObjectData object_data;
parent_volume->get_osd_proxy_mux()->read( file_credentials, file_credentials.get_xcap().get_file_id(), object_number, 0, object_offset, static_cast<uint32_t>( object_size ), object_data );
YIELD::auto_Buffer data = object_data.get_data();
uint32_t zero_padding = object_data.get_zero_padding();
log->getStream( YIELD::Log::LOG_INFO ) <<
"org::xtreemfs::client::File: read " << data->size() <<
" bytes from file " << file_credentials.get_xcap().get_file_id() <<
" with " << zero_padding << " bytes of zero padding.";
if ( !data->empty() )
{
if ( data->size() <= RBUF_REMAINING )
{
memcpy_s( rbuf_p, RBUF_REMAINING, static_cast<void*>( *data ), data->size() );
rbuf_p += data->size();
offset += data->size();
}
else
{
log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received data (data size=" << data->size() << ", zero_padding=" << zero_padding << ") larger than available buffer space (" << RBUF_REMAINING << ")";
YIELD::ExceptionResponse::set_errno( EIO );
return -1;
}
}
if ( zero_padding > 0 )
{
if ( zero_padding <= RBUF_REMAINING )
{
memset( rbuf_p, 0, zero_padding );
rbuf_p += zero_padding;
offset += zero_padding;
}
else
{
log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received zero_padding (data size=" << data->size() << ", zero_padding=" << zero_padding << ") larger than available buffer space (" << RBUF_REMAINING << ")";
YIELD::ExceptionResponse::set_errno( EIO );
return -1;
}
}
if ( data->size() < object_size || RBUF_REMAINING == 0 )
break;
}
#ifdef _DEBUG
if ( static_cast<size_t>( rbuf_p - rbuf_start ) > size ) YIELD::DebugBreak();
#endif
return static_cast<ssize_t>( rbuf_p - rbuf_start );
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return -1;
}
bool File::removexattr( const std::string& name )
{
return parent_volume->removexattr( path, name );
}
bool File::setxattr( const std::string& name, const std::string& value, int flags )
{
return parent_volume->setxattr( path, name, value, flags );
}
bool File::sync()
{
flush();
return true;
}
bool File::truncate( uint64_t new_size )
{
try
{
org::xtreemfs::interfaces::XCap truncate_xcap;
mrc_proxy->ftruncate( file_credentials.get_xcap(), truncate_xcap );
file_credentials.set_xcap( truncate_xcap );
org::xtreemfs::interfaces::OSDWriteResponse osd_write_response;
parent_volume->get_osd_proxy_mux()->truncate( file_credentials, file_credentials.get_xcap().get_file_id(), new_size, osd_write_response );
if ( osd_write_response > latest_osd_write_response )
latest_osd_write_response = osd_write_response;
if ( ( parent_volume->get_flags() & Volume::VOLUME_FLAG_CACHE_METADATA ) != Volume::VOLUME_FLAG_CACHE_METADATA )
flush();
return true;
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return false;
}
ssize_t File::write( const void* buffer, size_t buffer_len, uint64_t offset )
{
try
{
YIELD::auto_Object< YIELD::OneSignalEventQueue<> > write_response_queue( new YIELD::OneSignalEventQueue<> );
const char* wbuf_p = static_cast<const char*>( buffer );
uint64_t file_offset = offset, file_offset_max = offset + buffer_len;
uint32_t stripe_size = file_credentials.get_xlocs().get_replicas()[0].get_striping_policy().get_stripe_size() * 1024;
size_t expected_write_response_count = 0;
while ( file_offset < file_offset_max )
{
uint64_t object_number = file_offset / stripe_size;
uint32_t object_offset = file_offset % stripe_size;
uint64_t object_size = file_offset_max - file_offset;
if ( object_offset + object_size > stripe_size )
object_size = stripe_size - object_offset;
org::xtreemfs::interfaces::ObjectData object_data( 0, false, 0, new YIELD::StringLiteralBuffer( wbuf_p, static_cast<uint32_t>( object_size ) ) );
org::xtreemfs::interfaces::OSDInterface::writeRequest* write_request = new org::xtreemfs::interfaces::OSDInterface::writeRequest( file_credentials, file_credentials.get_xcap().get_file_id(), object_number, 0, object_offset, 0, object_data );
write_request->set_response_target( write_response_queue->incRef() );
parent_volume->get_osd_proxy_mux()->send( *write_request );
expected_write_response_count++;
wbuf_p += object_size;
file_offset += object_size;
}
for ( size_t write_response_i = 0; write_response_i < expected_write_response_count; write_response_i++ )
{
org::xtreemfs::interfaces::OSDInterface::writeResponse& write_response = write_response_queue->dequeue_typed<org::xtreemfs::interfaces::OSDInterface::writeResponse>();
if ( write_response.get_osd_write_response() > latest_osd_write_response )
latest_osd_write_response = write_response.get_osd_write_response();
YIELD::Object::decRef( write_response );
}
if ( ( parent_volume->get_flags() & Volume::VOLUME_FLAG_CACHE_METADATA ) != Volume::VOLUME_FLAG_CACHE_METADATA )
flush();
return static_cast<ssize_t>( file_offset - offset );
}
catch ( ProxyExceptionResponse& proxy_exception_response )
{
YIELD::Exception::set_errno( proxy_exception_response.get_platform_error_code() );
}
catch ( std::exception& )
{
YIELD::Exception::set_errno( EIO );
}
return -1;
}
ssize_t File::writev( const struct iovec* buffers, uint32_t buffers_count, uint64_t offset )
{
if ( buffers_count == 1 )
return write( buffers[0].iov_base, buffers[0].iov_len, offset );
else
{
#ifdef _WIN32
::SetLastError( ERROR_NOT_SUPPORTED );
#else
errno = ENOTSUP;
#endif
return -1;
}
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "ltac/Operator.hpp"
using namespace eddic;
using eddic::ltac::Operator;
bool ltac::erase_result(ltac::Operator op){
return op == Operator::MOV
|| op == Operator::FMOV
|| op == Operator::MUL3
|| op == Operator::XOR
|| op == Operator::OR
|| (op >= Operator::LEA && op <= Operator::CMOVLE);
}
bool ltac::erase_result_complete(ltac::Operator op){
return op == Operator::MOV
|| op == Operator::FMOV
|| op == Operator::LEA
|| op == Operator::MUL3;
}
<commit_msg>DIV does not erase the result<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "ltac/Operator.hpp"
using namespace eddic;
using eddic::ltac::Operator;
bool ltac::erase_result(ltac::Operator op){
return op != Operator::DIV
&& (
op == Operator::MOV
|| op == Operator::FMOV
|| op == Operator::MUL3
|| op == Operator::XOR
|| op == Operator::OR
|| (op >= Operator::LEA && op <= Operator::CMOVLE)
);
}
bool ltac::erase_result_complete(ltac::Operator op){
return op == Operator::MOV
|| op == Operator::FMOV
|| op == Operator::LEA
|| op == Operator::MUL3;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.