text
stringlengths 8
6.88M
|
|---|
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Zhi Yan.
* 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 Zhi Yan 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 "map_merging.hpp"
MapMerging::MapMerging() {
ros::NodeHandle private_nh("~");
private_nh.param<double>("merging_rate", merging_rate_, 10.0);
private_nh.param<int>("max_number_robots", max_number_robots_, 100);
private_nh.param<double>("max_comm_distance", max_comm_distance_, 10.0);
private_nh.param<std::string>("pose_topic", pose_topic_, "pose");
private_nh.param<std::string>("map_topic", map_topic_, "map");
private_nh.param<std::string>("merged_map_topic", merged_map_topic_, "merged_map");
private_nh.param<double>("init_pose_x", init_x_, 0);
private_nh.param<double>("init_pose_y", init_y_, 0);
private_nh.param<double>("init_pose_z", init_z_, 0);
private_nh.param<double>("init_pose_yaw", init_yaw_, 0);
private_nh.param<std::string>("world_frame", world_frame_, "world");
private_nh.param<std::string>("robot_base_frame", robot_base_frame_, "base_link");
geometry_msgs::Pose init_pose;
init_pose.position.x = init_x_;
init_pose.position.y = init_y_;
init_pose.position.z = init_z_;
tf::Quaternion init_pose_quaternion;
init_pose_quaternion.setEuler(init_yaw_, 0, 0);
init_pose.orientation.x = init_pose_quaternion.x();
init_pose.orientation.y = init_pose_quaternion.y();
init_pose.orientation.z = init_pose_quaternion.z();
init_pose.orientation.w = init_pose_quaternion.w();
/* publisher params */
map_has_been_merged_ = new bool[max_number_robots_]();
merged_map_publisher_ = private_nh.advertise<nav_msgs::OccupancyGrid>(merged_map_topic_, 1, true);
/* get robot's name */
// my_name_ = ros::this_node::getNamespace(); // Get the robot's name.
my_name_ = robot_base_frame_;
// my_name_.erase(0, 1); // [ROS_BUG #3671] Remove the first slash in front of the name.
curr_pose_publisher_ = node_.advertise<geometry_msgs::PoseStamped>( pose_topic_, 1, true);
my_id_ = tm_id_ = UNKNOWN;
}
MapMerging::~MapMerging() {
delete[] map_has_been_merged_;
}
/*
* topicSubscribing()
*/
void MapMerging::topicSubscribing() {
ros::master::V_TopicInfo topic_infos;
ros::master::getTopics(topic_infos);
for(ros::master::V_TopicInfo::const_iterator it_topic = topic_infos.begin(); it_topic != topic_infos.end(); ++it_topic) {
const ros::master::TopicInfo &published_topic = *it_topic;
/* robot pose subscribing */
if(published_topic.name.find(pose_topic_) != std::string::npos && !poseFound(published_topic.name, poses_)) {
ROS_INFO("[%s]:Subscribe to POSE topic: %s.", (ros::this_node::getName()).c_str(), published_topic.name.c_str());
poses_.push_back(Pose(published_topic.name, false));
pose_subsribers_.push_back(node_.subscribe<geometry_msgs::PoseStamped>(published_topic.name, 1, boost::bind(&MapMerging::poseCallback, this, _1, poses_.size()-1)));
/* get robot's ID */
ROS_WARN_STREAM("my_name_:"<<my_name_<<" published_topic:"<<published_topic.name);
if(my_name_.size() > 0 && published_topic.name.compare(1, my_name_.size(), my_name_) == 0) {
my_id_ = poses_.size()-1;
ROS_INFO("[%s]:My name is %s, ID = %d.", (ros::this_node::getName()).c_str(), my_name_.c_str(), my_id_);
}
}
}
if(my_id_ == UNKNOWN) {
ROS_WARN("[%s]:Can not get robot's pose.", (ros::this_node::getName()).c_str());
}
}
/*
* handShaking(): handshaking if robots are within the communication range.
*/
void MapMerging::handShaking() {
if(my_id_ == UNKNOWN || tm_id_ != UNKNOWN)
return;
geometry_msgs::Pose my_pose, tm_pose;
if(poses_[my_id_].received) {
my_pose.position.x = poses_[my_id_].data.pose.position.x;
my_pose.position.y = poses_[my_id_].data.pose.position.y;
my_pose.position.z = poses_[my_id_].data.pose.position.z;
poses_[my_id_].received = false;
//std::cout << "[" << ros::this_node::getName() << "] " << poses_[my_id_].data.header.frame_id << " x = " << my_pose.position.x << " y = " << my_pose.position.y << std::endl;
tm_id_list_.clear();
for(int i = 0; i < (int)poses_.size(); i++) {
if(i != my_id_ && !map_has_been_merged_[i]) {
tm_name_ = robotNameParsing(poses_[i].name);
if(poses_[i].received) {
tm_pose.position.x = poses_[i].data.pose.position.x;
tm_pose.position.y = poses_[i].data.pose.position.y;
tm_pose.position.z = poses_[i].data.pose.position.z;
poses_[i].received = false;
if(distBetween(tm_pose.position, my_pose.position) < max_comm_distance_) {
ROS_DEBUG("[%s]:Handshake with %s.", (ros::this_node::getName()).c_str(), tm_name_.c_str());
tm_id_ = i;
tm_id_list_.push_back(tm_id_);
}
}
}
}
}
if(tm_id_ == UNKNOWN) {
// do something here ...
}
}
/*
* mapMerging()
*/
void MapMerging::mapMerging() {
if(my_id_ == UNKNOWN || tm_id_ == UNKNOWN)
return;
std::string map_topic_name;
for(int i = 0; i < (int)poses_.size(); i++) {
map_topic_name = robotNameParsing(poses_[i].name)+"/"+map_topic_;
if(!mapFound(map_topic_name, maps_)) {
maps_.push_back(Map(map_topic_name, false));
map_subsribers_.push_back(node_.subscribe<nav_msgs::OccupancyGrid>(map_topic_name, 1, boost::bind(&MapMerging::mapCallback, this, _1, maps_.size()-1)));
ROS_INFO("[%s]:Subscribe to MAP topic: %s.", (ros::this_node::getName()).c_str(), map_topic_name.c_str());
}
}
merged_map_ = maps_[my_id_].data;
bool map_merging_end = false;
for(int t = 0; t < tm_id_list_.size(); t++){
tm_id_ = tm_id_list_[t];
tm_name_ = robotNameParsing(poses_[tm_id_].name);
if(maps_[my_id_].received) {
if(maps_[tm_id_].received) {
ROS_WARN("[%s]:Exchange map with %s.", (ros::this_node::getName()).c_str(), tm_name_.c_str());
//std::cout << "[" << ros::this_node::getName() << "] deltaX = " << delta.position.x << " deltaY = " << delta.position.y << std::endl;
//if(!map_has_been_merged_[my_id_]) {
// merged_map_ = maps_[my_id_].data;
// map_has_been_merged_[my_id_] = true;
//}
nav_msgs::OccupancyGrid temp_output;
geometry_msgs::Pose my_init_pose, tm_init_pose;
if(!getInitPose(my_name_, my_init_pose)){
ROS_ERROR_STREAM("Could not get init pose for "<<my_name_);
}
if(!getInitPose(tm_name_, tm_init_pose)){
ROS_ERROR_STREAM("Could not get init pose for "<<tm_name_);
}
map_expand(merged_map_, maps_[tm_id_].data, temp_output,
my_init_pose, tm_init_pose);
maps_[my_id_].data.info = temp_output.info;
maps_[my_id_].data.header = temp_output.header;
maps_[my_id_].data.data = temp_output.data;
merged_map_ = maps_[my_id_].data;
//GreedyMerging(round(delta.position.x), round(delta.position.y), tm_id_);
maps_[tm_id_].received = false;
}
}
}
maps_[my_id_].received = false;
map_merging_end = true;
if(map_merging_end) {
ROS_WARN("[%s]:Map has been merged with %s.", (ros::this_node::getName()).c_str(), tm_name_.c_str());
map_has_been_merged_[tm_id_] = true;
tm_id_ = UNKNOWN;
// It has coordinated with all that can be coordinated, so reset.
bool reset_and_publish = true;
// for(int i = 0; i < (int)poses_.size(); i++) {
// if(!map_has_been_merged_[i]) {
// reset_and_publish = false;
// break;
// }
// }
if(reset_and_publish) {
for(int i = 0; i < (int)poses_.size(); i++)
map_has_been_merged_[i] = false;
merged_map_publisher_.publish(maps_[my_id_].data);
}
}
}
/*********************
* callback function *
*********************/
void MapMerging::poseCallback(const geometry_msgs::PoseStamped::ConstPtr &msg, int id) {
ROS_DEBUG("poseCallback");
//boost::mutex::scoped_lock pose_lock (pose_mutex_);
poses_[id].received = true;
poses_[id].data = *msg;
}
void MapMerging::mapCallback(const nav_msgs::OccupancyGrid::ConstPtr &msg, int id) {
ROS_DEBUG("mapCallback");
//boost::mutex::scoped_lock map_lock (map_mutex_);
maps_[id].received = true;
maps_[id].data = *msg;
}
/*********************
* private function *
*********************/
bool MapMerging::poseFound(std::string name, std::vector<Pose> &poses) {
for(std::vector<Pose>::iterator it_pose = poses.begin(); it_pose != poses.end(); ++it_pose) {
if((*it_pose).name.compare(name) == 0)
return true;
}
return false;
}
bool MapMerging::mapFound(std::string name, std::vector<Map> &maps) {
for(std::vector<Map>::iterator it_map = maps.begin(); it_map != maps.end(); ++it_map) {
if((*it_map).name.compare(name) == 0)
return true;
}
return false;
}
std::string MapMerging::robotNameParsing(std::string s) {
return s.erase(s.find('/', 1), s.size());
}
/*
* Get robot's initial position
* TODO: get orientation
*/
bool MapMerging::getInitPose(std::string name, geometry_msgs::Pose &pose) {
if(ros::param::get("/"+name+"/map_merge/init_pose_x", pose.position.x) &&
ros::param::get("/"+name+"/map_merge/init_pose_y", pose.position.y) &&
ros::param::get("/"+name+"/map_merge/init_pose_z", pose.position.z)) {
return true;
}
return false;
}
/*
* Get the relative position of two robots
* TODO: get orientation
*/
bool MapMerging::getRelativePose(std::string n, std::string m, geometry_msgs::Pose &delta, double resolution) {
geometry_msgs::Pose p, q;
if(ros::param::get(n+"/map_merge/init_pose_x", p.position.x) &&
ros::param::get(n+"/map_merge/init_pose_y", p.position.y) &&
ros::param::get(n+"/map_merge/init_pose_z", p.position.z) &&
ros::param::get(m+"/map_merge/init_pose_x", q.position.x) &&
ros::param::get(m+"/map_merge/init_pose_y", q.position.y) &&
ros::param::get(m+"/map_merge/init_pose_z", q.position.z)) {
delta.position.x = round((p.position.x - q.position.x) / resolution);
delta.position.y = round((p.position.y - q.position.y) / resolution);
delta.position.z = round((p.position.z - q.position.z) / resolution);
return true;
}
return false;
}
double MapMerging::distBetween(geometry_msgs::Point &p, geometry_msgs::Point &q) {
// Euclidean distance
return sqrt((p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y)+(p.z-q.z)*(p.z-q.z));
}
/*
* Algorithm 1 - Greedy Merging
* yz14simpar
*/
void MapMerging::greedyMerging(int delta_x, int delta_y, int map_id) {
for(int i = 0; i < (int)merged_map_.info.width; i++) {
for(int j = 0; j < (int)merged_map_.info.height; j++) {
if(i+delta_x >= 0 && i+delta_x < (int)maps_[map_id].data.info.width &&
j+delta_y >= 0 && j+delta_y < (int)maps_[map_id].data.info.height) {
if((int)merged_map_.data[i+j*(int)merged_map_.info.width] == UNKNOWN)
merged_map_.data[i+j*(int)merged_map_.info.width] = maps_[map_id].data.data[i+delta_x+(j+delta_y)*(int)maps_[map_id].data.info.width];
}
}
}
}
/*
* input_pose and target_pose, these poses need to be in the same frame, no matter what frame. Now only supports same orientation
* output map shares the same frame as the input map
* TODO: add support for maps with orientation difference
*/
void MapMerging::map_expand(nav_msgs::OccupancyGrid& input, nav_msgs::OccupancyGrid& target, nav_msgs::OccupancyGrid & output,
geometry_msgs::Pose input_pose, geometry_msgs::Pose target_pose){
output.info = input.info;
output.header = input.header;
output.data = input.data;
double from_input_to_target_x = target_pose.position.x - input_pose.position.x;
double from_input_to_target_y = target_pose.position.y - input_pose.position.y;
int from_input_to_target_x_cell = from_input_to_target_x / input.info.resolution;
int from_input_to_target_y_cell = from_input_to_target_y / input.info.resolution;
//first expand the input map, resize to new size, that will contain both the input and the target map
double input_width = input.info.width * input.info.resolution;
double input_height = input.info.height * input.info.resolution;
double target_width = target.info.width * target.info.resolution;
double target_height = target.info.height * target.info.resolution;
std::vector<std::pair<double, double>> input_corners;
std::vector<std::pair<double, double>> target_corners;
double input_origin_x = input.info.origin.position.x;
double input_origin_y = input.info.origin.position.y;
double target_origin_x = target.info.origin.position.x;
double target_origin_y = target.info.origin.position.y;
input_corners = getMapCorners(input_origin_x, input_origin_y, input_width, input_height);
//target_corners in the input map frame
target_corners = getMapCorners(target_origin_x + from_input_to_target_x, target_origin_y + from_input_to_target_y, target_width, target_height);
bool is_input_origin_x_min = false;
bool is_input_origin_y_min = false;
if(input_origin_x > 0 && input_origin_y > 0){
is_input_origin_x_min = false;
is_input_origin_y_min = false;
}else if(input_origin_x > 0 && input_origin_y < 0){
is_input_origin_x_min = false;
is_input_origin_y_min = true;
}else if(input_origin_x < 0 && input_origin_y > 0){
is_input_origin_x_min = true;
is_input_origin_y_min = false;
}else if(input_origin_x < 0 && input_origin_y < 0){
is_input_origin_x_min = true;
is_input_origin_y_min = true;
}
double output_origin_x = 0.0;
double output_origin_y = 0.0;
double x_max = 0.0;
double x_min = 0.0;
double y_max = 0.0;
double y_min = 0.0;
double x_extre = 0.0;
double y_extre = 0.0;
if(is_input_origin_x_min){
x_extre = std::numeric_limits<double>::max();
}else{
x_extre = std::numeric_limits<double>::min();
}
if(is_input_origin_y_min){
y_extre = std::numeric_limits<double>::max();
}else{
y_extre = std::numeric_limits<double>::min();
}
x_max = std::numeric_limits<double>::min();
x_min = std::numeric_limits<double>::max();
y_max = std::numeric_limits<double>::min();
y_min = std::numeric_limits<double>::max();
for(auto i = input_corners.begin(); i != input_corners.end(); i++){
if(i->first >= x_max){
x_max = i->first;
}
if(i->first < x_min){
x_min = i->first;
}
if(i->second >= y_max){
y_max = i->second;
}
if(i->second < y_min){
y_min = i->second;
}
if(is_input_origin_x_min){
if(i->first < x_extre){
x_extre = i->first;
}
}else{
if(i->first > x_extre){
x_extre = i->first;
}
}
if(is_input_origin_y_min){
if(i->second < y_extre){
y_extre = i->second;
}
}else{
if(i->second > y_extre){
y_extre = i->second;
}
}
}
for(auto i = target_corners.begin(); i != target_corners.end(); i++){
if(i->first >= x_max){
x_max = i->first;
}
if(i->first < x_min){
x_min = i->first;
}
if(i->second >= y_max){
y_max = i->second;
}
if(i->second < y_min){
y_min = i->second;
}
if(is_input_origin_x_min){
if(i->first < x_extre){
x_extre = i->first;
}
}else{
if(i->first > x_extre){
x_extre = i->first;
}
}
if(is_input_origin_y_min){
if(i->second < y_extre){
y_extre = i->second;
}
}else{
if(i->second > y_extre){
y_extre = i->second;
}
}
}
output_origin_x = x_extre;
output_origin_y = y_extre;
int output_width_cell = (int)((x_max - x_min) / input.info.resolution);
int output_height_cell = (int)((y_max - y_min) / input.info.resolution);
output.info.width = output_width_cell;
output.info.height = output_height_cell;
output.info.origin.position.x = output_origin_x;
output.info.origin.position.y = output_origin_y;
//second fill the region of the original input map region
output.data.clear();
output.data.resize(output_width_cell * output_height_cell, -1);
int input_origin_to_output_origin_x_cell = (int)((output_origin_x - input.info.origin.position.x) / input.info.resolution); //output_origin_x_cell - input_origin_x_cell
int input_origin_to_output_origin_y_cell = (int)((output_origin_y - input.info.origin.position.y) / input.info.resolution); //output_origin_y_cell - input_origin_y_cell
for(int x = 0; x < input.info.width; x++){
for(int y = 0; y < input.info.height; y++){
int new_x = x - input_origin_to_output_origin_x_cell;
int new_y = y - input_origin_to_output_origin_y_cell;
int input_value = input.data[y*input.info.width + x];
output.data[new_y*output_width_cell + new_x] = input_value;
}
}
//last, fill or merge the region belonging to the target map
double target_origin_x_in_input_frame = (from_input_to_target_x + target.info.origin.position.x);
double target_origin_y_in_input_frame = (from_input_to_target_y + target.info.origin.position.y);
int target_origin_to_output_origin_x_cell_in_input_frame = (output_origin_x - target_origin_x_in_input_frame) / input.info.resolution; //output_origin_x_cell - input_origin_x_cell
int target_origin_to_output_origin_y_cell_in_input_frame = (output_origin_y - target_origin_y_in_input_frame) / input.info.resolution; //output_origin_y_cell - input_origin_y_cell
for(int x = 0; x < target.info.width; x++){
for(int y = 0; y < target.info.height; y++){
int new_x = x - target_origin_to_output_origin_x_cell_in_input_frame;
int new_y = y - target_origin_to_output_origin_y_cell_in_input_frame;
int target_value = target.data[y*target.info.width + x];
//could add more checking to compare the value from both input map and from target map
int previous_value = output.data[new_y*output_width_cell + new_x];
if(previous_value < OBSTACLE_COST){
if(target_value > OBSTACLE_COST){
output.data[new_y*output_width_cell + new_x] = target_value;
}else if(target_value != -1){
if(previous_value == -1){
output.data[new_y*output_width_cell + new_x] = target_value;
}else{
if(target_value < previous_value){
output.data[new_y*output_width_cell + new_x] = target_value;
}
}
}
}
}
}
}
std::vector<std::pair<double, double>> MapMerging::getMapCorners(double input_origin_x, double input_origin_y, double input_width, double input_height){
std::vector<std::pair<double, double>> input_corners;
input_corners.push_back(std::make_pair(input_origin_x, input_origin_y));
if(input_origin_x > 0 && input_origin_y > 0){
input_corners.push_back(std::make_pair(input_origin_x - input_width, input_origin_y));
input_corners.push_back(std::make_pair(input_origin_x - input_width, input_origin_y - input_height));
input_corners.push_back(std::make_pair(input_origin_x, input_origin_y - input_height));
}else if(input_origin_x > 0 && input_origin_y < 0){
input_corners.push_back(std::make_pair(input_origin_x - input_width, input_origin_y));
input_corners.push_back(std::make_pair(input_origin_x - input_width, input_origin_y + input_height));
input_corners.push_back(std::make_pair(input_origin_x, input_origin_y + input_height));
}else if(input_origin_x < 0 && input_origin_y > 0){
input_corners.push_back(std::make_pair(input_origin_x + input_width, input_origin_y));
input_corners.push_back(std::make_pair(input_origin_x + input_width, input_origin_y - input_height));
input_corners.push_back(std::make_pair(input_origin_x, input_origin_y - input_height));
}else if(input_origin_x < 0 && input_origin_y < 0){
input_corners.push_back(std::make_pair(input_origin_x + input_width, input_origin_y));
input_corners.push_back(std::make_pair(input_origin_x + input_width, input_origin_y + input_height));
input_corners.push_back(std::make_pair(input_origin_x, input_origin_y + input_height));
}
return input_corners;
}
void MapMerging::posePublishing(){
tf::TransformListener listener(node_);
geometry_msgs::PoseStamped curr_pose;
tf::StampedTransform transform;
try
{
listener.waitForTransform(world_frame_, robot_base_frame_, ros::Time(0), ros::Duration(30.0));
listener.lookupTransform(world_frame_, robot_base_frame_, ros::Time(0), transform);
}
catch (tf::TransformException ex)
{
ROS_ERROR("TF %s - %s: %s", world_frame_.c_str(), robot_base_frame_.c_str(), ex.what());
}
curr_pose.pose.position.x = transform.getOrigin().getX();
curr_pose.pose.position.y = transform.getOrigin().getY();
curr_pose.pose.position.z = transform.getOrigin().getZ();
curr_pose.pose.orientation.x = transform.getRotation().getX();
curr_pose.pose.orientation.y = transform.getRotation().getY();
curr_pose.pose.orientation.z = transform.getRotation().getZ();
curr_pose_publisher_.publish(curr_pose);
ros::spinOnce();
}
/*
* execute()
*/
void MapMerging::execute() {
ros::Rate r(merging_rate_);
while(node_.ok()) {
topicSubscribing();
handShaking();
mapMerging();
posePublishing();
r.sleep();
}
}
/*
* spin()
*/
void MapMerging::spin() {
ros::spinOnce();
boost::thread t(boost::bind(&MapMerging::execute, this));
ros::spin();
t.join();
}
int main(int argc, char **argv) {
ros::init(argc, argv, "map_merging");
MapMerging map_merging;
map_merging.spin();
return 0;
}
|
//
// Created by griha on 10.12.17.
//
#include <cassert>
#include <griha/tools/guard.hpp>
#include <misc/logger.hpp>
#include <misc/io_manip.hpp>
#include "crypto_context_impl.hpp"
#include "crypto/hsm_lib/crypto_context.hpp"
#include "misc/common.hpp"
namespace griha { namespace hsm {
using griha::tools::guard;
using tools::get_user_key;
using tools::set_param;
CryptoContext::~CryptoContext() {
if (h_key_exchange)
safed_deleter(CryptDestroyKey)(h_key_exchange);
if (h_key_signature)
safed_deleter(CryptDestroyKey)(h_key_signature);
if (h_key_trans)
safed_deleter(CryptDestroyKey)(h_key_trans);
if (h_prov)
safed_deleter(std::bind(&CryptReleaseContext, std::placeholders::_1, 0))(h_prov);
if (h_prov_trans)
safed_deleter(std::bind(&CryptReleaseContext, std::placeholders::_1, 0))(h_prov_trans);
}
bool CryptoContext::initialize(const wchar_t *prov_name, DWORD prov_type,
const wchar_t *cont_name, const wchar_t *trans_cont_name,
bool silent, bool trans_silent) {
assert(cont_name != nullptr);
if (!CryptAcquireContext(&h_prov, cont_name, prov_name, prov_type, silent ? CRYPT_SILENT : 0)) {
LOG_ERROR << "CryptoContext::initialize: error when crypto context has been acquired " << last_error;
return false;
}
LOG_DEBUG << "CryptoContext::initialize: user exchange key request";
bool ret = get_user_key(h_prov, false, h_key_exchange);
LOG_DEBUG << "CryptoContext::initialize: user signature key request";
ret = get_user_key(h_prov, true, h_key_signature) || ret;
if (!trans_cont_name)
return ret;
if (!CryptAcquireContext(&h_prov_trans, trans_cont_name, prov_name, prov_type, trans_silent ? CRYPT_SILENT : 0)) {
LOG_ERROR << "CryptoContext::initialize: error when crypto context of the transport container has been acquired "
<< last_error;
return false;
}
LOG_DEBUG << "CryptoContext::initialize: transport key request";
return get_user_key(h_prov_trans, false, h_key_trans) || get_user_key(h_prov_trans, true, h_key_trans);
}
ICryptoContext* __cdecl CreateCryptoContext(const wchar_t *prov_name, DWORD prov_type,
const wchar_t *cont_name, const char *password,
const wchar_t *trans_cont_name, const char *trans_password,
IError *error_sink) {
if (cont_name == nullptr) {
LOG_ERROR << "CreateCryptoContext: container name should be set";
set_error(error_sink, ErrorCode::IncorrectArgument, "CreateCryptoContext: container name should be set");
return nullptr;
}
try {
auto ret = guard(new CryptoContext);
if (!ret->initialize(prov_name, prov_type, cont_name, trans_cont_name, password != nullptr,
trans_password != nullptr)) {
set_error(error_sink, ErrorCode::CryptoError,
"CreateCryptoContext: crypto context initialization has been failed", GetLastError());
return nullptr;
}
if (password != nullptr &&
(!set_param(ret->h_prov, ProvParam::KeyExchangePin, password) &&
!set_param(ret->h_prov, ProvParam::SignaturePin, password))) {
set_error(error_sink, ErrorCode::IncorrectArgument,
"CreateCryptoContext: error of setting user key password", GetLastError());
return nullptr;
}
if (ret->h_key_trans && trans_password != nullptr &&
!set_param(ret->h_prov_trans, ProvParam::KeyExchangePin, trans_password)) {
set_error(error_sink, ErrorCode::IncorrectArgument,
"CreateCryptoContext: error of setting transport key password", GetLastError());
return nullptr;
}
LOG_INFO << "CreateCryptoContext: crypto context has successfully been created";
return ret.release();
} catch (std::exception &e) {
set_error(error_sink, ErrorCode::InternalError, "CreateCryptoContext: crypto context creating has been failed");
LOG_CRITICAL << "CreateCryptoContext: crypto context creating has been failed with error: " << e.what();
} catch (...) {
set_error(error_sink, ErrorCode::InternalError, "CreateCryptoContext: crypto context creating has been failed");
LOG_CRITICAL << "CreateCryptoContext: crypto context creating has been failed with unknown error";
}
return nullptr;
}
}} // namespace griha::hsm
|
#ifndef PACKETS_ROOMS_RESP
#define PACKETS_ROOMS_RESP
#include <cstdint>
#include "Packets/PacketBaseMessage.h"
#pragma pack(push, 1)
#include "Constructors/sg_constructor.h"
struct BM_SC_GET_ROOMLIST_RESP : public TS_MESSAGE_WNA
{
uint16_t roomcount;
uint16_t uk1;
uint16_t uk2;
sg_constructor::rooms_packet rooms[0];
//std::vector<sg_constructor::rooms_packet> rooms;
static const uint16_t packetID = 2304;
};
struct BM_SC_CREATE_ROOM_RESP : public TS_MESSAGE
{
char successmessage[8];
uint64_t uk1;
uint64_t uk2;
uint32_t roomid;
char relayip[20]; //Yes, this is 20 for whatever reason
uint16_t relayport;
uint8_t team; // 1 = red | 2 = Blue
uint8_t uk3;
uint8_t uk4;
uint32_t udpport; //default 5000
static const uint16_t packetID = 2174;
};
struct BM_SC_CREATE_FAILED_RESP : public TS_MESSAGE
{
char errormessage[16];
static const uint16_t packetID = 2174;
};
struct BM_SC_CREATE_ROOM_ALREADYJOINED_RESP : public TS_MESSAGE
{
char errormessage[21];
static const uint16_t packetID = 2174;
};
struct BM_SC_ENTER_ROOM_SUCCESS_RESP : public TS_MESSAGE
{
char successmessage[8];
uint64_t uk1;
uint64_t uk2;
char relayip[20];
uint16_t relayport;
uint8_t team; // 1 = red | 2 = Blue
uint8_t uk3;
uint8_t uk4;
uint32_t udpport; //default 5000
static const uint16_t packetID = 2176;
};
struct BM_SC_ENTER_ROOM_FAILED_RESP : public TS_MESSAGE
{
char errormessage[16];
static const uint16_t packetID = 2176;
};
struct BM_SC_ENTER_ROOM_ALREADYJOINED_RESP : public TS_MESSAGE
{
char errormessage[21];
static const uint16_t packetID = 2176;
};
struct BM_SC_LEAVE_ROOM_RESP : public TS_MESSAGE
{
char successmessage[8];
static const uint16_t packetID = 2178;
};
struct BM_SC_ROOM_MULTI_INFO_RESP : public TS_MESSAGE
{
char remoteendpoint[33];
char charname[40];
uint8_t lobbyposition;
uint8_t chartype;
uint8_t enterinfo; //has to be 3 BM_SC_USER_INFO:USER_ENTER
uint8_t isadmin;
uint8_t slotdisplay;
uint8_t ready;
uint8_t status;
uint16_t uk1;
uint8_t uk2;
uint8_t uk3;
static const uint16_t packetID = 2165;
};
struct BM_SC_SELECT_MAP_RESP : public TS_MESSAGE
{
char successmessage[8];
uint16_t mapid;
static const uint16_t packetID = 2199;
};
struct BM_SC_MAP_INFO_RESP : public TS_MESSAGE
{
uint32_t mapid;
static const uint16_t packetID = 2164;
};
struct BM_SC_START_GAME_RESP : public TS_MESSAGE_WNA
{
char successmessage[8];
uint64_t uk1;
uint64_t uk2;
char encryptionkey[16];
uint16_t playercount;
char ip1[45] = "192.168.1.91\0";
char ip2[45] = "192.168.1.31\0";
//char ip3[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//char ip4[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//char ip5[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//char ip6[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//char ip7[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//char ip8[45] = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//Playerlist
sg_constructor::room_players players[0];
static const uint16_t packetID = 2190;
};
struct BM_SC_END_GAME : public TS_MESSAGE
{
char successmessage[8];
static const uint16_t packetID = 2192;
};
struct BM_SC_UNKNOWN_INFO_RESP : public TS_MESSAGE
{
char name[40];
static const uint16_t packetID = 2184;
};
struct BM_SC_READY_GAME_RESP : public TS_MESSAGE
{
char successmessage[8];
static const uint16_t packetID = 2188;
};
#endif
|
#ifndef GAME_H
#define GAME_H
#include <vector>
#include <iostream>
#include "Card.h"
#include "User.h"
#include "Dealer.h"
#define TRUE 1
#define FALSE 0
class Game{
private:
bool end=FALSE;
public:
static unsigned int round;
// constructor
Game(vector<User>&,int); // done
void setAllBets(vector <User>& ,vector <User>::iterator);// done
// display function
void displayGame(vector <User>& , vector <User>::iterator,Dealer); // done
void displayResult(vector <User>& , vector <User>::iterator,Dealer); // done
// deals the first card of the game
void dealRound(Dealer&, vector <Card>&, vector <User>&, vector <User>::iterator);
void play(Dealer&, vector <Card>&, vector <User>&,vector <User>::iterator);
static unsigned int getRound();
void askForAce(int, vector<Card>&, vector<Card>::iterator);
void setGameEnd(bool);
bool getGameEnd()const;
~Game(); // destructor
};
#endif
|
//
// NoGold.cpp
// GetFish
//
// Created by zhusu on 15/8/17.
//
//
#include "NoGold.h"
#include "Common.h"
#include "Tools.h"
#include "Data.h"
#include "MapScene.h"
#include "GameSaveData.h"
#include "GameScene.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "IOSiAP_Bridge.h"
#endif
NoGold* NoGold::create(int type)
{
NoGold* map = new NoGold();
if(map && map->init(type)) {
map->autorelease();
return map;
}
CC_SAFE_DELETE(map);
return NULL;
}
NoGold::NoGold()
{
}
NoGold::~NoGold()
{
}
bool NoGold::init(int type)
{
if(CCLayer::init()) {
CCLayerColor* layerColor = CCLayerColor::create();
layerColor->setPosition(ccp(-CCDirector::sharedDirector()->getWinSize().width*0.5, -CCDirector::sharedDirector()->getWinSize().height*0.5));
layerColor->setColor(ccc3(0, 0, 0));
layerColor->setOpacity(150);
addChild(layerColor);
_type = type;
CCSprite* back = CCSprite::createWithSpriteFrameName("ui_tishi_back.png");
addChild(back);
if(_type>=TYPE_KAI_2){
CCSprite* name = CCSprite::createWithSpriteFrameName("ui_noname_10.png");
name->setPosition(ccp(0, 140));
addChild(name);
CCSprite* zi = CCSprite::createWithSpriteFrameName(("ui_nozi_"+Tools::intToString(type)+".png").c_str());
zi->setPosition(ccp(0, 50));
addChild(zi);
CCSprite* zi1 = CCSprite::createWithSpriteFrameName("ui_nozi_100.png");
zi1->setPosition(ccp(0, -30));
addChild(zi1);
}else{
CCSprite* name = CCSprite::createWithSpriteFrameName(("ui_noname_"+Tools::intToString(type)+".png").c_str());
name->setPosition(ccp(0, 140));
addChild(name);
CCSprite* zi = CCSprite::createWithSpriteFrameName(("ui_nozi_"+Tools::intToString(type)+".png").c_str());
addChild(zi);
}
_buttons = ButtonWithSpriteManage::create("ui/button.png");
this->addChild(_buttons);
_buttons->addButton(BUTTON_NOGOLD_BACK, "button_fanhui2.png", ccp(-144, -128));
if (type == TYPE_GOLD) {
_buttons->addButton(BUTTON_NOGOLD_GET, "button_buyGold.png", ccp(144, -128));
}else if(_type>=TYPE_KAI_2){
_buttons->addButton(BUTTON_NOGOLD_GET, "button_open.png", ccp(144, -128));
}else{
_buttons->addButton(BUTTON_NOGOLD_GET, "button_buyGet.png", ccp(144, -128));
}
this->setTouchEnabled(true);
return true;
}
return false;
}
void NoGold::onEnter()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, KEY_NOGOLD, true);
CCLayer::onEnter();
}
void NoGold::onExit()
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
CCLayer::onExit();
}
bool NoGold::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
// CCPoint pos = pTouch->getLocation();
_buttons->toucheBegan(pTouch, pEvent);
return true;
}
void NoGold::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
_buttons->toucheMoved(pTouch, pEvent);
}
void NoGold::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
_buttons->toucheEnded(pTouch, pEvent);
if (_buttons->getNowID() == BUTTON_NOGOLD_BACK) {
removeFromParentAndCleanup(true);
CCDirector::sharedDirector()->resume();
}else if (_buttons->getNowID() == BUTTON_NOGOLD_GET){
removeFromParentAndCleanup(true);
if (_type == TYPE_GOLD) {
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
MapScene::instance()->addBuy();
IOSiAP_Bridge::instance()->requestProducts(IOSiAP_Bridge::IAP_BIG_GOLD);
#else
player_gold+=75000;
MapScene::instance()->setGold();
GameSaveData::saveGoldData();
#endif
}else if (_type == TYPE_GET){
CCDirector::sharedDirector()->resume();
if (player_gold>=3000) {
player_gold-=3000;
GameSaveData::saveGoldData();
getAll+=1;
GameSaveData::saveAllData();
GameScene::instance()->setCiTie(getAll);
}
}else if (_type == TYPE_GOLD_GET){
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
GameScene::instance()->addBuy();
IOSiAP_Bridge::instance()->requestProducts(IOSiAP_Bridge::IAP_GAME_BIG_GOLD);
#else
player_gold+=75000;
player_gold-=3000;
GameSaveData::saveGoldData();
getAll+=1;
GameSaveData::saveAllData();
GameScene::instance()->setCiTie(getAll);
#endif
}else if(_type >= TYPE_KAI_2){
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
MapScene::instance()->addBuy();
IOSiAP_Bridge::instance()->requestProducts(IOSiAP_Bridge::IAP_OPEN_VIP);
#else
for (int i = 0; i<72; ++i) {
if (GameSaveData::loadLevelData(i)<=0) {
GameSaveData::saveLevelData(i, 1);
}
}
for (int i = 0; i<6; ++i) {
GameSaveData::savePlayer(i);
}
getAll+=99;
GameSaveData::saveAllData();
GameSaveData::saveVipGif();
select_player = 5;
MapScene::instance()->changeToMap();
#endif
}
}
}
|
// Created by: DAUTRY Philippe
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDF_RelocationTable_HeaderFile
#define _TDF_RelocationTable_HeaderFile
#include <Standard.hxx>
#include <TDF_LabelDataMap.hxx>
#include <TDF_AttributeDataMap.hxx>
#include <TColStd_IndexedDataMapOfTransientTransient.hxx>
#include <Standard_Transient.hxx>
#include <TDF_LabelMap.hxx>
#include <TDF_AttributeMap.hxx>
#include <Standard_OStream.hxx>
class TDF_Label;
class TDF_Attribute;
class TDF_RelocationTable;
DEFINE_STANDARD_HANDLE(TDF_RelocationTable, Standard_Transient)
//! This is a relocation dictionary between source
//! and target labels, attributes or any
//! transient(useful for copy or paste actions).
//! Note that one target value may be the
//! relocation value of more than one source object.
//!
//! Common behaviour: it returns true and the found
//! relocation value as target object; false
//! otherwise.
//!
//! Look at SelfRelocate method for more explanation
//! about self relocation behavior of this class.
class TDF_RelocationTable : public Standard_Transient
{
public:
//! Creates an relocation table. <selfRelocate> says
//! if a value without explicit relocation is its own
//! relocation.
Standard_EXPORT TDF_RelocationTable(const Standard_Boolean selfRelocate = Standard_False);
//! Sets <mySelfRelocate> to <selfRelocate>.
//!
//! This flag affects the HasRelocation method
//! behavior like this:
//!
//! <mySelfRelocate> == False:
//!
//! If no relocation object is found in the map, a
//! null object is returned
//!
//! <mySelfRelocate> == True:
//!
//! If no relocation object is found in the map, the
//! method assumes the source object is relocation
//! value; so the source object is returned as target
//! object.
Standard_EXPORT void SelfRelocate (const Standard_Boolean selfRelocate);
//! Returns <mySelfRelocate>.
Standard_EXPORT Standard_Boolean SelfRelocate() const;
Standard_EXPORT void AfterRelocate (const Standard_Boolean afterRelocate);
//! Returns <myAfterRelocate>.
Standard_EXPORT Standard_Boolean AfterRelocate() const;
//! Sets the relocation value of <aSourceLabel> to
//! <aTargetLabel>.
Standard_EXPORT void SetRelocation (const TDF_Label& aSourceLabel, const TDF_Label& aTargetLabel);
//! Finds the relocation value of <aSourceLabel>
//! and returns it into <aTargetLabel>.
//!
//! (See above SelfRelocate method for more
//! explanation about the method behavior)
Standard_EXPORT Standard_Boolean HasRelocation (const TDF_Label& aSourceLabel, TDF_Label& aTargetLabel) const;
//! Sets the relocation value of <aSourceAttribute> to
//! <aTargetAttribute>.
Standard_EXPORT void SetRelocation (const Handle(TDF_Attribute)& aSourceAttribute, const Handle(TDF_Attribute)& aTargetAttribute);
//! Finds the relocation value of <aSourceAttribute>
//! and returns it into <aTargetAttribute>.
//!
//! (See above SelfRelocate method for more
//! explanation about the method behavior)
Standard_EXPORT Standard_Boolean HasRelocation (const Handle(TDF_Attribute)& aSourceAttribute, Handle(TDF_Attribute)& aTargetAttribute) const;
//! Safe variant for arbitrary type of argument
template <class T>
Standard_Boolean HasRelocation (const Handle(TDF_Attribute)& theSource, Handle(T)& theTarget) const
{
Handle(TDF_Attribute) anAttr = theTarget;
return HasRelocation (theSource, anAttr) && ! (theTarget = Handle(T)::DownCast(anAttr)).IsNull();
}
//! Sets the relocation value of <aSourceTransient> to
//! <aTargetTransient>.
Standard_EXPORT void SetTransientRelocation (const Handle(Standard_Transient)& aSourceTransient, const Handle(Standard_Transient)& aTargetTransient);
//! Finds the relocation value of <aSourceTransient>
//! and returns it into <aTargetTransient>.
//!
//! (See above SelfRelocate method for more
//! explanation about the method behavior)
Standard_EXPORT Standard_Boolean HasTransientRelocation (const Handle(Standard_Transient)& aSourceTransient, Handle(Standard_Transient)& aTargetTransient) const;
//! Clears the relocation dictionary, but lets the
//! self relocation flag to its current value.
Standard_EXPORT void Clear();
//! Fills <aLabelMap> with target relocation
//! labels. <aLabelMap> is not cleared before use.
Standard_EXPORT void TargetLabelMap (TDF_LabelMap& aLabelMap) const;
//! Fills <anAttributeMap> with target relocation
//! attributes. <anAttributeMap> is not cleared before
//! use.
Standard_EXPORT void TargetAttributeMap (TDF_AttributeMap& anAttributeMap) const;
//! Returns <myLabelTable> to be used or updated.
Standard_EXPORT TDF_LabelDataMap& LabelTable();
//! Returns <myAttributeTable> to be used or updated.
Standard_EXPORT TDF_AttributeDataMap& AttributeTable();
//! Returns <myTransientTable> to be used or updated.
Standard_EXPORT TColStd_IndexedDataMapOfTransientTransient& TransientTable();
//! Dumps the relocation table.
Standard_EXPORT Standard_OStream& Dump (const Standard_Boolean dumpLabels, const Standard_Boolean dumpAttributes, const Standard_Boolean dumpTransients, Standard_OStream& anOS) const;
DEFINE_STANDARD_RTTIEXT(TDF_RelocationTable,Standard_Transient)
protected:
private:
Standard_Boolean mySelfRelocate;
Standard_Boolean myAfterRelocate;
TDF_LabelDataMap myLabelTable;
TDF_AttributeDataMap myAttributeTable;
TColStd_IndexedDataMapOfTransientTransient myTransientTable;
};
#endif // _TDF_RelocationTable_HeaderFile
|
/*
* Copyright (c) 2014-2017 Detlef Vollmann, vollmann engineering gmbh
*
* 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)
*/
#ifndef CANVAS_HH_SEEN_
#define CANVAS_HH_SEEN_
#include "shape.hh"
#include "extgraph.hh"
#include <vector>
#include <string>
#ifdef _WIN32
#include "w32win.hh"
#else
#include "xwin.hh"
#endif
namespace exercise
{
class CanvasImpl
{
public:
CanvasImpl(int width, int height, std::string const &name);
~CanvasImpl();
CanvasImpl(CanvasImpl const&) = delete;
CanvasImpl& operator=(CanvasImpl const&) = delete;
void operator+=(Shape *);
void draw() const;
void show() const;
void startLoop();
private:
GuiWin *win;
cairo_surface_t *surface;
cairo_t *cr;
std::vector<Shape *> elems;
};
class Canvas
{
public:
Canvas(int width, int height, std::string const &name);
~Canvas();
Canvas(Canvas const&) = delete;
Canvas& operator=(Canvas const&) = delete;
void operator+=(Shape *);
void draw() const;
void show() const;
void startLoop();
private:
CanvasImpl *pImpl;
};
} // namespace exercise
#endif /* CANVAS_HH_SEEN_ */
|
#include <iostream>
#include <filesystem>
#include <uvw.hpp>
#include "client.hpp"
#include "serialization.hpp"
namespace rpc {
generic_client::generic_client(generic_protocol server_protocol, generic_impl client_impl, std::string address_): server_text_address(std::move(address_)), server_protocol(std::move(server_protocol)), client_impl(std::move(client_impl)) {
std::cerr << "Connecting to address " << server_text_address << std::endl;
if(server_text_address[0] == '/' || (server_text_address[0] == '.' && server_text_address[1] == '/')) {
// Path to UNIX domain socket
_do_connect = [this]() {
_connect_impl<uvw::PipeHandle>(server_text_address);
};
} else {
// IPv4 or IPv6
auto i = server_text_address.rfind(':');
if(i == std::string::npos) {
throw std::runtime_error("Address must end with a colon followed by a port number");
}
auto loop = uvw::Loop::getDefault();
auto getaddrinfo = loop->resource<uvw::GetAddrInfoReq>();
auto addrinfo_result = getaddrinfo->addrInfoSync(server_text_address.substr(0, i), server_text_address.substr(i + 1));
if(!addrinfo_result.first) {
throw std::runtime_error("Could not resolve name");
}
struct addrinfo* addrinfo = addrinfo_result.second.get();
sockaddr_storage address = *reinterpret_cast<sockaddr_storage*>(addrinfo->ai_addr);
_do_connect = [this, address]() {
_connect_impl<uvw::TCPHandle>(reinterpret_cast<const sockaddr&>(address));
};
}
_do_connect();
}
generic_client::~generic_client() {
stop();
}
void generic_client::on_incoming_handshake(tcb::span<const std::byte> span) {
// This method attempts to reconnect on handshake failure or protocol violation. Whether this is a wise idea or
// it is better to fail fast is yet to be determined.
server_hello hello = deserialize<server_hello>(span);
if(hello.magic != std::array{'s', 'm', 'o', 'l'}) {
std::cerr << "Client failure on " << server_text_address << ": invalid magic" << std::endl;
reconnect(true);
return;
}
if(!hello.error_message.empty()) {
std::cerr << "Client failure on " << server_text_address << ": " << hello.error_message << std::endl;
reconnect(true);
return;
}
if(hello.method_ids.size() != server_protocol.methods.size()) {
std::cerr << "Client failure on " << server_text_address << ": The requested method count and the returned method ID count differs" << std::endl;
reconnect(true);
return;
}
for(size_t i = 0; i < server_protocol.methods.size(); i++) {
server_ids_of_methods[server_protocol.methods[i].name] = hello.method_ids[i];
}
std::cerr << "Handshake with " << server_text_address << " is now established" << std::endl;
for(pending_message& pending: pending_messages) {
rpc_message message;
message.message_size = 0;
message.method_id = server_ids_of_methods.at(pending.method_name);
message.message_id = pending.message_id;
message.args = std::move(pending.args);
message.message_size = serialize(message).size();
sock->write(serialize(message));
}
pending_messages.clear();
}
void generic_client::on_message(rpc_message&& message) {
if(message.method_id == -1) {
auto it = promises.find(message.message_id);
if(it == promises.end()) {
std::cerr << "Client failure on " << server_text_address << ": Response to message #" << message.message_id << ": no corresponding request or double response" << std::endl;
return;
}
promises.extract(it).mapped().set(std::move(message.args));
} else if(message.method_id == -2) {
std::cerr << "Client failure on " << server_text_address << ": Message #" << message.message_id << ": " << deserialize<std::string>(message.args) << std::endl;
} else if(0 <= message.method_id && message.method_id < client_impl.methods.size()) {
client_impl.methods[message.method_id].fn(client_impl_object, message.args) | [sock = sock, message_id = message.message_id](std::vector<std::byte> result) {
sock->reply(message_id, std::move(result));
};
} else {
sock->report_error(message.message_id, "Unknown method");
}
}
void generic_client::stop() {
is_active = false;
if(sock) {
sock->stop();
sock.reset();
}
if(timer) {
timer->close();
timer = nullptr;
}
}
void generic_client::reconnect(bool due_to_failure) {
if(due_to_failure) {
n_failures++;
} else {
n_failures = 0;
}
if(sock) {
sock->stop();
sock.reset();
}
if(!is_active) {
return;
}
std::cerr << "reconnecting..." << std::endl;
auto loop = uvw::Loop::getDefault();
timer = loop->template resource<uvw::TimerHandle>().get();
timer->template on<uvw::TimerEvent>([this](const uvw::TimerEvent&, uvw::TimerHandle& timer) {
timer.close();
this->timer = nullptr;
_do_connect();
});
int n_seconds;
if(n_failures == 0) {
n_seconds = 0;
} else if(n_failures <= 3) {
n_seconds = 1;
} else {
n_seconds = 1;
for(int i = 0; i < std::min(6, n_failures - 3); i++) {
n_seconds *= 2;
}
}
timer->start(std::chrono::seconds{n_seconds}, std::chrono::seconds{0});
}
async::promise<std::vector<std::byte>> generic_client::invoke(const char* method_name, std::vector<std::byte>&& args) {
uint64_t message_id = next_message_id++;
if(!sock || !sock->handshake_finished()) {
pending_messages.push_back({method_name, message_id, std::move(args)});
} else {
sock->invoke(server_ids_of_methods.at(method_name), message_id, std::move(args));
}
async::promise<std::vector<std::byte>> prom;
promises.emplace(message_id, prom);
return prom;
}
template<typename Handle, typename Address> void generic_client::_connect_impl(Address&& address) {
auto loop = uvw::Loop::getDefault();
auto client = loop->resource<Handle>();
client->template on<uvw::ConnectEvent>([this](const uvw::ConnectEvent&, Handle& client) {
client_hello hello;
hello.hello_size = 0;
hello.magic = {'S', 'M', 'O', 'L'};
hello.requested_server_protocol_name = server_protocol.name;
hello.advertised_client_protocol_name = client_impl.protocol_name;
for(auto spec: server_protocol.methods) {
hello.requested_server_methods.push_back({spec.name, spec.signature});
}
for(auto spec: client_impl.methods) {
hello.advertised_client_methods.push_back({spec.name, spec.signature});
}
hello.hello_size = serialize(hello).size();
sock->write(serialize(hello));
});
sock = std::make_shared<socket<Handle>>(client, false, [this](rpc_message&& message) {
on_message(std::move(message));
}, [this](tcb::span<const std::byte> span) {
on_incoming_handshake(span);
});
client->template once<uvw::CloseEvent>([this](const uvw::CloseEvent&, Handle& client) {
std::cerr << "Client failure on " << server_text_address << ": closed" << std::endl;
reconnect(true);
});
client->connect(address);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Alexander Remen (alexr)
*/
#include "core/pch.h"
#include "URLInputDialog.h"
#include "adjunct/quick/widgets/OpAddressDropDown.h"
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick_toolkit/widgets/OpLabel.h"
#include "modules/locale/oplanguagemanager.h"
/***********************************************************************************
**
** SetMessageAndTitle
**
***********************************************************************************/
void URLInputDialog::SetTitleAndMessage( const OpStringC& title, const OpStringC& message)
{
SetTitle(title.CStr());
OpLabel* label = static_cast<OpLabel*> (GetWidgetByName("message_field"));
if (label)
{
label->SetText(message.CStr());
}
}
/***********************************************************************************
**
** OnInit
**
***********************************************************************************/
void URLInputDialog::OnInit()
{
OpAddressDropDown* address_dropdown = (OpAddressDropDown*) GetWidgetByName("address_field");
if(address_dropdown)
{
address_dropdown->SetInvokeActionOnClick(FALSE);
address_dropdown->SetMaxNumberOfColumns(1);
address_dropdown->SetOpenInTab(FALSE);
OpInputAction *okaction = OP_NEW(OpInputAction, (OpInputAction::ACTION_OK));
address_dropdown->SetAction(okaction);
}
}
/***********************************************************************************
**
** OnOk
**
***********************************************************************************/
UINT32 URLInputDialog::OnOk()
{
OpAddressDropDown* address_dropdown = (OpAddressDropDown*) GetWidgetByName("Address_field");
if(address_dropdown)
{
OpString URL_result;
address_dropdown->GetText(URL_result);
if (m_url_input_listener)
m_url_input_listener->OnURLInputOkCallback(URL_result);
}
return 0;
}
/***********************************************************************************
**
** OnClose
**
***********************************************************************************/
void URLInputDialog::OnCancel()
{
if (m_url_input_listener)
m_url_input_listener->OnURLInputCancelCallback();
}
|
#include "menus.h"
using namespace std;
int main() {
unsigned short command;
double x, y, z;
double scalar;
bool yn = 1;
menu();
//Input choice
std::cin >> command;
while (command < 1 || command > 2 || std::cin.fail()) {
cin.clear();
cin.ignore();
std::cout << "Please enter a valid option:\n\n";
std::cin >> command;
}
switch (command) {
case 1:
//===============
//===============
// File stream
//===============
//===============
system("cls");
fileMenu();
break;
case 2:
{
//===============
//===============
// Console stream
//===============
//===============
system("cls");
consoleMenu();
//===============
//===============
//Geometric object
//===============
//===============
std::cin >> command;
switch (command) {
//===============
//===============
// Point
//===============
//===============
case 1:
{
Point p1, p2;
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
while (yn) {
system("cls");
pointMenu();
std::cin >> command;
switch (command) {
case 1:
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
if (p1 == p2) {
std::cout << "\nPoints are equal.\n\n";
}
else {
std::cout << "\nPoints are not equal.\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n\n";
std::cin >> yn;
}
}
break;
}
case 2:
//==================
//==================
// Vector
//==================
//==================
{
system("cls");
vectorInit();
Point p1, p2;
Vector v1, v2, v3;
std::cin >> command;
//Vector initialization
switch (command) {
case 1:
{
//==================
//==================
// Three values init
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v1.setZ(z);
break;
}
case 2:
{
//==================
//==================
// Two points init
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setX(z);
v1.setX(p2.getX() - p1.getX());
v1.setY(p2.getY() - p1.getY());
v1.setZ(p2.getZ() - p1.getZ());
break;
}
}
while (yn) {
system("cls");
vectorMenu();
std::cin >> command;
//Vector operations
switch (command) {
case 1:
std::cout << "Vector length is " << (v1.length()) << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 2:
std::cout << "Directional vector is " << v1.getDirection() << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 3:
if (v1.isNull()) {
std::cout << "Vector is null\n\n";
}
else {
std::cout << "Vector is not null\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 4:
//==================
//==================
// Paralellism check
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
if (v1.paralellismCheck(v2)) {
std::cout << "Vectors are parallel\n\n";
}
else {
std::cout << "Vectors are not parallel\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 5:
//==================
//==================
//Ortogonality check
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
if (v1.ortogonalityCheck(v2)) {
std::cout << "Vectors are ortogonal\n\n";
}
else {
std::cout << "Vectors are not ortogonal\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 6:
//==================
//==================
// Vector addition
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
std::cout << "Result is " << v1 + v2 << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 7:
//==================
//==================
//Vector substraction
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
std::cout << "Result is " << v1 - v2 << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 8:
//==================
//==================
//Vector-by-scalar mult.
//==================
//==================
std::cout << "Enter scalar \n";
std::cin >> scalar;
std::cout << "Result is " << v1 * scalar << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 9:
//==================
//==================
// Dot product
//==================
//==================
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
std::cout << "Dot product is " << v1 * v2 << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 10:
//==================
//==================
// Cross product
//==================
//==================
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
std::cout << "Cross product result is " << (v1 ^ v2) << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 11:
//==================
//==================
// Mixed product
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
v2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v2.setZ(z);
std::cout << "\n\n";
std::cin >> x;
v3.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v3.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v3.setZ(z);
std::cout << "Cross product is " << v1(v2, v3);
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
}
}
break;
}
case 3:
{
//==================
//==================
// Line
//==================
//==================
system("cls");
lineInit();
Line l1, l2;
Point p1, p2;
Vector v1;
std::cin >> command;
//Line initializatopn
switch (command) {
case 1:
//==================
//==================
// Two points
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
v1.setX(p2.getX() - p1.getX());
v1.setY(p2.getY() - p1.getY());
v1.setZ(p2.getZ() - p1.getZ());
l1.setP1(p1);
l1.setP2(p2);
l1.setV1(v1);
break;
case 2:
//==================
//==================
// Point and vector
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
v1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
v1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
v1.setZ(z);
p2.setX(p1.getX() + v1.getX());
p2.setY(p1.getY() + v1.getY());
p2.setZ(p1.getZ() + v1.getZ());
l1.setP1(p1);
l1.setP2(p2);
l1.setV1(v1);
break;
}
while (yn) {
system("cls");
lineMenu();
std::cin >> command;
switch (command) {
case 1:
//==================
//==================
//Directional vector
//==================
//==================
std::cout << "Directional vector is " << l1.getV1().getDirection() << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 2:
//==================
//==================
// Normal vector
//==================
//==================
std::cout << "Normal vector is " << l1.normalVector() << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 3:
//==================
//==================
// Lines angle
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
v1.setX(p2.getX() - p1.getX());
v1.setY(p2.getY() - p1.getY());
v1.setZ(p2.getZ() - p1.getZ());
l2.setV1(v1);
std::cout << "Angle is " << l1.angle(l2) << "\n\n";
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 4:
//==================
//==================
// Line cross point
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
if (l1 + p1) {
std::cout << "The line and the point intersect\n\n";
}
else {
std::cout << "The line and the point don't intersect\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 5:
//==================
//==================
// Lines parallel
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
l1.setP1(p1);
l1.setP2(p2);
if (l1 || l2) {
std::cout << "The two lines are parallel \n\n";
}
else {
std::cout << "The two lines are not parallel \n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 6:
//==================
//==================
// Lines coincide
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
l1.setP1(p1);
l1.setP2(p2);
if (l1 == l2) {
std::cout << "The lines coincide\n\n";
}
else {
std::cout << "The lines don't coincide\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 7:
//==================
//==================
// Lines cross
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
l1.setP1(p1);
l1.setP2(p2);
if (l1 && l2) {
std::cout << "The lines cross\n\n";
}
else {
std::cout << "The lines don't cross\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 8:
//==================
//==================
// Lines skew
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
l1.setP1(p1);
l1.setP2(p2);
if (l1 != l2) {
std::cout << "The lines are skew \n\n";
}
else {
std::cout << "The lines are not skew\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
case 9:
//==================
//==================
// Lines ortogonal
//==================
//==================
std::cout << "Enter x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter z value\n";
std::cin >> z;
p2.setZ(z);
l1.setP1(p1);
l1.setP2(p2);
if (l1 | l2) {
std::cout << "The lines are ortogonal\n\n";
}
else {
std::cout << "The lines are not ortogonal\n\n";
}
std::cout << "Do you want to continue operations with this object? 0/1 \n";
std::cin >> yn;
break;
}
}
break;
}
case 4:
{
Vector v1;
Segment s1;
Point p1, p2;
double t1, t2;
std::cout << "Enter p1.x value\n";
std::cin >> x;
p1.setX(x);
std::cout << "Enter p1.y value\n";
std::cin >> y;
p1.setY(y);
std::cout << "Enter p1.z value\n";
std::cin >> z;
p1.setZ(z);
std::cout << "\n\n";
std::cout << "Enter p2.x value\n";
std::cin >> x;
p2.setX(x);
std::cout << "Enter p2.y value\n";
std::cin >> y;
p2.setY(y);
std::cout << "Enter p2.z value\n";
std::cin >> z;
p2.setZ(z);
std::cout << "\n\n";
std::cout << "Enter t1 value\n";
std::cin >> t1;
std::cout << "Enter t2 value\n";
std::cin >> t2;
v1.setX(p2.getX() - p1.getX());
v1.setY(p2.getY() - p1.getY());
v1.setZ(p2.getZ() - p1.getZ());
segmentMenu();
break;
}
case 5:
{
system("cls");
triangleMenu();
break;
}
}
break;
}
}
}
|
//
// proj11_main.cpp
// HelloWorld
//
// Created by Kristjan von Bulow.
// Copyright © 2018 Kristjan von Bulow. All rights reserved.
//
#include<sstream>
#include<iostream>
using std::ostringstream;
using std::endl;
using std::cout;
using std::cin;
#include<string>
using std::string;
#include "proj11_trimap.hpp"
int main() {
cout << std::boolalpha;
TriMap <long, long>m;
m.insert(2,20);
m.insert(1, 10);
m.insert(4,40);
m.insert(3,30);
bool result = m.remove(3);
cout << result << endl;
//ASSERT_TRUE(result);
size_t sz = m.size();
cout << sz << endl;
//ASSERT_EQ(sz, 3);
ostringstream oss;
oss << m;
string s = oss.str();
string ans = "1:10:1, 2:20:0, 4:40:2";
cout << s << endl;
//ASSERT_EQ(s,ans);
}
|
// Created on: 1998-01-13
// Created by: Christian CAILLET
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSelect_SelectBypassSubfigure_HeaderFile
#define _IGESSelect_SelectBypassSubfigure_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_SelectExplore.hxx>
#include <Standard_Integer.hxx>
class Standard_Transient;
class Interface_Graph;
class Interface_EntityIterator;
class TCollection_AsciiString;
class IGESSelect_SelectBypassSubfigure;
DEFINE_STANDARD_HANDLE(IGESSelect_SelectBypassSubfigure, IFSelect_SelectExplore)
//! Selects a list built as follows :
//! Subfigures correspond to
//! * Definition (basic : type 308, or Network : type 320)
//! * Instance (Singular : type 408, or Network : 420, or
//! patterns : 412,414)
//!
//! Entities which are not Subfigure are taken as such
//! For Subfigures Instances, their definition is taken, then
//! explored itself
//! For Subfigures Definitions, the list of "Associated Entities"
//! is explored
//! Hence, level 0 (D) recursively explores a Subfigure if some of
//! its Elements are Subfigures. level 1 explores just at first
//! level (i.e. for an instance, returns its definition)
class IGESSelect_SelectBypassSubfigure : public IFSelect_SelectExplore
{
public:
//! Creates a SelectBypassSubfigure, by default all level
//! (level = 1 explores at first level)
Standard_EXPORT IGESSelect_SelectBypassSubfigure(const Standard_Integer level = 0);
//! Explores an entity : for a Subfigure, gives its elements
//! Else, takes the entity itself
Standard_EXPORT Standard_Boolean Explore (const Standard_Integer level, const Handle(Standard_Transient)& ent, const Interface_Graph& G, Interface_EntityIterator& explored) const Standard_OVERRIDE;
//! Returns a text defining the criterium : "Content of Subfigure"
Standard_EXPORT TCollection_AsciiString ExploreLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IGESSelect_SelectBypassSubfigure,IFSelect_SelectExplore)
protected:
private:
};
#endif // _IGESSelect_SelectBypassSubfigure_HeaderFile
|
// Created on: 1993-08-10
// Created by: Remi LEQUETTE
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRep_PointRepresentation_HeaderFile
#define _BRep_PointRepresentation_HeaderFile
#include <Standard.hxx>
#include <TopLoc_Location.hxx>
#include <Standard_Real.hxx>
#include <Standard_Transient.hxx>
class Geom_Curve;
class Geom2d_Curve;
class Geom_Surface;
class BRep_PointRepresentation;
DEFINE_STANDARD_HANDLE(BRep_PointRepresentation, Standard_Transient)
//! Root class for the points representations.
//! Contains a location and a parameter.
class BRep_PointRepresentation : public Standard_Transient
{
public:
//! A point on a 3d curve.
Standard_EXPORT virtual Standard_Boolean IsPointOnCurve() const;
//! A point on a 2d curve on a surface.
Standard_EXPORT virtual Standard_Boolean IsPointOnCurveOnSurface() const;
//! A point on a surface.
Standard_EXPORT virtual Standard_Boolean IsPointOnSurface() const;
//! A point on the curve <C>.
Standard_EXPORT virtual Standard_Boolean IsPointOnCurve (const Handle(Geom_Curve)& C, const TopLoc_Location& L) const;
//! A point on the 2d curve <PC> on the surface <S>.
Standard_EXPORT virtual Standard_Boolean IsPointOnCurveOnSurface (const Handle(Geom2d_Curve)& PC, const Handle(Geom_Surface)& S, const TopLoc_Location& L) const;
//! A point on the surface <S>.
Standard_EXPORT virtual Standard_Boolean IsPointOnSurface (const Handle(Geom_Surface)& S, const TopLoc_Location& L) const;
const TopLoc_Location& Location() const;
void Location (const TopLoc_Location& L);
Standard_Real Parameter() const;
void Parameter (const Standard_Real P);
Standard_EXPORT virtual Standard_Real Parameter2() const;
Standard_EXPORT virtual void Parameter2 (const Standard_Real P);
Standard_EXPORT virtual const Handle(Geom_Curve)& Curve() const;
Standard_EXPORT virtual void Curve (const Handle(Geom_Curve)& C);
Standard_EXPORT virtual const Handle(Geom2d_Curve)& PCurve() const;
Standard_EXPORT virtual void PCurve (const Handle(Geom2d_Curve)& C);
Standard_EXPORT virtual const Handle(Geom_Surface)& Surface() const;
Standard_EXPORT virtual void Surface (const Handle(Geom_Surface)& S);
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
DEFINE_STANDARD_RTTIEXT(BRep_PointRepresentation,Standard_Transient)
protected:
Standard_EXPORT BRep_PointRepresentation(const Standard_Real P, const TopLoc_Location& L);
private:
TopLoc_Location myLocation;
Standard_Real myParameter;
};
#include <BRep_PointRepresentation.lxx>
#endif // _BRep_PointRepresentation_HeaderFile
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int testCase;
class Node{
public:
int inDegree;
int buildTime;
vector<int> next;
vector<int> before;
Node(){
buildTime = 0;
inDegree = 0;
}
};
int main(){
ios_base::sync_with_stdio(false);
cin >> testCase;
int ret[testCase] = {0, };
for(int tcase = 0; tcase < testCase; tcase++){
int n, k, target;
cin >> n >> k;
Node node[n+1];
for(int i = 1; i <= n; i++){
cin >> node[i].buildTime;
}
for(int i = 1; i <= k; i++){
int a, b;
cin >> a >> b;
node[a].next.push_back(b);
node[b].inDegree++;
node[b].before.push_back(a);
}
cin >> target;
queue<int> q;
//시작점 찾기
for(int i = 1; i <= n; i++){
if(node[i].inDegree == 0){
q.push(i);
}
}
while(!q.empty()){
int curIndex = q.front();
q.pop();
for(auto it = node[curIndex].next.begin(); it != node[curIndex].next.end(); it++){
if(--node[*it].inDegree == 0){
//다음 노드의 inDegree를 깎은것이 0이면 q에 넣음
q.push(*it);
}
}
//현재 노드는 이전노드의 buildTime중 가장 큰시간에 자신의 buildTime을 더함.
if(node[curIndex].before.size() != 0){
int maxIndex = -1;
int maxTime = -1;
for(int i = 0; i < node[curIndex].before.size(); i++){
int index = node[curIndex].before[i];
if(node[index].buildTime > maxTime){
maxIndex = index;
maxTime = node[index].buildTime;
}
}
node[curIndex].buildTime += node[maxIndex].buildTime;
}
}
//구해진 건문들 답을 배열에 넣음.
ret[tcase] = node[target].buildTime;
}
for(int i = 0; i < testCase; i++){
cout << ret[i] << '\n';
}
return 0;
}
|
#pragma once
#include "Interface.h"
#include <string>
using namespace std;
#define TRANSLOG(...) CLog::Instance()->TranceLog(__VA_ARGS__);
class CLog :public IOCPHanlder
{
private:
CLog();
virtual ~CLog();
public:
static CLog * pInstance;
static CLog* Instance();
public:
//interface
virtual const HANDLE GetHanle();
virtual bool Callback(PerIocpData* pData, DWORD size);
virtual bool RegIOHandle();
public:
bool Init();
bool CloseLog();
bool TranceLog(const char* str, ...);
private:
bool m_bOpened;
string m_logfile;
HANDLE m_fileHandle;
PerIocpData* pData;
};
|
/*
* @Description: 订阅imu数据
* @Author: Ren Qian
* @Date: 2019-08-19 19:22:17
*/
#ifndef LIDAR_LOCALIZATION_SUBSCRIBER_IMU_SUBSCRIBER_HPP_
#define LIDAR_LOCALIZATION_SUBSCRIBER_IMU_SUBSCRIBER_HPP_
#include <deque>
#include <mutex>
#include <thread>
#include <ros/ros.h>
#include "sensor_msgs/Imu.h"
#include "lidar_localization/sensor_data/imu_data.hpp"
namespace lidar_localization {
class IMUSubscriber {
public:
IMUSubscriber(ros::NodeHandle& nh, std::string topic_name, size_t buff_size);
IMUSubscriber() = default;
void ParseData(std::deque<IMUData>& deque_imu_data);
private:
void msg_callback(const sensor_msgs::ImuConstPtr& imu_msg_ptr);
private:
ros::NodeHandle nh_;
ros::Subscriber subscriber_;
std::deque<IMUData> new_imu_data_;
std::mutex buff_mutex_;
};
}
#endif
|
#include "TableTimer.h"
#include "IProcess.h"
#include "Table.h"
#include "Logger.h"
#include "Configure.h"
#include "HallManager.h"
#include "AllocSvrConnect.h"
//====================CTimer_Handler==================================//
int CTimer_Handler::ProcessOnTimerOut()
{
if(handler)
return handler->ProcessOnTimerOut(this->timeid, this->uid);
else
return 0;
}
void CTimer_Handler::SetTimeEventObj(TableTimer * obj, int timeid, int uid)
{
this->handler = obj;
this->timeid = timeid;
this->uid = uid;
}
//==========================TableTimer==================================//
void TableTimer::init(Table* table)
{
this->table = table;
}
void TableTimer::stopAllTimer()
{
stopBetCoinTimer();
stopKickTimer();
stopTableStartTimer();
}
void TableTimer::startBetCoinTimer(int uid,int timeout)
{
m_BetTimer.SetTimeEventObj(this, BET_COIN_TIMER, uid);
m_BetTimer.StartTimer(timeout);
}
void TableTimer::stopBetCoinTimer()
{
m_BetTimer.StopTimer();
}
void TableTimer::startTableStartTimer(int timeout)
{
m_TableStartTimer.SetTimeEventObj(this, TABLE_START_TIMER);
m_TableStartTimer.StartTimer(timeout);
}
void TableTimer::stopTableStartTimer()
{
m_TableStartTimer.StopTimer();
}
void TableTimer::startKickTimer(int timeout)
{
m_TableKickTimer.SetTimeEventObj(this, TABLE_KICK_TIMER);
m_TableKickTimer.StartTimer(timeout);
}
void TableTimer::stopKickTimer()
{
m_TableKickTimer.StopTimer();
}
void TableTimer::startGameOverTimer(int timeout)
{
m_GameOverTimer.SetTimeEventObj(this, TABLE_GAME_OVER_TIMER);
m_GameOverTimer.StartMinTimer(timeout);
}
void TableTimer::stopGameOverTimer()
{
m_GameOverTimer.StopTimer();
}
void TableTimer::startCompareResultNotifyTimer(int timeout)
{
m_CompareResultNotifyTimer.SetTimeEventObj(this , TABLE_COMPARE_RESULT_NOTIFY_TIMER);
m_CompareResultNotifyTimer.StartMinTimer(timeout);
}
void TableTimer::stopCompareResultNotifyTimer()
{
m_CompareResultNotifyTimer.StopTimer();
}
int TableTimer::ProcessOnTimerOut(int Timerid, int uid)
{
switch (Timerid)
{
case BET_COIN_TIMER:
return BetTimeOut(uid);
case TABLE_START_TIMER:
return TableGameStartTimeOut();
case TABLE_KICK_TIMER:
return TableKickTimeOut();
case TABLE_GAME_OVER_TIMER:
return GameOverTimeOut();
case TABLE_COMPARE_RESULT_NOTIFY_TIMER:
return CompareResultNotifyTimeOut();
default:
return 0;
}
return 0;
}
int TableTimer::BetTimeOut(int uid)
{
this->stopBetCoinTimer();
Player* player = table->getPlayer(uid);
if(player == NULL)
{
_LOG_ERROR_("[BetTimeOut] uid=[%d] tid=[%d] Your not in This Table\n",uid, this->table->id);
return 0;
}
if(table->m_nCurrBetUid != uid)
{
_LOG_ERROR_("[BetTimeOut] uid=[%d] tid=[%d] betUid[%d] is not this uid:%d\n",uid, this->table->id, table->m_nCurrBetUid, uid);
return 0;
}
_LOG_INFO_("BetTimeOut Uid=[%d] GameID=[%s] m_lSumBetCoin=[%ld] currRound=[%d]\n", player->id, table->getGameID(), player->m_lSumBetCoin, table->m_bCurrRound);
//如果是第一轮用户就下注超时则记录下来,方便后续踢出用户
if(table->m_bCurrRound == 1)
player->timeoutCount++;
Player* nextplayer = NULL;
//表示此人已经弃牌
player->m_bCardStatus = CARD_DISCARD;
//设置下一个应该下注的用户
nextplayer = table->getNextBetPlayer(player,OP_THROW);
if(nextplayer)
{
table->setPlayerOptype(nextplayer, OP_THROW);
}
if(player->m_nTabIndex == table->m_nFirstIndex)
{
table->setNextFirstPlayer(player);
}
if(table->iscanGameOver())
nextplayer = NULL;
int sendNum = 0;
int i = 0;
for(i = 0; i < table->m_bMaxNum; ++i)
{
if(table->player_array[i])
{
sendBetTimeOut(table->player_array[i], table, player, nextplayer);
}
}
if(table->iscanGameOver())
return table->gameOver();
if(nextplayer)
{
table->startBetCoinTimer(nextplayer->id,Configure::getInstance()->betcointime);
nextplayer->setBetCoinTime(time(NULL));
}
return 0;
}
int TableTimer::sendBetTimeOut(Player* player, Table* table, Player* timeoutplayer,Player* nextplayer)
{
int svid = Configure::getInstance()->m_nServerId;
int tid = (svid << 16)|table->id;
OutputPacket response;
response.Begin(GMSERVER_BET_TIMEOUT, player->id);
response.WriteShort(0);
response.WriteString("");
response.WriteInt(player->id);
response.WriteShort(player->m_nStatus);
response.WriteInt(tid);
response.WriteShort(table->m_nStatus);
response.WriteByte(table->m_bCurrRound);
response.WriteInt(timeoutplayer->id);
response.WriteInt64(timeoutplayer->m_lSumBetCoin);
response.WriteInt64(timeoutplayer->m_lMoney);
response.WriteInt64(table->m_lCurrBetMax);
response.WriteInt(nextplayer ? nextplayer->id : 0);
response.WriteInt64(player->m_lSumBetCoin);
response.WriteInt64(player->m_lMoney);
response.WriteShort(player->optype);
response.WriteInt64(table->m_lSumPool);
response.WriteInt64(player->m_AllinCoin);
response.WriteByte(player->m_bCardStatus);
response.End();
_LOG_INFO_("<==[sendBetTimeOut] Push [0x%04x] to uid=[%d]\n", GMSERVER_BET_TIMEOUT, player->id);
_LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n");
_LOG_DEBUG_("[Data Response] uid=[%d]\n",player->id);
_LOG_DEBUG_("[Data Response] m_nStatus=[%d]\n",player->m_nStatus);
_LOG_DEBUG_("[Data Response] tid=[%d]\n", tid);
_LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus);
_LOG_DEBUG_("[Data Response] m_AllinCoin=[%ld]\n", player->m_AllinCoin);
_LOG_DEBUG_("[Data Response] optype=[%ld]\n", player->optype);
if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0)
_LOG_ERROR_("[sendBetTimeOut] Send To Uid[%d] Error!\n", player->id);
return 0;
}
int TableTimer::TableGameStartTimeOut()
{
this->stopTableStartTimer();
_LOG_INFO_("TableGameStartTimeOut tid=[%d]\n", this->table->id);
if(table->isActive())
{
_LOG_WARN_("this table[%d] is Active\n",table->id);
return 0;
}
int i;
if (table->isCanGameStart())
{
for(i = 0; i < table->m_bMaxNum; ++i)
{
Player* getplayer = table->player_array[i];
//把没有准备的用户踢出
if(getplayer && (getplayer->isComming() || getplayer->isGameOver()))
{
IProcess::serverPushLeaveInfo(table, getplayer);
table->playerLeave(getplayer);
}
}
if(table->isAllReady()&&table->m_nCountPlayer > 1)
return IProcess::GameStart(table);
else
_LOG_ERROR_("table[%d] m_nCountPlayer[%d] not all ready\n", table->id, table->m_nCountPlayer);
}
else
_LOG_WARN_("table[%d] is Can't GameStart PlayerCount[%d]\n", table->id, table->m_nCountPlayer);
return 0;
}
int TableTimer::TableKickTimeOut()
{
this->stopKickTimer();
_LOG_INFO_("TableKickTimeOut tid=[%d]\n", this->table->id);
table->unlockTable();
if(table->isActive())
{
_LOG_WARN_("this table[%d] is Active\n",table->id);
return 0;
}
if(table->m_nCountPlayer == 1)
{
_LOG_WARN_("this table[%d] is One Player\n",table->id);
return 0;
}
int i;
for(i = 0; i < table->m_bMaxNum; ++i)
{
Player* getplayer = table->player_array[i];
//把没有准备的用户踢出
if(getplayer && !getplayer->isReady())
{
IProcess::serverPushLeaveInfo(table, getplayer, 2);
table->playerLeave(getplayer);
}
}
if(table->isAllReady()&&table->m_nCountPlayer > 1)
return IProcess::GameStart(table);
else
_LOG_ERROR_("table[%d] m_nCountPlayer[%d] not all ready\n", table->id, table->m_nCountPlayer);
return 0;
}
int TableTimer::GameOverTimeOut()
{
this->stopGameOverTimer();
_LOG_INFO_("GameOverTimeOut tid=[%d]\n", this->table->id);
for(int i = 0; i < table->m_bMaxNum; ++i)
{
Player* player = table->player_array[i];
if(player && player->isActive())
{
player->m_nStatus = STATUS_PLAYER_OVER;
AllocSvrConnect::getInstance()->userUpdateStatus(player, STATUS_PLAYER_OVER);
player->startnum++;
}
}
table->m_nStatus = STATUS_TABLE_OVER;
table->setEndTime(time(NULL));
AllocSvrConnect::getInstance()->updateTableStatus(table);
table->calcCoin();
IProcess::GameOver(table);
table->reSetInfo();
return 0;
}
int TableTimer::CompareResultNotifyTimeOut()
{
this->stopCompareResultNotifyTimer();
CompareResultInfo& info = table->CmpRInfo;
Player* p1 = info.p1;
Player* p2 = info.p2;
if (!p1 || !p2)
{
return 0;
}
p1->m_bCompare = true;
if (info.result == 1)
{
p2->m_bCardStatus = CARD_DISCARD;
}
if (info.result == 0 || info.result == DRAW)
{
p1->m_bCardStatus = CARD_DISCARD;
info.result = 0;
}
_LOG_INFO_("tid=[%d], %d compare card with %d, result is %d, notify the result to the players on this table" , table->id, table->CmpRInfo.p1->id, table->CmpRInfo.p2->id, table->CmpRInfo.result);
for (int i = 0; i < table->m_bMaxNum; ++i)
{
Player* player = table->player_array[i];
if (player)
{
_LOG_ERROR_("Send compare card result %d of %d and %d to player %d:" , info.result , p1->id , p2->id , player->id);
IProcess::sendCompareInfoToPlayers(table->player_array[i] , table , info.p1 , info.p2, info.result , NULL , info.cmpMoney , 0);
}
}
table->ClearCompareResultInfo();
if (table->iscanGameOver())
return table->gameOver(true);
return 0;
}
|
#ifndef _BUTTON_CONTROLLER_H
#define _BUTTON_CONTROLLER_H
#include "button.h"
// #include "game_show.h"
#include "socket_server.h"
#include "pin_io.h"
#include <sstream>
class ButtonController
{
public:
ButtonController();
~ButtonController();
void update(unsigned int delta);
void startup(PinIO* _pinio, SocketServer* _socket_server);
bool getButtonState(string name);
Button *getButton(string name);
void outputButtons();
void setButtonState(Button *btn, bool newState);
void setButtonStateByName(string name, bool newState);
void overrideButtonState(string name, bool newState);
void resetAllWasPressedReleased();
string getInfoString();
private:
PinIO* pPinIo;
// GameShow* game_show;
SocketServer* pSocketServer;
void updateWebButtonState(Button *_btn);
bool canUpdateButton(Button *btn);
void loadButtonsFromFile();
unsigned int elapsedTime;
//static const int rowPins[8];
//static const int colPins[3]; //8 columns, on a binary decoder
//settings for column pins to set various columns.
//probably should generate them at startup... but meh, hardcoding works
//static const int colOutputs[8][3];
Button buttons[8][8];
// button buttons64[64];
};
#endif
|
#include "Player.h"
#include "record/Snapshot.h"
CPlayer::CPlayer()
: m_nStatus(PS_Stopped), m_nSeekpos(-1), m_isFirst(1), m_bIsMute(0), m_position(0), m_duration(0), m_audioctx(0), m_videoctx(0), m_pVideoDecodeThread(0), m_pAudioDecodeThread(0), m_pBufferManager(0)
{
memset(this, 0, sizeof(JNIStreamerContext));
m_nBufferInterval = 100; //100ms
m_hwmode = 1; //默认是软解
}
////////////////////////////////////////////////////////////////////////////////
void CPlayer::Doinit(JNIEnv *env, jobject weak)
{
m_owner = env->NewGlobalRef(weak);
m_pAudioTrack = new CAudioTrack();
m_pVideoDecodeThread = new CVideoDecodeThread(this);
m_pAudioDecodeThread = new CAudioDecodeThread(this);
}
void CPlayer::Uninit(JNIEnv *env)
{
if( m_pHook[0] != 0 ) m_pHook[0]->Write(0); //通知结束
if( m_pHook[1] != 0 ) m_pHook[1]->Write(0); //通知结束
delete m_pAudioDecodeThread;
delete m_pVideoDecodeThread;
delete m_pAudioTrack;
if( m_pSurfaceWindow != NULL) ANativeWindow_release(m_pSurfaceWindow);
env->DeleteGlobalRef(m_owner);
}
////////////////////////////////////////////////////////////////////////////////
CBuffer *CPlayer::GetVideoSpspps(int idx, CBuffer *frame)
{
frame->GetPacket()->duration = 1;
switch(idx)
{
case 0:
{
assert(m_videoSps.empty() == false);
frame->SetSize( m_videoSps.size());
memcpy(frame->GetPacket()->data, m_videoSps.c_str(), m_videoSps.size());
return frame;
}
case 1:
{
assert(m_videoPps.empty() == false);
frame->SetSize( m_videoPps.size());
memcpy(frame->GetPacket()->data, m_videoPps.c_str(), m_videoPps.size());
return frame;
}
default:
{
frame->SetSize( m_videoSps.size() + m_videoPps.size());
uint8_t *dst = frame->GetPacket()->data;
memcpy(dst, m_videoSps.c_str(), m_videoSps.size()); dst += m_videoSps.size();
memcpy(dst, m_videoPps.c_str(), m_videoPps.size());
return frame;
}
}
}
int CPlayer::Snapshot(JNIEnv *env, jint w, jint h, char *file)
{
if( m_pHook[1] != 0 ) return 1; //snapshot
if( m_videoctx == 0 ) return 2;
const char *n = strstr(file, "://");
if( n != 0 ) file = n + 2; //skip file:/
//refix w/h
if( w <= 0 ) w = m_videoctx->width;
if( h <= 0 ) h = m_videoctx->height;
float a = (float)w / m_videoctx->width;
float b = (float)h / m_videoctx->height;
float r;
if( a > b ) {
r = b;
w = r * m_videoctx->width;
} else {
r = a;
if( a < b ) h = r * m_videoctx->height;
}
int flags = SWS_FAST_BILINEAR; //fix flags
if( r > 1.0 ) flags = SWS_AREA;
else if( r < 1.0 ) flags = SWS_POINT;
int t = 1; //only support jpg file
int codecid;
CSwsScale *pScales;
if( w != m_videoctx->width || h != m_videoctx->height )
{//scale
codecid = MEDIA_DATA_TYPE_YUV;
pScales = new CSwsScale(m_videoctx->width, m_videoctx->height, m_videoctx->pix_fmt, w, h, t==0? AV_PIX_FMT_RGBA:AV_PIX_FMT_YUVJ420P, flags);
}
else
{
if( m_videoctx->codec_id == AV_CODEC_ID_MJPEG )
{
if( t == 0 )
{
codecid = MEDIA_DATA_TYPE_RGB;
pScales = 0;
}
else
{
codecid = MEDIA_DATA_TYPE_JPG;
pScales = 0;
}
}
else
{
if( t == 0 )
{
codecid = MEDIA_DATA_TYPE_RGB;
pScales = 0;
}
else
{
codecid = MEDIA_DATA_TYPE_YUV;
pScales = new CSwsScale(m_videoctx->width, m_videoctx->height, m_videoctx->pix_fmt, w, h, AV_PIX_FMT_YUVJ420P, flags);
}
}
}
memset(m_medias + 2 * MAX_MEDIA_FMT, 0, MAX_MEDIA_FMT * sizeof(m_medias[0])); //zero rec subcribe
SetCodecidEnabled(2, codecid, true);
m_pHook[1] = new CSnapshot(this, pScales, file, t);
return 0;
}
|
#ifndef TREEFACE_VECTOR_GRAPHICS_MATERIAL_H
#define TREEFACE_VECTOR_GRAPHICS_MATERIAL_H
#include "treeface/scene/SceneGraphMaterial.h"
namespace treeface
{
class VectorGraphicsMaterial: public SceneGraphMaterial
{
public:
static const treecore::Identifier UNIFORM_LINE_WIDTH;
static const treecore::Identifier UNIFORM_SKELETON_MIN;
static const treecore::Identifier UNIFORM_SKELETON_MAX;
VectorGraphicsMaterial();
virtual ~VectorGraphicsMaterial();
protected:
treecore::String get_shader_source_addition() const noexcept override;
};
} // namespace treeface
#endif // TREEFACE_VECTOR_GRAPHICS_MATERIAL_H
|
// Created on: 1990-12-19
// Created by: Christophe MARION
// Copyright (c) 1990-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef TopLoc_MapOfLocation_HeaderFile
#define TopLoc_MapOfLocation_HeaderFile
#include <TopLoc_MapLocationHasher.hxx>
#include <NCollection_Map.hxx>
typedef NCollection_Map<TopLoc_Location,TopLoc_MapLocationHasher> TopLoc_MapOfLocation;
typedef NCollection_Map<TopLoc_Location,TopLoc_MapLocationHasher>::Iterator TopLoc_MapIteratorOfMapOfLocation;
#endif
|
//
// C++ Implementation: DialogPeer
//
// Description:
//
//
// Author: cwll <cwll2009@126.com> ,(C) 2012.02
// Jally <jallyx@163.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "DialogPeer.h"
#include "ProgramData.h"
#include "CoreThread.h"
#include "MainWindow.h"
#include "LogSystem.h"
#include "Command.h"
#include "SendFile.h"
#include "RecvFileData.h"
#include "HelpDialog.h"
#include "output.h"
#include "callback.h"
#include "support.h"
#include "utils.h"
#include "dialog.h"
extern ProgramData progdt;
extern CoreThread cthrd;
extern MainWindow mwin;
extern LogSystem lgsys;
/**
* 类构造函数.
* @param grp 好友群组信息
*/
DialogPeer::DialogPeer(GroupInfo *grp):DialogBase(grp),
torcvsize(0),rcvdsize(0)
{
ReadUILayout();
}
/**
* 类析构函数.
*/
DialogPeer::~DialogPeer()
{
/* 非常重要,必须在窗口析构之前把定时触发事件停止,不然会出现意想不到的情况 */
if(timerrcv > 0)
g_source_remove(timerrcv);
/*---------------------------------------------------------------*/
WriteUILayout();
}
/**
* 好友对话框入口.
* @param grpinf 好友群组信息
*/
void DialogPeer::PeerDialogEntry(GroupInfo *grpinf)
{
DialogPeer *dlgpr;
GtkWidget *window, *widget;
dlgpr = new DialogPeer(grpinf);
window = dlgpr->CreateMainWindow();
gtk_container_add(GTK_CONTAINER(window), dlgpr->CreateAllArea());
gtk_widget_show_all(window);
/* 将焦点置于文本输入框 */
widget = GTK_WIDGET(g_datalist_get_data(&dlgpr->widset,
"input-textview-widget"));
gtk_widget_grab_focus(widget);
/* 从消息队列中移除 */
pthread_mutex_lock(cthrd.GetMutex());
if (cthrd.MsglineContainItem(grpinf)) {
mwin.MakeItemBlinking(grpinf, FALSE);
cthrd.PopItemFromMsgline(grpinf);
}
pthread_mutex_unlock(cthrd.GetMutex());
/* delete dlgpr;//请不要这样做,此类将会在窗口被摧毁后自动释放 */
}
/**
* 更新好友信息.
* @param pal 好友信息
*/
void DialogPeer::UpdatePalData(PalInfo *pal)
{
GtkWidget *textview;
GtkTextBuffer *buffer;
GtkTextIter start, end;
textview = GTK_WIDGET(g_datalist_get_data(&widset, "info-textview-widget"));
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
gtk_text_buffer_get_bounds(buffer, &start, &end);
gtk_text_buffer_delete(buffer, &start, &end);
FillPalInfoToBuffer(buffer, pal);
}
/**
* 插入好友数据.
* @param pal 好友信息
*/
void DialogPeer::InsertPalData(PalInfo *pal)
{
//此函数暂且无须实现
}
/**
* 删除好友数据.
* @param pal 好友信息
*/
void DialogPeer::DelPalData(PalInfo *pal)
{
//此函数暂且无须实现
}
/**
* 清除本群组所有好友数据.
*/
void DialogPeer::ClearAllPalData()
{
//此函数暂且无须实现
}
/**
* 读取对话框的UI布局数据.
*/
void DialogPeer::ReadUILayout()
{
GConfClient *client;
gint numeric;
client = gconf_client_get_default();
numeric = gconf_client_get_int(client, GCONF_PATH "/peer_window_width", NULL);
numeric = numeric ? numeric : 570;
g_datalist_set_data(&dtset, "window-width", GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client, GCONF_PATH "/peer_window_height", NULL);
numeric = numeric ? numeric : 420;
g_datalist_set_data(&dtset, "window-height", GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client,
GCONF_PATH "/peer_main_paned_divide", NULL);
numeric = numeric ? numeric : 375;
g_datalist_set_data(&dtset, "main-paned-divide", GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client,
GCONF_PATH "/peer_historyinput_paned_divide", NULL);
numeric = numeric ? numeric : 255;
g_datalist_set_data(&dtset, "historyinput-paned-divide",
GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client,
GCONF_PATH "/peer_infoenclosure_paned_divide", NULL);
numeric = numeric ? numeric : 255;
g_datalist_set_data(&dtset, "infoenclosure-paned-divide",
GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client,
GCONF_PATH "/peer_enclosure_paned_divide", NULL);
numeric = numeric ? numeric : 280;
g_datalist_set_data(&dtset, "enclosure-paned-divide",
GINT_TO_POINTER(numeric));
numeric = gconf_client_get_int(client,
GCONF_PATH "/peer_file_recieve_paned_divide", NULL);
numeric = numeric ? numeric : 140;
g_datalist_set_data(&dtset, "file-receive-paned-divide",
GINT_TO_POINTER(numeric));
g_object_unref(client);
}
/**
* 保存对话框的UI布局数据.
*/
void DialogPeer::WriteUILayout()
{
GConfClient *client;
gint numeric;
client = gconf_client_get_default();
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "window-width"));
gconf_client_set_int(client, GCONF_PATH "/peer_window_width", numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "window-height"));
gconf_client_set_int(client, GCONF_PATH "/peer_window_height", numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "main-paned-divide"));
gconf_client_set_int(client, GCONF_PATH "/peer_main_paned_divide", numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"historyinput-paned-divide"));
gconf_client_set_int(client, GCONF_PATH "/peer_historyinput_paned_divide",
numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"infoenclosure-paned-divide"));
gconf_client_set_int(client, GCONF_PATH "/peer_infoenclosure_paned_divide",
numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset,"enclosure-paned-divide"));
gconf_client_set_int(client, GCONF_PATH "/peer_enclosure_paned_divide",
numeric, NULL);
numeric = GPOINTER_TO_INT(g_datalist_get_data(&dtset,"file-receive-paned-divide"));
gconf_client_set_int(client, GCONF_PATH "/peer_file_recieve_paned_divide",
numeric, NULL);
g_object_unref(client);
}
/**
* 创建主窗口.
* @return 窗口
*/
GtkWidget *DialogPeer::CreateMainWindow()
{
char buf[MAX_BUFLEN];
GtkWidget *window;
gint width, height;
PalInfo *palinfor;
char ipstr[INET_ADDRSTRLEN];
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
palinfor = (PalInfo *)grpinf->member->data;
inet_ntop(AF_INET, &palinfor->ipv4, ipstr, INET_ADDRSTRLEN);
snprintf(buf, MAX_BUFLEN, _("Talk with %s(%s) IP:%s"),
palinfor->name,palinfor->host,ipstr);
gtk_window_set_title(GTK_WINDOW(window), buf);
width = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "window-width"));
height = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "window-height"));
gtk_window_set_default_size(GTK_WINDOW(window), width, height);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_add_accel_group(GTK_WINDOW(window), accel);
widget_enable_dnd_uri(window);
g_datalist_set_data(&widset, "window-widget", window);
grpinf->dialog = window;
g_object_set_data(G_OBJECT(window),"dialog",this);
MainWindowSignalSetup(window);
g_signal_connect_swapped(GTK_OBJECT(window), "show",
G_CALLBACK(ShowDialogPeer), this);
return window;
}
/**
* 创建所有区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateAllArea()
{
GtkWidget *box;
GtkWidget *hpaned, *vpaned;
gint position;
box = gtk_vbox_new(FALSE, 0);
/* 加入菜单条 */
gtk_box_pack_start(GTK_BOX(box), CreateMenuBar(), FALSE, FALSE, 0);
/* 加入主区域 */
hpaned = gtk_hpaned_new();
g_datalist_set_data(&widset, "main-paned", hpaned);
g_object_set_data(G_OBJECT(hpaned), "position-name",
(gpointer)"main-paned-divide");
position = GPOINTER_TO_INT(g_datalist_get_data(&dtset, "main-paned-divide"));
gtk_paned_set_position(GTK_PANED(hpaned), position);
gtk_box_pack_start(GTK_BOX(box), hpaned, TRUE, TRUE, 0);
g_signal_connect(hpaned, "notify::position",
G_CALLBACK(PanedDivideChanged), &dtset);
/*/* 加入聊天历史记录&输入区域 */
vpaned = gtk_vpaned_new();
g_object_set_data(G_OBJECT(vpaned), "position-name",
(gpointer)"historyinput-paned-divide");
position = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"historyinput-paned-divide"));
gtk_paned_set_position(GTK_PANED(vpaned), position);
gtk_paned_pack1(GTK_PANED(hpaned), vpaned, TRUE, TRUE);
g_signal_connect(vpaned, "notify::position",
G_CALLBACK(PanedDivideChanged), &dtset);
gtk_paned_pack1(GTK_PANED(vpaned), CreateHistoryArea(), TRUE, TRUE);
gtk_paned_pack2(GTK_PANED(vpaned), CreateInputArea(), FALSE, TRUE);
/* 加入好友信息&附件区域 */
vpaned = gtk_vpaned_new();
g_object_set_data(G_OBJECT(vpaned), "position-name",
(gpointer)"infoenclosure-paned-divide");
position = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"infoenclosure-paned-divide"));
gtk_paned_set_position(GTK_PANED(vpaned), position);
gtk_paned_pack2(GTK_PANED(hpaned), vpaned, FALSE, TRUE);
g_signal_connect(vpaned, "notify::position",
G_CALLBACK(PanedDivideChanged), &dtset);
gtk_paned_pack1(GTK_PANED(vpaned), CreateInfoArea(), TRUE, TRUE);
gtk_paned_pack2(GTK_PANED(vpaned), CreateFileArea(), FALSE, TRUE);
return box;
}
/**
* 创建菜单条.
* @return 菜单条
*/
GtkWidget *DialogPeer::CreateMenuBar()
{
GtkWidget *menubar;
menubar = gtk_menu_bar_new();
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), CreateFileMenu());
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), CreateToolMenu());
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), CreateHelpMenu());
return menubar;
}
/**
* 创建好友信息区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateInfoArea()
{
GtkWidget *frame, *sw;
GtkWidget *widget;
GtkTextBuffer *buffer;
frame = gtk_frame_new(_("Info."));
g_datalist_set_data(&widset, "info-frame", frame);
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
gtk_container_add(GTK_CONTAINER(frame), sw);
buffer = gtk_text_buffer_new(progdt.table);
if (grpinf->member)
FillPalInfoToBuffer(buffer, (PalInfo *)grpinf->member->data);
widget = gtk_text_view_new_with_buffer(buffer);
gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(widget), FALSE);
gtk_text_view_set_editable(GTK_TEXT_VIEW(widget), FALSE);
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget), GTK_WRAP_NONE);
gtk_container_add(GTK_CONTAINER(sw), widget);
g_datalist_set_data(&widset, "info-textview-widget", widget);
return frame;
}
/**
* 创建文件菜单.
* @return 菜单
*/
GtkWidget *DialogPeer::CreateFileMenu()
{
GtkWidget *menushell, *window;
GtkWidget *menu, *menuitem;
window = GTK_WIDGET(g_datalist_get_data(&widset, "window-widget"));
menushell = gtk_menu_item_new_with_mnemonic(_("_File"));
menu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menushell), menu);
menuitem = gtk_menu_item_new_with_label(_("Attach File"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate", G_CALLBACK(AttachRegular), this);
gtk_widget_add_accelerator(menuitem, "activate", accel,
GDK_S, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
menuitem = gtk_menu_item_new_with_label(_("Attach Folder"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate", G_CALLBACK(AttachFolder), this);
gtk_widget_add_accelerator(menuitem, "activate", accel,
GDK_D, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
menuitem = gtk_menu_item_new_with_label(_("Request Shared Resources"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate",
G_CALLBACK(AskSharedFiles), grpinf);
gtk_widget_add_accelerator(menuitem, "activate", accel,
GDK_R, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
menuitem = gtk_tearoff_menu_item_new();
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
menuitem = gtk_menu_item_new_with_label(_("Close"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate",
G_CALLBACK(gtk_widget_destroy), window);
gtk_widget_add_accelerator(menuitem, "activate", accel,
GDK_W, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
g_datalist_set_data(&widset, "file-menu",menu);
return menushell;
}
/**
* 创建工具菜单.
* @return 菜单
*/
GtkWidget *DialogPeer::CreateToolMenu()
{
GtkWidget *menushell;
GtkWidget *menu, *menuitem;
menushell = gtk_menu_item_new_with_mnemonic(_("_Tools"));
menu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menushell), menu);
menuitem = gtk_menu_item_new_with_label(_("Insert Picture"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate", G_CALLBACK(InsertPicture), this);
menuitem = gtk_menu_item_new_with_label(_("Clear Buffer"));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
g_signal_connect_swapped(menuitem, "activate",
G_CALLBACK(ClearHistoryBuffer), this);
return menushell;
}
/**
* 将好友信息数据写入指定的缓冲区.
* @param buffer text-buffer
* @param pal class PalInfo
*/
void DialogPeer::FillPalInfoToBuffer(GtkTextBuffer *buffer, PalInfo *pal)
{
char buf[MAX_BUFLEN], ipstr[INET_ADDRSTRLEN];
GdkPixbuf *pixbuf;
GtkTextIter iter;
gtk_text_buffer_get_end_iter(buffer, &iter);
snprintf(buf, MAX_BUFLEN, _("Version: %s\n"), pal->version);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
if (pal->group && *pal->group != '\0')
snprintf(buf, MAX_BUFLEN, _("Nickname: %s@%s\n"), pal->name, pal->group);
else
snprintf(buf, MAX_BUFLEN, _("Nickname: %s\n"), pal->name);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
snprintf(buf, MAX_BUFLEN, _("User: %s\n"), pal->user);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
snprintf(buf, MAX_BUFLEN, _("Host: %s\n"), pal->host);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
inet_ntop(AF_INET, &pal->ipv4, ipstr, INET_ADDRSTRLEN);
if (pal->segdes && *pal->segdes != '\0')
snprintf(buf, MAX_BUFLEN, _("Address: %s(%s)\n"), pal->segdes, ipstr);
else
snprintf(buf, MAX_BUFLEN, _("Address: %s\n"), ipstr);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
if (!FLAG_ISSET(pal->flags, 0))
snprintf(buf, MAX_BUFLEN, "%s", _("Compatibility: Microsoft\n"));
else
snprintf(buf, MAX_BUFLEN, "%s", _("Compatibility: GNU/Linux\n"));
gtk_text_buffer_insert(buffer, &iter, buf, -1);
snprintf(buf, MAX_BUFLEN, _("System coding: %s\n"), pal->encode);
gtk_text_buffer_insert(buffer, &iter, buf, -1);
if (pal->sign && *pal->sign != '\0') {
gtk_text_buffer_insert(buffer, &iter, _("Signature:\n"), -1);
gtk_text_buffer_insert_with_tags_by_name(buffer, &iter,
pal->sign, -1, "sign-words", NULL);
}
if (pal->photo && *pal->photo != '\0'
&& (pixbuf = gdk_pixbuf_new_from_file(pal->photo, NULL))) {
gtk_text_buffer_insert(buffer, &iter, _("\nPhoto:\n"), -1);
//TODO 缩放多少才合适
pixbuf_shrink_scale_1(&pixbuf, 200, -1);
gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
g_object_unref(pixbuf);
}
}
/**
* 发送附件给好友
*/
void DialogPeer::BroadcastEnclosureMsg(GSList *list)
{
SendFile sfile;
GSList *plist;
/* 向选中的成员发送附件 */
plist = NULL;
plist = g_slist_append(plist, grpinf->member->data);
sfile.BcstFileInfoEntry(plist, list);
g_slist_free(plist);
}
/**
* 发送文本消息.
* @return 是否发送数据
*/
bool DialogPeer::SendTextMsg()
{
static uint32_t count = 0;
GtkWidget *textview;
GtkTextBuffer *buffer;
GtkTextIter start, end, piter, iter;
GdkPixbuf *pixbuf;
char buf[MAX_UDPLEN];
gchar *chipmsg, *ptr;
pthread_t pid;
size_t len;
MsgPara *para;
ChipData *chip;
GSList *dtlist;
/* 考察缓冲区内是否存在数据 */
textview = GTK_WIDGET(g_datalist_get_data(&widset, "input-textview-widget"));
gtk_widget_grab_focus(textview); //为下一次任务做准备
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
gtk_text_buffer_get_bounds(buffer, &start, &end);
if (gtk_text_iter_equal(&start, &end))
return false;
/* 一些初始化工作 */
buf[0] = '\0'; //缓冲区数据为空
ptr = buf;
len = 0;
dtlist = NULL; //数据链表为空
/* 获取数据 */
piter = iter = start; //让指针指向缓冲区开始位置
do {
/**
* @note 由于gtk_text_iter_forward_find_char()会跳过当前字符,
* 所以必须先考察第一个字符是否为图片.
*/
if ( (pixbuf = gtk_text_iter_get_pixbuf(&iter))) {
/* 读取图片之前的字符数据,并写入缓冲区 */
chipmsg = gtk_text_buffer_get_text(buffer, &piter, &iter, FALSE);
snprintf(ptr, MAX_UDPLEN - len, "%s%c", chipmsg, OCCUPY_OBJECT);
len += strlen(ptr);
ptr = buf + len;
g_free(chipmsg);
piter = iter; //移动 piter 到新位置
/* 保存图片 */
chipmsg = g_strdup_printf("%s" IPTUX_PATH "/%" PRIx32,
g_get_user_config_dir(), count++);
gdk_pixbuf_save(pixbuf, chipmsg, "bmp", NULL, NULL);
/* 新建一个碎片数据(图片),并加入数据链表 */
chip = new ChipData;
chip->type = MESSAGE_CONTENT_TYPE_PICTURE;
chip->data = chipmsg;
dtlist = g_slist_append(dtlist, chip);
}
} while (gtk_text_iter_forward_find_char(&iter,
GtkTextCharPredicate(giter_compare_foreach),
GUINT_TO_POINTER(ATOM_OBJECT), &end));
/* 读取余下的字符数据,并写入缓冲区 */
chipmsg = gtk_text_buffer_get_text(buffer, &piter, &end, FALSE);
snprintf(ptr, MAX_UDPLEN - len, "%s", chipmsg);
g_free(chipmsg);
/* 新建一个碎片数据(字符串),并加入数据链表 */
chip = new ChipData;
chip->type = MESSAGE_CONTENT_TYPE_STRING;
chip->data = g_strdup(buf);
dtlist = g_slist_prepend(dtlist, chip); //保证字符串先被发送
/* 清空缓冲区并发送数据 */
gtk_text_buffer_delete(buffer, &start, &end);
FeedbackMsg(dtlist);
para = PackageMsg(dtlist);
pthread_create(&pid, NULL, ThreadFunc(ThreadSendTextMsg), para);
pthread_detach(pid);
/* g_slist_foreach(dtlist, GFunc(glist_delete_foreach), CHIP_DATA); */
/* g_slist_free(dtlist); */
return true;
}
/**
* 回馈消息.
* @param dtlist 数据链表
* @note 请不要修改链表(dtlist)中的数据
*/
void DialogPeer::FeedbackMsg(const GSList *dtlist)
{
MsgPara para;
/* 构建消息封装包 */
if (grpinf->member)
para.pal = (PalInfo *)grpinf->member->data;
else
para.pal = cthrd.GetPalFromList(grpinf->grpid);
para.stype = MESSAGE_SOURCE_TYPE_SELF;
para.btype = grpinf->type;
para.dtlist = (GSList *)dtlist;
/* 交给某人处理吧 */
cthrd.InsertMsgToGroupInfoItem(grpinf, ¶);
para.dtlist = NULL; //防止参数数据被修改
}
/**
* 封装消息.
* @param dtlist 数据链表
* @return 消息封装包
*/
MsgPara *DialogPeer::PackageMsg(GSList *dtlist)
{
MsgPara *para;
para = new MsgPara;
if (!(grpinf->member))
para->pal = cthrd.GetPalFromList(grpinf->grpid);
else
para->pal = (PalInfo *)grpinf->member->data;
para->stype = MESSAGE_SOURCE_TYPE_SELF;
para->btype = grpinf->type;
para->dtlist = dtlist;
return para;
}
/**
* 图片拖拽事件响应函数.
* @param dlgpr 对话框类
* @param context the drag context
* @param x where the drop happened
* @param y where the drop happened
* @param data the received data
* @param info the info that has been registered with the target in the GtkTargetList
* @param time the timestamp at which the data was received
*/
void DialogPeer::DragPicReceived(DialogPeer *dlgpr, GdkDragContext *context,
gint x, gint y, GtkSelectionData *data,
guint info, guint time)
{
GtkWidget *widget;
GtkTextBuffer *buffer;
GtkTextIter iter;
GdkPixbuf *pixbuf;
GSList *list, *flist, *tlist;
gint position;
if (data->length <= 0 || data->format != 8) {
gtk_drag_finish(context, FALSE, FALSE, time);
return;
}
/* 获取(text-buffer)的当前插入点 */
widget = GTK_WIDGET(g_datalist_get_data(&dlgpr->widset, "input-textview-widget"));
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
g_object_get(buffer, "cursor-position", &position, NULL);
gtk_text_buffer_get_iter_at_offset(buffer, &iter, position);
/* 分离图片文件和常规文件,图片立即处理,常规文件稍候再处理 */
flist = NULL; //预置常规文件链表为空
tlist = list = selection_data_get_path(data); //获取所有文件
while (tlist) {
if ( (pixbuf = gdk_pixbuf_new_from_file((char *)tlist->data, NULL))) {
/* 既然是图片,那就立即处理吧 */
gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
g_object_unref(pixbuf);
} else {
/* 将文件路径转移至文件链表(flist) */
flist = g_slist_append(flist, tlist->data);
tlist->data = NULL;
}
tlist = g_slist_next(tlist);
}
/*/* 释放链表数据 */
g_slist_foreach(list, GFunc(g_free), NULL);
g_slist_free(list);
/* 如果文件链表有文件,那就添加为附件吧 */
if (flist) {
dlgpr->AttachEnclosure(flist);
g_slist_foreach(flist, GFunc(g_free), NULL);
g_slist_free(flist);
widget = GTK_WIDGET(g_datalist_get_data(&dlgpr->widset,
"enclosure-frame-widget"));
gtk_widget_show(widget);
}
gtk_drag_finish(context, TRUE, FALSE, time);
}
/**
* 请求获取此好友的共享文件.
* @param grpinf 好友群组信息
*/
void DialogPeer::AskSharedFiles(GroupInfo *grpinf)
{
Command cmd;
PalInfo *pal;
if (!(grpinf->member))
pal = cthrd.GetPalFromList(grpinf->grpid);
else
pal = (PalInfo *)grpinf->member->data;
cmd.SendAskShared(cthrd.UdpSockQuote(), pal, 0, NULL);
}
/**
* 插入图片到输入缓冲区.
* @param dlgpr 对话框类
*/
void DialogPeer::InsertPicture(DialogPeer *dlgpr)
{
GtkWidget *widget, *window;
GtkTextBuffer *buffer;
GtkTextIter iter;
GdkPixbuf *pixbuf;
gchar *filename;
gint position;
window = GTK_WIDGET(g_datalist_get_data(&dlgpr->widset, "window-widget"));
if (!(filename = choose_file_with_preview(
_("Please select a picture to insert the buffer"), window)))
return;
if (!(pixbuf = gdk_pixbuf_new_from_file(filename, NULL))) {
g_free(filename);
return;
}
g_free(filename);
widget = GTK_WIDGET(g_datalist_get_data(&dlgpr->widset,
"input-textview-widget"));
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
g_object_get(buffer, "cursor-position", &position, NULL);
gtk_text_buffer_get_iter_at_offset(buffer, &iter, position);
gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
g_object_unref(pixbuf);
}
/**
* 发送文本消息.
* @param para 消息参数
*/
void DialogPeer::ThreadSendTextMsg(MsgPara *para)
{
Command cmd;
GSList *tlist;
char *ptr;
int sock;
tlist = para->dtlist;
while (tlist) {
ptr = ((ChipData *)tlist->data)->data;
switch (((ChipData *)tlist->data)->type) {
case MESSAGE_CONTENT_TYPE_STRING:
/* 文本类型 */
cmd.SendMessage(cthrd.UdpSockQuote(), para->pal, ptr);
break;
case MESSAGE_CONTENT_TYPE_PICTURE:
/* 图片类型 */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
pop_error(_("Fatal Error!!\nFailed to create new socket!"
"\n%s"), strerror(errno));
exit(1);
}
cmd.SendSublayer(sock, para->pal, IPTUX_MSGPICOPT, ptr);
close(sock); //关闭网络套接口
/*/* 删除此图片 */
unlink(ptr); //此文件已无用处
break;
default:
break;
}
tlist = g_slist_next(tlist);
}
/* 释放资源 */
delete para;
}
/**
* 创建文件接收和发送区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateFileArea()
{
GtkWidget *frame, *vpaned;
gint position;
frame = gtk_frame_new(_("Enclosure."));
g_datalist_set_data(&widset, "file-enclosure-frame-widget", frame);
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
vpaned = gtk_vpaned_new();
g_object_set_data(G_OBJECT(vpaned), "position-name",
(gpointer)"enclosure-paned-divide");
position = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"enclosure-paned-divide"));
gtk_paned_set_position(GTK_PANED(vpaned), position);
g_signal_connect(vpaned, "notify::position",
G_CALLBACK(PanedDivideChanged), &dtset);
gtk_container_add(GTK_CONTAINER(frame), vpaned);
gtk_paned_pack1(GTK_PANED(vpaned),CreateFileReceiveArea(),TRUE,TRUE);
gtk_paned_pack2(GTK_PANED(vpaned),CreateFileSendArea(),FALSE,TRUE);
return frame;
}
/**
* 创建文件接收区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateFileReceiveArea()
{
GtkWidget *vpaned;
gint position;
vpaned = gtk_vpaned_new();
g_datalist_set_data(&widset, "file-receive-paned-widget", vpaned);
g_object_set_data(G_OBJECT(vpaned), "position-name",
(gpointer)"file-receive-paned-divide");
position = GPOINTER_TO_INT(g_datalist_get_data(&dtset,
"file-receive-paned-divide"));
gtk_paned_set_position(GTK_PANED(vpaned), position);
g_signal_connect(vpaned, "notify::position",
G_CALLBACK(PanedDivideChanged), &dtset);
gtk_paned_pack1(GTK_PANED(vpaned),CreateFileToReceiveArea(),TRUE,FALSE);
gtk_paned_pack2(GTK_PANED(vpaned),CreateFileReceivedArea(),TRUE,FALSE);
return vpaned;
}
/**
* 创建待接收文件区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateFileToReceiveArea()
{
GtkWidget *frame, *hbox, *vbox, *button ,*pbar, *sw, *treeview;
GtkTreeModel *model;
frame = gtk_frame_new(_("File to be receive."));
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
pbar = gtk_progress_bar_new();
g_datalist_set_data(&widset, "file-receive-progress-bar-widget", pbar);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pbar),_("Receiving progress."));
hbox = gtk_hbox_new(FALSE,1);
gtk_box_pack_start(GTK_BOX(hbox),pbar,TRUE,TRUE,0);
button = gtk_button_new_with_label(_("Accept"));
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(ReceiveFile), this);
g_datalist_set_data(&widset, "file-receive-accept-button", button);
gtk_box_pack_start(GTK_BOX(hbox),button,FALSE,TRUE,0);
button = gtk_button_new_with_label(_("Refuse"));
gtk_box_pack_start(GTK_BOX(hbox),button,FALSE,TRUE,0);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(RemoveSelectedRcv), this);
g_datalist_set_data(&widset, "file-receive-refuse-button", button);
button = gtk_button_new_with_label(_("Detail"));
gtk_box_pack_end(GTK_BOX(hbox),button,FALSE,TRUE,0);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(OpenTransDlg), NULL);
vbox = gtk_vbox_new(FALSE,0);
gtk_box_pack_start(GTK_BOX(vbox),hbox,FALSE,FALSE,0);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
model = CreateFileToReceiveModel();
g_datalist_set_data_full(&mdlset, "file-to-receive-model", model,
GDestroyNotify(g_object_unref));
treeview = CreateFileToReceiveTree(model);
g_datalist_set_data(&widset, "file-to-receive-treeview-widget", treeview);
g_object_set_data(G_OBJECT(treeview), "dialog", this);
gtk_container_add(GTK_CONTAINER(sw), treeview);
gtk_box_pack_end(GTK_BOX(vbox),sw,TRUE,TRUE,0);
gtk_container_add(GTK_CONTAINER(frame), vbox);
return frame;
}
/**
* 创建已接收文件区域.
* @return 主窗体
*/
GtkWidget *DialogPeer::CreateFileReceivedArea()
{
GtkWidget *frame, *sw, *treeview;
GtkTreeModel *model;
frame = gtk_frame_new(_("File received."));
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
model = CreateFileReceivedModel();
g_datalist_set_data_full(&mdlset, "file-received-model", model,
GDestroyNotify(g_object_unref));
treeview = CreateFileReceivedTree(model);
g_datalist_set_data(&widset, "file-received-treeview-widget", treeview);
g_object_set_data(G_OBJECT(treeview), "dialog", this);
gtk_container_add(GTK_CONTAINER(sw), treeview);
gtk_container_add(GTK_CONTAINER(frame), sw);
return frame;
}
/**
* 创建待接收文件树(FileToReceive-tree).
* @param model FileToReceive-model
* @return 待接收文件树
*/
GtkWidget *DialogPeer::CreateFileToReceiveTree(GtkTreeModel *model)
{
GtkWidget *view;
GtkTreeSelection *selection;
GtkCellRenderer *cell;
GtkTreeViewColumn *column;
view = gtk_tree_view_new_with_model(model);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), TRUE);
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
cell = gtk_cell_renderer_pixbuf_new();
column = gtk_tree_view_column_new_with_attributes("",cell,"pixbuf",0,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes(_("Source"),cell,"text",1,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
g_object_set(cell, "editable", TRUE, NULL);
column = gtk_tree_view_column_new_with_attributes(_("SaveAs"),cell,"text",2,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes(_("Size"),cell,"text",3,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
g_signal_connect_swapped(GTK_OBJECT(view), "button_press_event",
G_CALLBACK(RcvTreePopup), view);
// //增加一列用来标记拒绝接收的文件,删除时用的
// cell = gtk_cell_renderer_text_new();
// column = gtk_tree_view_column_new_with_attributes("tag",cell,"text",5,NULL);
// gtk_tree_view_column_set_visible(column,FALSE);
// gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
// g_signal_connect_swapped(GTK_OBJECT(view), "button_press_event",
// G_CALLBACK(EncosureTreePopup), this);
return view;
}
/**
* 创建待接收文件树底层数据结构.
* @return FileToReceive-model
*/
GtkTreeModel *DialogPeer::CreateFileToReceiveModel()
{
GtkListStore *model;
model = gtk_list_store_new(6, GDK_TYPE_PIXBUF, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);
return GTK_TREE_MODEL(model);
}
/**
* 创建已接收文件树(FileReceived-tree).
* @param model FileReceived-model
* @return 已接收文件树
*/
GtkWidget *DialogPeer::CreateFileReceivedTree(GtkTreeModel *model)
{
GtkWidget *view;
GtkTreeSelection *selection;
GtkCellRenderer *cell;
GtkTreeViewColumn *column;
view = gtk_tree_view_new_with_model(model);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), TRUE);
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
cell = gtk_cell_renderer_pixbuf_new();
column = gtk_tree_view_column_new_with_attributes("",cell,"pixbuf",0,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes(_("Source"),cell,"text",1,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes(_("Name"),cell,"text",2,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
cell = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes(_("Size"),cell,"text",3,NULL);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_append_column(GTK_TREE_VIEW(view), column);
g_signal_connect_swapped(GTK_OBJECT(view), "button_press_event",
G_CALLBACK(RcvTreePopup), view);
return view;
}
/**
* 创建已接收文件树底层数据结构.
* @return FileReceived-model
*/
GtkTreeModel *DialogPeer::CreateFileReceivedModel()
{
GtkListStore *model;
model = gtk_list_store_new(6, GDK_TYPE_PIXBUF, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);
return GTK_TREE_MODEL(model);
}
/**
* 显示信息/文件接收UI(是否显示信息或文件接收).
*
*/
void DialogPeer::ShowInfoEnclosure(DialogPeer *dlgpr)
{
PalInfo *palinfor;
GtkTreeModel *mdltorcv,*mdlrcvd,*mdltmp;
GSList *ecslist;
GtkWidget *widget,*hpaned,*pbar;
float progress;
GdkPixbuf *pixbuf, *rpixbuf, *dpixbuf;
FileInfo *file;
gchar *filesize,*path;
char progresstip[MAX_BUFLEN];
GtkTreeIter iter;
gint receiving;//标记是不是窗口在正传送文件时被关闭,又打开的。
receiving = 0;
/* 获取文件图标 */
rpixbuf = obtain_pixbuf_from_stock(GTK_STOCK_FILE);
dpixbuf = obtain_pixbuf_from_stock(GTK_STOCK_DIRECTORY);
//设置界面显示
palinfor = (PalInfo *)(dlgpr->grpinf->member->data);
mdltorcv = (GtkTreeModel*)g_datalist_get_data(&(dlgpr->mdlset), "file-to-receive-model");
gtk_list_store_clear(GTK_LIST_STORE(mdltorcv));
mdlrcvd = (GtkTreeModel*)g_datalist_get_data(&(dlgpr->mdlset), "file-received-model");
gtk_list_store_clear(GTK_LIST_STORE(mdlrcvd));
ecslist = cthrd.GetPalEnclosure(palinfor);
if(ecslist) {
//只要有该好友的接收文件信息(不分待接收和未接收),就显示
hpaned = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "main-paned"));
widget = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "info-frame"));
gtk_widget_hide(widget);
widget = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset),"file-enclosure-frame-widget"));
gtk_paned_pack2(GTK_PANED(hpaned), widget, FALSE, TRUE);
widget = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset),"file-receive-paned-widget"));
gtk_widget_show(widget);
//将从中心节点取到的数据向附件接收列表填充
dlgpr->torcvsize = 0;
while (ecslist) {
file = (FileInfo *)ecslist->data;
filesize = numeric_to_size(file->filesize);
switch (GET_MODE(file->fileattr)) {
case IPMSG_FILE_REGULAR:
pixbuf = rpixbuf;
break;
case IPMSG_FILE_DIR:
pixbuf = dpixbuf;
break;
default:
pixbuf = NULL;
break;
}
if(file->finishedsize < file->filesize) {
file->filepath = ipmsg_get_filename_me(file->filepath,&path);
if(file->finishedsize > 0)
receiving += 1;
mdltmp = mdltorcv;
dlgpr->torcvsize += file->filesize;
} else
mdltmp = mdlrcvd;
gtk_list_store_append(GTK_LIST_STORE(mdltmp), &iter);
gtk_list_store_set(GTK_LIST_STORE(mdltmp), &iter, 0, pixbuf,
1, file->fileown->name, 2, file->filepath,
3, filesize, 5,file, -1);
g_free(filesize);
ecslist = g_slist_next(ecslist);
}
g_slist_free(ecslist);
//设置进度条,如果接收完成重新载入待接收和已接收列表
if(dlgpr->torcvsize == 0) {
progress = 0;
snprintf(progresstip, MAX_BUFLEN, "%s", _("Receiving Progress."));
} else {
if(dlgpr->rcvdsize == 0)
snprintf(progresstip, MAX_BUFLEN,_("%s to Receive."),
numeric_to_size(dlgpr->torcvsize));
else {
progress = percent(dlgpr->rcvdsize,dlgpr->torcvsize)/100;
snprintf(progresstip, MAX_BUFLEN, _("%s Of %s Received."),
numeric_to_size(dlgpr->rcvdsize),numeric_to_size(dlgpr->torcvsize));
}
}
if(progress == 1.0){
g_source_remove(dlgpr->timerrcv);
snprintf(progresstip, MAX_BUFLEN, "%s", _("Mission Completed!"));
}
pbar = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset),
"file-receive-progress-bar-widget"));
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(pbar),progress);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pbar),progresstip);
} else {
widget = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset),
"file-receive-paned-widget"));
gtk_widget_hide(widget);
}
/* 释放文件图标 */
if (rpixbuf)
g_object_unref(rpixbuf);
if (dpixbuf)
g_object_unref(dpixbuf);
if(receiving > 0)
dlgpr->ReceiveFile(dlgpr);
}
/**
* 显示窗口事件响应函数.
*@param dlgpr 对话框类
*
*/
bool DialogPeer::UpdataEnclosureRcvUI(DialogPeer *dlgpr)
{
GtkTreeModel *model;
GtkWidget *pbar,*button;
float progress;
FileInfo *file;
GtkTreeIter iter;
GtkIconTheme *theme;
GdkPixbuf *pixbuf;
const char *statusfile;
char progresstip[MAX_BUFLEN];
/* 获取文件图标 */
theme = gtk_icon_theme_get_default();
statusfile = "tip-finish";
pixbuf = gtk_icon_theme_load_icon(theme, statusfile, MAX_ICONSIZE,
GtkIconLookupFlags(0), NULL);
//处理待接收文件界面显示
model = (GtkTreeModel*)g_datalist_get_data(&(dlgpr->mdlset), "file-to-receive-model");
if(!model) {
g_source_remove(dlgpr->timerrcv);
return FALSE;
}
dlgpr->rcvdsize = 0;
gtk_tree_model_get_iter_first(model, &iter);
do { //遍历待接收model
gtk_tree_model_get(model, &iter,5,&file, -1);
if(pixbuf && (file->finishedsize == file->filesize))
gtk_list_store_set(GTK_LIST_STORE(model), &iter,0,pixbuf,-1);
dlgpr->rcvdsize += file->finishedsize;
} while (gtk_tree_model_iter_next(model, &iter));
//设置进度条,如果接收完成重新载入待接收和已接收列表
if(dlgpr->torcvsize == 0) {
progress = 0;
snprintf(progresstip, MAX_BUFLEN, "%s", _("Receiving Progress."));
} else {
if(dlgpr->rcvdsize == 0)
snprintf(progresstip, MAX_BUFLEN,_("%s to Receive."),
numeric_to_size(dlgpr->torcvsize));
else {
progress = percent(dlgpr->rcvdsize,dlgpr->torcvsize)/100;
snprintf(progresstip, MAX_BUFLEN, _("%s Of %s Received."),
numeric_to_size(dlgpr->rcvdsize),numeric_to_size(dlgpr->torcvsize));
}
}
pbar = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset),
"file-receive-progress-bar-widget"));
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(pbar),progress);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pbar),progresstip);
if((progress == 1) || (progress == 0)){
if(progress == 1) {
g_source_remove(dlgpr->timerrcv);
dlgpr->ShowInfoEnclosure(dlgpr);
}
//只要不是在接收过程中,恢复接收和拒收按键
button = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "file-receive-accept-button"));
gtk_widget_set_sensitive(button,TRUE);
button = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "file-receive-refuse-button"));
gtk_widget_set_sensitive(button,TRUE);
} else {
//接收过程中,禁止点接收和拒收按键
button = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "file-receive-accept-button"));
gtk_widget_set_sensitive(button,FALSE);
button = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "file-receive-refuse-button"));
gtk_widget_set_sensitive(button,FALSE);
}
return TRUE;
}
/**
* 显示窗口事件响应函数.
*@param dlgpr 对话框类
*
*/
void DialogPeer::ShowDialogPeer(DialogPeer *dlgpr)
{
//这个事件有可能需要触发其它功能,暂没有直接用ShowInfoEnclosure来执行
ShowInfoEnclosure(dlgpr);
}
/**
* 接收文件函数.
*@param dlgpr 对话框类
*
*/
void DialogPeer::ReceiveFile(DialogPeer *dlgpr)
{
GtkWidget *widget;
GtkTreeModel *model;
GtkTreeIter iter;
gchar *filename, *filepath;
FileInfo *file;
pthread_t pid;
filepath = pop_save_path(GTK_WIDGET(dlgpr->grpinf->dialog));
g_free(progdt.path);
progdt.path = filepath;
/* 考察数据集中是否存在项 */
widget = GTK_WIDGET(g_datalist_get_data(&(dlgpr->widset), "file-to-receive-treeview-widget"));
model = gtk_tree_view_get_model(GTK_TREE_VIEW(widget));
if(!model)
return;
if (!gtk_tree_model_get_iter_first(model, &iter))
return;
dlgpr->torcvsize = 0;
/* 将选中的项投入文件数据接收类 */
do {
gtk_tree_model_get(model, &iter,2, &filename,
5, &file, -1);
g_free(file->filepath);
file->filepath = g_strdup_printf("%s%s%s", filepath,
*(filepath + 1) != '\0' ? "/" : "",
filename);
pthread_create(&pid, NULL, ThreadFunc(ThreadRecvFile), file);
pthread_detach(pid);
g_free(filename);
dlgpr->torcvsize += file->filesize;
} while (gtk_tree_model_iter_next(model, &iter));
dlgpr->rcvdsize = 0;
dlgpr->timerrcv = g_timeout_add(300, GSourceFunc(UpdataEnclosureRcvUI), dlgpr);
}
/**
* 接收文件数据.
* @param file 文件信息
*/
void DialogPeer::ThreadRecvFile(FileInfo *file)
{
RecvFileData rfdt(file);
rfdt.RecvFileDataEntry();
}
/**
* 获取待发送成员列表.
* @return plist 获取待发送成员列表
* 调用该函数后须free plist
*/
GSList *DialogPeer::GetSelPal()
{
PalInfo *pal;
GSList *plist;
pal = (PalInfo *)(grpinf->member->data);
plist = NULL;
plist = g_slist_append(plist, pal);
return plist;
}
/**
*从接收文件的TreeView删除选定行(待接收和已接收都用此函数).
* @param widget TreeView
*/
void DialogPeer::RemoveSelectedRcv(GtkWidget *widget)
{
GtkTreeModel *model;
GtkTreeSelection *TreeSel;
GtkTreeIter iter;
FileInfo *file;
DialogPeer *dlg;
GList *list;
dlg = (DialogPeer *)(g_object_get_data(G_OBJECT(widget),"dialog"));
model = gtk_tree_view_get_model(GTK_TREE_VIEW(widget));
//从中心结点删除
TreeSel = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
list = gtk_tree_selection_get_selected_rows(TreeSel,NULL);
if(!list)
return;
while(list) {
gtk_tree_model_get_iter(GTK_TREE_MODEL(model), &iter, (GtkTreePath *)g_list_nth(list, 0)->data);
gtk_tree_model_get(model, &iter,5,&file, -1);
cthrd.PopItemFromEnclosureList(file);
list = g_list_next(list);
}
g_list_free(list);
//从列表中删除
RemoveSelectedFromTree(widget);
//重新刷新窗口显示
dlg->ShowInfoEnclosure(dlg);
}
/**
*显示接收附件的TreeView的弹出菜单回调函数.(待接收和已接收都用此函数)
* @param widget TreeView
* @param event 事件
*/
gint DialogPeer::RcvTreePopup(GtkWidget *treeview,GdkEvent *event)
{
GtkWidget *menu,*menuitem;
GdkEventButton *event_button;
menu = gtk_menu_new();
menuitem = gtk_menu_item_new_with_label(_("Remove Selected"));
g_signal_connect_swapped(menuitem, "activate", G_CALLBACK(RemoveSelectedRcv), treeview);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
if (event->type == GDK_BUTTON_PRESS) {
event_button = (GdkEventButton *) event;
if (event_button->button == 3) {
gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
event_button->button, event_button->time);
gtk_widget_show(menuitem);
return TRUE;
}
}
return FALSE;
}
|
#ifndef PACKETS_SOCIAL
#define PACKETS_SOCIAL
#include <cstdint>
#include "Packets/PacketBaseMessage.h"
#pragma pack(push, 1)
#include "Packets/PacketBaseMessage.h"
struct MM_SC_MSN : public TS_MESSAGE
{
//has some data
static const uint16_t packetID = 5001;
};
struct MM_SC_MSN_FIND_USER : public TS_MESSAGE
{
char username[42];
static const uint16_t packetID = 5013;
};
struct MM_SC_FRIEND_REQUEST : public TS_MESSAGE
{
char uk[40];
char username[402];
static const uint16_t packetID = 5015;
};
struct BM_SC_CHAT_MESSAGE : public TS_MESSAGE
{
char sender[33];
uint8_t type; // 0 = normal chat; 3 = whisper; 5 = shout
uint16_t messagelength;
char msg[70];
static const uint16_t packetID = 2206;
};
struct BM_SC_CLAN_CREATION : public TS_MESSAGE
{
char clanname[43];
static const uint16_t packetID = 2344;
};
struct BM_SC_MATE_INFO : public TS_MESSAGE
{
uint32_t uk1;
char charname[43];
static const uint16_t packetID = 2335;
};
struct BM_SC_UPDATE_MYMATEINFO : public TS_MESSAGE
{
uint8_t age;
uint32_t zoneid;
char zoneinfo[121];
char biostr[151];
uint8_t isprivate; // 1 = private; 0 = public
uint8_t gender; // 1 = Male; 2 = Female
static const uint16_t packetID = 2262;
};
#endif
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Author: Tatparya Shankar
long long int getNumHandshakes( int numPeople )
{
long long int sum;
sum = numPeople * numPeople - numPeople * ( numPeople - 1 ) / 2;
return sum;
}
int main()
{
int numTestCases;
int scan;
int numPeople;
scan = scanf( "%d", &numTestCases );
while( numTestCases > 0 )
{
numTestCases--;
scan = scanf( "%d", &numPeople );
printf( "%lld\n", getNumHandshakes( numPeople - 1 ) );
}
return 0;
}#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Author: Tatparya Shankar
long long int getNumHandshakes( int numPeople )
{
long long int sum;
// Get sum of AP n + n-1 + n-2 + .. + 2 + 1
sum = numPeople * numPeople - numPeople * ( numPeople - 1 ) / 2;
return sum;
}
int main()
{
int numTestCases;
int scan;
int numPeople;
scan = scanf( "%d", &numTestCases );
while( numTestCases > 0 )
{
numTestCases--;
scan = scanf( "%d", &numPeople );
printf( "%lld\n", getNumHandshakes( numPeople - 1 ) );
}
return 0;
}
|
//
// Created by Zakhar on 03.04.2017.
//
#pragma once
#include <string>
#include <iostream>
void printUsage()
{
std::cout << std::endl << "Usage: ./incCD -obligatory arg [-optional arg]" << std::endl
<< std::endl
<< "-test {arg}, -t {arg}" << std::endl
<< " | arg:" << std::endl
<< " | out, o - the result of the recovery" << std::endl
<< " | runtime, rt - runtime of the recovery" << std::endl
<< " | choose what to output from the action" << std::endl
<< std::endl
<< "-algorithm {str}, -alg {str}" << std::endl
<< " | codename of the algorithm to run the recovery on" << std::endl
<< std::endl
<< "-input {str}, -in {str}" << std::endl
<< " | file name, where to take the input matrix from" << std::endl
<< std::endl
<< "-output {str}, -out {str}" << std::endl
<< " | file name, where to store the result of <test>" << std::endl
<< std::endl
<< "[-n {int}] default(0)" << std::endl
<< " | amount of rows to load from the input file" << std::endl
<< " | 0 - load all of them" << std::endl
<< std::endl
<< "[-m {int}] default(0)" << std::endl
<< " | amount of columns to load from the input file" << std::endl
<< " | 0 - load all of them" << std::endl
<< std::endl
<< "[-k {int}] default(m)" << std::endl
<< " | amount of columns of truncated decomposition to keep" << std::endl
<< " | 0 (dec) - will be set to be equal to m" << std::endl
<< " | 0 (rec) - will be automatically detected" << std::endl
<< "[-xtra {string}] default(\"\")" << std::endl
<< " | extra string to be passed to the algorithm" << std::endl
<< std::endl;
}
enum class PTestType
{
Output, Runtime, Undefined
};
int CommandLine2(
int argc, char *argv[],
PTestType &test, std::string &algoCode,
std::string &input, std::string &output, std::string &xtra,
uint64_t &n, uint64_t &m, uint64_t &k
)
{
std::string temp;
for (int i = 1; i < argc; ++i)
{
temp = argv[i];
// man request
if (temp.empty())
{
continue;
}
else if (temp == "--help" || temp == "-help" || temp == "/?")
{
printUsage();
return 1;
}
// Test type, how the algorithm is applied
else if (temp == "-test" || temp == "-t")
{
++i;
temp = argv[i];
if (temp == "out" || temp == "o")
{
test = PTestType::Output;
}
else if (temp == "runtime" || temp == "rt")
{
test = PTestType::Runtime;
}
else
{
std::cout << "Unrecognized -test argument" << std::endl;
printUsage();
return EXIT_FAILURE;
}
}
else if (temp == "-algorithm" || temp == "-alg")
{
++i;
algoCode = argv[i];
}
// in/out
else if (temp == "-input" || temp == "-in")
{
++i;
input = argv[i];
}
else if (temp == "-output" || temp == "-out")
{
++i;
output = argv[i];
}
// Dimensions to override defaults
else if (temp == "-n")
{
++i;
temp = argv[i];
n = static_cast<uint64_t>(stoll(temp));
}
else if (temp == "-m")
{
++i;
temp = argv[i];
m = static_cast<uint64_t>(stoll(temp));
}
else if (temp == "-k")
{
++i;
temp = argv[i];
k = static_cast<uint64_t>(stoll(temp));
}
else if (temp == "-xtra")
{
++i;
xtra = argv[i];
}
else
{
std::cout << "Unrecognized CLI parameter" << std::endl;
printUsage();
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
|
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i,a[3000],x,n,flag;
while(cin>>n)
{
flag=0;
for(i=0;i<n;i++)
{
cin>>a[i];
}
x=(n*(n-1))/2;
for(i=1;i<n;i++)
{
x-=abs(a[i]-a[i-1]);
if(abs(a[i]-a[i-1])==0)
{flag=1; break;}
}
if(x==0&&flag!=1)
cout<<"Jolly"<<endl;
else cout<<"Not jolly"<<endl;
}
return 0;
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
begin = ofPoint(100,300);
end = ofPoint(900,500);
num = 10;
for (int i=0;i< num; i++){
Car temp;
cars.push_back(temp);
cars[i].init();
}
}
//--------------------------------------------------------------
void ofApp::update(){
for (int i=0;i< num; i++){
cars[i].follow(begin, end);
// cars[i].seek(end);
cars[i].update(begin, end);
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(50);
ofSetColor(0);
ofSetLineWidth(3);
ofDrawLine(begin, end);
for (int i=0;i< num; i++){
ofSetColor(255, 0, 0);
cars[i].draw();
}
// path.setMode(ofPath::POLYLINES);
//
// path.arc( 50 + 20, 50 + 20, 40 + 10, 40 + 10, 0, 360);
// path.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
// Copyright (c) 2012 Maciej Brodowicz
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config/defines.hpp>
#if defined(DOXYGEN)
/// Returns the GCC version pika is compiled with. Only set if compiled with GCC.
# define PIKA_GCC_VERSION
/// Returns the Clang version pika is compiled with. Only set if compiled with
/// Clang.
# define PIKA_CLANG_VERSION
/// Returns the Intel Compiler version pika is compiled with. Only set if
/// compiled with the Intel Compiler.
# define PIKA_INTEL_VERSION
/// This macro is set if the compilation is with MSVC.
# define PIKA_MSVC
/// This macro is set if the compilation is with Mingw.
# define PIKA_MINGW
/// This macro is set if the compilation is for Windows.
# define PIKA_WINDOWS
#else
// clang-format off
#if defined(__GNUC__)
// macros to facilitate handling of compiler-specific issues
# define PIKA_GCC_VERSION (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
# define PIKA_GCC_DIAGNOSTIC_PRAGMA_CONTEXTS 1
# undef PIKA_CLANG_VERSION
# undef PIKA_INTEL_VERSION
#else
# undef PIKA_GCC_VERSION
#endif
#if defined(__clang__)
# define PIKA_CLANG_VERSION \
(__clang_major__*10000 + __clang_minor__*100 + __clang_patchlevel__)
# undef PIKA_INTEL_VERSION
#else
# undef PIKA_CLANG_VERSION
#endif
#if defined(__INTEL_COMPILER)
# define PIKA_INTEL_VERSION __INTEL_COMPILER
# if defined(_WIN32) || (_WIN64)
# define PIKA_INTEL_WIN PIKA_INTEL_VERSION
// suppress a couple of benign warnings
// template parameter "..." is not used in declaring the parameter types of
// function template "..."
# pragma warning disable 488
// invalid redeclaration of nested class
# pragma warning disable 1170
// decorated name length exceeded, name was truncated
# pragma warning disable 2586
# endif
#else
# undef PIKA_INTEL_VERSION
#endif
#if defined(_MSC_VER)
# define PIKA_WINDOWS
# define PIKA_MSVC _MSC_VER
# define PIKA_MSVC_WARNING_PRAGMA
# if defined(__NVCC__)
# define PIKA_MSVC_NVCC
# endif
# define PIKA_CDECL __cdecl
#endif
#if defined(__MINGW32__)
# define PIKA_WINDOWS
# define PIKA_MINGW
#endif
// Detecting CUDA compilation mode
// Detecting nvhpc
// The CUDA version will also be defined so we end this block with with #endif,
// not #elif
#if defined(__NVCOMPILER)
# define PIKA_NVHPC_VERSION (__NVCOMPILER_MAJOR__ * 10000 + __NVCOMPILER_MINOR__ * 100 + __NVCOMPILER_PATCHLEVEL__)
#endif
// Detecting NVCC/CUDA
#if defined(__NVCC__) || defined(__CUDACC__)
// NVCC build version numbers can be high (without limit?) so we leave it out
// from the version definition
# define PIKA_CUDA_VERSION (__CUDACC_VER_MAJOR__*100 + __CUDACC_VER_MINOR__)
# define PIKA_COMPUTE_CODE
# if defined(__CUDA_ARCH__)
// nvcc compiling CUDA code, device mode.
# define PIKA_COMPUTE_DEVICE_CODE
# endif
// Detecting Clang CUDA
#elif defined(__clang__) && defined(__CUDA__)
# define PIKA_COMPUTE_CODE
# if defined(__CUDA_ARCH__)
// clang compiling CUDA code, device mode.
# define PIKA_COMPUTE_DEVICE_CODE
# endif
// Detecting HIPCC
#elif defined(__HIPCC__)
# include <hip/hip_version.h>
# define PIKA_HIP_VERSION HIP_VERSION
# if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated-copy"
# pragma clang diagnostic ignored "-Wunused-parameter"
# endif
// Not like nvcc, the __device__ __host__ function decorators are not defined
// by the compiler
# include <hip/hip_runtime_api.h>
# if defined(__clang__)
# pragma clang diagnostic pop
# endif
# define PIKA_COMPUTE_CODE
# if defined(__HIP_DEVICE_COMPILE__)
// hipclang compiling CUDA/HIP code, device mode.
# define PIKA_COMPUTE_DEVICE_CODE
# endif
#endif
#if !defined(PIKA_COMPUTE_DEVICE_CODE)
# define PIKA_COMPUTE_HOST_CODE
#endif
#if defined(PIKA_COMPUTE_CODE)
#define PIKA_DEVICE __device__
#define PIKA_HOST __host__
#define PIKA_CONSTANT __constant__
#else
#define PIKA_DEVICE
#define PIKA_HOST
#define PIKA_CONSTANT
#endif
#define PIKA_HOST_DEVICE PIKA_HOST PIKA_DEVICE
#if defined(__NVCC__)
#define PIKA_NVCC_PRAGMA_HD_WARNING_DISABLE #pragma hd_warning_disable
#else
#define PIKA_NVCC_PRAGMA_HD_WARNING_DISABLE
#endif
#if !defined(PIKA_CDECL)
#define PIKA_CDECL
#endif
#if defined(PIKA_HAVE_SANITIZERS)
# if defined(__has_feature)
# if __has_feature(address_sanitizer)
# define PIKA_HAVE_ADDRESS_SANITIZER
# endif
# elif defined(__SANITIZE_ADDRESS__) // MSVC defines this
# define PIKA_HAVE_ADDRESS_SANITIZER
# endif
#endif
// clang-format on
#endif
|
#ifndef ITENS_H
#define ITENS_H
class Item
{
public:
SDL_Surface* imagem;
SDL_Rect quadro, posicao;
Mix_Chunk* efeito;
int hp;
int mp;
int xp;
int lvl;
int atk;
int def;
char Nome[10];
};
#endif
|
//
/*
By:Luckyblock
有下列 状态之间可以进行转移:
*/
#include<cstdio>
#include<ctype.h>
#define ll long long
const int MARX = 110;
//=============================================================
int n,m,k, sum[MARX][3];
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
//=============================================================
signed main()
{
n = read(),m = read(), k = read();
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m ; j ++)
{
int tmp = read();
sum[i][j] = sum[i][j-1] + tmp;
}
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
ll power(ll a, ll n) {
if (n == 1) return a;
ll b = power(a, n >> 1);
ll res = (b * b) % mod;
if (n & 1) res = (res * a) % mod;
return res;
}
ll divmod(ll a, ll b) { // a div b = a * b^(p-2)
b = power(b, mod - 2);
return (a * b) % mod;
}
int main() {
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct zaznam
{
char kategoria[52];
char znacka[52];
char predajca[102];
int cena;
int vyrobene;
char stav[202];
struct zaznam *next;
};
void nacitaj(struct zaznam **zaciatok, FILE *f, int *pocet_zaznamov)
{
struct zaznam *aktualny=NULL;
if((f=fopen("auta.txt","r"))==NULL)
{printf("Zaznamy neboli nacitane.\n");
exit(0);}
(*pocet_zaznamov)=0;
while ((aktualny=(*zaciatok)) != NULL)
{
(*zaciatok)=(*zaciatok)->next;
free(aktualny);
}
aktualny=(*zaciatok);
char s[202];
fseek(f,0,SEEK_SET);
while((fgets(s,202,f))!=NULL)
{
struct zaznam* novy_zaznam = (struct zaznam*) malloc(sizeof(struct zaznam));
(*pocet_zaznamov)++;
fgets(s,202,f);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->kategoria,s);
fgets(s,202,f);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->znacka,s);
fgets(s,202,f);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->predajca,s);
fgets(s,202,f);
novy_zaznam->cena=atoi(s);
fgets(s,202,f);
novy_zaznam->vyrobene=atoi(s);
fgets(s,202,f);
if(s[strlen(s)]=='\n')s[strlen(s)-1]='\0';
strcpy(novy_zaznam->stav,s);
novy_zaznam->next=NULL;
if((*zaciatok)==NULL)
{
(*zaciatok)=novy_zaznam;
aktualny=(*zaciatok);
}
else
{
aktualny->next=novy_zaznam;
aktualny=aktualny->next;
}
}
printf("Nacitalo sa %d zaznamov.\n", (*pocet_zaznamov));
}
void pridaj(struct zaznam **zaciatok, int *pocet_zaznamov)
{
int poz,i=1;
char s[202];
if((*pocet_zaznamov)==0) *zaciatok=(struct zaznam*) malloc(sizeof(struct zaznam));
struct zaznam* aktualny=(*zaciatok);
scanf("%d",&poz);
if(poz>0)
{
if(poz==1)
{
struct zaznam* novy_zaznam = (struct zaznam*) malloc(sizeof(struct zaznam));
fgets(s,200,stdin);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->kategoria,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->znacka,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->predajca,s);
scanf("%d",&novy_zaznam->cena);
scanf("%d",&novy_zaznam->vyrobene);
fgets(s,200,stdin);
fgets(s,200,stdin);
if(s[strlen(s)]=='\n')s[strlen(s)-1]='\0';
strcpy(novy_zaznam->stav,s);
novy_zaznam->next=(*zaciatok);
(*zaciatok)=novy_zaznam;
(*pocet_zaznamov)++;
//printf("Zaznam pridany na poziciu %d \n",i);
}
else
{
while(aktualny!=NULL)
{
if(poz>(*pocet_zaznamov))
{
if((*pocet_zaznamov)<1)
{
struct zaznam* novy_zaznam = (struct zaznam*) malloc(sizeof(struct zaznam));
fgets(s,200,stdin);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->kategoria,s);
printf("%s",novy_zaznam->kategoria);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->znacka,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->predajca,s);
scanf("%d",&novy_zaznam->cena);
scanf("%d",&novy_zaznam->vyrobene);
fgets(s,200,stdin);
fgets(s,200,stdin);
if(s[strlen(s)]=='\n')s[strlen(s)-1]='\0';
strcpy(novy_zaznam->stav,s);
//novy_zaznam->next=NULL;
novy_zaznam->next=(*zaciatok);
(*zaciatok)=novy_zaznam;
(*zaciatok)->next=NULL;
(*pocet_zaznamov)++;
break;
}
aktualny = (*zaciatok);
while(aktualny->next!=NULL)
aktualny=aktualny->next;
struct zaznam* novy_zaznam = (struct zaznam*) malloc(sizeof(struct zaznam));
fgets(s,200,stdin);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->kategoria,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->znacka,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->predajca,s);
scanf("%d",&novy_zaznam->cena);
scanf("%d",&novy_zaznam->vyrobene);
fgets(s,200,stdin);
fgets(s,200,stdin);
if(s[strlen(s)]=='\n')s[strlen(s)-1]='\0';
strcpy(novy_zaznam->stav,s);
novy_zaznam->next=aktualny->next;
aktualny->next=novy_zaznam;
(*pocet_zaznamov)++;
//printf("Zaznam pridany na poziciu %d \n",(*pocet_zaznamov));
break;
}
if((poz-1)==i++)
{
struct zaznam* novy_zaznam = (struct zaznam*) malloc(sizeof(struct zaznam));
fgets(s,200,stdin);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->kategoria,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->znacka,s);
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
strcpy(novy_zaznam->predajca,s);
scanf("%d",&novy_zaznam->cena);
scanf("%d",&novy_zaznam->vyrobene);
fgets(s,200,stdin);
fgets(s,200,stdin);
if(s[strlen(s)]=='\n')s[strlen(s)-1]='\0';
strcpy(novy_zaznam->stav,s);
novy_zaznam->next=aktualny->next;
aktualny->next=novy_zaznam;
(*pocet_zaznamov)++;
//printf("Zaznam pridany na poziciu %d \n",i);
break;
}
aktualny=aktualny->next;
}
}
}
}
void vymaz_zaznam(struct zaznam **zaciatok, int *pocet_zaznamov)
{
char podstring[102], hlavny[102];
int vymazane=0;
struct zaznam* pred = *zaciatok;
struct zaznam* aktualny;
if (*zaciatok == NULL) return;
fgets(podstring, 100, stdin);
fgets(podstring, 100, stdin);
podstring[strlen(podstring)-1]='\0';
strupr(podstring);
while(strstr(strupr(strcpy(hlavny,(*zaciatok)->znacka)),podstring)!=NULL)
{
*zaciatok=(*zaciatok)->next;
free(pred);
(*pocet_zaznamov)--;
vymazane++;
}
pred=(*zaciatok);
aktualny=pred->next;
while (aktualny != NULL) {
strcpy(hlavny,aktualny->znacka);
strupr(hlavny);
if(strstr(hlavny,podstring))
{
pred->next=aktualny->next; // Will be NULL at the end of the list.
free(aktualny);
aktualny=pred->next;
(*pocet_zaznamov)--;
vymazane++;
}
else
{
pred=aktualny;
aktualny=aktualny->next;
}
}
printf("Vymazalo sa %d zaznamov.\n", vymazane);
}
void h(struct zaznam *zaznam)
{
struct zaznam *aktualny=zaznam;
int i=0, wish, check=0;
char podstring[102], hlavny[102];
fgets(podstring, 100, stdin);
fgets(podstring, 100, stdin);
podstring[strlen(podstring)-1]='\0';
strupr(podstring);
scanf("%d",&wish);
while (aktualny != NULL)
{
strcpy(hlavny,aktualny->znacka);
strupr(hlavny);
if(strcmp(hlavny,podstring)==0)
if(wish>=(aktualny->cena))
{
printf("%d.\n", ++i);
printf("kategoria: %s\n", aktualny->kategoria);
printf("znacka: %s\n", aktualny->znacka);
printf("predajca: %s\n", aktualny->predajca);
printf("cena: %d\n", aktualny->cena);
printf("rok_vyroby: %d\n", aktualny->vyrobene);
printf("stav_vozidla: %s\n", aktualny->stav);
check=1;
}
aktualny = aktualny->next;
}
if(check==0)printf("V ponuke nie su pozadovane auta\n");
}
void a(struct zaznam **zaznam)
{
struct zaznam *aktualny=(*zaznam);
int i=0, rok, upravene=0;
char podstring[102], hlavny[102];
fgets(podstring, 100, stdin);
fgets(podstring, 100, stdin);
podstring[strlen(podstring)-1]='\0';
strupr(podstring);
scanf("%d",&rok);
while (aktualny != NULL)
{
strcpy(hlavny,aktualny->znacka);
strupr(hlavny);
if(strcmp(hlavny,podstring)==0)
{
if(rok==(aktualny->vyrobene))
{
aktualny->cena-=100;
upravene++;
if(aktualny->cena<=0) aktualny->cena=0;
}
}
aktualny = aktualny->next;
}
printf("Aktualizovalo sa %d zaznamov\n", upravene);
}
void vypis(struct zaznam *zaciatok)
{
struct zaznam *aktualny=zaciatok;
int i=0;
while (aktualny != NULL)
{
printf("%d.\n", ++i);
printf("kategoria: %s\n", aktualny->kategoria);
printf("znacka: %s\n", aktualny->znacka);
printf("predajca: %s\n", aktualny->predajca);
printf("cena: %d\n", aktualny->cena);
printf("rok_vyroby: %d\n", aktualny->vyrobene);
printf("stav_vozidla: %s\n", aktualny->stav);
aktualny = aktualny->next;
}
printf("\n");
}
void ukonci(struct zaznam *zaciatok, FILE *f, int *w)
{
struct zaznam *aktualny = NULL;
while ((aktualny = zaciatok) != NULL)
{
zaciatok = zaciatok->next;
free(aktualny);
}
if(f!=NULL)
fclose(f);
*w=0;
}
int main()
{
struct zaznam *zaciatok = NULL;
FILE *f=NULL;
char hs[5];
int w=1, pocet_zaznamov=0;
while(w==1)
{
scanf("%s",hs);
if(hs[0]=='n') nacitaj(&zaciatok, f, &pocet_zaznamov);
if(hs[0]=='p') pridaj(&zaciatok, &pocet_zaznamov);
if(hs[0]=='v') vypis(zaciatok);
if(hs[0]=='h') h(zaciatok);
if(hs[0]=='a') a(&zaciatok);
if(hs[0]=='z') vymaz_zaznam(&zaciatok, &pocet_zaznamov);
if(hs[0]=='k') ukonci(zaciatok,f,&w);
}
return 0;
}
|
// Copyright 2017 Google Inc. All rights reserved.
//
// 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 FIREBASE_COCOS_CLASSES_FIREBASE_STORAGE_SCENE_H_
#define FIREBASE_COCOS_CLASSES_FIREBASE_STORAGE_SCENE_H_
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "FirebaseCocos.h"
#include "FirebaseScene.h"
#include "firebase/auth.h"
#include "firebase/storage.h"
#include "firebase/future.h"
#include "firebase/util.h"
// The size of the byte buffer that data will be written to.
static const size_t kBufferSize = 1024;
class StorageListener : public firebase::storage::Listener {
public:
virtual ~StorageListener() {}
/// Called whenever a transferred is paused.
void OnPaused(firebase::storage::Controller* controller) override;
/// Called repeatedly as a transfer is in progress.
void OnProgress(firebase::storage::Controller* controller) override;
void set_scene(FirebaseScene* scene) { scene_ = scene; }
private:
FirebaseScene* scene_;
};
class FirebaseStorageScene : public FirebaseScene {
public:
static cocos2d::Scene *createScene();
bool init() override;
void update(float delta) override;
void menuCloseAppCallback(cocos2d::Ref *pSender) override;
CREATE_FUNC(FirebaseStorageScene);
private:
/// An enum that tracks what the operations the app should be keeping track
/// of. First the app initializes the library, then it logs in using Firebase
/// Authentication, and then it listens for reads or writes to the storage.
enum State {
kStateInitialize,
kStateLogin,
kStateRun,
};
/// The update loop to run while initializing the app.
State updateInitialize();
/// The update loop to run while logging in.
State updateLogin();
/// The update loop to run once all setup is complete.
State updateRun();
/// Tracks the current state of the app through its setup and main loop.
State state_;
/// The ModuleInitializer is a utility class to make initializing multiple
/// Firebase libraries easier.
firebase::ModuleInitializer initializer_;
/// Firebase Auth, used for logging into Firebase.
firebase::auth::Auth* auth_;
/// Firebase Storage, the entry point to all storage operations.
firebase::storage::Storage* storage_;
/// A byte buffer for Firebase Storage to write to.
char byte_buffer_[kBufferSize];
/// A listener that responds to PutBytes and GetBytes progress.
StorageListener listener_;
/// A future that completes when the DataSnapshot for a query is received.
firebase::Future<size_t> get_bytes_future_;
/// A future that completes when a databse write is complete.
firebase::Future<firebase::storage::Metadata> put_bytes_future_;
/// A text field where a storage key string may be entered.
cocos2d::ui::TextField* key_text_field_;
/// A text field where a storage value string may be entered.
cocos2d::ui::TextField* value_text_field_;
/// A button that queries the value given by the key text field.
cocos2d::ui::Button* get_bytes_button_;
/// A button that sets the key to the value, given by the text fields.
cocos2d::ui::Button* put_bytes_button_;
};
#endif // FIREBASE_COCOS_CLASSES_FIREBASE_STORAGE_SCENE_H_
|
#include "stdafx.h"
#include "GameObject.h"
#include "GameObjectManager.h"
|
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cstring>
#include "BivariatePolynomial.h"
using namespace std;
void BivariatePolynomial::InitDegs() //find polynomial y, x degrees
{
this->degy = 0;
bool foundx=false,foundy=false;
this->degx = 0;
for (int i = matrixDimension -1; i >=0 ; --i) {
for(int j=matrixDimension-1;j>=0 ; j--)
if(this->MatrixRepresentation[i][j]!=0) //find the biggest power of y
{
this->degy = i;
foundx = true;
break;
}
if(foundx)
break;
}
for (int i = matrixDimension-1; i >=0 ; --i) { //find the biggest power of x
for(int j=matrixDimension-1;j>=0 ; j--)
if(this->MatrixRepresentation[j][i]!=0)
{
foundy = true;
this->degx = i;
break;
}
if(foundy)
break;
}
}
void BivariatePolynomial::Print() //Print polynomial
{
cout<<"DEGY : "<<this->degy<<endl<<"DEGX : "<<this->degx<<endl; //print degree of y, degree of x
for(int i=0;i < matrixDimension;i++)
{
for (int j = 0; j < matrixDimension; ++j)
{
cout << this->MatrixRepresentation[j][i]<<" ";
}
cout<<endl;
}
}
BivariatePolynomial::BivariatePolynomial(int sD, double ** P){
matrixDimension = sD + 1;
this->MatrixRepresentation = new double*[matrixDimension];
for (int i = 0; i < matrixDimension; ++i) {
this->MatrixRepresentation[i] = new double[matrixDimension];
for (int j = 0; j < matrixDimension; ++j) {
this->MatrixRepresentation[i][j] = P[i][j];
}
}
InitDegs();
}
BivariatePolynomial::BivariatePolynomial(char polstr[], int sD)
{
matrixDimension = sD + 1;
this->MatrixRepresentation = new double*[matrixDimension];
for (int i = 0; i < matrixDimension; ++i) {
this->MatrixRepresentation[i] = new double[matrixDimension];
for (int j = 0; j < matrixDimension; ++j) {
this->MatrixRepresentation[i][j] = 0; //initialize matrix elements (== 0)
}
}
Parse(polstr); //parse the polynomial
InitDegs(); //find the degrees
}
BivariatePolynomial::BivariatePolynomial(int sD) //Create random polynomial
{
srand (time(NULL)+rand()%10000);
matrixDimension = sD + 1;
this->MatrixRepresentation = new double*[matrixDimension];
for (int i = 0; i < matrixDimension; ++i) {
this->MatrixRepresentation[i] = new double[matrixDimension];
for (int j = 0; j < matrixDimension; ++j) {
this->MatrixRepresentation[i][j] = (rand()%100) - 50; //Matrix element range (-50,50)
}
}
InitDegs(); //Find the degrees
}
void BivariatePolynomial::Parse(char polstr[])
{
if(this->MatrixRepresentation == NULL)
{
perror("Matrix is null"); //Empty Matrix
return;
}
int col=0,row=0,j=0;
double coef = 1.0;
bool isPositive = true;
if(polstr[0] == '-') { //zero power coeficient case
isPositive = false;
j++;
}
if(isPositive)
this->MatrixRepresentation[0][0] = getDoubleCoefFromPolynomial(j, polstr);
else
this->MatrixRepresentation[0][0] = -getDoubleCoefFromPolynomial(j, polstr);
int choice = 0;
int i = j;
while(i <= strlen(polstr)){
col = 0;
row = 0;
if (polstr[i] == '+' || polstr[i] == '-') {
isPositive = polstr[i] == '+' ? true : false; //find if coef is positive or negative
i++;
coef = getDoubleCoefFromPolynomial(i, polstr); //reads the coeficient
choice = 0;
ParsePolynomialBody(i, polstr, 'x', 'y', col, row, choice, coef); //parse either with *x first
ParsePolynomialBody(i, polstr, 'y', 'x', row, col, choice, coef); //or with *y first
if (isPositive)
this->MatrixRepresentation[row][col] = coef;
else
this->MatrixRepresentation[row][col] = -coef;
}
else
{
i++;
}
}
}
void BivariatePolynomial::ParsePolynomialBody(int & i, char * polstr, char first, char second, int & firstCoord, int & secondCoord, int & choice, double coef)
//parsing method
{
if(choice == 1) //if you chose another method before that return
return;
if(polstr[i + 1] == second || (polstr[i + 2] == second && coef == 1.0)) //case we arent in the correct call
return;
if (polstr[i + 1] == '*' || coef == 1) {
if(coef == 1 && polstr[i+1] != '*') //case we have x*y and not 1*x*y
i--;
if (polstr[i + 2] == first) {
choice = 1;
if (polstr[i + 3] == '^') {
if(!consume(polstr, i, 4))
return; //no of chars consumed
firstCoord = getIntCoefFromPolynomial(i, polstr);
if (polstr[i + 1] == '*') {
if (polstr[i + 2] == second) {
if (polstr[i + 3] == '^') {
if(!consume(polstr, i, 4))
return;
secondCoord = getIntCoefFromPolynomial(i, polstr);
}
else
{
secondCoord = 1;
if(!consume(polstr, i, 3))
return;
}
}
}
}
else {
if(!consume(polstr, i, 3))
return;
firstCoord = 1;
if (polstr[i] == '*') {
if (polstr[i + 1] == second) {
if (polstr[i + 2] == '^') {
if(!consume(polstr, i, 3))
return;
secondCoord = getIntCoefFromPolynomial(i, polstr); //no of chars consumed
}
else
{
secondCoord = 1;
if(!consume(polstr, i, 2))
return;
}
}
}
}
}
}
}
bool BivariatePolynomial::consume(char * str, int & pos, int numChars)
{
for (int i = 0; i < numChars; ++i) {
if(str[pos] == '\0')
return false;
pos++;
}
return true;
}
int BivariatePolynomial::getIntCoefFromPolynomial(int & pos, char * polstr)
{
int count = 0;
if(!isdigit(polstr[pos]))
{
pos += count - 1;
return 1; //if no digit return 1
}
char * strCoef;
while (isdigit(polstr[pos + count])) {
count++;
}
strCoef = new char[count+1];
strCoef[count] = '\0';
count = 0;
while (isdigit(polstr[pos + count])) { //else read the digits one by one and return them as an int
strCoef[count] = polstr[pos + count];
count++;
}
pos +=count-1;
int k = atoi(strCoef);
delete []strCoef;
return k;
}
double BivariatePolynomial::getDoubleCoefFromPolynomial(int & pos, char * polstr)
{
int count = 0;
if(!isdigit(polstr[pos]))
{
pos += count - 1;
return 1; //if no digit return 1
}
char * strCoef;
while (isdigit(polstr[pos + count]) || polstr[pos + count] == '.') {
count++;
if(polstr[pos + count] == 'e') {
count++;
if (polstr[pos + count] == '-' ||
polstr[pos + count] == '+')
count++;
}
}
strCoef = new char[count+1];
strCoef[count] = '\0';
count = 0;
while (isdigit(polstr[pos + count]) || polstr[pos + count] == '.') { //else read the digits one by one and return them as an int
strCoef[count] = polstr[pos + count];
count++;
if(polstr[pos + count] == 'e') {
count++;
if (polstr[pos + count] == '-' ||
polstr[pos + count] == '+')
count++;
}
}
pos +=count-1;
double k = atof(strCoef);
delete []strCoef;
return k;
}
BivariatePolynomial::~BivariatePolynomial()
{
delete []this->MatrixRepresentation;
}
double BivariatePolynomial::exp(double num, int power) //compute (num)^(power)
{
if(power == 0)
return 1;
double first = num;
for (int i = 0; i < power - 1; ++i) {
num *= first;
}
return num;
}
double BivariatePolynomial::backSubstituteXandY(double x, double y) //substitude x,y in polynomial
{
double sum = 0;
for (int i = 0; i < this->degy + 1; ++i) {
for (int j = 0; j < this->degx + 1; ++j) {
if(this->MatrixRepresentation[i][j] != 0)
sum += this->MatrixRepresentation[i][j]*(exp(y, i) * exp(x, j));
}
}
return sum;
}
Polynomial * BivariatePolynomial::backSubstitute(double xy, char hiddenVar) //substitude x,y in polynomial
{
int size, hiddenSize;
// cout<<"bivariate"<<endl;
// this->Print();
// cout<<endl;
if(hiddenVar == 'x')
{
size = this->degy + 1;
hiddenSize = this->degx + 1;
}
else
{
size = this->degx + 1;
hiddenSize = this->degy + 1;
}
double matrix[size];
double sum = 0;
for (int i = 0; i < size; ++i) {
sum = 0;
for (int j = 0; j < hiddenSize; ++j) {
if(hiddenVar == 'x')
{
sum += this->MatrixRepresentation[i][j] * exp(xy, j);
}
else
{
// cout<<sum<<" + "<<this->MatrixRepresentation[j][i]<<" * "<<exp(xy,j) <<" = ";
sum += this->MatrixRepresentation[j][i] * exp(xy, j);
// cout<<sum<<endl;
}
}
// cout<<endl;
matrix[i] += sum;
}
Polynomial * retPol = new Polynomial(size - 1, matrix);
return retPol;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* perarne@opera.com
*
*/
#include "core/pch.h"
#include "modules/history/direct_history.h"
#include "modules/widgets/OpEdit.h"
#include "modules/logdoc/logdoc_util.h"
#include "modules/prefs/prefsmanager/collections/pc_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/url/url_socket_wrapper.h"
#include "modules/dragdrop/dragdrop_manager.h"
#include "modules/dragdrop/dragdrop_data_utils.h"
#include "adjunct/desktop_pi/DesktopOpSystemInfo.h"
#include "adjunct/quick/widgets/OpAddressDropDown.h"
#include "adjunct/quick/controller/FavoritesOverlayController.h"
#include "adjunct/quick/controller/AddressbarOverlayController.h"
#include "adjunct/quick/dialogs/PasswordDialog.h"
#include "adjunct/quick/managers/FavIconManager.h"
#include "adjunct/quick/managers/SpeedDialManager.h"
#include "adjunct/quick/menus/DesktopMenuHandler.h"
#include "adjunct/quick/models/HistoryAutocompleteModel.h"
#include "adjunct/quick/widgets/OpProgressField.h"
#include "adjunct/quick/widgets/OpTrustAndSecurityButton.h"
#include "adjunct/quick/widgets/FavoritesCompositeListener.h"
#include "adjunct/quick/widgets/URLFavMenuButton.h"
#include "adjunct/quick_toolkit/widgets/OpToolbar.h"
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/search_engine/WordHighlighter.h"
#include "modules/locale/oplanguagemanager.h"
#include "adjunct/quick/models/Bookmark.h"
#include "adjunct/quick/windows/BrowserDesktopWindow.h"
#include "adjunct/quick/managers/DesktopSecurityManager.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "adjunct/quick/managers/AnimationManager.h"
#include "adjunct/desktop_util/skin/SkinUtils.h"
#include "adjunct/desktop_util/string/i18n.h"
#include "adjunct/desktop_util/string/stringutils.h"
#include "adjunct/desktop_util/widget_utils/WidgetUtils.h"
#ifdef QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
# include "adjunct/quick_toolkit/widgets/OpPage.h"
#endif // QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
#include "adjunct/desktop_util/string/stringutils.h"
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
#include "adjunct/desktop_util/search/searchenginemanager.h"
#endif // DESKTOP_UTIL_SEARCH_ENGINES
#ifdef ENABLE_USAGE_REPORT
#include "adjunct/quick/usagereport/UsageReport.h"
#endif
#ifdef _MACINTOSH_
#include "modules/skin/OpSkinManager.h"
#endif // _MACINTOSH_
#ifdef EXTENSION_SUPPORT
#include "modules/gadgets/OpGadgetManager.h"
#endif
#include "adjunct/quick/widgets/DocumentView.h"
#include "adjunct/quick/managers/TipsManager.h"
#ifndef SEARCH_SUGGEST_DELAY
#define SEARCH_SUGGEST_DELAY 250 // wait 250ms after the last letter has been entered before doing a search suggestion call
#endif // SEARCH_SUGGEST_DELAY
// don't immediately remove the highlight when moving mouse over the address bar
// to prevent flickering
#ifndef ADDRESS_HIGHLIGHTING_DELAY
#define ADDRESS_HIGHLIGHTING_DELAY 150
#endif // ADDRESS_HIGHLIGHTING_DELAY
//Uncomment this if needed
//#define REMOVE_HIGHLIGHT_ONHOVER
#define SEARCH_LENGTH_THRESHOLD 3
#define SUGGESTIONS_INITIAL_PRIORITY 6
#define MAX_ROWS_IN_DROPDOWN 9
#ifdef SUPPORT_START_BAR
/***********************************************************************************
**
** PopupWindow - a WidgetWindow subclass for implementing the popup window
**
***********************************************************************************/
class PopupWindow;
class PopupToolbar : public OpToolbar
{
public:
static OP_STATUS Construct(PopupToolbar** obj, PopupWindow* popup_window);
PopupToolbar(PopupWindow* popup_window) : m_popup_window(popup_window) {}
virtual void OnAlignmentChanged();
virtual void OnSettingsChanged() { OnAlignmentChanged(); }
private:
PopupWindow* m_popup_window;
};
OP_STATUS PopupToolbar::Construct(PopupToolbar** obj, PopupWindow* popup_window)
{
*obj = OP_NEW(PopupToolbar, (popup_window));
if (!*obj)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError((*obj)->init_status))
{
OP_DELETE(*obj);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
class PopupWindow : public DesktopWidgetWindow, public SettingsListener
{
public:
PopupWindow(OpAddressDropDown* address_dropdown) :
init_status(OpStatus::OK),
m_address_dropdown(address_dropdown)
{
OP_STATUS status;
g_application->AddSettingsListener(this);
status = Init(OpWindow::STYLE_CHILD, "Address Popup Window", m_address_dropdown->GetParentOpWindow(), NULL, OpWindow::EFFECT_TRANSPARENT);
CHECK_STATUS(status);
SetParentInputContext(m_address_dropdown);
GetWidgetContainer()->SetParentDesktopWindow(m_address_dropdown->GetParentDesktopWindow());
OpWidget* root = GetWidgetContainer()->GetRoot();
root->GetBorderSkin()->SetImage("Start Popup Skin", "Edit Skin");
status = PopupToolbar::Construct(&m_toolbar, this);
CHECK_STATUS(status);
root->AddChild(m_toolbar);
m_toolbar->GetBorderSkin()->SetImage("Startbar Skin");
m_toolbar->SetName("Start Toolbar");
// This is a hack, but the only way to get the start bar to work properly.
// The problem is that there is no parent-child relationship between the
// popup window and the address bar. Therefore we force the toolbar into
// the widget container of the address bar. And wowo everything works. adamm
m_address_widget_collection = address_dropdown->GetNamedWidgetsCollection(); // this is the window one, so now GetWidgetByName works
m_address_widget_collection->WidgetAdded(m_toolbar);
GetWindow()->Raise(); // OpWindow* WidgetWindow::GetWindow()
}
void PlacePopupWindow()
{
if (m_toolbar->GetResultingAlignment() == OpBar::ALIGNMENT_OFF)
{
Show(FALSE);
return;
}
OpToolbar* parent_toolbar = (OpToolbar*) m_address_dropdown->GetParent();
// Crash fix when closing the appearance dialog
if (!parent_toolbar)
return;
OpRect rect = m_address_dropdown->GetRect(TRUE);
INT32 height = m_toolbar->GetHeightFromWidth(rect.width);
if (parent_toolbar->GetAlignment() == OpBar::ALIGNMENT_BOTTOM)
rect.y -= height - 1;
else
rect.y += rect.height - 1;
rect.height = height;
#ifdef _MACINTOSH_
rect.y += 3;
#endif
Show(TRUE, &rect);
rect.x = rect.y = 0;
m_toolbar->SetRect(rect);
}
// This is a hack, but the only way to get the start bar to work properly.
// The problem is that there is no parent-child relationship between the
// popup window and the address bar. Therefore we force the toolbar into
// the widget container of the address bar. And wowo everything works. adamm
void OnClose(BOOL user_initiated)
{
m_address_widget_collection->WidgetRemoved(m_toolbar);
DesktopWidgetWindow::OnClose(user_initiated);
}
virtual ~PopupWindow()
{
m_address_dropdown->m_popup_window = NULL;
}
virtual BOOL IsInputContextAvailable(FOCUS_REASON reason) {return TRUE;}
virtual void OnSettingsChanged(DesktopSettings* settings)
{
GetWidgetContainer()->GetRoot()->GenerateOnSettingsChanged(settings);
}
OP_STATUS init_status;
private:
OpAddressDropDown* m_address_dropdown;
OpNamedWidgetsCollection* m_address_widget_collection;
PopupToolbar* m_toolbar;
};
void PopupToolbar::OnAlignmentChanged()
{
if (IsOn())
m_popup_window->PlacePopupWindow();
else
m_popup_window->Show(FALSE);
}
#endif // SUPPORT_START_BAR
/***********************************************************************************
**
** OpPageCursor
**
***********************************************************************************/
#ifdef QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
OpPageCursor::OpPageCursor()
: m_listener(NULL), m_page(NULL)
{
}
OP_STATUS OpPageCursor::SetPage(OpPage& page)
{
OpWindowCommander* old_commander = NULL;
if(m_page)
{
old_commander = m_page->GetWindowCommander();
m_page->RemoveListener(this);
}
OP_STATUS status = page.AddListener(this);
m_page = &page;
m_listener->OnPageWindowChanging(old_commander, page.GetWindowCommander());
return status;
}
void OpPageCursor::OnPageDocumentIconAdded(OpWindowCommander* commander)
{
m_listener->OnTabChanged();
}
void OpPageCursor::OnPageStartLoading(OpWindowCommander* commander)
{
m_listener->OnTabChanged();
m_listener->OnTabLoading();
}
void OpPageCursor::OnPageLoadingFinished(OpWindowCommander* commander, OpLoadingListener::LoadingFinishStatus status, BOOL was_stopped_by_user)
{
m_listener->OnTabInfoChanged();
}
void OpPageCursor::OnPageUrlChanged(OpWindowCommander* commander, const uni_char* url)
{
m_listener->OnPageURLChanged(commander, url);
}
void OpPageCursor::OnPageTitleChanged(OpWindowCommander* commander, const uni_char* title)
{
m_listener->OnTabChanged();
}
void OpPageCursor::OnPageSecurityModeChanged(OpWindowCommander* commander, OpDocumentListener::SecurityMode mode, BOOL inline_elt)
{
m_listener->OnTabInfoChanged();
}
#ifdef TRUST_RATING
void OpPageCursor::OnPageTrustRatingChanged(OpWindowCommander* commander, TrustRating new_rating)
{
m_listener->OnTabInfoChanged();
}
#endif // TRUST_RATING
OpWindowCommander* OpPageCursor::GetWindowCommander()
{
return m_page ? m_page->GetWindowCommander() : NULL;
}
BOOL OpPageCursor::IsTargetWindow(DocumentDesktopWindow* document_window)
{
if(document_window)
return IsTargetWindow(document_window->GetWindowCommander());
return FALSE;
}
BOOL OpPageCursor::IsTargetWindow(OpWindowCommander* windowcommander)
{
return windowcommander && (GetWindowCommander() == windowcommander);
}
OP_STATUS OpPageCursor::GetSecurityInformation(OpString& text)
{
return m_page->GetSecurityInformation(text);
}
const OpWidgetImage* OpPageCursor::GetWidgetImage()
{
return m_page->GetDocumentIcon();
}
const OpWidgetImage* OpPageCursor::GetWidgetImage(OpWindowCommander* windowcommander)
{
if(windowcommander)
{
OP_ASSERT(m_page->GetWindowCommander() == windowcommander);
if(m_page->GetWindowCommander() == windowcommander)
return m_page->GetDocumentIcon();
}
return NULL;
}
#endif // QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
/***********************************************************************************
**
** OpOldCursor
**
***********************************************************************************/
OpOldCursor::OpOldCursor() :
m_current_target(NULL),
m_workspace(NULL)
{
}
OpOldCursor::~OpOldCursor()
{
UnHookCursor(FALSE);
}
void OpOldCursor::BroadcastTabInfoChanged()
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabInfoChanged();
}
}
void OpOldCursor::BroadcastTabLoading()
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabLoading();
}
}
void OpOldCursor::BroadcastTabChanged()
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabChanged();
}
}
void OpOldCursor::BroadcastTabWindowChanging(DocumentDesktopWindow* old_target_window,
DocumentDesktopWindow* new_target_window)
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabWindowChanging(old_target_window, new_target_window);
}
}
void OpOldCursor::BroadcastTabClosing(DocumentDesktopWindow* desktop_window)
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabClosing(desktop_window);
}
}
void OpOldCursor::BroadcastTabURLChanged(DocumentDesktopWindow* document_window,
const OpStringC & url)
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
OpTabCursor::Listener* item = m_listeners.GetNext(iterator);
item->OnTabURLChanged(document_window, url);
}
}
void OpOldCursor::HookUpCursor(OpInputContext * input_context)
{
// Hook up to the current page :
SetSpyInputContext(input_context, FALSE);
}
void OpOldCursor::UnHookCursor(BOOL send_change)
{
// Unhook the current page :
SetSpyInputContext(NULL, send_change);
// Stop listening to the workspace :
SetWorkspace(NULL);
}
BOOL OpOldCursor::IsTargetWindow(DocumentDesktopWindow* document_window)
{
return document_window == m_current_target;
}
BOOL OpOldCursor::IsTargetWindow(OpWindowCommander* windowcommander)
{
if(windowcommander && m_current_target)
return m_current_target->GetWindowCommander() == windowcommander;
return FALSE;
}
OpWindowCommander* OpOldCursor::GetWindowCommander()
{
if(m_current_target)
return m_current_target->GetWindowCommander();
return NULL;
}
OP_STATUS OpOldCursor::GetSecurityInformation(OpString& text)
{
if(m_current_target &&
m_current_target->GetBrowserView())
return m_current_target->GetBrowserView()->GetCachedSecurityButtonText(text);
return OpStatus::ERR;
}
const OpWidgetImage* OpOldCursor::GetWidgetImage()
{
return m_current_target ? m_current_target->GetWidgetImage() : NULL;
}
// This horrible function is meant to die when OpPage wins over DocumentDesktopWindow
const OpWidgetImage* OpOldCursor::GetWidgetImage(OpWindowCommander* windowcommander)
{
if(!windowcommander)
return NULL;
OpWindow* op_window = windowcommander->GetOpWindow();
DesktopWindow* desktop_window = g_application->GetDesktopWindowCollection().GetDesktopWindowFromOpWindow(op_window);
if (desktop_window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
return NULL;
DocumentDesktopWindow* document_window = static_cast<DocumentDesktopWindow*>(desktop_window);
return document_window->GetWidgetImage();
}
OP_STATUS OpOldCursor::AddListener(OpTabCursor::Listener *listener)
{
return m_listeners.Add(listener);
}
OP_STATUS OpOldCursor::RemoveListener(OpTabCursor::Listener *listener)
{
return m_listeners.Remove(listener);
}
// Set the workspace to listen to
OP_STATUS OpOldCursor::SetWorkspace(OpWorkspace* workspace)
{
OP_STATUS status = OpStatus::OK;
if(m_workspace)
{
m_workspace->RemoveListener(this);
OpVector<DesktopWindow> windows;
RETURN_IF_ERROR(m_workspace->GetDesktopWindows(windows, OpTypedObject::WINDOW_TYPE_DOCUMENT));
for (UINT32 i = 0; i < windows.GetCount(); i++)
{
DocumentDesktopWindow* document = static_cast<DocumentDesktopWindow*>(windows.Get(i));
document->RemoveDocumentWindowListener(this);
}
}
m_workspace = workspace;
if(m_workspace)
{
status = m_workspace->AddListener(this);
OpVector<DesktopWindow> windows;
RETURN_IF_ERROR(m_workspace->GetDesktopWindows(windows, OpTypedObject::WINDOW_TYPE_DOCUMENT));
for (UINT32 i = 0; i < windows.GetCount(); i++)
{
DocumentDesktopWindow* document = static_cast<DocumentDesktopWindow*>(windows.Get(i));
document->AddDocumentWindowListener(this);
}
}
return status;
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnStartLoading(DocumentDesktopWindow* document_window)
{
// We are only interested in start loading on the current target page
if(IsTargetWindow(document_window))
BroadcastTabLoading();
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnLoadingFinished(DocumentDesktopWindow* document_window,
OpLoadingListener::LoadingFinishStatus status,
BOOL was_stopped_by_user)
{
// We are only interested in loading finished on the current target page
if(IsTargetWindow(document_window))
BroadcastTabInfoChanged();
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnTargetDocumentDesktopWindowChanged(DocumentDesktopWindow* target_window)
{
DocumentDesktopWindow* current = m_current_target;
m_current_target = target_window;
SetTargetDocumentDesktopWindow(m_current_target, FALSE);
BroadcastTabWindowChanging(current, target_window);
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnDesktopWindowClosing(DesktopWindow* desktop_window, BOOL user_initiated)
{
// if the current window is closing we need to reset the m_current_target
// (same as m_document_desktop_window is reset in DocumentDesktopWindowSpy::OnDesktopWindowClosing below)
if (desktop_window == this->GetTargetDocumentDesktopWindow())
m_current_target = NULL;
DocumentDesktopWindowSpy::OnDesktopWindowClosing(desktop_window, user_initiated);
if (desktop_window->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT)
BroadcastTabClosing((DocumentDesktopWindow*) desktop_window);
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnUrlChanged(DocumentDesktopWindow* document_window,
const uni_char* url)
{
// If the url changed for another window than the current one
// the hashmap in OpAddressDropdown will be wrong.
BroadcastTabURLChanged(document_window, url);
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnDesktopWindowChanged(DesktopWindow* desktop_window)
{
if (desktop_window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
return;
OP_ASSERT(IsTargetWindow(static_cast<DocumentDesktopWindow*>(desktop_window)));
if(IsTargetWindow(static_cast<DocumentDesktopWindow*>(desktop_window)))
BroadcastTabChanged();
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnSecurityModeChanged(DocumentDesktopWindow* document_window)
{
// We are only interested in changes in security on the current target page
if(IsTargetWindow(document_window))
BroadcastTabInfoChanged();
}
// Implementing DocumentDesktopWindowSpy
void OpOldCursor::OnTrustRatingChanged(DocumentDesktopWindow* document_window)
{
// We are only interested in changes in trust on the current target page
if(IsTargetWindow(document_window))
BroadcastTabInfoChanged();
}
void OpOldCursor::OnOnDemandPluginStateChange(DocumentDesktopWindow* document_window)
{
if(IsTargetWindow(document_window))
BroadcastTabInfoChanged();
}
// Implementing OpWorkspace::WorkspaceListener
void OpOldCursor::OnDesktopWindowAdded(OpWorkspace* workspace, DesktopWindow* desktop_window)
{
if(desktop_window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
return;
DocumentDesktopWindow* document = static_cast<DocumentDesktopWindow*>(desktop_window);
RETURN_VOID_IF_ERROR(document->AddDocumentWindowListener(this));
}
// Implementing OpWorkspace::WorkspaceListener
void OpOldCursor::OnDesktopWindowRemoved(OpWorkspace* workspace, DesktopWindow* desktop_window)
{
if(desktop_window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
return;
DocumentDesktopWindow* document = static_cast<DocumentDesktopWindow*>(desktop_window);
document->RemoveDocumentWindowListener(this);
}
// Implementing OpWorkspace::WorkspaceListener
void OpOldCursor::OnDesktopWindowActivated(OpWorkspace* workspace, DesktopWindow* desktop_window, BOOL activate)
{
if(!activate)
return;
// DocumentWindowSpy will take care of switching between document windows,
// but when when one or both of the windows are not document windows we
// won't get callback from DocumentWindowSpy and need to handle it here
if(desktop_window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
OnTargetDocumentDesktopWindowChanged(NULL);
else if (!m_current_target || m_current_target->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
OnTargetDocumentDesktopWindowChanged(static_cast<DocumentDesktopWindow*>(desktop_window));
}
// Implementing OpWorkspace::WorkspaceListener
void OpOldCursor::OnWorkspaceDeleted(OpWorkspace* workspace)
{
// Stop listening to the workspace :
SetWorkspace(NULL);
}
/***********************************************************************************
**
** OpAddressDropDown
**
***********************************************************************************/
DEFINE_CONSTRUCT(OpAddressDropDown)
OpAddressDropDown::OpAddressDropDown() :
OpTreeViewDropdown()
, m_host_resolver(NULL)
, m_progress_field(NULL)
, m_url_fav_menu(NULL)
, m_bookmark_status_label(NULL)
, m_rss_button(NULL)
, m_ondemand_button(NULL)
, m_bookmark_button(NULL)
, m_protocol_button(NULL)
#ifdef SUPPORT_START_BAR
, m_popup_window(NULL)
#endif // SUPPORT_START_BAR
, m_url_page_mismatch(FALSE)
, m_show_all_item(NULL)
, m_tab_cursor(NULL)
, m_open_page_in_tab(TRUE)
, m_in_addressbar(FALSE)
, m_delayed_progress_visibility(FALSE)
, m_delayed_layout_in_progress(FALSE)
, m_addressbar_overlay_ctl(NULL)
, m_favorites_overlay_ctl(NULL)
, m_show_search_suggestions(TRUE)
, m_show_speed_dial_pages(true)
, m_process_search_results(FALSE)
, m_lock_current_text(0)
, m_is_quick_completed(false)
, m_tab_mode(FALSE)
, m_search_suggest_in_progress(FALSE)
, m_shall_show_addr_bar_badge(TRUE)
, m_search_suggest(NULL)
, m_mh(NULL)
, m_query_error_counter(0)
#if defined(_X11_SELECTION_POLICY_)
, m_select_start(0)
, m_select_end(0)
, m_caret_offset(-1)
#endif
, m_use_display_url(FALSE)
, m_item_to_select(NULL)
, m_url_fav_composite_listener(NULL)
, m_show_favorites_button(false)
, m_regex(NULL)
, m_search_for_item(NULL)
, m_selected_item(NULL)
, m_ignore_edit_focus(false)
, m_block_focus_timer(NULL)
, m_notification_timer(NULL)
{
RETURN_VOID_IF_ERROR(init_status);
OP_STATUS status = OpStatus::OK;
m_tab_cursor = OP_NEW(OpOldCursor, ());
if (!m_tab_cursor)
CHECK_STATUS(OpStatus::ERR_NO_MEMORY);
status = SetTabMode(TRUE);
CHECK_STATUS(status);
m_tab_cursor->HookUpCursor(this);
m_text_content.SetOwner(this);
status = g_application->AddAddressBar(this);
CHECK_STATUS(status);
TRAPD(err,g_pcui->RegisterListenerL(this));
//--------------------------------------------------
// Security :
//--------------------------------------------------
// For updating the security ui :
SetUpdateNeededWhen(UPDATE_NEEDED_WHEN_VISIBLE);
//--------------------------------------------------
// Widget settings :
//--------------------------------------------------
SetAlwaysInvoke(TRUE);
SetGrowValue(2);
SetListener(this);
ShowButton(FALSE);
GetBorderSkin()->SetImage("Dropdown Addressfield Skin", "Dropdown Skin");
// Avoid streched favicons :
SetRestrictImageSize(TRUE);
//--------------------------------------------------
// Initialize the ui widgets :
//--------------------------------------------------
OpString button_text;
// Edit field
status = InitializeEditField();
CHECK_STATUS(status);
// Progress field
status = InitializeProgressField();
CHECK_STATUS(status);
// Protocol button
status = InitializeProtocolButton();
CHECK_STATUS(status);
// Plugin On-demand activation button
g_languageManager->GetString(Str::S_ON_DEMAND_PLUGINS_ACTIVATE_TOOLTIP, button_text);
status = InitializeButton(&m_ondemand_button, "Activate on-demand plugins,,,,\"Ondemand\"", button_text.CStr());
m_ondemand_button->SetName(WIDGET_NAME_ADDRESSFIELD_BUTTON_ONDEMAND);
CHECK_STATUS(status);
// RSS button
g_languageManager->GetString(Str::D_FEED_LIST, button_text);
status = InitializeButton(&m_rss_button,
"Go to link element, \"application/atom+xml\",,,\"RSS\" | Go to link element, \"application/rss+xml\",,,\"RSS\"",
button_text.CStr());
m_rss_button->SetName(WIDGET_NAME_ADDRESSFIELD_BUTTON_RSS);
CHECK_STATUS(status);
// Note button
status = InitializeButton(&m_bookmark_button, "Highlight note,,,,\"Note\"", 0);
CHECK_STATUS(status);
// Dropdown button
status = InitializeButton(&m_dropdown_button, "Show dropdown,,,,\"Down arrow\"", 0);
m_dropdown_button->SetName(WIDGET_NAME_ADDRESSFIELD_BUTTON_DROPDOWN);
CHECK_STATUS(status);
m_mh = OP_NEW(MessageHandler, (NULL));
if (!m_mh)
CHECK_STATUS(OpStatus::ERR_NO_MEMORY);
m_search_suggest = OP_NEW(SearchSuggest, (this));
if (!m_search_suggest)
CHECK_STATUS(OpStatus::ERR_NO_MEMORY);
// Register for callbacks :
m_url_fav_composite_listener = OP_NEW(FavoritesCompositeListener, (this));
if (!m_url_fav_composite_listener)
CHECK_STATUS(OpStatus::ERR_NO_MEMORY);
// use global for content search
g_main_message_handler->SetCallBack(this, MSG_VPS_SEARCH_RESULT, reinterpret_cast<MH_PARAM_1>(static_cast<MessageObject *>(this)));
// local for other stuff
m_mh->SetCallBack(this, MSG_QUICK_REMOVE_ADDRESSFIELD_HISTORY_ITEM, 0);
m_mh->SetCallBack(this, MSG_QUICK_START_SEARCH_SUGGESTIONS, 0);
// set up the delayed trigger
m_delayed_trigger.SetDelayedTriggerListener(this);
m_delayed_trigger.SetTriggerDelay(0, 500);
m_highlight_delayed_trigger.SetDelayedTriggerListener(this);
m_highlight_delayed_trigger.SetTriggerDelay(ADDRESS_HIGHLIGHTING_DELAY, ADDRESS_HIGHLIGHTING_DELAY);
}
OpAddressDropDown::~OpAddressDropDown()
{
OP_DELETE(m_block_focus_timer);
OP_DELETE(m_notification_timer);
OP_DELETE(m_mh);
OP_DELETE(m_search_suggest);
OP_DELETE(m_host_resolver);
OP_DELETE(m_tab_cursor);
OP_DELETE(m_show_all_item);
OP_DELETE(m_url_fav_composite_listener);
OP_DELETE(m_regex);
OP_DELETE(m_search_for_item);
DeleteItems(m_search_suggestions_items);
DeleteItems(m_items_to_delete);
}
/***********************************************************************************
**
** Model converters
**
***********************************************************************************/
inline void OpAddressDropDown::SetModel(HistoryAutocompleteModel * tree_model, BOOL items_deletable)
{
OpTreeViewDropdown::SetModel(tree_model, items_deletable);
SetTreeViewName( WIDGET_NAME_ADDRESSFIELD_TREVIEW );
}
HistoryAutocompleteModel * OpAddressDropDown::GetModel()
{
return static_cast<HistoryAutocompleteModel*>(OpTreeViewDropdown::GetModel());
}
HistoryAutocompleteModelItem * OpAddressDropDown::GetSelectedItem(int * position)
{
return static_cast<HistoryAutocompleteModelItem*>(OpTreeViewDropdown::GetSelectedItem(position));
}
OP_STATUS OpAddressDropDown::SetTabMode(BOOL mode)
{
OP_STATUS rc = OpStatus::OK;
if (m_tab_mode != mode)
{
rc = mode ? m_tab_cursor->AddListener(this) : m_tab_cursor->RemoveListener(this);
if (OpStatus::IsSuccess(rc))
m_tab_mode = mode;
}
return rc;
}
#ifdef QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
OP_STATUS OpAddressDropDown::SetPage(OpPage& page)
{
if(m_tab_cursor->GetCursorType() == OpTabCursor::OLD_TYPE)
{
OpAutoPtr<OpTabCursor> tab_cursor(OP_NEW(OpPageCursor, ()));
if(!tab_cursor.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(tab_cursor->AddListener(this));
OP_DELETE(m_tab_cursor);
m_tab_cursor = tab_cursor.release();
}
return m_tab_cursor->SetPage(page);
}
#endif // QUICK_TOOLKIT_CAP_HAS_PAGE_VIEW
OP_STATUS OpAddressDropDown::InitializeEditField()
{
OpString ghost_text;
RETURN_IF_ERROR(g_languageManager->GetString(Str::S_GO_TO_WEB_ADDRESS_OR_SEARCH_HERE, ghost_text));
RETURN_VALUE_IF_NULL(edit,OpStatus::ERR);
edit->SetForceTextLTR(TRUE);
edit->SetShowGhostTextWhenFocused(TRUE);
edit->SetGhostTextJusifyWhenFocused(JUSTIFY_LEFT);
RETURN_IF_ERROR(edit->SetGhostText(ghost_text.CStr()));
#ifndef _MACINTOSH_
edit->SetDoubleClickSelectsAll(TRUE);
#endif // ! _MACINTOSH_
edit->SetReplaceAllOnDrop(TRUE);
edit->SetHasCssBackground(TRUE);
edit->GetBorderSkin()->SetImage("Dropdown Addressfield Edit Skin", "Edit Skin");
PageBasedAutocompleteItem::SetFontWidth(WidgetUtils::GetFontWidth(edit->font_info));
UINT32 color;
if (OpStatus::IsSuccess(g_skin_manager->GetTextColor("Ghost Text Foreground Skin", &color, 0)))
edit->SetGhostTextFGColorWhenFocused(color);
return OpStatus::OK;
}
/***********************************************************************************
**
** InitializeProgressField
**
***********************************************************************************/
OP_STATUS OpAddressDropDown::InitializeProgressField()
{
OP_STATUS status = OpProgressField::Construct(&m_progress_field, OpProgressField::PROGRESS_TYPE_GENERAL);
if(OpStatus::IsSuccess(status))
{
AddChild(m_progress_field, FALSE, TRUE);
m_progress_field->SetVisibility(FALSE);
m_progress_field->GetForegroundSkin()->SetImage("Addressbar Progress Full Skin");
m_progress_field->GetBorderSkin()->SetImage("Addressbar Progress Skin");
}
return status;
}
OP_STATUS OpAddressDropDown::InitializeBookmarkMenu()
{
OpString button_text;
OpAutoPtr<URLFavMenuButton> fav_btn(OP_NEW(URLFavMenuButton, ()));
RETURN_OOM_IF_NULL(fav_btn.get());
OpAutoPtr<OpInputAction> action;
if (g_desktop_op_system_info->SupportsContentSharing())
{
RETURN_IF_ERROR(OpButton::Construct(&m_bookmark_status_label, OpButton::TYPE_TOOLBAR, OpButton::STYLE_TEXT));
m_bookmark_status_label->SetName(WIDGET_NAME_ADDRESSFIELD_FAV_NOTIFICAITON);
m_bookmark_status_label->SetVisibility(FALSE);
AddChild(m_bookmark_status_label, FALSE, TRUE);
m_notification_timer = OP_NEW(OpTimer, ());
RETURN_OOM_IF_NULL(m_notification_timer);
RETURN_IF_ERROR(fav_btn->Init(NULL,"SharePage"));
action = OP_NEW(OpInputAction, (OpInputAction::ACTION_SHOW_HIDDEN_POPUP_MENU));
RETURN_OOM_IF_NULL(action.get());
action->SetActionDataString(UNI_L("Page Sharing Menu"));
RETURN_IF_ERROR(g_languageManager->GetString(Str::S_URL_SHARE_MENU_TT, button_text));
}
else
{
RETURN_IF_ERROR(fav_btn->Init(NULL, "NonBookmarked URL"));
action = OP_NEW(OpInputAction, (OpInputAction::ACTION_OPEN));
RETURN_OOM_IF_NULL(action.get());
action->SetActionDataString(UNI_L("URL Fav Menu"));
RETURN_IF_ERROR(g_languageManager->GetString(Str::S_URL_BOOKMARK_MENU_TT, button_text));
}
fav_btn->SetAction(action.release());
RETURN_IF_ERROR(fav_btn->SetText(button_text.CStr()));
fav_btn->SetName(WIDGET_NAME_ADDRESSFIELD_FAV_MENU_BUTTON);
fav_btn->SetVisibility(FALSE);
AddChild(fav_btn.get(), FALSE, TRUE);
m_url_fav_menu = fav_btn.release();
return OpStatus::OK;
}
OP_STATUS OpAddressDropDown::InitializeProtocolButton()
{
m_protocol_button = OP_NEW(OpProtocolButton, ());
RETURN_OOM_IF_NULL(m_protocol_button);
RETURN_IF_ERROR(m_protocol_button->Init());
AddChild(m_protocol_button, FALSE, TRUE);
m_protocol_button->SetVisibility(FALSE);
return OpStatus::OK;
}
OpWidget* OpAddressDropDown::GetWidgetByName(const char* name)
{
OpWidget* widget = OpTreeViewDropdown::GetWidgetByName(name);
if (widget)
return widget;
#ifdef SUPPORT_START_BAR
if (m_popup_window)
return m_popup_window->GetWidgetContainer()->GetRoot()->GetWidgetByName(name);
#endif // SUPPORT_START_BAR
return NULL;
}
#ifdef SUPPORT_START_BAR
void OpAddressDropDown::CreatePopupWindow()
{
OpWidget *parent = GetParent();
if (!parent || parent->GetType() != WIDGET_TYPE_TOOLBAR)
return;
OpToolbar* parent_toolbar = (OpToolbar*)parent;
if (parent_toolbar->IsLocked() ||
parent_toolbar->IsNamed("Start toolbar") ||
g_application->IsCustomizingToolbars())
// GetParentDesktopWindow() == (DesktopWindow*) g_application->GetCustomizeToolbarsDialog())
return;
if (!m_popup_window)
{
m_popup_window = OP_NEW(PopupWindow, (this));
if (m_popup_window && OpStatus::IsError(m_popup_window->init_status))
{
OP_DELETE(m_popup_window);
m_popup_window = NULL;
}
}
}
void OpAddressDropDown::PlacePopupWindow()
{
if (!m_popup_window)
return;
m_popup_window->PlacePopupWindow();
}
void OpAddressDropDown::ShowPopupWindow(BOOL show)
{
if (!m_popup_window || /* Bug 170735 & 248675 & friends*/ g_application->GetMenuHandler()->IsShowingMenu())
return;
if (show)
PlacePopupWindow();
else
m_popup_window->Show(FALSE);
}
void OpAddressDropDown::DestroyPopupWindow(BOOL close_immediately)
{
if (m_popup_window)
{
m_popup_window->SetParentInputContext(NULL);
m_popup_window->Close(close_immediately);
}
// Keep the m_popup_window here - it will be NULLed by ~PopupWindow()
// This is to ensure that a delayed closing (due to focus removal) can still be overridden
// with the necessary immediate closing when this OpAddressDropDown is deleted.
}
#endif // SUPPORT_START_BAR
OP_STATUS OpAddressDropDown::InitializeButton(OpButton ** button,
const char * action_string,
const uni_char * button_text)
{
*button = new OpAddressFieldButton();
if(*button)
{
OpInputAction* widget_action;
OP_STATUS status = OpInputAction::CreateInputActionsFromString(action_string, widget_action);
if (OpStatus::IsSuccess(status))
(*button)->SetAction(widget_action);
(*button)->SetButtonStyle(OpButton::STYLE_IMAGE);
(*button)->SetFixedImage(FALSE);
if(button_text)
(*button)->SetText(button_text);
AddChild(*button, FALSE, TRUE);
(*button)->SetVisibility(FALSE);
return status;
}
return OpStatus::ERR_NO_MEMORY;
}
void OpAddressDropDown::OnDeleted()
{
OP_DELETE(m_url_fav_composite_listener);
m_url_fav_composite_listener = NULL;
m_mh->UnsetCallBacks(this);
g_main_message_handler->UnsetCallBacks(this);
if (DesktopHistoryModel::GetInstance())
DesktopHistoryModel::GetInstance()->RemoveDesktopHistoryModelListener(this);
#ifdef SUPPORT_START_BAR
DestroyPopupWindow(TRUE);
#endif // SUPPORT_START_BAR
if (m_url_fav_menu)
{
m_url_fav_menu->Remove();
OP_DELETE(m_url_fav_menu);
m_url_fav_menu = NULL;
}
if (m_addressbar_overlay_ctl)
{
m_addressbar_overlay_ctl->SetAnchorWidget(NULL);
m_addressbar_overlay_ctl->SetListener(NULL);
CloseOverlayDialog();
}
OpTreeViewDropdown::OnDeleted();
m_tab_cursor->RemoveListener(this);
m_tab_cursor->UnHookCursor(FALSE);
g_application->RemoveAddressBar(this);
TRAPD(err,g_pcui->UnregisterListener(this));
}
void OpAddressDropDown::OnKeyboardInputGained(OpInputContext* new_input_context,
OpInputContext* old_input_context,
FOCUS_REASON reason)
{
if (new_input_context == m_url_fav_menu
|| (m_favorites_overlay_ctl && m_favorites_overlay_ctl->IsDialogVisible() && new_input_context != edit && new_input_context != this))
return;
OpTreeViewDropdown::OnKeyboardInputGained(new_input_context, old_input_context, reason);
UpdateButtons(FALSE);
#ifdef SUPPORT_START_BAR
ShowPopupWindow(TRUE);
#endif // SUPPORT_START_BAR
// _X11_SELECTION_POLICY_ in this function: Restore selection (without copying to the X11
// selection buffer) and cursor position as it was when widget lost focus. This allows the user
// midclick paste data into the edit field.
#if defined(_X11_SELECTION_POLICY_)
int pos = edit->GetCaretOffset();
#endif
if (GetFocused() == edit)
{
m_protocol_button->HideText();
}
// The edit get focused, show the full address(including protocol) if it wasn't edited
if (!m_url_page_mismatch)
{
RestoreOriginalAddress();
// If protocol was hidden we need to offset the selecting start
if (!g_pcui->GetIntegerPref(PrefsCollectionUI::ShowFullURL))
edit->selecting_start += m_address.GetProtocol().Length();
#if defined(_X11_SELECTION_POLICY_)
if (reason == FOCUS_REASON_MOUSE || reason == FOCUS_REASON_ACTIVATE)
{
if (!g_pcui->GetIntegerPref(PrefsCollectionUI::ShowFullURL))
pos += m_address.GetProtocol().Length();
if (m_select_start != m_select_end)
edit->SetSelection(m_select_start, m_select_end);
if (m_caret_offset != -1 && reason == FOCUS_REASON_ACTIVATE)
pos = m_caret_offset;
m_caret_offset = -1;
}
#else
edit->SelectAll();
#endif
}
#if defined(_X11_SELECTION_POLICY_)
if (reason == FOCUS_REASON_MOUSE || reason == FOCUS_REASON_ACTIVATE)
{
if (reason == FOCUS_REASON_MOUSE && vis_dev->GetView()->GetMouseButton(MOUSE_BUTTON_1))
{
edit->is_selecting = 1;
edit->SetCaretOffset(pos, FALSE);
edit->string.sel_start = edit->string.sel_stop = edit->GetCaretOffset();
}
else
edit->SetCaretOffset(pos);
}
else
{
// Select all text without copying to clipboard buffer
OpString text;
GetText(text);
edit->SetSelection(0, text.Length());
edit->SetCaretOffset(0);
}
m_select_start = m_select_end = 0;
#endif
UpdateAddressFieldHighlight(FALSE, TRUE);
}
void OpAddressDropDown::OnKeyboardInputLost(OpInputContext* new_input_context,
OpInputContext* old_input_context,
FOCUS_REASON reason)
{
if (m_favorites_overlay_ctl && m_favorites_overlay_ctl->IsDialogVisible())
return;
if (new_input_context != this &&
!IsParentInputContextOf(new_input_context) &&
!g_application->IsCustomizingToolbars() &&
!g_drag_manager->IsDragging())
{
UpdateButtons(FALSE);
// Delay closing of the popup so that all functions in the call chain
// referencing it can finish first (bug #185028)
#ifdef SUPPORT_START_BAR
if(new_input_context != this)
{
ShowPopupWindow(FALSE);
}
#endif // SUPPORT_START_BAR
}
// _X11_SELECTION_POLICY_ in this function: Save selection region and keep it visible
// so that 1) a user knows what can be midclick pasted elsewhere by looking at the text
// and 2) the selection can be properly restored when the widget gains focus
#if defined(_X11_SELECTION_POLICY_)
SELECTION_DIRECTION direction;
edit->GetSelection(m_select_start, m_select_end, direction);
int caret_offset = edit->GetCaretOffset();
#endif
// When edit is losing focus we want to show the short address but only if the address wasn't edited
if (GetFocused() != edit && GetWindowCommander())
{
m_protocol_button->ShowText();
OpString text;
GetText(text);
const uni_char* current_url = GetWindowCommander()->IsLoading() ?
GetWindowCommander()->GetLoadingURL(FALSE) :
GetWindowCommander()->GetCurrentURL(FALSE);
if (text.Compare(current_url) == 0)
{
/* The family of WindowCommander's GetFooURL() methods use the same
buffer for strings they return meaning that they will overwrite
the string that was obtained in the previous call, fooling
comparisons that are done throughout this code. We need to copy
the string. */
OpString url;
if (OpStatus::IsSuccess(url.Set(current_url)))
{
SetText(url.CStr());
#if defined(_X11_SELECTION_POLICY_)
m_caret_offset = caret_offset; // Save offset as it was before SetText
if (!g_pcui->GetIntegerPref(PrefsCollectionUI::ShowFullURL))
{
if (m_select_start != m_select_end)
{
int l = m_address.GetProtocol().Length();
edit->SetSelection(m_select_start-l, m_select_end-l);
}
}
#endif
}
}
}
UpdateAddressFieldHighlight();
// Caret should be reset to 0 when focus lost, this is standard
// behavior for other browsers too.
#if !defined(_X11_SELECTION_POLICY_)
if (reason != FOCUS_REASON_RELEASE)
edit->SetCaretOffset(0);
#endif
OpTreeViewDropdown::OnKeyboardInputLost(new_input_context, old_input_context, reason);
}
BOOL OpAddressDropDown::BelongsToADocumentDesktopWindow()
{
// Try to find a DocumentDesktopWindow on our input context path
return GetParentDesktopWindowType() == OpTypedObject::WINDOW_TYPE_DOCUMENT;
}
void OpAddressDropDown::OnAdded()
{
OpWidget* grand_parent = GetParent()->GetParent();
if (grand_parent->GetType() == PANEL_TYPE_START)
{
m_tab_cursor->UnHookCursor(TRUE);
GetForegroundSkin()->SetImage(NULL);
}
m_in_addressbar = GetParentDesktopWindowType() == WINDOW_TYPE_DOCUMENT || GetParentDesktopWindowType() == WINDOW_TYPE_BROWSER;
if (m_in_addressbar && m_protocol_button)
m_protocol_button->SetVisibility(TRUE);
OpInputAction *act = OP_NEW(OpInputAction, (OpInputAction::ACTION_GO_TO_TYPED_ADDRESS));
if (act)
{
SetAction(act);
}
OpTreeViewDropdown::OnAdded();
#ifdef SUPPORT_START_BAR
CreatePopupWindow();
#endif // SUPPORT_START_BAR
}
void OpAddressDropDown::ForwardWorkspace()
{
if(m_tab_cursor->HasWorkspace() || BelongsToADocumentDesktopWindow())
return;
// We are a tab on a status or main bar, and we have not yet started listening
// to the workspace. Make sure we listen now.
m_tab_cursor->SetWorkspace(GetWorkspace());
}
void OpAddressDropDown::OnTrigger(OpDelayedTrigger* trigger)
{
if (trigger == &m_delayed_trigger)
{
DesktopWindow *window = GetParentDesktopWindow();
if(window && window->GetType() == WINDOW_TYPE_DOCUMENT && ((DocumentDesktopWindow *)window)->IsLoading())
{
return;
}
m_progress_field->SetVisibility(m_delayed_progress_visibility);
Relayout();
m_delayed_layout_in_progress = FALSE;
}
else if (trigger == &m_highlight_delayed_trigger)
{
UpdateAddressFieldHighlight(FALSE, TRUE);
}
}
void OpAddressDropDown::UpdateButtons(BOOL new_url)
{
BOOL progress_visibility = FALSE;
BOOL security_visibility = FALSE;
BOOL security_button_changed = FALSE;
BOOL on_demand_visibility = FALSE;
BOOL rss_visibility = FALSE;
BOOL widget_visibility = FALSE;
BOOL bookmark_visibility = FALSE;
BOOL protocol_button_visibility = FALSE;
BOOL url_fav_menu_visibility = FALSE;
m_dropdown_button->SetVisibility(g_pcui->GetIntegerPref(PrefsCollectionUI::ShowDropdownButtonInAddressfield));
OpWindowCommander* win_comm = m_tab_cursor->GetWindowCommander();
if (!win_comm)
return;
if(new_url)
{
if (m_url_fav_menu)
m_url_fav_menu->SetVisibility(FALSE);
}
// Update status of the protocol button
if (m_in_addressbar && new_url)
{
UpdateProtocolStatus();
protocol_button_visibility = GetProtocolStatus() != OpProtocolButton::NotSet;
}
// Check the type of progress :
if (win_comm->IsLoading()) // Only display progress when you should
{
progress_visibility = g_pcui->GetIntegerPref(PrefsCollectionUI::ProgressPopup) == OpProgressField::PROGRESS_TYPE_TOTAL;
}
else
{
// URL Bookmark Menu
if (m_show_favorites_button)
{
URL url = WindowCommanderProxy::GetMovedToURL(win_comm);
url_fav_menu_visibility = !url.IsEmpty();
if (url_fav_menu_visibility)
{
const uni_char* url = m_tab_cursor->GetWindowCommander()->GetCurrentURL(FALSE);
if (url)
{
if (!DocumentView::IsUrlRestrictedForViewFlag(url, DocumentView::ALLOW_ADD_TO_SPEED_DIAL) &&
!DocumentView::IsUrlRestrictedForViewFlag(url, DocumentView::ALLOW_ADD_TO_BOOKMARK))
url_fav_menu_visibility = FALSE;
}
}
}
// Note button
HotlistModel* model = g_hotlist_manager->GetNotesModel();
HotlistModelItem* item = model->GetByURL(WindowCommanderProxy::GetMovedToURL(win_comm));
bookmark_visibility = (item != NULL && !item->GetIsInsideTrashFolder());
// Plugin On-demand button :
OpInputAction* current_action = m_ondemand_button->GetAction();
while (current_action && !on_demand_visibility)
{
on_demand_visibility = (g_input_manager->GetActionState(current_action, this) &
OpInputAction::STATE_ENABLED) != 0;
current_action = current_action->GetNextInputAction();
}
// RSS button
current_action = m_rss_button->GetAction();
while (current_action && !rss_visibility)
{
rss_visibility = (g_input_manager->GetActionState(current_action, this) &
OpInputAction::STATE_ENABLED) != 0;
current_action = current_action->GetNextInputAction();
}
}
// Turn them off if the user is using the edit field :
if (GetFocused() == OpDropDown::edit)
{
security_visibility = FALSE;
on_demand_visibility= FALSE;
rss_visibility = FALSE;
widget_visibility = FALSE;
bookmark_visibility = FALSE;
url_fav_menu_visibility = FALSE;
}
BOOL relayout = FALSE;
if (m_progress_field->IsVisible() != progress_visibility)
{
if (ShallMaskUrlFromDisplay(m_address.GetFullAddress()))
progress_visibility = FALSE;
if(progress_visibility) // if it's not visible and needs to be, make it visible right away
m_progress_field->SetVisibility(progress_visibility);
else
{
// If it needs to be hidden, delay hiding it a bit just in case we're going to show it again right again
m_delayed_progress_visibility = progress_visibility;
m_delayed_layout_in_progress = TRUE;
}
}
if (m_url_fav_menu && m_url_fav_menu->IsVisible() != url_fav_menu_visibility)
{
m_url_fav_menu->SetVisibility(url_fav_menu_visibility);
relayout = TRUE;
}
if (security_button_changed && security_visibility)
{
relayout = TRUE;
}
if (m_ondemand_button->IsVisible() != on_demand_visibility)
{
m_ondemand_button->SetVisibility(on_demand_visibility);
relayout = TRUE;
}
if (m_rss_button->IsVisible() != rss_visibility)
{
m_rss_button->SetVisibility(rss_visibility);
relayout = TRUE;
}
if (m_bookmark_button->IsVisible() != bookmark_visibility)
{
m_bookmark_button->SetVisibility(bookmark_visibility);
relayout = TRUE;
}
if (m_protocol_button->IsVisible() != protocol_button_visibility)
{
m_protocol_button->SetVisibility(protocol_button_visibility);
relayout = TRUE;
}
#ifdef EXTENSION_SUPPORT
SetDead(m_protocol_button->GetStatus() == OpProtocolButton::Widget);
#endif
// Update url fav menu icon
if (!win_comm->IsLoading())
UpdateFavoritesFG(!relayout && !m_delayed_layout_in_progress);
if (m_delayed_layout_in_progress)
m_delayed_trigger.InvokeTrigger(OpDelayedTrigger::INVOKE_DELAY);
else if (relayout)// relayout will happen in the OpTrigger anyway
Relayout();
}
void OpAddressDropDown::GetPadding(INT32* left,
INT32* top,
INT32* right,
INT32* bottom)
{
OpTreeViewDropdown::GetPadding(left, top, right, bottom);
// Left aligned buttons
if (m_protocol_button->IsVisible())
*left += m_protocol_button->GetTargetWidth();
// Right aligned buttons
OpWidget* buttons[] = {
m_progress_field,
m_url_fav_menu,
m_rss_button,
m_ondemand_button,
m_bookmark_button,
m_dropdown_button,
m_bookmark_status_label,
};
for (unsigned i = 0; i < ARRAY_SIZE(buttons); ++i)
if (buttons[i] != NULL && buttons[i]->IsVisible())
*right += buttons[i]->GetWidth();
}
void OpAddressDropDown::OnLayout()
{
OpRect rect = GetBounds();
INT32 left, top, right, bottom;
OpTreeViewDropdown::GetPadding(&left, &top, &right, &bottom);
rect.x += left;
rect.y += top;
rect.width -= left + right;
rect.height -= top + bottom;
rect.width -= GetRTL() ? GetInfo()->GetDropdownLeftButtonWidth(this) : GetInfo()->GetDropdownButtonWidth(this);
rect.x += rect.width;
INT32 height, width;
width = rect.width;
// Layout right- (left- for RTL) aligned buttons
if (m_dropdown_button->IsVisible())
{
m_dropdown_button->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_dropdown_button, rect);
}
rect.width = width;
if (m_progress_field->IsVisible())
{
m_progress_field->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_progress_field, rect);
}
height = rect.height;
if (m_url_fav_menu && m_url_fav_menu->IsVisible())
{
m_url_fav_menu->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_url_fav_menu, rect);
}
if (m_rss_button->IsVisible())
{
m_rss_button->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_rss_button, rect);
}
if (m_ondemand_button->IsVisible())
{
m_ondemand_button->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_ondemand_button, rect);
}
if (m_bookmark_button->IsVisible())
{
m_bookmark_button->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_bookmark_button, rect);
}
// status notification text should be the leftmost element of righ alignment buttons
if (m_bookmark_status_label)
{
m_bookmark_status_label->GetRequiredSize(rect.width, height);
rect.x -= rect.width;
SetChildRect(m_bookmark_status_label, rect);
}
// Layout left aligned buttons, but leave the button alone when it's animating
m_protocol_button->SetVisibility(m_in_addressbar); // only want this button in real address bar
// Either Window Document Icon or the Badge should be shown
if (!m_protocol_button->IsVisible() && m_shall_show_addr_bar_badge)
GetForegroundSkin()->SetImage("Window Document Icon");
else
GetForegroundSkin()->SetImage(NULL);
if (m_protocol_button->IsVisible() && !m_protocol_button->GetAnimation())
{
UpdateProtocolStatus();
// width, don't resize the width of the button, it'll take care of itself
INT32 dummy;
m_protocol_button->GetRequiredSize(rect.width, dummy);
// height and margins
INT32 margin_left, margin_right, margin_bottom, margin_top;
m_protocol_button->GetBorderSkin()->GetMargin(&margin_left, &margin_top, &margin_right, &margin_bottom);
rect.y += margin_top;
rect.height -= margin_top + margin_bottom;
rect.x = left + margin_left;
SetChildRect(m_protocol_button, rect);
}
OpTreeViewDropdown::OnLayout();
// Once the dropdown and the OpEdit have been layouted, the text may have scrolled
// if it didn't fit completely. To prevent url spoofing, we always want to show the
// protocol and domain, and therefore scroll back to beginning of the url.
if (GetFocused() != edit)
{
edit->ResetScroll();
}
#ifdef SUPPORT_START_BAR
if ((g_application->IsCustomizingToolbars() ||
g_drag_manager->IsDragging()) &&
GetParentDesktopWindow() &&
(GetParentDesktopWindow()->IsActive() || !GetParentWorkspace()))
ShowPopupWindow(TRUE);
else if (IsFocused(TRUE) &&
g_input_manager->GetKeyboardInputContext() != m_url_fav_menu)
ShowPopupWindow(TRUE);
else
ShowPopupWindow(FALSE);
#endif // SUPPORT_START_BAR
}
void OpAddressDropDown::OnResize(INT32* new_w, INT32* new_h)
{
OpTreeViewDropdown::OnResize(new_w, new_h);
// Notify open password dialogs about resize
DesktopWindow *dw = GetParentDesktopWindow();
if (!dw || dw->GetType() != WINDOW_TYPE_DOCUMENT)
return;
DocumentDesktopWindow *ddw = (DocumentDesktopWindow*) dw;
for (int i = 0; i < ddw->GetDialogCount(); i++)
{
if (ddw->GetDialog(i)->GetType() == DIALOG_TYPE_PASSWORD)
{
PasswordDialog* pwdialog = (PasswordDialog*)ddw->GetDialog(i);
pwdialog->OnAddressDropdownResize();
}
}
}
void OpAddressDropDown::OnUpdateActionState()
{
OpWindowCommander* win_comm = m_tab_cursor->GetWindowCommander();
if (!win_comm)
return;
if (!WindowCommanderProxy::HasConsistentRating(win_comm) // There is a change in trust rating
// The server has blacklisted paths, and we have to check this one.
// (This is a bit hackish, ideally the path itself should be checked,
// but we want this piece of code to be cheap because it runs often.
// Hitting a fraud server, on the other hand, is rare, and we can afford
// doing a bit of double work in those cases.)
|| (!WindowCommanderProxy::IsPhishing(win_comm) && !WindowCommanderProxy::FraudListIsEmpty(win_comm)))
{
win_comm->CheckDocumentTrust(FALSE, TRUE);
}
}
BOOL OpAddressDropDown::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_STOP:
child_action->SetEnabled(edit->IsFocused());
return TRUE;
}
break;
}
case OpInputAction::ACTION_PREVIOUS_ITEM:
case OpInputAction::ACTION_NEXT_ITEM:
{
if (!DropdownIsOpen())
{
ShowMenu();
return TRUE;
}
break;
}
case OpInputAction::ACTION_DELETE_SELECTED_ITEM:
{
int position = -1;
HistoryAutocompleteModelItem* item = GetSelectedItem(&position);
if(item && position >= 0)
{
DeleteItem(item, TRUE);
}
return TRUE;
}
case OpInputAction::ACTION_STOP:
case OpInputAction::ACTION_CLOSE_DROPDOWN:
{
if ( m_tab_cursor->GetWindowCommander() )
{
BOOL close_menu = action->GetAction() == OpInputAction::ACTION_CLOSE_DROPDOWN && DropdownIsOpen();
OpWindowCommander *win_comm = m_tab_cursor->GetWindowCommander();
if (action->IsKeyboardInvoked() && (!win_comm->IsLoading() || close_menu) && edit->IsFocused())
{
// The user pressed Esc :
// If the dropdown is open - close it :
if (DropdownIsOpen())
{
ShowDropdown(FALSE);
return TRUE;
}
// Get the text in the edit field :
OpString url;
GetText(url);
// Get the url of the current page or typed history :
OpString page_url;
if (m_tab_mode)
page_url.Set(win_comm->GetCurrentURL(FALSE));
else
page_url.Set(directHistory->GetFirst());
if (url.Compare(page_url.CStr()) == 0)
{
if (m_tab_mode)
{
// If they are the same focus the page :
ReleaseFocus(FOCUS_REASON_OTHER);
g_input_manager->InvokeAction(OpInputAction::ACTION_FOCUS_PAGE);
return TRUE;
}
else
{
// Let it be possible to close the dialog when pressing escape
return FALSE;
}
}
else
{
// Reset the edit field to the page url and select it:
SetText(page_url.CStr());
edit->UnsetForegroundColor();
edit->SelectText();
return TRUE;
}
}
}
break;
}
case OpInputAction::ACTION_AUTOCOMPLETE_SERVER_NAME:
{
OpString url;
if (m_is_quick_completed)
url.Set(m_text_before_quick_completion);
else
GetText(url);
url.Strip();
if (url.HasContent())
{
// start completing the url unless it's:
// 1) empty
// 2) already appears to be complete
// 3) looks like a search query eg. "g norske opera"
if (url.Find(UNI_L("://")) == KNotFound && url.FindFirstOf(' ') == KNotFound)
{
OpString prefix, suffix;
// add prefix to the url. f.i. "www." (suppplied as data string in action)
prefix.Set(action->GetActionDataString());
if (prefix.HasContent())
{
prefix.Append(UNI_L("."));
url.Insert(0, prefix);
}
// append suffix to the url. f.i. ".com" (suppplied as parameter in action)
suffix.Set(action->GetActionDataStringParameter());
if (suffix.HasContent())
url.AppendFormat(UNI_L(".%s"), suffix.CStr());
}
// set new url in the address edit field
SetText(url.CStr());
if (m_open_page_in_tab)
{
// Force the url to be loaded in the current active page.
// So the shift, ctrl modifiers do not change this behaviour
// (they conflict with keyboard shortcuts for this function).
g_input_manager->InvokeAction(OpInputAction::ACTION_OPEN_URL_IN_CURRENT_PAGE, 1, url.CStr(), this);
}
else
{
g_input_manager->InvokeAction(OpInputAction::ACTION_OK);
}
return TRUE;
}
break;
}
case OpInputAction::ACTION_GO_TO_TYPED_ADDRESS:
{
if (ActivateShowAllItem(action->IsMouseInvoked() != FALSE))
{
// Consume the action if this invoked the "show all" item.
return TRUE;
}
#ifdef ENABLE_USAGE_REPORT
if(g_usage_report_manager && g_usage_report_manager->GetSearchReport())
{
int pos = -1;
HistoryAutocompleteModelItem * item = GetSelectedItem(&pos);
g_usage_report_manager->GetSearchReport()->SetWasSuggestFromAddressDropdown(item && item->GetType() == OpTypedObject::WIDGET_TYPE_SEARCH_SUGGESTION_ITEM);
g_usage_report_manager->GetSearchReport()->SetWasSelectedFromAddressDropdown(pos > 0);
if(GetModel())
{
int count = GetModel()->GetCount();
g_usage_report_manager->GetSearchReport()->SetSelectedDefaultFromAddressDropdown(pos == count - 1);
}
}
#endif // ENABLE_USAGE_REPORT
break;
}
case OpInputAction::ACTION_SHOW_DROPDOWN:
{
if (edit)
edit->SetFocus(FOCUS_REASON_ACTION);
break;
}
case OpInputAction::ACTION_SHOW_ADDRESSBAR_OVERLAY:
{
GetWindowCommander()->GetUserConsent(DocumentDesktopWindow::ASK_FOR_PERMISSION_ON_USER_REQUEST);
return TRUE;
}
case OpInputAction::ACTION_OPEN:
if (action->IsActionDataStringEqualTo(UNI_L("URL Fav Menu")))
{
m_favorites_overlay_ctl = OP_NEW(FavoritesOverlayController, (m_url_fav_menu));
if (m_favorites_overlay_ctl)
{
m_favorites_overlay_ctl->SetListener(this);
m_url_fav_menu->SetDialogContext(m_favorites_overlay_ctl);
if (OpStatus::IsSuccess(ShowDialog(m_favorites_overlay_ctl, g_global_ui_context, GetParentDesktopWindow())))
{
OnShowFavoritesDialog();
}
}
return TRUE;
}
break;
}
return OpTreeViewDropdown::OnInputAction(action);
}
void OpAddressDropDown::OnChange(OpWidget *widget,
BOOL changed_by_mouse)
{
if (widget == edit)
{
m_actual_url.Empty();
m_selected_item = NULL;
OpString current_text;
GetText(current_text);
current_text.Strip(TRUE, TRUE);
if (GetWindowCommander())
{
// text could be short or full address
OpString show_address;
m_address.GetShowAddress(show_address);
m_url_page_mismatch = current_text.Compare(show_address) != 0 &&
current_text.Compare(GetWindowCommander()->GetCurrentURL(FALSE)) != 0 &&
current_text.Compare(GetWindowCommander()->GetLoadingURL(FALSE)) != 0;
UpdateProtocolStatus();
}
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::AutoDropDown) == TRUE)
{
//--------------------------------------------------
// The user has typed something - do autocompletion :
//--------------------------------------------------
m_url_proto_www_prefix.Empty();
//--------------------------------------------------
// If there is nothing - then do nothing :
//--------------------------------------------------
if(current_text.IsEmpty())
{
m_query_error_counter = 0;
Clear();
ShowDropdown(FALSE);
return;
}
//--------------------------------------------------
// Store the user text :
//--------------------------------------------------
SetUserString(current_text.CStr());
//--------------------------------------------------
// Quick "inline" completion of previosly typed urls.
//--------------------------------------------------
// FIX: We should probably not exclude local file urls. We should instead complete
// them if the user press tab! (same with all quick completed urls)
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
OpString stripped_local_file_url;
BOOL is_local_file_url = history_model->IsLocalFileURL(current_text, stripped_local_file_url);
OpString speed_dial_url, speed_dial_title;
uni_char * previously_typed_url = NULL;
if (!edit->IsComposing() &&
edit->IsLastUserChangeAnInsert() &&
// Only if the pref is enabled.
g_pcui->GetIntegerPref(PrefsCollectionUI::AddressbarInlineAutocompletion) &&
// Only if the caret is at the end, so the user can edit other parts without jumping to the end.
edit->GetCaretOffset() == current_text.Length() &&
!is_local_file_url &&
!g_hotlist_manager->HasNickname(current_text.CStr(), NULL) &&
!g_speeddial_manager->IsAddressSpeedDialNumber(current_text.CStr(), speed_dial_url, speed_dial_title))
{
SearchEngineManager::SearchSetting setting;
setting.m_target_window = GetParentDesktopWindow();
setting.m_keyword.Set(current_text);
if (!g_searchEngineManager->CanSearch(setting) || g_searchEngineManager->IsSingleWordSearch(current_text.CStr()))
{
// Iterate through all typed history and look for last typed match.
// After that, look for the shortest match matching the last typed match.
uni_char * candidate = NULL;
int candidate_len = 0;
OpString candidate_url_proto_www_prefix;
uni_char * address = directHistory->GetFirst();
while (address)
{
// DeduceProtocolOrSubdomain leaves prefix for this address in m_url_proto_www_prefix
m_url_proto_www_prefix.Empty();
address = DeduceProtocolOrSubdomain(current_text, address);
// Check if it's a match
if (current_text.Compare(address, current_text.Length()) == 0 &&
// Experiment: Do we wan't to complete really long urls? They're probably pasted and
// not subject for re-entering anyway which might look odd with to long urls anyway.
uni_strlen(address) < 40 &&
// Don't quick-complete other things than urls
g_searchEngineManager->IsUrl(address))
{
OpString domain;
unsigned domain_offset = 0;
if (OpStatus::IsError(StringUtils::FindDomain(address, domain, domain_offset)))
continue;
int address_len = uni_strlen(address);
// look for the shortest address matching the first domain provided by direct history
// (direct history provides entries sorted by last asscess time) : DSK-366279
if (!candidate || (address_len < candidate_len && domain.Compare(candidate,domain.Length()) == 0))
{
candidate = address;
candidate_len = address_len;
OpStatus::Ignore(candidate_url_proto_www_prefix.Set(m_url_proto_www_prefix));
}
}
address = directHistory->GetNext();
}
// We're done
OpStatus::Ignore(m_url_proto_www_prefix.Set(candidate_url_proto_www_prefix));
previously_typed_url = candidate;
}
}
// Insert the inline completion in the textfield.
if (previously_typed_url)
{
m_text_before_quick_completion.Set(current_text);
m_is_quick_completed = true;
// Experiment: If we don't want this, we should make a item and put it first instead.
OP_ASSERT(current_text.Length() <= (int)uni_strlen(previously_typed_url));
if (OpStatus::IsSuccess(OpDropDown::SetText(previously_typed_url, TRUE, TRUE)))
{
edit->SetSelection(current_text.Length(), uni_strlen(previously_typed_url));
edit->SetCaretOffset(current_text.Length());
}
}
else
{
m_is_quick_completed = false;
}
//--------------------------------------------------
// If you are supposed to do browse engine module then wait until that is done
// before populating the dropdown - otherwise just populate it
//--------------------------------------------------
// Start a new one
if(current_text.Length() >= SEARCH_LENGTH_THRESHOLD)
{
QuerySearchEngineModule(current_text);
}
else
{
PopulateDropdown();
}
}
}
else if(widget == GetTreeView())
{
HistoryAutocompleteModelItem* item = GetSelectedItem();
if (item && item->GetIndex() >0)
{
m_selected_item = item;
}
//--------------------------------------------------
// If the user has selected an item show the address
// Only as a result of a keyboard action :
//--------------------------------------------------
if (!changed_by_mouse && item)
{
if(item->GetType() == OpTypedObject::WIDGET_TYPE_SEARCH_SUGGESTION_ITEM)
{
if (!m_lock_current_text)
{
OpString formated_string;
if(OpStatus::IsSuccess(GetFormattedSuggestedSearch(static_cast<SearchSuggestionAutocompleteItem*>(item), formated_string)))
{
SetText(formated_string);
}
}
}
else
{
// Get the address to go to
OpString address;
if (!m_lock_current_text && OpStatus::IsSuccess(item->GetAddress(address)))
{
if (m_use_display_url && item->HasDisplayAddress())
{
m_actual_url.Set(address);
item->GetDisplayAddress(address);
SetText(address.CStr());
}
else
{
SetText(address.CStr());
}
}
}
}
}
}
void OpAddressDropDown::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks)
{
int position = -1;
GenericTreeModelItem* item = GetSelectedItem(&position);
if(item && nclicks == 1 && widget->GetType() == WIDGET_TYPE_TREEVIEW)
{
if(((OpTreeView*)widget)->IsHoveringAssociatedImageItem(pos) && !down)
{
// we clicked the close button on the history item, remove it
m_mh->PostDelayedMessage(MSG_QUICK_REMOVE_ADDRESSFIELD_HISTORY_ITEM, (MH_PARAM_1)item, 0, 0);
return;
}
}
OpTreeViewDropdown::OnMouseEvent(widget, pos, x, y, button, down, nclicks);
// Set the address as it was in none focus and eventually add query field in order to get the
// right caret offset when focus is gained
if (widget->IsOfType(WIDGET_TYPE_EDIT) && down && GetFocused()!=edit && m_address.HasContent() &&
!m_url_page_mismatch && !g_pcui->GetIntegerPref(PrefsCollectionUI::ShowFullURL))
{
OpString show_address;
m_address.GetShowAddress(show_address);
show_address.Append(m_address.GetQueryField());
show_address.Append(UNI_L("/")); // compensate for the removal of the ending '/'
OpTreeViewDropdown::SetText(show_address);
}
}
void OpAddressDropDown::OnMouseMove(OpWidget *widget, const OpPoint &point)
{
#ifdef REMOVE_HIGHLIGHT_ONHOVER
UpdateAddressFieldHighlight();
#endif
}
void OpAddressDropDown::OnMouseLeave(OpWidget *widget)
{
#ifdef REMOVE_HIGHLIGHT_ONHOVER
UpdateAddressFieldHighlight(TRUE);
#endif
}
void OpAddressDropDown::DeleteHistoryModelItem(const uni_char *str)
{
HistoryModelItem* history_item = DesktopHistoryModel::GetInstance()->GetItemByUrl(str);
if(history_item)
{
// Delete the item in the source
DesktopHistoryModel::GetInstance()->Delete(history_item);
}
}
void OpAddressDropDown::RemovePossibleContentSearchItems(OpStringC url)
{
DeleteHistoryModelItem(url);
// DSK-355955 Removing both http and https address from history when deleting one variant
int pos = url.Find(UNI_L("://"));
if (pos != KNotFound && url.Find("http") == 0)
{
OpString address_variant;
RETURN_VOID_IF_ERROR(address_variant.Set(pos == 4 ? UNI_L("https") : UNI_L("http")));
RETURN_VOID_IF_ERROR(address_variant.Append(url.SubString(pos)));
DeleteHistoryModelItem(address_variant);
}
// Remove similar item too (Similar items won't be visible in the list, but we should remove them)
// This should match the behaviour of HasSimilarItem.
pos = url.Find(UNI_L("://www."));
if (pos != KNotFound)
{
OpString similar_address;
RETURN_VOID_IF_ERROR(similar_address.Set(url));
similar_address.Delete(pos + 3, 4); // Delete "www." from the url.
DeleteHistoryModelItem(similar_address);
}
}
void OpAddressDropDown::DeleteItem(HistoryAutocompleteModelItem *item, BOOL call_on_change)
{
if (!DropdownIsOpen() || !item || !item->IsUserDeletable())
return;
OpString url;
RETURN_VOID_IF_ERROR(item->GetAddress(url));
if (item->IsInDirectHistory())
{
if (item->IsInDesktopHistoryModel())
{
DeleteFromDirectHistory(url);
}
else if (directHistory->Delete(url.CStr()))
{
INT32 pos = m_items_to_delete.Find(item);
if (pos != -1)
m_items_to_delete.Remove(pos);
item->Delete();
item = NULL;
}
}
if (item && item->IsInDirectHistory())
{
OP_ASSERT(m_items_to_delete.Find(item) == -1);
RemovePossibleContentSearchItems(url);
}
// Show again to automatically resize the dropdown
ShowDropdown(GetModel()->GetCount() > 0);
if (call_on_change)
{
// Call OnChange so we update info to the new selected item.
OnChange(GetTreeView(), FALSE);
}
}
void OpAddressDropDown::DeleteFromDirectHistory(OpStringC full_address)
{
// Due to performance issues there are deleted only full address, domain,
// domain/ if there is no '.' (user has to put domains without '.'
// with '/' at the end to prevent searching domain on default search
// engine) and www.domain. This should cover most of the cases of typed
// addresses.
directHistory->Delete(full_address);
OpString address_to_delete;
unsigned starting_position;
RETURN_VOID_IF_ERROR(StringUtils::FindDomain(full_address, address_to_delete, starting_position));
// Do not delete anything else if the full address goes to sub page of
// given domain.
if (address_to_delete.IsEmpty() || (address_to_delete.Length() + starting_position + 1 < unsigned(full_address.Length())))
return;
directHistory->Delete(address_to_delete);
if (address_to_delete.Find(UNI_L(".")) == KNotFound)
{
RETURN_VOID_IF_ERROR(address_to_delete.Append(UNI_L("/")));
directHistory->Delete(address_to_delete);
address_to_delete.Delete(address_to_delete.Length() - 1);
}
RETURN_VOID_IF_ERROR(address_to_delete.Insert(0, UNI_L("www.")));
directHistory->Delete(address_to_delete);
}
void OpAddressDropDown::GetBookmarks(const OpString& current_text, OpVector<HistoryAutocompleteModelItem>& result)
{
// this is probably some random text pasted accidentally into address bar and
// highlighting with large number of phrases may freeze UI for a few seconds (DSK-340411)
if (current_text.Length() > 1024)
return;
HotlistModel* bookmarks = g_hotlist_manager->GetBookmarksModel();
WordHighlighter word_highlighter;
for(int i = 0; (i < bookmarks->GetCount()) && (result.GetCount() < 20); i++)
{
// Get the bookmark
HotlistModelItem* item = bookmarks->GetItemByIndex(i);
if(item->GetType() != OpTypedObject::BOOKMARK_TYPE)
continue;
// Cast it to the correct type
Bookmark* bookmark = static_cast<Bookmark*>(item);
// Get the core history item for this bookmark
HistoryPage* page = bookmark->GetHistoryItem();
if(!page)
continue;
// Get the HistoryModelPage item for the core item
HistoryModelPage* history_item = DesktopHistoryModel::GetInstance()->GetPage(page);
if(!history_item)
continue;
// Get the simple item
PageBasedAutocompleteItem * simple_item = history_item->GetSimpleItem();
if(result.Find(simple_item) != -1)
continue;
// If it is not already in the model - check if it matches
if(simple_item && !simple_item->GetModel())
{
if (word_highlighter.Empty())
{
RETURN_VOID_IF_ERROR(word_highlighter.Init(current_text.CStr()));
if (word_highlighter.Empty())
return;
}
if(MatchAndHighlight(bookmark, history_item, word_highlighter))
{
simple_item->SetSearchType(PageBasedAutocompleteItem::BOOKMARK);
result.Add(simple_item);
}
}
}
}
BOOL OpAddressDropDown::MatchAndHighlight(Bookmark* bookmark,
HistoryModelPage* page,
WordHighlighter& word_highlighter)
{
if(!bookmark || !page)
return FALSE;
// Get the url:
OpString address;
RETURN_VALUE_IF_ERROR(address.Set(bookmark->GetDisplayUrl()), FALSE);
// Make the haystack
OpString haystack;
RETURN_VALUE_IF_ERROR(haystack.AppendFormat(UNI_L("%s %s %s"),
StringUtils::GetNonNullString(address),
StringUtils::GetNonNullString(bookmark->GetName()),
StringUtils::GetNonNullString(bookmark->GetDescription())), FALSE);
// Check that it is a match
if(!word_highlighter.ContainsWords(haystack))
return FALSE;
// Do the default highlighting
HistoryAutocompleteModelItem * simple_item = page->GetSimpleItem();
// Use the bookmark title for this hit
simple_item->SetBookmark(bookmark);
// Use the description for associated text, and highlight it
if (bookmark->GetName())
{
// Copy the description
OpString bookmark_name;
RETURN_VALUE_IF_ERROR(bookmark_name.Set(bookmark->GetName()), FALSE);
// Make highlighted name
OpString highlighted_name;
RETURN_VALUE_IF_ERROR(word_highlighter.AppendHighlight(highlighted_name,
bookmark_name.CStr(),
KAll,
UNI_L("<b>"),
UNI_L("</b>"),
-1), FALSE);
RETURN_VALUE_IF_ERROR(simple_item->SetAssociatedText(highlighted_name), FALSE);
}
else if(bookmark->GetDescription().HasContent())
{
// Copy the description
OpString bookmark_description;
RETURN_VALUE_IF_ERROR(bookmark_description.Set(bookmark->GetDescription()), FALSE);
// Make highlighted description
OpString highlighted_description;
RETURN_VALUE_IF_ERROR(word_highlighter.AppendHighlight(highlighted_description,
bookmark_description.CStr(),
KAll,
UNI_L("<b>"),
UNI_L("</b>"),
-1), FALSE);
RETURN_VALUE_IF_ERROR(simple_item->SetAssociatedText(highlighted_description), FALSE);
}
return TRUE;
}
bool OpAddressDropDown::ShouldQuerySearchSuggestions(const OpStringC& current_text)
{
if (!m_show_search_suggestions || current_text.Length() < SEARCH_LENGTH_THRESHOLD ||
(g_pcui->GetIntegerPref(PrefsCollectionUI::ShowSearchesInAddressfieldAutocompletion) == 0 && !g_searchEngineManager->IsSearchString(current_text)))
return false;
DocumentDesktopWindow* window = g_application->GetActiveDocumentDesktopWindow();
if (window && window->PrivacyMode())
return false;
if (!m_regex)
{
OpREFlags flags;
flags.multi_line = FALSE;
flags.case_insensitive = TRUE;
flags.ignore_whitespace = FALSE;
RETURN_VALUE_IF_ERROR(OpRegExp::CreateRegExp(&m_regex, UNI_L("^(htt(ps?)?|(www)|(ftp))$"), &flags), false);
}
OpREMatchLoc match_pos;
RETURN_VALUE_IF_ERROR(OpStatus::IsSuccess(m_regex->Match(current_text, &match_pos)), false);
if (match_pos.matchloc == 0)
return false;
if (current_text.FindFirstOf(UNI_L(" ")) != KNotFound)
return true;
if (current_text.Find(UNI_L(".")) == KNotFound && current_text.Find(UNI_L(":")) == KNotFound && current_text.Find(UNI_L("/")) == KNotFound)
return true;
return false;
}
void OpAddressDropDown::QuerySearchSuggestions(const OpStringC& search_phrase, SearchTemplate* search_template)
{
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
if (!search_template)
{
search_template = g_searchEngineManager->GetDefaultSearch();
}
if (!search_template)
{
return;
}
if(!m_search_suggest_in_progress && search_phrase.HasContent() && m_search_suggest->HasSuggest(search_template->GetUniqueGUID()))
{
RETURN_VOID_IF_ERROR(m_search_phrase.Set(search_phrase));
StartSearchSuggest();
}
#endif // DESKTOP_UTIL_SEARCH_ENGINES
}
void OpAddressDropDown::HandleSearchEngineModuleCallback(const OpStringC& search_text, OpAutoVector<VisitedSearch::SearchResult>* result)
{
if(!result)
{
return;
}
m_search_engine_items.Clear();
for(unsigned int i = 0; i < result->GetCount(); i++)
{
VisitedSearch::SearchResult * search_result = result->Get(i);
OpString url;
url.SetFromUTF8(search_result->url.CStr());
//--------------------------------------------------
// Find the history item - note it _should_ always exist :
//--------------------------------------------------
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
HistoryModelPage * item = history_model->GetItemByUrl(url);
bool page_content_search_enabled = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::PageContentSearch) == 1;
if(item && item->IsInHistory())
{
PageBasedAutocompleteItem* simple_item = item->GetSimpleItem();
OpString title;
RETURN_VOID_IF_ERROR(simple_item->GetTitle(title));
if (search_text.FindI(" ") != KNotFound)
{
bool found = false;
UniString uni_input;
uni_input.SetConstData(search_text.CStr());
OpAutoPtr< OtlCountedList<UniString> > parts(uni_input.Split(' '));
for (OtlList<UniString>::Iterator part = parts->Begin(); part != parts->End(); ++part)
{
if (part->IsEmpty())
continue;
if (title.FindI(part->Data(true)) == KNotFound && url.FindI(part->Data(true)) == KNotFound)
{
found = false;
break;
}
found = true;
}
if (found)
{
m_search_engine_items.Add(simple_item);
return;
}
}
if (title.FindI(search_text) != KNotFound || url.FindI(search_text) != KNotFound)
{
m_search_engine_items.Add(simple_item);
}
else if (page_content_search_enabled)
{
simple_item->SetSearchType(PageBasedAutocompleteItem::PAGE_CONTENT);
if (search_result->excerpt.CStr())
simple_item->SetAssociatedText(search_result->excerpt);
m_search_engine_items.Add(simple_item);
}
}
}
}
void OpAddressDropDown::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
if(msg == MSG_QUICK_START_SEARCH_SUGGESTIONS)
{
if(m_search_suggest_in_progress)
{
// already in progress - repost it
StartSearchSuggest();
return;
}
OpString key, value;
if(m_search_phrase.HasContent())
{
SearchEngineManager::SplitKeyValue(m_search_phrase, key, value);
SearchTemplate* search_template = NULL;
if (key.HasContent())
{
search_template = g_searchEngineManager->GetSearchEngineByKey(key);
}
else
{
search_template = g_searchEngineManager->GetDefaultSearch();
}
if (!search_template)
{
return;
}
if (value.HasContent())
{
OpString guid;
if (OpStatus::IsSuccess(search_template->GetUniqueGUID(guid)))
m_search_suggest->Connect(value, guid, SearchTemplate::ADDRESS_BAR);
}
else
{
if (GetModel())
{
GetModel()->RemoveAll();
}
DeleteItems(m_search_suggestions_items);
PopulateDropdown(false);
}
}
return;
}
else if (msg == MSG_VPS_SEARCH_RESULT)
{
// make sure we don't leak even if we don't process the search result
OpAutoPtr<OpAutoVector<VisitedSearch::SearchResult> > results(reinterpret_cast<OpAutoVector<VisitedSearch::SearchResult>*>(par2));
if (m_process_search_results)
{
OpString current_text;
OP_STATUS status = OpStatus::OK;
if (GetModel())
{
GetModel()->RemoveAll();
}
if (m_is_quick_completed)
{
status = current_text.Set(m_text_before_quick_completion);
}
else
{
status = GetText(current_text);
current_text.Strip();
}
if (OpStatus::IsSuccess(status))
{
if (ShouldQuerySearchSuggestions(current_text))
{
QuerySearchSuggestions(current_text);
}
else
{
DeleteItems(m_search_suggestions_items);
}
HandleSearchEngineModuleCallback(current_text, results.get());
}
PopulateDropdown();
}
}
else if (msg == MSG_QUICK_REMOVE_ADDRESSFIELD_HISTORY_ITEM)
{
HistoryAutocompleteModelItem *item = reinterpret_cast<HistoryAutocompleteModelItem*>(par1);
if(item && GetModel() && GetModel()->GetIndexByItem(item) > -1)
DeleteItem(item, FALSE);
}
else
OpTreeViewDropdown::HandleCallback(msg, par1, par2);
}
void OpAddressDropDown::QuerySearchEngineModule(const OpStringC& current_text)
{
#ifdef VPS_WRAPPER
OpString search_text;
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
// Strip away the history search prefix
OpString key;
OpString value;
SearchEngineManager::SplitKeyValue(current_text, key, value);
RETURN_VOID_IF_ERROR(search_text.Set(value.CStr()));
#else
RETURN_VOID_IF_ERROR(search_text.Set(current_text.CStr()));
#endif // DESKTOP_UTIL_SEARCH_ENGINES
RETURN_VOID_IF_ERROR(g_visited_search->Search(search_text.CStr(),
VisitedSearch::RankSort,
10,
300,
UNI_L("<b>"),
UNI_L("</b>"),
16,
this));
m_process_search_results = TRUE;
#endif // VPS_WRAPPER
}
bool OpAddressDropDown::HasSimilarItem(const HistoryAutocompleteModelItem* item, const OpVector<HistoryAutocompleteModelItem>& items)
{
OP_ASSERT(!item->GetModel());
for(unsigned i = 0; i < items.GetCount(); i++)
{
HistoryAutocompleteModelItem *added_item = items.Get(i);
OpString address, added_address;
item->GetAddress(address);
added_item->GetAddress(added_address);
// Compare the addresses without www. since we get lots of duplicates with and without www.
// Is there any way to make this cheaper? m_page m_core_page seems to have a m_key which may be what we want?
INT32 pos = address.Find(UNI_L("://www."));
if (pos != -1)
address.Delete(pos + 3, 4);
pos = added_address.Find(UNI_L("://www."));
if (pos != -1)
added_address.Delete(pos + 3, 4);
if (added_address == address)
return TRUE;
}
return FALSE;
}
void OpAddressDropDown::PopulateDropdown(bool refresh_history)
{
//--------------------------------------------------
// If we don't have focus do not display the dropdown
// This message is too late - ignore it
//--------------------------------------------------
if(!HasFocus())
return;
OpString stripped;
OpString current_text;
if (m_is_quick_completed)
{
current_text.Set(m_text_before_quick_completion);
}
else
{
GetText(current_text);
}
//--------------------------------------------------
// If there is nothing - then do nothing :
//--------------------------------------------------
if(current_text.IsEmpty())
{
Clear();
ShowDropdown(FALSE);
return;
}
//--------------------------------------------------
// Initialize the dropdown :
//--------------------------------------------------
RETURN_VOID_IF_ERROR(InitTreeViewDropdown("Addressfield Treeview Window Skin"));
if (refresh_history)
{
m_history_items.Clear();
m_item_to_select = NULL;
}
if (current_text.Length()<SEARCH_LENGTH_THRESHOLD)
{
DeleteItems(m_search_suggestions_items);
m_search_engine_items.Clear();
}
m_more_items.Clear();
HistoryAutocompleteModel* tree_model = NULL;
tree_model = OP_NEW(HistoryAutocompleteModel, ());
if (!tree_model)
{
return;
}
SetModel(tree_model, FALSE);
if(!GetTreeView())
{
return;
}
GetTreeView()->SetExtraLineHeight(4);
GetTreeView()->SetExpandOnSingleClick(FALSE);
GetTreeView()->SetOnlyShowAssociatedItemOnHover(TRUE);
GetTreeView()->SetAllowWrappingOnScrolling(TRUE);
GetTreeView()->SetPaintBackgroundLine(FALSE);
if (IsOperaPage(current_text))
{
AddOperaPages(current_text);
}
else if (refresh_history)
{
// ... then - if old searches are obsolete - start new search
if (ShouldQuerySearchSuggestions(current_text))
{
OpString key;
OpString value;
SearchEngineManager::SplitKeyValue(current_text, key, value);
SearchTemplate* search_template = g_searchEngineManager->GetSearchEngineByKey(key);
QuerySearchSuggestions(current_text, search_template);
}
}
if (AddSearchForItem(current_text))
{
m_item_to_select = m_search_for_item;
}
OpString search_for_address;
if (m_search_for_item)
m_search_for_item->GetAddress(search_for_address);
for (unsigned i = 0; i < m_search_suggestions_items.GetCount(); ++i)
{
SearchSuggestionAutocompleteItem* item = m_search_suggestions_items.Get(i);
OpString current_address;
if (OpStatus::IsSuccess(item->GetAddress(current_address)) && current_address == search_for_address)
continue;
item->SetShowSearchEngine();
GetModel()->AddLast(item);
}
AddPreviousSearches(current_text);
if (refresh_history)
PrepareHistory(current_text);
AddSpeedDialAddress(current_text);
OpVector<HistoryAutocompleteModelItem> combined_items;
for (unsigned i = 0; i < m_history_items.GetCount(); ++i)
{
HistoryAutocompleteModelItem* item = m_history_items.Get(i);
if (refresh_history)
item->UpdateRank(current_text);
combined_items.Add(item);
}
combined_items.QSort(HistoryAutocompleteModelItem::Cmp);
unsigned max_items = MAX_ROWS_IN_DROPDOWN - MAX_SUGGESTIONS_ADDRESS_FIELD_SEARCH;
for (unsigned i = 0; i < combined_items.GetCount(); ++i)
{
HistoryAutocompleteModelItem* item = combined_items.Get(i);
if (i < max_items || (m_more_items.GetCount() == 0 && combined_items.GetCount() == i + 1))
{
GetModel()->AddLast(item);
OpString item_address;
if (OpStatus::IsSuccess(item->GetAddress(item_address)) && item_address == current_text)
{
m_item_to_select = item;
}
}
else
m_more_items.Add(item);
}
if (m_more_items.GetCount() > 0)
AddExpander();
if (!m_is_quick_completed && m_item_to_select && !g_searchEngineManager->IsUrl(current_text.CStr()))
{
++m_lock_current_text;
SetSelectedItem(m_item_to_select, TRUE);
--m_lock_current_text;
}
else if (m_selected_item && !refresh_history)
{
++m_lock_current_text;
SetSelectedItem(m_selected_item, TRUE);
--m_lock_current_text;
}
ShowDropdown(GetModel()->GetCount() > 0);
}
bool OpAddressDropDown::AddSearchForItem(const OpStringC& current_text)
{
if (m_search_for_item || !m_show_speed_dial_pages)
return false;
OpString key;
OpString value;
OpString search_label;
OpString search_string;
OpString text;
SearchEngineManager::SplitKeyValue(current_text, key, value);
OpAutoPtr<SearchSuggestionAutocompleteItem> item(OP_NEW(SearchSuggestionAutocompleteItem, (GetModel())));
if (!item.get())
return false;
item->SetIsSearchWith();
RETURN_VALUE_IF_ERROR(item->SetHighlightText(value),false);
RETURN_VALUE_IF_ERROR(item->SetSearchSuggestion(value.CStr()), false);
SearchTemplate* search_template = NULL;
if (g_searchEngineManager->IsSearchString(current_text))
search_template = g_searchEngineManager->GetSearchEngineByKey(key);
else
search_template = g_searchEngineManager->GetDefaultSearch();
if (!search_template)
return false;
RETURN_VALUE_IF_ERROR(item->SetSearchProvider(search_template->GetUniqueGUID()), false);
RETURN_VALUE_IF_ERROR(item->SetAddress(search_string), false);
RETURN_VALUE_IF_ERROR(item->SetItemData(1, text.CStr()), false);
item->SetBadgeWidth(m_protocol_button->GetWidth());
if (GetModel()->AddLast(item.get()) >= 0)
{
m_search_for_item = item.release();
return true;
}
return false;
}
void OpAddressDropDown::PrepareHistory(const OpString& current_text)
{
OpVector<HistoryAutocompleteModelItem> history_items;
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
OpStatus::Ignore(history_model->GetSimpleItems(current_text, history_items));
if (OpStatus::IsError(history_model->AddDesktopHistoryModelListener(this)))
return;
GetBookmarks(current_text, history_items);
for (unsigned i = 0; i < m_search_engine_items.GetCount(); ++i)
{
OpStatus::Ignore(history_items.Add(m_search_engine_items.Get(i)));
}
for (unsigned int i = 0; i < history_items.GetCount(); i++)
{
HistoryAutocompleteModelItem* item_to_add = history_items.Get(i);
OpString display_address;
if (OpStatus::IsError(item_to_add->GetDisplayAddress(display_address)))
continue;
if (IsOperaPage(display_address))
continue;
if (HasSimilarItem(item_to_add, m_history_items))
continue;
bool found = false;
for (unsigned j = 0; j < m_history_items.GetCount(); ++j)
{
OpString address;
if (OpStatus::IsError(m_history_items.Get(j)->GetDisplayAddress(address)))
{
continue;
}
if (display_address == address)
{
found = true;
break;
}
}
if (found)
continue;
item_to_add->SetHighlightText(current_text);
item_to_add->SetBadgeWidth(m_protocol_button->GetWidth());
m_history_items.Add(item_to_add);
}
}
void OpAddressDropDown::AddOperaPages(const OpString& current_text)
{
int colon_position = current_text.Find(":");
OP_ASSERT(colon_position == 1 || colon_position == 5);
OpStringC opera_page = current_text.SubString(colon_position + 1);
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
OpVector<PageBasedAutocompleteItem> opera_pages;
history_model->GetOperaPages(opera_page, opera_pages);
unsigned lines_to_add = min((unsigned)GetMaxLines(), opera_pages.GetCount());
for (unsigned i = 0; i < lines_to_add; ++i)
{
PageBasedAutocompleteItem* item = opera_pages.Get(i);
item->SetSearchType(PageBasedAutocompleteItem::OPERA_PAGE);
item->SetBadgeWidth(m_protocol_button->GetWidth());
GetModel()->AddLast(item);
}
}
bool OpAddressDropDown::AddSpeedDialAddress(const OpString& current_text)
{
if (!m_show_speed_dial_pages)
{
return false;
}
OpString speed_dial_url;
OpString speed_dial_title;
if (!g_speeddial_manager->IsAddressSpeedDialNumber(current_text, speed_dial_url, speed_dial_title))
{
return false;
}
SimpleAutocompleteItem* item = OP_NEW(SimpleAutocompleteItem, (GetModel()));
if (!item || OpStatus::IsError(m_items_to_delete.Add(item)))
{
OP_DELETE(item);
return false;
}
OpString str;
RETURN_VALUE_IF_ERROR(g_languageManager->GetString(Str::S_ADDRESS_FIELD_OPEN_DIAL, str),false);
OpString info;
RETURN_VALUE_IF_ERROR(info.AppendFormat(str.CStr(), uni_atoi(current_text.CStr())),false);
RETURN_VALUE_IF_ERROR(item->SetItemData(1, info.CStr()),false);
int color = SkinUtils::GetTextColor("Address DropDown URL Label");
if (color >= 0)
{
item->SetItemColor(1, color);
}
item->SetBadgeWidth(m_protocol_button->GetWidth());
RETURN_VALUE_IF_ERROR(item->SetItemData(1, speed_dial_title.CStr()),false);
RETURN_VALUE_IF_ERROR(item->SetItemImage("Window Document Icon"),false);
RETURN_VALUE_IF_ERROR(item->SetAddress(current_text.CStr()),false);
if (GetModel()->AddLast(item) == -1)
return false;
m_item_to_select = item;
return true;
}
void OpAddressDropDown::AddExpander()
{
OP_DELETE(m_show_all_item);
m_show_all_item = OP_NEW(SimpleAutocompleteItem, (GetModel()));
if (!m_show_all_item)
{
return;
}
OpString str;
OpString info;
if (OpStatus::IsError(g_languageManager->GetString(Str::S_ADDRESS_FIELD_SHOW_MORE, str)))
{
return;
}
if (OpStatus::IsError(info.AppendFormat(str.CStr(), m_more_items.GetCount())))
{
return;
}
m_show_all_item->SetShowAll(TRUE);
m_show_all_item->SetItemData(1, info.CStr());
m_show_all_item->SetBadgeWidth(m_protocol_button->GetWidth());
int color = SkinUtils::GetTextColor("Address DropDown URL Label");
if (color >= 0)
{
m_show_all_item->SetItemColor(1, color);
}
GetModel()->AddLast(m_show_all_item);
for(UINT32 i = 0; i < m_more_items.GetCount(); i++)
{
if(!m_more_items.Get(i)->GetModel())
{
m_show_all_item->AddChildLast(m_more_items.Get(i));
}
}
}
void OpAddressDropDown::AddPreviousSearches(const OpStringC& search_text)
{
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
OpString key;
OpString value;
SearchEngineManager::SplitKeyValue(search_text, key, value);
SearchTemplate* search_template = g_searchEngineManager->GetSearchEngineByKey(key);
if(!search_template)
return;
int len = search_text.Length();
uni_char * address = directHistory->GetFirst();
// Add up to three previous searches
for (unsigned count = 0; address && count < 3;)
{
if(uni_strncmp(search_text.CStr(), address, len) == 0)
{
count++;
OpString search_name;
RETURN_VOID_IF_ERROR(search_template->GetEngineName(search_name));
SimpleAutocompleteItem * simple_item = OP_NEW(SimpleAutocompleteItem, (GetModel()));
if (!simple_item || OpStatus::IsError(simple_item->SetAddress(address)) ||
OpStatus::IsError(m_items_to_delete.Add(simple_item)))
{
OP_DELETE(simple_item);
return;
}
simple_item->SetInDirectHistory(TRUE);
OpString previous_search_text;
previous_search_text.Set(address);
previous_search_text.Append(" - ");
previous_search_text.Append(search_name.CStr());
simple_item->SetItemData(1, previous_search_text);
simple_item->SetBadgeWidth(m_protocol_button->GetWidth());
int color = SkinUtils::GetTextColor("Address DropDown URL Label");
if (color >= 0)
{
simple_item->SetItemColor(1, color);
}
simple_item->SetFavIconKey(search_template->GetUrl());
simple_item->SetItemImage(search_template->GetSkinIcon());
GetModel()->AddLast(simple_item);
}
address = directHistory->GetNext();
}
#endif // DESKTOP_UTIL_SEARCH_ENGINES
}
bool OpAddressDropDown::IsOperaPage(const OpString& address) const
{
// Check if address begins either with opera: or with o:
return address.CompareI("opera:", 6) == 0 || address.CompareI("o:", 2) == 0;
}
void OpAddressDropDown::StartIntranetTest(const uni_char *address)
{
OP_ASSERT(g_searchEngineManager->IsIntranet(address));
OP_DELETE(m_host_resolver);
m_host_resolver = NULL;
RETURN_VOID_IF_ERROR(m_host_resolve_address.Set(address));
if (OpStatus::IsSuccess(SocketWrapper::CreateHostResolver(&m_host_resolver, this)))
m_host_resolver->Resolve(address);
}
void OpAddressDropDown::OnHostResolved(OpHostResolver* host_resolver)
{
DesktopWindow *dw = GetParentDesktopWindow();
if (!dw || dw->GetType() != WINDOW_TYPE_DOCUMENT)
return;
DocumentDesktopWindow *ddw = (DocumentDesktopWindow*) dw;
ddw->ShowGoToIntranetBar(m_host_resolve_address.CStr());
// Cleanup right away
OP_DELETE(m_host_resolver);
m_host_resolver = NULL;
}
void OpAddressDropDown::OnHostResolverError(OpHostResolver* host_resolver, OpHostResolver::Error error)
{
// Cleanup right away
OP_DELETE(m_host_resolver);
m_host_resolver = NULL;
}
/***********************************************************************************
**
** TextIsNotUrl - used by TabTextContent
**
***********************************************************************************/
BOOL OpAddressDropDown::TextIsNotUrl(const OpStringC& text, OpWindowCommander* windowcommander)
{
OpString url;
OpStatus::Ignore(WindowCommanderProxy::GetMovedToURL(windowcommander).GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden, url));
return (text.Compare(url) != 0);
}
/***********************************************************************************
**
** ShowDropdown
**
***********************************************************************************/
void OpAddressDropDown::ShowDropdown(BOOL show)
{
// we want to process search results as long as the dropdown is open
m_process_search_results = show;
OpTreeViewDropdown::ShowDropdown(show);
}
/***********************************************************************************
**
** OnClear
**
***********************************************************************************/
void OpAddressDropDown::OnClear()
{
DeleteItems(m_items_to_delete);
OP_DELETE(m_search_for_item);
m_search_for_item = NULL;
}
void OpAddressDropDown::OnDropdownMenu(OpWidget *widget, BOOL show)
{
if (show)
{
//--------------------------------------------------
// Initialize the dropdown :
//--------------------------------------------------
RETURN_VOID_IF_ERROR(InitTreeViewDropdown("Addressfield Treeview Window Skin"));
OP_ASSERT(m_items_to_delete.GetCount() == 0); // It should be empty now
GetTreeView()->SetOnlyShowAssociatedItemOnHover(TRUE);
GetTreeView()->SetAllowWrappingOnScrolling(TRUE);
//--------------------------------------------------
// Make sure we have a model :
//--------------------------------------------------
// The dropdown is responsible for deleting the items
BOOL items_deletable = TRUE;
HistoryAutocompleteModel *tree_model = OP_NEW(HistoryAutocompleteModel, ());
if (!tree_model)
return;
SetModel(tree_model, items_deletable);
uni_char * address = directHistory->GetFirst();
int num_items = 0;
while (address)
{
OpString key;
OpString value;
SearchEngineManager::SplitKeyValue(address, key, value);
SimpleAutocompleteItem* simple_item = OP_NEW(SimpleAutocompleteItem, (GetModel()));
if (!simple_item)
return;
simple_item->SetAddress(address);
simple_item->SetItemData(1, address, 0, 0);
simple_item->SetBadgeWidth(m_protocol_button->GetWidth());
int color = SkinUtils::GetTextColor("Address DropDown URL Label");
if (color >= 0)
{
simple_item->SetItemColor(1, color);
}
simple_item->SetUserDeletable(TRUE);
simple_item->SetInDirectHistory(TRUE);
simple_item->SetIsTypedHistory();
GetModel()->AddLast(simple_item, -1);
simple_item->SetFavIconKey(address);
simple_item->SetItemImage("Window Document Icon");
num_items++;
address = directHistory->GetNext();
}
ShowDropdown(num_items > 0);
}
else
{
Clear();
}
}
/************************************************************************************/
bool OpAddressDropDown::ActivateShowAllItem(bool mouse_invoked)
{
HistoryAutocompleteModelItem* item = GetSelectedItem();
if (item && item->IsShowAllItem())
{
// Remove "show all" item and reparent all children to its parent.
GetModel()->Remove(item->GetIndex(), FALSE);
// Show again to automatically resize the dropdown to fit more items
ShowDropdown(TRUE);
// Call OnChange so we update info to the new selected item.
if (!mouse_invoked)
OnChange(GetTreeView(), FALSE);
return true;
}
return false;
}
/************************************************************************************/
OP_STATUS OpAddressDropDown::GetFullAddress(OpString& text)
{
// If the edit field has focus or there is no text use the edit field otherwise
// go for the full adress
if (GetFocused() == edit || !m_address.HasContent() || GetMisMatched())
{
RETURN_IF_ERROR(GetText(text));
return text.Insert(0, m_url_proto_www_prefix);
}
text.Set(m_address.GetFullAddress());
return OpStatus::OK;
}
void OpAddressDropDown::GetQueryField(OpString& text)
{
if (GetMisMatched())
text.Empty();
else
text.Set(m_address.GetQueryField());
}
void OpAddressDropDown::GetProtocolField(OpString& text)
{
if (GetMisMatched())
text.Empty();
else
text.Set(m_address.GetProtocol());
}
void OpAddressDropDown::GetHighlightDomain(OpString& text)
{
if (edit->string.m_highlight_len != -1 && edit->string.m_highlight_ofs != -1)
text.Set(edit->string.Get() + edit->string.m_highlight_ofs, edit->string.m_highlight_len);
else
text.Empty();
}
OP_STATUS OpAddressDropDown::GetText(OpString& text)
{
RETURN_IF_ERROR(OpDropDown::GetText(text));
if (text.Length() > 4096)
text[4096] = 0;
return OpStatus::OK;
}
OP_STATUS OpAddressDropDown::EmulatePaste(OpString& text)
{
if (edit && edit->IsFocused())
{
OpString edit_text;
RETURN_IF_ERROR(edit->GetText(edit_text));
INT32 start, stop;
SELECTION_DIRECTION direction;
edit->GetSelection(start, stop, direction);
INT32 pos = edit->GetCaretOffset();
if (start >= 0 && stop > start)
{
if (pos > start)
pos -= pos > stop ? stop-start : pos-start;
edit_text.Delete(start, stop-start);
}
RETURN_IF_ERROR(edit_text.Insert(pos, text));
RETURN_IF_ERROR(text.Set(edit_text));
}
return OpStatus::OK;
}
bool OpAddressDropDown::IsOnBottom() const
{
OpWidget* parent = GetParent();
if (parent && parent->GetType() == WIDGET_TYPE_TOOLBAR)
{
OpToolbar* toolbar = static_cast<OpToolbar*>(parent);
if (toolbar->GetAlignment() == OpBar::ALIGNMENT_BOTTOM)
{
return true;
}
}
return false;
}
/************************************************************************************/
BOOL OpAddressDropDown::OnBeforeInvokeAction(BOOL invoked_on_user_typed_string)
{
if (ActivateShowAllItem(true))
return FALSE;
return TRUE;
}
/***********************************************************************************
**
** OnInvokeAction - OpTreeViewDropdown Hook
**
***********************************************************************************/
void OpAddressDropDown::OnInvokeAction(BOOL invoked_on_user_typed_string)
{
if (GetSelectedItem() && GetSelectedItem()->IsShowAllItem())
return; // don't save stuff or start intranet testing if show all item is invoked.
OpString text;
GetText(text);
BOOL is_nick = g_hotlist_manager->HasNickname(text, NULL);
if (g_searchEngineManager->IsIntranet(text.CStr()) &&
!is_nick &&
!g_searchEngineManager->IsDetectedIntranetHost(text.CStr()))
{
StartIntranetTest(text.CStr());
}
// If the action is being invoked on the string the user
// typed/pasted then it should be added to typed history
//--------------------
if (!invoked_on_user_typed_string && DropdownIsOpen())
{
HistoryAutocompleteModelItem * item = GetSelectedItem();
if (item && item->GetForceAddHistory())
invoked_on_user_typed_string = TRUE;
}
DirectHistory::ItemType type = DirectHistory::TEXT_TYPE;
if (!invoked_on_user_typed_string)
type = DirectHistory::SELECTED_TYPE;
// Save type to the lower 8 bits and m_in_addressbar to the 9th bit
if (GetAction())
{
OpString full_url;
GetFullAddress(full_url);
GetAction()->SetActionData(((m_in_addressbar ? TRUE:FALSE) << 8) + type);
GetAction()->SetActionDataString(full_url);
//SetTitle
HistoryAutocompleteModelItem* item = GetSelectedItem();
if (item)
{
OpString str;
item->GetTitle(str); //Allow empty string to pass as a parameter
GetAction()->SetActionDataStringParameter(str);
}
}
}
/***********************************************************************************
**
** OnDragStart
**
***********************************************************************************/
void OpAddressDropDown::OnDragStart(OpWidget* widget,
INT32 pos,
INT32 x,
INT32 y)
{
DesktopDragObject* drag_object = GetDragObject(g_application->IsDragCustomizingAllowed() ?
DRAG_TYPE_ADDRESS_DROPDOWN : DRAG_TYPE_LINK, x, y);
if(!drag_object)
return;
if (widget == m_protocol_button)
{
if ( m_tab_cursor->GetWindowCommander() )
{
OpWindowCommander *win_comm = m_tab_cursor->GetWindowCommander();
drag_object->SetURL(win_comm->GetCurrentURL(FALSE));
drag_object->SetTitle(win_comm->GetCurrentTitle());
OpString description;
WindowCommanderProxy::GetDescription(m_tab_cursor->GetWindowCommander(), description);
DragDrop_Data_Utils::SetText(drag_object, description.CStr());
}
}
if (g_application->IsDragCustomizingAllowed())
{
drag_object->SetObject(this);
}
g_drag_manager->StartDrag(drag_object, NULL, FALSE);
}
/***********************************************************************************
** GetTextForSelectedItem
**
**
***********************************************************************************/
OP_STATUS OpAddressDropDown::GetTextForSelectedItem(OpString& item_text)
{
HistoryAutocompleteModelItem* item = GetSelectedItem();
if (!item)
return OpStatus::ERR;
if (m_use_display_url && item->HasDisplayAddress())
{
RETURN_IF_ERROR(item->GetAddress(m_actual_url));
return item->GetDisplayAddress(item_text);
}
else
{
return item->GetAddress(item_text);
}
}
void OpAddressDropDown::OnDesktopWindowClosing(DesktopWindow* desktop_window, BOOL user_initiated)
{
TipsConfigGeneralInfo tip_info;
if (g_tips_manager && g_tips_manager->CanTipBeDisplayed(UNI_L("Addressbar General Search Tip"), tip_info)
|| g_tips_manager->CanTipBeDisplayed(UNI_L("Addressbar Search Tip"), tip_info))
{
OpStatus::Ignore(g_tips_manager->GrabTipsToken(tip_info));
}
if (m_dropdown_button)
m_dropdown_button->OnMouseLeave();
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnTabInfoChanged()
{
UpdateButtons();
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnTabLoading()
{
UpdateButtons();
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnTabChanged()
{
//GetForegroundSkin()->SetWidgetImage(m_tab_cursor->GetWidgetImage());
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
** We are changing tabs, store any user text if there is any in the urlfield,
** clear the ui and find out what we need to show for the new tab.
***********************************************************************************/
void OpAddressDropDown::OnTabWindowChanging(DocumentDesktopWindow* old_target_window,
DocumentDesktopWindow* new_target_window)
{
OpWindowCommander* old_window_commander = old_target_window ? old_target_window->GetWindowCommander() : NULL;
OpWindowCommander* new_window_commander = new_target_window ? new_target_window->GetWindowCommander() : NULL;
OnPageWindowChanging(old_window_commander, new_window_commander);
}
void OpAddressDropDown::OnPageWindowChanging(OpWindowCommander* old_window_commander,
OpWindowCommander* new_window_commander)
{
ForwardWorkspace();
if(!new_window_commander)
{
SetText(NULL);
}
else if (OpStatus::IsError(m_text_content.PopTab(new_window_commander)))
{
OpString url;
OpStatus::Ignore(WindowCommanderProxy::GetMovedToURL(new_window_commander).GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden, url));
SetText(url.CStr());
}
edit->UnsetForegroundColor();
UpdateButtons();
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnTabClosing(DocumentDesktopWindow* desktop_window)
{
OpWindowCommander* window_commander = desktop_window ? desktop_window->GetWindowCommander() : NULL;
OnPageClosing(window_commander);
}
void OpAddressDropDown::OnPageClosing(OpWindowCommander* window_commander)
{
if(!window_commander)
return;
OpString old_text;
OpStatus::Ignore(m_text_content.RemoveContent(window_commander, old_text));
}
/***********************************************************************************
** OpTabCursor::Listener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnTabURLChanged(DocumentDesktopWindow* document_window,
const OpStringC & url)
{
OpWindowCommander* window_commander = document_window ? document_window->GetWindowCommander() : NULL;
OnPageURLChanged(window_commander, url);
}
void OpAddressDropDown::OnPageURLChanged(OpWindowCommander* window_commander, const OpStringC & url)
{
if(!m_tab_cursor->IsTargetWindow(window_commander))
{
OpStatus::Ignore(m_text_content.UpdateContent(window_commander, url));
return;
}
// see SetIgnoreEditFocus() description for more details
if (!edit->IsFocused() || m_ignore_edit_focus)
{
SetText(url.CStr());
edit->UnsetForegroundColor();
// The url in the addressbar is updated to match the page in the window.
// The url might be set to blank temporarily (when going back to speeddial).
// There is then a mismatch between the url displayed and the document loaded
m_url_page_mismatch = url.IsEmpty();
m_ignore_edit_focus = false;
}
else
{
// The url in the addressbar is not updated to match the page in the window.
// The security button must be hidden to avoid confusion about the server name
// and and security level. Bug 226176.
// But we must also keep in mind that this callback might come without the url
// actually changing (for instance on reload). If that is the case, there is
// no mismatch after all. Bug 289608.
OpString text;
this->GetText(text);
if (text.Compare(url))
m_url_page_mismatch = TRUE;
}
UpdateAddressFieldHighlight();
UpdateButtons(TRUE);
}
void OpAddressDropDown::StartSearchSuggest()
{
m_mh->RemoveDelayedMessage(MSG_QUICK_START_SEARCH_SUGGESTIONS, 0, 0);
int n = 2 << m_query_error_counter;
if (n > 25)
n = 25;
m_mh->PostDelayedMessage(MSG_QUICK_START_SEARCH_SUGGESTIONS, 0, 0, 100 * n);
}
void OpAddressDropDown::OnQueryComplete(const OpStringC& search_id, OpVector<SearchSuggestEntry>& entries)
{
OpString filter;
m_search_suggest_in_progress = FALSE;
if(!GetModel())
return;
UINT32 cnt;
// add a maximum of MAX_SUGGESTIONS_ADDRESS_FIELD_SEARCH hits to the drop down
UINT32 max_entries = min(unsigned(MAX_SUGGESTIONS_ADDRESS_FIELD_SEARCH), entries.GetCount());
// reset query error counter, as this attempt has been successful
m_query_error_counter = 0;
GetModel()->RemoveAll();
DeleteItems(m_search_suggestions_items);
for(cnt = 0; cnt < max_entries; cnt++)
{
SearchSuggestEntry *entry = entries.Get(cnt);
if(entry)
{
SearchSuggestionAutocompleteItem* suggest_item = OP_NEW(SearchSuggestionAutocompleteItem, (GetModel()));
if(!suggest_item)
continue;
suggest_item->SetSearchSuggestion(entry->GetData());
suggest_item->SetSearchProvider(search_id.CStr());
suggest_item->SetBadgeWidth(m_protocol_button->GetWidth());
suggest_item->SetHighlightText(m_search_phrase);
if (OpStatus::IsError(m_search_suggestions_items.Add(suggest_item)))
{
OP_DELETE(suggest_item);
}
}
}
PopulateDropdown(false);
}
void OpAddressDropDown::PrefChanged(OpPrefsCollection::Collections id, int pref,int newvalue)
{
if (OpPrefsCollection::UI == id)
{
if (pref == PrefsCollectionUI::HideURLParameter || pref == PrefsCollectionUI::ShowFullURL)
{
// Update the url if it wasn't edited
if (GetFocused() != edit && !m_url_page_mismatch)
{
OpString str;
str.Set(m_address.GetFullAddress()); // we're updating this object so save the text first
SetText(str);
}
if (pref == PrefsCollectionUI::ShowFullURL)
{
bool vis = newvalue == 0 && GetFocused() != edit;
m_protocol_button->SetTextVisibility(vis);
}
}
if(pref == PrefsCollectionUI::ShowDropdownButtonInAddressfield)
{
m_dropdown_button->SetVisibility(g_pcui->GetIntegerPref(PrefsCollectionUI::ShowDropdownButtonInAddressfield));
}
}
}
OP_STATUS OpAddressDropDown::GetFormattedSuggestedSearch(SearchSuggestionAutocompleteItem* suggest_item, OpString& formated_string)
{
SearchTemplate *search_template = g_searchEngineManager->GetByUniqueGUID(suggest_item->GetSearchProvider());
if(search_template)
{
OpString guid;
RETURN_IF_ERROR(search_template->GetUniqueGUID(guid));
// construct a search string suitable for history
return formated_string.AppendFormat(UNI_L("%s %s"), search_template->GetKey().CStr(), suggest_item->GetSearchSuggestion());
}
return OpStatus::OK;
}
void OpAddressDropDown::UpdateAddressFieldHighlight(BOOL leave, BOOL no_delay)
{
OpString text;
GetText(text);
BOOL highlighted = edit->string.GetHighlightType() != OpWidgetString::None;
BOOL should_highlight = m_address.GetHighlight()
&& !m_url_page_mismatch // don't when url doesn't match the page
&& GetFocused() != edit // don't when edit is focused
#ifdef REMOVE_HIGHLIGHT_ONHOVER
&& (g_widget_globals->hover_widget != edit || leave) // don't when hovered
// in OnMouseLeave the edit may still be the hover_widget, but will soon not
#endif
;
// Highlighting happens immediately if needed, removing the highlight
// when hovering is delayed for a short while to prevent url flashing when
// the user is just moving mouse over the address bar, not actually hovering.
if (!should_highlight && highlighted && !no_delay)
{
m_highlight_delayed_trigger.InvokeTrigger(OpDelayedTrigger::INVOKE_DELAY);
}
else
{
// Update the range to highlight
edit->string.SetHighlightType(should_highlight ? OpWidgetString::RootDomain : OpWidgetString::None);
edit->string.NeedUpdate();
edit->InvalidateAll();
}
}
void OpAddressDropDown::RestoreOriginalAddress()
{
if (m_address.HasContent())
{
// The edit get focused, show the full address(including protocol)
OpTreeViewDropdown::SetText(m_address.GetFullAddress());
}
}
OP_STATUS OpAddressDropDown::SetText(const uni_char* text)
{
m_url_proto_www_prefix.Empty();
m_address.Clear();
// Return if URL is maskable from display
if (MaskUrlFromDisplay(text))
return OpStatus::OK;
const uni_char* current_loading_url = GetWindowCommander() ? GetWindowCommander()->GetLoadingURL(FALSE) : NULL;
// Text changes, update m_url_page_mismatch
if (current_loading_url && !ShallMaskUrlFromDisplay(current_loading_url))
m_address.SetAddress(current_loading_url);
m_url_page_mismatch = !m_address.Compare(text);
m_actual_url.Empty();
// We need to know the status of the button to determine whether show the protocol or not
UpdateProtocolStatus();
if (GetFocused() == edit)
{
m_protocol_button->SetTextVisibility(FALSE);
}
if (!text)
OpTreeViewDropdown::SetText(NULL);
else if (!m_in_addressbar || GetFocused() == edit || m_url_page_mismatch) // Don't hide protocol when not needed
OpTreeViewDropdown::SetText(text);
else
{
OpString show_address;
// If there is a page and the badge is Empty then probably the page is
// an loading failed page, in this case we don't want the Web badge
// or hide protocol
if (m_protocol_button->HideProtocol())
m_address.GetShowAddress(show_address);
else
show_address.Set(m_address.GetFullAddress());
OpTreeViewDropdown::SetText(show_address);
edit->SetCaretOffset(0); // Compensate for the behavior in OpTreeViewDropdown::SetText
}
UpdateAddressFieldHighlight(FALSE, TRUE);
#if defined(_X11_SELECTION_POLICY_)
m_caret_offset = -1;
#endif
return OpStatus::OK;
}
UINT OpAddressDropDown::GetProtocolWidth()
{
OpString text, tmp;
INT text_len, text_with_protocol_len;
GetText(text);
// Width without protocol
OpString show_address;
m_address.GetShowAddress(show_address);
tmp.Set(show_address);
edit->string.Set(tmp, edit);
text_len = edit->GetStringWidth();
// Width with protocol
tmp.Insert(0, m_address.GetProtocol());
edit->string.Set(tmp, edit);
text_with_protocol_len = edit->GetStringWidth();
edit->string.Set(text, edit);
return text_with_protocol_len - text_len;
}
void OpAddressDropDown::EnableFavoritesButton(bool show_fav_btn)
{
m_show_favorites_button = show_fav_btn;
if (m_show_favorites_button && !m_url_fav_menu)
OpStatus::Ignore(InitializeBookmarkMenu());
}
OP_STATUS OpAddressDropDown::ListPopupWindowWidgets(OpVector<OpWidget> &widgets)
{
#ifdef SUPPORT_START_BAR
if (!m_popup_window)
return OpStatus::ERR;
OpWidget* widget = m_popup_window->GetWidgetContainer()->GetRoot();
if (!widget)
{
return OpStatus::ERR;
}
OpWidget* child = widget->GetFirstChild();
if (!child)
return OpStatus::ERR;
do {
widgets.Add(child);
ListWidgets(child, widgets);
} while (child = child->GetNextSibling());
return OpStatus::OK;
}
OP_STATUS OpAddressDropDown::ListWidgets(OpWidget* widget, OpVector<OpWidget> &widgets)
{
if (!widget)
return OpStatus::ERR;
OpWidget* child = widget->GetFirstChild();
if (!child)
return OpStatus::ERR;
do {
widgets.Add(child);
ListWidgets(child, widgets);
} while (child = child->GetNextSibling());
#endif // SUPPORT_START_BAR
return OpStatus::OK;
}
OP_STATUS OpAddressDropDown::GetTypedText(OpString& typed_text)
{
if (m_is_quick_completed)
{
RETURN_IF_ERROR(typed_text.Set(m_text_before_quick_completion));
}
else
{
RETURN_IF_ERROR(GetText(typed_text));
}
return OpStatus::OK;
}
void OpAddressDropDown::UpdateProtocolStatus()
{
OpWindowCommander* win_comm = m_tab_cursor->GetWindowCommander();
BOOL hide_protocol = m_protocol_button->HideProtocol();
m_protocol_button->UpdateStatus(win_comm, m_url_page_mismatch);
if (win_comm)
{
// When loading failed the badge switches from a normal size Web to minimal size Empty,
// the protocol is hidden in this case so we want to show it again
if (hide_protocol != m_protocol_button->HideProtocol())
{
// Update url, add or remove protocol
if (!GetMisMatched() && GetFocused() != edit)
{
/* The family of WindowCommander's GetFooURL() methods use the
same buffer for strings they return meaning that they will
overwrite the string that was obtained in the previous call,
fooling comparisons that are done throughout this code. We
need to copy the string. */
OpString current_url;
if (OpStatus::IsSuccess(current_url.Set(win_comm->GetCurrentURL(FALSE))))
SetText(current_url.CStr());
}
}
}
}
void OpAddressDropDown::UpdateFavoritesFG(bool reflow)
{
if (!m_url_fav_menu)
return;
bool is_item_bookmarked = false;
is_item_bookmarked = IsAddressInBookmarkList();
if (!is_item_bookmarked)
is_item_bookmarked = IsAddressInSpeedDialList();
const char *updated_img;
if (g_desktop_op_system_info->SupportsContentSharing())
updated_img = "SharePage";
else
updated_img = is_item_bookmarked ? "Bookmarked URL" : "NonBookmarked URL";
OpStringC8 img(m_url_fav_menu->GetForegroundSkin()->GetImage());
if (img.CompareI(updated_img, strlen(updated_img)))
{
// Update button image
m_url_fav_menu->GetForegroundSkin()->SetImage(updated_img);
if (reflow)
Relayout();
}
}
void OpAddressDropDown::CloseOverlayDialog()
{
if (m_addressbar_overlay_ctl)
{
m_addressbar_overlay_ctl->CancelDialog();
}
}
void OpAddressDropDown::DisplayOverlayDialog(const OpVector<OpPermissionListener::ConsentInformation>& info)
{
DocumentDesktopWindow* window = g_application->GetActiveDocumentDesktopWindow();
if (window && !window->PermissionControllerDisplayed() && m_protocol_button && !m_addressbar_overlay_ctl)
{
OpWidget* root = GetWidgetContainer()->GetRoot();
m_addressbar_overlay_ctl = OP_NEW(AddressbarOverlayController, (*this, *root, GetWindowCommander(), info));
if (!m_addressbar_overlay_ctl)
{
return;
}
m_addressbar_overlay_ctl->SetListener(this);
if (OpStatus::IsError(ShowDialog(m_addressbar_overlay_ctl, g_global_ui_context, GetParentDesktopWindow())))
{
return;
}
m_addressbar_overlay_ctl->SetFocus(FOCUS_REASON_MOUSE);
if (IsOnBottom())
{
m_addressbar_overlay_ctl->SetIsOnBottom();
}
}
}
void OpAddressDropDown::OnShowFavoritesDialog()
{
m_protocol_button->HideText();
RestoreOriginalAddress();
}
void OpAddressDropDown::OnCloseFavoritesDialog()
{
if (GetFocused() == edit)
return;
m_protocol_button->ShowText();
/* When url's fav menu loses focus the short-address will be displayed only
if current displayed address wasn't edited */
OpString text;
RETURN_VOID_IF_ERROR(GetText(text));
if (GetWindowCommander())
{
const uni_char* current_url = GetWindowCommander()->GetCurrentURL(FALSE);
if (text.Compare(current_url) == 0)
{
/* The family of WindowCommander's GetFooURL() methods use the same
buffer for strings they return meaning that they will overwrite
the string that was obtained in the previous call, fooling
comparisons that are done throughout this code. We need to copy
the string. */
OpString url;
if (OpStatus::IsSuccess(url.Set(current_url)))
SetText(url.CStr());
}
}
// Set focus to document
g_input_manager->InvokeAction(OpInputAction::ACTION_FOCUS_PAGE);
}
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// AddressHighlight
//////////////////////////////////////////////////////////////////////////////////////////
void AddressHighlight::Clear()
{
m_protocol.Empty();
m_short_address.Empty();
m_original_address.Empty();
}
void AddressHighlight::SetAddress(OpStringC url)
{
Clear();
m_original_address.Set(url);
m_short_address.Set(url);
m_highlight = TRUE;
UINT protocol_len = 0;
BOOL remove_parameter = FALSE;
if (m_short_address.CompareI(UNI_L("http://"), 7) == 0)
{
protocol_len = 7;
remove_parameter = TRUE;
}
else if (m_short_address.CompareI(UNI_L("https://"), 8) == 0)
{
protocol_len = 8;
remove_parameter = TRUE;
}
else if (m_short_address.CompareI(UNI_L("ftp://"), 6) == 0)
{
protocol_len = 6;
}
else if (m_short_address.CompareI(UNI_L("opera:"), 6) == 0
&& m_short_address.CompareI(UNI_L("opera:blank")) != 0) // we show Empty badge for this
{
protocol_len = 6;
m_highlight = FALSE;
}
else if (m_short_address.CompareI(UNI_L("file://"), 7) == 0)
{
protocol_len = 7;
m_highlight = FALSE;
}
else if (m_short_address.CompareI(UNI_L("attachment:"), 11) == 0)
{
protocol_len = 11;
m_highlight = FALSE;
}
else if (m_short_address.CompareI(UNI_L("widget://"), 9) == 0)
{
protocol_len = 0;
m_highlight = FALSE;
SetAddressForExtensions();
}
// Remove the parameters for http and https
if (remove_parameter && g_pcui->GetIntegerPref(PrefsCollectionUI::HideURLParameter))
{
int parameter_start = m_short_address.Find(UNI_L("?"));
if (parameter_start != -1)
{
m_query_field.Set(m_short_address.CStr() + parameter_start);
m_short_address.Delete(parameter_start);
}
}
// Remove the protocol. http://opera.com/ -> opera.com/
m_protocol.Set(m_short_address, protocol_len);
m_short_address.Delete(0, protocol_len);
// Remove the ending '/'. i.e. opera.com/ -> opera.com
if (m_short_address.Length() && m_short_address.Find("/") == m_short_address.Length() - 1)
m_short_address.CStr()[m_short_address.Length() - 1] = 0;
}
/***********************************************************************************
** DesktopHistoryModelListener callback function
**
**
***********************************************************************************/
void OpAddressDropDown::OnDesktopHistoryModelItemDeleted(HistoryModelItem* item)
{
HistoryAutocompleteModelItem *simple_item = item->GetHistoryAutocompleteModelItem();
if (simple_item)
{
HistoryAutocompleteModel *model = GetModel();
if (model)
{
INT32 remove_pos;
remove_pos = model->GetIndexByItem(simple_item);
if (remove_pos >= 0)
model->Remove(remove_pos);
}
}
}
void AddressHighlight::GetShowAddress(OpString& address)
{
BOOL show_full_url = g_pcui->GetIntegerPref(PrefsCollectionUI::ShowFullURL);
if (show_full_url)
address.Set(m_original_address);
else
address.Set(m_short_address);
}
BOOL AddressHighlight::Compare(OpStringC url)
{
if (m_original_address.CompareI(url) == 0)
return TRUE;
if (m_short_address.CompareI(url) == 0)
return TRUE;
return FALSE;
}
uni_char* OpAddressDropDown::DeduceProtocolOrSubdomain(const OpString& current_text, uni_char* address)
{
// Strip away parts that shouldn't matter. This gives the user hits on modified urls too,
// since modifying a incorrectly typed url also has the http://www. part (but the user usually doesn't type it).
const uni_char* http = UNI_L("http://");
const uni_char* https = UNI_L("https://");
const uni_char* www = UNI_L("www.");
if (uni_strncmp(current_text.CStr(), http, MIN(current_text.Length(), 7)) != 0 &&
uni_strncmp(address, http, 7) == 0)
{
m_url_proto_www_prefix.Set(http);
address += 7;
}
else if (uni_strncmp(current_text.CStr(), https, MIN(current_text.Length(), 8)) != 0 &&
uni_strncmp(address, https, 8) == 0)
{
m_url_proto_www_prefix.Set(https);
address += 8;
}
if (uni_strncmp(current_text.CStr(), www, MIN(current_text.Length(), 4)) != 0 &&
uni_strncmp(address, www, 4) == 0)
{
m_url_proto_www_prefix.Append(www);
address += 4;
}
return address;
}
void AddressHighlight::SetAddressForExtensions()
{
int wuid_end = m_short_address.Find(UNI_L("/"), 9);
if (wuid_end != KNotFound)
{
OpGadget * dst = g_gadget_manager->FindGadget(GADGET_FIND_BY_ID, m_short_address.SubString(9, wuid_end - 9).CStr(), FALSE);
OpString url;
url.Append(m_short_address.SubString(wuid_end+1).CStr());
m_short_address.Empty();
if (dst)
{
OpString format;
if (url.Compare(UNI_L("options.html")) == 0)
g_languageManager->GetString(Str::S_ADDRESS_BUTTON_ADDON_OPTIONS, format);
else
g_languageManager->GetString(Str::S_ADDRESS_BUTTON_ADDON_UNKNOWN, format);
const uni_char* text = dst->GetAttribute(WIDGET_NAME_SHORT);
if (!text || !*text) text = dst->GetAttribute(WIDGET_NAME_TEXT);
if (text && *text)
{
m_short_address.AppendFormat(format.CStr(), text, url.CStr());
}
else
{
OpString path;
dst->GetGadgetPath(path);
int leaf = path.FindLastOf(PATHSEPCHAR);
if (leaf == -1)
leaf = path.FindLastOf(UNI_L('/'));
m_short_address.AppendFormat(format.CStr(), path.SubString(leaf + 1).CStr(), url.CStr()); //will take whole path, if there are no separators...
}
}
else
m_short_address.Append(url);
m_original_address.Empty();
}
}
void OpAddressDropDown::OnDialogClosing(DialogContext* context)
{
if (context == m_addressbar_overlay_ctl)
{
m_addressbar_overlay_ctl = NULL;
}
else if (context == m_favorites_overlay_ctl)
{
OnCloseFavoritesDialog();
m_favorites_overlay_ctl = NULL;
m_url_fav_menu->SetDialogContext(NULL);
}
}
bool OpAddressDropDown::IsAddressInBookmarkList()
{
OpString doc_url;
GetFullAddress(doc_url);
if (doc_url.IsEmpty())
return false;
return g_hotlist_manager->GetBookmarksModel()->GetByURL(doc_url, false, true) != NULL;
}
bool OpAddressDropDown::IsAddressInSpeedDialList()
{
OpString doc_url;
GetFullAddress(doc_url);
if (doc_url.IsEmpty())
return false;
return g_speeddial_manager->FindSpeedDialByUrl(doc_url, true) != -1;
}
OpAddressDropDown::InitInfo::InitInfo()
: m_max_lines(1)
, m_show_dropdown_on_activation(false)
, m_invoke_action_on_click(false)
, m_open_page_in_tab(false)
, m_tab_mode(false)
, m_shall_show_addr_bar_badge(false)
, m_use_display_url(true)
, m_show_search_suggestions(false)
, m_show_speed_dial_pages(false)
{
}
void OpAddressDropDown::InitAddressDropDown(OpAddressDropDown::InitInfo &info)
{
SetMaxLines(info.m_max_lines);
SetShowDropdownOnActivation(info.m_show_dropdown_on_activation);
SetInvokeActionOnClick(info.m_invoke_action_on_click);
SetOpenInTab(info.m_open_page_in_tab);
SetTabMode(info.m_tab_mode);
EnableAddressBarBadge(info.m_shall_show_addr_bar_badge);
SetUseDisplayUrl(info.m_use_display_url);
m_show_search_suggestions = info.m_show_search_suggestions;
m_show_speed_dial_pages = info.m_show_speed_dial_pages;
// Get current page URL
if (info.m_url_string.HasContent())
OpStatus::Ignore(SetText(info.m_url_string));
/*
The styling of the edit field should be the same as for the title edit
field. It seems that using the same skin for op_drop_down as for
title_edit makes this work without breaking anything. Changing the skin
of op_drop_down->edit has no effect. See DSK-330160.
If this does break something, we should probably make a new skin for the
"speed dial config addressfield dropdown", which copies the necessary
data from "Edit Skin", "Addressfield Dropdown Skin" and "Dropdown Skin".
*/
GetBorderSkin()->SetImage("Edit Skin");
}
void OpAddressDropDown::BlockFocus()
{
if (m_block_focus_timer == NULL)
m_block_focus_timer = OP_NEW(OpTimer, ());
if (m_block_focus_timer && !m_block_focus_timer->IsStarted())
{
m_block_focus_timer->SetTimerListener(this);
m_block_focus_timer->Start(400);
if(edit)
edit->SetDead(TRUE);
}
}
void OpAddressDropDown::OnTimeOut(OpTimer* timer)
{
if(m_block_focus_timer == timer)
{
OP_DELETE(m_block_focus_timer);
m_block_focus_timer = NULL;
if(edit)
edit->SetDead(FALSE);
}
else if (m_notification_timer == timer)
{
AnimateBookmarkNotification(false, false);
}
else
OpTreeViewDropdown::OnTimeOut(timer);
}
void OpAddressDropDown::AnimateBookmarkNotification(bool show, bool added)
{
// ignore text when hiding
if (show)
{
OpString text_to_show;
g_languageManager->GetString(added ? Str::S_URL_ADDED_NOTIFICATION : Str::S_URL_REMOVED_NOTIFICATION,
text_to_show);
m_bookmark_status_label->SetText(text_to_show);
}
QuickAnimationWidget* animation = m_bookmark_status_label->GetAnimation();
if (animation && animation->IsAnimating())
g_animation_manager->abortAnimation(animation);
m_bookmark_status_label->SetVisibility(show);
m_bookmark_status_label->SetVisibility(TRUE);
animation = OP_NEW(QuickAnimationWidget,
(m_bookmark_status_label,
show ? ANIM_MOVE_NONE : ANIM_MOVE_SHRINK,
true,
show ? ANIM_FADE_IN : ANIM_FADE_OUT));
if (animation)
{
// we might consider depending animation time and timeout on text length
// but this would require some studies about how fast ppl read
// text basing on text length and complexity
g_animation_manager->startAnimation(animation, ANIM_CURVE_LINEAR, 300);
// if another show/hide notification would occur when current animation
// is in progress, then we can easly stop current timer, since new timer
// will be more important then previous one
m_notification_timer->Stop();
if (show)
{
m_notification_timer->SetTimerListener(this);
m_notification_timer->Start(900);
}
}
}
bool OpAddressDropDown::MaskUrlFromDisplay(const uni_char* url)
{
if (!ShallMaskUrlFromDisplay(url))
return false;
OpTreeViewDropdown::SetText(NULL);
return true;
}
bool OpAddressDropDown::ShallMaskUrlFromDisplay(const uni_char* url)
{
if (url && *url)
return !DocumentView::IsUrlRestrictedForViewFlag(url, DocumentView::ALLOW_SHOW_URL);
return false;
}
|
// ----------------
// PngViewerDlg.cpp
// ----------------
/**
* @file
* @brief Re: CAboutDlg, CPngViewerDlg
* @author Achim Klein
* @version 0.6
*/
// --------
// Includes
// --------
#include "stdafx.h"
#include "PngViewer.h"
#include "PngViewerDlg.h"
#include "PngImage.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ---------------------------------
// Definition of the CAboutDlg class
// ---------------------------------
/**
*
*/
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX);
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
// ---------
// CAboutDlg
// ---------
/**
*
*/
CAboutDlg::CAboutDlg()
: CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
// --------------
// DoDataExchange
// --------------
/**
*
*/
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
// -----------------
// BEGIN_MESSAGE_MAP
// -----------------
/**
*
*/
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// -------------
// CPngViewerDlg
// -------------
/**
* The standard-constructor.
*/
CPngViewerDlg::CPngViewerDlg(CWnd* pParent)
: CDialog(CPngViewerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CPngViewerDlg)
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_bitmap = 0;
m_visible = 0;
}
// --------------
// ~CPngViewerDlg
// --------------
/**
* The destructor frees the allocated memory.
*/
CPngViewerDlg::~CPngViewerDlg()
{
if (m_bitmap) delete m_bitmap;
if (m_visible) delete m_visible;
}
// --------------
// DoDataExchange
// --------------
/**
*
*/
void CPngViewerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPngViewerDlg)
//}}AFX_DATA_MAP
}
// -----------------
// BEGIN_MESSAGE_MAP
// -----------------
/**
*
*/
BEGIN_MESSAGE_MAP(CPngViewerDlg, CDialog)
//{{AFX_MSG_MAP(CPngViewerDlg)
ON_WM_SYSCOMMAND()
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
ON_COMMAND(ID_FILE_EXIT, OnFileExit)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// ------------
// OnInitDialog
// ------------
/**
*
*/
BOOL CPngViewerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
return TRUE;
}
// ------------
// OnSysCommand
// ------------
/**
*
*/
void CPngViewerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// -------
// OnPaint
// -------
/**
*
*/
void CPngViewerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this);
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
// check pointer
if (m_visible)
{
doDrawBitmap(m_visible, this);
}
}
}
// ------
// OnSize
// ------
/**
*
*/
void CPngViewerDlg::OnSize(UINT nType, int cx, int cy)
{
// check pointer
if (m_bitmap && m_visible)
{
// check size
if (doCheckZoom(m_visible, this))
{
doInvalidateBackground(m_visible, this);
delete m_visible;
m_visible = doZoomBitmap(m_bitmap, this);
}
}
}
// ---------------
// OnQueryDragIcon
// ---------------
/**
*
*/
HCURSOR CPngViewerDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
// ----
// OnOK
// ----
/**
* Called when ENTER is pressed.
*/
void CPngViewerDlg::OnOK()
{
// nothing
}
// --------
// OnCancel
// --------
/**
* Called when ESC is pressed.
*/
void CPngViewerDlg::OnCancel()
{
// redirect
OnFileExit();
}
// ----------
// OnFileOpen
// ----------
/**
*
*/
void CPngViewerDlg::OnFileOpen()
{
CFileDialog dlg(TRUE, "png", 0, OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, "Portable Network Graphics (.png)|*.png||");
if (dlg.DoModal() == IDCANCEL) return;
PngImage png;
if ( png.load(dlg.GetPathName()) )
{
// get size
int width = png.getWidth();
int height = png.getHeight();
// get blue, green, red and alpha
unsigned char* data = png.getBGRA();
// free memory first
if (m_bitmap) delete m_bitmap;
if (m_visible) delete m_visible;
// create a CBitmap to display
m_bitmap = doCreateCompatibleBitmap(width, height, data, this);
// used to speed up OnPaint()
m_visible = doZoomBitmap(m_bitmap, this);
// request graphical update
Invalidate();
UpdateWindow();
}
}
// ----------
// OnFileExit
// ----------
/**
*
*/
void CPngViewerDlg::OnFileExit()
{
CDialog::OnCancel();
}
// ------------------------
// doCreateCompatibleBitmap
// ------------------------
/**
* Creates a new bitmap.
*/
CBitmap* CPngViewerDlg::doCreateCompatibleBitmap(int Width, int Height, unsigned char* BGRA, CWnd* pCompatibleWindow) const
{
// RGB + Alpha
int size = Width * Height * 4;
// create bitmap
CBitmap* bmp = new CBitmap;
// get device context
CDC* pDC = pCompatibleWindow->GetDC();
// initialize
bmp->CreateCompatibleBitmap(pDC, Width, Height);
// set pixels
bmp->SetBitmapBits(size, BGRA);
// release device context
pCompatibleWindow->ReleaseDC(pDC);
// return object
return bmp;
}
// ------------
// doDrawBitmap
// ------------
/**
* Draws the passed bitmap into the specified window.
*/
void CPngViewerDlg::doDrawBitmap(CBitmap* pBitmap, CWnd* pWindow, CPoint Offset) const
{
// get bitmap information
BITMAP bmpInfo;
pBitmap->GetObject(sizeof(bmpInfo), &bmpInfo);
// get size
CSize size;
size.cx = bmpInfo.bmWidth;
size.cy = bmpInfo.bmHeight;
// get window's client device context
CClientDC* pDC = new CClientDC(pWindow);
// create memory device context
CDC* memDC = new CDC; memDC->CreateCompatibleDC(pDC);
// buffer bitmap
CBitmap* old = memDC->SelectObject(pBitmap);
// copy bitmap bits
pDC->BitBlt
(
Offset.x, // specifies the x-coordinate (in logical units) of the upper-left corner of the destination rectangle
Offset.y, // specifies the y-coordinate (in logical units) of the upper-left corner of the destination rectangle
size.cx, // specifies the width (in logical units) of the destination rectangle
size.cy, // specifies the height (in logical units) of the destination rectangle
memDC, // specifies the source device context
0, // specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle
0, // specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle
SRCCOPY // specifies the raster operation to be performed
);
// reselect first bitmap
memDC->SelectObject(old);
// delete device context and reset pointer
delete memDC; memDC = 0;
// delete device context and reset pointer
delete pDC; pDC = 0;
}
// -----------
// doCheckZoom
// -----------
/**
* Returns TRUE if the bitmap fits into the window's client rect or into the MaxSize rect.
*/
BOOL CPngViewerDlg::doCheckZoom(CBitmap* pBitmap, CWnd* pWindow, CSize MaxSize) const
{
// get bitmap information
BITMAP bmpInfo;
pBitmap->GetObject(sizeof(bmpInfo), &bmpInfo);
// get bitmap size
CSize bmpSize;
bmpSize.cx = bmpInfo.bmWidth;
bmpSize.cy = bmpInfo.bmHeight;
// get client rect
CRect clientRect;
pWindow->GetClientRect(&clientRect);
// check max size
if (MaxSize == CSize(0, 0))
{
// use client area
MaxSize.cx = clientRect.Width();
MaxSize.cy = clientRect.Height();
}
else
{
// use client area
if (MaxSize.cx > clientRect.Width()) MaxSize.cx = clientRect.Width();
if (MaxSize.cy > clientRect.Height()) MaxSize.cy = clientRect.Height();
}
// too narrow
if (MaxSize.cx < bmpSize.cx) return TRUE;
// too low
if (MaxSize.cy < bmpSize.cy) return TRUE;
// scale up bitmap
if ((MaxSize.cx > bmpSize.cx) && (MaxSize.cy > bmpSize.cy)) return TRUE;
// it fits
return FALSE;
}
// ------------
// doZoomBitmap
// ------------
/**
* Returns a new bitmap that fits proportionally into the client rect of the passed window or into the MaxSize rect.
*/
CBitmap* CPngViewerDlg::doZoomBitmap(CBitmap* pBitmap, CWnd* pCompatibleWindow, CSize MaxSize) const
{
// get bitmap information
BITMAP bmpInfo;
pBitmap->GetObject(sizeof(bmpInfo), &bmpInfo);
// get source size
CSize srcSize;
srcSize.cx = bmpInfo.bmWidth;
srcSize.cy = bmpInfo.bmHeight;
// get client rect
CRect clientRect;
pCompatibleWindow->GetClientRect(&clientRect);
// check max size
if (MaxSize == CSize(0, 0))
{
// use client area
MaxSize.cx = clientRect.Width();
MaxSize.cy = clientRect.Height();
}
else
{
// use client area
if (MaxSize.cx > clientRect.Width()) MaxSize.cx = clientRect.Width();
if (MaxSize.cy > clientRect.Height()) MaxSize.cy = clientRect.Height();
}
// calculate zoom factors
double xfac = MaxSize.cx / static_cast<double>(srcSize.cx);
double yfac = MaxSize.cy / static_cast<double>(srcSize.cy);
// use smaller factor
double zfac = (xfac < yfac) ? (xfac) : (yfac);
// get destination size
CSize dstSize;
dstSize.cx = static_cast<int>(zfac * srcSize.cx + 0.5); // round = add 0.5 first and cut off
dstSize.cy = static_cast<int>(zfac * srcSize.cy + 0.5); // round = add 0.5 first and cut off
CDC* pDC = pCompatibleWindow->GetDC();
// create memory device contexts
CDC* memDC1 = new CDC; memDC1->CreateCompatibleDC(pDC);
CDC* memDC2 = new CDC; memDC2->CreateCompatibleDC(pDC);
// create zoomed bitmap
CBitmap* zoomed = new CBitmap; zoomed->CreateCompatibleBitmap(pDC, dstSize.cx, dstSize.cy);
// not needed anymore
pCompatibleWindow->ReleaseDC(pDC);
// select bitmaps
CBitmap* old1 = memDC1->SelectObject(pBitmap);
CBitmap* old2 = memDC2->SelectObject(zoomed);
// stretch bitmap
memDC2->SetStretchBltMode(HALFTONE);
memDC2->StretchBlt
(
0, // specifies the x-coordinate (in logical units) of the upper-left corner of the destination rectangle
0, // specifies the y-coordinate (in logical units) of the upper-left corner of the destination rectangle
dstSize.cx, // specifies the width (in logical units) of the destination rectangle
dstSize.cy, // specifies the height (in logical units) of the destination rectangle
memDC1, // specifies the source device context
0, // specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle
0, // specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle
srcSize.cx, // specifies the width (in logical units) of the source rectangle
srcSize.cy, // specifies the height (in logical units) of the source rectangle
SRCCOPY // specifies the raster operation to be performed
);
// reselect old bitmaps
memDC2->SelectObject(old2);
memDC1->SelectObject(old1);
// delete temporary device contexts
delete memDC2;
delete memDC1;
// the zoomed bitmap
return zoomed;
}
// ----------------------
// doInvalidateBackground
// ----------------------
/**
* Invalidates the area that is not covered by the bitmap.
*/
void CPngViewerDlg::doInvalidateBackground(CBitmap* pBitmap, CWnd* pWindow) const
{
// get bitmap information
BITMAP bmpInfo;
pBitmap->GetObject(sizeof(bmpInfo), &bmpInfo);
// get bitmap size
CSize bmpSize;
bmpSize.cx = bmpInfo.bmWidth;
bmpSize.cy = bmpInfo.bmHeight;
// get client rect
CRect clientRect;
pWindow->GetClientRect(&clientRect);
// when the window was maximized and gets restored
if ((bmpSize.cx > clientRect.Width()) && (bmpSize.cy > clientRect.Height()))
{
pWindow->InvalidateRect( clientRect );
}
else
{
// check right
if (bmpSize.cx < clientRect.Width())
{
CRect update;
update.top = 0;
update.left = bmpSize.cx;
update.right = clientRect.right;
update.bottom = (bmpSize.cy > clientRect.bottom) ? bmpSize.cy : clientRect.bottom;
pWindow->InvalidateRect(update);
}
// check bottom
if (bmpSize.cy < clientRect.Height())
{
CRect update;
update.top = bmpSize.cy;
update.left = 0;
update.right = (bmpSize.cx > clientRect.right) ? bmpSize.cx : clientRect.right;
update.bottom = clientRect.bottom;
pWindow->InvalidateRect(update);
}
}
}
|
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxLengthOfN = 1300, maxNode = 1600;
const int Mod = int(1e9) + 7;
int m, len, cntNode = 0, que[maxNode * 10], ac[maxNode], fail[maxNode], trans[maxNode][10], dp[2][maxLengthOfN][maxNode];
char strN[maxLengthOfN], s[maxNode];
int Trans(int x, int j) {
int y = x;
while (x && ! trans[x][j]) x = fail[x];
while (y && ! trans[y][j]) trans[y][j] = trans[x][j], y = fail[y];
return trans[x][j];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("count.in", "r", stdin);
#endif
scanf("%s", strN); len = strlen(strN);
scanf("%d", &m);
memset(trans, 0, sizeof(trans));
for (int j = 0; j < m; ++ j) {
int p = 0;
scanf("%s", s);
for (int i = 0; s[i]; ++ i) {
int x = s[i] - '0';
if (! trans[p][x]) trans[p][x] = ++ cntNode;
p = trans[p][x];
}
ac[p] = 1; // accepted status
}
int l = 0, r = 1;
for (que[0] = 0; l < r; ++ l) {
int now = que[l];
for (int j = 0; j < 10; ++ j)
if (trans[now][j]) {
int next = fail[now];
while (next && ! trans[next][j]) next = fail[next];
fail[trans[now][j]] = now ? trans[next][j] : 0;
que[r ++] = trans[now][j];
}
}
for (int i = 1; i < strN[0] - '0'; ++ i)
if (! ac[trans[0][i]]) ++ dp[0][0][trans[0][i]]; // strictly smaller
int past;
if (! ac[past = trans[0][strN[0] - '0']]) ++ dp[1][0][past]; // equal
for (int i = 1; i < len; ++ i) {
int nowDigit = strN[i] - '0';
for (int j = 0; j < 10; ++ j) {
if (j && ! ac[trans[0][j]]) ++ dp[0][i][trans[0][j]];
for (int k = 0; k <= cntNode; ++ k) if (! ac[k]) {
int next = Trans(k, j);
if (! ac[next]) {
dp[0][i][next] = (dp[0][i][next] + dp[0][i - 1][k]) % Mod;
if (j < nowDigit) dp[0][i][next] = (dp[0][i][next] + dp[1][i - 1][k]) % Mod;
}
}
}
//printf("%d %d %d\n", i, dp[0][i][0], dp[0][i][1]);
int next = Trans(past, nowDigit);
if (! ac[past] && ! ac[next])
dp[1][i][next] = (dp[1][i][next] + dp[1][i - 1][past]) % Mod;
past = next;
}
int ans = 0;
for (int i = 0; i <= cntNode; ++ i)
if (! ac[i]) {
ans = (ans + dp[0][len - 1][i]) % Mod;
ans = (ans + dp[1][len - 1][i]) % Mod;
}
printf("%d\n", ans);
}
|
#pragma once
#include "Error.h"
namespace Log
{
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
int helper(int begin, int end, int val){
if(begin > end)
return end;
int mid = (begin + end)/2;
if(val / mid < mid)
return helper(begin,mid-1,val);
if(val / mid > mid)
return helper(mid+1,end,val);
if(val / mid == mid)
return mid;
}
int sqrt(int x){
if (x == 0 || x == 1) return x;
return helper(0,x/2+1,x);
}
int sqrt2(int x){
if(x == 0) return 0;
double
}
int main(){
int i;
cin >> i;
cout<<sqrt(i) <<endl;
}
|
//
// CircularConv.cpp
// fast_convolution
//
// Created by Ying Zhan on 1/22/16.
// Copyright (c) 2016 Ying Zhan. All rights reserved.
//
#include "CircularConv.h"
CircularConvolution::CircularConvolution(int buffer_size): buffer_size(buffer_size),FFT(buffer_size, false), iFFT(buffer_size, true) {
block_size = buffer_size / 2;
dot_product = new std::vector<std::complex<float>> (buffer_size);
cconv_result = new std::vector<std::complex<float>> (buffer_size);
real_conv = new float (block_size);
ifft_scalar = 1.0 / buffer_size;
}
void CircularConvolution::calFFT(std::vector<std::complex<float>>* time_domain, std::vector<std::complex<float>>*freq_domain) {
FFT.transform(time_domain->data(), freq_domain->data());
}
void CircularConvolution::calDotProduct(std::vector<std::complex<float>>* cpx_input_fft, std::vector<std::complex<float>>* cpx_ir_fft, int buffer_size) {
for (int sample = 0; sample < buffer_size; sample ++) {
dot_product->operator[](sample) = cpx_input_fft->operator[](sample) * cpx_ir_fft->operator[](sample);
}
}
std::vector<std::complex<float>>* CircularConvolution::getDotProduct() {
return dot_product;
}
void CircularConvolution::calCircularConv(std::vector<std::complex<float>>* dot_product) {
iFFT.transform(dot_product->data(), cconv_result->data());
}
float* CircularConvolution::getConvResult() {
for (int i = 0; i < block_size; i++) {
real_conv[i] = ifft_scalar * (cconv_result->operator[](i+block_size).real());
//std::cout << "real_conv1: " << real_conv[i] << std::endl;
}
return real_conv;
}
void CircularConvolution::outputRealConv() {
for (int i = 0; i < block_size; i++) {
std::cout << "real_conv: " << real_conv[i] << std::endl;
}
}
void CircularConvolution::outputConv() {
for (int i = 0; i < buffer_size; i++) {
std::cout << cconv_result->operator[](i) << std::endl;
}
}
void CircularConvolution::outputDotProduct() {
for (int i = 0; i < buffer_size; i++) {
std::cout << "dot_product: " << dot_product->operator[](i) << std::endl;
}
}
|
#include <strings.h>
#include "utils.h"
#include "opengl_function.h"
#define LIBRARY(name) const char* STRING_ ## name ## _LIBRARY = #name;
#include "libraries.h"
#undef LIBRARY
string trim(string str)
{
str.erase(str.begin(), find_if(str.begin(), str.end(), not1(ptr_fun<int, int>(isspace))));
str.erase(find_if(str.rbegin(), str.rend(), not1(ptr_fun<int, int>(isspace))).base(), str.end());
return str;
}
string replace_all(string str, char from, const std::string& to)
{
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != string::npos)
{
str.replace(start_pos, 1, to);
start_pos += to.length();
}
return str;
}
string to_upper(string str)
{
for (char& c : str)
c = toupper(c);
return str;
}
unsigned upper_power_of_two(unsigned x)
{
unsigned power = 1;
while (power < x)
power *= 2;
return power;
}
int str_starts_library_to_index(string library)
{
#define LIBRARY(name) \
if (library.substr(0, strlen(#name)) == #name) \
return name ## _LIBRARY;
#include "libraries.h"
#undef LIBRARY
return -1;
}
int library_to_index(string library)
{
#define LIBRARY(name) \
if (library == #name) \
return name ## _LIBRARY;
#include "libraries.h"
#undef LIBRARY
return -1;
}
int library_to_index_force(string library)
{
int index = library_to_index(library);
assert (index != -1);
return index;
}
string index_to_library(int index)
{
#define LIBRARY(name) \
if (index == name ## _LIBRARY) \
return #name;
#include "libraries.h"
#undef LIBRARY
return string("");
}
string index_to_library_force(int index)
{
string library = index_to_library(index);
assert (!library.empty());
return library;
}
string gl_version_to_library(int library)
{
switch (library)
{
case 1: return index_to_library_force(gl1_LIBRARY);
case 2: return index_to_library_force(gl2_LIBRARY);
case 3: return index_to_library_force(gl3_LIBRARY);
default:
abort();
}
return "";
}
int library_to_gl_version(string library)
{
if (library == index_to_library_force(gl1_LIBRARY))
return 1;
if (library == index_to_library_force(gl2_LIBRARY))
return 2;
if (library == index_to_library_force(gl3_LIBRARY))
return 3;
abort();
return -1;
}
void error(const char* number, const char* format, ...)
{
char info[MAX_ERROR_SIZE] = "";
va_list args;
va_start(args, format);
vsprintf(info, format, args);
va_end(args);
cout << "\nError " << number << ": " << info << "\n" << flush;
exit(255);
}
void error_func(opengl_function& func, int number, const char* info)
{
cout << "\nError F" << number << " in function " << func.name << " (" << func.library << "): " << info << "\n" << flush;
exit(255);
}
void error_line(glhl_line &line, int number, const char* info)
{
cout << "\nError H" << number << " in file " << line.file << " at line " <<
line.n << ": " << info << "\nLine: " << line.line << "\n" << flush;
exit(255);
}
|
#ifndef _StartGameProc_H_
#define _StartGameProc_H_
#include "BaseProcess.h"
class Table;
class Player;
class StartGameProc :public BaseProcess
{
public:
StartGameProc();
virtual ~StartGameProc();
int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
private:
int sendTabePlayersInfo(Player* player, Table* table, short num, Player* starter, short seq);
};
#endif
|
#include "graph.h"
/////////////////////////////////////graph functions
//this creates the graph with width (w) and height (h)
struct Graph* createGraph()
{
char *uHeight = (char*) malloc(sizeof(char*));
char *uWidth = (char*) malloc(sizeof(char*));
struct Graph *graphStruct = (struct Graph*) malloc(sizeof(struct Graph*));
int h, w;
printf("Please enter the height for the graph: ");
scanf("%s", uHeight);
printf("Please enter a width for the graph: ");
scanf("%s", uWidth);
h = atoi(uHeight);
w = atoi(uWidth);
int * values = static_cast<int*>(calloc(h*w, sizeof(int)));
int ** graph = static_cast<int**>(malloc(h*sizeof(int*)));
for(int i = 0; i<h; ++i)
{
graph[i] = values + i*w;
}
graphStruct->graph = graph;
graphStruct->height = h;
graphStruct->width = w;
randGraphGen(graphStruct, h, w);
free(uHeight);
free(uWidth);
return graphStruct;
}
//this deletes the graph
void deleteGraph(struct Graph* graph)
{
free(*graph->graph);
free(graph->graph);
free(graph);
}
//this populates the graph with random values
//0 being a clear vertex and 1 being blocked
int randGraphGen(struct Graph* graph, int h, int w)
{
srand(time(0));
int randBit;
int stop = 0;
//nest this in a do while loop that has the while condition
//set to the return from the BFS
while(stop == 0)
{
for(int i = 0; i < h; ++i)
{
for(int j = 0; j < w; ++j)
{
if((j == 0 && i == 0) || (j == w - 1 && i == h - 1))
{
graph->graph[i][j] = 0;
}
else
{
randBit = rand() % 5;
switch(randBit)
{
case 0:
randBit = 0;
break;
case 1:
randBit = 0;
break;
case 2:
randBit = 0;
break;
case 3:
randBit = 1;
break;
case 4:
randBit = 1;
break;
}
graph->graph[i][j] = randBit;
}
}
}
if(BFS(graph, false) != -1)
stop = 1;
}
return 0;
}
//this is the BFS function that returns the shortest path
int BFS(struct Graph* graph, bool printShortstPath)
{
struct Graph* boolGraph = (struct Graph*) malloc(sizeof(struct Graph*));
boolGraph->height = graph->height;
boolGraph->width = graph->width;
initBoolGraph(boolGraph); //Initialize bool graph to all 0's
struct Graph* graphToPrintHolder = (struct Graph*) malloc(sizeof(struct Graph*));
graphToPrintHolder->height = graph->height;
graphToPrintHolder->width = graph->width;
initBoolGraph(graphToPrintHolder); //Initialize bool graph to all 0's
struct Graph* graphToPrint = (struct Graph*) malloc(sizeof(struct Graph*));
graphToPrint->height = graph->height;
graphToPrint->width = graph->width;
initBoolGraph(graphToPrint); //Initialize bool graph to all 0's
std::queue<QNode> newQueue;
QNode initNode;
int leftDown = -1;
int rightUp = 1;
int row;
int col; //ints to keep track of the adjacent rows
initNode.location.x = 0;
initNode.location.y = 0;
initNode.count = 0;
int found;
//push the first node onto the queue
//this does not require a check for zero,
//because the graph will always have a 0 in the
//first position
newQueue.push(initNode);
while(!newQueue.empty())
{
QNode curNode = newQueue.front();
Location curLoc = curNode.location;
if(curLoc.y == graph->width - 1 && curLoc.x == graph->height - 1)
{
if(printShortstPath)
{
//work backwards from the width - 1 and height - 1
//if the graph has a value one lesser than it in any
//direction, store that value into a new graph seperate
//from the graphToPrint graph in its respective cell. This will be a new graph
//that is initialized to zero, and as you find a new value one lesser than
//the highest, find a way to move directly to that cell and start over.
int j = graphToPrint->width -1;
int i = graphToPrint->height -1;
while(graphToPrint->graph[i][j] != 1)
{
found = 0;
//check left
row = i - 1;
col = j;
if(inBounds(graph, row, col) && (graphToPrint->graph[i][j] - 1 == graphToPrint->graph[row][col]) && found == 0)
{
graphToPrintHolder->graph[row][col] = 1;
i = row;
j = col;
found = 1;
}
//check right
row = i + 1;
col = j;
if(inBounds(graph, row, col) && (graphToPrint->graph[i][j]- 1 == graphToPrint->graph[row][col]) && found == 0)
{
graphToPrintHolder->graph[row][col] = 1;
i = row;
j = col;
found = 1;
}
//check up
row = i;
col = j + 1;
if(inBounds(graph, row, col) && (graphToPrint->graph[i][j] - 1 == graphToPrint->graph[row][col]) && found == 0)
{
graphToPrintHolder->graph[row][col] = 1;
i = row;
j = col;
found = 1;
}
//check down
row = i;
col = j - 1;
if(inBounds(graph, row, col) && (graphToPrint->graph[i][j] - 1 == graphToPrint->graph[row][col]) && found == 0)
{
graphToPrintHolder->graph[row][col] = 1;
i = row;
j = col;
found = 1;
}
}
printf("The Solved Graph/Map:");
graphToPrintHolder->graph[graphToPrintHolder->width - 1][graphToPrintHolder->width - 1] = graphToPrint->graph[graph->height - 1][graph->width - 1];
printGraph(graphToPrintHolder);
}
deleteGraph(boolGraph);
deleteGraph(graphToPrint);
deleteGraph(graphToPrintHolder);
return curNode.count;
}
else
newQueue.pop();
//check left
row = curLoc.x;
col = curLoc.y + leftDown;
if(inBounds(graph, row, col) && graph->graph[row][col] == 0 && boolGraph->graph[row][col] == 0)
{
QNode left;
left.location.x = row;
left.location.y = col;
left.count = curNode.count + 1;
newQueue.push(left);
graphToPrint->graph[row][col] = curNode.count + 1;
boolGraph->graph[row][col] = 1;
}
//check right
row = curLoc.x;
col = curLoc.y + rightUp;
if(inBounds(graph, row, col) && graph->graph[row][col] == 0 && boolGraph->graph[row][col] == 0)
{
QNode right;
right.location.x = row;
right.location.y = col;
right.count = curNode.count + 1;
newQueue.push(right);
graphToPrint->graph[row][col] = curNode.count + 1;
boolGraph->graph[row][col] = 1;
}
//check up
row = curLoc.x + rightUp;
col = curLoc.y;
if(inBounds(graph, row, col) && graph->graph[row][col] == 0 && boolGraph->graph[row][col] == 0)
{
QNode up;
up.location.x = row;
up.location.y = col;
up.count = curNode.count + 1;
newQueue.push(up);
graphToPrint->graph[row][col] = curNode.count + 1;
boolGraph->graph[row][col] = 1;
}
//check down
row = curLoc.x + leftDown;
col = curLoc.y;
if(inBounds(graph, row, col) && graph->graph[row][col] == 0 && boolGraph->graph[row][col] == 0)
{
QNode down;
down.location.x = row;
down.location.y = col;
down.count = curNode.count + 1;
newQueue.push(down);
graphToPrint->graph[row][col] = curNode.count + 1;
boolGraph->graph[row][col] = 1;
}
}
deleteGraph(boolGraph);
return -1;
}
//print the graph in ascii art
void printGraph(struct Graph* graph)
{
//print an initial new line for spacing purposes
printf("\n");
for(int i = 0; i < (graph->height); ++i)
{
for(int j = 0; j < (graph->width); ++j)
{
printf(" %d ", graph->graph[i][j]);
}
printf("\n");
}
//print a final new line for spacing purposes
printf("\n");
}
//check to see if the position is in the graph's bounds
bool inBounds(struct Graph* graph, int posX, int posY)
{
int gHeight = graph->height;
int gWidth = graph->width;
if(posX >= 0 && posY >= 0 && posX < gHeight && posY < gWidth)
return true;
return false;
}
void initBoolGraph(struct Graph* boolGraph)
{
int * values = static_cast<int*>(calloc(boolGraph->height*boolGraph->width, sizeof(int)));
int ** graph = static_cast<int**>(malloc((boolGraph->height)*sizeof(int*)));
for(int i = 0; i<boolGraph->height; ++i)
{
graph[i] = values + i*boolGraph->width;
}
boolGraph->graph = graph;
for(int i = 0; i < boolGraph->height; ++i)
{
for(int j = 0; j < boolGraph->width; ++ j)
{
boolGraph->graph[i][j] = 0;
}
}
}
|
/*
* MessageManager.h
*
* Created on: Jun 11, 2017
* Author: root
*/
#ifndef NETWORK_MESSAGEMANAGER_H_
#define NETWORK_MESSAGEMANAGER_H_
#include <deque>
#include "../Smart_Ptr.h"
#include "../Thread/Task.h"
#include "../define.h"
#include "NetWorkConfig.h"
#include "../Common.h"
#include "Service_Handler.h"
#include "../ClassBase.h"
#include "../Ref_Object.h"
#include "../Memory/MemAllocator.h"
using namespace std;
namespace CommBaseOut
{
class Context;
class Session;
class Message : public Ref_Object
#ifdef USE_MEMORY_POOL
, public MemoryBase
#endif
{
public:
Message();
Message(int id, unsigned int type);
Message(int id, unsigned int type, int channel);
Message(int channel);
Message(int id, unsigned int type, int group, int64 key);
Message(Safe_Smart_Ptr<Message> &message);
~Message();
void SetHead(packetHeader &head);
void GetHead(packetHeader *head);
void SetContent(const char *content, int len);
char * GetContent();
void SetAddr(Safe_Smart_Ptr<Inet_Addr> &addr)
{
m_addr = addr;
}
Safe_Smart_Ptr<Inet_Addr> &GetAddr()
{
return m_addr;
}
void SetErrno(int no)
{
m_errno = no;
}
int GetErrno()
{
return m_errno;
}
void SetReqID(int id)
{
m_reqID = id;
}
int GetReqID()
{
return m_reqID;
}
void SetChannelID(int id)
{
m_channelID = id;
}
int GetChannelID()
{
return m_channelID;
}
void SetMessageID(DWORD id)
{
m_messageID = id;
}
DWORD GetMessageID()
{
return m_messageID;
}
int GetLength()
{
return m_length;
}
void SetMessageType(unsigned char type)
{
m_messageType = type;
}
int GetMessageType()
{
return m_messageType;
}
char * GetBuffer(int &len)
{
len = m_length;
return m_content;
}
void SetRequest(Safe_Smart_Ptr<Message> &req)
{
m_req = req;
}
Safe_Smart_Ptr<Message> &GetRequest()
{
return m_req;
}
void SetTimeout(WORD time)
{
m_timeout = time;
}
WORD GetTimeout()
{
return m_timeout;
}
void SetSecurity(bool se)
{
m_security = se;
}
bool GetSecurity()
{
return m_security;
}
void SetRemoteID(short int id)
{
m_remoteID = id;
}
short int GetRemoteID()
{
return m_remoteID;
}
void SetRemoteType(unsigned char type)
{
m_remoteType = type;
}
unsigned char GetRemoteType()
{
return m_remoteType;
}
short int GetLocalID()
{
return m_localID;
}
void SetLocalID(short int id)
{
m_localID = id;
}
void SetLocalType(unsigned char type)
{
m_localType = type;
}
unsigned char GetLocalType()
{
return m_localType;
}
void SetMessageTime(DWORD64 time)
{
m_sendTime = time;
}
DWORD64 GetMessageTime()
{
return m_sendTime;
}
int GetLoopIndex()
{
return m_loopIndex;
}
void SetLoopIndex(int index)
{
m_loopIndex = index;
}
int GetGroup()
{
return m_group;
}
void SetGroup(int group)
{
m_group = group;
}
int64 GetGroupKey()
{
return m_groupKey;
}
void SetGroupKey(int64 key)
{
m_groupKey = key;
}
void SetAct(Safe_Smart_Ptr<NullBase> act)
{
m_act = act;
}
Safe_Smart_Ptr<NullBase> & GetAct()
{
return m_act;
}
//加密判断
void EncryptMessage();
//解密判断
bool UnEncryptMessage();
private:
char * m_content;
Safe_Smart_Ptr<Message> m_req;
Safe_Smart_Ptr<Inet_Addr> m_addr;
short int m_remoteID;
unsigned char m_remoteType;
short int m_localID;
unsigned char m_localType;
WORD m_timeout;
int m_reqID;
int m_channelID;
DWORD m_messageID;
BYTE m_messageType;
int m_length;
int m_errno;
bool m_security;
DWORD64 m_sendTime;
int m_loopIndex;
int m_group;
int64 m_groupKey;
Safe_Smart_Ptr<NullBase> m_act;
};
}
#endif /* NETWORK_MESSAGEMANAGER_H_ */
|
#ifndef system_h
#define system_h
#include <windows.h>
#include <vector>
#include <string>
#include <functional>
#include <algorithm>
#ifdef WIN32
#include <shellapi.h>
#include <tlhelp32.h>
#endif // WIN32
namespace exception {
struct DisplaySize
{
int width;
int height;
DisplaySize(int w, int h) : width(w), height(h)
{}
bool operator==(const DisplaySize& v) const
{
return width==v.width && height==v.height;
}
bool operator<(const DisplaySize& v) const
{
return width!=v.width ? width<v.width : height<v.height;
}
};
typedef std::vector<DisplaySize> DisplaySizeList;
inline const DisplaySizeList& EnumDisplaySize()
{
static DisplaySizeList s_dsize;
if(s_dsize.empty()) {
#ifdef WIN32
::DEVMODE dm;
for(int i=0; ::EnumDisplaySettings(0, i, &dm); ++i) {
if(dm.dmBitsPerPel>16) {
DisplaySize t(dm.dmPelsWidth, dm.dmPelsHeight);
if(std::find(s_dsize.begin(), s_dsize.end(), t)==s_dsize.end()) {
s_dsize.push_back(t);
}
}
}
std::sort(s_dsize.begin(), s_dsize.end(), std::less<DisplaySize>());
#else // WIN32
DisplaySize dm[] = {
DisplaySize(640, 480),
DisplaySize(800, 600),
DisplaySize(1024, 768),
DisplaySize(1280, 800),
DisplaySize(1280, 960),
DisplaySize(1280, 1024),
};
#endif // WIN32
}
return s_dsize;
}
void OpenURL(const std::string& url);
bool FindProcess(const char *exe);
}
#endif // system_h
|
#ifndef _Reload_H_
#define _Reload_H_
#include "BaseProcess.h"
class Reload : public BaseProcess {
public:
Reload() { this->name = "Reload"; };
virtual ~Reload() {};
virtual int doRequest(CDLSocketHandler *clientHandler, InputPacket *inputPacket, Context *pt);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef UTIL_STRINGHASH_H
#define UTIL_STRINGHASH_H
#include "modules/util/hash.h"
/** Simple char* -> T hash table.
*
* This hash table keeps copies of key strings internally, eliminating messy
* ownership issues. It is used in (and tailored for size-wise) the WebGL
* implementation to keep track of data for various types of identifiers.
*
* I'd be happy to replace this class with some "Opera STL" equivalent if that
* ever comes along. It was introduced mainly to solve key string ownership
* issues and get a less clunky hash table interface. /Ulf
*
* Limitations:
*
* - No selective deletion of individual key/value pairs.
* - Modification during iteration is not safe in general.
*
*/
template<class T>
class StringHash
{
public:
StringHash() : cnt(0)
{
for (unsigned i = 0; i < N_BUCKETS; ++i)
buckets[i] = NULL;
}
~StringHash() { clear(); }
/** Get the data associated with a key.
*
* @param key The key string to look up.
* @param data Receives the data if @p key is in the table; unmodified
* otherwise.
*
* @return @c true if @p key is in the table, otherwise @c false.
*/
bool get(const char *key, T& data) const
{
for (Node *node = buckets[djb2hash(key) % N_BUCKETS]; node; node = node->next)
if (op_strcmp(node->key, key) == 0)
{
data = node->data;
return true;
}
return false;
}
/** Set the data associated with a key.
*
* A copy of the key string is stored internally in the hash table, so the
* caller is free to deallocate the string afterwards. @p data is copied
* internally using its cctor and operator=().
*
* @param key The key whose associated data is to be set.
* @param data The associated data to set.
*
* @retval OpStatus::OK The key was successfully inserted.
* @retval OpStatus::ERR_NO_MEMORY The insert operation failed due to OOM.
* The hash table will still be in a consistent state (without the
* new key and associated data) if this happens.
*/
OP_STATUS set(const char *key, const T& data)
{
Node **nextpp;
for (nextpp = &buckets[djb2hash(key) % N_BUCKETS]; *nextpp; nextpp = &(*nextpp)->next)
{
Node *node = *nextpp;
if (op_strcmp(node->key, key) == 0)
{
node->data = data;
return OpStatus::OK;
}
}
RETURN_IF_ERROR(add_node(nextpp, key, data));
++cnt;
return OpStatus::OK;
}
/** Check if a string is a key of the hash table.
*
* @param key The key string to look up.
*
* @return @c true if @p key is in the table, otherwise @c false.
*/
bool contains(const char *key) const
{
for (Node *node = buckets[djb2hash(key) % N_BUCKETS]; node; node = node->next)
if (op_strcmp(node->key, key) == 0)
return true;
return false;
}
/** Create a copy of the hash table.
*
* New copies of the key strings are allocated, so deallocating the source
* table afterwards is safe.
*
* @param new_sh Receives the new hash table. The prior value of the
* pointer is ignored.
*
* @retval OpStatus::OK The table was successfully copied.
* @retval OpStatus::ERR_NO_MEMORY The copy operation failed due to OOM.
* @p new_sh will not be modified if this happens.
*/
OP_STATUS copy(StringHash *&new_sh) const
{
StringHash *new_sh_local = new StringHash;
RETURN_OOM_IF_NULL(new_sh_local);
for (unsigned bucket = 0; bucket < N_BUCKETS; ++bucket)
{
Node *read_node;
Node **write_node;
for (read_node = buckets[bucket], write_node = &new_sh_local->buckets[bucket];
read_node;
read_node = read_node->next, write_node = &(*write_node)->next)
{
if (OpStatus::IsMemoryError(add_node(write_node, read_node->key, read_node->data)))
{
OP_DELETE(new_sh_local);
return OpStatus::ERR_NO_MEMORY;
}
}
}
new_sh_local->cnt = cnt;
new_sh = new_sh_local;
return OpStatus::OK;
}
/** Get the number of entries in the hash table.
*
* @return The number of keys with associated data that appear in the table.
*/
unsigned count() const { return cnt; }
/** Remove all key/value pairs from the hash table.
*
* Leaves the hash table in the same state as a newly created hash table.
*/
void clear()
{
for (unsigned i = 0; i < N_BUCKETS; ++i)
{
for (Node *node = buckets[i]; node;)
{
Node *next = node->next;
op_free(node->key);
OP_DELETE(node);
node = next;
}
buckets[i] = NULL;
}
cnt = 0;
}
private:
enum { N_BUCKETS = 31 };
struct Node
{
char *const key;
T data;
Node *next;
Node(char *key, const T& data)
: key(key)
, data(data)
, next(NULL) {}
};
Node *buckets[N_BUCKETS];
static OP_STATUS add_node(Node **location, const char *key, const T& data)
{
char *key_copy = op_strdup(key);
RETURN_OOM_IF_NULL(key_copy);
Node *new_node = OP_NEW(Node, (key_copy, data));
if (!new_node)
{
op_free(key_copy);
return OpStatus::ERR_NO_MEMORY;
}
// Make sure we are overwriting a null pointer
OP_ASSERT(!*location);
*location = new_node;
return OpStatus::OK;
}
unsigned cnt;
public:
class Iterator;
friend class Iterator;
/** StringHash iterator.
*
* Iterator class for stepping through all key/value pairs in a StringHash.
* Modifying the hash table during iteration is not safe in general.
*
* Example usage:
*
* StringHash<int> hash;
* <populate hash>
* StringHash<int>::Iterator iter = hash.get_iterator();
* const char *key;
* int value;
* while (iter.get_next(key, value))
* <do something with 'key' and 'value'>
*/
class Iterator
{
friend class StringHash;
private:
explicit Iterator(Node **buckets)
: buckets(buckets)
, current_bucket(-1)
, next_node(NULL) {}
public:
/** Get the next key/value pair from the table.
*
* @param key Receives the key. Unmodified if no more key/value pairs exist
* in the table.
*
* @param data Receives the associated data. Unmodified if no more
* key/value pairs exist in the table.
*
* @retval true key/data received the next key/value pair from the table.
* @retval false No more key/value pairs exist in the table.
*/
bool get_next(const char *&key, T& data)
{
while (!next_node)
{
if (current_bucket == N_BUCKETS - 1)
return false;
++current_bucket;
next_node = buckets[current_bucket];
}
key = next_node->key;
data = next_node->data;
next_node = next_node->next;
return true;
}
private:
Node **buckets;
int current_bucket;
typename StringHash::Node *next_node;
};
/** Get an iterator for stepping through all key/value pairs in the table.
*
* Modifying the table during iteration is not safe in general.
*/
Iterator get_iterator() { return Iterator(buckets); }
};
#endif // UTIL_STRINGHASH_H
|
#include <iostream>
#include <clocale>
using namespace std;
int* Perechislenie(int mM);
int* Talk_A(int mM);
int* Talk_B(int mM);
void neto();
void mn(int *A, int mA, int *B, int mB);
int* edin(int *A, int *B, int mA, int mB);
int* peresechenie(int *A, int *B, int mA, int mB);
int* Pa3HocTb(int *U, int *W, int mU, int mW);
int* Add(int *M, int mM);
int* SimmRaz(int *A, int *B, int mA, int mB);
int* Dekart(int *A, int *B, int mA, int mB);
int main()
{
setlocale(LC_ALL, "rus");
int *A, *B;
int mA, mB, mC, mD, mR, mY, mE, mP, mS;
int i, Operaziya = 0, ZMA = 0, ZMB = 0;
cout << "Введите мощность множества А (от 0 до 100): ";
cin >> mA;
A = new int[mA];
cout << endl;
cout << "Введите мощность множества B (от 0 до 100): ";
cin >> mB;
B = new int[mB];
cout << endl << "--------------------------------------------------------------------------------------" << endl << endl;
cout << "Выберите способ задания множества А: " << endl;
cout << " 1. Перечисление.\n 2. Высказывание.\n";
cin >> ZMA;
switch (ZMA)
{
case 1:
A = Perechislenie(mA);
break;
case 2:
A = Talk_A(mA);
break;
default:
neto();
return 0;
}
cout << endl << endl;
cout << "Выберите способ задания множества B: " << endl;
cout << " 1. Перечисление.\n 2. Высказывание.\n";
cin >> ZMB;
switch (ZMB)
{
case 1:
B = Perechislenie(mB);
break;
case 2:
B = Talk_B(mB);
break;
default:
neto();
return 0;
}
cout << endl << endl << "Множества А и В заполнены!" << endl << endl;
while (true)
{
system("pause");
system("cls");
mn(A, mA, B, mB);
cout << "Выберите операцию:" << endl;
cout << " 1. Объединение множеств\n 2. Пересечение множеств\n 3. Разность A и В\n 4. Дополнение А до U\n 5. Симметричная разность A u B\n 6. Декартово произведение A на B\n 0. Выход\n";
cin >> Operaziya;
system("cls");
switch (Operaziya)
{
case 1:
{
cout << "Объединение множеств" << endl;
int *C = new int[mA + mB];
C = edin(A, B, mA, mB);
mC = C[0];
for (int i = 1; i <= mC; i++)
cout << C[i] << " ";
cout << endl;
}
break;
case 2:
{
cout << "Пересечение множеств" << endl;
int *D = new int[mA + mB];
D = peresechenie(A, B, mA, mB);
mD = D[0];
for (int i = 1; i <= mD; i++)
cout << D[i] << " ";
cout << endl;
}
break;
case 3:
{
cout << "Разность A и В" << endl;
int *R = new int[mA];
R = Pa3HocTb(A, B, mA, mB);
mR = R[0];
for (int i = 1; i <= mR; i++)
cout << R[i] << " ";
cout << endl;
}
break;
/*case 4:
{
cout << "Разность B и A" << endl;
int *Y = new int[mB];
Y = Pa3HocTb(B, A, mB, mA);
mY = Y[0];
for (int i = 1; i <= mY; i++)
cout << Y[i] << " ";
cout << endl;
}
break;*/
case 4:
{
cout << "Дополнение А до U" << endl;
int *E = new int[101];
E = Add(A, mA);
mE = E[0];
for (int i = 1; i <= mE; i++)
cout << E[i] << " ";
cout << endl;
}
break;
/*case 6:
{
cout << "Дополнение B до U" << endl;
int *E = new int[1001];
E = Add(B, mB);
mE = E[0];
for (int i = 1; i <= mE; i++)
cout << E[i] << " ";
cout << endl;
}
break;*/
case 5:
{
cout << "Симметричная разность А и В" << endl;
int *S = new int[mA + mB + 2];
S = SimmRaz(A, B, mA, mB);
mS = S[0];
for (int i = 1; i <= mS; i++)
cout << S[i] << " ";
cout << endl;
}
break;
case 6:
{
cout << "Декартово произведение A на B" << endl;
int *P = new int[2 * (mA * mB) + 2];
P = Dekart(A, B, mA, mB);
mP = P[0];
for (int i = 1; i <= mP; i++)
{
cout << "<" << P[i] << ", " << P[i + 1] << ">";
if (i < mP - 1)
cout << ", ";
i++;
}
cout << endl;
}
break;
case 9:
{
cout << "Декартово произведение B на A" << endl;
int *P = new int[2 * (mA * mB) + 2];
P = Dekart(B, A, mB, mA);
mP = P[0];
for (int i = 1; i <= mP; i++)
{
cout << "<" << P[i] << ", " << P[i + 1] << ">";
if (i < mP - 1)
cout << ", ";
i++;
}
cout << endl;
}
break;
case 0:
return 0;
}
}
}
int* Perechislenie(int mM)
{
int *M = new int[mM];
if (mM == 0)
{
cout << endl << "Пустое множество!" << endl;
return M;
}
cout << endl << "Введте элементы множества: " << endl;
for (int i = 0; i < mM; i++)
cin >> M[i];
return M;
}
int* Talk_A(int n)
{
int *A = new int[n];
int a = 0;
cout << endl << "Элементы множества А: ";
if (n == 0)
{
cout << endl << endl << "Пустое множество!";
return A;
}
for (int x = 0; x < n; x++)
{
a = 4 * (x + 1) + 2 * (n - x);
A[x] = a;
cout << endl << a << " ";
}
return A;
}
int* Talk_B(int m)
{
int *B = new int[m];
int b = 0;
cout << endl << "Элементы множества B: ";
if (m == 0)
{
cout << endl << endl << "Пустое множество!";
return B;
}
for (int y = 0; y < m; y++)
{
b = 2 * (m - y) + 3 * y;
B[y] = b;
cout << endl << b << " ";
}
return B;
}
void neto()
{
cout << endl << endl << endl << " Sirius li? Там нет такой цифры. Код привередливый, код сломан!!!\n ПЕРЕзапускай ПроГРаМММУУУУУ.....\n EROoorr........Ereoreorr............" << endl << endl << endl;
system("pause");
}
void mn(int *A, int mA, int *B, int mB)
{
cout << "A = ";
cout << "{";
for (int i = 0; i < mA; i++)
{
cout << A[i];
if (i < (mA - 1))
cout << ", ";
}
cout << "}" << endl;
cout << "B = ";
cout << "{";
for (int i = 0; i < mB; i++)
{
cout << B[i];
if (i < (mB - 1))
cout << ", ";
}
cout << "}" << endl;
}
int* edin(int *A, int *B, int mA, int mB)
{
int mO = mA + mB + 1, i = 0;
int *C = new int[mO];
if (mB == 0 && mA == 0)
{
cout << "Пустое множество!";
return C;
}
if (mA == 0)
{
for (i = 0; i<mB; i++)
{
C[i + 1] = B[i];
}
C[0] = i;
return C;
}
if (mB == 0)
{
for (i = 0; i<mA; i++)
{
C[i + 1] = A[i];
}
C[0] = i;
return C;
}
for (i = 0; i<mA; i++)
{
C[i + 1] = A[i];
}
for (int b = 0; b < mB; b++)
{
for (int a = 0; a < mA; a++)
{
if (B[b] == A[a])
break;
if (B[b] != A[a])
{
if (a == (mA - 1))
{
i++;
C[i] = B[b];
}
else continue;
}
}
}
C[0] = i;
return C;
}
int* peresechenie(int *A, int *B, int mA, int mB)
{
int *D = new int[mB + mA];
int i = 0;
if (mA == 0 || mB == 0)
{
cout << "Пустое множество!";
return D;
}
for (int b = 0; b < mB; b++)
{
for (int a = 0; a < mA; a++)
{
if (B[b] == A[a])
{
i++;
D[i] = B[b];
}
}
}
if (i == 0)
cout << endl << "Пустое множество!" << endl;
D[0] = i;
return D;
}
int* Pa3HocTb(int *U, int *W, int mU, int mW)
{
int *R = new int[mU + 1];
int r = 0;
if (mU == 0)
{
cout << "Пустое множество!";
return R;
}
if (mW == 0)
{
for (int i = 0; i < mU; i++)
{
R[i + 1] = U[i];
}
R[0] = mU;
return R;
}
for (int i = 0; i < mU; i++)
{
for (int j = 0; j < mW; j++)
{
if (U[i] == W[j])
break;
if (j == (mW - 1))
{
r++;
R[r] = U[i];
}
}
}
if (r == 0)
cout << "Пустое множество!";
R[0] = r;
return R;
}
int* Add(int *M, int mM)
{
int *U = new int[100];
for (int u = 1; u <= 100; u++)
U[u] = u;
int *E = new int[101];
int e = 0;
if (mM == 0)
{
U[0] = 100;
return U;
}
for (int i = 1; i < 101; i++)
{
for (int j = 0; j < mM; j++)
{
if (U[i] == M[j])
break;
if (U[i] != M[j])
{
if (j == (mM - 1))
{
e++;
E[e] = U[i];
}
else continue;
}
}
}
E[0] = e;
return E;
}
int* SimmRaz(int *A, int *B, int mA, int mB)
{
int *S = new int[mA + mB + 2];
int s = 0, o = 0;
if (mA == 0 && mB == 0)
{
cout << "Пустое множество!";
return S;
}
if (mA == 0)
{
for (int i = 0; i < mB; i++)
{
S[i + 1] = B[i];
}
S[0] = mB;
return S;
}
if (mB == 0)
{
for (int i = 0; i < mA; i++)
{
S[i + 1] = A[i];
}
S[0] = mA;
return S;
}
for (int i = 0; i < mA; i++)
{
for (int j = 0; j < mB; j++)
{
o = 0;
if (A[i] == B[j])
continue;
for (int l = 1; l <= s; l++)
{
if (S[l] == A[i])
{
o = 1;
break;
}
}
for (int v = 0; v < mB; v++)
{
if (A[i] == B[v])
{
o = 1;
break;
}
}
if (o == 1)
continue;
s++;
S[s] = A[i];
}
}
for (int i = 0; i < mA; i++)
{
for (int j = 0; j < mB; j++)
{
o = 0;
for (int l = 1; l <= s; l++)
{
if (S[l] == B[j])
{
o = 1;
break;
}
}
for (int v = 0; v < mA; v++)
{
if (A[v] == B[j])
{
o = 1;
break;
}
}
if (o == 1)
continue;
s++;
S[s] = B[j];
}
}
if (s == 0)
cout << "Пустое множество!";
S[0] = s;
return S;
}
int* Dekart(int *A, int *B, int mA, int mB)
{
int *P = new int[2 * (mA*mB) + 2];
int p = 0, o = 0;
if (mA < 1 || mB<1)
{
cout << "Пустое множество!";
return P;
}
for (int i = 0; i < mA; i++)
{
for (int j = 0; j < mB; j++)
{
o = 0;
for (int k = 1; k < p; k += 2)
{
if (A[i] == P[k] && B[j] == P[k + 1])
{
o = 1;
break;
}
}
if (o == 1)
continue;
p++;
P[p] = A[i];
p++;
P[p] = B[j];
}
}
P[0] = p;
return P;
}
|
#ifndef DICON_H
#define DICON_H
#include <QQuickPaintedItem>
#include <QPainter>
class DIcon : public QQuickPaintedItem
{
Q_OBJECT
Q_DISABLE_COPY(DIcon)
Q_PROPERTY(QString theme READ theme WRITE setTheme NOTIFY themeChanged)
Q_PROPERTY(QString icon READ icon WRITE setIcon NOTIFY iconChanged)
public:
DIcon(QQuickPaintedItem *parent = 0);
~DIcon();
const QString& theme() { return m_theme; }
void setTheme(const QString& v);
Q_SIGNAL void themeChanged(QString);
const QString& icon() { return m_icon; }
void setIcon(const QString& v);
Q_SIGNAL void iconChanged(QString);
void paint(QPainter *painter);
private:
QString m_icon;
QString m_theme;
};
#endif // DICON_H
|
/*****************************************************************
* Copyright (C) 2017-2018 Robert Valler - All rights reserved.
*
* This file is part of the project: DevPlatformAppCMake.
*
* This project can not be copied and/or distributed
* without the express permission of the copyright holder
*****************************************************************/
#ifndef CORE_H
#define CORE_H
#include <thread>
#include <atomic>
enum stateMachineState {
smNull,
smStart,
smRun,
smStop
};
class ObjectFactory;
class IMainWnd;
struct coreParm {
std::shared_ptr<IMainWnd> pMWin;
std::shared_ptr<ObjectFactory> pObjFactory;
};
class core
{
public:
core(coreParm p);
~core()=default;
void exitNotification();
private:
void task();
void processStateMachine();
void setState(stateMachineState state);
stateMachineState getState(){return systemState;}
stateMachineState systemState;
std::thread t_core;
std::atomic<bool> exitThreadRequest;
std::atomic<bool> isExitNotification;
coreParm parm;
};
#endif // CORE_H
|
#pragma once
#include "../../Physics/Settings/PhysicsSettings.h"
#include "../../Maths/Functions/MathsFunctions.h"
#include "../../Aero/Aero.h"
#include "../../UI/Dependencies/IncludeImGui.h"
namespace ae
{
namespace priv
{
namespace ui
{
inline void PhysicsSettingsToEditor( PhysicsSettings& _PhysicsSettings )
{
ImGui::Text( "Physics Settings" );
std::string Integrators[3] = { "Euler", "Euler Ending Velocity", "Euler Average Velocity" };
Uint8 Integrator = ae::Math::Clamp( Cast( Uint8, 0 ), Cast( Uint8, 3 ), Cast( Uint8, _PhysicsSettings.Integrator ) );
if( ImGui::BeginCombo( "Integration Method", Integrators[Integrator].c_str() ) )
{
Bool IsSelected = False;
for( Uint8 p = 0; p < 3; p++ )
{
IsSelected = p == Integrator;
if( ImGui::Selectable( Integrators[p].c_str(), &IsSelected ) )
Integrator = p;
if( IsSelected )
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
_PhysicsSettings.Integrator = Cast( PhysicsSettings::IntegrationMethod, Integrator );
ImGui::DragFloat3( "Gravity", &_PhysicsSettings.Gravity.X );
ImGui::DragFloat3( "Global Wind", &_PhysicsSettings.GlobalWind.X );
int FixedFrameRate = Cast( int, _PhysicsSettings.FixedFrameRate );
ImGui::SliderInt( "Fixed Frame Rate", &FixedFrameRate, 1, 100 );
_PhysicsSettings.FixedFrameRate = Cast( Uint32, FixedFrameRate );
ImGui::Separator();
}
}
} // priv
} // ae
|
#include "StdAfx.h"
#include "wmvfile.h"
#include <comdef.h> // Compiler COM support
#include <atlbase.h>
#include <iostream>
using namespace std;
#ifndef __countof
#define __countof(x) ((sizeof(x)/sizeof(x[0])))
#endif
namespace com
{
namespace drollic
{
namespace graphics
{
namespace painting
{
namespace native
{
namespace processing
{
CwmvFile::CwmvFile() : readyToGenerate(false) {}
void CwmvFile::PrepareToGenerate(
const GUID& guidProfileID /*= WMProfile_V80_384Video*/,
DWORD dwFrameRate /*= 1*/,
char *movieFilename)
{
readyToGenerate = true;
totalFramesWritten = 0;
keyFrameEveryNFrames = 100;
//LPCTSTR lpszFileName = _T(movieFilename);
//LPCTSTR lpszFileName = A2CT(movieFilename);
//std::cout << "Entering Constructor" << std::endl;
//std::cout.flush();
CoInitialize(NULL);
HRESULT hr=E_FAIL;
GUID guidInputType;
DWORD dwInputCount=0;
IWMInputMediaProps* pInputProps = NULL;
IWMProfileManager2 *pProfileManager2=NULL;
m_hwmvDC = NULL;
m_pWMWriter = NULL;
m_dwVideoInput = 0;
m_msVideoTime = 0;
m_pWMProfile = NULL;
m_pVideoProps = NULL;
m_pWMProfileManager = NULL;
m_dwCurrentVideoSample = 0;
m_dwFrameRate = dwFrameRate;
_tcscpy(m_szErrMsg, _T("Method Succeeded"));
m_szErrMsg[__countof(m_szErrMsg)-1] = _T('\0');
pAppendFrame[0] = &CwmvFile::AppendDummy; // VC8 requires & for Function Pointer; Remove it if your compiler complains;
pAppendFrame[1] = &CwmvFile::AppendFrameFirstTime;
pAppendFrame[2] = &CwmvFile::AppendFrameUsual;
pAppendFrameBits[0] = &CwmvFile::AppendDummy;
pAppendFrameBits[1] = &CwmvFile::AppendFrameFirstTime;
pAppendFrameBits[2] = &CwmvFile::AppendFrameUsual;
m_nAppendFuncSelector=0; //Point to DummyFunction
if(FAILED(WMCreateProfileManager(&m_pWMProfileManager)))
{
SetErrorMessage(L"Unable to Create WindowsMedia Profile Manager");
goto TerminateConstructor;
}
if(FAILED(m_pWMProfileManager->QueryInterface(IID_IWMProfileManager2,(void**)&pProfileManager2)))
{
SetErrorMessage(L"Unable to Query Interface for ProfileManager2");
goto TerminateConstructor;
}
hr=pProfileManager2->SetSystemProfileVersion(WMFORMAT_SDK_VERSION);
pProfileManager2->Release();
if(FAILED(hr))
{
SetErrorMessage(L"Unable to Set System Profile Version");
goto TerminateConstructor;
}
if(FAILED(m_pWMProfileManager->LoadProfileByID(guidProfileID,&m_pWMProfile)))
{
SetErrorMessage(L"Unable to Load System Profile");
goto TerminateConstructor;
}
if(FAILED(WMCreateWriter(NULL,&m_pWMWriter)))
{
SetErrorMessage(L"Unable to Create Media Writer Object");
goto TerminateConstructor;
}
if(FAILED(m_pWMWriter->SetProfile(m_pWMProfile)))
{
SetErrorMessage(L"Unable to Set System Profile");
goto TerminateConstructor;
}
if(FAILED(m_pWMWriter->GetInputCount(&dwInputCount)))
{
SetErrorMessage(L"Unable to Get input count For Profile");
goto TerminateConstructor;
}
for(DWORD i=0;i<dwInputCount;i++)
{
if(FAILED(m_pWMWriter->GetInputProps(i,&pInputProps)))
{
SetErrorMessage(L"Unable to GetInput Properties");
goto TerminateConstructor;
}
if(FAILED(pInputProps->GetType(&guidInputType)))
{
SetErrorMessage(L"Unable to Get Input Property Type");
goto TerminateConstructor;
}
if(guidInputType==WMMEDIATYPE_Video)
{
m_pVideoProps=pInputProps;
m_dwVideoInput=i;
break;
}
else
{
pInputProps->Release();
pInputProps=NULL;
}
}
if(m_pVideoProps==NULL)
{
SetErrorMessage(L"Profile Does not Accept Video input");
goto TerminateConstructor;
}
#ifndef UNICODE
WCHAR pwszOutFile[1024];
if( 0 == MultiByteToWideChar( CP_ACP, 0, lpszFileName,-1, pwszOutFile, sizeof( pwszOutFile ) ) )
{
SetErrorMessage("Unable to Convert Output Filename");
goto TerminateConstructor;
}
if(FAILED(m_pWMWriter->SetOutputFilename( pwszOutFile )))
{
SetErrorMessage("Unable to Set Output Filename");
goto TerminateConstructor;
}
#else
/* calculate the no. of bytes in the input string, including terminating null */
size_t n = strlen(movieFilename) + 1;
/* allocate space for wchar array; */
wchar_t *pwcs = (wchar_t *)malloc (n * sizeof(wchar_t));
size_t rtrn_value = mbstowcs(pwcs, movieFilename, n);
//if(FAILED(m_pWMWriter->SetOutputFilename(lpszFileName)))
if(FAILED(m_pWMWriter->SetOutputFilename(pwcs)))
{
SetErrorMessage(L"Unable to Set Output Filename");
goto TerminateConstructor;
}
#endif //UNICODE
m_nAppendFuncSelector=1; //0=Dummy 1=FirstTime 2=Usual
//std::cout << "Leaving Constructor, normal exit" << std::endl;
//std::cout.flush();
return;
TerminateConstructor:
ReleaseMemory();
//std::cout << "Leaving Constructor, after ReleaseMemory" << std::endl;
//std::cout.flush();
return;
}
CwmvFile::~CwmvFile(void)
{
//std::cout << "Entering destructor" << std::endl;
//std::cout.flush();
if (readyToGenerate)
{
ReleaseMemory();
CoUninitialize();
}
//std::cout << "Leaving destructor" << std::endl;
//std::cout.flush();
}
void CwmvFile::ReleaseMemory()
{
//std::cout << "Entering ReleaseMemory" << std::endl;
//std::cout.flush();
if(m_nAppendFuncSelector==2) //If we are Currently Writing
{
if(m_pWMWriter)
m_pWMWriter->EndWriting();
}
m_nAppendFuncSelector=0; //Point to DummyFunction
if(m_pVideoProps)
{
m_pVideoProps->Release();
m_pVideoProps=NULL;
}
if(m_pWMWriter)
{
m_pWMWriter->Release();
m_pWMWriter=NULL;
}
if(m_pWMProfile)
{
m_pWMProfile->Release();
m_pWMProfile=NULL;
}
if(m_pWMProfileManager)
{
m_pWMProfileManager->Release();
m_pWMProfileManager=NULL;
}
if(m_hwmvDC)
{
DeleteDC(m_hwmvDC);
m_hwmvDC=NULL;
}
//std::cout << "Leaving ReleaseMemory" << std::endl;
//std::cout.flush();
}
void CwmvFile::SetErrorMessage(LPCTSTR lpszErrorMessage)
{
_tcsncpy(m_szErrMsg, lpszErrorMessage, __countof(m_szErrMsg)-1);
}
BSTR GetErrorMessage(_com_error e)
{
CComBSTR bstrMsg(_T(""));
TCHAR tmpStr[512];
_sntprintf(tmpStr, sizeof(tmpStr), _T("COM Error HRESULT 0x%X\n"), e.Error());
bstrMsg.Append(tmpStr);
_sntprintf(tmpStr, sizeof(tmpStr), _T("_com_error::ErrorMessage() = %s\n"), e.ErrorMessage());
bstrMsg.Append(tmpStr);
IErrorInfo *ptrIErrorInfo = e.ErrorInfo();
if (ptrIErrorInfo != NULL)
{
// IErrorInfo Interface located
_sntprintf(tmpStr, sizeof(tmpStr), _T("_com_error:escription() = %s\n"), (TCHAR *)e.Description());
bstrMsg.Append(tmpStr);
_sntprintf(tmpStr, sizeof(tmpStr), _T("\n_com_error::Source() = %s"), (TCHAR *)e.Source());
bstrMsg.Append(tmpStr);
}
else
{
bstrMsg.Append("No IErrorInfo Interface present\n");
}
// implicit BSTR cast operator used
return(bstrMsg);
}
HRESULT CwmvFile::InitMovieCreation(int nFrameWidth, int nFrameHeight, int nBitsPerPixel)
{
//std::cout << "Entering InitMovieCreation" << std::endl;
//std::cout.flush();
int nMaxWidth=GetSystemMetrics(SM_CXSCREEN), nMaxHeight=GetSystemMetrics(SM_CYSCREEN);
BITMAPINFO bmpInfo;
m_hwmvDC=CreateCompatibleDC(NULL);
if(m_hwmvDC==NULL)
{
SetErrorMessage(L"Unable to Create Device Context");
return E_FAIL;
}
ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biBitCount = nBitsPerPixel;
bmpInfo.bmiHeader.biWidth = nFrameWidth;
bmpInfo.bmiHeader.biHeight = nFrameHeight;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biSizeImage = nFrameWidth*nFrameHeight*nBitsPerPixel/8;
bmpInfo.bmiHeader.biCompression = BI_RGB;
if(bmpInfo.bmiHeader.biHeight>nMaxHeight) nMaxHeight=bmpInfo.bmiHeader.biHeight;
if(bmpInfo.bmiHeader.biWidth>nMaxWidth) nMaxWidth=bmpInfo.bmiHeader.biWidth;
WMVIDEOINFOHEADER videoInfo;
videoInfo.rcSource.left = 0;
videoInfo.rcSource.top = 0;
videoInfo.rcSource.right = bmpInfo.bmiHeader.biWidth;
videoInfo.rcSource.bottom = bmpInfo.bmiHeader.biHeight;
videoInfo.rcTarget = videoInfo.rcSource;
videoInfo.rcTarget.right = videoInfo.rcSource.right;
videoInfo.rcTarget.bottom = videoInfo.rcSource.bottom;
videoInfo.dwBitRate= (nMaxWidth*nMaxHeight*bmpInfo.bmiHeader.biBitCount* m_dwFrameRate);
videoInfo.dwBitErrorRate = 0;
//videoInfo.AvgTimePerFrame = ((QWORD)1) * 10000 * 1000 / m_dwFrameRate;
videoInfo.AvgTimePerFrame = ((QWORD)1) / m_dwFrameRate;
memcpy(&(videoInfo.bmiHeader),&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER));
WM_MEDIA_TYPE mt;
mt.majortype = WMMEDIATYPE_Video;
if( bmpInfo.bmiHeader.biCompression == BI_RGB )
{
if( bmpInfo.bmiHeader.biBitCount == 32 )
{
mt.subtype = WMMEDIASUBTYPE_RGB32;
}
else if( bmpInfo.bmiHeader.biBitCount == 24 )
{
mt.subtype = WMMEDIASUBTYPE_RGB24;
}
else if( bmpInfo.bmiHeader.biBitCount == 16 )
{
mt.subtype = WMMEDIASUBTYPE_RGB555;
}
else if( bmpInfo.bmiHeader.biBitCount == 8 )
{
mt.subtype = WMMEDIASUBTYPE_RGB8;
}
else
{
mt.subtype = GUID_NULL;
}
}
mt.bFixedSizeSamples = false;
mt.bTemporalCompression = false;
mt.lSampleSize = 0;
mt.formattype = WMFORMAT_VideoInfo;
mt.pUnk = NULL;
mt.cbFormat = sizeof(WMVIDEOINFOHEADER);
mt.pbFormat = (BYTE*)&videoInfo;
if(FAILED(m_pVideoProps->SetMediaType(&mt)))
{
SetErrorMessage(L"Unable to Set Media Type");
return E_FAIL;
}
//if(FAILED(m_pWMWriter->SetInputProps(m_dwVideoInput,m_pVideoProps)))
HRESULT res = m_pWMWriter->SetInputProps(m_dwVideoInput,m_pVideoProps);
if (res != S_OK)
{
if (res == E_INVALIDARG)
{
return E_FAIL;
}
else if (res == E_OUTOFMEMORY)
{
return E_FAIL;
}
else if (res == E_UNEXPECTED)
{
return E_FAIL;
}
GetErrorMessage(_com_error(res));
SetErrorMessage(L"Unable to Set Input Properties for Media Writer");
return E_FAIL;
}
//if(FAILED(m_pWMWriter->BeginWriting()))
HRESULT res2 = m_pWMWriter->BeginWriting();
if (res2 != S_OK)
{
if (res == E_OUTOFMEMORY)
{
return E_FAIL;
}
else if (res == E_UNEXPECTED)
{
return E_FAIL;
}
else if (res == NS_E_AUDIO_CODEC_ERROR)
{
return E_FAIL;
}
else if (res == NS_E_AUDIO_CODEC_NOT_INSTALLED)
{
return E_FAIL;
}
else if (res == NS_E_DRM_RIV_TOO_SMALL)
{
return E_FAIL;
}
else if (res == NS_E_INVALID_OUTPUT_FORMAT)
{
return E_FAIL;
}
else if (res == NS_E_VIDEO_CODEC_ERROR)
{
return E_FAIL;
}
else if (res == NS_E_VIDEO_CODEC_NOT_INSTALLED)
{
return E_FAIL;
}
GetErrorMessage(_com_error(res2));
SetErrorMessage(L"Unable to Initialize Writing");
return E_FAIL;
}
//std::cout << "Leaving InitMovieCreation" << std::endl;
//std::cout.flush();
return S_OK;
}
HRESULT CwmvFile::AppendFrameFirstTime(HBITMAP hBitmap)
{
//std::cout << "Entering AppendFrameFirstTime" << std::endl;
//std::cout.flush();
BITMAP Bitmap;
GetObject(hBitmap, sizeof(BITMAP), &Bitmap);
if(SUCCEEDED(InitMovieCreation( Bitmap.bmWidth,
Bitmap.bmHeight,
Bitmap.bmBitsPixel)))
{
m_nAppendFuncSelector=2; //Point to UsualAppend Function
return AppendFrameUsual(hBitmap);
}
//Control Comes here Only if there is Any Error
ReleaseMemory();
//std::cout << "Leaving AppendFrameFirstTime, after ReleaseMemory" << std::endl;
//std::cout.flush();
return E_FAIL;
}
HRESULT CwmvFile::AppendFrameUsual(HBITMAP hBitmap)
{
return NULL;
//std::cout << "Entering AppendFrameUsual" << std::endl;
//std::cout.flush();
HRESULT hr=E_FAIL;
INSSBuffer *pSample=NULL;
BYTE *pbBuffer=NULL;
DWORD cbBuffer=0;
BITMAPINFO bmpInfo;
bmpInfo.bmiHeader.biBitCount=0;
bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
GetDIBits(m_hwmvDC,hBitmap,0,0,NULL,&bmpInfo,DIB_RGB_COLORS);
bmpInfo.bmiHeader.biCompression=BI_RGB;
if(FAILED(m_pWMWriter->AllocateSample(bmpInfo.bmiHeader.biSizeImage,&pSample)))
{
SetErrorMessage(L"Unable to Allocate Memory");
goto TerminateAppendWMVFrameUsual;
}
if(FAILED(pSample->GetBufferAndLength(&pbBuffer,&cbBuffer)))
{
SetErrorMessage(L"Unable to Lock Buffer");
goto TerminateAppendWMVFrameUsual;
}
GetDIBits(m_hwmvDC,hBitmap,0,bmpInfo.bmiHeader.biHeight,(void*)pbBuffer,&bmpInfo,DIB_RGB_COLORS);
hr=m_pWMWriter->WriteSample(m_dwVideoInput,10000 * m_msVideoTime,0,pSample);
m_msVideoTime=(++m_dwCurrentVideoSample*1000)/m_dwFrameRate;
if(pSample) { pSample->Release(); pSample=NULL; }
if(FAILED(hr))
{
SetErrorMessage(L"Unable to Write Frame");
goto TerminateAppendWMVFrameUsual;
}
return S_OK;
TerminateAppendWMVFrameUsual:
if(pSample) { pSample->Release(); pSample=NULL; }
ReleaseMemory();
return E_FAIL;
}
HRESULT CwmvFile::AppendDummy(HBITMAP)
{
return E_FAIL;
}
HRESULT CwmvFile::AppendNewFrame(HBITMAP hBitmap)
{
return (this->*pAppendFrame[m_nAppendFuncSelector])(hBitmap);
}
HRESULT CwmvFile::AppendNewFrame(int nWidth, int nHeight, LPVOID pBits,int nBitsPerPixel)
{
return (this->*pAppendFrameBits[m_nAppendFuncSelector])(nWidth,nHeight,pBits,nBitsPerPixel);
}
HRESULT CwmvFile::AppendFrameFirstTime(int nWidth, int nHeight, LPVOID pBits,int nBitsPerPixel)
{
if(SUCCEEDED(InitMovieCreation(nWidth, nHeight, nBitsPerPixel)))
{
m_nAppendFuncSelector=2; //Point to UsualAppend Function
return AppendFrameUsual(nWidth,nHeight,pBits,nBitsPerPixel);
}
// Control Comes here Only if there is Any Error
ReleaseMemory();
return E_FAIL;
}
HRESULT CwmvFile::AppendFrameUsual(int nWidth, int nHeight, LPVOID pBits,int nBitsPerPixel)
{
//std::cout << "Entering AppendFrameUsual v2" << std::endl;
//std::cout.flush();
HRESULT hr=E_FAIL;
INSSBuffer *pSample=NULL;
BYTE *pbBuffer=NULL;
DWORD cbBuffer=0;
BITMAPINFO bmpInfo;
ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biBitCount=nBitsPerPixel;
bmpInfo.bmiHeader.biWidth=nWidth;
bmpInfo.bmiHeader.biHeight=nHeight;
bmpInfo.bmiHeader.biCompression=BI_RGB;
bmpInfo.bmiHeader.biPlanes=1;
bmpInfo.bmiHeader.biSizeImage=nWidth*nHeight*nBitsPerPixel/8;
if(FAILED(m_pWMWriter->AllocateSample(bmpInfo.bmiHeader.biSizeImage,&pSample)))
{
SetErrorMessage(L"Unable to Allocate Memory");
goto TerminateAppendWMVFrameUsualBits;
}
if(FAILED(pSample->GetBufferAndLength(&pbBuffer,&cbBuffer)))
{
SetErrorMessage(L"Unable to Lock Buffer");
goto TerminateAppendWMVFrameUsualBits;
}
memcpy(pbBuffer,pBits,bmpInfo.bmiHeader.biSizeImage);
DWORD writeSampleFlags = 0;
if ((totalFramesWritten % keyFrameEveryNFrames) == 0)
{
writeSampleFlags = WM_SF_CLEANPOINT;
}
hr=m_pWMWriter->WriteSample(m_dwVideoInput, 100 * m_msVideoTime, writeSampleFlags, pSample);
totalFramesWritten++;
m_msVideoTime=(++m_dwCurrentVideoSample*1000)/m_dwFrameRate;
if(pSample) { pSample->Release(); pSample=NULL; }
if(FAILED(hr))
{
SetErrorMessage(L"Unable to Write Frame");
goto TerminateAppendWMVFrameUsualBits;
}
return S_OK;
TerminateAppendWMVFrameUsualBits:
if(pSample) { pSample->Release(); pSample=NULL; }
ReleaseMemory();
return E_FAIL;
}
HRESULT CwmvFile::AppendDummy(int nWidth, int nHeight, LPVOID pBits,int nBitsPerPixel)
{
return E_FAIL;
}
}
}
}
}
}
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
const int maxn = 1e7 + 10;
int f[maxn],num[maxn];
stack<int> S;
int find(int k) {
while (f[k] != -1) {
S.push(k);
k = f[k];
}
while (!S.empty()) {
int p = S.top();S.pop();
f[p] = k;
}
return k;
}
int main() {
int n,a,b;
while (scanf("%d",&n) != EOF) {
memset(f,-1,sizeof(f));
memset(num,0,sizeof(num));
int ans = 0;
for (int i = 1;i <= n; i++) {
scanf("%d %d",&a,&b);
a = find(a);b = find(b);
//cout << a << ":" << b << endl;
if (a != b) {f[a] = b;num[b] += num[a]+1;ans = max(ans,num[b]);}
}
printf("%d\n",ans+1);
}
return 0;
}
|
Scalar const c0 = pow(omega[0], 2);
Scalar const c1 = pow(omega[1], 2);
Scalar const c2 = pow(omega[2], 2);
Scalar const c3 = c0 + c1 + c2;
Scalar const c4 = sqrt(c3);
Scalar const c5 = 1.0/c4;
Scalar const c6 = 0.5*c4;
Scalar const c7 = sin(c6);
Scalar const c8 = c5*c7;
Scalar const c9 = pow(c3, -3.0L/2.0L);
Scalar const c10 = c7*c9;
Scalar const c11 = 1.0/c3;
Scalar const c12 = cos(c6);
Scalar const c13 = 0.5*c11*c12;
Scalar const c14 = c7*c9*omega[0];
Scalar const c15 = 0.5*c11*c12*omega[0];
Scalar const c16 = -c14*omega[1] + c15*omega[1];
Scalar const c17 = -c14*omega[2] + c15*omega[2];
Scalar const c18 = omega[1]*omega[2];
Scalar const c19 = -c10*c18 + c13*c18;
Scalar const c20 = c5*omega[0];
Scalar const c21 = 0.5*c7;
Scalar const c22 = c5*omega[1];
Scalar const c23 = c5*omega[2];
Scalar const c24 = -c1;
Scalar const c25 = -c2;
Scalar const c26 = c24 + c25;
Scalar const c27 = sin(c4);
Scalar const c28 = -c27 + c4;
Scalar const c29 = c28*c9;
Scalar const c30 = cos(c4);
Scalar const c31 = -c30 + 1;
Scalar const c32 = c11*c31;
Scalar const c33 = c32*omega[2];
Scalar const c34 = c29*omega[0];
Scalar const c35 = c34*omega[1];
Scalar const c36 = c32*omega[1];
Scalar const c37 = c34*omega[2];
Scalar const c38 = pow(c3, -5.0L/2.0L);
Scalar const c39 = 3*c28*c38*omega[0];
Scalar const c40 = c26*c9;
Scalar const c41 = -c20*c30 + c20;
Scalar const c42 = c27*c9*omega[0];
Scalar const c43 = c42*omega[1];
Scalar const c44 = pow(c3, -2);
Scalar const c45 = 2*c31*c44*omega[0];
Scalar const c46 = c45*omega[1];
Scalar const c47 = c29*omega[2];
Scalar const c48 = c43 - c46 + c47;
Scalar const c49 = 3*c0*c28*c38;
Scalar const c50 = c9*omega[0]*omega[2];
Scalar const c51 = c41*c50 - c49*omega[2];
Scalar const c52 = c9*omega[0]*omega[1];
Scalar const c53 = c41*c52 - c49*omega[1];
Scalar const c54 = c42*omega[2];
Scalar const c55 = c45*omega[2];
Scalar const c56 = c29*omega[1];
Scalar const c57 = -c54 + c55 + c56;
Scalar const c58 = -2*c56;
Scalar const c59 = 3*c28*c38*omega[1];
Scalar const c60 = -c22*c30 + c22;
Scalar const c61 = -c18*c39;
Scalar const c62 = c32 + c61;
Scalar const c63 = c27*c9;
Scalar const c64 = c1*c63;
Scalar const c65 = 2*c31*c44;
Scalar const c66 = c1*c65;
Scalar const c67 = c50*c60;
Scalar const c68 = -c1*c39 + c52*c60;
Scalar const c69 = c18*c63;
Scalar const c70 = c18*c65;
Scalar const c71 = c34 - c69 + c70;
Scalar const c72 = -2*c47;
Scalar const c73 = 3*c28*c38*omega[2];
Scalar const c74 = -c23*c30 + c23;
Scalar const c75 = -c32 + c61;
Scalar const c76 = c2*c63;
Scalar const c77 = c2*c65;
Scalar const c78 = c52*c74;
Scalar const c79 = c34 + c69 - c70;
Scalar const c80 = -c2*c39 + c50*c74;
Scalar const c81 = -c0;
Scalar const c82 = c25 + c81;
Scalar const c83 = c32*omega[0];
Scalar const c84 = c18*c29;
Scalar const c85 = -2*c34;
Scalar const c86 = c82*c9;
Scalar const c87 = c0*c63;
Scalar const c88 = c0*c65;
Scalar const c89 = c9*omega[1]*omega[2];
Scalar const c90 = c41*c89;
Scalar const c91 = c54 - c55 + c56;
Scalar const c92 = -c1*c73 + c60*c89;
Scalar const c93 = -c43 + c46 + c47;
Scalar const c94 = -c2*c59 + c74*c89;
Scalar const c95 = c24 + c81;
Scalar const c96 = c9*c95;
result[0] = 0;
result[1] = 0;
result[2] = 0;
result[3] = -c0*c10 + c0*c13 + c8;
result[4] = c16;
result[5] = c17;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = c16;
result[10] = -c1*c10 + c1*c13 + c8;
result[11] = c19;
result[12] = 0;
result[13] = 0;
result[14] = 0;
result[15] = c17;
result[16] = c19;
result[17] = -c10*c2 + c13*c2 + c8;
result[18] = 0;
result[19] = 0;
result[20] = 0;
result[21] = -c20*c21;
result[22] = -c21*c22;
result[23] = -c21*c23;
result[24] = c26*c29 + 1;
result[25] = -c33 + c35;
result[26] = c36 + c37;
result[27] = upsilon[0]*(-c26*c39 + c40*c41) + upsilon[1]*(c53 + c57) + upsilon[2]*(c48 + c51);
result[28] = upsilon[0]*(-c26*c59 + c40*c60 + c58) + upsilon[1]*(c68 + c71) + upsilon[2]*(c62 + c64 - c66 + c67);
result[29] = upsilon[0]*(-c26*c73 + c40*c74 + c72) + upsilon[1]*(c75 - c76 + c77 + c78) + upsilon[2]*(c79 + c80);
result[30] = c33 + c35;
result[31] = c29*c82 + 1;
result[32] = -c83 + c84;
result[33] = upsilon[0]*(c53 + c91) + upsilon[1]*(-c39*c82 + c41*c86 + c85) + upsilon[2]*(c75 - c87 + c88 + c90);
result[34] = upsilon[0]*(c68 + c79) + upsilon[1]*(-c59*c82 + c60*c86) + upsilon[2]*(c92 + c93);
result[35] = upsilon[0]*(c62 + c76 - c77 + c78) + upsilon[1]*(c72 - c73*c82 + c74*c86) + upsilon[2]*(c57 + c94);
result[36] = -c36 + c37;
result[37] = c83 + c84;
result[38] = c29*c95 + 1;
result[39] = upsilon[0]*(c51 + c93) + upsilon[1]*(c62 + c87 - c88 + c90) + upsilon[2]*(-c39*c95 + c41*c96 + c85);
result[40] = upsilon[0]*(-c64 + c66 + c67 + c75) + upsilon[1]*(c48 + c92) + upsilon[2]*(c58 - c59*c95 + c60*c96);
result[41] = upsilon[0]*(c71 + c80) + upsilon[1]*(c91 + c94) + upsilon[2]*(-c73*c95 + c74*c96);
|
#pragma once
#include <vector>
#include <QObject>
#include "FileWorkspaceViewModel.h"
#include "SpeechTranscriptionViewModel.h"
#include "SharedServiceProvider.h"
#include "VisualNotificationService.h"
#include "JuliusRecognizerProvider.h"
#include "SpeechDataValidation.h"
namespace PticaGovorun
{
class AnnotationToolViewModel : public QObject
#ifdef PG_HAS_JULIUS
, public RecognizerNameHintProvider // represents the Julius recognizer name to
#endif
{
private:
Q_OBJECT
public:
signals:
void addedAudioTranscription(const boost::filesystem::path& filePath);
void activeAudioTranscriptionChanged(int ind);
void audioTranscriptionRemoved(int tabIndex);
void audioTranscriptionListCleared();
// Notifies view to ask a user to set the new speech annotation directory.
QString newAnnotDirQuery();
// commands
void commandsListChanged();
public:
AnnotationToolViewModel();
~AnnotationToolViewModel();
void init(std::shared_ptr<SharedServiceProvider> serviceProvider);
void onClose();
void closeAudioTranscriptionTab(int tabIndex);
bool tryChangeSpeechProjDir(const boost::filesystem::path& speechProjDir);
// Declares a user intent to open new speech annotation directory.
void openAnnotDirRequest();
// Declares a user intent to close new speech annotation directory.
void closeAnnotDirRequest();
void load();
// UI state
void loadStateSettings();
void saveStateSettings();
void saveRequest();
// recognizer
boost::string_view recognizerName() const;
void setRecognizerName(boost::string_view recogName);
#ifdef PG_HAS_JULIUS
boost::string_view recognizerNameHint() override;
std::shared_ptr<JuliusRecognizerProvider> juliusRecognizerProvider();
#endif
std::shared_ptr<SpeechTranscriptionViewModel> activeTranscriptionModel();
std::shared_ptr<SpeechTranscriptionViewModel> audioTranscriptionModelByAnnotFilePathAbs(const boost::filesystem::path& filePath);
std::shared_ptr<FileWorkspaceViewModel> fileWorkspaceModel();
void validateAllSpeechAnnotationRequest();
std::shared_ptr<PhoneticDictionaryViewModel> phoneticDictModel();
public:
// play
void playComposingRecipeRequest(boost::string_view recipe);
bool processCommandList(boost::string_view recipe);
void setCommandList(boost::string_view commandsList, bool updateView = true);
boost::string_view commandList() const;
private:
std::string commandList_;
public:
// navigate
void navigateToMarkerRequest();
public:
// Occurs when phonetic dialog closes and phonetic expansion of current marker's text must be updated.
void onPronIdPhoneticSpecChanged();
/// Checks whether speech working dir is opened.
bool isSpeechProjectOpened() const;
private slots:
// file workspace
void fileWorkspaceViewModel_openAnnotFile(const boost::filesystem::path& annotFilePath);
private:
void nextNotification(const QString& message) const;
private:
std::shared_ptr<SharedServiceProvider> serviceProvider_;
std::shared_ptr<VisualNotificationService> notificationService_;
std::shared_ptr<FileWorkspaceViewModel> fileWorkspaceViewModel_;
std::shared_ptr<AudioMarkupNavigator> audioMarkupNavigator_;
std::shared_ptr<PhoneticDictionaryViewModel> phoneticDictModel_;
std::vector<std::shared_ptr<SpeechTranscriptionViewModel>> audioTranscriptionModels_;
int activeAudioTranscriptionModelInd_ = -1;
std::shared_ptr<SpeechData> speechData_;
std::shared_ptr<PhoneRegistry> phoneReg_;
// recognition
std::string curRecognizerName_;
#ifdef PG_HAS_JULIUS
std::shared_ptr<JuliusRecognizerProvider> juliusRecognizerProvider_;
#endif
};
}
|
#pragma once
#include <glad/glad.h>
#include <string>
#include <glm/glm.hpp>
class ShaderBase
{
public:
virtual ~ShaderBase();
void Start();
void End();
void Set(const char* varName, bool value);
void Set(const char* varName, int value);
void Set(const char* varName, float value);
void Set(const char* varName, const glm::vec2 &value);
void Set(const char* varName, float x, float y);
void Set(const char* varName, const glm::vec3 &value);
void Set(const char* varName, float x, float y, float z);
void Set(const char* varName, const glm::vec4 &value);
void Set(const char* varName, float x, float y, float z, float w);
void Set(const char* varName, const glm::mat2 &mat);
void Set(const char* varName, const glm::mat3 &mat);
void Set(const char* varName, const glm::mat4 &mat);
void Set(const char* varName, const glm::ivec2 &value);
void Set(const char* varName, const glm::ivec3 &value);
void Set(const char* varName, const glm::ivec4 &value);
protected:
GLuint _id;
};
|
// Copyright (c) 2007-2012 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config.hpp>
#include <pika/assert.hpp>
#include <pika/concurrency/spinlock.hpp>
#include <pika/functional/deferred_call.hpp>
#include <pika/functional/function.hpp>
#include <pika/functional/unique_function.hpp>
#include <pika/futures/future_fwd.hpp>
#include <pika/modules/errors.hpp>
#include <pika/threading_base/scheduler_base.hpp>
#include <pika/threading_base/thread_data.hpp>
#include <pika/threading_base/thread_pool_base.hpp>
#include <pika/timing/steady_clock.hpp>
#include <fmt/format.h>
#include <cstddef>
#include <exception>
#include <functional>
#include <iosfwd>
#include <mutex>
#include <type_traits>
#include <utility>
#include <pika/config/warnings_prefix.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace pika {
///////////////////////////////////////////////////////////////////////////
using thread_termination_handler_type =
util::detail::function<void(std::exception_ptr const& e)>;
PIKA_EXPORT void set_thread_termination_handler(thread_termination_handler_type f);
class PIKA_EXPORT thread
{
using mutex_type = pika::concurrency::detail::spinlock;
void terminate(const char* function, const char* reason) const;
public:
class id;
using native_handle_type = threads::detail::thread_id_type;
thread() noexcept;
template <typename F,
typename Enable =
typename std::enable_if<!std::is_same<std::decay_t<F>, thread>::value>::type>
explicit thread(F&& f)
{
auto thrd_data = threads::detail::get_self_id_data();
PIKA_ASSERT(thrd_data);
start_thread(thrd_data->get_scheduler_base()->get_parent_pool(),
util::detail::deferred_call(PIKA_FORWARD(F, f)));
}
template <typename F, typename... Ts>
explicit thread(F&& f, Ts&&... vs)
{
auto thrd_data = threads::detail::get_self_id_data();
PIKA_ASSERT(thrd_data);
start_thread(thrd_data->get_scheduler_base()->get_parent_pool(),
util::detail::deferred_call(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, vs)...));
}
template <typename F>
thread(threads::detail::thread_pool_base* pool, F&& f)
{
start_thread(pool, util::detail::deferred_call(PIKA_FORWARD(F, f)));
}
template <typename F, typename... Ts>
thread(threads::detail::thread_pool_base* pool, F&& f, Ts&&... vs)
{
start_thread(
pool, util::detail::deferred_call(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, vs)...));
}
~thread();
public:
thread(thread&&) noexcept;
thread& operator=(thread&&) noexcept;
void swap(thread&) noexcept;
bool joinable() const noexcept
{
std::lock_guard<mutex_type> l(mtx_);
return joinable_locked();
}
void join();
void detach()
{
std::lock_guard<mutex_type> l(mtx_);
detach_locked();
}
id get_id() const noexcept;
native_handle_type native_handle() const //-V659
{
std::lock_guard<mutex_type> l(mtx_);
return id_.noref();
}
[[nodiscard]] static unsigned int hardware_concurrency() noexcept;
// extensions
void interrupt(bool flag = true);
bool interruption_requested() const;
static void interrupt(id, bool flag = true);
pika::future<void> get_future(error_code& ec = throws);
std::size_t get_thread_data() const;
std::size_t set_thread_data(std::size_t);
private:
bool joinable_locked() const noexcept { return threads::detail::invalid_thread_id != id_; }
void detach_locked() { id_ = threads::detail::invalid_thread_id; }
void start_thread(
threads::detail::thread_pool_base* pool, util::detail::unique_function<void()>&& func);
static threads::detail::thread_result_type thread_function_nullary(
util::detail::unique_function<void()> const& func);
mutable mutex_type mtx_;
threads::detail::thread_id_ref_type id_;
};
inline void swap(thread& x, thread& y) noexcept { x.swap(y); }
///////////////////////////////////////////////////////////////////////////
class thread::id
{
private:
threads::detail::thread_id_type id_;
friend bool operator==(thread::id const& x, thread::id const& y) noexcept;
friend bool operator!=(thread::id const& x, thread::id const& y) noexcept;
friend bool operator<(thread::id const& x, thread::id const& y) noexcept;
friend bool operator>(thread::id const& x, thread::id const& y) noexcept;
friend bool operator<=(thread::id const& x, thread::id const& y) noexcept;
friend bool operator>=(thread::id const& x, thread::id const& y) noexcept;
template <typename Char, typename Traits>
friend std::basic_ostream<Char, Traits>&
operator<<(std::basic_ostream<Char, Traits>&, thread::id const&);
friend class thread;
public:
id() noexcept = default;
explicit id(threads::detail::thread_id_type const& i) noexcept
: id_(i)
{
}
explicit id(threads::detail::thread_id_type&& i) noexcept
: id_(PIKA_MOVE(i))
{
}
explicit id(threads::detail::thread_id_ref_type const& i) noexcept
: id_(i.get().get())
{
}
explicit id(threads::detail::thread_id_ref_type&& i) noexcept
: id_(PIKA_MOVE(i).get().get())
{
}
threads::detail::thread_id_type const& native_handle() const { return id_; }
};
inline bool operator==(thread::id const& x, thread::id const& y) noexcept
{
return x.id_ == y.id_;
}
inline bool operator!=(thread::id const& x, thread::id const& y) noexcept { return !(x == y); }
inline bool operator<(thread::id const& x, thread::id const& y) noexcept
{
return x.id_ < y.id_;
}
inline bool operator>(thread::id const& x, thread::id const& y) noexcept { return y < x; }
inline bool operator<=(thread::id const& x, thread::id const& y) noexcept { return !(x > y); }
inline bool operator>=(thread::id const& x, thread::id const& y) noexcept { return !(x < y); }
template <typename Char, typename Traits>
std::basic_ostream<Char, Traits>&
operator<<(std::basic_ostream<Char, Traits>& out, thread::id const& id)
{
out << id.id_;
return out;
}
// template <class T> struct hash;
// template <> struct hash<thread::id>;
///////////////////////////////////////////////////////////////////////////
namespace this_thread {
PIKA_EXPORT thread::id get_id() noexcept;
PIKA_EXPORT void yield() noexcept;
PIKA_EXPORT void yield_to(thread::id) noexcept;
// extensions
PIKA_EXPORT execution::thread_priority get_priority();
PIKA_EXPORT std::ptrdiff_t get_stack_size();
PIKA_EXPORT void interruption_point();
PIKA_EXPORT bool interruption_enabled();
PIKA_EXPORT bool interruption_requested();
PIKA_EXPORT void interrupt();
PIKA_EXPORT void sleep_until(pika::chrono::steady_time_point const& abs_time);
inline void sleep_for(pika::chrono::steady_duration const& rel_time)
{
sleep_until(rel_time.from_now());
}
PIKA_EXPORT std::size_t get_thread_data();
PIKA_EXPORT std::size_t set_thread_data(std::size_t);
class PIKA_EXPORT disable_interruption
{
private:
disable_interruption(disable_interruption const&);
disable_interruption& operator=(disable_interruption const&);
bool interruption_was_enabled_;
friend class restore_interruption;
public:
disable_interruption();
~disable_interruption();
};
class PIKA_EXPORT restore_interruption
{
private:
restore_interruption(restore_interruption const&);
restore_interruption& operator=(restore_interruption const&);
bool interruption_was_enabled_;
public:
explicit restore_interruption(disable_interruption& d);
~restore_interruption();
};
} // namespace this_thread
} // namespace pika
template <>
struct fmt::formatter<pika::thread::id> : fmt::formatter<pika::threads::detail::thread_id>
{
template <typename FormatContext>
auto format(pika::thread::id const& id, FormatContext& ctx)
{
return fmt::formatter<pika::threads::detail::thread_id>::format(id.native_handle(), ctx);
}
};
namespace std {
// specialize std::hash for pika::thread::id
template <>
struct hash<::pika::thread::id>
{
std::size_t operator()(::pika::thread::id const& id) const
{
std::hash<::pika::threads::detail::thread_id_ref_type> hasher_;
return hasher_(id.native_handle());
}
};
} // namespace std
#include <pika/config/warnings_suffix.hpp>
|
/*
Exp no : 10
FTP Using TCP
S1330-R-Jayadeep
03/10/2016
*/
#include<iostream>
#include<sys/socket.h>
#include<netinet/in.h>
#include<cstring>
#include<unistd.h>
#include<fstream>
using namespace std;
#define port 9012
int main(int argc,char* argv[]){
int tcpSocket,nBytes;
struct sockaddr_in addr,cliAddr;
bool client = true;
bzero((char*) &addr,sizeof(addr));
if(argc==2)
client = false;
socklen_t addr_size,cliLen;
tcpSocket = socket(AF_INET,SOCK_STREAM,0);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
int newSockFd;
if(!client){
addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(tcpSocket,(struct sockaddr*) &addr,sizeof(addr));
cout<<"waiting for File"<<endl;
listen(tcpSocket,5);
addr_size = sizeof(addr);
newSockFd = accept(tcpSocket,(struct sockaddr*) &cliAddr,&cliLen);
if(newSockFd<0){
cout<<"Error on accept";
}
}else{
if(connect(tcpSocket,(struct sockaddr*)&addr,sizeof(addr))<0){
cout<<"Error on connecing";
return 0;
}
}
while(!client){
char* buffer;
int size;
if(read(newSockFd,&size,sizeof(size))<0){
cout<<"Error reading";
break;
}
cout<<"Receiving file of size : "<<size<<endl;
buffer = new char[size];
if(read(newSockFd,buffer,size)<0){
cout<<"Error reading";
break;
}
cout<<"File received"<<endl;
cout<<buffer<<endl;
cout<<"Enter file name to write : ";
string file;
cin>>file;
ofstream fout(file.c_str());
if(!fout)
cout<<"Unable to open file"<<endl;
fout.write(buffer,size);
cout<<"Written to "<<file<<endl;
}
while(client){
//client
char* buffer;
int size;
cout<<"Enter file name"<<endl;
string fileName;
cin>>fileName;
ifstream fin(fileName.c_str());
fin.seekg(0,ios::end);
size = fin.tellg();
fin.seekg(0,ios::beg);
buffer = new char[size];
fin.read(buffer,size);
if(write(tcpSocket,&size,sizeof(size))>=0)
cout<<"File Size : "<<size<<endl;
else
cout<<"Unable to send file metadata"<<endl;
if(write(tcpSocket,buffer,size)>=0)
cout<<"File Sent"<<endl;
else
cout<<"Unable to send file"<<endl;
}
return 0;
}
/**********************************OUTPUT***************************
Enter file name
1-fork.c
File Size : 660
File Sent
waiting for File
Receiving file of size : 660
File received
#include<stdio.h>
#include<sys/types.h>
void printDetails(){
printf("%d : process id is : %d\n",getpid(),getpid());
printf("%d : parent id is : %d\n",getpid(),getppid());
printf("%d : real user id is : %d\n",getpid(),getuid());
printf("%d : effective user id is : %d\n",getpid(),geteuid());
printf("%d : group id is : %d\n",getpid(),getgid());
printf("%d : effective group id is : %d\n",getpid(),getegid());
}
int main(){
pid_t pid = fork();
// printf("pid is : %d\n",pid);
if(pid>0){
printDetails();
printf("%d : child id is %d\n",getpid(),pid);
}else{
printDetails();
printf("%d : i am child of %d\n",getpid(),getppid());
}
return 0;
}
Enter file name to write : out.txt
Written to out.txt
*********************************************************************************************************************************/
Result
--------
Program is executed and output is verified
|
#include "quadrant.h"
#include "gamesettings.h"
#include <QPainter>
Quadrant::Quadrant()
{
int quadrantSize = GameSettings::instance()->getQuadrantSize();
image = QImage(":/images/star-background.png");
image = image.scaled(quadrantSize, quadrantSize, Qt::IgnoreAspectRatio);
}
QRectF Quadrant::boundingRect() const
{
int quadrantSize = GameSettings::instance()->getQuadrantSize();
return QRectF(0, 0, quadrantSize, quadrantSize);
}
void Quadrant::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setOpacity(0.9);
painter->drawImage(0, 0, image);
painter->setOpacity(1);
QPen bigPen(Qt::red, 5);
painter->setOpacity(0.5);
painter->setPen(bigPen);
painter->drawRect(boundingRect());
}
|
#include <iostream>
#include <string>
#include <cstdio>
#include <memory.h>
#include <string.h>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <climits>
typedef long long LL;
typedef long long ll;
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef unsigned uint;
typedef long double LD;
typedef long double ld;
const LD PI = 3.1415926535897932384626433832795;
template<typename T>
T sqr(const T& x) { return x * x; }
using namespace std;
bool good(const vector<int>& a) {
for (int i = 0; i < a.size(); ++i) if (a[i] != i) return false;
return true;
}
bool solve(vector<int>& a, vector< pair<int, int> >& ans) {
for (int i = 0; i + 4 < a.size(); ++i) {
for (int j = 0; j < a.size(); ++j) if (a[j] == i) {
int p = j;
while (i + 3 <= p) {
ans.push_back(make_pair(1, p - 3));
swap(a[p], a[p - 3]);
swap(a[p - 1], a[p - 2]);
p -= 3;
}
if (i + 1 == p) {
ans.push_back(make_pair(1, i));
swap(a[i], a[i + 3]);
swap(a[i + 2], a[i + 1]);
++p;
}
if (i + 2 == p) {
ans.push_back(make_pair(1, i + 1));
swap(a[i + 1], a[i + 4]);
swap(a[i + 3], a[i + 2]);
++p;
}
if (i + 3 == p) {
ans.push_back(make_pair(1, p - 3));
swap(a[p], a[p - 3]);
swap(a[p - 1], a[p - 2]);
p -= 3;
}
break;
}
}
if (good(a)) return true;
ans.push_back(make_pair(1, a.size() - 4));
swap(a[a.size() - 4], a[a.size() - 1]);
swap(a[a.size() - 3], a[a.size() - 2]);
if (good(a)) return true;
return false;
}
int main() {
// freopen(".in","r", stdin);
// freopen(".out","w", stdout);
int n;
while (cin >> n) {
n += n;
vector<int> a(n);
vector< pair<int, int> > ans;
for (int i = 0; i < n; ++i) {
cin >> a[i];
--a[i];
}
do {
if (solve(a, ans)) {
printf("%d\n", ans.size());
for (int j = 0; j < ans.size(); ++j) {
printf("%d %d\n", ans[j].first, ans[j].second + (ans[j].first == 1));
}
break;
}
for (int i = 0; i < 3; ++i) {
int x = (rand() % n) + 1;
ans.push_back(make_pair(2, x));
rotate(a.begin(), a.begin() + x, a.end());
if (good(a)) break;
}
for (int i = 0; i < 3; ++i) {
int x = rand() % n;
ans.push_back(make_pair(1, x));
swap(a[x], a[(x + 3) % n]);
swap(a[(x + 2) % n], a[(x + 1) % n]);
if (good(a)) break;
}
} while (true);
}
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-01.
//
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int x):data(x),left(NULL),right(NULL){}
};
void morrisIn(Node *root){
if(!root) return;
Node *node1 = root;
Node *node2 = NULL;
while(node1){
node2 = node1->left;
if(node2){
while(node2->right && node2->right != node1){
node2 = node2->right;
}
if(node2->right == NULL){
node2->right = node1;
node1 = node1->left;
continue;
}else{
node2->right = NULL;
}
}
cout<<node1->data<<" ";
node1 = node1->right;
}
cout<<endl;
}
void morrisPre(Node *root){
if(!root) return;
Node *node1 = root;
Node *node2 = NULL;
while(node1){
node2 = node1->left;
if(node2){
while(node2->right && node2->right != node1){
node2 = node2->right;
}
if(node2->right == NULL){
node2->right = node1;
cout<<node1->data<<" ";
node1 = node1->left;
continue;
}else{
node2->right = NULL;
}
}else{
cout<<node1->data<<" ";
}
node1 = node1->right;
}
cout<<endl;
}
int main(){
Node *node1 = new Node(1);
Node *node2 = new Node(2);
Node *node3 = new Node(3);
Node *node4 = new Node(4);
Node *node5 = new Node(5);
Node *node6 = new Node(6);
Node *node7 = new Node(7);
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = node5;
node3->left = node6;
node5->right = node7;
morrisPre(node1);
return 0;
}
|
#pragma once
#include "AL\al.h"
#include "AL\alc.h"
#include "AL\alut.h"
class Audio
{
private:
//Variabili
ALsizei size, freq;
ALenum format;
ALvoid *data;
ALboolean loop;
ALbyte *path[7];
public:
Audio(void);
~Audio(void);
//Procedure
void initAL();
void playAL(int musicValue);
void playAsStream(int musicValue);
void stopAL(int musicValue);
void pauseAL(int musicValue);
};
|
#include <iostream>
using namespace std;
int main()
{
int n,m,x,y;
cout<<"ÇëÊäÈën,m"<<endl;
cin>>n>>m;
x=(4*n-m)/2 , y=(m-2*n)/2;
if((4*n-m)%2==1 || (m-2*n)/2==1 || 4*n<m || m<2*n)
cout<<"ÎÞ½â";
else cout<<x<<y;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef SVG_DOM
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domsvg/domsvgdoc.h"
#include "modules/doc/frm_doc.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
DOM_SVGDocument::DOM_SVGDocument(DOM_DOMImplementation *implementation)
: DOM_Document(implementation, TRUE)
{
}
/* status */ OP_STATUS
DOM_SVGDocument::Make(DOM_SVGDocument *&document, DOM_DOMImplementation *implementation)
{
DOM_Runtime *runtime = implementation->GetRuntime();
return DOMSetObjectRuntime(document = OP_NEW(DOM_SVGDocument, (implementation)), runtime, runtime->GetPrototype(DOM_Runtime::SVGDOCUMENT_PROTOTYPE), "SVGDocument");
}
HTML_Element *
DOM_SVGDocument::GetElement(Markup::Type type)
{
HTML_Element *element = GetPlaceholderElement();
while (element)
if (element->IsMatchingType(type, NS_SVG))
break;
else
element = element->NextActual();
return element;
}
/* virtual */ ES_GetState
DOM_SVGDocument::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
#ifdef SVG_FULL_11
DOM_EnvironmentImpl *environment = GetEnvironment();
DOM_Runtime *runtime = environment->GetDOMRuntime();
FramesDocument *frames_doc = environment->GetFramesDocument();
#endif // SVG_FULL_11
switch(property_name)
{
#ifdef SVG_FULL_11
case OP_ATOM_title:
{
TempBuffer *buffer = GetEmptyTempBuf();
if (IsMainDocument())
if (FramesDocument *frames_doc = GetFramesDocument())
{
DOMSetString(value, frames_doc->Title(buffer));
return GET_SUCCESS;
}
if (HTML_Element *element = GetElement(Markup::SVGE_TITLE))
{
GET_FAILED_IF_ERROR(buffer->Expand(element->GetTextContentLength() + 1));
element->GetTextContent(buffer->GetStorage(), buffer->GetCapacity());
}
DOMSetString(value, buffer);
return GET_SUCCESS;
}
case OP_ATOM_referrer:
DOMSetString(value);
if (frames_doc)
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::ReferrerEnabled, GetHostName()))
{
URL ref_url = frames_doc->GetRefURL().url;
switch (ref_url.Type())
{
case URL_HTTPS:
if (!OriginCheck(ref_url, frames_doc->GetURL()))
break;
case URL_HTTP:
DOMSetString(value, ref_url.GetAttribute(URL::KUniName).CStr());
}
}
return GET_SUCCESS;
case OP_ATOM_domain:
if (value)
{
DOMSetString(value);
if (!runtime->GetMutableOrigin()->IsUniqueOrigin())
{
const uni_char *domain;
runtime->GetDomain(&domain, NULL, NULL);
DOMSetString(value, domain);
}
}
return GET_SUCCESS;
case OP_ATOM_URL:
if (value)
{
const uni_char *url;
if (frames_doc)
url = frames_doc->GetURL().GetAttribute(URL::KUniName_With_Fragment).CStr();
else
url = NULL;
DOMSetString(value, url);
}
return GET_SUCCESS;
case OP_ATOM_rootElement:
DOMSetElement(value, GetElement(Markup::SVGE_SVG));
return GET_SUCCESS;
#endif // SVG_FULL_11
}
return DOM_Document::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_SVGDocument::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch(property_name)
{
#ifdef SVG_FULL_11
case OP_ATOM_title:
case OP_ATOM_domain:
case OP_ATOM_referrer:
case OP_ATOM_URL:
case OP_ATOM_rootElement:
return PUT_READ_ONLY;
#endif // SVG_FULL_11
}
return DOM_Document::PutName(property_name, value, origining_runtime);
}
#endif // SVG_DOM
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/parser/svglengthparser.h"
#include "modules/svg/src/SVGVector.h"
#include "modules/svg/src/SVGFontSize.h"
OP_STATUS
SVGLengthParser::ParseLength(const uni_char *input, unsigned input_length,
SVGLengthObject *&length_object)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
if (!ScanLength(length_object))
status = OpStatus::ERR;
return tokenizer.ReturnStatus(status);
}
OP_STATUS
SVGLengthParser::ParseLengthList(const uni_char *input, unsigned input_length,
SVGVector &vector)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
SVGLengthObject* length_object;
while(ScanLength(length_object) && OpStatus::IsSuccess(status))
{
status = vector.Append(length_object);
if(OpStatus::IsError(status))
OP_DELETE(length_object);
tokenizer.EatWspSeparatorWsp(',');
}
return OpStatus::OK;
}
BOOL
SVGLengthParser::ScanLength(SVGLengthObject *&length_object)
{
tokenizer.EatWsp();
if (tokenizer.IsEnd())
return FALSE;
SVGLength length;
if (ScanLength(length))
{
length_object = OP_NEW(SVGLengthObject, ());
if (length_object)
{
length_object->GetLength() = length;
return TRUE;
}
status = OpStatus::ERR_NO_MEMORY;
}
return FALSE;
}
BOOL
SVGLengthParser::ScanLength(SVGLength &length)
{
double d;
if (tokenizer.ScanNumber(d))
{
int unit = CSS_NUMBER;
if (tokenizer.Scan("em"))
unit = CSS_EM;
else if (tokenizer.Scan("rem"))
unit = CSS_REM;
else if (tokenizer.Scan("ex"))
unit = CSS_EX;
else if(tokenizer.Scan('%'))
unit = CSS_PERCENTAGE;
else if(tokenizer.Scan("pt"))
unit = CSS_PT;
else if(tokenizer.Scan("px"))
unit = CSS_PX;
else if(tokenizer.Scan("pc"))
unit = CSS_PC;
else if(tokenizer.Scan("cm"))
unit = CSS_CM;
else if(tokenizer.Scan("mm"))
unit = CSS_MM;
else if(tokenizer.Scan("in"))
unit = CSS_IN;
length.SetUnit(unit);
length.SetScalar(d);
return TRUE;
}
else
{
return FALSE;
}
}
OP_STATUS
SVGLengthParser::ParseBaselineShift(const uni_char *input, unsigned input_length, SVGBaselineShiftObject *&bls_object)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
SVGLength length;
SVGBaselineShift::BaselineShiftType bls_type = SVGBaselineShift::SVGBASELINESHIFT_BASELINE; // dummy value, warningfix
if (tokenizer.Scan("baseline"))
{
bls_type = SVGBaselineShift::SVGBASELINESHIFT_BASELINE;
}
else if (tokenizer.Scan("sub"))
{
bls_type = SVGBaselineShift::SVGBASELINESHIFT_SUB;
}
else if (tokenizer.Scan("super"))
{
bls_type = SVGBaselineShift::SVGBASELINESHIFT_SUPER;
}
else if (ScanLength(length))
{
bls_type = SVGBaselineShift::SVGBASELINESHIFT_VALUE;
}
else
{
status = OpStatus::ERR;
}
if (OpStatus::IsSuccess(status))
{
bls_object = OP_NEW(SVGBaselineShiftObject, (bls_type));
if (!bls_object)
status = OpStatus::ERR_NO_MEMORY;
else if (bls_type == SVGBaselineShift::SVGBASELINESHIFT_VALUE)
bls_object->GetBaselineShift().GetValueRef() = length;
}
return tokenizer.ReturnStatus(status);
}
OP_STATUS
SVGLengthParser::ParseFontsize(const uni_char *input, unsigned input_length,
SVGFontSizeObject *&fontsize_object)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
SVGAbsoluteFontSize abs_fontsize = SVGABSOLUTEFONTSIZE_MEDIUM;
SVGRelativeFontSize rel_fontsize = SVGRELATIVEFONTSIZE_SMALLER;
SVGLength length;
SVGFontSize::FontSizeMode fontsize_mode = SVGFontSize::MODE_UNKNOWN;
if (tokenizer.Scan("smaller"))
{
rel_fontsize = SVGRELATIVEFONTSIZE_SMALLER;
fontsize_mode = SVGFontSize::MODE_RELATIVE;
}
else if (tokenizer.Scan("larger"))
{
rel_fontsize = SVGRELATIVEFONTSIZE_LARGER;
fontsize_mode = SVGFontSize::MODE_RELATIVE;
}
else if (tokenizer.Scan("xx-small"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_XXSMALL;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("x-small"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_XSMALL;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("small"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_SMALL;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("medium"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_MEDIUM;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("large"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_LARGE;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("x-large"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_XLARGE;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else if (tokenizer.Scan("xx-large"))
{
abs_fontsize = SVGABSOLUTEFONTSIZE_XXLARGE;
fontsize_mode = SVGFontSize::MODE_ABSOLUTE;
}
else
{
if (ScanLength(length))
{
fontsize_mode = SVGFontSize::MODE_LENGTH;
}
else
{
status = OpStatus::ERR;
}
}
if (OpStatus::IsSuccess(status))
{
fontsize_object = OP_NEW(SVGFontSizeObject, ());
if (!fontsize_object)
status = OpStatus::ERR_NO_MEMORY;
else if (fontsize_mode == SVGFontSize::MODE_LENGTH)
status = fontsize_object->font_size.SetLength(length);
else if (fontsize_mode == SVGFontSize::MODE_ABSOLUTE)
fontsize_object->font_size.SetAbsoluteFontSize(abs_fontsize);
else if (fontsize_mode == SVGFontSize::MODE_RELATIVE)
fontsize_object->font_size.SetRelativeFontSize(rel_fontsize);
#ifdef _DEBUG
else
OP_ASSERT(!"Not reached");
#endif // _DEBUG
}
return tokenizer.ReturnStatus(status);
}
OP_STATUS
SVGLengthParser::ParseCoordinatePair(const uni_char *input, unsigned input_length,
SVGLength &coordinate_x, SVGLength &coordinate_y)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
ScanCoordinatePair(coordinate_x, coordinate_y);
return tokenizer.ReturnStatus(status);
}
void
SVGLengthParser::ScanCoordinatePair(SVGLength &coordinate_x, SVGLength &coordinate_y)
{
tokenizer.EatWsp();
if (tokenizer.IsEnd())
{
status = OpStatus::ERR;
return;
}
BOOL l1b = ScanLength(coordinate_x);
tokenizer.EatWspSeparatorWsp(',');
BOOL l2b = ScanLength(coordinate_y);
tokenizer.EatWsp();
if (!l1b || !l2b)
{
status = OpStatus::ERR;
}
}
OP_STATUS
SVGLengthParser::ParseClipShape(const uni_char *input, unsigned input_length,
SVGRectObject*& shape)
{
status = OpStatus::OK;
tokenizer.Reset(input, input_length);
if (tokenizer.Scan("auto"))
{
shape = OP_NEW(SVGRectObject, ());
if (!shape)
return OpStatus::ERR_NO_MEMORY;
}
else if (tokenizer.Scan("rect("))
{
int i = 0;
SVGLength lengths[4]; // This is the order from CSS2.1: top, right, bottom, left
for (;i<4;i++)
{
if (ScanLength(lengths[i]))
{
/* empty */
}
else if (tokenizer.Scan("auto"))
{
lengths[i] = SVGLength(); // Zero length
}
else
{
break;
}
tokenizer.EatWspSeparatorWsp(',');
}
if (i == 4)
{
// Ignores unit, we have no datatype for a rectangle of
// lengths.
shape = OP_NEW(SVGRectObject, (SVGRect(lengths[0].GetScalar(),
lengths[1].GetScalar(),
lengths[2].GetScalar(),
lengths[3].GetScalar())));
if (!shape)
return OpStatus::ERR_NO_MEMORY;
if (!tokenizer.Scan(')'))
status = OpSVGStatus::ATTRIBUTE_ERROR;
}
else
{
return OpSVGStatus::ATTRIBUTE_ERROR;
}
}
else
{
return OpSVGStatus::ATTRIBUTE_ERROR;
}
return OpStatus::OK;
}
#endif // SVG_SUPPORT
|
#define T1 160
#define T2 120
#define debug false
#define MAIN_LED_PIN 5
#define BLUE_LED_PIN 4
volatile boolean mainLed = false;
volatile boolean blueLed = false;
byte addressArray[10] = {3,4,5,6,7,8,11,12,13,14};
byte dataArray[10] = {4,154,43,166,244,34,82,136,42,128};
int count = 0; //counter for SN/GTIN send times
void setup()
{
pinMode(MAIN_LED_PIN,OUTPUT);
pinMode(BLUE_LED_PIN,OUTPUT);
attachInterrupt(0,pin2ISR,RISING); //attach ISR on pin 2
attachInterrupt(1,pin3ISR,RISING); //attach ISR on pin 3
Serial.begin(9600);
Serial.println("--Start--");
}
void loop()
{
//digitalWrite(8,HIGH);
//pin2ReadNew = digitalRead(SWITCHPIN1);
/*if((pin2ReadNew==1) && (pin2ReadNew != pin2ReadOld))
{
switch1Flag = !switch1Flag;
count = 0;
}
pin2ReadOld = pin2ReadNew;*/
//if(debug) Serial.println(pin2ReadNew);
//if(debug) Serial.println();
//Serial.println(ledFlag);
if(true)
{
for(int i=0; i<10;i++)
{
//Serial.println(micros());
//if(debug) Serial.println();
if(true){
startBits(MAIN_LED_PIN);
sendBit(MAIN_LED_PIN,addressArray[i]);
sendBit(MAIN_LED_PIN,dataArray[i]);
}
/*if(blueLed){
startBits(BLUE_LED_PIN);
sendBit(BLUE_LED_PIN,addressArray[i]);
sendBit(BLUE_LED_PIN,dataArray[i]);
}*/
//Serial.println(micros());
digitalWrite(MAIN_LED_PIN,LOW);
digitalWrite(BLUE_LED_PIN,LOW);
//remove flicker
for(int i=0; i<225;i++)
{
digitalWrite(MAIN_LED_PIN,LOW);
delayMicroseconds(292);
digitalWrite(MAIN_LED_PIN,HIGH);
delayMicroseconds(108);
}
//delay(92);
}
//delay(92);
count ++;
}
}
void sendBit(int pin,byte data)
{
//send each data bits
for(int i=7; i>=0; i--)
{
if(bitRead(data,i))
{
if(debug) Serial.print("1");
if(debug) Serial.print(" ");
one(pin);
}
else {
if(debug) Serial.print("0");
if(debug) Serial.print(" ");
zero(pin);
}
}
}
void startBits(int pin)
{
zero(pin);
zero(pin);
}
void one(int pin)
{
space(pin);
mark(pin);
}
void zero(int pin)
{
mark(pin);
space(pin);
}
void mark(int pin)
{
for(int i=0; i<9;i++)
{
digitalWrite(pin,HIGH);
delayMicroseconds(5);
digitalWrite(pin,LOW);
delayMicroseconds(4);
}
}
void space(int pin)
{
digitalWrite(pin,LOW);
delayMicroseconds(T1);
}
void pin3ISR(){
mainLed = !mainLed;
count = 0;
if (debug) Serial.print("Main led status: ");
if (debug )Serial.println(mainLed);
}
void pin2ISR(){
blueLed = !blueLed;
count = 0;
if (debug) Serial.print("Blue led status: ");
if (debug) Serial.println(blueLed);
}
|
#ifndef _INTERPOLATION_
#define _INTERPOLATION_
#include <iostream>
#include <fstream>
#include "eigen/Eigen/Dense"
#include "BivariatePolynomial.h"
#include "inttypes.h"
using namespace Eigen;
class Interpolation
{
int d;
int k;
int deg;
MatrixXd A;
MatrixXd M;
MatrixXd ker;
double** P;
int rank;
public:
int getRank()
{
return rank;
}
int getK()
{
return k;
}
Interpolation(uint64_t, MatrixXd);
~Interpolation();
MatrixXd & ComputeM();
double entry(uint64_t, uint64_t, uint64_t);
int Check_k();
double powerOf(double, uint64_t);
BivariatePolynomial * find(std::ofstream &);
};
#endif
|
namespace exception {
class Lines : public Inherit3(HavePosition, Dummy, RefCounter)
{
private:
const float m_speed;
const int m_cycle;
std::deque<vector2> m_line;
vector2 m_pos;
vector2 m_direction;
size_t m_frame;
static float getRand()
{
static ist::Random s_rand(::time(0));
return float(s_rand.genReal());
}
public:
Lines(size_t length=50, float speed=5.0f, int cycle=320) :
m_speed(speed), m_cycle(cycle), m_frame(0)
{
m_frame = size_t(getRand()*20.0f);
m_direction = vector2(0.0f, 5.0f);
m_pos = vector2(0, 0);
m_line.resize(length, m_pos);
};
void update()
{
m_pos+=m_direction;
m_line.push_front(m_pos);
m_line.pop_back();
if(++m_frame==m_cycle) {
m_frame = 0;
m_pos = vector2(0, 0);
std::fill(m_line.begin(), m_line.end(), m_pos);
}
if(getRand() < 0.05f) {
float f = float(getRand());
if(f < 0.5f) {
m_direction = vector2(m_speed, 0.0f);
}
else {
m_direction = vector2(0.0f, m_speed);
}
}
}
void draw()
{
static std::vector<vector4> color;
int length = int(m_line.size());
color.clear();
float u = 1.0f/length;
for(int i=length; i>=0; --i) {
color.push_back(vector4(u*i, u*i, 1.0f, u*i));
}
glBegin(GL_LINE_STRIP);
for(int i=0; i<length; ++i) {
glColor4fv(color[i].v);
glVertex2fv(m_line[i].v);
}
glEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
};
typedef intrusive_ptr<Lines> line_ptr;
typedef std::vector<line_ptr> line_cont;
class BackgroundBase : public Inherit2(HavePosition, IEffect)
{
typedef Inherit2(HavePosition, IEffect) Super;
protected:
int m_fade;
float m_opa;
enum {
NONE,
FADEIN,
FADEOUT,
};
public:
BackgroundBase() : m_fade(NONE), m_opa(1.0f)
{
Register(this);
fadein();
}
BackgroundBase(Deserializer& s) : Super(s)
{
s >> m_fade >> m_opa;
}
void serialize(Serializer& s) const
{
Super::serialize(s);
s << m_fade << m_opa;
}
void fadeout() { m_fade=FADEOUT; }
void fadein() { m_fade=FADEIN; }
void setOpa(float v) { m_opa=v; }
bool isFadeout() { return m_fade==FADEOUT; }
bool isFadein() { return m_fade==FADEIN; }
float getOpa() { return m_opa; }
float getDrawPriority() { return 0.0f; }
void drawFadeEffect()
{
if(m_opa>=0.0f) {
glColor4f(0,0,0,m_opa);
DrawRect(vector2(640, 480), vector2(0,0));
glColor4f(1,1,1,1);
}
}
void onUpdate(UpdateMessage& m)
{
Super::onUpdate(m);
if(m_fade==FADEIN) {
m_opa-=(1.0f/60.0f);
if(m_opa<=0.0f) {
m_opa = 0;
m_fade = NONE;
}
}
else if(m_fade==FADEOUT) {
m_opa+=(1.0f/480.0f);
if(m_opa>=1.0f) {
SendDestroyMessage(0, this);
}
}
}
};
class Actor : public Optional
{
typedef Optional Super;
public:
Actor() {}
Actor(Deserializer& s) : Super(s) {}
};
class ScrolledActor : public Inherit2(HaveParent, Actor)
{
typedef Inherit2(HaveParent, Actor) Super;
public:
ScrolledActor() {}
ScrolledActor(Deserializer& s) : Super(s) {}
virtual void scroll()
{
vector4 pos = getRelativePosition();
pos+=getParentIMatrix()*GetGlobalScroll();
setPosition(pos);
}
void onUpdate(UpdateMessage& m)
{
Super::onUpdate(m);
scroll();
}
};
} // exception
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#if !defined OPBINARYLANGUAGEMANAGER_H && defined LOC_BINFILELANGMAN
#define OPBINARYLANGUAGEMANAGER_H
#include "modules/locale/oplanguagemanager.h"
class OpFileDescriptor;
// Inline readers if opposite-endian support is disabled.
#ifdef LOCALE_BINARY_ENDIAN
# define LOCALE_INLINE
#else
# define LOCALE_INLINE inline
#endif
/**
* Platform-independent binary file-based locale string manager.
*
* This class handles the locale strings used in the UI and elsewhere for
* Opera. This implementation of the OpLanguageManager reads from the
* supplied translation file. Platforms with special needs can re-implement
* the OpLanguageManager interface in a manner they see fit.
*
* @author Peter Krefting
*/
class OpBinaryFileLanguageManager : public OpLanguageManager
{
public:
OpBinaryFileLanguageManager();
virtual ~OpBinaryFileLanguageManager();
/** Load a translation into the language manager. The file to load must
* be set up before the call to this method. The file to be read has
* a binary format described in the module documentation for this
* module.
*
* Only to be called from LocaleModule::InitL().
*
* @param lngfile A pointer to the file to read.
*/
void LoadTranslationL(OpFileDescriptor *lngfile);
public:
// Inherited interfaces; see OpLanguageManager for descriptions
virtual const OpStringC GetLanguage()
{ return m_language; }
virtual unsigned int GetDatabaseVersionFromFileL()
{ return m_db; }
virtual OP_STATUS GetString(Str::LocaleString num, UniString &s);
virtual WritingDirection GetWritingDirection()
{ return LTR; /* FIXME: Need to update file format to support this flag. */ }
private:
static int entrycmp(const void *, const void *);
OpString m_language;
unsigned int m_db;
struct stringdb_s
{
int id;
UniString string;
};
stringdb_s *m_stringdb;
UINT32 m_number_of_strings;
LOCALE_INLINE static UINT32 ReadNative32L(OpFileDescriptor *);
LOCALE_INLINE static void ReadNativeStringL(OpFileDescriptor *, uni_char *, size_t);
#ifdef LOCALE_BINARY_ENDIAN
static UINT32 ReadOpposite32L(OpFileDescriptor *);
static void ReadOppositeStringL(OpFileDescriptor *, uni_char *, size_t);
#endif
};
#endif // OPBINARYLANGUAGEMANAGER_H && LOC_BINFILELANGMAN
|
#ifndef G_MATH_HPP
#define G_MATH_HPP
#include <xmmintrin.h>
#include <iostream>
#include <math.h>
#include <string>
#define SHUFFLE_PARAM(x, y, z, w) \
((x) | ((y) << 2) | ((z) << 4) | ((w) << 6))
#define _mm_replicate_x_ps(v) \
_mm_shuffle_ps((v), (v), _MM_SHUFFLE(0, 0, 0, 0))
#define _mm_replicate_y_ps(v) \
_mm_shuffle_ps((v), (v), _MM_SHUFFLE(1, 1, 1, 1))
#define _mm_replicate_z_ps(v) \
_mm_shuffle_ps((v), (v), _MM_SHUFFLE(2, 2, 2, 2))
#define _mm_replicate_w_ps(v) \
_mm_shuffle_ps((v), (v), _MM_SHUFFLE(3, 3, 3, 3))
namespace gmath {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// vec4
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class vec4 {
public:
float* data = nullptr;
vec4(const float& x = 0.0f, const float& y = 0.0f, const float& z = 0.0f, const float& w = 0.0f);
vec4(const __m128& data);
vec4(const vec4& other);
vec4(vec4&& other);
~vec4();
vec4& operator=(const vec4& other);
vec4& operator=(vec4&& other);
float& operator[](const uint32_t& i) const;
vec4 operator-() const;
float dot(const vec4& other) const;
float magnitude() const;
float magnitude2() const;
vec4 multiply(const vec4& other) const;
vec4 normalize() const;
std::string toString() const;
static float dot(const vec4& v1, const vec4& v2);
static vec4 multiply(const vec4& v1, const vec4& v2);
};
vec4 operator*(const vec4& v1, const vec4& v2);
vec4 operator*(const float& s, const vec4& v);
vec4 operator*(const vec4& v, const float& s);
vec4 operator/(const vec4& q, const float& s);
vec4 operator+(const vec4& v1, const vec4& v2);
vec4 operator-(const vec4& v1, const vec4& v2);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// mat
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class mat {
public:
// each entry is a column
vec4* data = nullptr;
mat(const vec4& c1 = vec4(1.0f), const vec4& c2 = vec4(0.0f, 1.0f), const vec4& c3 = vec4(0.0f, 0.0f, 1.0f), const vec4& c4 = vec4(0.0f, 0.0f, 0.0f, 1.0f));
mat(const mat& other);
mat(mat&& other);
~mat();
vec4& operator[](const uint32_t& i) const;
mat& operator=(const mat& other);
mat& operator=(mat&& other);
std::string toString() const;
static mat translate(const vec4& t);
static mat rotateX(const float& radians);
static mat rotateY(const float& radians);
static mat rotateZ(const float& radians);
static mat rotate(const vec4& a, const float& radians);
static mat transform(const vec4& a, const float& radians, const vec4& t);
};
vec4 operator*(const mat& m, const vec4& v);
mat operator*(const mat& m1, const mat& m2);
mat operator*(const float& s, const mat& m);
mat operator*(const mat& m, const float& s);
mat operator/(const mat& m, const float& s);
mat operator+(const mat& m1, const mat& m2);
mat operator-(const mat& m1, const mat& m2);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// quat
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class quat {
public:
// layout of data
// [0] real component
// [1] i quaternion unit
// [2] j quaternion unit
// [3] k quaternion unit
float* data = nullptr;
quat(const float a = 0.0f, const float b = 0.0f, const float c = 0.0f, const float d = 0.0f);
quat(const __m128& data);
quat(const vec4& v);
quat(const quat& other);
quat(quat&& other);
~quat();
float& operator[](const uint32_t& i) const;
quat& operator=(const quat& other);
quat& operator=(quat&& other);
quat operator-() const;
quat conjugate() const;
float norm() const;
quat inverse() const;
quat normalize() const;
vec4 transform(const vec4& v) const;
vec4 transform(const vec4& v, const vec4& t) const;
std::string toString() const;
};
quat operator*(const quat& q1, const quat& q2);
quat operator*(const float& s, const quat& q);
quat operator*(const quat& q, const float& s);
quat operator/(const quat& q, const float& s);
quat operator+(const quat& v1, const quat& v2);
quat operator-(const quat& v1, const quat& v2);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dualquat
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class dualquat {
public:
// [0] rotation component
// [1] dual component
quat* data;
dualquat(const quat& real = quat(), const quat& dual = quat());
dualquat(const vec4& v);
dualquat(const quat& r, const vec4& t);
dualquat(const dualquat& other);
dualquat(dualquat&& other);
~dualquat();
dualquat& operator=(const dualquat& other);
dualquat& operator=(dualquat&& other);
quat& operator[](const uint32_t i) const;
dualquat conjugate() const;
dualquat dualConjugate() const;
dualquat inverse() const;
vec4 transform(const vec4& v) const;
std::string toString() const;
};
dualquat operator*(const dualquat& d1, const dualquat& d2);
dualquat operator*(const float& s, const dualquat& d);
dualquat operator*(const dualquat& d, const float& s);
dualquat operator+(const dualquat& d1, const dualquat& d2);
dualquat operator-(const dualquat& d1, const dualquat& d2);
}
#endif // !G_MATH_HPP
|
#pragma once
#include <QWidget>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QFileDialog>
#include <QDir>
namespace envire { namespace viz {
class PclWidget : public QWidget
{
Q_OBJECT
public:
PclWidget(QWidget* parent = nullptr) : QWidget(parent),
horizontalLayout(new QHBoxLayout(this)), lineEdit(new QLineEdit()),
pushButton(new QPushButton())
{
lineEdit->setEnabled(false);
horizontalLayout->addWidget(lineEdit);
pushButton->setText("Select PCL File");
horizontalLayout->addWidget(pushButton);
setLayout(horizontalLayout);
connect(pushButton, SIGNAL(clicked(bool)), this, SLOT(buttonClicked(bool)));
}
public:
QString getPclPath() const
{
return lineEdit->text();
}
private slots:
void buttonClicked(bool checked)
{
const QString file = QFileDialog::getOpenFileName(this, tr("Open PCL File"),
QDir::currentPath(), QString(),
0, QFileDialog::DontUseNativeDialog);
lineEdit->setText(file);
}
private:
QHBoxLayout *horizontalLayout;
QLineEdit *lineEdit;
QPushButton *pushButton;
};
}}
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "opencv2/core/hal/intrin.hpp"
#define DEF_ACC_INT_FUNCS(suffix, type, acctype) \
void acc_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_NEON(acc_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(acc_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(acc_general_, (src, dst, mask, len, cn)); \
} \
void accSqr_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_NEON(accSqr_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(accSqr_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(accSqr_general_, (src, dst, mask, len, cn)); \
} \
void accProd_##suffix(const type* src1, const type* src2, \
acctype* dst, const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_NEON(accProd_simd_, (src1, src2, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(accProd_simd_, (src1, src2, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(accProd_general_, (src1, src2, dst, mask, len, cn)); \
} \
void accW_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn, double alpha) \
{ \
CV_CPU_CALL_NEON(accW_simd_, (src, dst, mask, len, cn, alpha)); \
CV_CPU_CALL_SSE2(accW_simd_, (src, dst, mask, len, cn, alpha)); \
CV_CPU_CALL_BASELINE(accW_general_, (src, dst, mask, len, cn, alpha)); \
}
#define DEF_ACC_FLT_FUNCS(suffix, type, acctype) \
void acc_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_AVX(acc_avx_##suffix, (src, dst, mask, len, cn)); \
CV_CPU_CALL_NEON(acc_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(acc_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(acc_general_, (src, dst, mask, len, cn)); \
} \
void accSqr_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_AVX(accSqr_avx_##suffix, (src, dst, mask, len, cn)); \
CV_CPU_CALL_NEON(accSqr_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(accSqr_simd_, (src, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(accSqr_general_, (src, dst, mask, len, cn)); \
} \
void accProd_##suffix(const type* src1, const type* src2, \
acctype* dst, const uchar* mask, int len, int cn) \
{ \
CV_CPU_CALL_AVX(accProd_avx_##suffix, (src1, src2, dst, mask, len, cn)); \
CV_CPU_CALL_NEON(accProd_simd_, (src1, src2, dst, mask, len, cn)); \
CV_CPU_CALL_SSE2(accProd_simd_, (src1, src2, dst, mask, len, cn)); \
CV_CPU_CALL_BASELINE(accProd_general_, (src1, src2, dst, mask, len, cn)); \
} \
void accW_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn, double alpha) \
{ \
CV_CPU_CALL_AVX(accW_avx_##suffix, (src, dst, mask, len, cn, alpha)); \
CV_CPU_CALL_NEON(accW_simd_, (src, dst, mask, len, cn, alpha)); \
CV_CPU_CALL_SSE2(accW_simd_, (src, dst, mask, len, cn, alpha)); \
CV_CPU_CALL_BASELINE(accW_general_, (src, dst, mask, len, cn, alpha)); \
}
#define DECLARATE_ACC_FUNCS(suffix, type, acctype) \
void acc_##suffix(const type* src, acctype* dst, const uchar* mask, int len, int cn); \
void accSqr_##suffix(const type* src, acctype* dst, const uchar* mask, int len, int cn); \
void accProd_##suffix(const type* src1, const type* src2, acctype* dst, const uchar* mask, int len, int cn); \
void accW_##suffix(const type* src, acctype* dst, const uchar* mask, int len, int cn, double alpha);
namespace cv {
DECLARATE_ACC_FUNCS(8u32f, uchar, float)
DECLARATE_ACC_FUNCS(8u64f, uchar, double)
DECLARATE_ACC_FUNCS(16u32f, ushort, float)
DECLARATE_ACC_FUNCS(16u64f, ushort, double)
DECLARATE_ACC_FUNCS(32f, float, float)
DECLARATE_ACC_FUNCS(32f64f, float, double)
DECLARATE_ACC_FUNCS(64f, double, double)
CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN
void acc_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn);
void acc_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn);
void acc_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn);
void acc_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn);
void acc_simd_(const float* src, float* dst, const uchar* mask, int len, int cn);
void acc_simd_(const float* src, double* dst, const uchar* mask, int len, int cn);
void acc_simd_(const double* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const float* src, float* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const float* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_simd_(const double* src, double* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const uchar* src1, const uchar* src2, float* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const ushort* src1, const ushort* src2, float* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const uchar* src1, const uchar* src2, double* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const ushort* src1, const ushort* src2, double* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const float* src1, const float* src2, float* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const float* src1, const float* src2, double* dst, const uchar* mask, int len, int cn);
void accProd_simd_(const double* src1, const double* src2, double* dst, const uchar* mask, int len, int cn);
void accW_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const float* src, float* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const float* src, double* dst, const uchar* mask, int len, int cn, double alpha);
void accW_simd_(const double* src, double* dst, const uchar* mask, int len, int cn, double alpha);
// accumulate series optimized by AVX
void acc_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn);
void acc_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn);
void acc_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn);
void accSqr_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn);
void accSqr_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn);
void accProd_avx_32f(const float* src1, const float* src2, float* dst, const uchar* mask, int len, int cn);
void accProd_avx_32f64f(const float* src1, const float* src2, double* dst, const uchar* mask, int len, int cn);
void accProd_avx_64f(const double* src1, const double* src2, double* dst, const uchar* mask, int len, int cn);
void accW_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn, double alpha);
void accW_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn, double alpha);
void accW_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn, double alpha);
#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY
template <typename T, typename AT>
void acc_general_(const T* src, AT* dst, const uchar* mask, int len, int cn, int start = 0 )
{
int i = start;
if( !mask )
{
len *= cn;
#if CV_ENABLE_UNROLLED
for( ; i <= len - 4; i += 4 )
{
AT t0, t1;
t0 = src[i] + dst[i];
t1 = src[i+1] + dst[i+1];
dst[i] = t0; dst[i+1] = t1;
t0 = src[i+2] + dst[i+2];
t1 = src[i+3] + dst[i+3];
dst[i+2] = t0; dst[i+3] = t1;
}
#endif
for( ; i < len; i++ )
{
dst[i] += src[i];
}
}
else
{
src += (i * cn);
dst += (i * cn);
for( ; i < len; i++, src += cn, dst += cn )
{
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
dst[k] += src[k];
}
}
}
}
}
template<typename T, typename AT> void
accSqr_general_( const T* src, AT* dst, const uchar* mask, int len, int cn, int start = 0 )
{
int i = start;
if( !mask )
{
len *= cn;
#if CV_ENABLE_UNROLLED
for( ; i <= len - 4; i += 4 )
{
AT t0, t1;
t0 = (AT)src[i]*src[i] + dst[i];
t1 = (AT)src[i+1]*src[i+1] + dst[i+1];
dst[i] = t0; dst[i+1] = t1;
t0 = (AT)src[i+2]*src[i+2] + dst[i+2];
t1 = (AT)src[i+3]*src[i+3] + dst[i+3];
dst[i+2] = t0; dst[i+3] = t1;
}
#endif
for( ; i < len; i++ )
{
dst[i] += (AT)src[i]*src[i];
}
}
else
{
src += (i * cn);
dst += (i * cn);
for( ; i < len; i++, src += cn, dst += cn )
{
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
dst[k] += (AT)src[k]*src[k];
}
}
}
}
}
template<typename T, typename AT> void
accProd_general_( const T* src1, const T* src2, AT* dst, const uchar* mask, int len, int cn, int start = 0 )
{
int i = start;
if( !mask )
{
len *= cn;
#if CV_ENABLE_UNROLLED
for( ; i <= len - 4; i += 4 )
{
AT t0, t1;
t0 = (AT)src1[i]*src2[i] + dst[i];
t1 = (AT)src1[i+1]*src2[i+1] + dst[i+1];
dst[i] = t0; dst[i+1] = t1;
t0 = (AT)src1[i+2]*src2[i+2] + dst[i+2];
t1 = (AT)src1[i+3]*src2[i+3] + dst[i+3];
dst[i+2] = t0; dst[i+3] = t1;
}
#endif
for( ; i < len; i++ )
{
dst[i] += (AT)src1[i]*src2[i];
}
}
else
{
src1 += (i * cn);
src2 += (i * cn);
dst += (i * cn);
for( ; i < len; i++, src1 += cn, src2 += cn, dst += cn )
{
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
dst[k] += (AT)src1[k]*src2[k];
}
}
}
}
}
template<typename T, typename AT> void
accW_general_( const T* src, AT* dst, const uchar* mask, int len, int cn, double alpha, int start = 0 )
{
AT a = (AT)alpha, b = 1 - a;
int i = start;
if( !mask )
{
len *= cn;
#if CV_ENABLE_UNROLLED
for( ; i <= len - 4; i += 4 )
{
AT t0, t1;
t0 = src[i]*a + dst[i]*b;
t1 = src[i+1]*a + dst[i+1]*b;
dst[i] = t0; dst[i+1] = t1;
t0 = src[i+2]*a + dst[i+2]*b;
t1 = src[i+3]*a + dst[i+3]*b;
dst[i+2] = t0; dst[i+3] = t1;
}
#endif
for( ; i < len; i++ )
{
dst[i] = src[i]*a + dst[i]*b;
}
}
else
{
src += (i * cn);
dst += (i * cn);
for( ; i < len; i++, src += cn, dst += cn )
{
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
dst[k] = src[k]*a + dst[k]*b;
}
}
}
}
}
#if CV_SIMD128
void acc_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_src = v_load(src + x);
v_uint16x8 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else
{
v_uint8x16 v_0 = v_setall_u8(0);
if (cn == 1)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint8x16 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint16x8 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint8x16 v_src0, v_src1, v_src2;
v_load_deinterleave(src + (x * cn), v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_expand(v_src2, v_src20, v_src21);
v_uint32x4 v_src000, v_src001, v_src010, v_src011;
v_uint32x4 v_src100, v_src101, v_src110, v_src111;
v_uint32x4 v_src200, v_src201, v_src210, v_src211;
v_expand(v_src00, v_src000, v_src001);
v_expand(v_src01, v_src010, v_src011);
v_expand(v_src10, v_src100, v_src101);
v_expand(v_src11, v_src110, v_src111);
v_expand(v_src20, v_src200, v_src201);
v_expand(v_src21, v_src210, v_src211);
v_float32x4 v_dst000, v_dst001, v_dst010, v_dst011;
v_float32x4 v_dst100, v_dst101, v_dst110, v_dst111;
v_float32x4 v_dst200, v_dst201, v_dst210, v_dst211;
v_load_deinterleave(dst + (x * cn), v_dst000, v_dst100, v_dst200);
v_load_deinterleave(dst + ((x + 4) * cn), v_dst001, v_dst101, v_dst201);
v_load_deinterleave(dst + ((x + 8) * cn), v_dst010, v_dst110, v_dst210);
v_load_deinterleave(dst + ((x + 12) * cn), v_dst011, v_dst111, v_dst211);
v_store_interleave(dst + (x * cn), v_dst000 + v_cvt_f32(v_reinterpret_as_s32(v_src000)), v_dst100 + v_cvt_f32(v_reinterpret_as_s32(v_src100)), v_dst200 + v_cvt_f32(v_reinterpret_as_s32(v_src200)));
v_store_interleave(dst + ((x + 4) * cn), v_dst001 + v_cvt_f32(v_reinterpret_as_s32(v_src001)), v_dst101 + v_cvt_f32(v_reinterpret_as_s32(v_src101)), v_dst201 + v_cvt_f32(v_reinterpret_as_s32(v_src201)));
v_store_interleave(dst + ((x + 8) * cn), v_dst010 + v_cvt_f32(v_reinterpret_as_s32(v_src010)), v_dst110 + v_cvt_f32(v_reinterpret_as_s32(v_src110)), v_dst210 + v_cvt_f32(v_reinterpret_as_s32(v_src210)));
v_store_interleave(dst + ((x + 12) * cn), v_dst011 + v_cvt_f32(v_reinterpret_as_s32(v_src011)), v_dst111 + v_cvt_f32(v_reinterpret_as_s32(v_src111)), v_dst211 + v_cvt_f32(v_reinterpret_as_s32(v_src211)));
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
void acc_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src0)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src1)));
}
}
else
{
if (cn == 1)
{
v_uint16x8 v_0 = v_setall_u16(0);
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint32x4 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src0)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src1)));
}
}
else if (cn == 3)
{
v_uint16x8 v_0 = v_setall_u16(0);
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint32x4 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_expand(v_src2, v_src20, v_src21);
v_float32x4 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_cvt_f32(v_reinterpret_as_s32(v_src00)), v_dst10 + v_cvt_f32(v_reinterpret_as_s32(v_src10)), v_dst20 + v_cvt_f32(v_reinterpret_as_s32(v_src20)));
v_store_interleave(dst + (x + 4) * cn, v_dst01 + v_cvt_f32(v_reinterpret_as_s32(v_src01)), v_dst11 + v_cvt_f32(v_reinterpret_as_s32(v_src11)), v_dst21 + v_cvt_f32(v_reinterpret_as_s32(v_src21)));
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
void acc_simd_(const float* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_store(dst + x, v_load(dst + x) + v_load(src + x));
v_store(dst + x + 4, v_load(dst + x + 4) + v_load(src + x + 4));
}
}
else
{
v_float32x4 v_0 = v_setzero_f32();
if (cn == 1)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint16x8 v_masku16 = v_load_expand(mask + x);
v_uint32x4 v_masku320, v_masku321;
v_expand(v_masku16, v_masku320, v_masku321);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_masku320 == v_reinterpret_as_u32(v_0)));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_masku321 == v_reinterpret_as_u32(v_0)));
v_store(dst + x, v_load(dst + x) + (v_load(src + x) & v_mask0));
v_store(dst + x + 4, v_load(dst + x + 4) + (v_load(src + x + 4) & v_mask1));
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint16x8 v_masku16 = v_load_expand(mask + x);
v_uint32x4 v_masku320, v_masku321;
v_expand(v_masku16, v_masku320, v_masku321);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_masku320 == v_reinterpret_as_u32(v_0)));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_masku321 == v_reinterpret_as_u32(v_0)));
v_float32x4 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_load_deinterleave(src + x * cn, v_src00, v_src10, v_src20);
v_load_deinterleave(src + (x + 4) * cn, v_src01, v_src11, v_src21);
v_src00 = v_src00 & v_mask0;
v_src01 = v_src01 & v_mask1;
v_src10 = v_src10 & v_mask0;
v_src11 = v_src11 & v_mask1;
v_src20 = v_src20 & v_mask0;
v_src21 = v_src21 & v_mask1;
v_float32x4 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 4) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
#if CV_SIMD128_64F
void acc_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_src = v_load(src + x);
v_uint16x8 v_int0, v_int1;
v_expand(v_src, v_int0, v_int1);
v_uint32x4 v_int00, v_int01, v_int10, v_int11;
v_expand(v_int0, v_int00, v_int01);
v_expand(v_int1, v_int10, v_int11);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src4 = v_cvt_f64(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src5 = v_cvt_f64_high(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src6 = v_cvt_f64(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src7 = v_cvt_f64_high(v_reinterpret_as_s32(v_int11));
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_float64x2 v_dst4 = v_load(dst + x + 8);
v_float64x2 v_dst5 = v_load(dst + x + 10);
v_float64x2 v_dst6 = v_load(dst + x + 12);
v_float64x2 v_dst7 = v_load(dst + x + 14);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_dst4 = v_dst4 + v_src4;
v_dst5 = v_dst5 + v_src5;
v_dst6 = v_dst6 + v_src6;
v_dst7 = v_dst7 + v_src7;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
v_store(dst + x + 8, v_dst4);
v_store(dst + x + 10, v_dst5);
v_store(dst + x + 12, v_dst6);
v_store(dst + x + 14, v_dst7);
}
}
else
{
v_uint8x16 v_0 = v_setall_u8(0);
if (cn == 1)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_mask == v_0);
v_uint8x16 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint16x8 v_int0, v_int1;
v_expand(v_src, v_int0, v_int1);
v_uint32x4 v_int00, v_int01, v_int10, v_int11;
v_expand(v_int0, v_int00, v_int01);
v_expand(v_int1, v_int10, v_int11);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src4 = v_cvt_f64(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src5 = v_cvt_f64_high(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src6 = v_cvt_f64(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src7 = v_cvt_f64_high(v_reinterpret_as_s32(v_int11));
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_float64x2 v_dst4 = v_load(dst + x + 8);
v_float64x2 v_dst5 = v_load(dst + x + 10);
v_float64x2 v_dst6 = v_load(dst + x + 12);
v_float64x2 v_dst7 = v_load(dst + x + 14);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_dst4 = v_dst4 + v_src4;
v_dst5 = v_dst5 + v_src5;
v_dst6 = v_dst6 + v_src6;
v_dst7 = v_dst7 + v_src7;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
v_store(dst + x + 8, v_dst4);
v_store(dst + x + 10, v_dst5);
v_store(dst + x + 12, v_dst6);
v_store(dst + x + 14, v_dst7);
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint8x16 v_src0, v_src1, v_src2;
v_load_deinterleave(src + (x * cn), v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_expand(v_src2, v_src20, v_src21);
v_uint32x4 v_src000, v_src001, v_src010, v_src011;
v_uint32x4 v_src100, v_src101, v_src110, v_src111;
v_uint32x4 v_src200, v_src201, v_src210, v_src211;
v_expand(v_src00, v_src000, v_src001);
v_expand(v_src01, v_src010, v_src011);
v_expand(v_src10, v_src100, v_src101);
v_expand(v_src11, v_src110, v_src111);
v_expand(v_src20, v_src200, v_src201);
v_expand(v_src21, v_src210, v_src211);
v_float64x2 v_src0000, v_src0001, v_src0010, v_src0011, v_src0100, v_src0101, v_src0110, v_src0111;
v_float64x2 v_src1000, v_src1001, v_src1010, v_src1011, v_src1100, v_src1101, v_src1110, v_src1111;
v_float64x2 v_src2000, v_src2001, v_src2010, v_src2011, v_src2100, v_src2101, v_src2110, v_src2111;
v_src0000 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src000)));
v_src0001 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src000)));
v_src0010 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src001)));
v_src0011 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src001)));
v_src0100 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src010)));
v_src0101 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src010)));
v_src0110 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src011)));
v_src0111 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src011)));
v_src1000 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src100)));
v_src1001 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src100)));
v_src1010 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src101)));
v_src1011 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src101)));
v_src1100 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src110)));
v_src1101 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src110)));
v_src1110 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src111)));
v_src1111 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src111)));
v_src2000 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src200)));
v_src2001 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src200)));
v_src2010 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src201)));
v_src2011 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src201)));
v_src2100 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src210)));
v_src2101 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src210)));
v_src2110 = v_cvt_f64(v_cvt_f32(v_reinterpret_as_s32(v_src211)));
v_src2111 = v_cvt_f64_high(v_cvt_f32(v_reinterpret_as_s32(v_src211)));
v_float64x2 v_dst0000, v_dst0001, v_dst0010, v_dst0011, v_dst0100, v_dst0101, v_dst0110, v_dst0111;
v_float64x2 v_dst1000, v_dst1001, v_dst1010, v_dst1011, v_dst1100, v_dst1101, v_dst1110, v_dst1111;
v_float64x2 v_dst2000, v_dst2001, v_dst2010, v_dst2011, v_dst2100, v_dst2101, v_dst2110, v_dst2111;
v_load_deinterleave(dst + (x * cn), v_dst0000, v_dst1000, v_dst2000);
v_load_deinterleave(dst + ((x + 2) * cn), v_dst0001, v_dst1001, v_dst2001);
v_load_deinterleave(dst + ((x + 4) * cn), v_dst0010, v_dst1010, v_dst2010);
v_load_deinterleave(dst + ((x + 6) * cn), v_dst0011, v_dst1011, v_dst2011);
v_load_deinterleave(dst + ((x + 8) * cn), v_dst0100, v_dst1100, v_dst2100);
v_load_deinterleave(dst + ((x + 10) * cn), v_dst0101, v_dst1101, v_dst2101);
v_load_deinterleave(dst + ((x + 12) * cn), v_dst0110, v_dst1110, v_dst2110);
v_load_deinterleave(dst + ((x + 14) * cn), v_dst0111, v_dst1111, v_dst2111);
v_store_interleave(dst + (x * cn), v_dst0000 + v_src0000, v_dst1000 + v_src1000, v_dst2000 + v_src2000);
v_store_interleave(dst + ((x + 2) * cn), v_dst0001 + v_src0001, v_dst1001 + v_src1001, v_dst2001 + v_src2001);
v_store_interleave(dst + ((x + 4) * cn), v_dst0010 + v_src0010, v_dst1010 + v_src1010, v_dst2010 + v_src2010);
v_store_interleave(dst + ((x + 6) * cn), v_dst0011 + v_src0011, v_dst1011 + v_src1011, v_dst2011 + v_src2011);
v_store_interleave(dst + ((x + 8) * cn), v_dst0100 + v_src0100, v_dst1100 + v_src1100, v_dst2100 + v_src2100);
v_store_interleave(dst + ((x + 10) * cn), v_dst0101 + v_src0101, v_dst1101 + v_src1101, v_dst2101 + v_src2101);
v_store_interleave(dst + ((x + 12) * cn), v_dst0110 + v_src0110, v_dst1110 + v_src1110, v_dst2110 + v_src2110);
v_store_interleave(dst + ((x + 14) * cn), v_dst0111 + v_src0111, v_dst1111 + v_src1111, v_dst2111 + v_src2111);
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
void acc_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_int0, v_int1;
v_expand(v_src, v_int0, v_int1);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int1));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int1));
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint32x4 v_int0, v_int1;
v_expand(v_src, v_int0, v_int1);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int1));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int1));
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
if (cn == 3)
{
for ( ; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint32x4 v_int00, v_int01, v_int10, v_int11, v_int20, v_int21;
v_expand(v_src0, v_int00, v_int01);
v_expand(v_src1, v_int10, v_int11);
v_expand(v_src2, v_int20, v_int21);
v_float64x2 v_src00 = v_cvt_f64(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src01 = v_cvt_f64_high(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src02 = v_cvt_f64(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src03 = v_cvt_f64_high(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src10 = v_cvt_f64(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src11 = v_cvt_f64_high(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src12 = v_cvt_f64(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src13 = v_cvt_f64_high(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src20 = v_cvt_f64(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src21 = v_cvt_f64_high(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src22 = v_cvt_f64(v_reinterpret_as_s32(v_int21));
v_float64x2 v_src23 = v_cvt_f64_high(v_reinterpret_as_s32(v_int21));
v_float64x2 v_dst00, v_dst01, v_dst02, v_dst03, v_dst10, v_dst11, v_dst12, v_dst13, v_dst20, v_dst21, v_dst22, v_dst23;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_load_deinterleave(dst + (x + 4) * cn, v_dst02, v_dst12, v_dst22);
v_load_deinterleave(dst + (x + 6) * cn, v_dst03, v_dst13, v_dst23);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
v_store_interleave(dst + (x + 4) * cn, v_dst02 + v_src02, v_dst12 + v_src12, v_dst22 + v_src22);
v_store_interleave(dst + (x + 6) * cn, v_dst03 + v_src03, v_dst13 + v_src13, v_dst23 + v_src23);
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
void acc_simd_(const float* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float32x4 v_src = v_load(src + x);
v_float64x2 v_src0 = v_cvt_f64(v_src);
v_float64x2 v_src1 = v_cvt_f64_high(v_src);
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else
{
v_uint64x2 v_0 = v_setzero_u64();
if (cn == 1)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint32x4 v_masku32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_masku32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float32x4 v_src = v_load(src + x);
v_float64x2 v_src0 = v_cvt_f64(v_src) & v_mask0;
v_float64x2 v_src1 = v_cvt_f64_high(v_src) & v_mask1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint32x4 v_masku32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_masku32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float32x4 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_float64x2 v_src00 = v_cvt_f64(v_src0) & v_mask0;
v_float64x2 v_src01 = v_cvt_f64_high(v_src0) & v_mask1;
v_float64x2 v_src10 = v_cvt_f64(v_src1) & v_mask0;
v_float64x2 v_src11 = v_cvt_f64_high(v_src1) & v_mask1;
v_float64x2 v_src20 = v_cvt_f64(v_src2) & v_mask0;
v_float64x2 v_src21 = v_cvt_f64_high(v_src2) & v_mask1;
v_float64x2 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
void acc_simd_(const double* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float64x2 v_src0 = v_load(src + x);
v_float64x2 v_src1 = v_load(src + x + 2);
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else
{
v_uint64x2 v_0 = v_setzero_u64();
if (cn == 1)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint32x4 v_masku32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_masku32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_src0 = v_load(src + x);
v_float64x2 v_src1 = v_load(src + x + 2);
v_store(dst + x, v_load(dst + x) + (v_src0 & v_mask0));
v_store(dst + x + 2, v_load(dst + x + 2) + (v_src1 & v_mask1));
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint32x4 v_masku32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_masku32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_src00, v_src10, v_src20, v_src01, v_src11, v_src21;
v_load_deinterleave(src + x * cn, v_src00, v_src10, v_src20);
v_load_deinterleave(src + (x + 2) * cn, v_src01, v_src11, v_src21);
v_src00 = v_src00 & v_mask0;
v_src01 = v_src01 & v_mask1;
v_src10 = v_src10 & v_mask0;
v_src11 = v_src11 & v_mask1;
v_src20 = v_src20 & v_mask0;
v_src21 = v_src21 & v_mask1;
v_float64x2 v_dst00, v_dst10, v_dst20, v_dst01, v_dst11, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
acc_general_(src, dst, mask, len, cn, x);
}
#else
void acc_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn)
{
acc_general_(src, dst, mask, len, cn, 0);
}
void acc_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn)
{
acc_general_(src, dst, mask, len, cn, 0);
}
void acc_simd_(const float* src, double* dst, const uchar* mask, int len, int cn)
{
acc_general_(src, dst, mask, len, cn, 0);
}
void acc_simd_(const double* src, double* dst, const uchar* mask, int len, int cn)
{
acc_general_(src, dst, mask, len, cn, 0);
}
#endif
// square accumulate optimized by universal intrinsic
void accSqr_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_src = v_load(src + x);
v_uint16x8 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else
{
v_uint8x16 v_0 = v_setall_u8(0);
if (cn == 1)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint8x16 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint16x8 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint8x16 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_expand(v_src2, v_src20, v_src21);
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_uint32x4 v_src000, v_src001, v_src010, v_src011;
v_uint32x4 v_src100, v_src101, v_src110, v_src111;
v_uint32x4 v_src200, v_src201, v_src210, v_src211;
v_expand(v_src00, v_src000, v_src001);
v_expand(v_src01, v_src010, v_src011);
v_expand(v_src10, v_src100, v_src101);
v_expand(v_src11, v_src110, v_src111);
v_expand(v_src20, v_src200, v_src201);
v_expand(v_src21, v_src210, v_src211);
v_float32x4 v_dst000, v_dst001, v_dst010, v_dst011;
v_float32x4 v_dst100, v_dst101, v_dst110, v_dst111;
v_float32x4 v_dst200, v_dst201, v_dst210, v_dst211;
v_load_deinterleave(dst + x * cn, v_dst000, v_dst100, v_dst200);
v_load_deinterleave(dst + (x + 4) * cn, v_dst001, v_dst101, v_dst201);
v_load_deinterleave(dst + (x + 8) * cn, v_dst010, v_dst110, v_dst210);
v_load_deinterleave(dst + (x + 12) * cn, v_dst011, v_dst111, v_dst211);
v_store_interleave(dst + x * cn, v_dst000 + v_cvt_f32(v_reinterpret_as_s32(v_src000)), v_dst100 + v_cvt_f32(v_reinterpret_as_s32(v_src100)), v_dst200 + v_cvt_f32(v_reinterpret_as_s32(v_src200)));
v_store_interleave(dst + (x + 4) * cn, v_dst001 + v_cvt_f32(v_reinterpret_as_s32(v_src001)), v_dst101 + v_cvt_f32(v_reinterpret_as_s32(v_src101)), v_dst201 + v_cvt_f32(v_reinterpret_as_s32(v_src201)));
v_store_interleave(dst + (x + 8) * cn, v_dst010 + v_cvt_f32(v_reinterpret_as_s32(v_src010)), v_dst110 + v_cvt_f32(v_reinterpret_as_s32(v_src110)), v_dst210 + v_cvt_f32(v_reinterpret_as_s32(v_src210)));
v_store_interleave(dst + (x + 12) * cn, v_dst011 + v_cvt_f32(v_reinterpret_as_s32(v_src011)), v_dst111 + v_cvt_f32(v_reinterpret_as_s32(v_src111)), v_dst211 + v_cvt_f32(v_reinterpret_as_s32(v_src211)));
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
void accSqr_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_float32x4 v_float0, v_float1;
v_float0 = v_cvt_f32(v_reinterpret_as_s32(v_src0));
v_float1 = v_cvt_f32(v_reinterpret_as_s32(v_src1));
v_float0 = v_float0 * v_float0;
v_float1 = v_float1 * v_float1;
v_store(dst + x, v_load(dst + x) + v_float0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_float1);
}
}
else
{
v_uint32x4 v_0 = v_setzero_u32();
if (cn == 1)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint16x8 v_mask16 = v_load_expand(mask + x);
v_uint32x4 v_mask0, v_mask1;
v_expand(v_mask16, v_mask0, v_mask1);
v_mask0 = ~(v_mask0 == v_0);
v_mask1 = ~(v_mask1 == v_0);
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_src0 = v_src0 & v_mask0;
v_src1 = v_src1 & v_mask1;
v_float32x4 v_float0, v_float1;
v_float0 = v_cvt_f32(v_reinterpret_as_s32(v_src0));
v_float1 = v_cvt_f32(v_reinterpret_as_s32(v_src1));
v_float0 = v_float0 * v_float0;
v_float1 = v_float1 * v_float1;
v_store(dst + x, v_load(dst + x) + v_float0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_float1);
}
}
else if (cn == 3)
{
for ( ; x <= len - cVectorWidth ; x += cVectorWidth)
{
v_uint16x8 v_mask16 = v_load_expand(mask + x);
v_uint32x4 v_mask0, v_mask1;
v_expand(v_mask16, v_mask0, v_mask1);
v_mask0 = ~(v_mask0 == v_0);
v_mask1 = ~(v_mask1 == v_0);
v_uint16x8 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_uint32x4 v_int00, v_int01, v_int10, v_int11, v_int20, v_int21;
v_expand(v_src0, v_int00, v_int01);
v_expand(v_src1, v_int10, v_int11);
v_expand(v_src2, v_int20, v_int21);
v_int00 = v_int00 & v_mask0;
v_int01 = v_int01 & v_mask1;
v_int10 = v_int10 & v_mask0;
v_int11 = v_int11 & v_mask1;
v_int20 = v_int20 & v_mask0;
v_int21 = v_int21 & v_mask1;
v_float32x4 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_src00 = v_cvt_f32(v_reinterpret_as_s32(v_int00));
v_src01 = v_cvt_f32(v_reinterpret_as_s32(v_int01));
v_src10 = v_cvt_f32(v_reinterpret_as_s32(v_int10));
v_src11 = v_cvt_f32(v_reinterpret_as_s32(v_int11));
v_src20 = v_cvt_f32(v_reinterpret_as_s32(v_int20));
v_src21 = v_cvt_f32(v_reinterpret_as_s32(v_int21));
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_float32x4 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 4) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
void accSqr_simd_(const float* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float32x4 v_src0 = v_load(src + x);
v_float32x4 v_src1 = v_load(src + x + 4);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_src1);
}
}
else
{
v_uint32x4 v_0 = v_setzero_u32();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask16 = v_load_expand(mask + x);
v_uint32x4 v_mask_0, v_mask_1;
v_expand(v_mask16, v_mask_0, v_mask_1);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_mask_0 == v_0));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_mask_1 == v_0));
v_float32x4 v_src0 = v_load(src + x);
v_float32x4 v_src1 = v_load(src + x + 4);
v_src0 = v_src0 & v_mask0;
v_src1 = v_src1 & v_mask1;
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_src1);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask16 = v_load_expand(mask + x);
v_uint32x4 v_mask_0, v_mask_1;
v_expand(v_mask16, v_mask_0, v_mask_1);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_mask_0 == v_0));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_mask_1 == v_0));
v_float32x4 v_src00, v_src10, v_src20, v_src01, v_src11, v_src21;
v_load_deinterleave(src + x * cn, v_src00, v_src10, v_src20);
v_load_deinterleave(src + (x + 4) * cn, v_src01, v_src11, v_src21);
v_src00 = v_src00 & v_mask0;
v_src01 = v_src01 & v_mask1;
v_src10 = v_src10 & v_mask0;
v_src11 = v_src11 & v_mask1;
v_src20 = v_src20 & v_mask0;
v_src21 = v_src21 & v_mask1;
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_float32x4 v_dst00, v_dst10, v_dst20, v_dst01, v_dst11, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 4) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
#if CV_SIMD128_64F
void accSqr_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_int = v_load_expand(src + x);
v_uint32x4 v_int0, v_int1;
v_expand(v_int, v_int0, v_int1);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int1));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int1));
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_src2 = v_src2 * v_src2;
v_src3 = v_src3 * v_src3;
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src = v_load_expand(src + x);
v_uint16x8 v_int = v_src & v_mask;
v_uint32x4 v_int0, v_int1;
v_expand(v_int, v_int0, v_int1);
v_float64x2 v_src0 = v_cvt_f64(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src1 = v_cvt_f64_high(v_reinterpret_as_s32(v_int0));
v_float64x2 v_src2 = v_cvt_f64(v_reinterpret_as_s32(v_int1));
v_float64x2 v_src3 = v_cvt_f64_high(v_reinterpret_as_s32(v_int1));
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_src2 = v_src2 * v_src2;
v_src3 = v_src3 * v_src3;
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else if (cn == 3)
{
for (; x <= len - /*cVectorWidth*/16; x += cVectorWidth)
{
v_uint8x16 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_uint16x8 v_int0, v_int1, v_int2, dummy;
v_expand(v_src0, v_int0, dummy);
v_expand(v_src1, v_int1, dummy);
v_expand(v_src2, v_int2, dummy);
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_int0 = v_int0 & v_mask;
v_int1 = v_int1 & v_mask;
v_int2 = v_int2 & v_mask;
v_uint32x4 v_int00, v_int01, v_int10, v_int11, v_int20, v_int21;
v_expand(v_int0, v_int00, v_int01);
v_expand(v_int1, v_int10, v_int11);
v_expand(v_int2, v_int20, v_int21);
v_float64x2 v_src00 = v_cvt_f64(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src01 = v_cvt_f64_high(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src02 = v_cvt_f64(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src03 = v_cvt_f64_high(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src10 = v_cvt_f64(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src11 = v_cvt_f64_high(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src12 = v_cvt_f64(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src13 = v_cvt_f64_high(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src20 = v_cvt_f64(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src21 = v_cvt_f64_high(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src22 = v_cvt_f64(v_reinterpret_as_s32(v_int21));
v_float64x2 v_src23 = v_cvt_f64_high(v_reinterpret_as_s32(v_int21));
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src02 = v_src02 * v_src02;
v_src03 = v_src03 * v_src03;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src12 = v_src12 * v_src12;
v_src13 = v_src13 * v_src13;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_src22 = v_src22 * v_src22;
v_src23 = v_src23 * v_src23;
v_float64x2 v_dst00, v_dst01, v_dst02, v_dst03, v_dst10, v_dst11, v_dst12, v_dst13, v_dst20, v_dst21, v_dst22, v_dst23;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_load_deinterleave(dst + (x + 4) * cn, v_dst02, v_dst12, v_dst22);
v_load_deinterleave(dst + (x + 6) * cn, v_dst03, v_dst13, v_dst23);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
v_store_interleave(dst + (x + 4) * cn, v_dst02 + v_src02, v_dst12 + v_src12, v_dst22 + v_src22);
v_store_interleave(dst + (x + 6) * cn, v_dst03 + v_src03, v_dst13 + v_src13, v_dst23 + v_src23);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
void accSqr_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_int_0, v_int_1;
v_expand(v_src, v_int_0, v_int_1);
v_int32x4 v_int0 = v_reinterpret_as_s32(v_int_0);
v_int32x4 v_int1 = v_reinterpret_as_s32(v_int_1);
v_float64x2 v_src0 = v_cvt_f64(v_int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_int0);
v_float64x2 v_src2 = v_cvt_f64(v_int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_int1);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_src2 = v_src2 * v_src2;
v_src3 = v_src3 * v_src3;
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src = v_load(src + x);
v_src = v_src & v_mask;
v_uint32x4 v_int_0, v_int_1;
v_expand(v_src, v_int_0, v_int_1);
v_int32x4 v_int0 = v_reinterpret_as_s32(v_int_0);
v_int32x4 v_int1 = v_reinterpret_as_s32(v_int_1);
v_float64x2 v_src0 = v_cvt_f64(v_int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_int0);
v_float64x2 v_src2 = v_cvt_f64(v_int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_int1);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_src2 = v_src2 * v_src2;
v_src3 = v_src3 * v_src3;
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_mask;
v_src1 = v_src1 & v_mask;
v_src2 = v_src2 & v_mask;
v_uint32x4 v_int00, v_int01, v_int10, v_int11, v_int20, v_int21;
v_expand(v_src0, v_int00, v_int01);
v_expand(v_src1, v_int10, v_int11);
v_expand(v_src2, v_int20, v_int21);
v_float64x2 v_src00 = v_cvt_f64(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src01 = v_cvt_f64_high(v_reinterpret_as_s32(v_int00));
v_float64x2 v_src02 = v_cvt_f64(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src03 = v_cvt_f64_high(v_reinterpret_as_s32(v_int01));
v_float64x2 v_src10 = v_cvt_f64(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src11 = v_cvt_f64_high(v_reinterpret_as_s32(v_int10));
v_float64x2 v_src12 = v_cvt_f64(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src13 = v_cvt_f64_high(v_reinterpret_as_s32(v_int11));
v_float64x2 v_src20 = v_cvt_f64(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src21 = v_cvt_f64_high(v_reinterpret_as_s32(v_int20));
v_float64x2 v_src22 = v_cvt_f64(v_reinterpret_as_s32(v_int21));
v_float64x2 v_src23 = v_cvt_f64_high(v_reinterpret_as_s32(v_int21));
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src02 = v_src02 * v_src02;
v_src03 = v_src03 * v_src03;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src12 = v_src12 * v_src12;
v_src13 = v_src13 * v_src13;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_src22 = v_src22 * v_src22;
v_src23 = v_src23 * v_src23;
v_float64x2 v_dst00, v_dst01, v_dst02, v_dst03;
v_float64x2 v_dst10, v_dst11, v_dst12, v_dst13;
v_float64x2 v_dst20, v_dst21, v_dst22, v_dst23;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2)* cn, v_dst01, v_dst11, v_dst21);
v_load_deinterleave(dst + (x + 4)* cn, v_dst02, v_dst12, v_dst22);
v_load_deinterleave(dst + (x + 6)* cn, v_dst03, v_dst13, v_dst23);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
v_store_interleave(dst + (x + 4) * cn, v_dst02 + v_src02, v_dst12 + v_src12, v_dst22 + v_src22);
v_store_interleave(dst + (x + 6) * cn, v_dst03 + v_src03, v_dst13 + v_src13, v_dst23 + v_src23);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
void accSqr_simd_(const float* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float32x4 v_src = v_load(src + x);
v_float64x2 v_src0 = v_cvt_f64(v_src);
v_float64x2 v_src1 = v_cvt_f64_high(v_src);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else
{
v_uint32x4 v_0 = v_setzero_u32();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask = v_load_expand_q(mask + x);;
v_mask = ~(v_mask == v_0);
v_float32x4 v_src = v_load(src + x);
v_src = v_src & v_reinterpret_as_f32(v_mask);
v_float64x2 v_src0 = v_cvt_f64(v_src);
v_float64x2 v_src1 = v_cvt_f64_high(v_src);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask = v_load_expand_q(mask + x);
v_mask = ~(v_mask == v_0);
v_float32x4 v_src0, v_src1, v_src2;
v_load_deinterleave(src + x * cn, v_src0, v_src1, v_src2);
v_src0 = v_src0 & v_reinterpret_as_f32(v_mask);
v_src1 = v_src1 & v_reinterpret_as_f32(v_mask);
v_src2 = v_src2 & v_reinterpret_as_f32(v_mask);
v_float64x2 v_src00 = v_cvt_f64(v_src0);
v_float64x2 v_src01 = v_cvt_f64_high(v_src0);
v_float64x2 v_src10 = v_cvt_f64(v_src1);
v_float64x2 v_src11 = v_cvt_f64_high(v_src1);
v_float64x2 v_src20 = v_cvt_f64(v_src2);
v_float64x2 v_src21 = v_cvt_f64_high(v_src2);
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_float64x2 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
void accSqr_simd_(const double* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float64x2 v_src0 = v_load(src + x);
v_float64x2 v_src1 = v_load(src + x + 2);
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else
{
v_uint64x2 v_0 = v_setzero_u64();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_mask32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_src0 = v_load(src + x);
v_float64x2 v_src1 = v_load(src + x + 2);
v_src0 = v_src0 & v_mask0;
v_src1 = v_src1 & v_mask1;
v_src0 = v_src0 * v_src0;
v_src1 = v_src1 * v_src1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 2, v_load(dst + x + 2) + v_src1);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_mask32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_load_deinterleave(src + x * cn, v_src00, v_src10, v_src20);
v_load_deinterleave(src + (x + 2) * cn, v_src01, v_src11, v_src21);
v_src00 = v_src00 & v_mask0;
v_src01 = v_src01 & v_mask1;
v_src10 = v_src10 & v_mask0;
v_src11 = v_src11 & v_mask1;
v_src20 = v_src20 & v_mask0;
v_src21 = v_src21 & v_mask1;
v_src00 = v_src00 * v_src00;
v_src01 = v_src01 * v_src01;
v_src10 = v_src10 * v_src10;
v_src11 = v_src11 * v_src11;
v_src20 = v_src20 * v_src20;
v_src21 = v_src21 * v_src21;
v_float64x2 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accSqr_general_(src, dst, mask, len, cn, x);
}
#else
void accSqr_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn)
{
accSqr_general_(src, dst, mask, len, cn, 0);
}
void accSqr_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn)
{
accSqr_general_(src, dst, mask, len, cn, 0);
}
void accSqr_simd_(const float* src, double* dst, const uchar* mask, int len, int cn)
{
accSqr_general_(src, dst, mask, len, cn, 0);
}
void accSqr_simd_(const double* src, double* dst, const uchar* mask, int len, int cn)
{
accSqr_general_(src, dst, mask, len, cn, 0);
}
#endif
// product accumulate optimized by universal intrinsic
void accProd_simd_(const uchar* src1, const uchar* src2, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_1src = v_load(src1 + x);
v_uint8x16 v_2src = v_load(src2 + x);
v_uint16x8 v_1src0, v_1src1, v_2src0, v_2src1;
v_expand(v_1src, v_1src0, v_1src1);
v_expand(v_2src, v_2src0, v_2src1);
v_uint16x8 v_src0, v_src1;
v_src0 = v_1src0 * v_2src0;
v_src1 = v_1src1 * v_2src1;
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else
{
v_uint8x16 v_0 = v_setzero_u8();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_mask == v_0);
v_uint8x16 v_1src = v_load(src1 + x);
v_uint8x16 v_2src = v_load(src2 + x);
v_1src = v_1src & v_mask;
v_2src = v_2src & v_mask;
v_uint16x8 v_1src0, v_1src1, v_2src0, v_2src1;
v_expand(v_1src, v_1src0, v_1src1);
v_expand(v_2src, v_2src0, v_2src1);
v_uint16x8 v_src0, v_src1;
v_src0 = v_1src0 * v_2src0;
v_src1 = v_1src1 * v_2src1;
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_store(dst + x, v_load(dst + x) + v_cvt_f32(v_reinterpret_as_s32(v_src00)));
v_store(dst + x + 4, v_load(dst + x + 4) + v_cvt_f32(v_reinterpret_as_s32(v_src01)));
v_store(dst + x + 8, v_load(dst + x + 8) + v_cvt_f32(v_reinterpret_as_s32(v_src10)));
v_store(dst + x + 12, v_load(dst + x + 12) + v_cvt_f32(v_reinterpret_as_s32(v_src11)));
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_mask = v_load(mask + x);
v_mask = ~(v_mask == v_0);
v_uint8x16 v_1src0, v_1src1, v_1src2, v_2src0, v_2src1, v_2src2;
v_load_deinterleave(src1 + x * cn, v_1src0, v_1src1, v_1src2);
v_load_deinterleave(src2 + x * cn, v_2src0, v_2src1, v_2src2);
v_1src0 = v_1src0 & v_mask;
v_1src1 = v_1src1 & v_mask;
v_1src2 = v_1src2 & v_mask;
v_2src0 = v_2src0 & v_mask;
v_2src1 = v_2src1 & v_mask;
v_2src2 = v_2src2 & v_mask;
v_uint16x8 v_1src00, v_1src01, v_1src10, v_1src11, v_1src20, v_1src21, v_2src00, v_2src01, v_2src10, v_2src11, v_2src20, v_2src21;
v_expand(v_1src0, v_1src00, v_1src01);
v_expand(v_1src1, v_1src10, v_1src11);
v_expand(v_1src2, v_1src20, v_1src21);
v_expand(v_2src0, v_2src00, v_2src01);
v_expand(v_2src1, v_2src10, v_2src11);
v_expand(v_2src2, v_2src20, v_2src21);
v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
v_src00 = v_1src00 * v_2src00;
v_src01 = v_1src01 * v_2src01;
v_src10 = v_1src10 * v_2src10;
v_src11 = v_1src11 * v_2src11;
v_src20 = v_1src20 * v_2src20;
v_src21 = v_1src21 * v_2src21;
v_uint32x4 v_src000, v_src001, v_src002, v_src003, v_src100, v_src101, v_src102, v_src103, v_src200, v_src201, v_src202, v_src203;
v_expand(v_src00, v_src000, v_src001);
v_expand(v_src01, v_src002, v_src003);
v_expand(v_src10, v_src100, v_src101);
v_expand(v_src11, v_src102, v_src103);
v_expand(v_src20, v_src200, v_src201);
v_expand(v_src21, v_src202, v_src203);
v_float32x4 v_dst000, v_dst001, v_dst002, v_dst003, v_dst100, v_dst101, v_dst102, v_dst103, v_dst200, v_dst201, v_dst202, v_dst203;
v_load_deinterleave(dst + x * cn, v_dst000, v_dst100, v_dst200);
v_load_deinterleave(dst + (x + 4) * cn, v_dst001, v_dst101, v_dst201);
v_load_deinterleave(dst + (x + 8) * cn, v_dst002, v_dst102, v_dst202);
v_load_deinterleave(dst + (x + 12) * cn, v_dst003, v_dst103, v_dst203);
v_dst000 = v_dst000 + v_cvt_f32(v_reinterpret_as_s32(v_src000));
v_dst001 = v_dst001 + v_cvt_f32(v_reinterpret_as_s32(v_src001));
v_dst002 = v_dst002 + v_cvt_f32(v_reinterpret_as_s32(v_src002));
v_dst003 = v_dst003 + v_cvt_f32(v_reinterpret_as_s32(v_src003));
v_dst100 = v_dst100 + v_cvt_f32(v_reinterpret_as_s32(v_src100));
v_dst101 = v_dst101 + v_cvt_f32(v_reinterpret_as_s32(v_src101));
v_dst102 = v_dst102 + v_cvt_f32(v_reinterpret_as_s32(v_src102));
v_dst103 = v_dst103 + v_cvt_f32(v_reinterpret_as_s32(v_src103));
v_dst200 = v_dst200 + v_cvt_f32(v_reinterpret_as_s32(v_src200));
v_dst201 = v_dst201 + v_cvt_f32(v_reinterpret_as_s32(v_src201));
v_dst202 = v_dst202 + v_cvt_f32(v_reinterpret_as_s32(v_src202));
v_dst203 = v_dst203 + v_cvt_f32(v_reinterpret_as_s32(v_src203));
v_store_interleave(dst + x * cn, v_dst000, v_dst100, v_dst200);
v_store_interleave(dst + (x + 4) * cn, v_dst001, v_dst101, v_dst201);
v_store_interleave(dst + (x + 8) * cn, v_dst002, v_dst102, v_dst202);
v_store_interleave(dst + (x + 12) * cn, v_dst003, v_dst103, v_dst203);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
void accProd_simd_(const ushort* src1, const ushort* src2, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_1src = v_load(src1 + x);
v_uint16x8 v_2src = v_load(src2 + x);
v_uint32x4 v_1src0, v_1src1, v_2src0, v_2src1;
v_expand(v_1src, v_1src0, v_1src1);
v_expand(v_2src, v_2src0, v_2src1);
v_float32x4 v_1float0 = v_cvt_f32(v_reinterpret_as_s32(v_1src0));
v_float32x4 v_1float1 = v_cvt_f32(v_reinterpret_as_s32(v_1src1));
v_float32x4 v_2float0 = v_cvt_f32(v_reinterpret_as_s32(v_2src0));
v_float32x4 v_2float1 = v_cvt_f32(v_reinterpret_as_s32(v_2src1));
v_float32x4 v_src0 = v_1float0 * v_2float0;
v_float32x4 v_src1 = v_1float1 * v_2float1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_src1);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint16x8 v_1src = v_load(src1 + x) & v_mask;
v_uint16x8 v_2src = v_load(src2 + x) & v_mask;
v_uint32x4 v_1src0, v_1src1, v_2src0, v_2src1;
v_expand(v_1src, v_1src0, v_1src1);
v_expand(v_2src, v_2src0, v_2src1);
v_float32x4 v_1float0 = v_cvt_f32(v_reinterpret_as_s32(v_1src0));
v_float32x4 v_1float1 = v_cvt_f32(v_reinterpret_as_s32(v_1src1));
v_float32x4 v_2float0 = v_cvt_f32(v_reinterpret_as_s32(v_2src0));
v_float32x4 v_2float1 = v_cvt_f32(v_reinterpret_as_s32(v_2src1));
v_float32x4 v_src0 = v_1float0 * v_2float0;
v_float32x4 v_src1 = v_1float1 * v_2float1;
v_store(dst + x, v_load(dst + x) + v_src0);
v_store(dst + x + 4, v_load(dst + x + 4) + v_src1);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_0 == v_mask);
v_uint16x8 v_1src0, v_1src1, v_1src2, v_2src0, v_2src1, v_2src2;
v_load_deinterleave(src1 + x * cn, v_1src0, v_1src1, v_1src2);
v_load_deinterleave(src2 + x * cn, v_2src0, v_2src1, v_2src2);
v_1src0 = v_1src0 & v_mask;
v_1src1 = v_1src1 & v_mask;
v_1src2 = v_1src2 & v_mask;
v_2src0 = v_2src0 & v_mask;
v_2src1 = v_2src1 & v_mask;
v_2src2 = v_2src2 & v_mask;
v_uint32x4 v_1src00, v_1src01, v_1src10, v_1src11, v_1src20, v_1src21, v_2src00, v_2src01, v_2src10, v_2src11, v_2src20, v_2src21;
v_expand(v_1src0, v_1src00, v_1src01);
v_expand(v_1src1, v_1src10, v_1src11);
v_expand(v_1src2, v_1src20, v_1src21);
v_expand(v_2src0, v_2src00, v_2src01);
v_expand(v_2src1, v_2src10, v_2src11);
v_expand(v_2src2, v_2src20, v_2src21);
v_float32x4 v_1float00 = v_cvt_f32(v_reinterpret_as_s32(v_1src00));
v_float32x4 v_1float01 = v_cvt_f32(v_reinterpret_as_s32(v_1src01));
v_float32x4 v_1float10 = v_cvt_f32(v_reinterpret_as_s32(v_1src10));
v_float32x4 v_1float11 = v_cvt_f32(v_reinterpret_as_s32(v_1src11));
v_float32x4 v_1float20 = v_cvt_f32(v_reinterpret_as_s32(v_1src20));
v_float32x4 v_1float21 = v_cvt_f32(v_reinterpret_as_s32(v_1src21));
v_float32x4 v_2float00 = v_cvt_f32(v_reinterpret_as_s32(v_2src00));
v_float32x4 v_2float01 = v_cvt_f32(v_reinterpret_as_s32(v_2src01));
v_float32x4 v_2float10 = v_cvt_f32(v_reinterpret_as_s32(v_2src10));
v_float32x4 v_2float11 = v_cvt_f32(v_reinterpret_as_s32(v_2src11));
v_float32x4 v_2float20 = v_cvt_f32(v_reinterpret_as_s32(v_2src20));
v_float32x4 v_2float21 = v_cvt_f32(v_reinterpret_as_s32(v_2src21));
v_float32x4 v_src00 = v_1float00 * v_2float00;
v_float32x4 v_src01 = v_1float01 * v_2float01;
v_float32x4 v_src10 = v_1float10 * v_2float10;
v_float32x4 v_src11 = v_1float11 * v_2float11;
v_float32x4 v_src20 = v_1float20 * v_2float20;
v_float32x4 v_src21 = v_1float21 * v_2float21;
v_float32x4 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 4) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
void accProd_simd_(const float* src1, const float* src2, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_store(dst + x, v_load(dst + x) + v_load(src1 + x) * v_load(src2 + x));
v_store(dst + x + 4, v_load(dst + x + 4) + v_load(src1 + x + 4) * v_load(src2 + x + 4));
}
}
else
{
v_uint32x4 v_0 = v_setzero_u32();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32_0 = v_load_expand_q(mask + x);
v_uint32x4 v_mask32_1 = v_load_expand_q(mask + x + 4);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_mask32_0 == v_0));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_mask32_1 == v_0));
v_store(dst + x, v_load(dst + x) + ((v_load(src1 + x) * v_load(src2 + x)) & v_mask0));
v_store(dst + x + 4, v_load(dst + x + 4) + ((v_load(src1 + x + 4) * v_load(src2 + x + 4)) & v_mask1));
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32_0 = v_load_expand_q(mask + x);
v_uint32x4 v_mask32_1 = v_load_expand_q(mask + x + 4);
v_float32x4 v_mask0 = v_reinterpret_as_f32(~(v_mask32_0 == v_0));
v_float32x4 v_mask1 = v_reinterpret_as_f32(~(v_mask32_1 == v_0));
v_float32x4 v_1src00, v_1src01, v_1src10, v_1src11, v_1src20, v_1src21;
v_float32x4 v_2src00, v_2src01, v_2src10, v_2src11, v_2src20, v_2src21;
v_load_deinterleave(src1 + x * cn, v_1src00, v_1src10, v_1src20);
v_load_deinterleave(src2 + x * cn, v_2src00, v_2src10, v_2src20);
v_load_deinterleave(src1 + (x + 4) * cn, v_1src01, v_1src11, v_1src21);
v_load_deinterleave(src2 + (x + 4) * cn, v_2src01, v_2src11, v_2src21);
v_float32x4 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 4) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + ((v_1src00 * v_2src00) & v_mask0), v_dst10 + ((v_1src10 * v_2src10) & v_mask0), v_dst20 + ((v_1src20 * v_2src20) & v_mask0));
v_store_interleave(dst + (x + 4) * cn, v_dst01 + ((v_1src01 * v_2src01) & v_mask1), v_dst11 + ((v_1src11 * v_2src11) & v_mask1), v_dst21 + ((v_1src21 * v_2src21) & v_mask1));
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
#if CV_SIMD128_64F
void accProd_simd_(const uchar* src1, const uchar* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_1int = v_load_expand(src1 + x);
v_uint16x8 v_2int = v_load_expand(src2 + x);
v_uint32x4 v_1int_0, v_1int_1, v_2int_0, v_2int_1;
v_expand(v_1int, v_1int_0, v_1int_1);
v_expand(v_2int, v_2int_0, v_2int_1);
v_int32x4 v_1int0 = v_reinterpret_as_s32(v_1int_0);
v_int32x4 v_1int1 = v_reinterpret_as_s32(v_1int_1);
v_int32x4 v_2int0 = v_reinterpret_as_s32(v_2int_0);
v_int32x4 v_2int1 = v_reinterpret_as_s32(v_2int_1);
v_float64x2 v_src0 = v_cvt_f64(v_1int0) * v_cvt_f64(v_2int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_1int0) * v_cvt_f64_high(v_2int0);
v_float64x2 v_src2 = v_cvt_f64(v_1int1) * v_cvt_f64(v_2int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_1int1) * v_cvt_f64_high(v_2int1);
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_1int = v_load_expand(src1 + x) & v_mask;
v_uint16x8 v_2int = v_load_expand(src2 + x) & v_mask;
v_uint32x4 v_1int_0, v_1int_1, v_2int_0, v_2int_1;
v_expand(v_1int, v_1int_0, v_1int_1);
v_expand(v_2int, v_2int_0, v_2int_1);
v_int32x4 v_1int0 = v_reinterpret_as_s32(v_1int_0);
v_int32x4 v_1int1 = v_reinterpret_as_s32(v_1int_1);
v_int32x4 v_2int0 = v_reinterpret_as_s32(v_2int_0);
v_int32x4 v_2int1 = v_reinterpret_as_s32(v_2int_1);
v_float64x2 v_src0 = v_cvt_f64(v_1int0) * v_cvt_f64(v_2int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_1int0) * v_cvt_f64_high(v_2int0);
v_float64x2 v_src2 = v_cvt_f64(v_1int1) * v_cvt_f64(v_2int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_1int1) * v_cvt_f64_high(v_2int1);
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 += v_src0;
v_dst1 += v_src1;
v_dst2 += v_src2;
v_dst3 += v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else if (cn == 3)
{
for (; x <= len - /*cVectorWidth*/16; x += cVectorWidth)
{
v_uint8x16 v_1src0, v_1src1, v_1src2, v_2src0, v_2src1, v_2src2;
v_load_deinterleave(src1 + x * cn, v_1src0, v_1src1, v_1src2);
v_load_deinterleave(src2 + x * cn, v_2src0, v_2src1, v_2src2);
v_uint16x8 v_1int0, v_1int1, v_1int2, v_2int0, v_2int1, v_2int2, dummy;
v_expand(v_1src0, v_1int0, dummy);
v_expand(v_1src1, v_1int1, dummy);
v_expand(v_1src2, v_1int2, dummy);
v_expand(v_2src0, v_2int0, dummy);
v_expand(v_2src1, v_2int1, dummy);
v_expand(v_2src2, v_2int2, dummy);
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_1int0 = v_1int0 & v_mask;
v_1int1 = v_1int1 & v_mask;
v_1int2 = v_1int2 & v_mask;
v_2int0 = v_2int0 & v_mask;
v_2int1 = v_2int1 & v_mask;
v_2int2 = v_2int2 & v_mask;
v_uint32x4 v_1int00, v_1int01, v_1int10, v_1int11, v_1int20, v_1int21;
v_uint32x4 v_2int00, v_2int01, v_2int10, v_2int11, v_2int20, v_2int21;
v_expand(v_1int0, v_1int00, v_1int01);
v_expand(v_1int1, v_1int10, v_1int11);
v_expand(v_1int2, v_1int20, v_1int21);
v_expand(v_2int0, v_2int00, v_2int01);
v_expand(v_2int1, v_2int10, v_2int11);
v_expand(v_2int2, v_2int20, v_2int21);
v_float64x2 v_src00 = v_cvt_f64(v_reinterpret_as_s32(v_1int00)) * v_cvt_f64(v_reinterpret_as_s32(v_2int00));
v_float64x2 v_src01 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int00)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int00));
v_float64x2 v_src02 = v_cvt_f64(v_reinterpret_as_s32(v_1int01)) * v_cvt_f64(v_reinterpret_as_s32(v_2int01));
v_float64x2 v_src03 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int01)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int01));
v_float64x2 v_src10 = v_cvt_f64(v_reinterpret_as_s32(v_1int10)) * v_cvt_f64(v_reinterpret_as_s32(v_2int10));
v_float64x2 v_src11 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int10)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int10));
v_float64x2 v_src12 = v_cvt_f64(v_reinterpret_as_s32(v_1int11)) * v_cvt_f64(v_reinterpret_as_s32(v_2int11));
v_float64x2 v_src13 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int11)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int11));
v_float64x2 v_src20 = v_cvt_f64(v_reinterpret_as_s32(v_1int20)) * v_cvt_f64(v_reinterpret_as_s32(v_2int20));
v_float64x2 v_src21 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int20)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int20));
v_float64x2 v_src22 = v_cvt_f64(v_reinterpret_as_s32(v_1int21)) * v_cvt_f64(v_reinterpret_as_s32(v_2int21));
v_float64x2 v_src23 = v_cvt_f64_high(v_reinterpret_as_s32(v_1int21)) * v_cvt_f64_high(v_reinterpret_as_s32(v_2int21));
v_float64x2 v_dst00, v_dst01, v_dst02, v_dst03, v_dst10, v_dst11, v_dst12, v_dst13, v_dst20, v_dst21, v_dst22, v_dst23;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_load_deinterleave(dst + (x + 4) * cn, v_dst02, v_dst12, v_dst22);
v_load_deinterleave(dst + (x + 6) * cn, v_dst03, v_dst13, v_dst23);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
v_store_interleave(dst + (x + 4) * cn, v_dst02 + v_src02, v_dst12 + v_src12, v_dst22 + v_src22);
v_store_interleave(dst + (x + 6) * cn, v_dst03 + v_src03, v_dst13 + v_src13, v_dst23 + v_src23);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
void accProd_simd_(const ushort* src1, const ushort* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_1src = v_load(src1 + x);
v_uint16x8 v_2src = v_load(src2 + x);
v_uint32x4 v_1int_0, v_1int_1, v_2int_0, v_2int_1;
v_expand(v_1src, v_1int_0, v_1int_1);
v_expand(v_2src, v_2int_0, v_2int_1);
v_int32x4 v_1int0 = v_reinterpret_as_s32(v_1int_0);
v_int32x4 v_1int1 = v_reinterpret_as_s32(v_1int_1);
v_int32x4 v_2int0 = v_reinterpret_as_s32(v_2int_0);
v_int32x4 v_2int1 = v_reinterpret_as_s32(v_2int_1);
v_float64x2 v_src0 = v_cvt_f64(v_1int0) * v_cvt_f64(v_2int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_1int0) * v_cvt_f64_high(v_2int0);
v_float64x2 v_src2 = v_cvt_f64(v_1int1) * v_cvt_f64(v_2int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_1int1) * v_cvt_f64_high(v_2int1);
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else
{
v_uint16x8 v_0 = v_setzero_u16();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_1src = v_load(src1 + x);
v_uint16x8 v_2src = v_load(src2 + x);
v_1src = v_1src & v_mask;
v_2src = v_2src & v_mask;
v_uint32x4 v_1int_0, v_1int_1, v_2int_0, v_2int_1;
v_expand(v_1src, v_1int_0, v_1int_1);
v_expand(v_2src, v_2int_0, v_2int_1);
v_int32x4 v_1int0 = v_reinterpret_as_s32(v_1int_0);
v_int32x4 v_1int1 = v_reinterpret_as_s32(v_1int_1);
v_int32x4 v_2int0 = v_reinterpret_as_s32(v_2int_0);
v_int32x4 v_2int1 = v_reinterpret_as_s32(v_2int_1);
v_float64x2 v_src0 = v_cvt_f64(v_1int0) * v_cvt_f64(v_2int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_1int0) * v_cvt_f64_high(v_2int0);
v_float64x2 v_src2 = v_cvt_f64(v_1int1) * v_cvt_f64(v_2int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_1int1) * v_cvt_f64_high(v_2int1);
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 = v_dst0 + v_src0;
v_dst1 = v_dst1 + v_src1;
v_dst2 = v_dst2 + v_src2;
v_dst3 = v_dst3 + v_src3;
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_mask = v_load_expand(mask + x);
v_mask = ~(v_mask == v_0);
v_uint16x8 v_1src0, v_1src1, v_1src2, v_2src0, v_2src1, v_2src2;
v_load_deinterleave(src1 + x * cn, v_1src0, v_1src1, v_1src2);
v_load_deinterleave(src2 + x * cn, v_2src0, v_2src1, v_2src2);
v_1src0 = v_1src0 & v_mask;
v_1src1 = v_1src1 & v_mask;
v_1src2 = v_1src2 & v_mask;
v_2src0 = v_2src0 & v_mask;
v_2src1 = v_2src1 & v_mask;
v_2src2 = v_2src2 & v_mask;
v_uint32x4 v_1int_00, v_1int_01, v_2int_00, v_2int_01;
v_uint32x4 v_1int_10, v_1int_11, v_2int_10, v_2int_11;
v_uint32x4 v_1int_20, v_1int_21, v_2int_20, v_2int_21;
v_expand(v_1src0, v_1int_00, v_1int_01);
v_expand(v_1src1, v_1int_10, v_1int_11);
v_expand(v_1src2, v_1int_20, v_1int_21);
v_expand(v_2src0, v_2int_00, v_2int_01);
v_expand(v_2src1, v_2int_10, v_2int_11);
v_expand(v_2src2, v_2int_20, v_2int_21);
v_int32x4 v_1int00 = v_reinterpret_as_s32(v_1int_00);
v_int32x4 v_1int01 = v_reinterpret_as_s32(v_1int_01);
v_int32x4 v_1int10 = v_reinterpret_as_s32(v_1int_10);
v_int32x4 v_1int11 = v_reinterpret_as_s32(v_1int_11);
v_int32x4 v_1int20 = v_reinterpret_as_s32(v_1int_20);
v_int32x4 v_1int21 = v_reinterpret_as_s32(v_1int_21);
v_int32x4 v_2int00 = v_reinterpret_as_s32(v_2int_00);
v_int32x4 v_2int01 = v_reinterpret_as_s32(v_2int_01);
v_int32x4 v_2int10 = v_reinterpret_as_s32(v_2int_10);
v_int32x4 v_2int11 = v_reinterpret_as_s32(v_2int_11);
v_int32x4 v_2int20 = v_reinterpret_as_s32(v_2int_20);
v_int32x4 v_2int21 = v_reinterpret_as_s32(v_2int_21);
v_float64x2 v_src00 = v_cvt_f64(v_1int00) * v_cvt_f64(v_2int00);
v_float64x2 v_src01 = v_cvt_f64_high(v_1int00) * v_cvt_f64_high(v_2int00);
v_float64x2 v_src02 = v_cvt_f64(v_1int01) * v_cvt_f64(v_2int01);
v_float64x2 v_src03 = v_cvt_f64_high(v_1int01) * v_cvt_f64_high(v_2int01);
v_float64x2 v_src10 = v_cvt_f64(v_1int10) * v_cvt_f64(v_2int10);
v_float64x2 v_src11 = v_cvt_f64_high(v_1int10) * v_cvt_f64_high(v_2int10);
v_float64x2 v_src12 = v_cvt_f64(v_1int11) * v_cvt_f64(v_2int11);
v_float64x2 v_src13 = v_cvt_f64_high(v_1int11) * v_cvt_f64_high(v_2int11);
v_float64x2 v_src20 = v_cvt_f64(v_1int20) * v_cvt_f64(v_2int20);
v_float64x2 v_src21 = v_cvt_f64_high(v_1int20) * v_cvt_f64_high(v_2int20);
v_float64x2 v_src22 = v_cvt_f64(v_1int21) * v_cvt_f64(v_2int21);
v_float64x2 v_src23 = v_cvt_f64_high(v_1int21) * v_cvt_f64_high(v_2int21);
v_float64x2 v_dst00, v_dst01, v_dst02, v_dst03;
v_float64x2 v_dst10, v_dst11, v_dst12, v_dst13;
v_float64x2 v_dst20, v_dst21, v_dst22, v_dst23;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_load_deinterleave(dst + (x + 4) * cn, v_dst02, v_dst12, v_dst22);
v_load_deinterleave(dst + (x + 6) * cn, v_dst03, v_dst13, v_dst23);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
v_store_interleave(dst + (x + 4) * cn, v_dst02 + v_src02, v_dst12 + v_src12, v_dst22 + v_src22);
v_store_interleave(dst + (x + 6) * cn, v_dst03 + v_src03, v_dst13 + v_src13, v_dst23 + v_src23);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
void accProd_simd_(const float* src1, const float* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float32x4 v_1src = v_load(src1 + x);
v_float32x4 v_2src = v_load(src2 + x);
v_float64x2 v_1src0 = v_cvt_f64(v_1src);
v_float64x2 v_1src1 = v_cvt_f64_high(v_1src);
v_float64x2 v_2src0 = v_cvt_f64(v_2src);
v_float64x2 v_2src1 = v_cvt_f64_high(v_2src);
v_store(dst + x, v_load(dst + x) + (v_1src0 * v_2src0));
v_store(dst + x + 2, v_load(dst + x + 2) + (v_1src1 * v_2src1));
}
}
else
{
v_uint32x4 v_0 = v_setzero_u32();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask = v_load_expand_q(mask + x);
v_mask = ~(v_mask == v_0);
v_float32x4 v_1src = v_load(src1 + x);
v_float32x4 v_2src = v_load(src2 + x);
v_1src = v_1src & v_reinterpret_as_f32(v_mask);
v_2src = v_2src & v_reinterpret_as_f32(v_mask);
v_float64x2 v_1src0 = v_cvt_f64(v_1src);
v_float64x2 v_1src1 = v_cvt_f64_high(v_1src);
v_float64x2 v_2src0 = v_cvt_f64(v_2src);
v_float64x2 v_2src1 = v_cvt_f64_high(v_2src);
v_store(dst + x, v_load(dst + x) + (v_1src0 * v_2src0));
v_store(dst + x + 2, v_load(dst + x + 2) + (v_1src1 * v_2src1));
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask = v_load_expand_q(mask + x);
v_mask = ~(v_mask == v_0);
v_float32x4 v_1src0, v_1src1, v_1src2, v_2src0, v_2src1, v_2src2;
v_load_deinterleave(src1 + x * cn, v_1src0, v_1src1, v_1src2);
v_load_deinterleave(src2 + x * cn, v_2src0, v_2src1, v_2src2);
v_1src0 = v_1src0 & v_reinterpret_as_f32(v_mask);
v_1src1 = v_1src1 & v_reinterpret_as_f32(v_mask);
v_1src2 = v_1src2 & v_reinterpret_as_f32(v_mask);
v_2src0 = v_2src0 & v_reinterpret_as_f32(v_mask);
v_2src1 = v_2src1 & v_reinterpret_as_f32(v_mask);
v_2src2 = v_2src2 & v_reinterpret_as_f32(v_mask);
v_float64x2 v_src00 = v_cvt_f64(v_1src0) * v_cvt_f64(v_2src0);
v_float64x2 v_src01 = v_cvt_f64_high(v_1src0) * v_cvt_f64_high(v_2src0);
v_float64x2 v_src10 = v_cvt_f64(v_1src1) * v_cvt_f64(v_2src1);
v_float64x2 v_src11 = v_cvt_f64_high(v_1src1) * v_cvt_f64_high(v_2src1);
v_float64x2 v_src20 = v_cvt_f64(v_1src2) * v_cvt_f64(v_2src2);
v_float64x2 v_src21 = v_cvt_f64_high(v_1src2) * v_cvt_f64_high(v_2src2);
v_float64x2 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
void accProd_simd_(const double* src1, const double* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float64x2 v_src00 = v_load(src1 + x);
v_float64x2 v_src01 = v_load(src1 + x + 2);
v_float64x2 v_src10 = v_load(src2 + x);
v_float64x2 v_src11 = v_load(src2 + x + 2);
v_store(dst + x, v_load(dst + x) + (v_src00 * v_src10));
v_store(dst + x + 2, v_load(dst + x + 2) + (v_src01 * v_src11));
}
}
else
{
v_uint64x2 v_0 = v_setzero_u64();
if (cn == 1)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_mask32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_src00 = v_load(src1 + x);
v_float64x2 v_src01 = v_load(src1 + x + 2);
v_float64x2 v_src10 = v_load(src2 + x);
v_float64x2 v_src11 = v_load(src2 + x + 2);
v_store(dst + x, v_load(dst + x) + ((v_src00 * v_src10) & v_mask0));
v_store(dst + x + 2, v_load(dst + x + 2) + ((v_src01 * v_src11) & v_mask1));
}
}
else if (cn == 3)
{
for (; x <= len - cVectorWidth; x += cVectorWidth)
{
v_uint32x4 v_mask32 = v_load_expand_q(mask + x);
v_uint64x2 v_masku640, v_masku641;
v_expand(v_mask32, v_masku640, v_masku641);
v_float64x2 v_mask0 = v_reinterpret_as_f64(~(v_masku640 == v_0));
v_float64x2 v_mask1 = v_reinterpret_as_f64(~(v_masku641 == v_0));
v_float64x2 v_1src00, v_1src01, v_1src10, v_1src11, v_1src20, v_1src21;
v_float64x2 v_2src00, v_2src01, v_2src10, v_2src11, v_2src20, v_2src21;
v_load_deinterleave(src1 + x * cn, v_1src00, v_1src10, v_1src20);
v_load_deinterleave(src1 + (x + 2) * cn, v_1src01, v_1src11, v_1src21);
v_load_deinterleave(src2 + x * cn, v_2src00, v_2src10, v_2src20);
v_load_deinterleave(src2 + (x + 2) * cn, v_2src01, v_2src11, v_2src21);
v_float64x2 v_src00 = (v_1src00 & v_mask0) * v_2src00;
v_float64x2 v_src01 = (v_1src01 & v_mask1) * v_2src01;
v_float64x2 v_src10 = (v_1src10 & v_mask0) * v_2src10;
v_float64x2 v_src11 = (v_1src11 & v_mask1) * v_2src11;
v_float64x2 v_src20 = (v_1src20 & v_mask0) * v_2src20;
v_float64x2 v_src21 = (v_1src21 & v_mask1) * v_2src21;
v_float64x2 v_dst00, v_dst01, v_dst10, v_dst11, v_dst20, v_dst21;
v_load_deinterleave(dst + x * cn, v_dst00, v_dst10, v_dst20);
v_load_deinterleave(dst + (x + 2) * cn, v_dst01, v_dst11, v_dst21);
v_store_interleave(dst + x * cn, v_dst00 + v_src00, v_dst10 + v_src10, v_dst20 + v_src20);
v_store_interleave(dst + (x + 2) * cn, v_dst01 + v_src01, v_dst11 + v_src11, v_dst21 + v_src21);
}
}
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
#else
void accProd_simd_(const uchar* src1, const uchar* src2, double* dst, const uchar* mask, int len, int cn)
{
accProd_general_(src1, src2, dst, mask, len, cn, 0);
}
void accProd_simd_(const ushort* src1, const ushort* src2, double* dst, const uchar* mask, int len, int cn)
{
accProd_general_(src1, src2, dst, mask, len, cn, 0);
}
void accProd_simd_(const float* src1, const float* src2, double* dst, const uchar* mask, int len, int cn)
{
accProd_general_(src1, src2, dst, mask, len, cn, 0);
}
void accProd_simd_(const double* src1, const double* src2, double* dst, const uchar* mask, int len, int cn)
{
accProd_general_(src1, src2, dst, mask, len, cn, 0);
}
#endif
// running weight accumulate optimized by universal intrinsic
void accW_simd_(const uchar* src, float* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float32x4 v_alpha = v_setall_f32((float)alpha);
const v_float32x4 v_beta = v_setall_f32((float)(1.0f - alpha));
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint8x16 v_src = v_load(src + x);
v_uint16x8 v_src0, v_src1;
v_expand(v_src, v_src0, v_src1);
v_uint32x4 v_src00, v_src01, v_src10, v_src11;
v_expand(v_src0, v_src00, v_src01);
v_expand(v_src1, v_src10, v_src11);
v_float32x4 v_dst00 = v_load(dst + x);
v_float32x4 v_dst01 = v_load(dst + x + 4);
v_float32x4 v_dst10 = v_load(dst + x + 8);
v_float32x4 v_dst11 = v_load(dst + x + 12);
v_dst00 = (v_dst00 * v_beta) + (v_cvt_f32(v_reinterpret_as_s32(v_src00)) * v_alpha);
v_dst01 = (v_dst01 * v_beta) + (v_cvt_f32(v_reinterpret_as_s32(v_src01)) * v_alpha);
v_dst10 = (v_dst10 * v_beta) + (v_cvt_f32(v_reinterpret_as_s32(v_src10)) * v_alpha);
v_dst11 = (v_dst11 * v_beta) + (v_cvt_f32(v_reinterpret_as_s32(v_src11)) * v_alpha);
v_store(dst + x, v_dst00);
v_store(dst + x + 4, v_dst01);
v_store(dst + x + 8, v_dst10);
v_store(dst + x + 12, v_dst11);
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
void accW_simd_(const ushort* src, float* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float32x4 v_alpha = v_setall_f32((float)alpha);
const v_float32x4 v_beta = v_setall_f32((float)(1.0f - alpha));
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_int0, v_int1;
v_expand(v_src, v_int0, v_int1);
v_float32x4 v_src0 = v_cvt_f32(v_reinterpret_as_s32(v_int0));
v_float32x4 v_src1 = v_cvt_f32(v_reinterpret_as_s32(v_int1));
v_src0 = v_src0 * v_alpha;
v_src1 = v_src1 * v_alpha;
v_float32x4 v_dst0 = v_load(dst + x) * v_beta;
v_float32x4 v_dst1 = v_load(dst + x + 4) * v_beta;
v_store(dst + x, v_dst0 + v_src0);
v_store(dst + x + 4, v_dst1 + v_src1);
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
void accW_simd_(const float* src, float* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float32x4 v_alpha = v_setall_f32((float)alpha);
const v_float32x4 v_beta = v_setall_f32((float)(1.0f - alpha));
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_store(dst + x, ((v_load(dst + x) * v_beta) + (v_load(src + x) * v_alpha)));
v_store(dst + x + 4, ((v_load(dst + x + 4) * v_beta) + (v_load(src + x + 4) * v_alpha)));
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
#if CV_SIMD128_64F
void accW_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float64x2 v_alpha = v_setall_f64(alpha);
const v_float64x2 v_beta = v_setall_f64(1.0f - alpha);
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src16 = v_load_expand(src + x);
v_uint32x4 v_int_0, v_int_1;
v_expand(v_src16, v_int_0, v_int_1);
v_int32x4 v_int0 = v_reinterpret_as_s32(v_int_0);
v_int32x4 v_int1 = v_reinterpret_as_s32(v_int_1);
v_float64x2 v_src0 = v_cvt_f64(v_int0);
v_float64x2 v_src1 = v_cvt_f64_high(v_int0);
v_float64x2 v_src2 = v_cvt_f64(v_int1);
v_float64x2 v_src3 = v_cvt_f64_high(v_int1);
v_float64x2 v_dst0 = v_load(dst + x);
v_float64x2 v_dst1 = v_load(dst + x + 2);
v_float64x2 v_dst2 = v_load(dst + x + 4);
v_float64x2 v_dst3 = v_load(dst + x + 6);
v_dst0 = (v_dst0 * v_beta) + (v_src0 * v_alpha);
v_dst1 = (v_dst1 * v_beta) + (v_src1 * v_alpha);
v_dst2 = (v_dst2 * v_beta) + (v_src2 * v_alpha);
v_dst3 = (v_dst3 * v_beta) + (v_src3 * v_alpha);
v_store(dst + x, v_dst0);
v_store(dst + x + 2, v_dst1);
v_store(dst + x + 4, v_dst2);
v_store(dst + x + 6, v_dst3);
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
void accW_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float64x2 v_alpha = v_setall_f64(alpha);
const v_float64x2 v_beta = v_setall_f64(1.0f - alpha);
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_uint16x8 v_src = v_load(src + x);
v_uint32x4 v_int_0, v_int_1;
v_expand(v_src, v_int_0, v_int_1);
v_int32x4 v_int0 = v_reinterpret_as_s32(v_int_0);
v_int32x4 v_int1 = v_reinterpret_as_s32(v_int_1);
v_float64x2 v_src00 = v_cvt_f64(v_int0);
v_float64x2 v_src01 = v_cvt_f64_high(v_int0);
v_float64x2 v_src10 = v_cvt_f64(v_int1);
v_float64x2 v_src11 = v_cvt_f64_high(v_int1);
v_float64x2 v_dst00 = v_load(dst + x);
v_float64x2 v_dst01 = v_load(dst + x + 2);
v_float64x2 v_dst10 = v_load(dst + x + 4);
v_float64x2 v_dst11 = v_load(dst + x + 6);
v_dst00 = (v_dst00 * v_beta) + (v_src00 * v_alpha);
v_dst01 = (v_dst01 * v_beta) + (v_src01 * v_alpha);
v_dst10 = (v_dst10 * v_beta) + (v_src10 * v_alpha);
v_dst11 = (v_dst11 * v_beta) + (v_src11 * v_alpha);
v_store(dst + x, v_dst00);
v_store(dst + x + 2, v_dst01);
v_store(dst + x + 4, v_dst10);
v_store(dst + x + 6, v_dst11);
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
void accW_simd_(const float* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float64x2 v_alpha = v_setall_f64(alpha);
const v_float64x2 v_beta = v_setall_f64(1.0f - alpha);
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float32x4 v_src0 = v_load(src + x);
v_float32x4 v_src1 = v_load(src + x + 4);
v_float64x2 v_src00 = v_cvt_f64(v_src0);
v_float64x2 v_src01 = v_cvt_f64_high(v_src0);
v_float64x2 v_src10 = v_cvt_f64(v_src1);
v_float64x2 v_src11 = v_cvt_f64_high(v_src1);
v_store(dst + x, ((v_load(dst + x) * v_beta) + (v_src00 * v_alpha)));
v_store(dst + x + 2, ((v_load(dst + x + 2) * v_beta) + (v_src01 * v_alpha)));
v_store(dst + x + 4, ((v_load(dst + x + 4) * v_beta) + (v_src10 * v_alpha)));
v_store(dst + x + 6, ((v_load(dst + x + 6) * v_beta) + (v_src11 * v_alpha)));
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
void accW_simd_(const double* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const v_float64x2 v_alpha = v_setall_f64(alpha);
const v_float64x2 v_beta = v_setall_f64(1.0f - alpha);
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for (; x <= size - cVectorWidth; x += cVectorWidth)
{
v_float64x2 v_src0 = v_load(src + x);
v_float64x2 v_src1 = v_load(src + x + 2);
v_store(dst + x, ((v_load(dst + x) * v_beta) + (v_src0 * v_alpha)));
v_store(dst + x + 2, ((v_load(dst + x + 2) * v_beta) + (v_src1 * v_alpha)));
}
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
#else
void accW_simd_(const uchar* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
accW_general_(src, dst, mask, len, cn, alpha, 0);
}
void accW_simd_(const ushort* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
accW_general_(src, dst, mask, len, cn, alpha, 0);
}
void accW_simd_(const float* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
accW_general_(src, dst, mask, len, cn, alpha, 0);
}
void accW_simd_(const double* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
accW_general_(src, dst, mask, len, cn, alpha, 0);
}
#endif // CV_SIMD128_64F
#endif // CV_SIMD128
#if CV_AVX
// accumulate optimized by AVX
void acc_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src = _mm256_loadu_ps(src + x);
__m256 v_dst = _mm256_loadu_ps(dst + x);
v_dst = _mm256_add_ps(v_src, v_dst);
_mm256_storeu_ps(dst + x, v_dst);
}
acc_general_(src, dst, mask, len, cn, x);
}
else
{
acc_simd_(src, dst, mask, len, cn);
}
}
void acc_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src = _mm256_loadu_ps(src + x);
__m256d v_src0 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src, 0));
__m256d v_src1 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src, 1));
__m256d v_dst0 = _mm256_loadu_pd(dst + x);
__m256d v_dst1 = _mm256_loadu_pd(dst + x + 4);
v_dst0 = _mm256_add_pd(v_src0, v_dst0);
v_dst1 = _mm256_add_pd(v_src1, v_dst1);
_mm256_storeu_pd(dst + x, v_dst0);
_mm256_storeu_pd(dst + x + 4, v_dst1);
}
acc_general_(src, dst, mask, len, cn, x);
}
else
{
acc_simd_(src, dst, mask, len, cn);
}
}
void acc_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256d v_src = _mm256_loadu_pd(src + x);
__m256d v_dst = _mm256_loadu_pd(dst + x);
v_dst = _mm256_add_pd(v_dst, v_src);
_mm256_storeu_pd(dst + x, v_dst);
}
acc_general_(src, dst, mask, len, cn, x);
}
else
{
acc_simd_(src, dst, mask, len, cn);
}
}
// square accumulate optimized by avx
void accSqr_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src = _mm256_loadu_ps(src + x);
__m256 v_dst = _mm256_loadu_ps(dst + x);
v_src = _mm256_mul_ps(v_src, v_src);
v_dst = _mm256_add_ps(v_src, v_dst);
_mm256_storeu_ps(dst + x, v_dst);
}
accSqr_general_(src, dst, mask, len, cn, x);
}
else
{
accSqr_simd_(src, dst, mask, len, cn);
}
}
void accSqr_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src = _mm256_loadu_ps(src + x);
__m256d v_src0 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src,0));
__m256d v_src1 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src,1));
__m256d v_dst0 = _mm256_loadu_pd(dst + x);
__m256d v_dst1 = _mm256_loadu_pd(dst + x + 4);
v_src0 = _mm256_mul_pd(v_src0, v_src0);
v_src1 = _mm256_mul_pd(v_src1, v_src1);
v_dst0 = _mm256_add_pd(v_src0, v_dst0);
v_dst1 = _mm256_add_pd(v_src1, v_dst1);
_mm256_storeu_pd(dst + x, v_dst0);
_mm256_storeu_pd(dst + x + 4, v_dst1);
}
accSqr_general_(src, dst, mask, len, cn, x);
}
else
{
accSqr_simd_(src, dst, mask, len, cn);
}
}
void accSqr_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256d v_src = _mm256_loadu_pd(src + x);
__m256d v_dst = _mm256_loadu_pd(dst + x);
v_src = _mm256_mul_pd(v_src, v_src);
v_dst = _mm256_add_pd(v_dst, v_src);
_mm256_storeu_pd(dst + x, v_dst);
}
accSqr_general_(src, dst, mask, len, cn, x);
}
else
{
accSqr_simd_(src, dst, mask, len, cn);
}
}
// product accumulate optimized by avx
void accProd_avx_32f(const float* src1, const float* src2, float* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src0 = _mm256_loadu_ps(src1 + x);
__m256 v_src1 = _mm256_loadu_ps(src2 + x);
__m256 v_dst = _mm256_loadu_ps(dst + x);
__m256 v_src = _mm256_mul_ps(v_src0, v_src1);
v_dst = _mm256_add_ps(v_src, v_dst);
_mm256_storeu_ps(dst + x, v_dst);
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
else
{
accProd_simd_(src1, src2, dst, mask, len, cn);
}
}
void accProd_avx_32f64f(const float* src1, const float* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_1src = _mm256_loadu_ps(src1 + x);
__m256 v_2src = _mm256_loadu_ps(src2 + x);
__m256d v_src00 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_1src,0));
__m256d v_src01 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_1src,1));
__m256d v_src10 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_2src,0));
__m256d v_src11 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_2src,1));
__m256d v_dst0 = _mm256_loadu_pd(dst + x);
__m256d v_dst1 = _mm256_loadu_pd(dst + x + 4);
__m256d v_src0 = _mm256_mul_pd(v_src00, v_src10);
__m256d v_src1 = _mm256_mul_pd(v_src01, v_src11);
v_dst0 = _mm256_add_pd(v_src0, v_dst0);
v_dst1 = _mm256_add_pd(v_src1, v_dst1);
_mm256_storeu_pd(dst + x, v_dst0);
_mm256_storeu_pd(dst + x + 4, v_dst1);
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
else
{
accProd_simd_(src1, src2, dst, mask, len, cn);
}
}
void accProd_avx_64f(const double* src1, const double* src2, double* dst, const uchar* mask, int len, int cn)
{
int x = 0;
const int cVectorWidth = 4;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256d v_src0 = _mm256_loadu_pd(src1 + x);
__m256d v_src1 = _mm256_loadu_pd(src2 + x);
__m256d v_dst = _mm256_loadu_pd(dst + x);
v_src0 = _mm256_mul_pd(v_src0, v_src1);
v_dst = _mm256_add_pd(v_dst, v_src0);
_mm256_storeu_pd(dst + x, v_dst);
}
accProd_general_(src1, src2, dst, mask, len, cn, x);
}
else
{
accProd_simd_(src1, src2, dst, mask, len, cn);
}
}
// running weight accumulate optimized by avx
void accW_avx_32f(const float* src, float* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const __m256 v_alpha = _mm256_set1_ps((float)alpha);
const __m256 v_beta = _mm256_set1_ps((float)(1.0f - alpha));
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
_mm256_storeu_ps(dst + x, _mm256_add_ps(_mm256_mul_ps(_mm256_loadu_ps(dst + x), v_beta), _mm256_mul_ps(_mm256_loadu_ps(src + x), v_alpha)));
_mm256_storeu_ps(dst + x + 8, _mm256_add_ps(_mm256_mul_ps(_mm256_loadu_ps(dst + x + 8), v_beta), _mm256_mul_ps(_mm256_loadu_ps(src + x + 8), v_alpha)));
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
else
{
accW_simd_(src, dst, mask, len, cn, alpha);
}
}
void accW_avx_32f64f(const float* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const __m256d v_alpha = _mm256_set1_pd(alpha);
const __m256d v_beta = _mm256_set1_pd(1.0f - alpha);
const int cVectorWidth = 16;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256 v_src0 = _mm256_loadu_ps(src + x);
__m256 v_src1 = _mm256_loadu_ps(src + x + 8);
__m256d v_src00 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src0,0));
__m256d v_src01 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src0,1));
__m256d v_src10 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src1,0));
__m256d v_src11 = _mm256_cvtps_pd(_mm256_extractf128_ps(v_src1,1));
_mm256_storeu_pd(dst + x, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x), v_beta), _mm256_mul_pd(v_src00, v_alpha)));
_mm256_storeu_pd(dst + x + 4, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x + 4), v_beta), _mm256_mul_pd(v_src01, v_alpha)));
_mm256_storeu_pd(dst + x + 8, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x + 8), v_beta), _mm256_mul_pd(v_src10, v_alpha)));
_mm256_storeu_pd(dst + x + 12, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x + 12), v_beta), _mm256_mul_pd(v_src11, v_alpha)));
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
else
{
accW_simd_(src, dst, mask, len, cn, alpha);
}
}
void accW_avx_64f(const double* src, double* dst, const uchar* mask, int len, int cn, double alpha)
{
int x = 0;
const __m256d v_alpha = _mm256_set1_pd(alpha);
const __m256d v_beta = _mm256_set1_pd(1.0f - alpha);
const int cVectorWidth = 8;
if (!mask)
{
int size = len * cn;
for ( ; x <= size - cVectorWidth ; x += cVectorWidth)
{
__m256d v_src0 = _mm256_loadu_pd(src + x);
__m256d v_src1 = _mm256_loadu_pd(src + x + 4);
_mm256_storeu_pd(dst + x, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x), v_beta), _mm256_mul_pd(v_src0, v_alpha)));
_mm256_storeu_pd(dst + x + 4, _mm256_add_pd(_mm256_mul_pd(_mm256_loadu_pd(dst + x + 4), v_beta), _mm256_mul_pd(v_src1, v_alpha)));
}
accW_general_(src, dst, mask, len, cn, alpha, x);
}
else
{
accW_simd_(src, dst, mask, len, cn, alpha);
}
}
#endif
#endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY
CV_CPU_OPTIMIZATION_NAMESPACE_END
} // namespace cv
///* End of file. */
|
#include <vector>
#include "arch_graph.h"
#include "bsgs.h"
#include "nauty.h"
#include "perm_set.h"
namespace
{
int nauty_generator_degree;
cgtl::PermSet nauty_generators;
void nauty_save_generator(int, int *perm, int *, int, int, int)
{
std::vector<unsigned> tmp(nauty_generator_degree);
for (int i = 0; i < nauty_generator_degree; ++i)
tmp[i] = perm[i] + 1;
nauty_generators.emplace(tmp);
}
void nauty_free()
{
naugraph_freedyn();
nautil_freedyn();
nauty_freedyn();
}
} // anonymous namespace
namespace cgtl
{
PermGroup ArchGraph::update_automorphisms_nauty(
BSGS::Options const *bsgs_options)
{
// allocate nauty structures
DYNALLSTAT(graph, g, g_sz);
DYNALLSTAT(int, lab, lab_sz);
DYNALLSTAT(int, ptn, ptn_sz);
DYNALLSTAT(int, orbits, orbits_sz);
static DEFAULTOPTIONS_GRAPH(options);
options.defaultptn = FALSE;
options.userautomproc = nauty_save_generator;
statsblk stats;
int cts = static_cast<int>(_channel_types.size());
int cts_log2 = 0; while (cts >>= 1) ++cts_log2;
int n_orig = static_cast<int>(boost::num_vertices(_adj));
int n = static_cast<int>(n_orig * (cts_log2 + 1u));
int m = SETWORDSNEEDED(n);
#ifndef NDBUG
nauty_check(WORDSIZE, m, n, NAUTYVERSIONID);
#endif
DYNALLOC2(graph, g, g_sz, m, n, "malloc graph");
DYNALLOC1(int, lab, lab_sz, n, "malloc lab");
DYNALLOC1(int, ptn, ptn_sz, n, "malloc ptn");
DYNALLOC1(int, orbits, orbits_sz, n, "malloc orbits");
// construct nauty graph
EMPTYGRAPH(g, m, n);
std::vector<vertices_size_type> processor_type_offsets(
_processor_types.size());
std::vector<vertices_size_type> processor_type_counters(
_processor_types.size(), 0u);
vertices_size_type offs_accu = 0u;
for (processor_type_size_type i = 0u; i < _processor_types.size(); ++i) {
processor_type_offsets[i] = offs_accu;
offs_accu += _processor_type_instances[i];
}
/* node numbering:
* ... ... ...
* | | |
* (n+1)---(n+2)-- ... --(n+n)
* | | |
* (1)-----(2)--- ... ---(n)
*/
for (int level = 0; level <= cts_log2; ++level) {
if (level > 0) {
for (int v = 0; v < n_orig; ++v)
ADDONEEDGE(g, v + level * n_orig, v + (level - 1) * n_orig, m);
}
for (auto e : boost::make_iterator_range(boost::edges(_adj))) {
int t = static_cast<int>(_adj[e].type) + 1;
if (t & (1 << level)){
int source = static_cast<int>(boost::source(e, _adj));
int target = static_cast<int>(boost::target(e, _adj));
ADDONEEDGE(g, source + level * n_orig, target + level * n_orig, m);
}
t >>= 1u;
}
}
for (int level = 0; level <= cts_log2; ++level) {
std::fill(processor_type_counters.begin(),
processor_type_counters.end(), 0u);
for (int v = 0; v < n_orig; ++v) {
processor_type_size_type t = _adj[v].type;
vertices_size_type offs =
processor_type_offsets[t] + processor_type_counters[t];
lab[offs + level * n_orig] = v + level * n_orig;
ptn[offs + level * n_orig] =
++processor_type_counters[t] != _processor_type_instances[t];
}
}
// call nauty
nauty_generators.clear();
nauty_generator_degree = n_orig;
densenauty(g, lab, ptn, orbits, &options, &stats, m, n, nullptr);
DYNFREE(g, g_sz);
DYNFREE(lab, lab_sz);
DYNFREE(ptn, ptn_sz);
DYNFREE(orbits, orbits_sz);
nauty_free();
return PermGroup(BSGS(nauty_generator_degree, nauty_generators, bsgs_options));
}
} // namespace cgtl
|
/*
EXECUTE THE CIRCULAR MANEUVER
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//HEADER FILES
#include "maneuvers/flip_maneuver.h"
#include <iostream>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace Eigen;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
flip_traverse::flip_traverse(const ros::NodeHandle& nh): nh_(nh)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SUBSCRIBER DEFINITION
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Subscribe to the current position and attitude of the quadrotor
mavposeSub_ = nh_.subscribe("/mavros/local_position/pose", 50, &flip_traverse::mavposeCallback, this,ros::TransportHints().tcpNoDelay());
//Subscribe to the current velocity and angular velocity of the quadrotor
mavtwistSub_ = nh_.subscribe("/mavros/local_position/velocity_local", 50, &flip_traverse::mavtwistCallback, this,ros::TransportHints().tcpNoDelay());
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
flip_init_vel << 0.0, 0.0, 0.0;
flip_init_pos << 0.0, 0.0, 0.0;
mavPos_ << 0.0, 0.0, 10.0;
mavVel_ << 0.0, 0.0, 0.0;
nh_.param<double>("/trajectory_generator/flip_init_vel_x", flip_init_vel[0], 3.0);
nh_.param<double>("/trajectory_generator/flip_init_vel_y", flip_init_vel[1], 0.0);
nh_.param<double>("/trajectory_generator/Tc", Tc, 1.1);
nh_.param<double>("/trajectory_generator/flip_init_pos_x", flip_init_pos[0], 5.0);
nh_.param<double>("/trajectory_generator/flip_init_pos_y", flip_init_pos[1], 0.0);
nh_.param<double>("/trajectory_generator/flip_height", flip_init_pos[2], 10.0);
curr_vel = flip_init_vel.norm();
r = (curr_vel*curr_vel)/(Tc*g - g);
pitch_angle = 0.0;
energy = (curr_vel*curr_vel)/2.0;
g = 9.8;
}
flip_traverse::~flip_traverse() {
//Destructor
}
double flip_traverse::maneuver_init(double time)
{
//std::cout<<mavPos_<<" "<<mavVel_<<"\n";
//eth_set_pos(mavPos_,flip_init_pos);
//eth_set_vel(mavVel_,flip_init_vel);
//T1 = eth_trajectory_init();
T1 = 0.0;
T2 = 1.0;
return T1 + T2;
}
void flip_traverse::trajectory_generator(double time)
{
if(time<T1)
{
target_position = eth_trajectory_pos(time);
target_velocity = eth_trajectory_vel(time);
target_acceleration = eth_trajectory_acc(time);
type = 1;
}
else
{
pitch_angle += (curr_vel*0.01)/r;
curr_vel = pow(2*std::max(0.1,(energy - g*(mavPos_[2] - flip_init_pos[2]))),0.5);
target_velocity << curr_vel*cos(pitch_angle), 0, curr_vel*sin(pitch_angle);
target_acceleration << Tc*g*sin(pitch_angle), 0, (Tc*g*cos(pitch_angle)) - g;
//target_position += Eigen::Vector3d(0.01*target_velocity[0],0,0.01*target_velocity[2]);
r = (curr_vel*curr_vel)/(Tc*g - g*cos(pitch_angle));
type = 4;
}
target_angvel << 0.0, 0.0, 0.0;
target_yaw = 0.0;
}
Eigen::Vector3d flip_traverse::calculate_trajectory_angvel()
{
}
Eigen::Vector3d flip_traverse::get_target_pos()
{
return target_position;
}
Eigen::Vector3d flip_traverse::get_target_vel()
{
return target_velocity;
}
Eigen::Vector3d flip_traverse::get_target_acc()
{
return target_acceleration;
}
Eigen::Vector3d flip_traverse::get_target_angvel()
{
return target_angvel;
}
Eigen::Vector3d flip_traverse::get_target_jerk()
{
return target_jerk;
}
double flip_traverse::get_target_yaw()
{
return target_yaw;
}
int flip_traverse::get_type()
{
return type;
}
void flip_traverse::mavtwistCallback(const geometry_msgs::TwistStamped& msg){
mavVel_ << msg.twist.linear.x, msg.twist.linear.y, msg.twist.linear.z;
}
void flip_traverse::mavposeCallback(const geometry_msgs::PoseStamped& msg){
mavPos_ << msg.pose.position.x, msg.pose.position.y, msg.pose.position.z;
}
|
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T temp(T x, T y)
{
if(x>y)
return x;
else
return y;
}
template <typename T>
T templ(T x, T y)
{
if(x>y)
return y;
return x;
}
main()
{
int a=9, c;
int b=8;
c= temp(a,b);
int x;
x=templ(1,6);
cout<<c<<"\n";
cout<<x;
}
|
/*
* @Description: 关键帧,在各个模块之间传递数据
* @Author: Ren Qian
* @Date: 2020-02-28 19:13:26
*/
#ifndef LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_
#define LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_
#include <Eigen/Dense>
namespace lidar_localization {
class KeyFrame {
public:
double time = 0.0;
unsigned int index = 0;
Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();
public:
Eigen::Quaternionf GetQuaternion();
};
}
#endif
|
// Created on: 1995-10-26
// Created by: Yves FRICAUD
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepOffset_MakeOffset_HeaderFile
#define _BRepOffset_MakeOffset_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Compound.hxx>
#include <BRepOffset_Mode.hxx>
#include <GeomAbs_JoinType.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <BRepOffset_Analyse.hxx>
#include <BRepAlgo_Image.hxx>
#include <TopTools_ListOfShape.hxx>
#include <BRepOffset_Error.hxx>
#include <BRepOffset_MakeLoops.hxx>
#include <TopTools_MapOfShape.hxx>
#include <BRepOffset_DataMapOfShapeOffset.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <Message_ProgressRange.hxx>
class BRepAlgo_AsDes;
class TopoDS_Face;
class BRepOffset_Inter3d;
class BRepOffset_MakeOffset
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepOffset_MakeOffset();
Standard_EXPORT BRepOffset_MakeOffset(const TopoDS_Shape& S,
const Standard_Real Offset,
const Standard_Real Tol,
const BRepOffset_Mode Mode = BRepOffset_Skin,
const Standard_Boolean Intersection = Standard_False,
const Standard_Boolean SelfInter = Standard_False,
const GeomAbs_JoinType Join = GeomAbs_Arc,
const Standard_Boolean Thickening = Standard_False,
const Standard_Boolean RemoveIntEdges = Standard_False,
const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT void Initialize (const TopoDS_Shape& S,
const Standard_Real Offset,
const Standard_Real Tol,
const BRepOffset_Mode Mode = BRepOffset_Skin,
const Standard_Boolean Intersection = Standard_False,
const Standard_Boolean SelfInter = Standard_False,
const GeomAbs_JoinType Join = GeomAbs_Arc,
const Standard_Boolean Thickening = Standard_False,
const Standard_Boolean RemoveIntEdges = Standard_False);
Standard_EXPORT void Clear();
//! Changes the flag allowing the linearization
Standard_EXPORT void AllowLinearization (const Standard_Boolean theIsAllowed);
//! Add Closing Faces, <F> has to be in the initial
//! shape S.
Standard_EXPORT void AddFace (const TopoDS_Face& F);
//! set the offset <Off> on the Face <F>
Standard_EXPORT void SetOffsetOnFace (const TopoDS_Face& F, const Standard_Real Off);
Standard_EXPORT void MakeOffsetShape(const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT void MakeThickSolid(const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT const BRepOffset_Analyse& GetAnalyse() const;
Standard_EXPORT Standard_Boolean IsDone() const;
Standard_EXPORT const TopoDS_Shape& Shape() const;
const TopoDS_Shape& InitShape() const
{
return myInitialShape;
}
//! returns information about offset state.
Standard_EXPORT BRepOffset_Error Error() const;
//! Returns <Image> containing links between initials
//! shapes and offset faces.
Standard_EXPORT const BRepAlgo_Image& OffsetFacesFromShapes() const;
//! Returns myJoin.
Standard_EXPORT GeomAbs_JoinType GetJoinType() const;
//! Returns <Image> containing links between initials
//! shapes and offset edges.
Standard_EXPORT const BRepAlgo_Image& OffsetEdgesFromShapes() const;
//! Returns the list of closing faces stores by AddFace
Standard_EXPORT const TopTools_IndexedMapOfShape& ClosingFaces() const;
//! Makes pre analysis of possibility offset perform. Use method Error() to get more information.
//! Finds first error. List of checks:
//! 1) Check for existence object with non-null offset.
//! 2) Check for connectivity in offset shell.
//! 3) Check continuity of input surfaces.
//! 4) Check for normals existence on grid.
//! @return True if possible make computations and false otherwise.
Standard_EXPORT Standard_Boolean CheckInputData(const Message_ProgressRange& theRange);
//! Return bad shape, which obtained in CheckInputData.
Standard_EXPORT const TopoDS_Shape& GetBadShape() const;
public: //! @name History methods
//! Returns the list of shapes generated from the shape <S>.
Standard_EXPORT const TopTools_ListOfShape& Generated (const TopoDS_Shape& theS);
//! Returns the list of shapes modified from the shape <S>.
Standard_EXPORT const TopTools_ListOfShape& Modified (const TopoDS_Shape& theS);
//! Returns true if the shape S has been deleted.
Standard_EXPORT Standard_Boolean IsDeleted (const TopoDS_Shape& S);
protected:
//! Analyze progress steps of the whole operation.
//! @param theWhole - sum of progress of all operations.
//! @oaram theSteps - steps of the operations supported by PI
Standard_EXPORT void analyzeProgress (const Standard_Real theWhole,
TColStd_Array1OfReal& theSteps) const;
private:
//! Check if shape consists of only planar faces
//! If <myIsLinearizationAllowed> is TRUE, try to approximate images of faces
//! by planar faces
Standard_EXPORT Standard_Boolean IsPlanar();
//! Set the faces that are to be removed
Standard_EXPORT void SetFaces();
//! Set the faces with special value of offset
Standard_EXPORT void SetFacesWithOffset();
Standard_EXPORT void BuildFaceComp();
Standard_EXPORT void BuildOffsetByArc(const Message_ProgressRange& theRange);
Standard_EXPORT void BuildOffsetByInter(const Message_ProgressRange& theRange);
//! Make Offset faces
Standard_EXPORT void MakeOffsetFaces(BRepOffset_DataMapOfShapeOffset& theMapSF, const Message_ProgressRange& theRange);
Standard_EXPORT void SelfInter (TopTools_MapOfShape& Modif);
Standard_EXPORT void Intersection3D (BRepOffset_Inter3d& Inter, const Message_ProgressRange& theRange);
Standard_EXPORT void Intersection2D (const TopTools_IndexedMapOfShape& Modif,
const TopTools_IndexedMapOfShape& NewEdges,
const Message_ProgressRange& theRange);
Standard_EXPORT void MakeLoops (TopTools_IndexedMapOfShape& Modif, const Message_ProgressRange& theRange);
Standard_EXPORT void MakeLoopsOnContext (TopTools_MapOfShape& Modif);
Standard_EXPORT void MakeFaces (TopTools_IndexedMapOfShape& Modif, const Message_ProgressRange& theRange);
Standard_EXPORT void MakeShells(const Message_ProgressRange& theRange);
Standard_EXPORT void SelectShells();
Standard_EXPORT void EncodeRegularity();
//! Replace roots in history maps
Standard_EXPORT void ReplaceRoots();
Standard_EXPORT void MakeSolid(const Message_ProgressRange& theRange);
Standard_EXPORT void ToContext (BRepOffset_DataMapOfShapeOffset& MapSF);
//! Private method use to update the map face<->offset
Standard_EXPORT void UpdateFaceOffset();
//! Private method used to correct degenerated edges on conical faces
Standard_EXPORT void CorrectConicalFaces();
//! Private method used to build walls for thickening the shell
Standard_EXPORT void MakeMissingWalls(const Message_ProgressRange& theRange);
//! Removes INTERNAL edges from the result
Standard_EXPORT void RemoveInternalEdges();
//! Intersects edges
Standard_EXPORT void IntersectEdges (const TopTools_ListOfShape& theFaces,
BRepOffset_DataMapOfShapeOffset& theMapSF,
TopTools_DataMapOfShapeShape& theMES,
TopTools_DataMapOfShapeShape& theBuild,
Handle(BRepAlgo_AsDes)& theAsDes,
Handle(BRepAlgo_AsDes)& theAsDes2d,
const Message_ProgressRange& theRange);
//! Building of the splits of the offset faces for mode Complete
//! and joint type Intersection. This method is an advanced alternative
//! for BRepOffset_MakeLoops::Build method.
//! Currently the Complete intersection mode is limited to work only on planar cases.
Standard_EXPORT void BuildSplitsOfExtendedFaces(const TopTools_ListOfShape& theLF,
const BRepOffset_Analyse& theAnalyse,
const Handle(BRepAlgo_AsDes)& theAsDes,
TopTools_DataMapOfShapeListOfShape& theEdgesOrigins,
TopTools_DataMapOfShapeShape& theFacesOrigins,
TopTools_DataMapOfShapeShape& theETrimEInf,
BRepAlgo_Image& theImage,
const Message_ProgressRange& theRange);
//! Building of the splits of the already trimmed offset faces for mode Complete
//! and joint type Intersection.
Standard_EXPORT void BuildSplitsOfTrimmedFaces(const TopTools_ListOfShape& theLF,
const Handle(BRepAlgo_AsDes)& theAsDes,
BRepAlgo_Image& theImage,
const Message_ProgressRange& theRange);
Standard_Real myOffset;
Standard_Real myTol;
TopoDS_Shape myInitialShape;
TopoDS_Shape myShape;
TopoDS_Compound myFaceComp;
BRepOffset_Mode myMode;
Standard_Boolean myIsLinearizationAllowed;
Standard_Boolean myInter;
Standard_Boolean mySelfInter;
GeomAbs_JoinType myJoin;
Standard_Boolean myThickening;
Standard_Boolean myRemoveIntEdges;
TopTools_DataMapOfShapeReal myFaceOffset;
TopTools_IndexedMapOfShape myFaces;
TopTools_IndexedMapOfShape myOriginalFaces;
BRepOffset_Analyse myAnalyse;
TopoDS_Shape myOffsetShape;
BRepAlgo_Image myInitOffsetFace;
BRepAlgo_Image myInitOffsetEdge;
BRepAlgo_Image myImageOffset;
BRepAlgo_Image myImageVV;
TopTools_ListOfShape myWalls;
Handle(BRepAlgo_AsDes) myAsDes;
TopTools_DataMapOfShapeListOfShape myEdgeIntEdges;
Standard_Boolean myDone;
BRepOffset_Error myError;
BRepOffset_MakeLoops myMakeLoops;
Standard_Boolean myIsPerformSewing; // Handle bad walls in thicksolid mode.
Standard_Boolean myIsPlanar;
TopoDS_Shape myBadShape;
TopTools_DataMapOfShapeShape myFacePlanfaceMap;
TopTools_ListOfShape myGenerated;
TopTools_MapOfShape myResMap;
};
#endif // _BRepOffset_MakeOffset_HeaderFile
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "Monte.h"
#include "MonteGameMode.h"
#include "MontePawn.h"
AMonteGameMode::AMonteGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
// set default pawn class to our character class
DefaultPawnClass = AMontePawn::StaticClass();
}
|
#include "receiverprotocol.h"
#include <stdio.h>
//ReceiverProtocol::ReceiverProtocol()
//{
//}
//ReceiverProtocol::~ReceiverProtocol()
//{
//}
/*
* @result: data of 16channels
RX:0F E0 03 1F 58 C0 07 16 B0 80 05 2C 60 01 0B F8 C0 07 00 00 00 00 00 03 00
CH: 992 992 352 992 352 352 352 352 352 352 992 992 000 000 000 000
RX:0F 60 01 0B 58 C0 07 66 30 83 19 7C 60 06 1F F8 C0 07 00 00 00 00 00 03 00
CH: 352 352 352 992 1632 1632 1632 992 1632 992 992 992 000 000 000 000
*/
void ReceiverProtocol::parse(char* buf, int* ch)
{
sbusPackage_t *data = (sbusPackage_t *)buf;
static int c = 0;
if ((data->start == SBUS_STARTBIT) && (data->end == SBUS_ENDBIT)){
ch[ 0] = (buf[ 1] | (buf[2] << 8)) &0x07ff; //!< Channel 0
ch[ 1] = ((buf[ 2] >> 3) | (buf[3] << 5)) &0x07ff; //!< Channel 1
ch[ 2] = ((buf[ 3] >> 6) | (buf[4] << 2) | (buf[5] << 10)) &0x07ff; //!< Channel 2 油门通道
ch[ 3] = ((buf[ 5] >> 1) | (buf[6] << 7)) &0x07ff; //!< Channel 3
ch[ 4] = ((buf[ 6] >> 4) | (buf[7] << 4)) &0x07ff; //!< Channel 4
ch[ 5] = ((buf[ 7] >> 7) | (buf[8] << 1) | (buf[9] << 9)) &0x07ff; //!< Channel 5
ch[ 6] = ((buf[ 9] >> 2) | (buf[10] << 6)) &0x07ff; //!< Channel 6
ch[ 7] = ((buf[10] >> 5) | (buf[11] << 3)) &0x07ff; //!< Channel 7
ch[ 8] = (buf[12] | (buf[13] << 8)) &0x07ff; //!< Channel 8
ch[ 9] = ((buf[13] >> 3) | (buf[14] << 5)) &0x07ff; //!< Channel 9
ch[10] = ((buf[14] >> 6) | (buf[15] << 2) | (buf[16] << 10)) &0x07ff;//!< Channel 10
ch[11] = ((buf[16] >> 1) | (buf[17] << 7)) &0x07ff; //!< Channel 11
ch[12] = ((buf[17] >> 4) | (buf[18] << 4)) &0x07ff; //!< Channel 12
ch[13] = ((buf[18] >> 7) | (buf[19] << 1) | (buf[20] << 9)) &0x07ff; //!< Channel 13
ch[14] = ((buf[20] >> 2) | (buf[21] << 6)) &0x07ff; //!< Channel 14
ch[15] = ((buf[21] >> 5) | (buf[22] << 3)) &0x07ff; //!< Channel 15
if (c++ % (50*1/2) == 0) // 500ms
qDebug("Invalid data");
for (int i = 0; i < 16; i++){
printf("%d ", ch[i]);
if (i == 7)
printf("\n");
}
printf("\n");
// qDebug("parse data: over");
}
else{
memset(ch, 0, 16);
if (c++ % (5*4) == 0) // 400ms
qDebug("Invalid data");
}
}
|
class FoodBioMeat
{
weight = 0.2;
};
class FoodCanSardines
{
weight = 0.2;
};
class FoodCanBakedBeans
{
weight = 0.2;
};
class FoodCanFrankBeans
{
weight = 0.2;
};
class FoodCanPasta
{
weight = 0.2;
};
class FoodCanUnlabeled
{
weight = 0.2;
};
class FoodMRE
{
weight = 0.4;
};
class FoodPistachio
{
weight = 0.003;
};
class FoodNutmix
{
weight = 0.003;
};
class FoodCanBeef
{
weight = 0.2;
};
class FoodCanPotatoes
{
weight = 0.2;
};
class FoodCanGriff
{
weight = 0.2;
};
class FoodCanBadguy
{
weight = 0.2;
};
class FoodCanBoneboy
{
weight = 0.2;
};
class FoodCanCorn
{
weight = 0.2;
};
class FoodCanCurgon
{
weight = 0.2;
};
class FoodCanDemon
{
weight = 0.2;
};
class FoodCanFraggleos
{
weight = 0.2;
};
class FoodCanHerpy
{
weight = 0.2;
};
class FoodCanDerpy
{
weight = 0.2;
};
class FoodCanOrlok
{
weight = 0.2;
};
class FoodCanPowell
{
weight = 0.2;
};
class FoodCanTylers
{
weight = 0.2;
};
class FoodCanRusUnlabeled
{
weight = 0.2;
};
class FoodCanRusStew
{
weight = 0.2;
};
class FoodCanRusPork
{
weight = 0.2;
};
class FoodCanRusPeas
{
weight = 0.2;
};
class FoodCanRusMilk
{
weight = 0.2;
};
class FoodCanRusCorn
{
weight = 0.2;
};
class FoodChipsSulahoops
{
weight = 0.2;
};
class FoodChipsMysticales
{
weight = 0.2;
};
class FoodChipsChocolate
{
weight = 0.2;
};
class FoodCandyChubby
{
weight = 0.2;
};
class FoodCandyAnders
{
weight = 0.2;
};
class FoodCandyLegacys
{
weight = 0.2;
};
class FoodCakeCremeCakeClean
{
weight = 0.2;
};
class FoodCandyMintception
{
weight = 0.2;
};
class equip_garlic_bulb
{
weight = 0.1;
};
class FoodPotatoRaw
{
weight = 0.25;
};
class FoodPotatoBaked
{
weight = 0.25;
};
class FoodCarrot
{
weight = 0.25;
};
|
/*
* This source file is part of MyGUI. For the latest info, see http://mygui.info/
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#ifndef MYGUI_SUB_WIDGET_MANAGER_H_
#define MYGUI_SUB_WIDGET_MANAGER_H_
#include <_GUI/Prerequest.h>
#include <_GUI/Singleton.h>
namespace _GUI
{
class MYGUI_EXPORT SubWidgetManager :
public Singleton<SubWidgetManager>
{
public:
SubWidgetManager();
void initialise();
void shutdown();
const std::string& getCategoryName() const;
const std::string& getStateCategoryName() const;
private:
bool mIsInitialise;
std::string mCategoryName;
std::string mStateCategoryName;
};
} // namespace _GUI
#endif // MYGUI_SUB_WIDGET_MANAGER_H_
|
/*
* File: Tower.h
* Author: mohammedheader
*
* Created on November 23, 2014, 6:01 PM
*/
#ifndef TOWER_H
#define TOWER_H
#include "cocos2d.h"
class HelloWorld;
class Tower : public cocos2d::Node {
public:
static Tower* create(HelloWorld* game, cocos2d::Vec2 location);
virtual void update(float dt);
virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, unsigned int flags);
cocos2d::CustomCommand _customCommand;
private:
Tower* init(HelloWorld* game, cocos2d::Vec2 location);
void onDrawPrimitives(const cocos2d::Mat4 &transform);
void targetKilled();
void shootWeapon(float dt);
void damageEnemy();
bool attacking;
Enemy *chosenEnemy;
int attackRange;
int damage;
float fireRate;
HelloWorld *theGame;
cocos2d::Sprite *mySprite;
};
#endif /* TOWER_H */
|
#ifndef __IRR_REFCTD_DYNAMIC_ARRAY_H_INCLUDED__
#define __IRR_REFCTD_DYNAMIC_ARRAY_H_INCLUDED__
#include "irr/core/dynamic_array.h"
#include "irr/core/IReferenceCounted.h"
namespace irr { namespace core
{
template<typename T, class allocator = core::allocator<T>>
class refctd_dynamic_array : public dynamic_array<T, allocator>, public IReferenceCounted
{
using base_t = dynamic_array<T, allocator>;
public:
refctd_dynamic_array(size_t _length, const allocator& _alctr = allocator()) : base_t(_length, _alctr) {}
refctd_dynamic_array(size_t _length, const T& _val, const allocator& _alctr = allocator()) : base_t(_length, _val, _alctr) {}
refctd_dynamic_array(std::initializer_list<T> _contents, const allocator& _alctr = allocator()) : base_t(_contents, _alctr) {}
protected:
virtual ~refctd_dynamic_array() = default;
};
}}
#endif
|
/*
Copyright (c) 2007-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "DirectoryComparisonTestCheckTests.hpp"
#include "FileComparisonTestCheckTests.hpp"
#include "JUnitXMLWriterTests.hpp"
#include "TestContextTests.hpp"
#include "TestHarnessTests.hpp"
#include "TestNumberTests.hpp"
#include "TestTests.hpp"
#include "TestMacrosFormatterTests.h"
#include "TestMacrosTests.h"
#include "TestSequenceTests.h"
#include "ConsoleApplicationTestTests/ConsoleApplicationTestTests.h"
#include "HeapAllocationErrorsTestTests/HeapAllocationErrorsTestTests.h"
#include "TestSetupActionsTests/TestSetupActionsTests.h"
#include "TestTeardownActionsTests/TestTeardownActionsTests.h"
#include <Ishiko/Configuration.hpp>
#include <Ishiko/TestFramework/Core.hpp>
#include <exception>
using namespace Ishiko;
int main(int argc, char* argv[])
{
try
{
TestHarness::CommandLineSpecification commandLineSpec;
commandLineSpec.setDefaultValue("context.data", "../../data");
commandLineSpec.setDefaultValue("context.output", "../../output");
commandLineSpec.setDefaultValue("context.reference", "../../reference");
Configuration configuration = commandLineSpec.createDefaultConfiguration();
CommandLineParser::parse(commandLineSpec, argc, argv, configuration);
TestHarness theTestHarness("IshikoTestFrameworkCore", configuration);
TestSequence& theTests = theTestHarness.tests();
theTests.append<TestContextTests>();
theTests.append<TestNumberTests>();
theTests.append<TestTests>();
theTests.append<FileComparisonTestCheckTests>();
theTests.append<DirectoryComparisonTestCheckTests>();
theTests.append<TestMacrosFormatterTests>();
theTests.append<TestMacrosTests>();
theTests.append<TestSequenceTests>();
theTests.append<ConsoleApplicationTestTests>();
theTests.append<HeapAllocationErrorsTestTests>();
theTests.append<TestSetupActionsTests>();
theTests.append<TestTeardownActionsTests>();
theTests.append<JUnitXMLWriterTests>();
theTests.append<TestHarnessTests>();
return theTestHarness.run();
}
catch (const std::exception& e)
{
return TestApplicationReturnCode::exception;
}
catch (...)
{
return TestApplicationReturnCode::exception;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2006-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OPCERTIFICATEMANAGER_H
#define OPCERTIFICATEMANAGER_H
class OpCertificate;
/** @short External SSL certificate manager.
*
* This is a class used to browse device certificates, like root certificates
* and personal certificates installed on device.
*
* The intended life cycle is like this:
*
* 1) Somewhen, for example on initialization or on first Get() call or
* whenever it is convenient, the platform creates the certificate manager
* instance.
*
* 2) Core calls OpCertificateManager::Get() and gets a pointer to this
* instance. The platform increments the usage counter.
*
* 3) Core is done with the manager and calls OpCertificateManager::Release()
* to release the instance. The platform decrements the usage counter.
*
* 4) On shutdown or on low memory or whenever it is convenient, the platform
* destructs the instance, if the usage counter is 0.
*/
class OpCertificateManager
{
public:
/** Type of certificate. */
enum CertificateType
{
/** Personal/client certificate. */
CertTypePersonal,
/** Root CA certificate. */
CertTypeAuthorities,
/** Intermediate CA certificate. */
CertTypeIntermediate,
/** Server certificate, verified successfully or approved by user. */
CertTypeApproved,
/** Server certificate, failed to verify and rejected by user. */
CertTypeRejected
};
/** Certificate settings. */
struct Settings
{
/** Warn when this certificate is encountered. */
BOOL warn;
/** Allow connections that use this certificate. */
BOOL allow;
};
/** Get certificate manager instance from the platform.
* The platform may allocate some resources on this call. */
static OP_STATUS Get(OpCertificateManager** cert_manager, CertificateType type);
/** Release certificate manager instance.
* The platform may deallocate some resources on this call. */
virtual void Release() = 0;
/** Count the certificates being managed by this instance. */
virtual unsigned int Count() const = 0;
/** Get certificate by index.
* Certificates are indexed sequentially, starting from zero.
* The returned certificate remains owned by the certificate manager,
* the caller doesn't take over ownership. The returned pointer
* is valid until the first function call that changes the certificate
* manager, for example @ref Release() or @ref RemoveCertificate().
*/
virtual OpCertificate* GetCertificate(unsigned int index) = 0;
/** Get certificate settings. */
virtual OP_STATUS GetSettings(unsigned int index, Settings& settings) const = 0;
/** Update certificate settings. */
virtual OP_STATUS UpdateSettings(unsigned int index, const Settings& settings) = 0;
/** Remove certificate by index.
* The manager is at liberty to now forget it ever knew anything
* about this certificate. */
virtual OP_STATUS RemoveCertificate(unsigned int index) = 0;
protected:
virtual ~OpCertificateManager() {}
};
#endif //OPCERTIFICATEMANAGER_H
|
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <string>
#include <stack>
int main() {
std::string str;
std::stack < int >contain;
int res;
int count;
char iMem;
int count1 = 2;
std::cin >> str;
contain.push(0);
for(int i = 0; i < str.length(); ++i) {
iMem = str[i];
if('[' == str[i]) {
res = 1;
continue;
}
if(']' == str[i]) {
res = -1;
continue;
}
if('}' == str[i]) {
res = -2;
continue;
}
if('{' == str[i]) {
res = 2;
continue;
}
if('(' == str[i]) {
res = 3;
continue;
}
if(')' == str[i]) {
res = -3;
continue;
}
if('"' == str[i]) {
res = pow (-1, count1) * 4;
++count1;
continue;
}
if(0 < res) {
contain.push(res);
} else {
if(0 == contain.top ()) {
contain.push(7);
std::cout << "arajin pakagic@ chi karox pakox linel" << std::endl;
break;
} else {
if(0 == contain.top() + res) {
contain.pop();
}
}
}
}
if (0 == contain.top())
{
std::cout << "amen inch chisht e" << std::endl;
}
else
{
if (7 != contain.top())
std::cout << "hetevyal " << iMem << "-@ sxal e " << std::endl;
}
return 0;
}
|
/****************************************************************************
** Copyright (c) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** 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 LibQxt project 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 <COPYRIGHT HOLDER> 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.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
/*!
\class QxtScgiServerConnector
\inmodule QxtWeb
\brief The QxtScgiServerConnector class provides an SCGI connector for QxtHttpSessionManager
QxtScgiServerConnector implements the SCGI protocoll supported by almost all modern web servers.
\sa QxtHttpSessionManager
*/
#include "qxthttpsessionmanager.h"
#include "qxtwebevent.h"
#include <QTcpServer>
#include <QHash>
#include <QTcpSocket>
#include <QString>
#ifndef QXT_DOXYGEN_RUN
class QxtScgiServerConnectorPrivate : public QxtPrivate<QxtScgiServerConnector>
{
public:
QTcpServer* server;
};
#endif
/*!
* Creates a QxtHttpServerConnector with the given \a parent.
*/
QxtScgiServerConnector::QxtScgiServerConnector(QObject* parent) : QxtAbstractHttpConnector(parent)
{
QXT_INIT_PRIVATE(QxtScgiServerConnector);
qxt_d().server = new QTcpServer(this);
QObject::connect(qxt_d().server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}
/*!
* \reimp
*/
bool QxtScgiServerConnector::listen(const QHostAddress& iface, quint16 port)
{
return qxt_d().server->listen(iface, port);
}
/*!
* \reimp
*/
bool QxtScgiServerConnector::shutdown()
{
if(qxt_d().server->isListening()){
qxt_d().server->close();
return true;
}
return false;
}
/*!
* \reimp
*/
quint16 QxtScgiServerConnector::serverPort() const
{
return qxt_d().server->serverPort();
}
/*!
* \internal
*/
void QxtScgiServerConnector::acceptConnection()
{
QTcpSocket* socket = qxt_d().server->nextPendingConnection();
addConnection(socket);
}
/*!
* \reimp
*/
bool QxtScgiServerConnector::canParseRequest(const QByteArray& buffer)
{
if (buffer.size() < 10)
return false;
QString expectedsize;
for (int i = 0;i < 10;i++)
{
if (buffer.at(i) == ':')
{
break;
}
else
{
expectedsize += buffer.at(i);
}
}
if (expectedsize.isEmpty())
{
//protocoll error
return false;
}
// The SCGI header is [len]":"[key/value pairs]","
int headersize = expectedsize.count() + expectedsize.toInt() + 2;
return (buffer.size() >= headersize);
}
/*!
* \reimp
*/
QHttpRequestHeader QxtScgiServerConnector::parseRequest(QByteArray& buffer)
{
QString expectedsize_s;
for (int i = 0;i < 20;i++)
{
if (buffer.at(i) == ':')
{
break;
}
else
{
expectedsize_s += buffer.at(i);
}
}
if (expectedsize_s.isEmpty())
{
//protocoll error
return QHttpRequestHeader();
}
int expectedsize = expectedsize_s.toInt();
QByteArray requestheaders = buffer.mid(expectedsize_s.count() + 1, expectedsize);
buffer = buffer.mid(expectedsize_s.count() + expectedsize + 2);
QHttpRequestHeader request_m;
QByteArray name;
int i = 0;
while ((i = requestheaders.indexOf('\0')) > -1)
{
if (name.isEmpty())
{
name = requestheaders.left(i);
}
else
{
request_m.setValue(QString::fromLatin1(name).toLower(), QString::fromLatin1(requestheaders.left(i)));
name = "";
}
requestheaders = requestheaders.mid(i + 1);
}
request_m.setRequest(request_m.value("request_method"), request_m.value("request_uri"), 1, 0);
foreach(const QString& key, request_m.keys())
{
if (key.startsWith(QString("http_")))
{
QString realKey = key.right(key.size() - 5).replace(QLatin1Char('_'), QLatin1Char('-'));
request_m.setValue(realKey, request_m.value(key));
}
}
request_m.setValue("Connection", "close");
return request_m;
}
/*!
* \reimp
*/
void QxtScgiServerConnector::writeHeaders(QIODevice* device, const QHttpResponseHeader& response_m)
{
device->write(("Status:" + QString::number(response_m.statusCode()) + ' ' + response_m.reasonPhrase() + "\r\n").toLatin1());
foreach(const QString& key, response_m.keys())
{
device->write((key + ':' + response_m.value(key) + "\r\n").toLatin1());
}
device->write("\r\n");
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef M2_MAPI_SUPPORT
#include "platforms/windows/mapi/WindowsDesktopMailClientUtils.h"
#include "platforms/windows/mapi/OperaMapiUtils.h"
#include "platforms/windows/utils/authorization.h"
OP_STATUS DesktopMailClientUtils::Create(DesktopMailClientUtils** desktop_mail_client_utils)
{
*desktop_mail_client_utils = OP_NEW(WindowsDesktopMailClientUtils,());
if (!*desktop_mail_client_utils)
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
void WindowsDesktopMailClientUtils::SignalMailClientIsInitialized(bool initialized)
{
if (IsOperaDefaultMailClient())
{
if (!m_event.get())
{
OpString event_name;
RETURN_VALUE_IF_ERROR(event_name.AppendFormat(OperaMapiConst::ready_event_name, GetCurrentProcessId()), );
m_event.reset(::CreateEvent(NULL, TRUE, FALSE, event_name.CStr()));
}
if (initialized)
SetEvent(m_event);
else
ResetEvent(m_event);
}
}
void WindowsDesktopMailClientUtils::SignalMailClientHandledMessage(INT32 id)
{
OpString name;
name.AppendFormat(OperaMapiConst::request_handled_event_name, id);
HANDLE handle = OpenEvent(READ_CONTROL|SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, name.CStr());
if (!handle)
return;
SetEvent(handle);
CloseHandle(handle);
}
OP_STATUS WindowsDesktopMailClientUtils::SetOperaAsDefaultMailClient()
{
OperaInstaller installer;
OP_STATUS status = installer.SetDefaultMailerAndAssociations();
if (OpStatus::IsSuccess(status) && !IsSystemWinVista() && WindowsUtils::IsPrivilegedUser(FALSE))
{
status = installer.SetDefaultMailerAndAssociations(TRUE);
}
return status;
}
#endif //M2_MAPI_SUPPORT
|
#pragma once
#ifndef LINKEDHASH_HPP_INCLUDE
#define LINKEDHASH_HPP_INCLUDE
namespace lh {
#include "common.hpp"
typedef char* Data;
typedef struct _Node
{
Data data;
struct _Node *prev;
struct _Node *next;
}Node;
typedef struct _Hash
// Basically a Linked List
{
unsigned int collision;
Node *head;
Node *tail;
}Hash;
typedef struct _HashTable
{
int size;
unsigned int collision;
Hash **hashlist;
}HashTable;
Node *initNode(Data data);
Hash *initHash();
HashTable *initHashTable(int size);
void RandHtGen(HashTable *h, int n);
void addFront(Data data, Hash *hashlist);
Node *find(Data data, HashTable *hashtable);
Node *extract(Data data, HashTable *hashtable);
int hashCode(Data data, int size);
double loadFactor(HashTable* ht);
int enlarge(HashTable *h);
void insert(Data data, HashTable *hashtable);
void printList(Hash *ll);
void printTable(HashTable *ht);
int isEmpty(Hash *hash);
}
#endif //LINKEDHASH_HPP_INCLUDE
|
#ifndef EXAMPLE_FUNCTION_HPP
#define EXAMPLE_FUNCTION_HPP
int ownSquare(int x);
#endif //EXAMPLE_FUNCTION_HPP
|
#include<bits/stdc++.h>
using namespace std;
#define MAX 110005
typedef pair<long long int,long long int>pa;
#define pb push_back
long long int INF=3*1e18;
vector<pa>adj[MAX]; // Graph
vector<pa>adjr[MAX]; // Reversed Graph
long long int v_for[MAX]; //virtual function for forward/main Graph
long long int v_back[MAX]; //virtual function for Backward Graph
long long int src,dest,n,m;
pa location[MAX]; //coordinates of each node
long long int f_dist[MAX]; //distance array
bool f_vis[MAX]; //visited array
//For faster input and output
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
//cmputing virtual function for each node
void computing_virtual_function()
{
for(int i=1;i<=n;i++)
{
unsigned long long cc=(((location[dest].first-location[i].first))*((location[dest].first-location[i].first)))+
(((location[dest].second-location[i].second))*((location[dest].second-location[i].second)));
v_for[i]=sqrt(cc);
}
}
//Astar for faster output
long long int Astar()
{
computing_virtual_function();
priority_queue<pa,vector<pa>,greater<pa>>f_pq; //priority queue for forward/original graph
for(int i=1;i<=n;i++)
{
f_dist[i]=INF;
f_vis[i]=false;
}
long long int estimate=INF;
f_pq.push({0,src});
f_dist[src]=0;
f_vis[src]=true;
// A star - dijkstra with virtual function
while(!f_pq.empty())
{
long long int wt=f_pq.top().first;
long long int v=f_pq.top().second;
f_vis[v]=true;
f_pq.pop();
if(f_vis[dest])
{
return f_dist[dest]+v_for[src];
}
for (auto jj:adj[v])
{
long long int u=jj.second;
long long int edge_wt=jj.first+v_for[u]-v_for[v];
if(!f_vis[u] && f_dist[v]+edge_wt<f_dist[u])
{
f_dist[u]=f_dist[v]+edge_wt;
f_pq.push({f_dist[v]+edge_wt,u});
}
}
}
return -1;
}
int main()
{
fastio();
long long int x,y,wt;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
location[i]={x,y};
}
for(int i=0;i<m;i++)
{
cin>>x>>y>>wt;
adj[x].pb({wt,y}); //adding edge to the graph
adjr[y].pb({wt,x}); //adding edge to the reversed Graph
}
long long int num_of_queries;
cin>>num_of_queries;
while(num_of_queries--)
{
cin>>src>>dest;
if(src==dest)
{
cout<<0<<"\n";
continue;
}
long long int ans=Astar();
cout<<ans<<"\n";
}
}
|
#include <iostream>
#include <cmath>
using namespace std;
int modExp(int x, int y, int N)
{
//output : (x ^ y ) mod N
if (y == 0)
return 1;
int z = modExp(x, floor(y / 2), N);
if (y % 2 == 0)
return (z * z) % N;
else
return (x * z * z) % N;
}
int main()
{
int a = 5;
int b = 4;
int N = 3;
int c = modExp(a, b, N);
cout << "The modular exponentiation value of " << a << "^" << b << " mod " << N << " is " << c << endl;
return 0;
}
|
#ifndef MESSAGE_BOX_H
#define MESSAGE_BOX_H
#include <QMessageBox>
#include <utility/raii.hpp>
#include <QPoint>
#include <QMouseEvent>
class message_box : public QMessageBox
{
public:
template<typename ... ARGS>
message_box(ARGS && ... args) : QMessageBox (std::forward<ARGS> (args)...) {}
void mousePressEvent (QMouseEvent* event) override
{
is_dragged_ = true;
drag_pos_ = event->globalPos () - pos ();
QMessageBox::mousePressEvent (event);
}
void mouseMoveEvent (QMouseEvent* event) override
{
SCOPE_EXIT { QMessageBox::mouseMoveEvent (event); };
if (is_dragged_ and event->buttons () & Qt::LeftButton )
{
move (event->globalPos () - drag_pos_);
event->accept ();
setWindowOpacity (0.5);
}
}
void mouseReleaseEvent (QMouseEvent* event) override
{
is_dragged_ = false;
setWindowOpacity (1);
QMessageBox::mouseReleaseEvent (event);
}
~message_box () override = default;
private:
bool is_dragged_ = false;
QPoint drag_pos_;
};
#endif // MESSAGE_BOX_H
|
#include <iostream>
#include "x.cpp"
using namespace std;
/*
struct RBNode{
RBNode *left,*right,*up;
int key;
char colour;
};
*/
RBNode *NULLT;
void leftRotate(RBNode *&T,RBNode *x)
{
RBNode *y=x->right;
x->right=y->left;
y->left->up=x;
y->up=x->up;
if(x->up==NULLT)
T=y;
else if(x==x->up->left)
y->up->left=y;
else
y->up->right=y;
y->left=x;
x->up=y;
}
void rightRotate(RBNode *&T,RBNode *x)
{
RBNode *y=x->left;
x->left=y->right;
y->right->up=x;
y->up=x->up;
if(x->up==NULLT)
T=y;
else if(x==x->up->right)
y->up->right=y;
else
y->up->left=y;
y->right=x;
x->up=y;
}
void fixup(RBNode *&T,RBNode *z)
{
RBNode*y;
while(z->up->colour=='r')
{
if(z->up==z->up->up->left)
{
y=z->up->up->right;
if(y->colour=='r')
{
z->up->colour='b';
y->colour='b';
z->up->up->colour='r';
z=z->up->up;
}
else if(z==z->up->right)
{
z=z->up;
leftRotate(T,z);
z->up->colour='b';
z->up->up->colour='r';
rightRotate(T,z->up->up);
}
}
else
{
y=z->up->up->left;
if(y->colour=='r')
{
z->up->colour='b';
y->colour='b';
z->up->up->colour='r';
z=z->up->up;
}
else if(z==z->up->left)
{
z=z->up;
leftRotate(T,z);
z->up->colour='b';
z->up->up->colour='r';
rightRotate(T,z->up->up);
}
}
}
T->colour='b';
}
void Insert(RBNode *&T,int key)
{
RBNode *z=new RBNode;
z->key=key;
RBNode *x=T,*y=NULLT;
while(x!=NULLT)
{
y=x;
if(z->key<x->key)
x=x->left;
else
x=x->right;
}
z->up=y;
if(y==NULLT)
T=z;
else if(z->key<y->key)
y->left=z;
else
y->right=z;
z->left=NULLT;
z->right=NULLT;
z->colour='r';
fixup(T,z);
}
int main()
{
NULLT=new RBNode;
NULLT->left=NULLT;
NULLT->right=NULLT;
NULLT->up=NULLT;
NULLT->colour='c';
NULLT->key=999;
RBNode *x=NULLT;
Insert(x,4);
Insert(x,5);
Insert(x,-4);
Insert(x,43);
//print2D(x);
cout << "Hello world!" << endl;
return 0;
}
|
#include "Vector3Double.hpp"
Elysium::Core::Math::Numerics::Vector3Double::Vector3Double()
{
}
Elysium::Core::Math::Numerics::Vector3Double::Vector3Double(double Value)
{
}
Elysium::Core::Math::Numerics::Vector3Double::Vector3Double(double ValueX, double ValueY, double ValueZ)
{
}
Elysium::Core::Math::Numerics::Vector3Double::~Vector3Double()
{
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Backward()
{
return Vector3Double(0.0, 0.0, 1.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Down()
{
return Vector3Double(0.0, -1.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Forward()
{
return Vector3Double(0.0, 0.0, -1.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Left()
{
return Vector3Double(-1.0, 0.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::One()
{
return Vector3Double(1.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Right()
{
return Vector3Double(1.0, 0.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::UnitX()
{
return Vector3Double(1.0, 0.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::UnitY()
{
return Vector3Double(0.0, 1.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::UnitZ()
{
return Vector3Double(0.0, 0.0, 1.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Up()
{
return Vector3Double(0.0, 1.0, 0.0);
}
Elysium::Core::Math::Numerics::Vector3Double Elysium::Core::Math::Numerics::Vector3Double::Zero()
{
return Vector3Double(0.0);
}
Elysium::Core::Math::Numerics::Vector3Single Elysium::Core::Math::Numerics::Vector3Double::ToVector3Single()
{
return Vector3Single(X, Y, Z);
}
|
#include "crvLin.h"
#include <stdio.h>
#include <math.h>
struct MetricCoefficients {
double G11, G12, G22, G;
};
void computeMetricCoefficients(int i, int j, int nX, int nY, double ** x, double ** y, MetricCoefficients & metrCof) {
double hKsi, hEta;
double dXdKsi, dXdEta, dYdKsi, dYdEta;
hKsi = 1.0 / (nX - 1);
hEta = 1.0 / (nY - 1);
dXdKsi = (x[i + 1][j] - x[i - 1][j]) / (2.0 * hKsi);
dYdKsi = (y[i + 1][j] - y[i - 1][j]) / (2.0 * hKsi);
dXdEta = (x[i][j + 1] - x[i][j - 1]) / (2.0 * hEta);
dYdEta = (y[i][j + 1] - y[i][j - 1]) / (2.0 * hEta);
metrCof.G11 = dXdKsi * dXdKsi + dYdKsi * dYdKsi;
metrCof.G12 = dXdKsi * dXdEta + dYdKsi * dYdEta;
metrCof.G22 = dXdEta * dXdEta + dYdEta * dYdEta;
metrCof.G = dXdKsi * dYdEta - dXdEta * dYdKsi;
}
double fLaplace(int i, int j, int nX, int nY, MetricCoefficients & metrCof, double ** f) {
double hKsi = 1.0 / (nX - 1);
double hEta = 1.0 / (nY - 1);
return (metrCof.G22 * (f[i + 1][j] + f[i - 1][j]) +
metrCof.G11 * (f[i][j + 1] + f[i][j - 1]) * pow(hKsi / hEta, 2) -
metrCof.G12 * (f[i + 1][j + 1] - f[i - 1][j + 1] - f[i + 1][j - 1] + f[i - 1][j - 1]) * 0.5 * hKsi / hEta) /
(2.0 * (metrCof.G22 + metrCof.G11 * pow(hKsi / hEta, 2)));
}
double relaxation(double fOld, double fNew, double alpha) {
return fOld * (1.0 - alpha) + fNew * alpha;
}
void computeGrid(int nX, int nY, int nXMin, int nYMin, int nXMax, int nYMax, double ** x, double ** y, double eps) {
const double alpha = 1.8;
double epsIter = 0.0;
MetricCoefficients metrCofij;
double xNew, yNew;
double epsXij, epsYij;
int kIter = 0;
do {
kIter++;
epsIter = 0.0;
for (int j = 1; j < nY - 1; j++) {
for (int i = 1; i < nX - 1; i++) {
if ((i >= nXMin) && (i <= nXMax) && (j >= nYMin) && (j <= nYMax)) continue;
computeMetricCoefficients(i, j, nX, nY, x, y, metrCofij);
xNew = fLaplace(i, j, nX, nY, metrCofij, x);
yNew = fLaplace(i, j, nX, nY, metrCofij, y);
epsXij = fabs(x[i][j] - xNew);
epsYij = fabs(y[i][j] - yNew);
if (epsIter < epsXij) epsIter = epsXij;
if (epsIter < epsYij) epsIter = epsYij;
x[i][j] = relaxation(x[i][j], xNew, alpha);
y[i][j] = relaxation(y[i][j], yNew, alpha);
}
}
printf("%d | %le\n", kIter, epsIter);
if (kIter == 2000) break;
} while (epsIter > eps);
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
// fwComEd
#include <fwComEd/fieldHelper/MedicalImageHelpers.hpp>
#include <fwComEd/Dictionary.hpp>
// fwData
#include <fwData/Point.hpp>
#include <fwData/PointList.hpp>
#include <fwData/String.hpp>
#include "gdcmIO/reader/DicomLandmarkReader.hpp"
#include "gdcmIO/helper/GdcmHelper.hpp"
#include "gdcmIO/DicomDictionarySR.hpp"
namespace gdcmIO
{
namespace reader
{
//------------------------------------------------------------------------------
DicomLandmarkReader::DicomLandmarkReader()
{
SLM_TRACE_FUNC();
this->m_dicomLandmarks = ::boost::shared_ptr<DicomLandmark>( new DicomLandmark );
}
//------------------------------------------------------------------------------
DicomLandmarkReader::~DicomLandmarkReader()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomLandmarkReader::read() throw (::fwTools::Failed)
{
SLM_TRACE_FUNC();
::fwData::Image::sptr image = this->getConcreteObject();
SLM_ASSERT("fwData::Image not instanced", image);
SLM_ASSERT("gdcm::Reader not instanced", this->getReader());
const ::gdcm::DataSet & gDsRoot = this->getDataSet();
if (helper::GdcmData::getTagValue<0x0040,0xa040>(gDsRoot) == DicomDictionarySR::getTypeString(DicomDictionarySR::CONTAINER))
{
// Define the continuity of content
bool continuity = false;
const std::string continuityStr = helper::GdcmData::getTagValue<0x0040,0xa050>(gDsRoot); // Continuity Of Content
if ( continuityStr == DicomDictionarySR::getContinuityString(DicomDictionarySR::CONTINUOUS) )
{
continuity = true;
}
// Search child in the root of the document SR
if (gDsRoot.FindDataElement( ::gdcm::Tag(0x0040,0xa730) )) // Content Sequence
{
const ::gdcm::DataElement & gDeLandmarks = gDsRoot.GetDataElement( ::gdcm::Tag(0x0040,0xa730) );
const ::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSqLandmarks = gDeLandmarks.GetValueAsSQ();
// Search and read landmark(s) in children of the document SR root
::gdcm::SequenceOfItems::ConstIterator it = gSqLandmarks->Begin();
::gdcm::SequenceOfItems::ConstIterator itEnd = gSqLandmarks->End();
// For each child
for (; it != itEnd; ++it)
{
try
{// Try to read a child as a landmark
// Read one landmark and add it to m_dicomLandmark
this->readLandmark(it->GetNestedDataSet(), continuity);
}
catch(::fwTools::Failed & e)
{
OSLM_ERROR("Structured reporting reading error : "<<e.what());
}
}
// Add landmarks to fwData::Image
this->m_dicomLandmarks->convertToData(image);
}
else
{
throw ::fwTools::Failed("Empty structured reporting container");
}
}
// else nothing because root of SR data set is always a container
}
//------------------------------------------------------------------------------
void DicomLandmarkReader::readLandmark(const ::gdcm::DataSet & a_ds, const bool a_continuity/* = false*/) throw (::fwTools::Failed)
{
SLM_TRACE_FUNC();
if ( a_continuity )
{// if continuous content
throw ::fwTools::Failed("Continuous content not handled");
}
// Initialization
std::string label = "", refFrame = "";
SCoord scoord; // Spatial COORDinates of a frame point
const std::string separator = ","; // Separator of binary content
//***** Get a label *****//
const ::gdcm::DataSet * gDsTEXT = helper::DicomSR::getCodedContainer(DicomDictionarySR::getCodeValue(DicomDictionarySR::LANDMARK),
a_ds);
if ( gDsTEXT == 0 )
throw ::fwTools::Failed("No landmark found");
label = helper::GdcmData::getTagValue<0x0040,0xa160>(*gDsTEXT); // Text Value
//***** Get a point *****//
//*** Get SCOORD *****//
const ::gdcm::DataSet * gDsSCOORD = helper::DicomSR::getTypedContainer(DicomDictionarySR::getTypeString(DicomDictionarySR::SCOORD),
*gDsTEXT);
if ( gDsSCOORD == 0 )
throw ::fwTools::Failed("No point found");
scoord = helper::DicomSR::readSCOORD(*gDsSCOORD);
if ( scoord.getCRefGraphicType() != DicomDictionarySR::getGraphicTypeString(DicomDictionarySR::POINT) )
{
throw ::fwTools::Failed("Graphic Type not found or unappropriated");
}
// Check SCOORD comply with one point of a landmark
const unsigned int nbCoords = scoord.getGraphicDataSize();
if ( nbCoords != 2 )
throw ::fwTools::Failed("Graphic data are corrupted.");
//*** Get IMAGE *****//
const ::gdcm::DataSet * gDsIMAGE = helper::DicomSR::getTypedContainer(DicomDictionarySR::getTypeString(DicomDictionarySR::IMAGE),
*gDsSCOORD);
if ( gDsIMAGE == 0 )
throw ::fwTools::Failed("Referenced Type not found or unappropriated");
if ( !gDsIMAGE->FindDataElement( ::gdcm::Tag(0x0008,0x1199) ) ) // Referenced SOP Sequence
throw ::fwTools::Failed("Referenced sequence not found");
const ::gdcm::DataElement & gDeRefSeq = gDsIMAGE->GetDataElement( ::gdcm::Tag(0x0008,0x1199) ); // Referenced SOP Sequence
const ::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSqRefSeq = gDeRefSeq.GetValueAsSQ();
if ( gSqRefSeq->GetNumberOfItems() < 1 )
throw ::fwTools::Failed("Referenced sequence empty");
const ::gdcm::Item & gItRefSeq = gSqRefSeq->GetItem(1);
const ::gdcm::DataSet & gDsRefSeq = gItRefSeq.GetNestedDataSet();
::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance();
// For multiframe image, we search one indexes of frame
if (dicomInstance->getIsMultiFrame())
{
// Referenced Frame Number
refFrame = helper::GdcmData::getTagValue<0x0008,0x1160>(gDsRefSeq); // Type 1C
if (refFrame.empty())
{// If referenced frames number are not found
refFrame = "1"; // First frame is referenced for 2D image
::fwData::Image::csptr image = this->getConcreteObject();
if (image->getNumberOfDimensions() > 2)
{// All frames are referenced for 3D image
const unsigned int nbFrames = image->getSize()[2];
for (unsigned int i = 2; i <= nbFrames; ++i)
{
refFrame += separator + ::fwTools::getString(i);
}
}
}
}
else
{
// Referenced SOP Instance UID
const std::string SOPInstanceUID = helper::GdcmData::getTagValue<0x0008,0x1155>(gDsRefSeq); // Type 1
if (SOPInstanceUID.empty())
throw ::fwTools::Failed("Referenced image empty");
const std::vector< std::string > & referencedSOPInstanceUIDs = dicomInstance->getCRefReferencedSOPInstanceUIDs();
try
{// Try to translate the SOP instance UID into the corresponding frame number
refFrame = ::fwTools::getString( helper::DicomSR::instanceUIDToFrameNumber(SOPInstanceUID, referencedSOPInstanceUIDs) );
}
catch(::fwTools::Failed & e)
{
throw;
}
}
// Add one landmark
if (!a_continuity)
{// if separate content
this->m_dicomLandmarks->addLabel( label );
this->m_dicomLandmarks->addSCoord( scoord );
this->m_dicomLandmarks->addRefFrame( atoi( refFrame.c_str() ) );
}
}
} // namespace reader
} // namespace gdcmIO
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#include "adjunct/desktop_util/mempool/mempool.h"
/***********************************************************************************
** Structure of the pool:
**
** Block:
** ------------------------------------------------------------------------------------------
** | pointer to next block | Block Size | Padding | Block Size * Unit |
** ------------------------------------------------------------------------------------------
**
** The padding is only used on machines that need alignment.
**
** Unit:
** ---------------------------------------------------------
** | pointer to next unit | m_unit_size |
** ---------------------------------------------------------
**
** In the case of a free unit, the 'next unit' is the next free unit; in case
** of an occupied unit, its value is '1'.
**
***********************************************************************************/
/***********************************************************************************
** Constructor
**
** GenericMemPool::GenericMemPool
** @param unit_size Size of the units to be managed in bytes
** @param units_per_block How many units to create per block
**
***********************************************************************************/
GenericMemPool::GenericMemPool(size_t unit_size, size_t units_per_block, size_t initial_units)
: m_unit_size(unit_size)
, m_units_per_block(units_per_block)
, m_initial_units(initial_units)
, m_blocks(0)
, m_free_units(0)
{
#ifdef NEEDS_RISC_ALIGNMENT
// Make sure unit size is divideable by 8 bytes
if ((m_unit_size + sizeof(void*)) % 8)
m_unit_size += 8 - ((m_unit_size + sizeof(void*)) % 8);
#else
// Make sure unit size is divideable by sizeof(void*)
if (m_unit_size % sizeof(void*))
m_unit_size += sizeof(void*) - (m_unit_size % sizeof(void*));
#endif
}
/***********************************************************************************
** Mark all units as free and free all memory kept by the pool
**
** GenericMemPool::DeleteAll
**
***********************************************************************************/
void GenericMemPool::DeleteAll()
{
while (m_blocks)
{
void* next_block = *m_blocks;
op_free(m_blocks);
m_blocks = (void**)next_block;
}
m_free_units = 0;
}
/***********************************************************************************
** Create a new block of units
**
** GenericMemPool::NewBlock
** @param block_size Size of block to create (in units)
**
***********************************************************************************/
void GenericMemPool::NewBlock(size_t block_size)
{
size_t real_unit_size = sizeof(void*) + m_unit_size;
size_t word_unit_size = real_unit_size / sizeof(void*);
void** new_block = (void**)op_malloc((HeaderWords * sizeof(void*)) + (real_unit_size * block_size));
if (!new_block)
return;
// Save block size
*(new_block + 1) = (void*)block_size;
// Initialize units
void** unit = new_block + HeaderWords;
for (size_t i = 0; i < block_size - 1; i++, unit += word_unit_size)
{
*unit = unit + word_unit_size;
}
*unit = m_free_units;
// Maintain lists
*new_block = m_blocks;
m_blocks = new_block;
m_free_units = new_block + HeaderWords;
}
|
#include <sstream>
#include "ltr_client/utility/data_info.h"
using std::stringstream;
string ToString(const DataInfo& info) {;
stringstream out(stringstream::out);
out << "TDataInfo(name=" << info.name
<< ", approach=" << info.approach
<< ", format=" << info.format
<< ", file_name=" << info.file
<< ")";
return out.str();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.