text
stringlengths
54
60.6k
<commit_before>#include <polar/core/log.h> #include <polar/fs/local.h> #include <polar/util/sdl.h> namespace polar::core { std::shared_ptr<logger> logger::instance; void logger::msgbox(std::string title, std::string msg) { #if defined(_WIN32) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL); #endif std::cerr << title << ": " << msg << std::endl; } logger::logger(priority_t priority) : file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc), priority(priority) {} } <commit_msg>Throw exception on fatal error<commit_after>#include <polar/core/log.h> #include <polar/fs/local.h> #include <polar/util/sdl.h> namespace polar::core { std::shared_ptr<logger> logger::instance; void logger::msgbox(std::string title, std::string msg) { #if defined(_WIN32) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL); #endif std::cerr << title << ": " << msg << std::endl; throw std::runtime_error("fatal error"); } logger::logger(priority_t priority) : file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc), priority(priority) {} } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <vw/Image/ImageView.h> #include <vw/Image/PixelMask.h> #include <vw/Image/PixelMath.h> #include <vw/Image/PixelTypeInfo.h> #include <vw/Image/PixelTypes.h> #include <vw/Math/Vector.h> #include <vw/Math/LevenbergMarquardt.h> #include <vw/Camera/CameraModel.h> #include <vw/Stereo/StereoModel.h> namespace vw { namespace stereo { namespace detail { class PointLMA : public math::LeastSquaresModelBase<PointLMA> { const camera::CameraModel *m_camera1, *m_camera2; public: typedef Vector<double,4> result_type; typedef Vector<double,3> domain_type; typedef Matrix<double> jacobian_type; PointLMA( camera::CameraModel const* cam1, camera::CameraModel const* cam2 ) : m_camera1(cam1), m_camera2(cam2) {} inline result_type operator()( domain_type const& x ) const { Vector4 output; subvector(output,0,2) = m_camera1->point_to_pixel( x ); subvector(output,2,2) = m_camera2->point_to_pixel( x ); return output; } }; } StereoModel::StereoModel(camera::CameraModel const* camera_model1, camera::CameraModel const* camera_model2, bool least_squares_refine ) : m_camera1(camera_model1), m_camera2(camera_model2), m_least_squares(least_squares_refine) {} ImageView<Vector3> StereoModel::operator()(ImageView<PixelMask<Vector2f> > const& disparity_map, ImageView<double> &error) const { // Error analysis double mean_error = 0.0; double max_error = 0.0; int32 point_count = 0; int32 divergent = 0; // Allocate xyz image and get pointer to buffer ImageView<Vector3> xyz(disparity_map.cols(), disparity_map.rows()); error.set_size(disparity_map.cols(), disparity_map.rows()); // Compute 3D position for each pixel in the disparity map vw_out() << "StereoModel: Applying camera models\n"; for (int32 y = 0; y < disparity_map.rows(); y++) { if (y % 100 == 0) { printf("\tStereoModel computing points: %0.2f%% complete.\r", 100.0f*float(y)/disparity_map.rows()); fflush(stdout); } for (int32 x = 0; x < disparity_map.cols(); x++) { if ( is_valid(disparity_map(x,y)) ) { xyz(x,y) = (*this)(Vector2( x, y), Vector2( x+disparity_map(x,y)[0], y+disparity_map(x,y)[1]), error(x,y) ); if (error(x,y) >= 0) { // Keep track of error statistics if (error(x,y) > max_error) max_error = error(x,y); mean_error += error(x,y); ++point_count; } else { // rays diverge or are parallel xyz(x,y) = Vector3(); divergent++; } } else { xyz(x,y) = Vector3(); error(x,y) = 0; } } } if (divergent != 0) vw_out() << "WARNING in StereoModel: " << divergent << " rays diverged or were parallel!\n"; vw_out() << "\tStereoModel computing points: Done. \n"; vw_out() << "\tMean error = " << mean_error/double(point_count) << ", Max error = " << max_error << std::endl; return xyz; } bool StereoModel::are_nearly_parallel(Vector3 const& vec1, Vector3 const& vec2) const{ // If vec1 and vec2 are nearly parallel, there will be // very large numerical uncertainty about where to place the // point. We set a threshold here to reject points that are // on nearly parallel rays. The threshold of 1e-4 corresponds // to a convergence of less than theta = 0.81 degrees, so if // the two rays are within 0.81 degrees of being parallel, we // reject this point. // // This threshold was chosen empirically for now, but should // probably be revisited once a more rigorous analysis has // been completed. -mbroxton (11-MAR-07) return ( (1-dot_prod(vec1, vec2) < 1e-4 && !m_least_squares) || (1-dot_prod(vec1, vec2) < 1e-5 && m_least_squares) ); } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, Vector3& errorVec) const { // Note: Class RPCStereoModel inherits from this class and re-implements this function. errorVec = Vector3(); // Check for NaN values if (pix1 != pix1 || pix2 != pix2) return Vector3(); try { // Determine range by triangulation Vector3 vec1 = m_camera1->pixel_to_vector(pix1); Vector3 vec2 = m_camera2->pixel_to_vector(pix2); if (are_nearly_parallel(vec1, vec2)){ return Vector3(); } Vector3 origin1 = m_camera1->camera_center(pix1); Vector3 origin2 = m_camera2->camera_center(pix2); Vector3 result = triangulate_point(origin1, vec1, origin2, vec2, errorVec); if ( m_least_squares ) refine_point(pix1, pix2, result); // Reflect points that fall behind one of the two cameras if ( dot_prod(result - origin1, vec1) < 0 || dot_prod(result - origin2, vec2) < 0 ) { result = -result + 2*origin1; } return result; } catch (const camera::PixelToRayErr& /*e*/) { return Vector3(); } } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, double& error ) const { Vector3 errorVec; Vector3 result = operator()(pix1, pix2, errorVec); error = norm_2(errorVec); return result; } double StereoModel::convergence_angle(Vector2 const& pix1, Vector2 const& pix2) const { return acos(dot_prod(m_camera1->pixel_to_vector(pix1), m_camera2->pixel_to_vector(pix2))); } Vector3 StereoModel::triangulate_point(Vector3 const& point1, Vector3 const& vec1, Vector3 const& point2, Vector3 const& vec2, Vector3& errorVec) const { // Triangulate the point by finding the midpoint of the segment // joining the closest points on the two rays emanating // from the camera. Vector3 v12 = cross_prod(vec1, vec2); Vector3 v1 = cross_prod(v12, vec1); Vector3 v2 = cross_prod(v12, vec2); Vector3 closestPoint1 = point1 + dot_prod(v2, point2-point1)/dot_prod(v2, vec1)*vec1; Vector3 closestPoint2 = point2 + dot_prod(v1, point1-point2)/dot_prod(v1, vec2)*vec2; errorVec = closestPoint1 - closestPoint2; return 0.5 * (closestPoint1 + closestPoint2); } void StereoModel::refine_point(Vector2 const& pix1, Vector2 const& pix2, Vector3& point) const { // Refine the point by minimizing the least squares error in pixel domain. detail::PointLMA model( m_camera1, m_camera2 ); Vector4 objective( pix1[0], pix1[1], pix2[0], pix2[1] ); int status = 0; Vector3 npoint = levenberg_marquardt( model, point, objective, status, 1e-3, 1e-6, 10 ); if ( status > 0 ) point = npoint; } }} // vw::stereo <commit_msg>StereoModel: Catch all exceptions<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <vw/Image/ImageView.h> #include <vw/Image/PixelMask.h> #include <vw/Image/PixelMath.h> #include <vw/Image/PixelTypeInfo.h> #include <vw/Image/PixelTypes.h> #include <vw/Math/Vector.h> #include <vw/Math/LevenbergMarquardt.h> #include <vw/Camera/CameraModel.h> #include <vw/Stereo/StereoModel.h> namespace vw { namespace stereo { namespace detail { class PointLMA : public math::LeastSquaresModelBase<PointLMA> { const camera::CameraModel *m_camera1, *m_camera2; public: typedef Vector<double,4> result_type; typedef Vector<double,3> domain_type; typedef Matrix<double> jacobian_type; PointLMA( camera::CameraModel const* cam1, camera::CameraModel const* cam2 ) : m_camera1(cam1), m_camera2(cam2) {} inline result_type operator()( domain_type const& x ) const { Vector4 output; subvector(output,0,2) = m_camera1->point_to_pixel( x ); subvector(output,2,2) = m_camera2->point_to_pixel( x ); return output; } }; } StereoModel::StereoModel(camera::CameraModel const* camera_model1, camera::CameraModel const* camera_model2, bool least_squares_refine ) : m_camera1(camera_model1), m_camera2(camera_model2), m_least_squares(least_squares_refine) {} ImageView<Vector3> StereoModel::operator()(ImageView<PixelMask<Vector2f> > const& disparity_map, ImageView<double> &error) const { // Error analysis double mean_error = 0.0; double max_error = 0.0; int32 point_count = 0; int32 divergent = 0; // Allocate xyz image and get pointer to buffer ImageView<Vector3> xyz(disparity_map.cols(), disparity_map.rows()); error.set_size(disparity_map.cols(), disparity_map.rows()); // Compute 3D position for each pixel in the disparity map vw_out() << "StereoModel: Applying camera models\n"; for (int32 y = 0; y < disparity_map.rows(); y++) { if (y % 100 == 0) { printf("\tStereoModel computing points: %0.2f%% complete.\r", 100.0f*float(y)/disparity_map.rows()); fflush(stdout); } for (int32 x = 0; x < disparity_map.cols(); x++) { if ( is_valid(disparity_map(x,y)) ) { xyz(x,y) = (*this)(Vector2( x, y), Vector2( x+disparity_map(x,y)[0], y+disparity_map(x,y)[1]), error(x,y) ); if (error(x,y) >= 0) { // Keep track of error statistics if (error(x,y) > max_error) max_error = error(x,y); mean_error += error(x,y); ++point_count; } else { // rays diverge or are parallel xyz(x,y) = Vector3(); divergent++; } } else { xyz(x,y) = Vector3(); error(x,y) = 0; } } } if (divergent != 0) vw_out() << "WARNING in StereoModel: " << divergent << " rays diverged or were parallel!\n"; vw_out() << "\tStereoModel computing points: Done. \n"; vw_out() << "\tMean error = " << mean_error/double(point_count) << ", Max error = " << max_error << std::endl; return xyz; } bool StereoModel::are_nearly_parallel(Vector3 const& vec1, Vector3 const& vec2) const{ // If vec1 and vec2 are nearly parallel, there will be // very large numerical uncertainty about where to place the // point. We set a threshold here to reject points that are // on nearly parallel rays. The threshold of 1e-4 corresponds // to a convergence of less than theta = 0.81 degrees, so if // the two rays are within 0.81 degrees of being parallel, we // reject this point. // // This threshold was chosen empirically for now, but should // probably be revisited once a more rigorous analysis has // been completed. -mbroxton (11-MAR-07) return ( (1-dot_prod(vec1, vec2) < 1e-4 && !m_least_squares) || (1-dot_prod(vec1, vec2) < 1e-5 && m_least_squares) ); } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, Vector3& errorVec) const { // Note: Class RPCStereoModel inherits from this class and re-implements this function. errorVec = Vector3(); // Check for NaN values if (pix1 != pix1 || pix2 != pix2) return Vector3(); try { // Determine range by triangulation Vector3 vec1 = m_camera1->pixel_to_vector(pix1); Vector3 vec2 = m_camera2->pixel_to_vector(pix2); if (are_nearly_parallel(vec1, vec2)){ return Vector3(); } Vector3 origin1 = m_camera1->camera_center(pix1); Vector3 origin2 = m_camera2->camera_center(pix2); Vector3 result = triangulate_point(origin1, vec1, origin2, vec2, errorVec); if ( m_least_squares ) refine_point(pix1, pix2, result); // Reflect points that fall behind one of the two cameras if ( dot_prod(result - origin1, vec1) < 0 || dot_prod(result - origin2, vec2) < 0 ) { result = -result + 2*origin1; } return result; } catch (...) { return Vector3(); } } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, double& error ) const { Vector3 errorVec; Vector3 result = operator()(pix1, pix2, errorVec); error = norm_2(errorVec); return result; } double StereoModel::convergence_angle(Vector2 const& pix1, Vector2 const& pix2) const { return acos(dot_prod(m_camera1->pixel_to_vector(pix1), m_camera2->pixel_to_vector(pix2))); } Vector3 StereoModel::triangulate_point(Vector3 const& point1, Vector3 const& vec1, Vector3 const& point2, Vector3 const& vec2, Vector3& errorVec) const { // Triangulate the point by finding the midpoint of the segment // joining the closest points on the two rays emanating // from the camera. Vector3 v12 = cross_prod(vec1, vec2); Vector3 v1 = cross_prod(v12, vec1); Vector3 v2 = cross_prod(v12, vec2); Vector3 closestPoint1 = point1 + dot_prod(v2, point2-point1)/dot_prod(v2, vec1)*vec1; Vector3 closestPoint2 = point2 + dot_prod(v1, point1-point2)/dot_prod(v1, vec2)*vec2; errorVec = closestPoint1 - closestPoint2; return 0.5 * (closestPoint1 + closestPoint2); } void StereoModel::refine_point(Vector2 const& pix1, Vector2 const& pix2, Vector3& point) const { // Refine the point by minimizing the least squares error in pixel domain. detail::PointLMA model( m_camera1, m_camera2 ); Vector4 objective( pix1[0], pix1[1], pix2[0], pix2[1] ); int status = 0; Vector3 npoint = levenberg_marquardt( model, point, objective, status, 1e-3, 1e-6, 10 ); if ( status > 0 ) point = npoint; } }} // vw::stereo <|endoftext|>
<commit_before>// Copyright 2012, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ----------------------------------------------------------------------------- // // Tool to view protocol buffer files generated by the ReFr toolkit. // Author: [email protected] (Keith Hall) // // Example usage: // protoview -i training_data_file // protoview -M -i model_file // protoview -S -i symbol_table_file // protoview -F -i feature_message_file // #include <fstream> #include <iostream> #include <string> #include <getopt.h> #include <math.h> #include "../proto/data.pb.h" #include "../proto/dataio.h" #include "../utils/kdebug.h" #include "../proto/model.pb.h" using namespace std; int main(int argc, char* argv[]) { bool compressed = true; bool base64 = true; int option_char; bool decode_model = false; bool decode_features = false; bool decode_symbols = false; string input_file; // Invokes member function `int operator ()(void);' while ((option_char = getopt(argc, argv, "RUi:MFS")) != EOF) { switch (option_char) { case 'S': decode_symbols = true; break; case 'M': decode_model = true; break; case 'F': decode_features = true; break; case 'U': compressed = false; break; case 'R': base64 = false; break; case 'i': input_file = optarg; break; case '?': cerr << "usage: [-R] [-U] [-M] [-F] [-S] [-i file]" << endl; cerr << "-R - view raw encoded file (non-base64)" << endl; cerr << "-U - uncompressed input file" << endl; cerr << "-i - if empty, uses stdin" << endl; cerr << "-M - output model messages" << endl; cerr << "-F - output feature messages" << endl; cerr << "-S - output symbol messages" << endl; return -1; break; } } ConfusionProtoIO* reader; if (!input_file.empty()) { reader = new ConfusionProtoIO(input_file, ConfusionProtoIO::READ, compressed, base64); } else { reader = new ConfusionProtoIO("", ConfusionProtoIO::READSTD, false, base64); } bool reader_valid = true; bool first_message = true; while (reader_valid) { google::protobuf::Message* tmp_msg; if (decode_model) { if (first_message) { tmp_msg = new confusion_learning::ModelMessage; first_message = false; } else { tmp_msg = new confusion_learning::FeatureMessage; } } else if (decode_features) { tmp_msg = new confusion_learning::FeatureMessage; } else if (decode_symbols) { tmp_msg = new confusion_learning::SymbolMessage; } else { // Default is to decode candidate-set messages tmp_msg = new confusion_learning::CandidateSetMessage; } reader_valid = reader->Read(tmp_msg); if (reader_valid) { cout << "Data: " << tmp_msg->Utf8DebugString(); } } reader->Close(); delete reader; google::protobuf::ShutdownProtobufLibrary(); } <commit_msg>Fixed memory leak.<commit_after>// Copyright 2012, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ----------------------------------------------------------------------------- // // Tool to view protocol buffer files generated by the ReFr toolkit. // Author: [email protected] (Keith Hall) // // Example usage: // protoview -i training_data_file // protoview -M -i model_file // protoview -S -i symbol_table_file // protoview -F -i feature_message_file // #include <fstream> #include <iostream> #include <string> #include <getopt.h> #include <math.h> #include "../proto/data.pb.h" #include "../proto/dataio.h" #include "../utils/kdebug.h" #include "../proto/model.pb.h" using namespace std; int main(int argc, char* argv[]) { bool compressed = true; bool base64 = true; int option_char; bool decode_model = false; bool decode_features = false; bool decode_symbols = false; string input_file; // Invokes member function `int operator ()(void);' while ((option_char = getopt(argc, argv, "RUi:MFS")) != EOF) { switch (option_char) { case 'S': decode_symbols = true; break; case 'M': decode_model = true; break; case 'F': decode_features = true; break; case 'U': compressed = false; break; case 'R': base64 = false; break; case 'i': input_file = optarg; break; case '?': cerr << "usage: [-R] [-U] [-M] [-F] [-S] [-i file]" << endl; cerr << "-R - view raw encoded file (non-base64)" << endl; cerr << "-U - uncompressed input file" << endl; cerr << "-i - if empty, uses stdin" << endl; cerr << "-M - output model messages" << endl; cerr << "-F - output feature messages" << endl; cerr << "-S - output symbol messages" << endl; return -1; break; } } ConfusionProtoIO* reader; if (!input_file.empty()) { reader = new ConfusionProtoIO(input_file, ConfusionProtoIO::READ, compressed, base64); } else { reader = new ConfusionProtoIO("", ConfusionProtoIO::READSTD, false, base64); } bool reader_valid = true; bool first_message = true; while (reader_valid) { google::protobuf::Message* tmp_msg; if (decode_model) { if (first_message) { tmp_msg = new confusion_learning::ModelMessage; first_message = false; } else { tmp_msg = new confusion_learning::FeatureMessage; } } else if (decode_features) { tmp_msg = new confusion_learning::FeatureMessage; } else if (decode_symbols) { tmp_msg = new confusion_learning::SymbolMessage; } else { // Default is to decode candidate-set messages tmp_msg = new confusion_learning::CandidateSetMessage; } if (tmp_msg == NULL) { continue } reader_valid = reader->Read(tmp_msg); if (reader_valid) { cout << "Data: " << tmp_msg->Utf8DebugString(); } delete tmp_msg; } reader->Close(); delete reader; google::protobuf::ShutdownProtobufLibrary(); } <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define EIGEN_USE_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/quantize_and_dequantize_op.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/type_traits.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; // Simulate quantization precision loss in a float tensor by: // 1. Quantize the tensor to fixed point numbers, which should match the target // quantization method when it is used in inference. // 2. Dequantize it back to floating point numbers for the following ops, most // likely matmul. template <typename Device, typename T> class QuantizeAndDequantizeV2Op : public OpKernel { public: explicit QuantizeAndDequantizeV2Op(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_, " with signed_input_ ", signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); string round_mode_string; OP_REQUIRES_OK(ctx, ctx->GetAttr("round_mode", &round_mode_string)); OP_REQUIRES( ctx, (round_mode_string == "HALF_UP" || round_mode_string == "HALF_TO_EVEN"), errors::InvalidArgument("Round mode string must be " "'HALF_UP' or " "'HALF_TO_EVEN', is '" + round_mode_string + "'")); if (round_mode_string == "HALF_UP") { round_mode_ = ROUND_HALF_UP; } else if (round_mode_string == "HALF_TO_EVEN") { round_mode_ = ROUND_HALF_TO_EVEN; } } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor input_min_tensor; Tensor input_max_tensor; if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); auto min_val = input_min_tensor.scalar<T>()(); auto max_val = input_max_tensor.scalar<T>()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument("Invalid range: input_min ", min_val, " > input_max ", max_val)); } else { OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_max_tensor)); } functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, output->flat<T>()); } private: bool signed_input_; int num_bits_; bool range_given_; QuantizerRoundMode round_mode_; }; // Simulate quantization precision loss in a float tensor by: // 1. Quantize the tensor to fixed point numbers, which should match the target // quantization method when it is used in inference. // 2. Dequantize it back to floating point numbers for the following ops, most // likely matmul. // Almost identical to QuantizeAndDequantizeV2Op, except that num_bits is a // tensor. template <typename Device, typename T> class QuantizeAndDequantizeV3Op : public OpKernel { public: explicit QuantizeAndDequantizeV3Op(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor num_bits_tensor; num_bits_tensor = ctx->input(3); int num_bits_val = num_bits_tensor.scalar<int32>()(); OP_REQUIRES( ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_val, " with signed_input_ ", signed_input_)); Tensor input_min_tensor; Tensor input_max_tensor; if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); auto min_val = input_min_tensor.scalar<T>()(); auto max_val = input_max_tensor.scalar<T>()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument("Invalid range: input_min ", min_val, " > input_max ", max_val)); } else { OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_max_tensor)); } functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_val, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, output->flat<T>()); } private: bool signed_input_; bool range_given_; }; // DEPRECATED: Use QuantizeAndDequantizeV2Op. template <typename Device, typename T> class QuantizeAndDequantizeOp : public OpKernel { public: explicit QuantizeAndDequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_, " with signed_input_ ", signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("input_min", &input_min_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("input_max", &input_max_)); if (range_given_) { OP_REQUIRES( ctx, input_min_ <= input_max_, errors::InvalidArgument("Invalid range: input_min ", input_min_, " > input_max ", input_max_)); } } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); // One global scale. Tensor input_min_tensor(DataTypeToEnum<T>::value, TensorShape()); Tensor input_max_tensor(DataTypeToEnum<T>::value, TensorShape()); // Initialize the tensors with the values in the Attrs. input_min_tensor.template scalar<T>()() = static_cast<T>(input_min_); input_max_tensor.template scalar<T>()() = static_cast<T>(input_max_); functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> functor; functor(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, output->flat<T>()); } private: bool signed_input_; int num_bits_; bool range_given_; float input_min_; float input_max_; }; // Specialization for CPUDevice. namespace functor { template <typename T> struct QuantizeAndDequantizeOneScaleFunctor<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::ConstVec input, const bool signed_input, const int num_bits, const bool range_given, Tensor* input_min_tensor, Tensor* input_max_tensor, QuantizerRoundMode round_mode, typename TTypes<T>::Vec out) { QuantizeAndDequantizeOneScaleImpl<CPUDevice, T>::Compute( d, input, signed_input, num_bits, range_given, input_min_tensor, input_max_tensor, round_mode, out); } }; } // namespace functor #define REGISTER_CPU_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV2Op<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV3") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV3Op<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("QuantizeAndDequantize").Device(DEVICE_CPU).TypeConstraint<T>("T"), \ QuantizeAndDequantizeOp<CPUDevice, T>); TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); #undef REGISTER_CPU_KERNEL #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define REGISTER_GPU_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV2") \ .Device(DEVICE_GPU) \ .HostMemory("input_max") \ .HostMemory("input_min") \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV2Op<GPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV3") \ .Device(DEVICE_GPU) \ .HostMemory("input_max") \ .HostMemory("input_min") \ .HostMemory("num_bits") \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV3Op<GPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("QuantizeAndDequantize").Device(DEVICE_GPU).TypeConstraint<T>("T"), \ QuantizeAndDequantizeOp<GPUDevice, T>); TF_CALL_float(REGISTER_GPU_KERNEL); TF_CALL_double(REGISTER_GPU_KERNEL); #undef REGISTER_GPU_KERNEL #endif } // namespace tensorflow <commit_msg>Added comment to endif<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define EIGEN_USE_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/quantize_and_dequantize_op.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/type_traits.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; // Simulate quantization precision loss in a float tensor by: // 1. Quantize the tensor to fixed point numbers, which should match the target // quantization method when it is used in inference. // 2. Dequantize it back to floating point numbers for the following ops, most // likely matmul. template <typename Device, typename T> class QuantizeAndDequantizeV2Op : public OpKernel { public: explicit QuantizeAndDequantizeV2Op(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_, " with signed_input_ ", signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); string round_mode_string; OP_REQUIRES_OK(ctx, ctx->GetAttr("round_mode", &round_mode_string)); OP_REQUIRES( ctx, (round_mode_string == "HALF_UP" || round_mode_string == "HALF_TO_EVEN"), errors::InvalidArgument("Round mode string must be " "'HALF_UP' or " "'HALF_TO_EVEN', is '" + round_mode_string + "'")); if (round_mode_string == "HALF_UP") { round_mode_ = ROUND_HALF_UP; } else if (round_mode_string == "HALF_TO_EVEN") { round_mode_ = ROUND_HALF_TO_EVEN; } } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor input_min_tensor; Tensor input_max_tensor; if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); auto min_val = input_min_tensor.scalar<T>()(); auto max_val = input_max_tensor.scalar<T>()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument("Invalid range: input_min ", min_val, " > input_max ", max_val)); } else { OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_max_tensor)); } functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, output->flat<T>()); } private: bool signed_input_; int num_bits_; bool range_given_; QuantizerRoundMode round_mode_; }; // Simulate quantization precision loss in a float tensor by: // 1. Quantize the tensor to fixed point numbers, which should match the target // quantization method when it is used in inference. // 2. Dequantize it back to floating point numbers for the following ops, most // likely matmul. // Almost identical to QuantizeAndDequantizeV2Op, except that num_bits is a // tensor. template <typename Device, typename T> class QuantizeAndDequantizeV3Op : public OpKernel { public: explicit QuantizeAndDequantizeV3Op(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor num_bits_tensor; num_bits_tensor = ctx->input(3); int num_bits_val = num_bits_tensor.scalar<int32>()(); OP_REQUIRES( ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_val, " with signed_input_ ", signed_input_)); Tensor input_min_tensor; Tensor input_max_tensor; if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); auto min_val = input_min_tensor.scalar<T>()(); auto max_val = input_max_tensor.scalar<T>()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument("Invalid range: input_min ", min_val, " > input_max ", max_val)); } else { OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape(), &input_max_tensor)); } functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_val, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, output->flat<T>()); } private: bool signed_input_; bool range_given_; }; // DEPRECATED: Use QuantizeAndDequantizeV2Op. template <typename Device, typename T> class QuantizeAndDequantizeOp : public OpKernel { public: explicit QuantizeAndDequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63), errors::InvalidArgument("num_bits is out of range: ", num_bits_, " with signed_input_ ", signed_input_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("input_min", &input_min_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("input_max", &input_max_)); if (range_given_) { OP_REQUIRES( ctx, input_min_ <= input_max_, errors::InvalidArgument("Invalid range: input_min ", input_min_, " > input_max ", input_max_)); } } void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); // One global scale. Tensor input_min_tensor(DataTypeToEnum<T>::value, TensorShape()); Tensor input_max_tensor(DataTypeToEnum<T>::value, TensorShape()); // Initialize the tensors with the values in the Attrs. input_min_tensor.template scalar<T>()() = static_cast<T>(input_min_); input_max_tensor.template scalar<T>()() = static_cast<T>(input_max_); functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> functor; functor(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, output->flat<T>()); } private: bool signed_input_; int num_bits_; bool range_given_; float input_min_; float input_max_; }; // Specialization for CPUDevice. namespace functor { template <typename T> struct QuantizeAndDequantizeOneScaleFunctor<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::ConstVec input, const bool signed_input, const int num_bits, const bool range_given, Tensor* input_min_tensor, Tensor* input_max_tensor, QuantizerRoundMode round_mode, typename TTypes<T>::Vec out) { QuantizeAndDequantizeOneScaleImpl<CPUDevice, T>::Compute( d, input, signed_input, num_bits, range_given, input_min_tensor, input_max_tensor, round_mode, out); } }; } // namespace functor #define REGISTER_CPU_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV2Op<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV3") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV3Op<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("QuantizeAndDequantize").Device(DEVICE_CPU).TypeConstraint<T>("T"), \ QuantizeAndDequantizeOp<CPUDevice, T>); TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); #undef REGISTER_CPU_KERNEL #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define REGISTER_GPU_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV2") \ .Device(DEVICE_GPU) \ .HostMemory("input_max") \ .HostMemory("input_min") \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV2Op<GPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("QuantizeAndDequantizeV3") \ .Device(DEVICE_GPU) \ .HostMemory("input_max") \ .HostMemory("input_min") \ .HostMemory("num_bits") \ .TypeConstraint<T>("T"), \ QuantizeAndDequantizeV3Op<GPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("QuantizeAndDequantize").Device(DEVICE_GPU).TypeConstraint<T>("T"), \ QuantizeAndDequantizeOp<GPUDevice, T>); TF_CALL_float(REGISTER_GPU_KERNEL); TF_CALL_double(REGISTER_GPU_KERNEL); #undef REGISTER_GPU_KERNEL #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM } // namespace tensorflow <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <memory> using namespace std; static void test_unique() { unique_ptr<string> films[5] = { unique_ptr<string> (new string("Fowl Balls")), unique_ptr<string> (new string("Duck Walks")), unique_ptr<string> (new string("Chicken Runs")), unique_ptr<string> (new string("Turkey Errors")), unique_ptr<string> (new string("Goose Eggs")) }; cout << "The nominees for best avian baseball file are\n"; for (int i = 0; i < 5; i++) { cout << *films[i] << endl; } unique_ptr<string> pwin = std::move(films[2]); cout << "The winner is " << *pwin << endl; } static void test_shared() { shared_ptr<string> films[5] = { shared_ptr<string> (new string("Fowl Balls")), shared_ptr<string> (new string("Duck Walks")), shared_ptr<string> (new string("Chicken Runs")), shared_ptr<string> (new string("Turkey Errors")), shared_ptr<string> (new string("Goose Eggs")) }; shared_ptr<string> pwin = films[2]; cout << "The nominees for best avian baseball file are\n"; for (int i = 0; i < 5; i++) { cout << *films[i] << endl; } cout << "The winner is " << *pwin << endl; } class A : public std::enable_shared_from_this<A> { public: A() { cout << "A::A() constructor" << endl; } ~A() { cout << "A::~A() destructor" << endl; } std::shared_ptr<A> GetSelf() { return shared_from_this(); } }; int main() { test_unique(); test_shared(); std::shared_ptr<A> pA(new A); std::shared_ptr<A> pB = pA->GetSelf(); std::shared_ptr<A> pC = std::make_shared<A>(); return 0; } <commit_msg>modify on languages/program_on_cpp/In_Depth_C++_11/chapter4-smartpointer/shared_ptr.cpp<commit_after>#include <iostream> #include <string> #include <memory> using namespace std; static void test_unique() { unique_ptr<string> films[5] = { unique_ptr<string> (new string("Fowl Balls")), unique_ptr<string> (new string("Duck Walks")), unique_ptr<string> (new string("Chicken Runs")), unique_ptr<string> (new string("Turkey Errors")), unique_ptr<string> (new string("Goose Eggs")) }; cout << "The nominees for best avian baseball file are\n"; for (int i = 0; i < 5; i++) { cout << *films[i] << endl; } unique_ptr<string> pwin = std::move(films[2]); cout << "The winner is " << *pwin << endl; } static void test_shared() { shared_ptr<string> films[5] = { shared_ptr<string> (new string("Fowl Balls")), shared_ptr<string> (new string("Duck Walks")), shared_ptr<string> (new string("Chicken Runs")), shared_ptr<string> (new string("Turkey Errors")), shared_ptr<string> (new string("Goose Eggs")) }; shared_ptr<string> pwin = films[2]; cout << "The nominees for best avian baseball file are\n"; for (int i = 0; i < 5; i++) { cout << *films[i] << endl; } cout << "The winner is " << *pwin << endl; } class A : public std::enable_shared_from_this<A> { public: A() { cout << "A::A() constructor" << endl; } ~A() { cout << "A::~A() destructor" << endl; } std::shared_ptr<A> GetSelf() { return shared_from_this(); } }; void test_reset() { int *p = new int(1); std::shared_ptr<int> pInt = nullptr; pInt.reset(p); printf("i = %d\n", *pInt); } int main() { test_unique(); test_shared(); std::shared_ptr<A> pA(new A); std::shared_ptr<A> pB = pA->GetSelf(); std::shared_ptr<A> pC = std::make_shared<A>(); test_reset(); return 0; } <|endoftext|>
<commit_before>#include "tiramisu/tiramisu.h" // This code is the Tiramisu implementation of the following Matlab code // https://www.mathworks.com/examples/computer-vision/community/35625-lucas-kanade-method-example-2?s_tid=examples_p1_BOTH using namespace tiramisu; int main(int argc, char* argv[]) { // Declare the function name tiramisu::init("optical_flow_tiramisu"); // TODO: input should be a gray image. // TODO: check data types. // TODO: isolate ludcmp and compare it separately. // TODO: compare correctness (partial results) to Matlab. // TODO: compare results and performance to OpenCV (one pyramid). // Declare input sizes // TODO: "input" dimension sizes should be expressions not variables. input SIZES("SIZES", {var("S", 0, 2)}, p_int32); constant N0("N0", SIZES(0)); constant N1("N1", SIZES(1)); constant NC("NC", 20); // Number of corners constant w("w", 10); // Window size // Loop iterators var x("x", 0, N1), y("y", 0, N0), k("k", 0, NC); // input images input im1("im1", {y, x}, p_uint8); input im2("im2", {y, x}, p_uint8); // Corners input C1("C1", {k}, p_int32); input C2("C2", {k}, p_int32); // First convolution (partial on x) expr e1 = cast(p_uint8, (cast(p_float32, im1(y, x) - im1(y, x + 1) + im1(y + 1, x) - im1(y + 1, x + 1)))); computation Ix_m("Ix_m", {y, x}, e1); // Second convolution (partial on y) expr e2 = cast(p_uint8, (cast(p_float32, im1(y, x) + im1(y, x + 1) - im1(y + 1, x + 1) - im1(y + 1, x )))); computation Iy_m("Iy_m", {y, x}, e2); // Third convolution expr e3 = cast(p_uint8, (cast(p_float32, im1(y, x) + im1(y, x + 1) + im1(y + 1, x) + im1(y + 1, x + 1)))); expr e4 = cast(p_uint8, (cast(p_float32, (- im2(y, x)) - im2(y, x + 1) - im2(y + 1, x) - im2(y + 1, x + 1)))); computation It_m("It_m", {y, x}, e3 + e4); // Second part of the algorithm // Compute "u" and "v" for each corner "k" computation i({k}, C2(k)); computation j({k}, C1(k)); // Ix = Ix_m(i-w:i+w, j-w:j+w); // Iy = Iy_m(i-w:i+w, j-w:j+w); // It = It_m(i-w:i+w, j-w:j+w); // Ix = Ix(:); % flatten the IX 2D array into a vector // Iy = Iy(:); // A = [Ix Iy]; // b = -It(:); % get b here var x1("x1", 0, 2*w); var y1("y1", 0, 2*w); computation A("A", {k, y1, x1}, Ix_m(i(0)+y1-w, j(0)+x1-w)); //TODO: use i(k) and j(k) instead of i(0) and j(0) computation A_right("A_right", {k, y1, x1}, Iy_m(i(0)+y1-w, j(0)+x1-w)); //i(k), j(k) computation b("b", {k, y1, x1}, (-It_m(i(0)+y1-w, j(0)+x1-w))); //i(k), j(k) // Compute pinv(A): // tA = transpose(A) // mul1 = tA * A // X = inv(mul1) // pinv(A) = X * tA var x2("x2", 0, 4*w); var y2("y2", 0, 4*w); var l1("l1", 0, 2*w); computation tA("tA", {k, x2, y1}, A(k, y1, x2)); computation mul1("mul1", {k, x2, y2}, expr((uint8_t) 0)); computation mul1_update("mul1_update", {k, x2, y2, l1}, mul1(k, x2, y2) + tA(k, x2, l1) * A(k, l1, y2)); // Compute the inverse of mul1 using LU decomposition. // We use the following reference implementation (lines 95 to 126) // https://github.com/Meinersbur/polybench/blob/master/polybench-code/linear-algebra/solvers/ludcmp/ludcmp.c // 1)- Compute the LU decomposition of mul1: LU = mul1 // 2)- Use LU to compute X, the inverse of mul1 by solving the following // system: // LU*X=I // where I is the identity matrix. var i1("i1", 0, 4*w); var j1("j1", 0, i1); var l2("l2", 0, j1); // LU decomposition of A computation w1("w1", {k, i1, j1}, mul1(k, i1, j1)); computation w1_update("w1_update", {k, i1, j1, l2}, w1(k, i1, j1) - mul1(k, i1, l2)*mul1(k, l2, j1)); computation temp("temp", {k, i1, j1}, w1(k, i1, j1)/mul1(k, j1, j1)); var j2("j2", i1, 4*w); var l3("l3", 0, i1); computation w2("w2", {k, i1, j2}, temp(k, i1, j2)); computation w2_update("w2_update", {k, i1, j2, l3}, w2(k, i1, j2) - temp(k, i1, l3)*temp(k, l3, j2)); computation LU("LU", {k, i1, j2}, w2(k, i1, j2)); // Finding the inverse of A. // The inverse will be stored in X. var r("r", 0, 4*w); var r2("r2", r, r+1); computation Y("Y", {k, r, i1}, p_uint8); computation bp("bp", {k, r, i1}, expr((uint8_t) 0)); computation bp_update("bp_update", {k, r, r2}, expr((uint8_t) 1)); computation w3("w3", {k, r, i1}, bp(k, r, i1)); computation w3_update("w3_update", {k, r, i1, j1}, w3(k, r, i1) - LU(k, i1, j1)*Y(k, r, j1)); Y.set_expression(w3(k, r, i1)); // TODO: support reverse order loops. var j3("j3", i1+1, 4*w); computation X("X", {k, r, i1}, p_uint8); computation w4("w4", {k, r, i1}, Y(k, r, 4-w-1-i1)); computation w4_update("w4_update", {k, r, i1, j3}, w4(k, r, i1) - LU(k, 4-w-1-i1, j3)*X(k, r, j3)); X.set_expression(w4(k, r, i1)/LU(k, 4-w-1-i1, 4-w-1-i1)); // Computing pinv(A)=X*tA var j4("j4", 0, 4*w); computation pinvA("pinvA", {k, i1, y1}, expr((uint8_t) 0)); computation pinvA_update("pinvA_update", {k, i1, y1, j4}, pinvA(k, i1, y1) + X(k, i1, j4)*tA(k, j4, y1)); // Compute nu = pinv(A)*b computation nu("nu", {k, i1, x1}, expr((uint8_t) 0)); computation nu_update("nu_update", {k, i1, x1, y1}, nu(k, i1, x1) + pinvA(k, i1, y1)*b(k, y1, x1)); // Results // u(k) = nu(0) // v(k) = nu(1) Ix_m.then(Iy_m, x) .then(It_m, x) .then(i, computation::root) .then(j, k) .then(A, y1) .then(A_right, y1) .then(b, y1) .then(tA, computation::root) .then(mul1, computation::root) .then(mul1_update, y2) .then(w1, computation::root) .then(w1_update, j1) .then(temp, j1) .then(w2, computation::root) .then(w2_update, j2) .then(LU, j2) .then(bp, computation::root) .then(bp_update, r) .then(w3, r) .then(w3_update, i1) .then(Y, i1) .then(w4, computation::root) .then(w4_update, i1) .then(X, i1) .then(pinvA, computation::root) .then(pinvA_update, y1) .then(nu, computation::root) .then(nu_update, x1); // Buffer allocation and mapping computations to buffers buffer b_SIZES("b_SIZES", {2}, p_int32, a_input); buffer b_im1("b_im1", {N0, N1}, p_uint8, a_input); buffer b_im2("b_im2", {N0, N1}, p_uint8, a_input); buffer b_Ix_m("b_Ix_m", {N0, N1}, p_float32, a_output); buffer b_Iy_m("b_Iy_m", {N0, N1}, p_float32, a_output); buffer b_It_m("b_It_m", {N0, N1}, p_float32, a_output); buffer b_C1("b_C1", {NC}, p_int32, a_input); buffer b_C2("b_C2", {NC}, p_int32, a_input); buffer b_i("b_i", {1}, p_int32, a_temporary); buffer b_j("b_j", {1}, p_int32, a_temporary); buffer b_A("b_A", {2*w, 4*w}, p_float32, a_temporary); buffer b_b("b_b", {2*w, 2*w}, p_float32, a_temporary); buffer b_tA("b_tA", {4*w, 2*w}, p_float32, a_temporary); buffer b_mul("b_mul", {2*w, 2*w}, p_float32, a_temporary); buffer b_w1("b_w1", {1}, p_float32, a_temporary); buffer b_temp("b_temp", {2*w, 2*w}, p_float32, a_temporary); buffer b_w2("b_w2", {1}, p_float32, a_temporary); buffer b_LU("b_LU", {2*w, 2*w}, p_float32, a_temporary); buffer b_y("b_y", {2*w, 2*w}, p_float32, a_temporary); buffer b_bp("b_bp", {2*w, 2*w}, p_float32, a_temporary); buffer b_w3("b_w3", {1}, p_float32, a_temporary); buffer b_x("b_x", {2*w, 2*w}, p_float32, a_temporary); buffer b_w4("b_w4", {1}, p_float32, a_temporary); buffer b_pinvA("b_pinvA", {4*w, 2*w}, p_float32, a_temporary); buffer b_nu("b_nu", {4*w, 2*w}, p_float32, a_temporary); SIZES.store_in(&b_SIZES); im1.store_in(&b_im1); im2.store_in(&b_im2); Ix_m.store_in(&b_Ix_m); Iy_m.store_in(&b_Iy_m); It_m.store_in(&b_It_m); C1.store_in(&b_C1); C2.store_in(&b_C2); i.store_in(&b_i, {0}); j.store_in(&b_j, {0}); A.store_in(&b_A, {x1, y1}); A_right.store_in(&b_A, {x1+2*10, y1}); //2*w b.store_in(&b_b, {x1, y1}); tA.store_in(&b_tA, {x2, y1}); mul1.store_in(&b_mul, {x2, y2}); mul1_update.store_in(&b_mul, {x2, y2}); w1.store_in(&b_w1, {0}); w1_update.store_in(&b_w1, {0}); temp.store_in(&b_temp, {i1, j1}); w2.store_in(&b_w2, {0}); w2_update.store_in(&b_w2, {0}); LU.store_in(&b_LU, {i1, j2}); Y.store_in(&b_y, {r, i1}); bp.store_in(&b_bp, {r, i1}); bp_update.store_in(&b_bp, {r, r2}); w3.store_in(&b_w3, {0}); w3_update.store_in(&b_w3, {0}); X.store_in(&b_x, {r, i1}); w4.store_in(&b_w4, {0}); w4_update.store_in(&b_w4, {0}); pinvA.store_in(&b_pinvA, {i1, y1}); pinvA_update.store_in(&b_pinvA, {i1, y1}); nu.store_in(&b_nu, {i1, x1}); nu_update.store_in(&b_nu, {i1, x1}); tiramisu::codegen({&b_SIZES, &b_im1, &b_im2, &b_Ix_m, &b_Iy_m, &b_It_m, &b_C1, &b_C2}, "build/generated_fct_optical_flow.o"); return 0; } <commit_msg>Update optical flow<commit_after>#include "tiramisu/tiramisu.h" // This code is the Tiramisu implementation of the following Matlab code // https://www.mathworks.com/examples/computer-vision/community/35625-lucas-kanade-method-example-2?s_tid=examples_p1_BOTH using namespace tiramisu; int main(int argc, char* argv[]) { // Declare the function name tiramisu::init("optical_flow_tiramisu"); // TODO: input should be a gray image. // TODO: check data types. // TODO: isolate ludcmp and compare it separately. // TODO: compare correctness (partial results) to Matlab. // TODO: compare results and performance to OpenCV (one pyramid). // Declare input sizes // TODO: "input" dimension sizes should be expressions not variables. input SIZES("SIZES", {var("S", 0, 2)}, p_int32); constant N0("N0", SIZES(0)); constant N1("N1", SIZES(1)); constant NC("NC", 20); // Number of corners // Window size #define w 10 // Loop iterators var x("x", 0, N1), y("y", 0, N0), k("k", 0, NC); // input images input im1("im1", {y, x}, p_uint8); input im2("im2", {y, x}, p_uint8); // Corners input C1("C1", {k}, p_int32); input C2("C2", {k}, p_int32); // First convolution (partial on x) expr e1 = (cast(p_float32, im1(y, x) - im1(y, x + 1) + im1(y + 1, x) - im1(y + 1, x + 1))); computation Ix_m("Ix_m", {y, x}, e1); // Second convolution (partial on y) expr e2 = (cast(p_float32, im1(y, x) + im1(y, x + 1) - im1(y + 1, x + 1) - im1(y + 1, x ))); computation Iy_m("Iy_m", {y, x}, e2); // Third convolution expr e3 = (cast(p_float32, im1(y, x) + im1(y, x + 1) + im1(y + 1, x) + im1(y + 1, x + 1))); expr e4 = (cast(p_float32, (- im2(y, x)) - im2(y, x + 1) - im2(y + 1, x) - im2(y + 1, x + 1))); computation It_m("It_m", {y, x}, e3 + e4); // Second part of the algorithm // Compute "u" and "v" for each corner "k" computation i("i", {k}, C2(k)); computation j("j", {k}, C1(k)); // Ix = Ix_m(i-w:i+w, j-w:j+w); // Iy = Iy_m(i-w:i+w, j-w:j+w); // It = It_m(i-w:i+w, j-w:j+w); // Ix = Ix(:); % flatten the IX 2D array into a vector // Iy = Iy(:); // A = [Ix Iy]; // b = -It(:); % get b here var xp("xp", 0, 2*w); var yp("yp", 0, 2*w); computation A1("A1", {k, yp, xp}, Ix_m(i(0)+yp-w, j(0)+xp-w)); //TODO: use i(k) and j(k) instead of i(0) and j(0) computation A1_right("A1_right", {k, yp, xp}, Iy_m(i(0)+yp-w, j(0)+xp-w)); //i(k), j(k) computation b1("b1", {k, yp, xp}, (-It_m(i(0)+yp-w, j(0)+xp-w))); //i(k), j(k) // Reshape A1 to A var x1("x1", 0, 2); var y1("y1", 0, 4*w*w); input A("A", {k, y1, x1}, p_float32); // Use A to reshape A1 and A1_right input b("b", {k, y1}, p_float32); // Use b to reshape b1 // Compute pinv(A): // 1) tA = transpose(A) // 2) tAA = tA * A // 3) X = inv(tAA) // 4) pinv(A) = X * tA // 1) Computing tA = transpose(A) computation tA("tA", {k, x1, y1}, A(k, y1, x1)); // 2) Computing tAA = tA * A var y2("y2", 0, 2); var l1("l1", 0, 4*w*w); computation tAA("tAA", {k, x1, y2}, expr((float) 0)); computation tAA_update("tAA_update", {k, x1, y2, l1}, tAA(k, x1, y2) + (tA(k, x1, l1) * A(k, l1, y2))); // 3) Computing X = inv(tAA) computation determinant("determinant", {k}, (tAA(k,0,0)*tAA(k,1,1)) - (tAA(k,0,1)*tAA(k,1,0))); computation tAAp_00("tAAp_00", {k}, tAA(k,1,1)/determinant(k)); computation tAAp_11("tAAp_11", {k}, tAA(k,0,0)/determinant(k)); computation tAAp_01("tAAp_01", {k}, -tAA(k,0,1)/determinant(k)); computation tAAp_10("tAAp_10", {k}, -tAA(k,1,0)/determinant(k)); input X("X", {k, x1, y2}, p_float32); // 4) Computing pinv(A) = X*tA var l2("l2", 0, 2); computation pinvA("pinvA", {k, x1, y1}, expr((float) 0)); computation pinvA_update("pinvA_update", {k, x1, y1, l2}, pinvA(k, x1, y1) + X(k, x1, l2)*tA(k, l2, y1)); // Compute nu = pinv(A)*b computation nu("nu", {k, x1}, expr((float) 0)); computation nu_update("nu_update", {k, x1, y1}, nu(k, x1) + pinvA(k, x1, y1)*b(k, y1)); // Results // u(k) = nu(0) // v(k) = nu(1) Ix_m.then(Iy_m, x) .then(It_m, x) .then(i, computation::root) .then(j, k) .then(A1, k) .then(A1_right, k) .then(b1, k) .then(tA, k) .then(tAA, k) .then(tAA_update, y2) .then(determinant, k) .then(tAAp_00, k) .then(tAAp_11, k) .then(tAAp_01, k) .then(tAAp_10, k) .then(X, k) .then(pinvA, k) .then(pinvA_update, y1) .then(nu, k) .then(nu_update, x1); // Buffer allocation and mapping computations to buffers buffer b_SIZES("b_SIZES", {2}, p_int32, a_input); buffer b_im1("b_im1", {N0, N1}, p_uint8, a_input); buffer b_im2("b_im2", {N0, N1}, p_uint8, a_input); buffer b_Ix_m("b_Ix_m", {N0, N1}, p_float32, a_output); buffer b_Iy_m("b_Iy_m", {N0, N1}, p_float32, a_output); buffer b_It_m("b_It_m", {N0, N1}, p_float32, a_output); buffer b_C1("b_C1", {NC}, p_int32, a_input); buffer b_C2("b_C2", {NC}, p_int32, a_input); buffer b_i("b_i", {1}, p_int32, a_temporary); buffer b_j("b_j", {1}, p_int32, a_temporary); buffer b_A("b_A", {4*w*w, 2}, p_float32, a_temporary); buffer b_b("b_b", {4*w*w}, p_float32, a_temporary); buffer b_tA("b_tA", {2, 4*w*w}, p_float32, a_temporary); buffer b_tAA("b_tAA", {2, 2}, p_float32, a_temporary); buffer b_determinant("b_determinant", {1}, p_float32, a_temporary); buffer b_X("b_X", {2, 2}, p_float32, a_temporary); buffer b_pinvA("b_pinvA", {2, 4*w*w}, p_float32, a_temporary); buffer b_nu("b_nu", {2}, p_float32, a_temporary); SIZES.store_in(&b_SIZES); im1.store_in(&b_im1); im2.store_in(&b_im2); Ix_m.store_in(&b_Ix_m); Iy_m.store_in(&b_Iy_m); It_m.store_in(&b_It_m); C1.store_in(&b_C1); C2.store_in(&b_C2); i.store_in(&b_i, {0}); j.store_in(&b_j, {0}); A1.store_in(&b_A, {xp+yp*2*w, 0}); A1_right.store_in(&b_A, {xp+yp*2*w, 1}); b1.store_in(&b_b, {xp+yp*2*w}); A.store_in(&b_A, {y1, x1}); b.store_in(&b_b, {y1}); tA.store_in(&b_tA, {x1, y1}); tAA.store_in(&b_tAA, {x1, y2}); tAA_update.store_in(&b_tAA, {x1, y2}); determinant.store_in(&b_determinant, {0}); tAAp_00.store_in(&b_X, {0, 0}); tAAp_01.store_in(&b_X, {0, 1}); tAAp_10.store_in(&b_X, {1, 0}); tAAp_11.store_in(&b_X, {1, 1}); X.store_in(&b_X, {x1, y2}); pinvA.store_in(&b_pinvA, {x1, y1}); pinvA_update.store_in(&b_pinvA, {x1, y1}); nu.store_in(&b_nu, {x1}); nu_update.store_in(&b_nu, {x1}); tiramisu::codegen({&b_SIZES, &b_im1, &b_im2, &b_Ix_m, &b_Iy_m, &b_It_m, &b_C1, &b_C2}, "build/generated_fct_optical_flow.o"); return 0; } <|endoftext|>
<commit_before>// // Bareflank Hypervisor // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <[email protected]> // Author: Brendan Kerrigan <[email protected]> // Author: Connor Davis <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <test.h> #include <vmcs/vmcs_intel_x64.h> #include <memory_manager/memory_manager.h> static std::map<uint32_t, uint64_t> g_msrs; static std::map<uint64_t, uint64_t> g_vmcs_fields; static uint64_t read_msr(uint32_t msr) { return g_msrs[msr]; } static void write_msr(uint32_t msr, uint64_t val) { g_msrs[msr] = val; } static bool vmread(uint64_t field, uint64_t *val) { *val = g_vmcs_fields[field]; return true; } static bool vmwrite(uint64_t field, uint64_t val) { g_vmcs_fields[field] = val; return true; } static uint16_t get_16bit_state() { return 0; } static uint32_t get_32bit_state() { return 0; } static uint64_t get_64bit_state() { return 0; } static void dump() { } static uintptr_t virt_to_phys_ptr(void *ptr) { (void) ptr; return 0x0000000ABCDEF0000; } static void setup_vmcs_x64_state_intrinsics(MockRepository &mocks, vmcs_intel_x64_state *state_in) { // Setup 16 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::es).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cs).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ss).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::fs).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gs).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::tr).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gdt_limit).Do(get_16bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::idt_limit).Do(get_16bit_state); // Setup 32 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::es_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_limit).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::es_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_access_rights).Do(get_32bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_access_rights).Do(get_32bit_state); // Setup 64 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::cr0).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cr3).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cr4).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::dr7).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::rflags).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gdt_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::idt_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::es_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_base).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_debugctl_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_pat_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_efer_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_perf_global_ctrl_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_cs_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_esp_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_eip_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_fs_base_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_gs_base_msr).Do(get_64bit_state); mocks.OnCall(state_in, vmcs_intel_x64_state::dump).Do(dump); } static void setup_vmcs_intrinsics(MockRepository &mocks, memory_manager *mm, intrinsics_intel_x64 *in) { // Emulate the memory manager mocks.OnCallFunc(memory_manager::instance).Return(mm); mocks.OnCallOverload(mm, (uintptr_t(memory_manager::*)(void *))&memory_manager::virt_to_phys).Do(virt_to_phys_ptr); // Setup MSR and vmread returns to mock a successful vmcs_intel_x64::filter_unsupported mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_BASIC_MSR).Return(0x7fffFFFF); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_PINBASED_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_PROCBASED_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_PROCBASED_CTLS2_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_EXIT_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_ENTRY_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::vmread).Return(0x5555555555555555); mocks.OnCall(in, intrinsics_intel_x64::read_msr).Do(read_msr); mocks.OnCall(in, intrinsics_intel_x64::write_msr).Do(write_msr); mocks.OnCall(in, intrinsics_intel_x64::vmread).Do(vmread); mocks.OnCall(in, intrinsics_intel_x64::vmwrite).Do(vmwrite); // Make the default return of the vm* calls true mocks.OnCall(in, intrinsics_intel_x64::vmclear).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmptrld).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmwrite).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmlaunch).Return(true); } void vmcs_ut::test_launch_success() { MockRepository mocks; auto mm = mocks.Mock<memory_manager>(); auto in = bfn::mock_shared<intrinsics_intel_x64>(mocks); auto host_state = bfn::mock_shared<vmcs_intel_x64_state>(mocks); auto guest_state = bfn::mock_shared<vmcs_intel_x64_state>(mocks); setup_vmcs_intrinsics(mocks, mm, in.get()); setup_vmcs_x64_state_intrinsics(mocks, host_state.get()); setup_vmcs_x64_state_intrinsics(mocks, guest_state.get()); RUN_UNITTEST_WITH_MOCKS(mocks, [&] { vmcs_intel_x64 vmcs(in); EXPECT_NO_EXCEPTION(vmcs.launch(host_state, guest_state)); }); } <commit_msg>Add vmcs_intel_x64_state mocked functions<commit_after>// // Bareflank Hypervisor // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <[email protected]> // Author: Brendan Kerrigan <[email protected]> // Author: Connor Davis <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <test.h> #include <vmcs/vmcs_intel_x64.h> #include <memory_manager/memory_manager.h> static std::map<uint32_t, uint64_t> g_msrs; static std::map<uint64_t, uint64_t> g_vmcs_fields; static uint64_t read_msr(uint32_t msr) { return g_msrs[msr]; } static void write_msr(uint32_t msr, uint64_t val) { g_msrs[msr] = val; } static bool vmread(uint64_t field, uint64_t *val) { *val = g_vmcs_fields[field]; return true; } static bool vmwrite(uint64_t field, uint64_t val) { g_vmcs_fields[field] = val; return true; } static uint16_t es() { return 0; } static uint16_t cs() { return 0; } static uint16_t ss() { return 0; } static uint16_t ds() { return 0; } static uint16_t fs() { return 0; } static uint16_t gs() { return 0; } static uint16_t ldtr() { return 0; } static uint16_t tr() { return 0; } static uint64_t cr0() { return 0; } static uint64_t cr3() { return 0; } static uint64_t cr4() { return 0; } static uint64_t dr7() { return 0; } static uint64_t rflags() { return 0; } static uint64_t gdt_base() { return 0; } static uint64_t idt_base() { return 0; } static uint16_t gdt_limit() { return 0; } static uint16_t idt_limit() { return 0; } static uint32_t es_limit() { return 0; } static uint32_t cs_limit() { return 0; } static uint32_t ss_limit() { return 0; } static uint32_t ds_limit() { return 0; } static uint32_t fs_limit() { return 0; } static uint32_t gs_limit() { return 0; } static uint32_t ldtr_limit() { return 0; } static uint32_t tr_limit() { return 0; } static uint32_t es_access_rights() { return 0x10000; } static uint32_t cs_access_rights() { return 0x10000; } static uint32_t ss_access_rights() { return 0x10000; } static uint32_t ds_access_rights() { return 0x10000; } static uint32_t fs_access_rights() { return 0x10000; } static uint32_t gs_access_rights() { return 0x10000; } static uint32_t ldtr_access_rights() { return 0x10000; } static uint32_t tr_access_rights() { return 0x10000; } static uint64_t es_base() { return 0; } static uint64_t cs_base() { return 0; } static uint64_t ss_base() { return 0; } static uint64_t ds_base() { return 0; } static uint64_t fs_base() { return 0; } static uint64_t gs_base() { return 0; } static uint64_t ldtr_base() { return 0; } static uint64_t tr_base() { return 0; } static uint64_t ia32_debugctl_msr() { return 0; } static uint64_t ia32_pat_msr() { return 0; } static uint64_t ia32_efer_msr() { return 0; } static uint64_t ia32_perf_global_ctrl_msr() { return 0; } static uint64_t ia32_sysenter_cs_msr() { return 0; } static uint64_t ia32_sysenter_esp_msr() { return 0; } static uint64_t ia32_sysenter_eip_msr() { return 0; } static uint64_t ia32_fs_base_msr() { return 0; } static uint64_t ia32_gs_base_msr() { return 0; } static void dump() {} static uintptr_t virt_to_phys_ptr(void *ptr) { (void) ptr; return 0x0000000ABCDEF0000; } static void setup_vmcs_x64_state_intrinsics(MockRepository &mocks, vmcs_intel_x64_state *state_in) { // Setup 16 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::es).Do(es); mocks.OnCall(state_in, vmcs_intel_x64_state::cs).Do(cs); mocks.OnCall(state_in, vmcs_intel_x64_state::ss).Do(ss); mocks.OnCall(state_in, vmcs_intel_x64_state::ds).Do(ds); mocks.OnCall(state_in, vmcs_intel_x64_state::fs).Do(fs); mocks.OnCall(state_in, vmcs_intel_x64_state::gs).Do(gs); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr).Do(ldtr); mocks.OnCall(state_in, vmcs_intel_x64_state::tr).Do(tr); mocks.OnCall(state_in, vmcs_intel_x64_state::gdt_limit).Do(gdt_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::idt_limit).Do(idt_limit); // Setup 32 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::es_limit).Do(es_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_limit).Do(cs_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_limit).Do(ss_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_limit).Do(ds_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_limit).Do(ds_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_limit).Do(fs_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_limit).Do(gs_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_limit).Do(ldtr_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_limit).Do(tr_limit); mocks.OnCall(state_in, vmcs_intel_x64_state::es_access_rights).Do(es_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_access_rights).Do(cs_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_access_rights).Do(ss_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_access_rights).Do(ds_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_access_rights).Do(ds_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_access_rights).Do(fs_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_access_rights).Do(gs_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_access_rights).Do(ldtr_access_rights); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_access_rights).Do(tr_access_rights); // Setup 64 bit state functions mocks.OnCall(state_in, vmcs_intel_x64_state::cr0).Do(cr0); mocks.OnCall(state_in, vmcs_intel_x64_state::cr3).Do(cr3); mocks.OnCall(state_in, vmcs_intel_x64_state::cr4).Do(cr4); mocks.OnCall(state_in, vmcs_intel_x64_state::dr7).Do(dr7); mocks.OnCall(state_in, vmcs_intel_x64_state::rflags).Do(rflags); mocks.OnCall(state_in, vmcs_intel_x64_state::gdt_base).Do(gdt_base); mocks.OnCall(state_in, vmcs_intel_x64_state::idt_base).Do(idt_base); mocks.OnCall(state_in, vmcs_intel_x64_state::es_base).Do(es_base); mocks.OnCall(state_in, vmcs_intel_x64_state::cs_base).Do(cs_base); mocks.OnCall(state_in, vmcs_intel_x64_state::ss_base).Do(ss_base); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_base).Do(ds_base); mocks.OnCall(state_in, vmcs_intel_x64_state::ds_base).Do(ds_base); mocks.OnCall(state_in, vmcs_intel_x64_state::fs_base).Do(fs_base); mocks.OnCall(state_in, vmcs_intel_x64_state::gs_base).Do(gs_base); mocks.OnCall(state_in, vmcs_intel_x64_state::ldtr_base).Do(ldtr_base); mocks.OnCall(state_in, vmcs_intel_x64_state::tr_base).Do(tr_base); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_debugctl_msr).Do(ia32_debugctl_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_pat_msr).Do(ia32_pat_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_efer_msr).Do(ia32_efer_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_perf_global_ctrl_msr).Do(ia32_perf_global_ctrl_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_cs_msr).Do(ia32_sysenter_cs_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_esp_msr).Do(ia32_sysenter_esp_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_sysenter_eip_msr).Do(ia32_sysenter_eip_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_fs_base_msr).Do(ia32_fs_base_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::ia32_gs_base_msr).Do(ia32_gs_base_msr); mocks.OnCall(state_in, vmcs_intel_x64_state::dump).Do(dump); } static void setup_vmcs_intrinsics(MockRepository &mocks, memory_manager *mm, intrinsics_intel_x64 *in) { // Emulate the memory manager mocks.OnCallFunc(memory_manager::instance).Return(mm); mocks.OnCallOverload(mm, (uintptr_t(memory_manager::*)(void *))&memory_manager::virt_to_phys).Do(virt_to_phys_ptr); // Setup MSR and vmread returns to mock a successful vmcs_intel_x64::filter_unsupported mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_BASIC_MSR).Return(0x7fffFFFF); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_PINBASED_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_PROCBASED_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_PROCBASED_CTLS2_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_EXIT_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::read_msr).With(IA32_VMX_TRUE_ENTRY_CTLS_MSR).Return(0x55555555aaaaAAAA); mocks.OnCall(in, intrinsics_intel_x64::vmread).Return(0x5555555555555555); mocks.OnCall(in, intrinsics_intel_x64::read_msr).Do(read_msr); mocks.OnCall(in, intrinsics_intel_x64::write_msr).Do(write_msr); mocks.OnCall(in, intrinsics_intel_x64::vmread).Do(vmread); mocks.OnCall(in, intrinsics_intel_x64::vmwrite).Do(vmwrite); // Make the default return of the vm* calls true mocks.OnCall(in, intrinsics_intel_x64::vmclear).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmptrld).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmwrite).Return(true); mocks.OnCall(in, intrinsics_intel_x64::vmlaunch).Return(true); } void vmcs_ut::test_launch_success() { MockRepository mocks; auto mm = mocks.Mock<memory_manager>(); auto in = bfn::mock_shared<intrinsics_intel_x64>(mocks); auto host_state = bfn::mock_shared<vmcs_intel_x64_state>(mocks); auto guest_state = bfn::mock_shared<vmcs_intel_x64_state>(mocks); setup_vmcs_intrinsics(mocks, mm, in.get()); setup_vmcs_x64_state_intrinsics(mocks, host_state.get()); setup_vmcs_x64_state_intrinsics(mocks, guest_state.get()); RUN_UNITTEST_WITH_MOCKS(mocks, [&] { vmcs_intel_x64 vmcs(in); EXPECT_NO_EXCEPTION(vmcs.launch(host_state, guest_state)); }); } <|endoftext|>
<commit_before>/* Copyright 2009 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include "py_oiio.h" namespace PyOpenImageIO { using namespace boost::python; using namespace OpenImageIO; // This our stand-in ProgressCallback which allows oiio to call a Python function. bool PythonProgressCallback(void* opaque_data, float portion_done) { // When oiio calls our ProgressCallback, it will give back the opaque_data which // we can turn back into a Python object, which will turn out to be the // function we are supposed to call. boost::python::object* obj = reinterpret_cast<boost::python::object*>(opaque_data); // One-liner to call the function and return a result as a bool return boost::python::extract<bool>((*obj)(portion_done)); } // This is standing in for a method from oiio which takes a ProgressCallback. void progress_callback_example_original(ProgressCallback pc, void* opaque_data) { for (float f = 0.0; f < 10.0; ++f) { bool result = pc(opaque_data, f); if (!result) { std::cout << "Callback example terminated at " << f << std::endl; return; } } } // This is a wrapper for the above stand-in oiio function. void progress_callback_wrapper(object progress_callback) { // Casting the object to a pointer is kind of dangerious, but safe in this case // because we know its lifetime will be tied to this function. progress_callback_example_original(&PythonProgressCallback, &progress_callback); } object create_array(int length) { // Make some dummy data - this would normally be coming // from oiio, and wouldn't necessarily be int. In fact, // it would usually be void - we'd have to determine the // desired type from the TypeDesc. int* test = new int[length]; for (int i = 0; i < length; ++i) test[i] = i; // Import the Python array module and instantly wrap it // in a Boost.Python handle. This means BP will take care // of reference-counting Python objects for us. object module(handle<>(PyImport_ImportModule("array"))); // This is Boost.Python's way of finding and calling a // function within the module. It's a bit like doing // >>> import array as module // >>> array = getattr(module, "array")("i") object array = module.attr("array")("i"); // Now for something ugly. The array module doesn't // provide a convenient way to construct an array // from C, so we will abuse the fromstring method. // First we create a Python string using the most // direct method available to us (i.e. avoiding boost) // and then we pass that into the fromstring method. // It only actually results in one extra copy so it's // not all that bad. object data( handle<>( PyString_FromStringAndSize( reinterpret_cast<const char*>(test), sizeof(int) * length))); array.attr("fromstring")(data); // Tidy up and prove to ourselves that the returned // array really stands on its own. delete[] test; return array; } // OIIO often expects the user to allocate an array, pass in // the pointer and have that array filled. Python provides // the buffer interface for that. The array module is one way // of creating a buffer. If an array is passed into this // function, it will be treated as an int array and filled // with int data. So it's up to the user to pass the right // kind of array, of the right size - just like the OIIO C++ // interface. void fill_array(const object& buffer) { // We'll pretend it's an int array but we don't actually // know - it's just an area of memory. int* array; Py_ssize_t length; int success = PyObject_AsWriteBuffer(buffer.ptr(), reinterpret_cast<void**>(&array), &length); // throw_error_already_set is Boost.Python's way of // throwing Python exceptions from within C++. if (success != 0) throw_error_already_set(); // Fill the buffer with dummy data. for (int i = 0; i < length / static_cast<int>(sizeof(int)); ++i) { array[i] = i; } } void print_array(const object& buffer) { using namespace std; object module(handle<>(PyImport_ImportModule("array"))); int isArray = PyObject_IsInstance(buffer.ptr(), object(module.attr("array")).ptr()); if (isArray == -1) throw_error_already_set(); char type = 'i'; int size = sizeof(int); if (isArray) { type = extract<string>(buffer.attr("typecode"))()[0]; size = extract<int>(buffer.attr("itemsize")); } const void* array; Py_ssize_t length; int success = PyObject_AsReadBuffer(buffer.ptr(), &array, &length); if (success != 0) boost::python::throw_error_already_set(); switch (type) { case 'i': for (int i = 0; i < length / size; ++i) cout << ((int*)array)[i] << endl; break; case 'f': for (int i = 0; i < length / size; ++i) cout << ((float*)array)[i] << endl; break; case 'c': for (int i = 0; i < length / size; ++i) cout << ((char*)array)[i] << endl; break; default: throw std::runtime_error("Can't print this array type"); } } bool PyProgressCallback(void *function, float data) { boost::python::object *func = reinterpret_cast<boost::python::object*>(function); return boost::python::extract<bool>((*func)(data)); } BOOST_PYTHON_MODULE(OpenImageIO) { declare_imageinput(); declare_imagespec(); declare_imageoutput(); declare_typedesc(); declare_imagecache(); declare_imagebuf(); declare_paramvalue(); def("progress_callback_example", &progress_callback_wrapper); def("create_array", &create_array); def("fill_array", &fill_array); def("print_array", &print_array); } } // namespace PyOpenImageIO <commit_msg>Python: to/from Python conversion for ustring<commit_after>/* Copyright 2009 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include "py_oiio.h" namespace PyOpenImageIO { using namespace boost::python; using namespace OpenImageIO; // This our stand-in ProgressCallback which allows oiio to call a Python function. bool PythonProgressCallback(void* opaque_data, float portion_done) { // When oiio calls our ProgressCallback, it will give back the opaque_data which // we can turn back into a Python object, which will turn out to be the // function we are supposed to call. boost::python::object* obj = reinterpret_cast<boost::python::object*>(opaque_data); // One-liner to call the function and return a result as a bool return boost::python::extract<bool>((*obj)(portion_done)); } // This is standing in for a method from oiio which takes a ProgressCallback. void progress_callback_example_original(ProgressCallback pc, void* opaque_data) { for (float f = 0.0; f < 10.0; ++f) { bool result = pc(opaque_data, f); if (!result) { std::cout << "Callback example terminated at " << f << std::endl; return; } } } // This is a wrapper for the above stand-in oiio function. void progress_callback_wrapper(object progress_callback) { // Casting the object to a pointer is kind of dangerious, but safe in this case // because we know its lifetime will be tied to this function. progress_callback_example_original(&PythonProgressCallback, &progress_callback); } object create_array(int length) { // Make some dummy data - this would normally be coming // from oiio, and wouldn't necessarily be int. In fact, // it would usually be void - we'd have to determine the // desired type from the TypeDesc. int* test = new int[length]; for (int i = 0; i < length; ++i) test[i] = i; // Import the Python array module and instantly wrap it // in a Boost.Python handle. This means BP will take care // of reference-counting Python objects for us. object module(handle<>(PyImport_ImportModule("array"))); // This is Boost.Python's way of finding and calling a // function within the module. It's a bit like doing // >>> import array as module // >>> array = getattr(module, "array")("i") object array = module.attr("array")("i"); // Now for something ugly. The array module doesn't // provide a convenient way to construct an array // from C, so we will abuse the fromstring method. // First we create a Python string using the most // direct method available to us (i.e. avoiding boost) // and then we pass that into the fromstring method. // It only actually results in one extra copy so it's // not all that bad. object data( handle<>( PyString_FromStringAndSize( reinterpret_cast<const char*>(test), sizeof(int) * length))); array.attr("fromstring")(data); // Tidy up and prove to ourselves that the returned // array really stands on its own. delete[] test; return array; } // OIIO often expects the user to allocate an array, pass in // the pointer and have that array filled. Python provides // the buffer interface for that. The array module is one way // of creating a buffer. If an array is passed into this // function, it will be treated as an int array and filled // with int data. So it's up to the user to pass the right // kind of array, of the right size - just like the OIIO C++ // interface. void fill_array(const object& buffer) { // We'll pretend it's an int array but we don't actually // know - it's just an area of memory. int* array; Py_ssize_t length; int success = PyObject_AsWriteBuffer(buffer.ptr(), reinterpret_cast<void**>(&array), &length); // throw_error_already_set is Boost.Python's way of // throwing Python exceptions from within C++. if (success != 0) throw_error_already_set(); // Fill the buffer with dummy data. for (int i = 0; i < length / static_cast<int>(sizeof(int)); ++i) { array[i] = i; } } void print_array(const object& buffer) { using namespace std; object module(handle<>(PyImport_ImportModule("array"))); int isArray = PyObject_IsInstance(buffer.ptr(), object(module.attr("array")).ptr()); if (isArray == -1) throw_error_already_set(); char type = 'i'; int size = sizeof(int); if (isArray) { type = extract<string>(buffer.attr("typecode"))()[0]; size = extract<int>(buffer.attr("itemsize")); } const void* array; Py_ssize_t length; int success = PyObject_AsReadBuffer(buffer.ptr(), &array, &length); if (success != 0) boost::python::throw_error_already_set(); switch (type) { case 'i': for (int i = 0; i < length / size; ++i) cout << ((int*)array)[i] << endl; break; case 'f': for (int i = 0; i < length / size; ++i) cout << ((float*)array)[i] << endl; break; case 'c': for (int i = 0; i < length / size; ++i) cout << ((char*)array)[i] << endl; break; default: throw std::runtime_error("Can't print this array type"); } } bool PyProgressCallback(void *function, float data) { boost::python::object *func = reinterpret_cast<boost::python::object*>(function); return boost::python::extract<bool>((*func)(data)); } struct ustring_to_python_str { static PyObject* convert(ustring const& s) { return boost::python::incref(boost::python::object(s.string()).ptr()); } }; struct ustring_from_python_str { ustring_from_python_str() { boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<ustring>()); } static void* convertible(PyObject* obj_ptr) { if (!PyString_Check(obj_ptr)) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { const char* value = PyString_AsString(obj_ptr); if (value == 0) boost::python::throw_error_already_set(); void* storage = ( (boost::python::converter::rvalue_from_python_storage<ustring>*) data)->storage.bytes; new (storage) ustring(value); data->convertible = storage; } }; BOOST_PYTHON_MODULE(OpenImageIO) { boost::python::to_python_converter< ustring, ustring_to_python_str>(); ustring_from_python_str(); declare_imageinput(); declare_imagespec(); declare_imageoutput(); declare_typedesc(); declare_imagecache(); declare_imagebuf(); declare_paramvalue(); def("progress_callback_example", &progress_callback_wrapper); def("create_array", &create_array); def("fill_array", &fill_array); def("print_array", &print_array); } } // namespace PyOpenImageIO <|endoftext|>
<commit_before>#ifdef WIN32 #define UNICODE #define _UNICODE #include <stdlib.h> #include "win32bindings.h" #include "javasigar.h" #ifdef __cplusplus extern "C" { #endif JNIEXPORT jint JNICALL SIGAR_JNI(win32_RegistryKey_RegCloseKey) (JNIEnv *, jclass, jlong hkey) { return RegCloseKey((HKEY)hkey); } JNIEXPORT jlong JNICALL SIGAR_JNI(win32_RegistryKey_RegCreateKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { HKEY hkeyResult = NULL; LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); RegCreateKeyEx((HKEY)hkey, lpSubkey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkeyResult, NULL); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); return (jlong)hkeyResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); LONG lResult = RegDeleteKey((HKEY)hkey, lpSubkey); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); return lResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteValue) (JNIEnv *env, jclass, jlong hkey, jstring valueName) { LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL); LONG lResult = RegDeleteValue((HKEY)hkey, lpValueName); env->ReleaseStringChars(valueName, (const jchar *)lpValueName); return lResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumKey) (JNIEnv *env, jclass, jlong hkey, jint index) { jstring strResult; TCHAR szBuffer[MAX_PATH + 1]; if(RegEnumKey((HKEY)hkey, index, szBuffer, sizeof(szBuffer)) == ERROR_SUCCESS) strResult = env->NewString((const jchar *)szBuffer, lstrlen(szBuffer)); else strResult = NULL; return strResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumValueName) (JNIEnv *env, jclass, jlong hkey, jint index) { jstring strResult; TCHAR szValueName[MAX_PATH + 1]; DWORD cbValueName = sizeof(szValueName); if(RegEnumValue((HKEY)hkey, index, szValueName, &cbValueName, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) strResult = env->NewString((const jchar *)szValueName, lstrlen(szValueName)); else strResult = NULL; return strResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegFlushKey) (JNIEnv *env, jclass, long hkey) { return RegFlushKey((HKEY)hkey); } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegLoadKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey, jstring file) { LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); LPCTSTR lpFile = (LPCTSTR)env->GetStringChars(file, NULL); LONG lResult = RegLoadKey((HKEY)hkey, lpSubkey, lpFile); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); env->ReleaseStringChars(file, (const jchar *)lpFile); return lResult; } JNIEXPORT jlong SIGAR_JNI(win32_RegistryKey_RegOpenKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { HKEY hkeyResult = NULL; jsize len = env->GetStringLength(subkey); LPTSTR lpSubkey = (LPTSTR)env->GetStringChars(subkey, NULL); LPTSTR copy; /* required under IBM/WebSphere 4.0 for certain keys */ if (lpSubkey[len] != '\0') { copy = wcsdup(lpSubkey); copy[len] = '\0'; } else { copy = lpSubkey; } RegOpenKey((HKEY)hkey, copy, &hkeyResult); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); if (copy != lpSubkey) { free(copy); } return (jlong)hkeyResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegQueryIntValue) (JNIEnv *env, jclass, jlong hkey, jstring valueName) { DWORD dwResult; DWORD dwType; LPBYTE lpValue; DWORD cbValue; LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL); LONG lErr = RegQueryValueEx((HKEY)hkey, lpValueName, NULL, (LPDWORD)&dwType, NULL, &cbValue); if(lErr == ERROR_SUCCESS) { lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbValue); if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, NULL, lpValue, &cbValue) == ERROR_SUCCESS) { switch(dwType) { case REG_DWORD: dwResult = *(LPDWORD)lpValue; break; case REG_SZ: dwResult = _ttol((LPCTSTR)lpValue); break; default: lErr = ERROR_SUCCESS - 1; // Make an error } } HeapFree(GetProcessHeap(), 0, lpValue); } else // Make an error out of not seeing a REG_DWORD lErr = ERROR_SUCCESS - 1; env->ReleaseStringChars(valueName, (const jchar *)lpValueName); if(lErr != ERROR_SUCCESS) { jclass cls = env->FindClass(WIN32_PACKAGE "Win32Exception"); env->ThrowNew(cls, NULL); } return dwResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegQueryStringValue) (JNIEnv *env, jclass, jlong hkey, jstring name) { jstring strResult; DWORD dwType; LPBYTE lpValue; DWORD cbValue; LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(name, NULL); LONG lErr = RegQueryValueEx((HKEY)hkey, lpValueName, NULL, (LPDWORD)&dwType, NULL, &cbValue); if(lErr == ERROR_SUCCESS) { lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbValue); if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, NULL, lpValue, &cbValue) == ERROR_SUCCESS) { switch(dwType) { case REG_DWORD: TCHAR szBuf[20]; _ltot(*(LPDWORD)lpValue, szBuf, 10); strResult = env->NewString((const jchar *)szBuf, lstrlen(szBuf)); break; case REG_SZ: case REG_EXPAND_SZ: { DWORD len; LPTSTR dest = NULL; len = ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, 0); dest = (LPTSTR)malloc(len * sizeof(TCHAR)); ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, len); strResult = env->NewString((const jchar *)dest, len); free(dest); break; } default: lErr = ERROR_SUCCESS - 1; // Make an error } } HeapFree(GetProcessHeap(), 0, lpValue); } env->ReleaseStringChars(name, (const jchar *)lpValueName); if(lErr == ERROR_SUCCESS) return strResult; else { jclass cls = env->FindClass(WIN32_PACKAGE "Win32Exception"); env->ThrowNew(cls, ""); return NULL; } } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetIntValue) (JNIEnv * env, jclass, jlong hkey, jstring valueName, jint value) { LPCTSTR lpValueName; if(valueName != NULL) lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL); else lpValueName = NULL; int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, REG_DWORD, (LPBYTE)&value, sizeof(value)); if(valueName != NULL) env->ReleaseStringChars(valueName, (const jchar *)lpValueName); return iResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetStringValue) (JNIEnv *env, jclass, jlong hkey, jstring name, jstring value) { LPCTSTR lpValueName; if(name != NULL) lpValueName = (LPCTSTR)env->GetStringChars(name, NULL); else lpValueName = NULL; LPCTSTR lpValue = (LPCTSTR)env->GetStringChars(value, NULL); int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, REG_SZ, (LPBYTE)lpValue, (lstrlen(lpValue) + 1) * sizeof(TCHAR)); if(name != NULL) env->ReleaseStringChars(name, (const jchar *)lpValueName); env->ReleaseStringChars(value, (const jchar *)lpValue); return iResult; } #ifdef __cplusplus } #endif #endif /* WIN32 */ <commit_msg>more fixes for ibm/websphere4 jdk<commit_after>#ifdef WIN32 #define UNICODE #define _UNICODE #include <stdlib.h> #include "win32bindings.h" #include "javasigar.h" #ifdef __cplusplus extern "C" { #endif JNIEXPORT jint JNICALL SIGAR_JNI(win32_RegistryKey_RegCloseKey) (JNIEnv *, jclass, jlong hkey) { return RegCloseKey((HKEY)hkey); } JNIEXPORT jlong JNICALL SIGAR_JNI(win32_RegistryKey_RegCreateKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { HKEY hkeyResult = NULL; LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); RegCreateKeyEx((HKEY)hkey, lpSubkey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkeyResult, NULL); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); return (jlong)hkeyResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); LONG lResult = RegDeleteKey((HKEY)hkey, lpSubkey); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); return lResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteValue) (JNIEnv *env, jclass, jlong hkey, jstring valueName) { LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL); LONG lResult = RegDeleteValue((HKEY)hkey, lpValueName); env->ReleaseStringChars(valueName, (const jchar *)lpValueName); return lResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumKey) (JNIEnv *env, jclass, jlong hkey, jint index) { jstring strResult; TCHAR szBuffer[MAX_PATH + 1]; if(RegEnumKey((HKEY)hkey, index, szBuffer, sizeof(szBuffer)) == ERROR_SUCCESS) strResult = env->NewString((const jchar *)szBuffer, lstrlen(szBuffer)); else strResult = NULL; return strResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumValueName) (JNIEnv *env, jclass, jlong hkey, jint index) { jstring strResult; TCHAR szValueName[MAX_PATH + 1]; DWORD cbValueName = sizeof(szValueName); if(RegEnumValue((HKEY)hkey, index, szValueName, &cbValueName, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) strResult = env->NewString((const jchar *)szValueName, lstrlen(szValueName)); else strResult = NULL; return strResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegFlushKey) (JNIEnv *env, jclass, long hkey) { return RegFlushKey((HKEY)hkey); } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegLoadKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey, jstring file) { LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL); LPCTSTR lpFile = (LPCTSTR)env->GetStringChars(file, NULL); LONG lResult = RegLoadKey((HKEY)hkey, lpSubkey, lpFile); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); env->ReleaseStringChars(file, (const jchar *)lpFile); return lResult; } JNIEXPORT jlong SIGAR_JNI(win32_RegistryKey_RegOpenKey) (JNIEnv *env, jclass, jlong hkey, jstring subkey) { HKEY hkeyResult = NULL; jsize len = env->GetStringLength(subkey); LPTSTR lpSubkey = (LPTSTR)env->GetStringChars(subkey, NULL); LPTSTR copy; /* required under IBM/WebSphere 4.0 for certain keys */ if (lpSubkey[len] != '\0') { copy = wcsdup(lpSubkey); copy[len] = '\0'; } else { copy = lpSubkey; } RegOpenKey((HKEY)hkey, copy, &hkeyResult); env->ReleaseStringChars(subkey, (const jchar *)lpSubkey); if (copy != lpSubkey) { free(copy); } return (jlong)hkeyResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegQueryIntValue) (JNIEnv *env, jclass, jlong hkey, jstring valueName) { DWORD dwResult; DWORD dwType; LPBYTE lpValue; DWORD cbValue; LPTSTR copy; jsize len = env->GetStringLength(valueName); LPTSTR lpValueName = (LPTSTR)env->GetStringChars(valueName, NULL); LONG lErr; /* required under IBM/WebSphere 4.0 for certain keys */ if (lpValueName[len] != '\0') { copy = wcsdup(lpValueName); copy[len] = '\0'; } else { copy = lpValueName; } lErr = RegQueryValueEx((HKEY)hkey, copy, NULL, (LPDWORD)&dwType, NULL, &cbValue); if(lErr == ERROR_SUCCESS) { lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbValue); if(RegQueryValueEx((HKEY)hkey, copy, NULL, NULL, lpValue, &cbValue) == ERROR_SUCCESS) { switch(dwType) { case REG_DWORD: dwResult = *(LPDWORD)lpValue; break; case REG_SZ: dwResult = _ttol((LPCTSTR)lpValue); break; default: lErr = ERROR_SUCCESS - 1; // Make an error } } HeapFree(GetProcessHeap(), 0, lpValue); } else // Make an error out of not seeing a REG_DWORD lErr = ERROR_SUCCESS - 1; env->ReleaseStringChars(valueName, (const jchar *)lpValueName); if (copy != lpValueName) { free(copy); } if(lErr != ERROR_SUCCESS) { jclass cls = env->FindClass(WIN32_PACKAGE "Win32Exception"); env->ThrowNew(cls, NULL); } return dwResult; } JNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegQueryStringValue) (JNIEnv *env, jclass, jlong hkey, jstring name) { jstring strResult; DWORD dwType; LPBYTE lpValue; DWORD cbValue; jsize len = env->GetStringLength(name); LPTSTR lpValueName = (LPTSTR)env->GetStringChars(name, NULL); LPTSTR copy; LONG lErr; /* required under IBM/WebSphere 4.0 for certain keys */ if (lpValueName[len] != '\0') { copy = wcsdup(lpValueName); copy[len] = '\0'; } else { copy = lpValueName; } lErr = RegQueryValueEx((HKEY)hkey, copy, NULL, (LPDWORD)&dwType, NULL, &cbValue); if(lErr == ERROR_SUCCESS) { lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbValue); if(RegQueryValueEx((HKEY)hkey, copy, NULL, NULL, lpValue, &cbValue) == ERROR_SUCCESS) { switch(dwType) { case REG_DWORD: TCHAR szBuf[20]; _ltot(*(LPDWORD)lpValue, szBuf, 10); strResult = env->NewString((const jchar *)szBuf, lstrlen(szBuf)); break; case REG_SZ: case REG_EXPAND_SZ: { DWORD len; LPTSTR dest = NULL; len = ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, 0); dest = (LPTSTR)malloc(len * sizeof(TCHAR)); ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, len); strResult = env->NewString((const jchar *)dest, len); free(dest); break; } default: lErr = ERROR_SUCCESS - 1; // Make an error } } HeapFree(GetProcessHeap(), 0, lpValue); } env->ReleaseStringChars(name, (const jchar *)lpValueName); if (copy != lpValueName) { free(copy); } if(lErr == ERROR_SUCCESS) return strResult; else { jclass cls = env->FindClass(WIN32_PACKAGE "Win32Exception"); env->ThrowNew(cls, ""); return NULL; } } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetIntValue) (JNIEnv * env, jclass, jlong hkey, jstring valueName, jint value) { LPCTSTR lpValueName; if(valueName != NULL) lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL); else lpValueName = NULL; int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, REG_DWORD, (LPBYTE)&value, sizeof(value)); if(valueName != NULL) env->ReleaseStringChars(valueName, (const jchar *)lpValueName); return iResult; } JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetStringValue) (JNIEnv *env, jclass, jlong hkey, jstring name, jstring value) { LPCTSTR lpValueName; if(name != NULL) lpValueName = (LPCTSTR)env->GetStringChars(name, NULL); else lpValueName = NULL; LPCTSTR lpValue = (LPCTSTR)env->GetStringChars(value, NULL); int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, REG_SZ, (LPBYTE)lpValue, (lstrlen(lpValue) + 1) * sizeof(TCHAR)); if(name != NULL) env->ReleaseStringChars(name, (const jchar *)lpValueName); env->ReleaseStringChars(value, (const jchar *)lpValue); return iResult; } #ifdef __cplusplus } #endif #endif /* WIN32 */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/raster_colorizer.hpp> using mapnik::raster_colorizer; using mapnik::raster_colorizer_ptr; using mapnik::color_band; using mapnik::color_bands; using mapnik::color; namespace { void append_band1(raster_colorizer_ptr & rc, color_band b) { rc->append_band(b); } void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m) { rc->append_band(b, m); } void append_band3(raster_colorizer_ptr & rc, float v, color c) { rc->append_band(v, c); } void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m) { rc->append_band(v, c, m); } void append_band5(raster_colorizer_ptr & rc, float v, float vm, color c, unsigned m) { rc->append_band(v, vm, c, m); } void append_band6(raster_colorizer_ptr & rc, float v, float vm, color c) { rc->append_band(v, vm, c); } color_bands const& get_color_bands(raster_colorizer_ptr & rc) { return rc->get_color_bands(); } } void export_raster_colorizer() { using namespace boost::python; class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Default ctor.")) .add_property("bands",make_function (get_color_bands, return_value_policy<reference_existing_object>())) .def("append_band", append_band1, (arg("color_band")), "Append a color band to the raster colorizer.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.ColorBand()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> color_band = mapnik.ColorBand(3, color)\n" ">>> colorizer.append_band(color_band)\n" ) .def("append_band", append_band2, (arg("color_band"), arg("midpoint")), "Append a color band with a midpoint to the raster colorizer.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.ColorBand()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> color_band = mapnik.ColorBand(3, color)\n" ">>> colorizer.append_band(color_band, 1)\n" ) .def("append_band", append_band3, (arg("value"), arg("color")), "Append a color for a specific value to the raster colorizer\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, color)\n" ) .def("append_band", append_band4, (arg("value"), arg("color"), arg("midpoints")), "Append a color for a certain value to the raster colorizer,\n" "with a specified midpoint.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, color, 4)\n" ) .def("append_band", append_band5, (arg("value"), arg("value_max"), arg("color"), arg("midpoints")), "Append a color for a value range from value to value_max\n" "to the raster colorizer, with a specified midpoint.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color, 4)\n" ) .def("append_band", append_band6, (arg("value"), arg("value_max"), arg("color")), "Append a color for a value range from value to value_max\n" "to the raster colorizer.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color)\n" ) .def("get_color", &raster_colorizer::get_color, "Get the color assigned to a certain value in raster data.\n" "By default, returns Color(\"transparent\")\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color)\n" ">>> colorizer.get_color(35)\n" "Color('#0044cc')\n" ) ; class_<color_bands>("ColorBands",init<>("Default ctor.")) .def(vector_indexing_suite<color_bands>()) ; class_<color_band>("ColorBand",init<float,color const&>( "A Color Band object.\n" "Create with a value and color\n" "\n" "Usage:" ">>> color = mapnik.Color(\"#fff000\")\n" ">>> color_band = mapnik.ColorBand(4, color)\n" )) .add_property("color", make_function (&color_band::get_color, return_value_policy<reference_existing_object>())) .add_property("value", &color_band::get_value) .add_property("max_value", &color_band::get_max_value) .def(self == self) .def("__str__",&color_band::to_string) ; } <commit_msg>improved RasterColorizer's docstrings as requested in #619<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/raster_colorizer.hpp> using mapnik::raster_colorizer; using mapnik::raster_colorizer_ptr; using mapnik::color_band; using mapnik::color_bands; using mapnik::color; namespace { void append_band1(raster_colorizer_ptr & rc, color_band b) { rc->append_band(b); } void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m) { rc->append_band(b, m); } void append_band3(raster_colorizer_ptr & rc, float v, color c) { rc->append_band(v, c); } void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m) { rc->append_band(v, c, m); } void append_band5(raster_colorizer_ptr & rc, float v, float vm, color c, unsigned m) { rc->append_band(v, vm, c, m); } void append_band6(raster_colorizer_ptr & rc, float v, float vm, color c) { rc->append_band(v, vm, c); } color_bands const& get_color_bands(raster_colorizer_ptr & rc) { return rc->get_color_bands(); } } void export_raster_colorizer() { using namespace boost::python; class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Default ctor.")) .add_property("bands",make_function (get_color_bands, return_value_policy<reference_existing_object>())) .def("append_band", append_band1, (arg("color_band")), "Append a color band to the raster colorizer.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.ColorBand()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> color_band = mapnik.ColorBand(3, color)\n" ">>> colorizer.append_band(color_band)\n" ) .def("append_band", append_band2, (arg("color_band"), arg("midpoints")), "Append a color band to the raster colorizer with midpoints " "lineally interpolated color bands between this one and the " "previous one.\n" "\n" "Usage:\n" ">>> colorizer = mapnik.ColorBand()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> color_band = mapnik.ColorBand(3, color)\n" ">>> colorizer.append_band(color_band, 1)\n" ) .def("append_band", append_band3, (arg("value"), arg("color")), "Create and append a color band to color the range " "[value, next_val) where next_val is the next band's color or " "inifinity if there is no next band.\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, color)\n" ) .def("append_band", append_band4, (arg("value"), arg("color"), arg("midpoints")), "Create and append a color band to the raster colorizer with " "midpoints lineally interpolated color bands between this one and " "the previous one.\n" "color will be applied to all values in the " "range [value, next_val) where next_val is the next band's color " "or infinity if there is no next band\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, color, 4)\n" ) .def("append_band", append_band5, (arg("value"), arg("value_max"), arg("color"), arg("midpoints")), "Create and append a color band to the raster colorizer with " "midpoints lineally interpolated color bands between this one and " "the previous one.\n" "color will be applied to all values in the " "range [value, next_val) where next_val is the next band's color " "or value_max if there is no next band\n" "\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color, 4)\n" ) .def("append_band", append_band6, (arg("value"), arg("value_max"), arg("color")), "Create and append a color band to color the range " "[value, next_val) where next_val is the next band's color or " "value_max if there is no next band.\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color)\n" ) .def("get_color", &raster_colorizer::get_color, "Get the color assigned to a certain value in raster data.\n" "By default, returns Color(\"transparent\")\n" "\n" "Usage:\n" ">>> colorizer = mapnik.RasterColorizer()\n" ">>> color = mapnik.Color(\"#0044cc\")\n" ">>> colorizer.append_band(30, 40, color)\n" ">>> colorizer.get_color(35)\n" "Color('#0044cc')\n" ) ; class_<color_bands>("ColorBands", "A RasterColorizer's collection of ordered color bands.\n" "This class is not meant to be instantiated from python. However, " "it can be accessed at a RasterColorizer's \"bands\" attribute for " "introspection purposes", no_init) .def(vector_indexing_suite<color_bands>()) ; class_<color_band>("ColorBand",init<float,color const&>( "A Color Band object.\n" "Create with a value and color\n" "\n" "Usage:" ">>> color = mapnik.Color(\"#fff000\")\n" ">>> color_band = mapnik.ColorBand(4, color)\n" )) .add_property("color", make_function (&color_band::get_color, return_value_policy<reference_existing_object>())) .add_property("value", &color_band::get_value) .add_property("max_value", &color_band::get_max_value) .def(self == self) .def("__str__",&color_band::to_string) ; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.08.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "beaglebone_black.h" #include "beaglebone_black_pinmux.h" #include <core/console.h> #include <dev/device_manager.h> #include <dev/gpio.h> #include <dev/uart.h> #include <dev/ti_am335x/am335x_gpio.h> #include <dev/ti_am335x/am335x_uart.h> using namespace Device; using namespace Device::GPIO; using namespace Device::UART; namespace Board { IBoard* IBoard::create() { return new BeagleBoneBlack(); } BeagleBoneBlack::BeagleBoneBlack() { m_name = "BeagleBone Black"; m_vendor = "Texas Instruments"; m_version = "1.0"; } bool BeagleBoneBlack::initDevice() { DeviceManager<IGPIOPort>::init(); DeviceManager<IUART>::init(); initUserLED(); initConsole(); return true; } bool BeagleBoneBlack::initUserLED() { // Init user led0. GPIOPin led0(PIN_USER_LED0); led0.setFunction(GPIO::PAD_FUNC_7); led0.setDirection(DIRECTION_OUTPUT); led0.setResistor(RESISTOR_NONE); led0.write(true); return true; } bool BeagleBoneBlack::initConsole() { // Init console on UART1. GPIOPin consoleTx(PIN_P9_24); consoleTx.setFunction(GPIO::PAD_FUNC_0); consoleTx.setDirection(DIRECTION_OUTPUT); AM335x_UART consoleUart(UART_1); consoleUart.setBaudRate(115200); return console.init(); } } // namespace Board <commit_msg>board: Initialize console in proper way.<commit_after>//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.08.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "beaglebone_black.h" #include "beaglebone_black_pinmux.h" #include <core/console.h> #include <dev/device_manager.h> #include <dev/gpio.h> #include <dev/uart.h> #include <dev/ti_am335x/am335x_gpio.h> #include <dev/ti_am335x/am335x_uart.h> using namespace Device; using namespace Device::GPIO; using namespace Device::UART; namespace Board { IBoard* IBoard::create() { return new BeagleBoneBlack(); } BeagleBoneBlack::BeagleBoneBlack() { m_name = "BeagleBone Black"; m_vendor = "Texas Instruments"; m_version = "1.0"; } bool BeagleBoneBlack::initDevice() { DeviceManager<IGPIOPort>::init(); DeviceManager<IUART>::init(); initUserLED(); initConsole(); return true; } bool BeagleBoneBlack::initUserLED() { // Init user led0. GPIOPin led0(PIN_USER_LED0); led0.setFunction(GPIO::PAD_FUNC_7); led0.setDirection(DIRECTION_OUTPUT); led0.setResistor(RESISTOR_NONE); led0.write(true); return true; } bool BeagleBoneBlack::initConsole() { // Init console on UART1. GPIOPin consoleTx(PIN_SERIAL_DEBUG_TX); consoleTx.setFunction(GPIO::PAD_FUNC_0); consoleTx.setDirection(DIRECTION_OUTPUT); consoleTx.setResistor(RESISTOR_NONE); AM335x_UART consoleUart(UART_0); consoleUart.setBaudRate(115200); consoleUart.setDataBits(DATA_BITS_8); consoleUart.setStopBits(STOP_BITS_1); consoleUart.setPartity(PARTITY_NONE); consoleUart.setFlowControl(FLOW_CONTROL_NONE); consoleUart.setDirection(DIRECTION_WRITE); consoleUart.setTransmissionMode(MODE_ASYNCHRONOUS); consoleUart.write("DUPA BLADA\r\n", 12); return console.init(); } } // namespace Board <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WrappedIgnoreProperty.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:48:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_WRAPPED_IGNORE_PROPERTY_HXX #define CHART_WRAPPED_IGNORE_PROPERTY_HXX #include "WrappedProperty.hxx" #include <vector> //............................................................................. namespace chart { //............................................................................. class WrappedIgnoreProperty : public WrappedProperty { public: WrappedIgnoreProperty( const ::rtl::OUString& rOuterName, const ::com::sun::star::uno::Any& rDefaultValue ); virtual ~WrappedIgnoreProperty(); virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void setPropertyToDefault( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any getPropertyDefault( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::beans::PropertyState getPropertyState( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); protected: ::com::sun::star::uno::Any m_aDefaultValue; mutable ::com::sun::star::uno::Any m_aCurrentValue; }; class WrappedIgnoreProperties { public: static void addIgnoreLineProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties_without_BitmapProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties_only_BitmapProperties( std::vector< WrappedProperty* >& rList ); }; //............................................................................. } //namespace chart //............................................................................. // CHART_WRAPPED_IGNORE_PROPERTY_HXX #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.94); FILE MERGED 2008/03/28 16:43:58 rt 1.3.94.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WrappedIgnoreProperty.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CHART_WRAPPED_IGNORE_PROPERTY_HXX #define CHART_WRAPPED_IGNORE_PROPERTY_HXX #include "WrappedProperty.hxx" #include <vector> //............................................................................. namespace chart { //............................................................................. class WrappedIgnoreProperty : public WrappedProperty { public: WrappedIgnoreProperty( const ::rtl::OUString& rOuterName, const ::com::sun::star::uno::Any& rDefaultValue ); virtual ~WrappedIgnoreProperty(); virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void setPropertyToDefault( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any getPropertyDefault( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::beans::PropertyState getPropertyState( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >& xInnerPropertyState ) const throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); protected: ::com::sun::star::uno::Any m_aDefaultValue; mutable ::com::sun::star::uno::Any m_aCurrentValue; }; class WrappedIgnoreProperties { public: static void addIgnoreLineProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties_without_BitmapProperties( std::vector< WrappedProperty* >& rList ); static void addIgnoreFillProperties_only_BitmapProperties( std::vector< WrappedProperty* >& rList ); }; //............................................................................. } //namespace chart //............................................................................. // CHART_WRAPPED_IGNORE_PROPERTY_HXX #endif <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_process_finder_win.h" #include <shellapi.h> #include <string> #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/process/process_handle.h" #include "base/process/process_info.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/win/message_window.h" #include "base/win/metro.h" #include "base/win/scoped_handle.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "chrome/browser/metro_utils/metro_chrome_win.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" namespace { const int kTimeoutInSeconds = 20; // The following is copied from net/base/escape.cc. We don't want to depend on // net here because this gets compiled into chrome.exe to facilitate // fast-rendezvous (see https://codereview.chromium.org/14617003/). // TODO(koz): Move these functions out of net/base/escape.cc into base/escape.cc // so we can depend on it directly. // BEGIN COPY from net/base/escape.cc // A fast bit-vector map for ascii characters. // // Internally stores 256 bits in an array of 8 ints. // Does quick bit-flicking to lookup needed characters. struct Charmap { bool Contains(unsigned char c) const { return ((map[c >> 5] & (1 << (c & 31))) != 0); } uint32 map[8]; }; const char kHexString[] = "0123456789ABCDEF"; inline char IntToHex(int i) { DCHECK_GE(i, 0) << i << " not a hex value"; DCHECK_LE(i, 15) << i << " not a hex value"; return kHexString[i]; } // Given text to escape and a Charmap defining which values to escape, // return an escaped string. If use_plus is true, spaces are converted // to +, otherwise, if spaces are in the charmap, they are converted to // %20. std::string Escape(const std::string& text, const Charmap& charmap, bool use_plus) { std::string escaped; escaped.reserve(text.length() * 3); for (unsigned int i = 0; i < text.length(); ++i) { unsigned char c = static_cast<unsigned char>(text[i]); if (use_plus && ' ' == c) { escaped.push_back('+'); } else if (charmap.Contains(c)) { escaped.push_back('%'); escaped.push_back(IntToHex(c >> 4)); escaped.push_back(IntToHex(c & 0xf)); } else { escaped.push_back(c); } } return escaped; } // Everything except alphanumerics and !'()*-._~ // See RFC 2396 for the list of reserved characters. static const Charmap kQueryCharmap = {{ 0xffffffffL, 0xfc00987dL, 0x78000001L, 0xb8000001L, 0xffffffffL, 0xffffffffL, 0xffffffffL, 0xffffffffL }}; std::string EscapeQueryParamValue(const std::string& text, bool use_plus) { return Escape(text, kQueryCharmap, use_plus); } // END COPY from net/base/escape.cc } // namespace namespace chrome { HWND FindRunningChromeWindow(const base::FilePath& user_data_dir) { return base::win::MessageWindow::FindWindow(user_data_dir.value()); } NotifyChromeResult AttemptToNotifyRunningChrome(HWND remote_window, bool fast_start) { DCHECK(remote_window); static const char kSearchUrl[] = "http://www.google.com/search?q=%s&sourceid=chrome&ie=UTF-8"; DWORD process_id = 0; DWORD thread_id = GetWindowThreadProcessId(remote_window, &process_id); if (!thread_id || !process_id) return NOTIFY_FAILED; if (base::win::IsMetroProcess()) { // Interesting corner case. We are launched as a metro process but we // found another chrome running. Since metro enforces single instance then // the other chrome must be desktop chrome and this must be a search charm // activation. This scenario is unique; other cases should be properly // handled by the delegate_execute which will not activate a second chrome. string16 terms; base::win::MetroLaunchType launch = base::win::GetMetroLaunchParams(&terms); if (launch != base::win::METRO_SEARCH) { LOG(WARNING) << "In metro mode, but and launch is " << launch; } else { std::string query = EscapeQueryParamValue(UTF16ToUTF8(terms), true); std::string url = base::StringPrintf(kSearchUrl, query.c_str()); SHELLEXECUTEINFOA sei = { sizeof(sei) }; sei.fMask = SEE_MASK_FLAG_LOG_USAGE; sei.nShow = SW_SHOWNORMAL; sei.lpFile = url.c_str(); OutputDebugStringA(sei.lpFile); sei.lpDirectory = ""; ::ShellExecuteExA(&sei); } return NOTIFY_SUCCESS; } base::win::ScopedHandle process_handle; if (base::win::GetVersion() >= base::win::VERSION_WIN8 && base::OpenProcessHandleWithAccess( process_id, PROCESS_QUERY_INFORMATION, process_handle.Receive()) && base::win::IsProcessImmersive(process_handle.Get())) { chrome::ActivateMetroChrome(); } CommandLine command_line(*CommandLine::ForCurrentProcess()); command_line.AppendSwitchASCII( switches::kOriginalProcessStartTime, base::Int64ToString( base::CurrentProcessInfo::CreationTime().ToInternalValue())); if (fast_start) command_line.AppendSwitch(switches::kFastStart); // Send the command line to the remote chrome window. // Format is "START\0<<<current directory>>>\0<<<commandline>>>". std::wstring to_send(L"START\0", 6); // want the NULL in the string. base::FilePath cur_dir; if (!file_util::GetCurrentDirectory(&cur_dir)) return NOTIFY_FAILED; to_send.append(cur_dir.value()); to_send.append(L"\0", 1); // Null separator. to_send.append(command_line.GetCommandLineString()); to_send.append(L"\0", 1); // Null separator. // Allow the current running browser window to make itself the foreground // window (otherwise it will just flash in the taskbar). ::AllowSetForegroundWindow(process_id); COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t)); cds.lpData = const_cast<wchar_t*>(to_send.c_str()); DWORD_PTR result = 0; if (::SendMessageTimeout(remote_window, WM_COPYDATA, NULL, reinterpret_cast<LPARAM>(&cds), SMTO_ABORTIFHUNG, kTimeoutInSeconds * 1000, &result)) { return result ? NOTIFY_SUCCESS : NOTIFY_FAILED; } // It is possible that the process owning this window may have died by now. if (!::IsWindow(remote_window)) return NOTIFY_FAILED; // If the window couldn't be notified but still exists, assume it is hung. return NOTIFY_WINDOW_HUNG; } } // namespace chrome <commit_msg>comment metro code in chrome_process_finder_win.cc<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_process_finder_win.h" #include <shellapi.h> #include <string> #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/process/process_handle.h" #include "base/process/process_info.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/win/message_window.h" #include "base/win/metro.h" #include "base/win/scoped_handle.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "chrome/browser/metro_utils/metro_chrome_win.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" namespace { const int kTimeoutInSeconds = 20; // The following is copied from net/base/escape.cc. We don't want to depend on // net here because this gets compiled into chrome.exe to facilitate // fast-rendezvous (see https://codereview.chromium.org/14617003/). // TODO(koz): Move these functions out of net/base/escape.cc into base/escape.cc // so we can depend on it directly. // BEGIN COPY from net/base/escape.cc // A fast bit-vector map for ascii characters. // // Internally stores 256 bits in an array of 8 ints. // Does quick bit-flicking to lookup needed characters. struct Charmap { bool Contains(unsigned char c) const { return ((map[c >> 5] & (1 << (c & 31))) != 0); } uint32 map[8]; }; const char kHexString[] = "0123456789ABCDEF"; inline char IntToHex(int i) { DCHECK_GE(i, 0) << i << " not a hex value"; DCHECK_LE(i, 15) << i << " not a hex value"; return kHexString[i]; } // Given text to escape and a Charmap defining which values to escape, // return an escaped string. If use_plus is true, spaces are converted // to +, otherwise, if spaces are in the charmap, they are converted to // %20. std::string Escape(const std::string& text, const Charmap& charmap, bool use_plus) { std::string escaped; escaped.reserve(text.length() * 3); for (unsigned int i = 0; i < text.length(); ++i) { unsigned char c = static_cast<unsigned char>(text[i]); if (use_plus && ' ' == c) { escaped.push_back('+'); } else if (charmap.Contains(c)) { escaped.push_back('%'); escaped.push_back(IntToHex(c >> 4)); escaped.push_back(IntToHex(c & 0xf)); } else { escaped.push_back(c); } } return escaped; } // Everything except alphanumerics and !'()*-._~ // See RFC 2396 for the list of reserved characters. static const Charmap kQueryCharmap = {{ 0xffffffffL, 0xfc00987dL, 0x78000001L, 0xb8000001L, 0xffffffffL, 0xffffffffL, 0xffffffffL, 0xffffffffL }}; std::string EscapeQueryParamValue(const std::string& text, bool use_plus) { return Escape(text, kQueryCharmap, use_plus); } // END COPY from net/base/escape.cc } // namespace namespace chrome { HWND FindRunningChromeWindow(const base::FilePath& user_data_dir) { return base::win::MessageWindow::FindWindow(user_data_dir.value()); } NotifyChromeResult AttemptToNotifyRunningChrome(HWND remote_window, bool fast_start) { DCHECK(remote_window); static const char kSearchUrl[] = "http://www.google.com/search?q=%s&sourceid=chrome&ie=UTF-8"; DWORD process_id = 0; DWORD thread_id = GetWindowThreadProcessId(remote_window, &process_id); if (!thread_id || !process_id) return NOTIFY_FAILED; if (base::win::IsMetroProcess()) { // Interesting corner case. We are launched as a metro process but we // found another chrome running. Since metro enforces single instance then // the other chrome must be desktop chrome and this must be a search charm // activation. This scenario is unique; other cases should be properly // handled by the delegate_execute which will not activate a second chrome. string16 terms; base::win::MetroLaunchType launch = base::win::GetMetroLaunchParams(&terms); if (launch != base::win::METRO_SEARCH) { LOG(WARNING) << "In metro mode, but and launch is " << launch; } else { std::string query = EscapeQueryParamValue(UTF16ToUTF8(terms), true); std::string url = base::StringPrintf(kSearchUrl, query.c_str()); SHELLEXECUTEINFOA sei = { sizeof(sei) }; sei.fMask = SEE_MASK_FLAG_LOG_USAGE; sei.nShow = SW_SHOWNORMAL; sei.lpFile = url.c_str(); OutputDebugStringA(sei.lpFile); sei.lpDirectory = ""; ::ShellExecuteExA(&sei); } return NOTIFY_SUCCESS; } base::win::ScopedHandle process_handle; if (base::win::GetVersion() >= base::win::VERSION_WIN8 && base::OpenProcessHandleWithAccess( process_id, PROCESS_QUERY_INFORMATION, process_handle.Receive()) && base::win::IsProcessImmersive(process_handle.Get())) { // chrome::ActivateMetroChrome(); } CommandLine command_line(*CommandLine::ForCurrentProcess()); command_line.AppendSwitchASCII( switches::kOriginalProcessStartTime, base::Int64ToString( base::CurrentProcessInfo::CreationTime().ToInternalValue())); if (fast_start) command_line.AppendSwitch(switches::kFastStart); // Send the command line to the remote chrome window. // Format is "START\0<<<current directory>>>\0<<<commandline>>>". std::wstring to_send(L"START\0", 6); // want the NULL in the string. base::FilePath cur_dir; if (!file_util::GetCurrentDirectory(&cur_dir)) return NOTIFY_FAILED; to_send.append(cur_dir.value()); to_send.append(L"\0", 1); // Null separator. to_send.append(command_line.GetCommandLineString()); to_send.append(L"\0", 1); // Null separator. // Allow the current running browser window to make itself the foreground // window (otherwise it will just flash in the taskbar). ::AllowSetForegroundWindow(process_id); COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t)); cds.lpData = const_cast<wchar_t*>(to_send.c_str()); DWORD_PTR result = 0; if (::SendMessageTimeout(remote_window, WM_COPYDATA, NULL, reinterpret_cast<LPARAM>(&cds), SMTO_ABORTIFHUNG, kTimeoutInSeconds * 1000, &result)) { return result ? NOTIFY_SUCCESS : NOTIFY_FAILED; } // It is possible that the process owning this window may have died by now. if (!::IsWindow(remote_window)) return NOTIFY_FAILED; // If the window couldn't be notified but still exists, assume it is hung. return NOTIFY_WINDOW_HUNG; } } // namespace chrome <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/external_metrics.h" #include <map> #include <string> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/metrics/statistics_recorder.h" #include "base/timer/elapsed_timer.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chromeos_metrics_provider.h" #include "components/metrics/metrics_service.h" #include "components/metrics/serialization/metric_sample.h" #include "components/metrics/serialization/serialization_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/user_metrics.h" using base::UserMetricsAction; using content::BrowserThread; namespace chromeos { namespace { bool CheckValues(const std::string& name, int minimum, int maximum, size_t bucket_count) { if (!base::Histogram::InspectConstructionArguments( name, &minimum, &maximum, &bucket_count)) return false; base::HistogramBase* histogram = base::StatisticsRecorder::FindHistogram(name); if (!histogram) return true; return histogram->HasConstructionArguments(minimum, maximum, bucket_count); } bool CheckLinearValues(const std::string& name, int maximum) { return CheckValues(name, 1, maximum, maximum + 1); } // Establishes field trial for wifi scanning in chromeos. crbug.com/242733. void SetupProgressiveScanFieldTrial() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); const char name_of_experiment[] = "ProgressiveScan"; const base::FilePath group_file_path( "/home/chronos/.progressive_scan_variation"); const base::FieldTrial::Probability kDivisor = 1000; scoped_refptr<base::FieldTrial> trial = base::FieldTrialList::FactoryGetFieldTrial( name_of_experiment, kDivisor, "Default", 2013, 12, 31, base::FieldTrial::SESSION_RANDOMIZED, NULL); // Announce the groups with 0 percentage; the actual percentages come from // the server configuration. std::map<int, std::string> group_to_char; group_to_char[trial->AppendGroup("FullScan", 0)] = "c"; group_to_char[trial->AppendGroup("33Percent_4MinMax", 0)] = "1"; group_to_char[trial->AppendGroup("50Percent_4MinMax", 0)] = "2"; group_to_char[trial->AppendGroup("50Percent_8MinMax", 0)] = "3"; group_to_char[trial->AppendGroup("100Percent_8MinMax", 0)] = "4"; group_to_char[trial->AppendGroup("100Percent_1MinSeen_A", 0)] = "5"; group_to_char[trial->AppendGroup("100Percent_1MinSeen_B", 0)] = "6"; group_to_char[trial->AppendGroup("100Percent_1Min_4Max", 0)] = "7"; // Announce the experiment to any listeners (especially important is the UMA // software, which will append the group names to UMA statistics). const int group_num = trial->group(); std::string group_char = "x"; if (ContainsKey(group_to_char, group_num)) group_char = group_to_char[group_num]; // Write the group to the file to be read by ChromeOS. int size = static_cast<int>(group_char.length()); if (base::WriteFile(group_file_path, group_char.c_str(), size) == size) { VLOG(1) << "Configured in group '" << trial->group_name() << "' ('" << group_char << "') for " << name_of_experiment << " field trial"; } else { VLOG(1) << "Couldn't write to " << group_file_path.value(); } } } // namespace // The interval between external metrics collections in seconds static const int kExternalMetricsCollectionIntervalSeconds = 30; const char kEventsFilePath[] = "/var/run/metrics/uma-events"; ExternalMetrics::ExternalMetrics() : uma_events_file_(kEventsFilePath) { } ExternalMetrics::~ExternalMetrics() {} void ExternalMetrics::Start() { // Register user actions external to the browser. // tools/metrics/actions/extract_actions.py won't understand these lines, so // all of these are explicitly added in that script. // TODO(derat): We shouldn't need to verify actions before reporting them; // remove all of this once http://crosbug.com/11125 is fixed. valid_user_actions_.insert("Cryptohome.PKCS11InitFail"); valid_user_actions_.insert("Updater.ServerCertificateChanged"); valid_user_actions_.insert("Updater.ServerCertificateFailed"); // Initialize here field trials that don't need to read from files. // (None for the moment.) // Initialize any chromeos field trials that need to read from a file (e.g., // those that have an upstart script determine their experimental group for // them) then schedule the data collection. All of this is done on the file // thread. bool task_posted = BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&chromeos::ExternalMetrics::SetupFieldTrialsOnFileThread, this)); DCHECK(task_posted); } // static scoped_refptr<ExternalMetrics> ExternalMetrics::CreateForTesting( const std::string& filename) { scoped_refptr<ExternalMetrics> external_metrics(new ExternalMetrics()); external_metrics->uma_events_file_ = filename; return external_metrics; } void ExternalMetrics::RecordActionUI(std::string action_string) { if (valid_user_actions_.count(action_string)) { content::RecordComputedAction(action_string); } else { DLOG(ERROR) << "undefined UMA action: " << action_string; } } void ExternalMetrics::RecordAction(const std::string& action) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ExternalMetrics::RecordActionUI, this, action)); } void ExternalMetrics::RecordCrashUI(const std::string& crash_kind) { ChromeOSMetricsProvider::LogCrash(crash_kind); } void ExternalMetrics::RecordCrash(const std::string& crash_kind) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ExternalMetrics::RecordCrashUI, this, crash_kind)); } void ExternalMetrics::RecordHistogram(const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::HISTOGRAM, sample.type()); if (!CheckValues( sample.name(), sample.min(), sample.max(), sample.bucket_count())) { DLOG(ERROR) << "Invalid histogram: " << sample.name(); return; } base::HistogramBase* counter = base::Histogram::FactoryGet(sample.name(), sample.min(), sample.max(), sample.bucket_count(), base::Histogram::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } void ExternalMetrics::RecordLinearHistogram( const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::LINEAR_HISTOGRAM, sample.type()); if (!CheckLinearValues(sample.name(), sample.max())) { DLOG(ERROR) << "Invalid linear histogram: " << sample.name(); return; } base::HistogramBase* counter = base::LinearHistogram::FactoryGet( sample.name(), 1, sample.max(), sample.max() + 1, base::Histogram::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } void ExternalMetrics::RecordSparseHistogram( const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::SPARSE_HISTOGRAM, sample.type()); base::HistogramBase* counter = base::SparseHistogram::FactoryGet( sample.name(), base::HistogramBase::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } int ExternalMetrics::CollectEvents() { ScopedVector<metrics::MetricSample> samples; metrics::SerializationUtils::ReadAndTruncateMetricsFromFile(uma_events_file_, &samples); for (ScopedVector<metrics::MetricSample>::iterator it = samples.begin(); it != samples.end(); ++it) { const metrics::MetricSample& sample = **it; // Do not use the UMA_HISTOGRAM_... macros here. They cache the Histogram // instance and thus only work if |sample.name()| is constant. switch (sample.type()) { case metrics::MetricSample::CRASH: RecordCrash(sample.name()); break; case metrics::MetricSample::USER_ACTION: RecordAction(sample.name()); break; case metrics::MetricSample::HISTOGRAM: RecordHistogram(sample); break; case metrics::MetricSample::LINEAR_HISTOGRAM: RecordLinearHistogram(sample); break; case metrics::MetricSample::SPARSE_HISTOGRAM: RecordSparseHistogram(sample); break; } } return samples.size(); } void ExternalMetrics::CollectEventsAndReschedule() { base::ElapsedTimer timer; CollectEvents(); UMA_HISTOGRAM_TIMES("UMA.CollectExternalEventsTime", timer.Elapsed()); ScheduleCollector(); } void ExternalMetrics::ScheduleCollector() { bool result; result = BrowserThread::PostDelayedTask( BrowserThread::FILE, FROM_HERE, base::Bind(&chromeos::ExternalMetrics::CollectEventsAndReschedule, this), base::TimeDelta::FromSeconds(kExternalMetricsCollectionIntervalSeconds)); DCHECK(result); } void ExternalMetrics::SetupFieldTrialsOnFileThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Field trials that do not read from files can be initialized in // ExternalMetrics::Start() above. SetupProgressiveScanFieldTrial(); ScheduleCollector(); } } // namespace chromeos <commit_msg>chromeos metrics: use /var/lib/metrics instead of /var/run/metrics<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/external_metrics.h" #include <map> #include <string> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/metrics/statistics_recorder.h" #include "base/timer/elapsed_timer.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chromeos_metrics_provider.h" #include "components/metrics/metrics_service.h" #include "components/metrics/serialization/metric_sample.h" #include "components/metrics/serialization/serialization_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/user_metrics.h" using base::UserMetricsAction; using content::BrowserThread; namespace chromeos { namespace { bool CheckValues(const std::string& name, int minimum, int maximum, size_t bucket_count) { if (!base::Histogram::InspectConstructionArguments( name, &minimum, &maximum, &bucket_count)) return false; base::HistogramBase* histogram = base::StatisticsRecorder::FindHistogram(name); if (!histogram) return true; return histogram->HasConstructionArguments(minimum, maximum, bucket_count); } bool CheckLinearValues(const std::string& name, int maximum) { return CheckValues(name, 1, maximum, maximum + 1); } // Establishes field trial for wifi scanning in chromeos. crbug.com/242733. void SetupProgressiveScanFieldTrial() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); const char name_of_experiment[] = "ProgressiveScan"; const base::FilePath group_file_path( "/home/chronos/.progressive_scan_variation"); const base::FieldTrial::Probability kDivisor = 1000; scoped_refptr<base::FieldTrial> trial = base::FieldTrialList::FactoryGetFieldTrial( name_of_experiment, kDivisor, "Default", 2013, 12, 31, base::FieldTrial::SESSION_RANDOMIZED, NULL); // Announce the groups with 0 percentage; the actual percentages come from // the server configuration. std::map<int, std::string> group_to_char; group_to_char[trial->AppendGroup("FullScan", 0)] = "c"; group_to_char[trial->AppendGroup("33Percent_4MinMax", 0)] = "1"; group_to_char[trial->AppendGroup("50Percent_4MinMax", 0)] = "2"; group_to_char[trial->AppendGroup("50Percent_8MinMax", 0)] = "3"; group_to_char[trial->AppendGroup("100Percent_8MinMax", 0)] = "4"; group_to_char[trial->AppendGroup("100Percent_1MinSeen_A", 0)] = "5"; group_to_char[trial->AppendGroup("100Percent_1MinSeen_B", 0)] = "6"; group_to_char[trial->AppendGroup("100Percent_1Min_4Max", 0)] = "7"; // Announce the experiment to any listeners (especially important is the UMA // software, which will append the group names to UMA statistics). const int group_num = trial->group(); std::string group_char = "x"; if (ContainsKey(group_to_char, group_num)) group_char = group_to_char[group_num]; // Write the group to the file to be read by ChromeOS. int size = static_cast<int>(group_char.length()); if (base::WriteFile(group_file_path, group_char.c_str(), size) == size) { VLOG(1) << "Configured in group '" << trial->group_name() << "' ('" << group_char << "') for " << name_of_experiment << " field trial"; } else { VLOG(1) << "Couldn't write to " << group_file_path.value(); } } } // namespace // The interval between external metrics collections in seconds static const int kExternalMetricsCollectionIntervalSeconds = 30; const char kEventsFilePath[] = "/var/lib/metrics/uma-events"; ExternalMetrics::ExternalMetrics() : uma_events_file_(kEventsFilePath) { } ExternalMetrics::~ExternalMetrics() {} void ExternalMetrics::Start() { // Register user actions external to the browser. // tools/metrics/actions/extract_actions.py won't understand these lines, so // all of these are explicitly added in that script. // TODO(derat): We shouldn't need to verify actions before reporting them; // remove all of this once http://crosbug.com/11125 is fixed. valid_user_actions_.insert("Cryptohome.PKCS11InitFail"); valid_user_actions_.insert("Updater.ServerCertificateChanged"); valid_user_actions_.insert("Updater.ServerCertificateFailed"); // Initialize here field trials that don't need to read from files. // (None for the moment.) // Initialize any chromeos field trials that need to read from a file (e.g., // those that have an upstart script determine their experimental group for // them) then schedule the data collection. All of this is done on the file // thread. bool task_posted = BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&chromeos::ExternalMetrics::SetupFieldTrialsOnFileThread, this)); DCHECK(task_posted); } // static scoped_refptr<ExternalMetrics> ExternalMetrics::CreateForTesting( const std::string& filename) { scoped_refptr<ExternalMetrics> external_metrics(new ExternalMetrics()); external_metrics->uma_events_file_ = filename; return external_metrics; } void ExternalMetrics::RecordActionUI(std::string action_string) { if (valid_user_actions_.count(action_string)) { content::RecordComputedAction(action_string); } else { DLOG(ERROR) << "undefined UMA action: " << action_string; } } void ExternalMetrics::RecordAction(const std::string& action) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ExternalMetrics::RecordActionUI, this, action)); } void ExternalMetrics::RecordCrashUI(const std::string& crash_kind) { ChromeOSMetricsProvider::LogCrash(crash_kind); } void ExternalMetrics::RecordCrash(const std::string& crash_kind) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ExternalMetrics::RecordCrashUI, this, crash_kind)); } void ExternalMetrics::RecordHistogram(const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::HISTOGRAM, sample.type()); if (!CheckValues( sample.name(), sample.min(), sample.max(), sample.bucket_count())) { DLOG(ERROR) << "Invalid histogram: " << sample.name(); return; } base::HistogramBase* counter = base::Histogram::FactoryGet(sample.name(), sample.min(), sample.max(), sample.bucket_count(), base::Histogram::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } void ExternalMetrics::RecordLinearHistogram( const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::LINEAR_HISTOGRAM, sample.type()); if (!CheckLinearValues(sample.name(), sample.max())) { DLOG(ERROR) << "Invalid linear histogram: " << sample.name(); return; } base::HistogramBase* counter = base::LinearHistogram::FactoryGet( sample.name(), 1, sample.max(), sample.max() + 1, base::Histogram::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } void ExternalMetrics::RecordSparseHistogram( const metrics::MetricSample& sample) { CHECK_EQ(metrics::MetricSample::SPARSE_HISTOGRAM, sample.type()); base::HistogramBase* counter = base::SparseHistogram::FactoryGet( sample.name(), base::HistogramBase::kUmaTargetedHistogramFlag); counter->Add(sample.sample()); } int ExternalMetrics::CollectEvents() { ScopedVector<metrics::MetricSample> samples; metrics::SerializationUtils::ReadAndTruncateMetricsFromFile(uma_events_file_, &samples); for (ScopedVector<metrics::MetricSample>::iterator it = samples.begin(); it != samples.end(); ++it) { const metrics::MetricSample& sample = **it; // Do not use the UMA_HISTOGRAM_... macros here. They cache the Histogram // instance and thus only work if |sample.name()| is constant. switch (sample.type()) { case metrics::MetricSample::CRASH: RecordCrash(sample.name()); break; case metrics::MetricSample::USER_ACTION: RecordAction(sample.name()); break; case metrics::MetricSample::HISTOGRAM: RecordHistogram(sample); break; case metrics::MetricSample::LINEAR_HISTOGRAM: RecordLinearHistogram(sample); break; case metrics::MetricSample::SPARSE_HISTOGRAM: RecordSparseHistogram(sample); break; } } return samples.size(); } void ExternalMetrics::CollectEventsAndReschedule() { base::ElapsedTimer timer; CollectEvents(); UMA_HISTOGRAM_TIMES("UMA.CollectExternalEventsTime", timer.Elapsed()); ScheduleCollector(); } void ExternalMetrics::ScheduleCollector() { bool result; result = BrowserThread::PostDelayedTask( BrowserThread::FILE, FROM_HERE, base::Bind(&chromeos::ExternalMetrics::CollectEventsAndReschedule, this), base::TimeDelta::FromSeconds(kExternalMetricsCollectionIntervalSeconds)); DCHECK(result); } void ExternalMetrics::SetupFieldTrialsOnFileThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Field trials that do not read from files can be initialized in // ExternalMetrics::Start() above. SetupProgressiveScanFieldTrial(); ScheduleCollector(); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/location_bar_view_gtk.h" #include <string> #include "app/resource_bundle.h" #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/logging.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/alternate_nav_url_fetcher.h" #include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "chrome/common/page_transition_types.h" #include "third_party/skia/include/core/SkBitmap.h" #include "webkit/glue/window_open_disposition.h" namespace { // We are positioned with a little bit of extra space that we don't use now. const int kTopMargin = 1; const int kBottomMargin = 1; // We don't want to edit control's text to be right against the edge. const int kEditLeftRightPadding = 4; // We draw a border on the top and bottom (but not on left or right). const int kBorderThickness = 1; // Padding around the security icon. const int kSecurityIconPaddingLeft = 4; const int kSecurityIconPaddingRight = 2; // TODO(deanm): Eventually this should be painted with the background png // image, but for now we get pretty close by just drawing a solid border. const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); } // namespace // static const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = { GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White. }; LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater, ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner) : security_icon_(NULL), profile_(NULL), command_updater_(command_updater), toolbar_model_(toolbar_model), popup_positioner_(popup_positioner), disposition_(CURRENT_TAB), transition_(PageTransition::TYPED) { } LocationBarViewGtk::~LocationBarViewGtk() { // All of our widgets should have be children of / owned by the alignment. alignment_.Destroy(); } void LocationBarViewGtk::Init() { location_entry_.reset(new AutocompleteEditViewGtk(this, toolbar_model_, profile_, command_updater_, popup_positioner_)); location_entry_->Init(); alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0)); UpdateAlignmentPadding(); // We will paint for the alignment, to paint the background and border. gtk_widget_set_app_paintable(alignment_.get(), TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(alignment_.get(), TRUE); g_signal_connect(alignment_.get(), "expose-event", G_CALLBACK(&HandleExposeThunk), this); gtk_container_add(GTK_CONTAINER(alignment_.get()), location_entry_->widget()); } void LocationBarViewGtk::SetProfile(Profile* profile) { profile_ = profile; } void LocationBarViewGtk::Update(const TabContents* contents) { SetSecurityIcon(toolbar_model_->GetIcon()); location_entry_->Update(contents); // The security level (background color) could have changed, etc. gtk_widget_queue_draw(alignment_.get()); } void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url) { if (!url.is_valid()) return; location_input_ = UTF8ToWide(url.spec()); disposition_ = disposition; transition_ = transition; if (!command_updater_) return; if (!alternate_nav_url.is_valid()) { command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); return; } scoped_ptr<AlternateNavURLFetcher> fetcher( new AlternateNavURLFetcher(alternate_nav_url)); // The AlternateNavURLFetcher will listen for the pending navigation // notification that will be issued as a result of the "open URL." It // will automatically install itself into that navigation controller. command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) { // I'm not sure this should be reachable, but I'm not also sure enough // that it shouldn't to stick in a NOTREACHED(). In any case, this is // harmless; we can simply let the fetcher get deleted here and it will // clean itself up properly. } else { fetcher.release(); // The navigation controller will delete the fetcher. } } void LocationBarViewGtk::OnChanged() { // TODO(deanm): Here is where we would do layout when we have things like // the keyword display, ssl icons, etc. } void LocationBarViewGtk::OnInputInProgress(bool in_progress) { // Here's a comment copied from the Windows code, which propagates this // call up to the toolbar. // "Called by the location bar view when the user starts typing in the edit. // This forces our security style to be UNKNOWN for the duration of the // editing." // http://code.google.com/p/chromium/issues/detail?id=10965 } SkBitmap LocationBarViewGtk::GetFavIcon() const { NOTIMPLEMENTED(); return SkBitmap(); } std::wstring LocationBarViewGtk::GetTitle() const { NOTIMPLEMENTED(); return std::wstring(); } void LocationBarViewGtk::ShowFirstRunBubble(bool use_OEM_bubble) { NOTIMPLEMENTED(); } std::wstring LocationBarViewGtk::GetInputString() const { return location_input_; } WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const { return disposition_; } PageTransition::Type LocationBarViewGtk::GetPageTransition() const { return transition_; } void LocationBarViewGtk::AcceptInput() { AcceptInputWithDisposition(CURRENT_TAB); } void LocationBarViewGtk::AcceptInputWithDisposition( WindowOpenDisposition disposition) { location_entry_->model()->AcceptInput(disposition, false); } void LocationBarViewGtk::FocusLocation() { location_entry_->SetFocus(); location_entry_->SelectAll(true); } void LocationBarViewGtk::FocusSearch() { location_entry_->SetUserText(L"?"); location_entry_->SetFocus(); } void LocationBarViewGtk::UpdatePageActions() { // http://code.google.com/p/chromium/issues/detail?id=11973 } void LocationBarViewGtk::SaveStateToContents(TabContents* contents) { // http://crbug.com/9225 } void LocationBarViewGtk::Revert() { location_entry_->RevertAll(); } gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget, GdkEventExpose* event) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); GdkRectangle* alloc_rect = &alignment_.get()->allocation; // The area outside of our margin, which includes the border. GdkRectangle inner_rect = { alloc_rect->x, alloc_rect->y + kTopMargin, alloc_rect->width, alloc_rect->height - kTopMargin - kBottomMargin}; // Some of our calculations are a bit sloppy. Since we draw on our parent // window, set a clip to make sure that we don't draw outside. gdk_gc_set_clip_rectangle(gc, &inner_rect); // Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an // overdrawn stroked rect with a clip to the allocation? gdk_gc_set_rgb_fg_color(gc, &kBorderColor); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y, inner_rect.width, kBorderThickness); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + inner_rect.height - kBorderThickness, inner_rect.width, kBorderThickness); // Draw the background within the border. gdk_gc_set_rgb_fg_color(gc, &kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + kBorderThickness, inner_rect.width, inner_rect.height - (kBorderThickness * 2)); // If we have an SSL icon, draw it vertically centered on the right side. if (security_icon_) { int icon_width = gdk_pixbuf_get_width(security_icon_); int icon_height = gdk_pixbuf_get_height(security_icon_); int icon_x = inner_rect.x + inner_rect.width - kBorderThickness - icon_width - kSecurityIconPaddingRight; int icon_y = inner_rect.y + ((inner_rect.height - icon_height) / 2); gdk_draw_pixbuf(drawable, gc, security_icon_, 0, 0, icon_x, icon_y, -1, -1, GDK_RGB_DITHER_NONE, 0, 0); } g_object_unref(gc); return FALSE; // Continue propagating the expose. } void LocationBarViewGtk::UpdateAlignmentPadding() { // When we have an icon, increase our right padding to make space for it. int right_padding = security_icon_ ? gdk_pixbuf_get_width(security_icon_) + kSecurityIconPaddingLeft + kSecurityIconPaddingRight : kEditLeftRightPadding; gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()), kTopMargin + kBorderThickness, kBottomMargin + kBorderThickness, kEditLeftRightPadding, right_padding); } void LocationBarViewGtk::SetSecurityIcon(ToolbarModel::Icon icon) { static ResourceBundle& rb = ResourceBundle::GetSharedInstance(); static GdkPixbuf* kLockIcon = rb.GetPixbufNamed(IDR_LOCK); static GdkPixbuf* kWarningIcon = rb.GetPixbufNamed(IDR_WARNING); switch (icon) { case ToolbarModel::LOCK_ICON: security_icon_ = kLockIcon; break; case ToolbarModel::WARNING_ICON: security_icon_ = kWarningIcon; break; case ToolbarModel::NO_ICON: security_icon_ = NULL; break; default: NOTREACHED(); security_icon_ = NULL; break; } // Make sure there is room for the icon. UpdateAlignmentPadding(); } <commit_msg>Linux Omnibox, handle OnInputInProgress to clear the security style.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/location_bar_view_gtk.h" #include <string> #include "app/resource_bundle.h" #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/logging.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/alternate_nav_url_fetcher.h" #include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "chrome/common/page_transition_types.h" #include "third_party/skia/include/core/SkBitmap.h" #include "webkit/glue/window_open_disposition.h" namespace { // We are positioned with a little bit of extra space that we don't use now. const int kTopMargin = 1; const int kBottomMargin = 1; // We don't want to edit control's text to be right against the edge. const int kEditLeftRightPadding = 4; // We draw a border on the top and bottom (but not on left or right). const int kBorderThickness = 1; // Padding around the security icon. const int kSecurityIconPaddingLeft = 4; const int kSecurityIconPaddingRight = 2; // TODO(deanm): Eventually this should be painted with the background png // image, but for now we get pretty close by just drawing a solid border. const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); } // namespace // static const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = { GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White. }; LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater, ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner) : security_icon_(NULL), profile_(NULL), command_updater_(command_updater), toolbar_model_(toolbar_model), popup_positioner_(popup_positioner), disposition_(CURRENT_TAB), transition_(PageTransition::TYPED) { } LocationBarViewGtk::~LocationBarViewGtk() { // All of our widgets should have be children of / owned by the alignment. alignment_.Destroy(); } void LocationBarViewGtk::Init() { location_entry_.reset(new AutocompleteEditViewGtk(this, toolbar_model_, profile_, command_updater_, popup_positioner_)); location_entry_->Init(); alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0)); UpdateAlignmentPadding(); // We will paint for the alignment, to paint the background and border. gtk_widget_set_app_paintable(alignment_.get(), TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(alignment_.get(), TRUE); g_signal_connect(alignment_.get(), "expose-event", G_CALLBACK(&HandleExposeThunk), this); gtk_container_add(GTK_CONTAINER(alignment_.get()), location_entry_->widget()); } void LocationBarViewGtk::SetProfile(Profile* profile) { profile_ = profile; } void LocationBarViewGtk::Update(const TabContents* contents) { SetSecurityIcon(toolbar_model_->GetIcon()); location_entry_->Update(contents); // The security level (background color) could have changed, etc. gtk_widget_queue_draw(alignment_.get()); } void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url) { if (!url.is_valid()) return; location_input_ = UTF8ToWide(url.spec()); disposition_ = disposition; transition_ = transition; if (!command_updater_) return; if (!alternate_nav_url.is_valid()) { command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); return; } scoped_ptr<AlternateNavURLFetcher> fetcher( new AlternateNavURLFetcher(alternate_nav_url)); // The AlternateNavURLFetcher will listen for the pending navigation // notification that will be issued as a result of the "open URL." It // will automatically install itself into that navigation controller. command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) { // I'm not sure this should be reachable, but I'm not also sure enough // that it shouldn't to stick in a NOTREACHED(). In any case, this is // harmless; we can simply let the fetcher get deleted here and it will // clean itself up properly. } else { fetcher.release(); // The navigation controller will delete the fetcher. } } void LocationBarViewGtk::OnChanged() { // TODO(deanm): Here is where we would do layout when we have things like // the keyword display, ssl icons, etc. } void LocationBarViewGtk::OnInputInProgress(bool in_progress) { // This is identical to the Windows code, except that we don't proxy the call // back through the Toolbar, and just access the model here. // The edit should make sure we're only notified when something changes. DCHECK(toolbar_model_->input_in_progress() != in_progress); toolbar_model_->set_input_in_progress(in_progress); Update(NULL); } SkBitmap LocationBarViewGtk::GetFavIcon() const { NOTIMPLEMENTED(); return SkBitmap(); } std::wstring LocationBarViewGtk::GetTitle() const { NOTIMPLEMENTED(); return std::wstring(); } void LocationBarViewGtk::ShowFirstRunBubble(bool use_OEM_bubble) { NOTIMPLEMENTED(); } std::wstring LocationBarViewGtk::GetInputString() const { return location_input_; } WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const { return disposition_; } PageTransition::Type LocationBarViewGtk::GetPageTransition() const { return transition_; } void LocationBarViewGtk::AcceptInput() { AcceptInputWithDisposition(CURRENT_TAB); } void LocationBarViewGtk::AcceptInputWithDisposition( WindowOpenDisposition disposition) { location_entry_->model()->AcceptInput(disposition, false); } void LocationBarViewGtk::FocusLocation() { location_entry_->SetFocus(); location_entry_->SelectAll(true); } void LocationBarViewGtk::FocusSearch() { location_entry_->SetUserText(L"?"); location_entry_->SetFocus(); } void LocationBarViewGtk::UpdatePageActions() { // http://code.google.com/p/chromium/issues/detail?id=11973 } void LocationBarViewGtk::SaveStateToContents(TabContents* contents) { // http://crbug.com/9225 } void LocationBarViewGtk::Revert() { location_entry_->RevertAll(); } gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget, GdkEventExpose* event) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); GdkRectangle* alloc_rect = &alignment_.get()->allocation; // The area outside of our margin, which includes the border. GdkRectangle inner_rect = { alloc_rect->x, alloc_rect->y + kTopMargin, alloc_rect->width, alloc_rect->height - kTopMargin - kBottomMargin}; // Some of our calculations are a bit sloppy. Since we draw on our parent // window, set a clip to make sure that we don't draw outside. gdk_gc_set_clip_rectangle(gc, &inner_rect); // Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an // overdrawn stroked rect with a clip to the allocation? gdk_gc_set_rgb_fg_color(gc, &kBorderColor); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y, inner_rect.width, kBorderThickness); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + inner_rect.height - kBorderThickness, inner_rect.width, kBorderThickness); // Draw the background within the border. gdk_gc_set_rgb_fg_color(gc, &kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + kBorderThickness, inner_rect.width, inner_rect.height - (kBorderThickness * 2)); // If we have an SSL icon, draw it vertically centered on the right side. if (security_icon_) { int icon_width = gdk_pixbuf_get_width(security_icon_); int icon_height = gdk_pixbuf_get_height(security_icon_); int icon_x = inner_rect.x + inner_rect.width - kBorderThickness - icon_width - kSecurityIconPaddingRight; int icon_y = inner_rect.y + ((inner_rect.height - icon_height) / 2); gdk_draw_pixbuf(drawable, gc, security_icon_, 0, 0, icon_x, icon_y, -1, -1, GDK_RGB_DITHER_NONE, 0, 0); } g_object_unref(gc); return FALSE; // Continue propagating the expose. } void LocationBarViewGtk::UpdateAlignmentPadding() { // When we have an icon, increase our right padding to make space for it. int right_padding = security_icon_ ? gdk_pixbuf_get_width(security_icon_) + kSecurityIconPaddingLeft + kSecurityIconPaddingRight : kEditLeftRightPadding; gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()), kTopMargin + kBorderThickness, kBottomMargin + kBorderThickness, kEditLeftRightPadding, right_padding); } void LocationBarViewGtk::SetSecurityIcon(ToolbarModel::Icon icon) { static ResourceBundle& rb = ResourceBundle::GetSharedInstance(); static GdkPixbuf* kLockIcon = rb.GetPixbufNamed(IDR_LOCK); static GdkPixbuf* kWarningIcon = rb.GetPixbufNamed(IDR_WARNING); switch (icon) { case ToolbarModel::LOCK_ICON: security_icon_ = kLockIcon; break; case ToolbarModel::WARNING_ICON: security_icon_ = kWarningIcon; break; case ToolbarModel::NO_ICON: security_icon_ = NULL; break; default: NOTREACHED(); security_icon_ = NULL; break; } // Make sure there is room for the icon. UpdateAlignmentPadding(); } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_ONTOLOGY_VARIABLE_STRUCT_HPP_INCLUDED #define __YLIKUUTIO_ONTOLOGY_VARIABLE_STRUCT_HPP_INCLUDED #include "entity_struct.hpp" #include "activate_callback.hpp" #include "read_callback.hpp" // Include standard headers #include <memory> // std::make_shared, std::shared_ptr namespace yli::data { class AnyValue; } namespace yli::ontology { class Entity; struct VariableStruct: public yli::ontology::EntityStruct { VariableStruct() { // constructor. this->is_variable = true; } VariableStruct(std::shared_ptr<yli::data::AnyValue> initial_value) : initial_value { initial_value } { // constructor. this->is_variable = true; } VariableStruct(const yli::ontology::VariableStruct& variable_struct) : EntityStruct(variable_struct), parent { variable_struct.parent }, initial_value { variable_struct.initial_value }, activate_callback { variable_struct.activate_callback }, read_callback { variable_struct.read_callback }, should_call_activate_callback_now { variable_struct.should_call_activate_callback_now } { // copy constructor. this->global_name = variable_struct.global_name; this->local_name = variable_struct.local_name; this->is_variable = true; } yli::ontology::Entity* parent { nullptr }; std::shared_ptr<yli::data::AnyValue> initial_value { nullptr }; ActivateCallback activate_callback { nullptr }; ReadCallback read_callback { nullptr }; bool should_call_activate_callback_now { true }; }; } #endif <commit_msg>`VariableStruct`: make 1 parameter constructor `explicit`.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_ONTOLOGY_VARIABLE_STRUCT_HPP_INCLUDED #define __YLIKUUTIO_ONTOLOGY_VARIABLE_STRUCT_HPP_INCLUDED #include "entity_struct.hpp" #include "activate_callback.hpp" #include "read_callback.hpp" // Include standard headers #include <memory> // std::make_shared, std::shared_ptr namespace yli::data { class AnyValue; } namespace yli::ontology { class Entity; struct VariableStruct: public yli::ontology::EntityStruct { VariableStruct() { // constructor. this->is_variable = true; } explicit VariableStruct(std::shared_ptr<yli::data::AnyValue> initial_value) : initial_value { initial_value } { // constructor. this->is_variable = true; } VariableStruct(const yli::ontology::VariableStruct& variable_struct) : EntityStruct(variable_struct), parent { variable_struct.parent }, initial_value { variable_struct.initial_value }, activate_callback { variable_struct.activate_callback }, read_callback { variable_struct.read_callback }, should_call_activate_callback_now { variable_struct.should_call_activate_callback_now } { // copy constructor. this->global_name = variable_struct.global_name; this->local_name = variable_struct.local_name; this->is_variable = true; } yli::ontology::Entity* parent { nullptr }; std::shared_ptr<yli::data::AnyValue> initial_value { nullptr }; ActivateCallback activate_callback { nullptr }; ReadCallback read_callback { nullptr }; bool should_call_activate_callback_now { true }; }; } #endif <|endoftext|>
<commit_before>#include "colibri_ca.h" #include "colibri_local_nav.h" #include "colibri_action.h" #include "PID_controller.h" #include "global_planner.h" #include "task_mgr.h" #include <boost/bind.hpp> #include "geometry_msgs/PoseStamped.h" void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag); int main(int argc, char* argv[]) { ros::init(argc, argv, "Nav_Mult_RvizGoal_Node"); scan_ca scan4caObj; local_nav local4navObj; nav_action actionObj; planner plannerObj; task_mgr taskObj; ROS_INFO("Start to Go to Mult Rviz Goal ... "); ros::Rate loop_rate(10); // ctrl freq 10 hz unsigned int delay_cnt = 0; float tmp_delta_dis = 0.0; float tmp_robot2goal_yaw = 0.0; float tmp_laser2goal_yaw = 0.0; bool goal_inlaser_flag = true; float dir_goal_in_laser = 0.0; float self_rotation_angle = 0.0; unsigned int turn_adj_flag = 1; float tmp_action_cmd_t[2] = {0.0, 0.0}; float* ptr_action_cmd_t = tmp_action_cmd_t; float newyaw = 145.0; unsigned int micro_adj_flag = 0; unsigned int adj_flag = 0; bool obtain_flag = false; unsigned int search_start = 0; ros::NodeHandle nh_fp; ros::Timer planner_timer; bool finish_plan = false; bool tmp_timer_finish =false; bool *timer_finish = &tmp_timer_finish; static unsigned int index4gravaton = 0; float delta_robot2gravaton = 0.0; bool at_gravaton_flag = false; bool exist_gravaton_flag = false; bool replan_flag = false; float rt_r2g_dis = 100.0; while(taskObj.obtain_goal_flag == false) { ros::spinOnce(); loop_rate.sleep(); } local4navObj.goal_state[0] = taskObj.cur_goal[0]; local4navObj.goal_state[1] = taskObj.cur_goal[1]; local4navObj.goal_state[2] = taskObj.cur_goal[2]; cout<<" local4navObj.goal_state.x = "<<local4navObj.goal_state[0]<<endl; cout<<" local4navObj.goal_state.y = "<<local4navObj.goal_state[1]<<endl; while (!ros::service::waitForService(plannerObj.srv4make_plan, ros::Duration(0.2))) { ROS_INFO("Waiting for service move_base/make_plan to become available"); } ROS_INFO("Service move_base/make_plan prepared OK..."); finish_plan = plannerObj.ExecMonoPlanAndGravaton(plannerObj,&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], search_start,index4gravaton); planner_timer = nh_fp.createTimer(ros::Duration(PLAN_INTERVAL), boost::bind(&PlannerCallback, &plannerObj, &local4navObj.amcl_cur_state[0],&taskObj.cur_goal[0], timer_finish)); while (ros::ok()) { if(delay_cnt < DELAY_CNT_MAX) { delay_cnt++; ros::spinOnce(); loop_rate.sleep(); } if(delay_cnt >= DELAY_CNT_MAX) { ROS_INFO("------ start ------"); if(*timer_finish == true) { *timer_finish = false; index4gravaton = 0; replan_flag = true; }else { if((at_gravaton_flag == true && local4navObj.approaching_flag == false)||(replan_flag == true)) { plannerObj.CalcPath2RobotDeltaDis(plannerObj.path_array, local4navObj.amcl_cur_state); index4gravaton = plannerObj.CalcGravatonFromPath(plannerObj.path_array, plannerObj.path2robot_array, index4gravaton, plannerObj.gravaton,exist_gravaton_flag); at_gravaton_flag = false; replan_flag = false; } at_gravaton_flag = actionObj.ReachGravatonOK(&local4navObj.amcl_cur_state[0],&plannerObj.gravaton.x, delta_robot2gravaton); if(local4navObj.approaching_flag == true) { plannerObj.gravaton.x = taskObj.cur_goal[0]; plannerObj.gravaton.y = taskObj.cur_goal[1]; plannerObj.gravaton.yaw = taskObj.cur_goal[2]; } } local4navObj.CalcOffsetOfGoalAndRobot(local4navObj.amcl_cur_state, &plannerObj.gravaton.x, &tmp_delta_dis, &tmp_robot2goal_yaw, &tmp_laser2goal_yaw); goal_inlaser_flag = local4navObj.CalcGoalDirOfLaserViewNew(&tmp_laser2goal_yaw, &local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &self_rotation_angle); scan4caObj.CalcPhiParam(local4navObj.cur_robot_vel[0], dir_goal_in_laser); scan4caObj.CalcKrfTheta(scan4caObj.kp_phi_vec, scan4caObj.phi_start_vec, scan4caObj.phi_end_vec); scan4caObj.CalcCorrectedKrf(); scan4caObj.CalcPassFcnAndFwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec); scan4caObj.CalcPassFcnAndBwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec); scan4caObj.angle_adj = scan4caObj.CalcAdjDir(scan4caObj.passfcn_vec,scan4caObj.max_passfcn_val, &scan4caObj.maxfcn_fwdbnd,&scan4caObj.maxfcn_bwdbnd); scan4caObj.CalcCollisionInAPF(); if(goal_inlaser_flag == true) { local4navObj.apf_ctrl_output[0] = (V_MAX - V_MIN) * (scan4caObj.max_passfcn_val / D_M) + V_MIN; local4navObj.apf_ctrl_output[1] = scan4caObj.angle_adj / 200.0; } else { local4navObj.apf_ctrl_output[0] = 0.0; local4navObj.apf_ctrl_output[1] = 0.0; } local4navObj.SatuateCmdVel(local4navObj.apf_ctrl_output,local4navObj.apf_ctrl_output+1); local4navObj.CalcEuclidDistance(local4navObj.amcl_cur_state, taskObj.cur_goal, rt_r2g_dis); local4navObj.approaching_flag = local4navObj.ReachApprochingAreaOK(&rt_r2g_dis); if(tmp_delta_dis >= GOAL_NGHBORHD) { ptr_action_cmd_t = actionObj.AdjustMovingDirAction(&local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &tmp_robot2goal_yaw, &turn_adj_flag); } else { } if(turn_adj_flag == 1) { if(local4navObj.approaching_flag == false) { *ptr_action_cmd_t = local4navObj.apf_ctrl_output[0]; *(ptr_action_cmd_t + 1) = local4navObj.apf_ctrl_output[1]; } else { ptr_action_cmd_t = actionObj.ApproachingGoalAction(&local4navObj.amcl_cur_state[0],&local4navObj.goal_state[0],&dir_goal_in_laser,&micro_adj_flag); } } cout<<"carto_current_robot_state[0]"<<local4navObj.cur_robot_state[0]<<endl; cout<<"carto_current_robot_state[1]"<<local4navObj.cur_robot_state[1]<<endl; cout<<"carto_current_robot_state[2]"<<local4navObj.cur_robot_state[2]<<endl; cout<<"amcl_current_robot_state[0]"<<local4navObj.amcl_cur_state[0]<<endl; cout<<"amcl_current_robot_state[1]"<<local4navObj.amcl_cur_state[1]<<endl; cout<<"amcl_current_robot_state[2]"<<local4navObj.amcl_cur_state[2]<<endl; cout<<"adj_angle: "<< scan4caObj.angle_adj <<endl; cout<<"tmp_delta_dis: "<<tmp_delta_dis<<endl; cout<<"tmp_robot2goal_yaw: "<<tmp_robot2goal_yaw<<endl; cout<<"tmp_laser2goal_yaw: "<<tmp_laser2goal_yaw<<endl; cout<<"dir_goal_in_laser: "<<dir_goal_in_laser<<endl; //local4navObj.position_OK_flag = local4navObj.ReachGoalPositionOK(&tmp_delta_dis); local4navObj.SatuateCmdVel(ptr_action_cmd_t,ptr_action_cmd_t + 1); local4navObj.apf_cmd_vel.linear.x = *ptr_action_cmd_t; local4navObj.apf_cmd_vel.angular.z = *(ptr_action_cmd_t + 1); if(local4navObj.position_OK_flag == true) { local4navObj.apf_cmd_vel.linear.x = 0.0; local4navObj.apf_cmd_vel.angular.z = 0.0; } cout<<"approaching_flag: " << local4navObj.approaching_flag <<endl; cout<<"position_OK_flag: " << local4navObj.position_OK_flag <<endl; local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); cout<<"pub_linear_x: " << local4navObj.apf_cmd_vel.linear.x <<endl; cout<<"pub_angular_z: " << local4navObj.apf_cmd_vel.angular.z <<endl; scan4caObj.fwd_maxpass_num = 0; scan4caObj.bwd_maxpass_num = 0; cout<<"taskObj.cur_goal[0]: "<<taskObj.cur_goal[0]<<endl; cout<<"taskObj.cur_goal[1]: "<<taskObj.cur_goal[1]<<endl; cout<<"taskObj.cur_goal[2]: "<<taskObj.cur_goal[2]<<endl; ros::spinOnce(); loop_rate.sleep(); ROS_INFO("------- end --------"); } } local4navObj.apf_cmd_vel.linear.x = 0.0; local4navObj.apf_cmd_vel.angular.z = 0.0; local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); return 0; } void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag) { plannerObj->ObtainPathArray(plannerObj->serviceClient, plannerObj->path_srv, start_pos, goal_pos, finish_flag); } <commit_msg>re arrange the statements and comments<commit_after>#include "colibri_ca.h" #include "colibri_local_nav.h" #include "colibri_action.h" #include "PID_controller.h" #include "global_planner.h" #include "task_mgr.h" #include <boost/bind.hpp> #include "geometry_msgs/PoseStamped.h" void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag); int main(int argc, char* argv[]) { ROS_INFO("Start to Go to Mult Goals in Rviz ... "); // ROS nav node initial ros::init(argc, argv, "Nav_Mult_RvizGoal_Node"); ros::Rate loop_rate(10); // Set control freq at 10 hz unsigned int delay_cnt = 0; // Init delay conter for scanObj // Auto nav obj initial scan_ca scan4caObj; local_nav local4navObj; nav_action actionObj; planner plannerObj; task_mgr taskObj; // Local key points relation param initial float tmp_delta_dis = 0.0; float tmp_robot2goal_yaw = 0.0; float tmp_laser2goal_yaw = 0.0; float dir_goal_in_laser = 0.0; float self_rotation_angle = 0.0; bool goal_inlaser_flag = true; unsigned int turn_adj_flag = 1; float tmp_action_cmd_t[2] = {0.0, 0.0}; float* ptr_action_cmd_t = tmp_action_cmd_t; unsigned int micro_adj_flag = 0; unsigned int adj_flag = 0; bool obtain_flag = false; unsigned int search_start = 0; ros::NodeHandle nh_fp; ros::Timer planner_timer; bool finish_plan = false; bool tmp_timer_finish =false; bool *timer_finish = &tmp_timer_finish; static unsigned int index4gravaton = 0; float delta_robot2gravaton = 0.0; bool at_gravaton_flag = false; bool exist_gravaton_flag = false; bool replan_flag = false; float rt_r2g_dis = 100.0; // Waiting for set goal in Rviz while(taskObj.obtain_goal_flag == false) { ros::spinOnce(); loop_rate.sleep(); } local4navObj.goal_state[0] = taskObj.cur_goal[0]; // Extract the Rviz goal for nav local4navObj.goal_state[1] = taskObj.cur_goal[1]; local4navObj.goal_state[2] = taskObj.cur_goal[2]; while (!ros::service::waitForService(plannerObj.srv4make_plan, ros::Duration(0.2))) // Waiting for path paln srv { ROS_INFO("Waiting for srv move_base/make_plan to become available"); } ROS_INFO("Srv move_base/make_plan prepared OK..."); // Inital path plan calling and gravaton calc finish_plan = plannerObj.ExecMonoPlanAndGravaton(plannerObj,&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], search_start,index4gravaton); // Set path plan timer planner_timer = nh_fp.createTimer(ros::Duration(PLAN_INTERVAL), boost::bind(&PlannerCallback, &plannerObj, &local4navObj.amcl_cur_state[0],&taskObj.cur_goal[0], timer_finish)); while (ros::ok()) { if(delay_cnt < DELAY_CNT_MAX) { delay_cnt++; ros::spinOnce(); loop_rate.sleep(); } if(delay_cnt >= DELAY_CNT_MAX) { ROS_INFO("------ start ------"); if(*timer_finish == true) { *timer_finish = false; index4gravaton = 0; replan_flag = true; } else { if((at_gravaton_flag == true && local4navObj.approaching_flag == false)||(replan_flag == true)) { plannerObj.CalcPath2RobotDeltaDis(plannerObj.path_array, local4navObj.amcl_cur_state); index4gravaton = plannerObj.CalcGravatonFromPath(plannerObj.path_array, plannerObj.path2robot_array, index4gravaton, plannerObj.gravaton,exist_gravaton_flag); at_gravaton_flag = false; replan_flag = false; } at_gravaton_flag = actionObj.ReachGravatonOK(&local4navObj.amcl_cur_state[0],&plannerObj.gravaton.x, delta_robot2gravaton); if(local4navObj.approaching_flag == true) { plannerObj.gravaton.x = taskObj.cur_goal[0]; plannerObj.gravaton.y = taskObj.cur_goal[1]; plannerObj.gravaton.yaw = taskObj.cur_goal[2]; } } local4navObj.CalcOffsetOfGoalAndRobot(local4navObj.amcl_cur_state, &plannerObj.gravaton.x, &tmp_delta_dis, &tmp_robot2goal_yaw, &tmp_laser2goal_yaw); goal_inlaser_flag = local4navObj.CalcGoalDirOfLaserViewNew(&tmp_laser2goal_yaw, &local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &self_rotation_angle); scan4caObj.CalcPhiParam(local4navObj.cur_robot_vel[0], dir_goal_in_laser); scan4caObj.CalcKrfTheta(scan4caObj.kp_phi_vec, scan4caObj.phi_start_vec, scan4caObj.phi_end_vec); scan4caObj.CalcCorrectedKrf(); scan4caObj.CalcPassFcnAndFwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec); scan4caObj.CalcPassFcnAndBwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec); scan4caObj.angle_adj = scan4caObj.CalcAdjDir(scan4caObj.passfcn_vec,scan4caObj.max_passfcn_val, &scan4caObj.maxfcn_fwdbnd,&scan4caObj.maxfcn_bwdbnd); scan4caObj.CalcCollisionInAPF(); if(goal_inlaser_flag == true) { local4navObj.apf_ctrl_output[0] = (V_MAX - V_MIN) * (scan4caObj.max_passfcn_val / D_M) + V_MIN; local4navObj.apf_ctrl_output[1] = scan4caObj.angle_adj / 200.0; } else { local4navObj.apf_ctrl_output[0] = 0.0; local4navObj.apf_ctrl_output[1] = 0.0; } local4navObj.SatuateCmdVel(local4navObj.apf_ctrl_output,local4navObj.apf_ctrl_output+1); local4navObj.CalcEuclidDistance(local4navObj.amcl_cur_state, taskObj.cur_goal, rt_r2g_dis); local4navObj.approaching_flag = local4navObj.ReachApprochingAreaOK(&rt_r2g_dis); if(tmp_delta_dis >= GOAL_NGHBORHD) { ptr_action_cmd_t = actionObj.AdjustMovingDirAction(&local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &tmp_robot2goal_yaw, &turn_adj_flag); } else { } if(turn_adj_flag == 1) { if(local4navObj.approaching_flag == false) { *ptr_action_cmd_t = local4navObj.apf_ctrl_output[0]; *(ptr_action_cmd_t + 1) = local4navObj.apf_ctrl_output[1]; } else { ptr_action_cmd_t = actionObj.ApproachingGoalAction(&local4navObj.amcl_cur_state[0],&local4navObj.goal_state[0],&dir_goal_in_laser,&micro_adj_flag); } } //local4navObj.position_OK_flag = local4navObj.ReachGoalPositionOK(&tmp_delta_dis); local4navObj.SatuateCmdVel(ptr_action_cmd_t,ptr_action_cmd_t + 1); local4navObj.apf_cmd_vel.linear.x = *ptr_action_cmd_t; local4navObj.apf_cmd_vel.angular.z = *(ptr_action_cmd_t + 1); if(local4navObj.position_OK_flag == true) { local4navObj.apf_cmd_vel.linear.x = 0.0; local4navObj.apf_cmd_vel.angular.z = 0.0; } local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); scan4caObj.fwd_maxpass_num = 0; scan4caObj.bwd_maxpass_num = 0; cout<<"taskObj.cur_goal[0]: "<<taskObj.cur_goal[0]<<endl; cout<<"taskObj.cur_goal[1]: "<<taskObj.cur_goal[1]<<endl; cout<<"taskObj.cur_goal[2]: "<<taskObj.cur_goal[2]<<endl; ros::spinOnce(); loop_rate.sleep(); ROS_INFO("------- end --------"); } } local4navObj.apf_cmd_vel.linear.x = 0.0; local4navObj.apf_cmd_vel.angular.z = 0.0; local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel); return 0; } void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag) { plannerObj->ObtainPathArray(plannerObj->serviceClient, plannerObj->path_srv, start_pos, goal_pos, finish_flag); } <|endoftext|>
<commit_before>// // refract/Element.cc // librefract // // Created by Jiri Kratochvil on 18/05/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "Element.h" #include <cassert> #include <set> #include <map> #include <string> #include "ComparableVisitor.h" #include "TypeQueryVisitor.h" #include <string.h> namespace refract { namespace { const constexpr std::array<const char*, 13> reservedKeywords = { "null", "boolean", "number", "string", "member", "array", "enum", "object", "ref", "select", "option", "extend", "generic" }; const constexpr std::array<const char*, 3> noMetaKeywords = { "id", "prefix", "namespace" }; const constexpr std::array<const char*, 0> emptyArray = { }; template <typename Container> struct inKeys { const Container& keywords; inKeys(const Container& keywords) : keywords(keywords) {} bool operator()(const std::string& searched) { return std::any_of(keywords.begin(), keywords.end(), [&searched](const char* key) { return !strcmp(key, searched.c_str()); }); } }; template <typename Container> inKeys<Container> InKeysChecker(const Container& keywords) { return inKeys<Container>(keywords); } } bool isReserved(const std::string& element) { return InKeysChecker(reservedKeywords)(element); } IElement::MemberElementCollection::const_iterator IElement::MemberElementCollection::find( const std::string& name) const { ComparableVisitor v(name); Visitor visitor(v); return std::find_if(elements.begin(), elements.end(), [&visitor, &v](const MemberElement* e) { e->value.first->content(visitor); return v.get(); }); } IElement::MemberElementCollection::iterator IElement::MemberElementCollection::find(const std::string& name) { ComparableVisitor v(name); Visitor visitor(v); return std::find_if(elements.begin(), elements.end(), [&visitor, &v](const MemberElement* e) { e->value.first->content(visitor); return v.get(); }); } IElement::MemberElementCollection::~MemberElementCollection() { for (MemberElement* e : elements) delete e; } StringElement* IElement::Create(const char* value) { return Create(std::string(value)); }; MemberElement& IElement::MemberElementCollection::operator[](const std::string& name) { auto it = find(name); if (it != elements.end()) { return *(*it); } elements.emplace_back(new MemberElement(new StringElement(name), nullptr)); return *elements.back(); } void IElement::MemberElementCollection::clone(const IElement::MemberElementCollection& other) { for (const auto& el : other.elements) { elements.emplace_back(static_cast<MemberElement*>(el->clone())); } } void IElement::MemberElementCollection::erase(const std::string& key) { auto it = find(key); if (it != elements.end()) { delete *it; elements.erase(it); } } namespace { bool TypeChecker(const ExtendElement::ValueType& values) { if (values.empty()) { return true; } TypeQueryVisitor visitor; Visit(visitor, *values.front()); const TypeQueryVisitor::ElementType base = visitor.get(); return std::all_of(values.begin(), values.end(), [&visitor, base](const IElement* e) { Visit(visitor, *e); return base == visitor.get(); }); } } void ExtendElement::set(const ExtendElement::ValueType& val) { if (!TypeChecker(val)) { throw LogicError("ExtendElement must be composed from Elements of same type"); } if (val.empty()) { return; } hasContent = true; value = val; } void ExtendElement::push_back(IElement* e) { if (!e) { return; } if (!value.empty()) { TypeQueryVisitor baseType; Visit(baseType, *value.front()); TypeQueryVisitor type; Visit(type, *e); if (baseType.get() != type.get()) { throw LogicError("ExtendElement must be composed from Elements of same type"); } } hasContent = true; value.push_back(e); } namespace { class ElementMerger { IElement* result; TypeQueryVisitor::ElementType base; /** * Merge strategy for Primitive types - just replace by latest value */ template <typename T, typename V = typename T::ValueType> struct ValueMerge { V& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { value = merge.value; } }; template <typename T> struct ValueMerge<T, IElement*> { IElement*& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { if (!value && merge.value) { value = merge.value->clone(); } } }; /** * Merge stategy for objects/array * - if member * - without existing key -> append * - with existing key - replace old value * - if not member * - if empty value -> ignore (type holder for array) * - else append */ template <typename T> struct ValueMerge<T, RefractElements> { typename T::ValueType& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { typedef std::map<std::string, MemberElement*> MapKeyToMember; typedef std::map<std::string, RefElement*> MapNameToRef; MapKeyToMember keysBase; MapNameToRef refBase; for (auto& element : value) { if (MemberElement* member = TypeQueryVisitor::as<MemberElement>(element)) { if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { keysBase[key->value] = member; } } else if (RefElement* ref = TypeQueryVisitor::as<RefElement>(element)) { refBase[ref->value] = ref; } } for (auto const& element : merge.value) { if (MemberElement* member = TypeQueryVisitor::as<MemberElement>(element)) { if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { MapKeyToMember::iterator iKey = keysBase.find(key->value); if (iKey != keysBase.end()) { // key is already presented, replace value delete iKey->second->value.second; iKey->second->value.second = member->value.second->clone(); CollectionMerge()(iKey->second->meta, member->meta, InKeysChecker(noMetaKeywords)); CollectionMerge()(iKey->second->attributes, member->attributes, InKeysChecker(emptyArray)); } else { // unknown key, append value MemberElement* clone = static_cast<MemberElement*>(member->clone()); value.push_back(clone); keysBase[key->value] = clone; } } } else if (RefElement* ref = TypeQueryVisitor::as<RefElement>(element)) { if (refBase.find(ref->value) == refBase.end()) { RefElement* clone = static_cast<RefElement*>(member->clone()); value.push_back(clone); refBase[ref->value] = clone; } } else if (!(element)->empty()) { // merge member is not MemberElement, append value value.push_back(element->clone()); } } } }; class CollectionMerge { public: CollectionMerge() = default; void operator()(IElement::MemberElementCollection& info, const IElement::MemberElementCollection& append, std::function<bool (const std::string&)> noMerge) { IElement::MemberElementCollection toAppend; for (const auto& member : append) { assert(member); if (!member) { continue; } if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { if (noMerge(key->value)) { continue; } IElement::MemberElementCollection::iterator item = info.find(key->value); if (item != info.end()) { // this key alrady exist, replace value delete (*item)->value.second; (*item)->value.second = member->value.second->clone(); continue; } } toAppend.push_back(static_cast<MemberElement*>(member->clone())); } for (const auto& member : toAppend) { info.push_back(member); } toAppend.clear(); } }; /** * precondition - target && append element MUST BE of same type * we use static_cast<> without checking type this is responsibility of caller */ template <typename T> static void doMerge(IElement* target, const IElement* append) { typedef T ElementType; CollectionMerge()(target->meta, append->meta, InKeysChecker(noMetaKeywords)); CollectionMerge()(target->attributes, append->attributes, InKeysChecker(emptyArray)); ValueMerge<T>(static_cast<ElementType&>(*target))(static_cast<const ElementType&>(*append)); } public: ElementMerger() : result(NULL), base(TypeQueryVisitor::Unknown) { } void operator()(const IElement* e) { if (!e) { return; } if (!result) { result = e->clone(); TypeQueryVisitor type; Visit(type, *result); base = type.get(); return; } TypeQueryVisitor type; VisitBy(*e, type); if (type.get() != base) { throw refract::LogicError("Can not merge different types of elements"); } switch (base) { case TypeQueryVisitor::String: doMerge<StringElement>(result, e); return; case TypeQueryVisitor::Number: doMerge<NumberElement>(result, e); return; case TypeQueryVisitor::Boolean: doMerge<BooleanElement>(result, e); return; case TypeQueryVisitor::Array: doMerge<ArrayElement>(result, e); return; case TypeQueryVisitor::Object: doMerge<ObjectElement>(result, e); return; case TypeQueryVisitor::Enum: doMerge<EnumElement>(result, e); return; case TypeQueryVisitor::Ref: doMerge<RefElement>(result, e); return; case TypeQueryVisitor::Member: case TypeQueryVisitor::Extend: case TypeQueryVisitor::Null: throw LogicError("Unappropriate kind of element to merging"); default: throw LogicError("Element has no implemented merging"); } } operator IElement*() const { return result; } }; } IElement* ExtendElement::merge() const { return std::for_each(value.begin(), value.end(), ElementMerger()); } }; // namespace refract <commit_msg>No init empty array<commit_after>// // refract/Element.cc // librefract // // Created by Jiri Kratochvil on 18/05/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "Element.h" #include <cassert> #include <set> #include <map> #include <string> #include "ComparableVisitor.h" #include "TypeQueryVisitor.h" #include <string.h> namespace refract { namespace { const constexpr std::array<const char*, 13> reservedKeywords = { "null", "boolean", "number", "string", "member", "array", "enum", "object", "ref", "select", "option", "extend", "generic" }; const constexpr std::array<const char*, 3> noMetaKeywords = { "id", "prefix", "namespace" }; const constexpr std::array<const char*, 0> emptyArray; template <typename Container> struct inKeys { const Container& keywords; inKeys(const Container& keywords) : keywords(keywords) {} bool operator()(const std::string& searched) { return std::any_of(keywords.begin(), keywords.end(), [&searched](const char* key) { return !strcmp(key, searched.c_str()); }); } }; template <typename Container> inKeys<Container> InKeysChecker(const Container& keywords) { return inKeys<Container>(keywords); } } bool isReserved(const std::string& element) { return InKeysChecker(reservedKeywords)(element); } IElement::MemberElementCollection::const_iterator IElement::MemberElementCollection::find( const std::string& name) const { ComparableVisitor v(name); Visitor visitor(v); return std::find_if(elements.begin(), elements.end(), [&visitor, &v](const MemberElement* e) { e->value.first->content(visitor); return v.get(); }); } IElement::MemberElementCollection::iterator IElement::MemberElementCollection::find(const std::string& name) { ComparableVisitor v(name); Visitor visitor(v); return std::find_if(elements.begin(), elements.end(), [&visitor, &v](const MemberElement* e) { e->value.first->content(visitor); return v.get(); }); } IElement::MemberElementCollection::~MemberElementCollection() { for (MemberElement* e : elements) delete e; } StringElement* IElement::Create(const char* value) { return Create(std::string(value)); }; MemberElement& IElement::MemberElementCollection::operator[](const std::string& name) { auto it = find(name); if (it != elements.end()) { return *(*it); } elements.emplace_back(new MemberElement(new StringElement(name), nullptr)); return *elements.back(); } void IElement::MemberElementCollection::clone(const IElement::MemberElementCollection& other) { for (const auto& el : other.elements) { elements.emplace_back(static_cast<MemberElement*>(el->clone())); } } void IElement::MemberElementCollection::erase(const std::string& key) { auto it = find(key); if (it != elements.end()) { delete *it; elements.erase(it); } } namespace { bool TypeChecker(const ExtendElement::ValueType& values) { if (values.empty()) { return true; } TypeQueryVisitor visitor; Visit(visitor, *values.front()); const TypeQueryVisitor::ElementType base = visitor.get(); return std::all_of(values.begin(), values.end(), [&visitor, base](const IElement* e) { Visit(visitor, *e); return base == visitor.get(); }); } } void ExtendElement::set(const ExtendElement::ValueType& val) { if (!TypeChecker(val)) { throw LogicError("ExtendElement must be composed from Elements of same type"); } if (val.empty()) { return; } hasContent = true; value = val; } void ExtendElement::push_back(IElement* e) { if (!e) { return; } if (!value.empty()) { TypeQueryVisitor baseType; Visit(baseType, *value.front()); TypeQueryVisitor type; Visit(type, *e); if (baseType.get() != type.get()) { throw LogicError("ExtendElement must be composed from Elements of same type"); } } hasContent = true; value.push_back(e); } namespace { class ElementMerger { IElement* result; TypeQueryVisitor::ElementType base; /** * Merge strategy for Primitive types - just replace by latest value */ template <typename T, typename V = typename T::ValueType> struct ValueMerge { V& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { value = merge.value; } }; template <typename T> struct ValueMerge<T, IElement*> { IElement*& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { if (!value && merge.value) { value = merge.value->clone(); } } }; /** * Merge stategy for objects/array * - if member * - without existing key -> append * - with existing key - replace old value * - if not member * - if empty value -> ignore (type holder for array) * - else append */ template <typename T> struct ValueMerge<T, RefractElements> { typename T::ValueType& value; ValueMerge(T& element) : value(element.value) { } void operator()(const T& merge) { typedef std::map<std::string, MemberElement*> MapKeyToMember; typedef std::map<std::string, RefElement*> MapNameToRef; MapKeyToMember keysBase; MapNameToRef refBase; for (auto& element : value) { if (MemberElement* member = TypeQueryVisitor::as<MemberElement>(element)) { if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { keysBase[key->value] = member; } } else if (RefElement* ref = TypeQueryVisitor::as<RefElement>(element)) { refBase[ref->value] = ref; } } for (auto const& element : merge.value) { if (MemberElement* member = TypeQueryVisitor::as<MemberElement>(element)) { if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { MapKeyToMember::iterator iKey = keysBase.find(key->value); if (iKey != keysBase.end()) { // key is already presented, replace value delete iKey->second->value.second; iKey->second->value.second = member->value.second->clone(); CollectionMerge()(iKey->second->meta, member->meta, InKeysChecker(noMetaKeywords)); CollectionMerge()(iKey->second->attributes, member->attributes, InKeysChecker(emptyArray)); } else { // unknown key, append value MemberElement* clone = static_cast<MemberElement*>(member->clone()); value.push_back(clone); keysBase[key->value] = clone; } } } else if (RefElement* ref = TypeQueryVisitor::as<RefElement>(element)) { if (refBase.find(ref->value) == refBase.end()) { RefElement* clone = static_cast<RefElement*>(member->clone()); value.push_back(clone); refBase[ref->value] = clone; } } else if (!(element)->empty()) { // merge member is not MemberElement, append value value.push_back(element->clone()); } } } }; class CollectionMerge { public: CollectionMerge() = default; void operator()(IElement::MemberElementCollection& info, const IElement::MemberElementCollection& append, std::function<bool (const std::string&)> noMerge) { IElement::MemberElementCollection toAppend; for (const auto& member : append) { assert(member); if (!member) { continue; } if (StringElement* key = TypeQueryVisitor::as<StringElement>(member->value.first)) { if (noMerge(key->value)) { continue; } IElement::MemberElementCollection::iterator item = info.find(key->value); if (item != info.end()) { // this key alrady exist, replace value delete (*item)->value.second; (*item)->value.second = member->value.second->clone(); continue; } } toAppend.push_back(static_cast<MemberElement*>(member->clone())); } for (const auto& member : toAppend) { info.push_back(member); } toAppend.clear(); } }; /** * precondition - target && append element MUST BE of same type * we use static_cast<> without checking type this is responsibility of caller */ template <typename T> static void doMerge(IElement* target, const IElement* append) { typedef T ElementType; CollectionMerge()(target->meta, append->meta, InKeysChecker(noMetaKeywords)); CollectionMerge()(target->attributes, append->attributes, InKeysChecker(emptyArray)); ValueMerge<T>(static_cast<ElementType&>(*target))(static_cast<const ElementType&>(*append)); } public: ElementMerger() : result(NULL), base(TypeQueryVisitor::Unknown) { } void operator()(const IElement* e) { if (!e) { return; } if (!result) { result = e->clone(); TypeQueryVisitor type; Visit(type, *result); base = type.get(); return; } TypeQueryVisitor type; VisitBy(*e, type); if (type.get() != base) { throw refract::LogicError("Can not merge different types of elements"); } switch (base) { case TypeQueryVisitor::String: doMerge<StringElement>(result, e); return; case TypeQueryVisitor::Number: doMerge<NumberElement>(result, e); return; case TypeQueryVisitor::Boolean: doMerge<BooleanElement>(result, e); return; case TypeQueryVisitor::Array: doMerge<ArrayElement>(result, e); return; case TypeQueryVisitor::Object: doMerge<ObjectElement>(result, e); return; case TypeQueryVisitor::Enum: doMerge<EnumElement>(result, e); return; case TypeQueryVisitor::Ref: doMerge<RefElement>(result, e); return; case TypeQueryVisitor::Member: case TypeQueryVisitor::Extend: case TypeQueryVisitor::Null: throw LogicError("Unappropriate kind of element to merging"); default: throw LogicError("Element has no implemented merging"); } } operator IElement*() const { return result; } }; } IElement* ExtendElement::merge() const { return std::for_each(value.begin(), value.end(), ElementMerger()); } }; // namespace refract <|endoftext|>
<commit_before>/*! \file */ #include "Grid.h" Grid::Grid() { } // deconstructor Grid::~Grid() { } // initialization int Grid::reinit() { for (int id=0; id<365; id++) { //the following are the original algorithm, and // modified as below by Yi (2013 Feb): // double ampl; // ampl = exp(7.42 +0.045 *gd.lat)/3600.; // gd.alldaylengths[id] = ampl * (sin ((id -79) *0.01721)) +12.0; double daylength = 0.0; //http://www.jgiesen.de/astro/solarday.htm //http://www.gandraxa.com/length_of_day.xml //make sure all arguments in sin, cos and tan are // in unit of arc (not degree) double pi =3.14159; double m = 1- tan(gd.lat*pi/180.0)* tan(23.45*cos(id*pi/182.625)*pi/180.0); m = fmax(m, 0.); m = fmin(m, 2.); double b = acos(1-m)/pi; daylength = b*24; gd.alldaylengths[id] = daylength; } //check for the validity of grid level data if(gd.fri<0|| gd.fri>2000) { gd.fri =2000; } // 06-05-14 // If grid fire related parameters are not // set here, then they are read and set from your // input netCDF files (grid.nc and firestatistics.nc?) //gd.fri = 60; //gd.pfseason[1] = 0.80; //gd.pfsize[1] = 0.80; if(gd.topsoil <0 || gd.botsoil <0) { return -2; } return 0; } //'ed' for the whole grid void Grid::setEnvData(EnvData* edp) { grded = edp; } //'bd' for the whole grid void Grid::setBgcData(BgcData* bdp) { grdbd = bdp; } //inputs void Grid::setRegionData(RegionData* rdp) { rd = rdp; } <commit_msg>Update Grid.cpp<commit_after>/*! \file */ #include "Grid.h" Grid::Grid() { } // deconstructor Grid::~Grid() { } // initialization int Grid::reinit() { for (int id=0; id<365; id++) { //the following are the original algorithm, and // modified as below by Yi (2013 Feb): // double ampl; // ampl = exp(7.42 +0.045 *gd.lat)/3600.; // gd.alldaylengths[id] = ampl * (sin ((id -79) *0.01721)) +12.0; double daylength = 0.0; //http://www.jgiesen.de/astro/solarday.htm //http://www.gandraxa.com/length_of_day.xml //make sure all arguments in sin, cos and tan are // in unit of arc (not degree) double pi =3.14159; double m = 1- tan(gd.lat*pi/180.0)* tan(23.45*cos(id*pi/182.625)*pi/180.0); m = fmax(m, 0.); m = fmin(m, 2.); double b = acos(1-m)/pi; daylength = b*24; gd.alldaylengths[id] = daylength; } //check for the validity of grid level data if(gd.fri<0|| gd.fri>2000) { gd.fri =2000; } //testing or manual firestatistics setting // 06-05-14 // If grid fire related parameters are // set here, then they ARE NOT set from your // input file firestatistics.nc in datagrd //gd.fri = 60; //gd.pfseason[1] = 0.80; //gd.pfsize[1] = 0.80; if(gd.topsoil <0 || gd.botsoil <0) { return -2; } return 0; } //'ed' for the whole grid void Grid::setEnvData(EnvData* edp) { grded = edp; } //'bd' for the whole grid void Grid::setBgcData(BgcData* bdp) { grdbd = bdp; } //inputs void Grid::setRegionData(RegionData* rdp) { rd = rdp; } <|endoftext|>
<commit_before> #include <s2sinputstream.h> #include <virtualhost.h> #include <nanosoft/asyncdns.h> #include <iostream> using namespace std; /** * Конструктор потока */ S2SInputStream::S2SInputStream(XMPPServer *srv, int sock): XMPPStream(srv, sock) { } /** * Деструктор потока */ S2SInputStream::~S2SInputStream() { } /** * Событие: начало потока */ void S2SInputStream::onStartStream(const std::string &name, const attributes_t &attributes) { fprintf(stderr, "#%d new s2s stream\n", getWorkerId()); initXML(); startElement("stream:stream"); setAttribute("xmlns:stream", "http://etherx.jabber.org/streams"); setAttribute("xmlns", "jabber:server"); setAttribute("xmlns:db", "jabber:server:dialback"); setAttribute("id", id = "123456"); // Требования к id — непредсказуемость и уникальность setAttribute("xml:lang", "en"); flush(); } /** * Событие: конец потока */ void S2SInputStream::onEndStream() { cerr << "s2s input stream closed" << endl; endElement("stream:stream"); } /** * Обработчик станзы */ void S2SInputStream::onStanza(Stanza stanza) { fprintf(stderr, "#%d s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); if (stanza->name() == "verify" ) onDBVerifyStanza(stanza); else if (stanza->name() == "result") onDBResultStanza(stanza); else { fprintf(stderr, "#%d unexpected s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); Stanza error = Stanza::streamError("not-authoized"); sendStanza(error); delete error; terminate(); } } /** * Обработка <db:verify> */ void S2SInputStream::onDBVerifyStanza(Stanza stanza) { } /** * Резолвер s2s хоста, запись A (IPv4) */ static void on_s2s_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_a4\n"); for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_jabber._tcp) */ static void on_s2s_srv_jabber(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_s2s_srv_jabber\n"); for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_xmpp-server._tcp) */ static void on_srv_xmpp_server(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_srv_xmpp_server\n"); for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись RBL */ static void on_s2s_rbl(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_rbl\n"); if ( result ) { for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } } printf("\n"); } /** * Обработка <db:result> */ void S2SInputStream::onDBResultStanza(Stanza stanza) { string to = stanza->getAttribute("to"); string from = stanza->getAttribute("from"); cerr << "[s2s-input] db:result to: " << to << ", from: " << from << endl; // Шаг 1. проверка: "to" должен быть нашим виртуальным хостом XMPPDomain *host = server->getHostByName(to); VirtualHost *vhost = dynamic_cast<VirtualHost *>(host); if ( ! vhost ) { Stanza stanza = Stanza::streamError("host-unknown"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 2. проверка "from" // // RFC 3920 не запрещает делать повторные коннекты (8.3.4). // // До завершения авторизации нужно поддерживать старое соединение, // пока не авторизуется новое. Но можно блокировать повторные // коннекты с ошибкой <not-authorized />, что мы и делаем. // // NOTE: В любом случае, логично блокировать попытки представиться // нашим хостом - мы сами к себе никогда не коннектимся. // Так что, если будете открывать повторные коннекты, то забудьте // блокировать попытки коннекта к самим себе. if ( server->getHostByName(from) ) { Stanza stanza = Stanza::streamError("not-authorized"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 3. резолвим DNS записи сервера // NOTE для оптимизации отправляем все DNS (асинхронные) запросы сразу server->adns->a4(from.c_str(), on_s2s_a4, this); server->adns->srv(from.c_str(), "jabber", "tcp", on_s2s_srv_jabber, this); server->adns->srv(from.c_str(), "xmpp-server", "tcp", on_srv_xmpp_server, this); // TODO извлекать список DNSBL из конфига server->adns->a4((from + ".dnsbl.jabber.ru").c_str(), on_s2s_rbl, this); } /** * Событие закрытие соединения * * Вызывается если peer закрыл соединение */ void S2SInputStream::onShutdown() { cerr << "[s2s input]: peer shutdown connection" << endl; if ( state != terminating ) { AsyncXMLStream::onShutdown(); XMLWriter::flush(); } server->daemon->removeObject(this); shutdown(READ | WRITE); delete this; cerr << "[s2s input]: shutdown leave" << endl; } void S2SInputStream::terminate() { cerr << "[s2s input]: terminating connection..." << endl; switch ( state ) { case terminating: return; case authorized: break; } mutex.lock(); if ( state != terminating ) { state = terminating; endElement("stream:stream"); flush(); shutdown(WRITE); } mutex.unlock(); } /** * Сигнал завершения работы * * Объект должен закрыть файловый дескриптор * и освободить все занимаемые ресурсы */ void S2SInputStream::onTerminate() { terminate(); } <commit_msg>s2s: fix проверка на остуствие DNS записи<commit_after> #include <s2sinputstream.h> #include <virtualhost.h> #include <nanosoft/asyncdns.h> #include <iostream> using namespace std; /** * Конструктор потока */ S2SInputStream::S2SInputStream(XMPPServer *srv, int sock): XMPPStream(srv, sock) { } /** * Деструктор потока */ S2SInputStream::~S2SInputStream() { } /** * Событие: начало потока */ void S2SInputStream::onStartStream(const std::string &name, const attributes_t &attributes) { fprintf(stderr, "#%d new s2s stream\n", getWorkerId()); initXML(); startElement("stream:stream"); setAttribute("xmlns:stream", "http://etherx.jabber.org/streams"); setAttribute("xmlns", "jabber:server"); setAttribute("xmlns:db", "jabber:server:dialback"); setAttribute("id", id = "123456"); // Требования к id — непредсказуемость и уникальность setAttribute("xml:lang", "en"); flush(); } /** * Событие: конец потока */ void S2SInputStream::onEndStream() { cerr << "s2s input stream closed" << endl; endElement("stream:stream"); } /** * Обработчик станзы */ void S2SInputStream::onStanza(Stanza stanza) { fprintf(stderr, "#%d s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); if (stanza->name() == "verify" ) onDBVerifyStanza(stanza); else if (stanza->name() == "result") onDBResultStanza(stanza); else { fprintf(stderr, "#%d unexpected s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); Stanza error = Stanza::streamError("not-authoized"); sendStanza(error); delete error; terminate(); } } /** * Обработка <db:verify> */ void S2SInputStream::onDBVerifyStanza(Stanza stanza) { } /** * Резолвер s2s хоста, запись A (IPv4) */ static void on_s2s_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_a4\n"); if ( result ) for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_jabber._tcp) */ static void on_s2s_srv_jabber(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_s2s_srv_jabber\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_xmpp-server._tcp) */ static void on_srv_xmpp_server(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_srv_xmpp_server\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись RBL */ static void on_s2s_rbl(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_rbl\n"); if ( result ) { for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } } printf("\n"); } /** * Обработка <db:result> */ void S2SInputStream::onDBResultStanza(Stanza stanza) { string to = stanza->getAttribute("to"); string from = stanza->getAttribute("from"); cerr << "[s2s-input] db:result to: " << to << ", from: " << from << endl; // Шаг 1. проверка: "to" должен быть нашим виртуальным хостом XMPPDomain *host = server->getHostByName(to); VirtualHost *vhost = dynamic_cast<VirtualHost *>(host); if ( ! vhost ) { Stanza stanza = Stanza::streamError("host-unknown"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 2. проверка "from" // // RFC 3920 не запрещает делать повторные коннекты (8.3.4). // // До завершения авторизации нужно поддерживать старое соединение, // пока не авторизуется новое. Но можно блокировать повторные // коннекты с ошибкой <not-authorized />, что мы и делаем. // // NOTE: В любом случае, логично блокировать попытки представиться // нашим хостом - мы сами к себе никогда не коннектимся. // Так что, если будете открывать повторные коннекты, то забудьте // блокировать попытки коннекта к самим себе. if ( server->getHostByName(from) ) { Stanza stanza = Stanza::streamError("not-authorized"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 3. резолвим DNS записи сервера // NOTE для оптимизации отправляем все DNS (асинхронные) запросы сразу server->adns->a4(from.c_str(), on_s2s_a4, this); server->adns->srv(from.c_str(), "jabber", "tcp", on_s2s_srv_jabber, this); server->adns->srv(from.c_str(), "xmpp-server", "tcp", on_srv_xmpp_server, this); // TODO извлекать список DNSBL из конфига server->adns->a4((from + ".dnsbl.jabber.ru").c_str(), on_s2s_rbl, this); } /** * Событие закрытие соединения * * Вызывается если peer закрыл соединение */ void S2SInputStream::onShutdown() { cerr << "[s2s input]: peer shutdown connection" << endl; if ( state != terminating ) { AsyncXMLStream::onShutdown(); XMLWriter::flush(); } server->daemon->removeObject(this); shutdown(READ | WRITE); delete this; cerr << "[s2s input]: shutdown leave" << endl; } void S2SInputStream::terminate() { cerr << "[s2s input]: terminating connection..." << endl; switch ( state ) { case terminating: return; case authorized: break; } mutex.lock(); if ( state != terminating ) { state = terminating; endElement("stream:stream"); flush(); shutdown(WRITE); } mutex.unlock(); } /** * Сигнал завершения работы * * Объект должен закрыть файловый дескриптор * и освободить все занимаемые ресурсы */ void S2SInputStream::onTerminate() { terminate(); } <|endoftext|>
<commit_before>#include "dsa_common.h" #include "string.h" #include <boost/filesystem.hpp> #include "openssl/rand.h" #include "module/default/simple_storage.h" using namespace std; namespace fs = boost::filesystem; namespace dsa { string_ string_from_file(string_ file_path) { SimpleStorage simple_storage; std::unique_ptr<StorageBucket> storage_bucket; string_ data; storage_bucket = simple_storage.get_bucket(file_path); auto read_callback = [&](std::string storage_key, std::vector<uint8_t> vec) { string_ content(vec.begin(), vec.end()); data = content; }; storage_bucket->read(file_path, read_callback); return data; } void string_to_file(string_ data, string_ file_path) { SimpleStorage simple_storage; std::unique_ptr<StorageBucket> storage_bucket; storage_bucket = simple_storage.get_bucket(file_path); auto content = new RefCountBytes(&data.c_str()[0], &data.c_str()[strlen(data.c_str())]); storage_bucket->write(file_path, std::forward<RefCountBytes*>(content)); } std::vector<unsigned char> get_random_byte_array(int len) { if (!IS_RAND_INITIALIZED) { RAND_poll(); IS_RAND_INITIALIZED = 1; } std::vector<unsigned char> buffer(len); RAND_bytes(buffer.data(), len); return buffer; } static unsigned char get_random_char() { while (1) { unsigned char n = (unsigned char)(get_random_byte_array(1)[0] & 0x7F); if ((n >= '0' && n <= '9') || (n >= 'A' && n <= 'Z') || (n >= 'a' && n <= 'z')) { return n; } } } string_ generate_random_string(int len) { string_ randStr; for (int i = 0; i < len; ++i) { randStr += get_random_char(); } return randStr; } string_ get_close_token_from_file(string_ path_str, bool force_to_generate_one) { try { string_ token = string_from_file(path_str); if (token.length() != 32) throw std::runtime_error("invalid token length != 32 in file"); return token; } catch (std::exception &e) { if (!force_to_generate_one) return ""; } auto new_token = generate_random_string(32); string_to_file(new_token, path_str); return new_token; } }<commit_msg>fix compilation error, need to include io_service first so winsock header is included in the right order<commit_after>#include "dsa_common.h" #include "string.h" #include <boost/asio/io_service.hpp> #include <boost/filesystem.hpp> #include "module/default/simple_storage.h" #include "openssl/rand.h" using namespace std; namespace fs = boost::filesystem; namespace dsa { string_ string_from_file(string_ file_path) { SimpleStorage simple_storage; std::unique_ptr<StorageBucket> storage_bucket; string_ data; storage_bucket = simple_storage.get_bucket(file_path); auto read_callback = [&](std::string storage_key, std::vector<uint8_t> vec) { string_ content(vec.begin(), vec.end()); data = content; }; storage_bucket->read(file_path, read_callback); return data; } void string_to_file(string_ data, string_ file_path) { SimpleStorage simple_storage; std::unique_ptr<StorageBucket> storage_bucket; storage_bucket = simple_storage.get_bucket(file_path); auto content = new RefCountBytes(&data.c_str()[0], &data.c_str()[strlen(data.c_str())]); storage_bucket->write(file_path, std::forward<RefCountBytes *>(content)); } std::vector<unsigned char> get_random_byte_array(int len) { if (!IS_RAND_INITIALIZED) { RAND_poll(); IS_RAND_INITIALIZED = 1; } std::vector<unsigned char> buffer(len); RAND_bytes(buffer.data(), len); return buffer; } static unsigned char get_random_char() { while (1) { unsigned char n = (unsigned char)(get_random_byte_array(1)[0] & 0x7F); if ((n >= '0' && n <= '9') || (n >= 'A' && n <= 'Z') || (n >= 'a' && n <= 'z')) { return n; } } } string_ generate_random_string(int len) { string_ randStr; for (int i = 0; i < len; ++i) { randStr += get_random_char(); } return randStr; } string_ get_close_token_from_file(string_ path_str, bool force_to_generate_one) { try { string_ token = string_from_file(path_str); if (token.length() != 32) throw std::runtime_error("invalid token length != 32 in file"); return token; } catch (std::exception &e) { if (!force_to_generate_one) return ""; } auto new_token = generate_random_string(32); string_to_file(new_token, path_str); return new_token; } }<|endoftext|>
<commit_before>#include "include/writer.h" #include <QFile> #include <QTextStream> #include <QDebug> #include "include/abstractdata.h" #include "filechecker.h" using namespace QtCSV; // Write data to .csv file // @input: // - filePath - string with absolute path to csv file // - data - not empty data that should be written to .csv file // - separator - string or character separating columns // - mode - write mode of the file: rewrite file or append data to the end // - header - strings that will be written at the beginning of the file in // one line. separator will be used as delimiter character. // - footer - strings that will be written at the end of the file in // one line. separator will be used as delimiter character. // @output: // - bool - True if data was written to the file, otherwise False bool Writer::write(const QString &filePath, const AbstractData &data, const QString &separator, const WriteMode &mode, const QStringList &header, const QStringList &footer) { if ( true == filePath.isEmpty() || true == data.isEmpty() ) { qDebug() << __func__ << "Error - invalid arguments"; return false; } if ( false == CheckFile(filePath) ) { qDebug() << __func__ << "Error - wrong file path/name:" << filePath; return false; } QFile csvFile; csvFile.setFileName(filePath); bool fileOpened = csvFile.open(GetMode(mode) | QIODevice::Text); if ( false == fileOpened ) { qDebug() << __func__ << "Error - can't open file:" << filePath; return false; } QTextStream stream; stream.setDevice(&csvFile); if ( false == header.isEmpty() ) { stream << header.join(separator) << endl; } int rowsNum = data.getNumberOfRows(); for (int i = 0; i < rowsNum; ++i) { QStringList rowValues = data.getRowValues(i); stream << rowValues.join(separator) << endl; } if ( false == footer.isEmpty() ) { stream << footer.join(separator) << endl; } csvFile.close(); return true; } // Get QIODevice mode // @input: // - mode - write mode // @output: // - QIODevice::OpenMode - corresponding QIODevice::OpenMode QIODevice::OpenMode Writer::GetMode(const WriteMode &mode) { switch (mode) { case WriteMode::APPEND: return QIODevice::Append; case WriteMode::REWRITE: default: return QIODevice::WriteOnly; } return QIODevice::WriteOnly; } <commit_msg>Postpone all operations with file to the end of the write() function<commit_after>#include "include/writer.h" #include <QFile> #include <QTextStream> #include <QDebug> #include "include/abstractdata.h" #include "filechecker.h" using namespace QtCSV; // Write data to .csv file // @input: // - filePath - string with absolute path to csv file // - data - not empty data that should be written to .csv file // - separator - string or character separating columns // - mode - write mode of the file: rewrite file or append data to the end // - header - strings that will be written at the beginning of the file in // one line. separator will be used as delimiter character. // - footer - strings that will be written at the end of the file in // one line. separator will be used as delimiter character. // @output: // - bool - True if data was written to the file, otherwise False bool Writer::write(const QString &filePath, const AbstractData &data, const QString &separator, const WriteMode &mode, const QStringList &header, const QStringList &footer) { if ( true == filePath.isEmpty() || true == data.isEmpty() ) { qDebug() << __func__ << "Error - invalid arguments"; return false; } if ( false == CheckFile(filePath) ) { qDebug() << __func__ << "Error - wrong file path/name:" << filePath; return false; } // Prepare data that would be written to file QStringList textLines; if ( false == header.isEmpty() ) { textLines << header.join(separator); } const int rowsNum = data.getNumberOfRows(); for (int i = 0; i < rowsNum; ++i) { textLines << data.getRowValues(i).join(separator); } if ( false == footer.isEmpty() ) { textLines << footer.join(separator); } // Write prepaired data to file QFile csvFile(filePath); if ( false == csvFile.open(GetMode(mode) | QIODevice::Text) ) { qDebug() << __func__ << "Error - can't open file:" << filePath; return false; } QTextStream stream; stream.setDevice(&csvFile); stream << textLines.join("\n"); stream.flush(); csvFile.close(); return true; } // Get QIODevice mode // @input: // - mode - write mode // @output: // - QIODevice::OpenMode - corresponding QIODevice::OpenMode QIODevice::OpenMode Writer::GetMode(const WriteMode &mode) { switch (mode) { case WriteMode::APPEND: return QIODevice::Append; case WriteMode::REWRITE: default: return QIODevice::WriteOnly; } return QIODevice::WriteOnly; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashdev.h" #include <splashcore/SplashNet.pb.h> #include <ext/stdio_filebuf.h> using namespace std; void ShowUsage(); void ShowVersion(); //Map of watch descriptors to directory names map<int, string> g_watchMap; /** @brief Program entry point */ int main(int argc, char* argv[]) { Severity console_verbosity = Severity::NOTICE; //Parse command-line arguments for(int i=1; i<argc; i++) { string s(argv[i]); //Let the logger eat its args first if(ParseLoggerArguments(i, argc, argv, console_verbosity)) continue; else if(s == "--help") { ShowUsage(); return 0; } else if(s == "--version") { ShowVersion(); return 0; } //Bad argument else { ShowUsage(); return 1; } } //Set up logging g_log_sinks.emplace(g_log_sinks.begin(), new ColoredSTDLogSink(console_verbosity)); //Print header if(console_verbosity >= Severity::NOTICE) { ShowVersion(); printf("\n"); } //Load the configuration so we know where the server is, etc g_clientSettings = new ClientSettings; //Connect to the server Socket sock(AF_INET6, SOCK_STREAM, IPPROTO_TCP); if(!ConnectToServer(sock, ClientHello::CLIENT_DEVELOPER)) return 1; //Send the devInfo SplashMsg devi; auto devim = devi.mutable_devinfo(); devim->set_arch(ShellCommand("dpkg-architecture -l | grep DEB_HOST_GNU_TYPE | cut -d '=' -f 2", true)); if(!SendMessage(sock, devi)) return 1; //Recursively send file-changed notifications for everything in our working directory //(in case anything changed while we weren't running) LogVerbose("Sending initial change notifications...\n"); double start = GetTime(); SplashMsg icn; BuildChangeNotificationForDir(icn.mutable_bulkfilechanged(), g_clientSettings->GetProjectRoot()); if(!SendMessage(sock, icn)) return 1; SplashMsg icr; if(!RecvMessage(sock, icr)) return 1; if(!ProcessBulkFileAck(sock, icr)) return 1; double dt = GetTime() - start; LogVerbose("Change notifications sent (in %.3f sec)\n", dt); //Open the source directory and start an inotify watcher on it and all subdirectories int hnotify = inotify_init(); if(hnotify < 0) LogFatal("Couldn't start inotify\n"); LogNotice("Watching for changes to source files in: %s\n", g_clientSettings->GetProjectRoot().c_str()); WatchDirRecursively(hnotify, g_clientSettings->GetProjectRoot()); //TODO: signal handler so we can quit gracefully //Main event loop size_t buflen = 8192; char ebuf[buflen]; while(1) { //Get the event ssize_t len = read(hnotify, ebuf, buflen); if(len <= 0) break; ssize_t offset = 0; while(offset < len) { inotify_event* evt = reinterpret_cast<inotify_event*>(ebuf + offset); //Skip events without a filename, or hidden files if( (evt->len != 0) && (evt->name[0] != '.') ) WatchedFileChanged(sock, evt->mask, g_watchMap[evt->wd] + "/" + evt->name); //Go on to the next one offset += sizeof(inotify_event) + evt->len; } } //Done close(hnotify); delete g_clientSettings; return 0; } /** @brief Add watches to a directory *and* all subdirectories */ void WatchDirRecursively(int hnotify, string dir) { //Do not watch the build directory for obvious reasons if(dir == "build") return; //LogDebug(" Recursively watching directory %s\n", dir.c_str()); //Watch changes to the directory int wd; if(0 > (wd = inotify_add_watch( hnotify, dir.c_str(), IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF))) { LogFatal("Failed to watch directory %s\n", dir.c_str()); } g_watchMap[wd] = dir; //Look for any subdirs and watch them vector<string> subdirs; FindSubdirs(dir, subdirs); for(auto s : subdirs) WatchDirRecursively(hnotify, s); } void ShowVersion() { printf( "SPLASH developer workstation daemon by Andrew D. Zonenberg.\n" "\n" "License: 3-clause BSD\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } void ShowUsage() { printf("Usage: splashdev [standard log arguments]\n"); exit(0); } <commit_msg>splashdev: added support for ".splashignore" files to skip child directories<commit_after>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashdev.h" #include <splashcore/SplashNet.pb.h> #include <ext/stdio_filebuf.h> using namespace std; void ShowUsage(); void ShowVersion(); //Map of watch descriptors to directory names map<int, string> g_watchMap; /** @brief Program entry point */ int main(int argc, char* argv[]) { Severity console_verbosity = Severity::NOTICE; //Parse command-line arguments for(int i=1; i<argc; i++) { string s(argv[i]); //Let the logger eat its args first if(ParseLoggerArguments(i, argc, argv, console_verbosity)) continue; else if(s == "--help") { ShowUsage(); return 0; } else if(s == "--version") { ShowVersion(); return 0; } //Bad argument else { ShowUsage(); return 1; } } //Set up logging g_log_sinks.emplace(g_log_sinks.begin(), new ColoredSTDLogSink(console_verbosity)); //Print header if(console_verbosity >= Severity::NOTICE) { ShowVersion(); printf("\n"); } //Load the configuration so we know where the server is, etc g_clientSettings = new ClientSettings; //Connect to the server Socket sock(AF_INET6, SOCK_STREAM, IPPROTO_TCP); if(!ConnectToServer(sock, ClientHello::CLIENT_DEVELOPER)) return 1; //Send the devInfo SplashMsg devi; auto devim = devi.mutable_devinfo(); devim->set_arch(ShellCommand("dpkg-architecture -l | grep DEB_HOST_GNU_TYPE | cut -d '=' -f 2", true)); if(!SendMessage(sock, devi)) return 1; //Recursively send file-changed notifications for everything in our working directory //(in case anything changed while we weren't running) LogVerbose("Sending initial change notifications...\n"); double start = GetTime(); SplashMsg icn; BuildChangeNotificationForDir(icn.mutable_bulkfilechanged(), g_clientSettings->GetProjectRoot()); if(!SendMessage(sock, icn)) return 1; SplashMsg icr; if(!RecvMessage(sock, icr)) return 1; if(!ProcessBulkFileAck(sock, icr)) return 1; double dt = GetTime() - start; LogVerbose("Change notifications sent (in %.3f sec)\n", dt); //Open the source directory and start an inotify watcher on it and all subdirectories int hnotify = inotify_init(); if(hnotify < 0) LogFatal("Couldn't start inotify\n"); LogNotice("Watching for changes to source files in: %s\n", g_clientSettings->GetProjectRoot().c_str()); WatchDirRecursively(hnotify, g_clientSettings->GetProjectRoot()); //TODO: signal handler so we can quit gracefully //Main event loop size_t buflen = 8192; char ebuf[buflen]; while(1) { //Get the event ssize_t len = read(hnotify, ebuf, buflen); if(len <= 0) break; ssize_t offset = 0; while(offset < len) { inotify_event* evt = reinterpret_cast<inotify_event*>(ebuf + offset); //Skip events without a filename, or hidden files if( (evt->len != 0) && (evt->name[0] != '.') ) WatchedFileChanged(sock, evt->mask, g_watchMap[evt->wd] + "/" + evt->name); //Go on to the next one offset += sizeof(inotify_event) + evt->len; } } //Done close(hnotify); delete g_clientSettings; return 0; } /** @brief Add watches to a directory *and* all subdirectories */ void WatchDirRecursively(int hnotify, string dir) { //Do not watch the build directory for obvious reasons if(dir == "build") return; //If the directory has a ".splashignore" file in it, don't do anything if(DoesFileExist(dir + "/.splashignore")) return; //LogDebug(" Recursively watching directory %s\n", dir.c_str()); //Watch changes to the directory int wd; if(0 > (wd = inotify_add_watch( hnotify, dir.c_str(), IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF))) { LogFatal("Failed to watch directory %s\n", dir.c_str()); } g_watchMap[wd] = dir; //Look for any subdirs and watch them vector<string> subdirs; FindSubdirs(dir, subdirs); for(auto s : subdirs) WatchDirRecursively(hnotify, s); } void ShowVersion() { printf( "SPLASH developer workstation daemon by Andrew D. Zonenberg.\n" "\n" "License: 3-clause BSD\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } void ShowUsage() { printf("Usage: splashdev [standard log arguments]\n"); exit(0); } <|endoftext|>
<commit_before>#include "tarsnapaccount.h" #include "debug.h" #include "utils.h" #include <QMessageBox> #include <QNetworkReply> #include <QNetworkRequest> #include <QSettings> #include <QTableWidget> #define URL_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=activity&format=csv" #define URL_MACHINE_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity&mid=%3&format=csv" TarsnapAccount::TarsnapAccount(QWidget *parent) : QDialog(parent), _nam(this) { _ui.setupUi(this); setWindowFlags((windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint); } void TarsnapAccount::getAccountInfo(bool displayActivity, bool displayMachineActivity) { QSettings settings; _user = settings.value("tarsnap/user", "").toString(); _machine = settings.value("tarsnap/machine", "").toString(); if(Utils::tarsnapVersionMinimum("1.0.37")) { emit getKeyId(settings.value("tarsnap/key", "").toString()); } else { QMessageBox::warning(this, tr("Warning"), tr("You need Tarsnap CLI utils version 1.0.37 to " "be able to fetch machine activity. " "You have version %1.") .arg(settings.value("tarsnap/version", "").toString())); } if(_user.isEmpty() || _machine.isEmpty()) { QMessageBox::warning(this, tr("Warning"), tr("Tarsnap user and machine name must be set.")); return; } _ui.textLabel->setText(tr("Type password for account %1:").arg(_user)); if(exec() == QDialog::Rejected) return; QString getActivity(URL_ACTIVITY); getActivity = getActivity.arg(QString(QUrl::toPercentEncoding(_user)), QString(QUrl::toPercentEncoding( _ui.passwordLineEdit->text()))); QNetworkReply *activityReply = tarsnapRequest(getActivity); connect(activityReply, &QNetworkReply::finished, [=]() { QByteArray replyData = readReply(activityReply, true); parseCredit(replyData); if(displayActivity) displayCSVTable(replyData, tr("Account activity")); }); _machineId = settings.value("tarsnap/key_id", 0).toInt(); if(_machineId) { QString machineActivity(URL_MACHINE_ACTIVITY); QString hexId("%1"); hexId = hexId.arg(_machineId, 16, 16, QLatin1Char('0')); machineActivity = machineActivity.arg( QString(QUrl::toPercentEncoding(_user)), QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())), QString(QUrl::toPercentEncoding(hexId))); QNetworkReply *machineActivityReply = tarsnapRequest(machineActivity); connect(machineActivityReply, &QNetworkReply::finished, [=]() { QByteArray replyData = readReply(machineActivityReply); parseLastMachineActivity(replyData); if(displayMachineActivity) displayCSVTable(replyData, tr("Machine activity")); }); } _ui.passwordLineEdit->clear(); } void TarsnapAccount::parseCredit(QString csv) { if(csv.isEmpty() || !csv.startsWith("RECTYPE")) return; QRegExp lastBalanceRx("^(Balance.+)$", Qt::CaseInsensitive, QRegExp::RegExp2); QString lastBalance; foreach(QString line, csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts)) { if(0 == lastBalanceRx.indexIn(line)) lastBalance = line; } if(!lastBalance.isEmpty()) { QStringList fields = lastBalance.split(',', QString::SkipEmptyParts); if(fields.count() != 3) { DEBUG << "Invalid CSV."; return; } emit accountCredit(fields.last().toFloat(), QDate::fromString(fields[1], Qt::ISODate)); } } void TarsnapAccount::parseLastMachineActivity(QString csv) { if(csv.isEmpty() || !csv.startsWith("DATE")) return; QString lastLine = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts).last(); emit lastMachineActivity(lastLine.split(',', QString::SkipEmptyParts)); } void TarsnapAccount::displayCSVTable(QString csv, QString title) { DEBUG << csv; if(csv.isEmpty() || csv.startsWith("<!DOCTYPE html>")) return; QStringList lines = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); if(lines.count() <= 1) return; QStringList columnHeaders = lines.first().split(',', QString::SkipEmptyParts); lines.removeFirst(); QTableWidget *table = new QTableWidget(lines.count(), columnHeaders.count()); table->setHorizontalHeaderLabels(columnHeaders); table->horizontalHeader()->setStretchLastSection(true); table->setAlternatingRowColors(true); table->setEditTriggers(QAbstractItemView::NoEditTriggers); QDialog *tableDialog = new QDialog(this); tableDialog->setWindowTitle(title); tableDialog->setAttribute(Qt::WA_DeleteOnClose, true); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(table); layout->setMargin(0); tableDialog->setLayout(layout); qint64 row = 0; qint64 column = 0; foreach(QString line, lines) { foreach(QString entry, line.split(',', QString::KeepEmptyParts)) { table->setItem(row, column, new QTableWidgetItem(entry)); column++; } row++; column = 0; } tableDialog->show(); } QNetworkReply *TarsnapAccount::tarsnapRequest(QString url) { QNetworkRequest request; request.setUrl(url); request.setRawHeader( "User-Agent", (qApp->applicationName() + " " + qApp->applicationVersion()).toLatin1()); QNetworkReply *reply = _nam.get(request); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); connect(reply, &QNetworkReply::sslErrors, this, &TarsnapAccount::sslError); return reply; } QByteArray TarsnapAccount::readReply(QNetworkReply *reply, bool warn) { QByteArray data = reply->readAll(); if(warn && data.contains("Password is incorrect; please try again.")) { QMessageBox::warning(this, tr("Invalid password"), tr("Password for account %1 is incorrect; please try again.").arg(_user)); } else if(warn && data.contains("No user exists with the provided email " "address; please try again.")) { QMessageBox::warning(this, tr("Invalid username"), tr("Account %1 is invalid; please try again.").arg(_user)); } reply->close(); reply->deleteLater(); return data; } void TarsnapAccount::networkError(QNetworkReply::NetworkError error) { Q_UNUSED(error) QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); DEBUG << reply->errorString(); } void TarsnapAccount::sslError(QList<QSslError> errors) { foreach(QSslError error, errors) { DEBUG << error.errorString(); } } <commit_msg>Disable Login button if password input is empty.<commit_after>#include "tarsnapaccount.h" #include "debug.h" #include "utils.h" #include <QMessageBox> #include <QNetworkReply> #include <QNetworkRequest> #include <QSettings> #include <QTableWidget> #define URL_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=activity&format=csv" #define URL_MACHINE_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity&mid=%3&format=csv" TarsnapAccount::TarsnapAccount(QWidget *parent) : QDialog(parent), _nam(this) { _ui.setupUi(this); setWindowFlags((windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint); connect(_ui.passwordLineEdit, &QLineEdit::textEdited, this, [&]() { _ui.loginButton->setEnabled(!_ui.passwordLineEdit->text().isEmpty()); }); } void TarsnapAccount::getAccountInfo(bool displayActivity, bool displayMachineActivity) { QSettings settings; _user = settings.value("tarsnap/user", "").toString(); _machine = settings.value("tarsnap/machine", "").toString(); if(Utils::tarsnapVersionMinimum("1.0.37")) { emit getKeyId(settings.value("tarsnap/key", "").toString()); } else { QMessageBox::warning(this, tr("Warning"), tr("You need Tarsnap CLI utils version 1.0.37 to " "be able to fetch machine activity. " "You have version %1.") .arg(settings.value("tarsnap/version", "").toString())); } if(_user.isEmpty() || _machine.isEmpty()) { QMessageBox::warning(this, tr("Warning"), tr("Tarsnap user and machine name must be set.")); return; } _ui.textLabel->setText(tr("Type password for account %1:").arg(_user)); _ui.loginButton->setEnabled(false); if(exec() == QDialog::Rejected) return; QString getActivity(URL_ACTIVITY); getActivity = getActivity.arg(QString(QUrl::toPercentEncoding(_user)), QString(QUrl::toPercentEncoding( _ui.passwordLineEdit->text()))); QNetworkReply *activityReply = tarsnapRequest(getActivity); connect(activityReply, &QNetworkReply::finished, [=]() { QByteArray replyData = readReply(activityReply, true); parseCredit(replyData); if(displayActivity) displayCSVTable(replyData, tr("Account activity")); }); _machineId = settings.value("tarsnap/key_id", 0).toInt(); if(_machineId) { QString machineActivity(URL_MACHINE_ACTIVITY); QString hexId("%1"); hexId = hexId.arg(_machineId, 16, 16, QLatin1Char('0')); machineActivity = machineActivity.arg( QString(QUrl::toPercentEncoding(_user)), QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())), QString(QUrl::toPercentEncoding(hexId))); QNetworkReply *machineActivityReply = tarsnapRequest(machineActivity); connect(machineActivityReply, &QNetworkReply::finished, [=]() { QByteArray replyData = readReply(machineActivityReply); parseLastMachineActivity(replyData); if(displayMachineActivity) displayCSVTable(replyData, tr("Machine activity")); }); } _ui.passwordLineEdit->clear(); } void TarsnapAccount::parseCredit(QString csv) { if(csv.isEmpty() || !csv.startsWith("RECTYPE")) return; QRegExp lastBalanceRx("^(Balance.+)$", Qt::CaseInsensitive, QRegExp::RegExp2); QString lastBalance; foreach(QString line, csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts)) { if(0 == lastBalanceRx.indexIn(line)) lastBalance = line; } if(!lastBalance.isEmpty()) { QStringList fields = lastBalance.split(',', QString::SkipEmptyParts); if(fields.count() != 3) { DEBUG << "Invalid CSV."; return; } emit accountCredit(fields.last().toFloat(), QDate::fromString(fields[1], Qt::ISODate)); } } void TarsnapAccount::parseLastMachineActivity(QString csv) { if(csv.isEmpty() || !csv.startsWith("DATE")) return; QString lastLine = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts).last(); emit lastMachineActivity(lastLine.split(',', QString::SkipEmptyParts)); } void TarsnapAccount::displayCSVTable(QString csv, QString title) { DEBUG << csv; if(csv.isEmpty() || csv.startsWith("<!DOCTYPE html>")) return; QStringList lines = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); if(lines.count() <= 1) return; QStringList columnHeaders = lines.first().split(',', QString::SkipEmptyParts); lines.removeFirst(); QTableWidget *table = new QTableWidget(lines.count(), columnHeaders.count()); table->setHorizontalHeaderLabels(columnHeaders); table->horizontalHeader()->setStretchLastSection(true); table->setAlternatingRowColors(true); table->setEditTriggers(QAbstractItemView::NoEditTriggers); QDialog *tableDialog = new QDialog(this); tableDialog->setWindowTitle(title); tableDialog->setAttribute(Qt::WA_DeleteOnClose, true); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(table); layout->setMargin(0); tableDialog->setLayout(layout); qint64 row = 0; qint64 column = 0; foreach(QString line, lines) { foreach(QString entry, line.split(',', QString::KeepEmptyParts)) { table->setItem(row, column, new QTableWidgetItem(entry)); column++; } row++; column = 0; } tableDialog->show(); } QNetworkReply *TarsnapAccount::tarsnapRequest(QString url) { QNetworkRequest request; request.setUrl(url); request.setRawHeader( "User-Agent", (qApp->applicationName() + " " + qApp->applicationVersion()).toLatin1()); QNetworkReply *reply = _nam.get(request); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); connect(reply, &QNetworkReply::sslErrors, this, &TarsnapAccount::sslError); return reply; } QByteArray TarsnapAccount::readReply(QNetworkReply *reply, bool warn) { QByteArray data = reply->readAll(); if(warn && data.contains("Password is incorrect; please try again.")) { QMessageBox::warning(this, tr("Invalid password"), tr("Password for account %1 is incorrect; please try again.").arg(_user)); } else if(warn && data.contains("No user exists with the provided email " "address; please try again.")) { QMessageBox::warning(this, tr("Invalid username"), tr("Account %1 is invalid; please try again.").arg(_user)); } reply->close(); reply->deleteLater(); return data; } void TarsnapAccount::networkError(QNetworkReply::NetworkError error) { Q_UNUSED(error) QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); DEBUG << reply->errorString(); } void TarsnapAccount::sslError(QList<QSslError> errors) { foreach(QSslError error, errors) { DEBUG << error.errorString(); } } <|endoftext|>
<commit_before>#include <iostream> #include "fetcher.hpp" #include "tcp_connection.hpp" boost::shared_ptr<tcp_connection> tcp_connection::create( asio::io_service &io_service, unsigned int depth_limit) { return boost::shared_ptr<tcp_connection>( new tcp_connection(io_service, depth_limit)); } asio::ip::tcp::socket &tcp_connection::get_socket() { return socket_; } void tcp_connection::start() { // Read the person's id uint32_t pid = read_uint(); // Read the other person's id uint32_t apid = read_uint(); // Get the current relations and calculate the path graph::graph_t relations = fetcher::get_instance()->get_relations(); searcher searcher(relations); boost::shared_ptr<graph::path_t> path = searcher.find_shortest_path( pid, apid, depth_limit_); uint32_t path_length = !path ? 0 : path->size(); // Write the path length write_uint(path_length); // Write the path for (uint32_t i = 0; i < path_length; i++) write_uint(path->at(i)); } tcp_connection::tcp_connection(asio::io_service &io_service, unsigned int depth_limit) : socket_(io_service) , depth_limit_(depth_limit) { } uint32_t tcp_connection::read_uint() { asio::error_code error; uint32_t uint; socket_.read_some(asio::buffer((void *) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); return uint; } void tcp_connection::write_uint(uint32_t uint) { asio::error_code error; socket_.write_some(asio::buffer((void *) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); } <commit_msg>Removed an obsolete include.<commit_after>#include "fetcher.hpp" #include "tcp_connection.hpp" boost::shared_ptr<tcp_connection> tcp_connection::create( asio::io_service &io_service, unsigned int depth_limit) { return boost::shared_ptr<tcp_connection>( new tcp_connection(io_service, depth_limit)); } asio::ip::tcp::socket &tcp_connection::get_socket() { return socket_; } void tcp_connection::start() { // Read the person's id uint32_t pid = read_uint(); // Read the other person's id uint32_t apid = read_uint(); // Get the current relations and calculate the path graph::graph_t relations = fetcher::get_instance()->get_relations(); searcher searcher(relations); boost::shared_ptr<graph::path_t> path = searcher.find_shortest_path( pid, apid, depth_limit_); uint32_t path_length = !path ? 0 : path->size(); // Write the path length write_uint(path_length); // Write the path for (uint32_t i = 0; i < path_length; i++) write_uint(path->at(i)); } tcp_connection::tcp_connection(asio::io_service &io_service, unsigned int depth_limit) : socket_(io_service) , depth_limit_(depth_limit) { } uint32_t tcp_connection::read_uint() { asio::error_code error; uint32_t uint; socket_.read_some(asio::buffer((void *) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); return uint; } void tcp_connection::write_uint(uint32_t uint) { asio::error_code error; socket_.write_some(asio::buffer((void *) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); } <|endoftext|>
<commit_before>#include "../include/base/CuteHMI.hpp" namespace cutehmi { namespace base { CuteHMI & CuteHMI::Instance() { return *(InstancePtr().get()); } void CuteHMI::Destroy() { InstancePtr().reset(); } Project * CuteHMI::project() const { return m->project.get(); } PopupBridge * CuteHMI::popupBridge() const { return m->popupBridge.get(); } NotificationManager * CuteHMI::notificationManager() const { return m->notificationManager.get(); } CuteHMI::CuteHMI(): m(new Members{ std::unique_ptr<Project>(new Project), std::unique_ptr<PopupBridge>(new PopupBridge), std::unique_ptr<NotificationManager>(new NotificationManager)}) { qRegisterMetaType<cutehmi::base::ErrorInfo>(); } std::unique_ptr<CuteHMI> & CuteHMI::InstancePtr() { static std::unique_ptr<CuteHMI> instance(new CuteHMI); return instance; } } } //(c)MP: Copyright © 2017, Michal Policht. All rights reserved. //(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. <commit_msg>Register "cutehmi::base::Prompt::button_t" in Qt meta-object system.<commit_after>#include "../include/base/CuteHMI.hpp" namespace cutehmi { namespace base { CuteHMI & CuteHMI::Instance() { return *(InstancePtr().get()); } void CuteHMI::Destroy() { InstancePtr().reset(); } Project * CuteHMI::project() const { return m->project.get(); } PopupBridge * CuteHMI::popupBridge() const { return m->popupBridge.get(); } NotificationManager * CuteHMI::notificationManager() const { return m->notificationManager.get(); } CuteHMI::CuteHMI(): m(new Members{ std::unique_ptr<Project>(new Project), std::unique_ptr<PopupBridge>(new PopupBridge), std::unique_ptr<NotificationManager>(new NotificationManager)}) { qRegisterMetaType<cutehmi::base::ErrorInfo>(); qRegisterMetaType<cutehmi::base::Prompt::button_t>(); } std::unique_ptr<CuteHMI> & CuteHMI::InstancePtr() { static std::unique_ptr<CuteHMI> instance(new CuteHMI); return instance; } } } //(c)MP: Copyright © 2017, Michal Policht. All rights reserved. //(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "docsumwriter.h" #include "docsumstate.h" #include "docsum_field_writer_state.h" #include <vespa/searchlib/common/transport.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/searchlib/attribute/iattributemanager.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.docsumwriter"); using namespace vespalib::slime::convenience; namespace search::docsummary { uint32_t IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf) { const uint32_t preUsed = buf.GetUsedLen(); const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID; buf.append(&magic, sizeof(magic)); SlimeOutputRawBufAdapter adapter(buf); vespalib::slime::BinaryFormat::encode(slime, adapter); return (buf.GetUsedLen() - preUsed); } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const { DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName); if (!rci.mustSkip && !rci.allGenerated) { resolveInputClass(rci, inputClassId); } return rci; } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const { DynamicDocsumWriter::ResolveClassInfo result; uint32_t id = _defaultOutputClass; id = _resultConfig->LookupResultClassId(summaryClass, id); if (id != ResultConfig::NoClassID()) { const ResultClass *oC = _resultConfig->LookupResultClass(id); if (oC == nullptr) { LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id); result.mustSkip = true; } else { result.outputClass = oC; const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo(); if (rcInfo->_generateCnt == oC->GetNumEntries()) { LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt); result.allGenerated = true; } result.outputClassInfo = rcInfo; } } result.outputClassId = id; return result; } void DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const { rci.inputClass = _resultConfig->LookupResultClass(id); if (rci.inputClass == nullptr) { rci.mustSkip = true; return; } if (rci.outputClass == nullptr) { LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID()); rci.outputClassId = id; rci.outputClass = rci.inputClass; rci.outputClassInfo = rci.inputClass->getDynamicInfo(); } } constexpr uint32_t default_32bits_int = (uint32_t)std::numeric_limits<int32_t>::min(); constexpr uint64_t default_64bits_int = (uint64_t)std::numeric_limits<int64_t>::min(); static void convertEntry(GetDocsumsState *state, const ResConfigEntry *resCfg, const ResEntry *entry, Inserter &inserter, Slime &slime) { using vespalib::slime::BinaryFormat; const char *ptr; uint32_t len; LOG_ASSERT(resCfg != nullptr && entry != nullptr); switch (resCfg->_type) { case RES_INT: case RES_SHORT: case RES_BYTE: if (entry->_intval != default_32bits_int) { inserter.insertLong(entry->_intval); } break; case RES_BOOL: inserter.insertBool(entry->_intval != 0); break; case RES_FLOAT: case RES_DOUBLE: if (! std::isnan(entry->_doubleval)) { inserter.insertDouble(entry->_doubleval); } break; case RES_INT64: if (entry->_int64val != default_64bits_int) { inserter.insertLong(entry->_int64val); } break; case RES_STRING: case RES_LONG_STRING: case RES_FEATUREDATA: case RES_XMLSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { inserter.insertString(Memory(ptr, len)); } break; case RES_DATA: case RES_TENSOR: case RES_LONG_DATA: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { inserter.insertData(Memory(ptr, len)); } break; case RES_JSONSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { // note: 'JSONSTRING' really means 'structured data' size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter); if (d != len) { LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d); } } break; } } void DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter) { if (rci.allGenerated) { // generate docsum entry on-the-fly vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue]; if (! writer->isDefaultValue(docid, state)) { const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); writer->insertField(docid, nullptr, state, resCfg->_type, inserter); } } } else { // look up docsum entry DocsumStoreValue value = docinfos->getMappedDocsum(docid); // re-pack docsum blob GeneralResult gres(rci.inputClass); if (! gres.inplaceUnpack(value)) { LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid); topInserter.insertNix(); return; } vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue]; const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); if (writer != nullptr) { if (! writer->isDefaultValue(docid, state)) { writer->insertField(docid, &gres, state, outCfg->_type, inserter); } } else { if (rci.inputClass == rci.outputClass) { convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime); } else { int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue); const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx); if (inCfg != nullptr && inCfg->_type == outCfg->_type) { // copy field const ResEntry *entry = gres.GetEntry(inIdx); LOG_ASSERT(entry != nullptr); convertEntry(state, outCfg, entry, inserter, slime); } } } } } } DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor) : _resultConfig(config), _keywordExtractor(extractor), _defaultOutputClass(ResultConfig::NoClassID()), _numClasses(config->GetNumResultClasses()), _numEnumValues(config->GetFieldNameEnum().GetNumEntries()), _numFieldWriterStates(0), _classInfoTable(nullptr), _overrideTable(nullptr) { LOG_ASSERT(config != nullptr); _classInfoTable = new ResultClass::DynamicInfo[_numClasses]; _overrideTable = new IDocsumFieldWriter*[_numEnumValues]; uint32_t i = 0; for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) { _classInfoTable[i]._overrideCnt = 0; _classInfoTable[i]._generateCnt = 0; it->setDynamicInfo(&(_classInfoTable[i])); } LOG_ASSERT(i == _numClasses); for (i = 0; i < _numEnumValues; i++) _overrideTable[i] = nullptr; } DynamicDocsumWriter::~DynamicDocsumWriter() { delete _resultConfig; delete _keywordExtractor; delete [] _classInfoTable; for (uint32_t i = 0; i < _numEnumValues; i++) delete _overrideTable[i]; delete [] _overrideTable; } bool DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID) { const ResultClass *resClass = _resultConfig->LookupResultClass(classID); if (resClass == nullptr || _defaultOutputClass != ResultConfig::NoClassID()) { if (resClass == nullptr) { LOG(warning, "cannot set default output docsum class to %d; class not defined", classID); } else if (_defaultOutputClass != ResultConfig::NoClassID()) { LOG(warning, "cannot set default output docsum class to %d; value already set", classID); } return false; } _defaultOutputClass = classID; return true; } bool DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer) { uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName); if (fieldEnumValue >= _numEnumValues || _overrideTable[fieldEnumValue] != nullptr) { if (fieldEnumValue >= _numEnumValues) { LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName); } else if (_overrideTable[fieldEnumValue] != nullptr) { LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName); } delete writer; return false; } writer->setIndex(fieldEnumValue); _overrideTable[fieldEnumValue] = writer; if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) { ++_numFieldWriterStates; } for (auto & entry : *_resultConfig) { if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) { ResultClass::DynamicInfo *info = entry.getDynamicInfo(); info->_overrideCnt++; if (writer->IsGenerated()) info->_generateCnt++; } } return true; } void DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state) { state->_kwExtractor = _keywordExtractor; state->_attrCtx = attrMan.createContext(); state->_attributes.resize(_numEnumValues); state->_fieldWriterStates.resize(_numFieldWriterStates); for (size_t i(0); i < state->_attributes.size(); i++) { const IDocsumFieldWriter *fw = _overrideTable[i]; if (fw) { const vespalib::string & attributeName = fw->getAttributeName(); if (!attributeName.empty()) { state->_attributes[i] = state->_attrCtx->getAttribute(attributeName); } } } } uint32_t DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target) { vespalib::Slime slime; vespalib::slime::SlimeInserter inserter(slime); ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId()); insertDocsum(rci, docid, state, docinfos, slime, inserter); return slime2RawBuf(slime, *target); } } <commit_msg>Revert "skip fields which are empty or only have the default value"<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "docsumwriter.h" #include "docsumstate.h" #include "docsum_field_writer_state.h" #include <vespa/searchlib/common/transport.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/searchlib/attribute/iattributemanager.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.docsumwriter"); using namespace vespalib::slime::convenience; namespace search::docsummary { uint32_t IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf) { const uint32_t preUsed = buf.GetUsedLen(); const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID; buf.append(&magic, sizeof(magic)); SlimeOutputRawBufAdapter adapter(buf); vespalib::slime::BinaryFormat::encode(slime, adapter); return (buf.GetUsedLen() - preUsed); } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const { DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName); if (!rci.mustSkip && !rci.allGenerated) { resolveInputClass(rci, inputClassId); } return rci; } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const { DynamicDocsumWriter::ResolveClassInfo result; uint32_t id = _defaultOutputClass; id = _resultConfig->LookupResultClassId(summaryClass, id); if (id != ResultConfig::NoClassID()) { const ResultClass *oC = _resultConfig->LookupResultClass(id); if (oC == nullptr) { LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id); result.mustSkip = true; } else { result.outputClass = oC; const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo(); if (rcInfo->_generateCnt == oC->GetNumEntries()) { LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt); result.allGenerated = true; } result.outputClassInfo = rcInfo; } } result.outputClassId = id; return result; } void DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const { rci.inputClass = _resultConfig->LookupResultClass(id); if (rci.inputClass == nullptr) { rci.mustSkip = true; return; } if (rci.outputClass == nullptr) { LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID()); rci.outputClassId = id; rci.outputClass = rci.inputClass; rci.outputClassInfo = rci.inputClass->getDynamicInfo(); } } static void convertEntry(GetDocsumsState *state, const ResConfigEntry *resCfg, const ResEntry *entry, Inserter &inserter, Slime &slime) { using vespalib::slime::BinaryFormat; const char *ptr; uint32_t len; LOG_ASSERT(resCfg != nullptr && entry != nullptr); switch (resCfg->_type) { case RES_INT: case RES_SHORT: case RES_BYTE: inserter.insertLong(entry->_intval); break; case RES_BOOL: inserter.insertBool(entry->_intval != 0); break; case RES_FLOAT: case RES_DOUBLE: inserter.insertDouble(entry->_doubleval); break; case RES_INT64: inserter.insertLong(entry->_int64val); break; case RES_STRING: case RES_LONG_STRING: case RES_FEATUREDATA: case RES_XMLSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); inserter.insertString(Memory(ptr, len)); break; case RES_DATA: case RES_TENSOR: case RES_LONG_DATA: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); inserter.insertData(Memory(ptr, len)); break; case RES_JSONSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { // note: 'JSONSTRING' really means 'structured data' size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter); if (d != len) { LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d); } } break; } } void DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter) { if (rci.allGenerated) { // generate docsum entry on-the-fly vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue]; if (! writer->isDefaultValue(docid, state)) { const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); writer->insertField(docid, nullptr, state, resCfg->_type, inserter); } } } else { // look up docsum entry DocsumStoreValue value = docinfos->getMappedDocsum(docid); // re-pack docsum blob GeneralResult gres(rci.inputClass); if (! gres.inplaceUnpack(value)) { LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid); topInserter.insertNix(); return; } vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue]; const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); if (writer != nullptr) { //TODO: Need to add test for writer->isDefaultValue writer->insertField(docid, &gres, state, outCfg->_type, inserter); } else { //TODO: Need to add similar test as writer->isDefaultValue if (rci.inputClass == rci.outputClass) { convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime); } else { int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue); const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx); if (inCfg != nullptr && inCfg->_type == outCfg->_type) { // copy field const ResEntry *entry = gres.GetEntry(inIdx); LOG_ASSERT(entry != nullptr); convertEntry(state, outCfg, entry, inserter, slime); } } } } } } DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor) : _resultConfig(config), _keywordExtractor(extractor), _defaultOutputClass(ResultConfig::NoClassID()), _numClasses(config->GetNumResultClasses()), _numEnumValues(config->GetFieldNameEnum().GetNumEntries()), _numFieldWriterStates(0), _classInfoTable(nullptr), _overrideTable(nullptr) { LOG_ASSERT(config != nullptr); _classInfoTable = new ResultClass::DynamicInfo[_numClasses]; _overrideTable = new IDocsumFieldWriter*[_numEnumValues]; uint32_t i = 0; for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) { _classInfoTable[i]._overrideCnt = 0; _classInfoTable[i]._generateCnt = 0; it->setDynamicInfo(&(_classInfoTable[i])); } LOG_ASSERT(i == _numClasses); for (i = 0; i < _numEnumValues; i++) _overrideTable[i] = nullptr; } DynamicDocsumWriter::~DynamicDocsumWriter() { delete _resultConfig; delete _keywordExtractor; delete [] _classInfoTable; for (uint32_t i = 0; i < _numEnumValues; i++) delete _overrideTable[i]; delete [] _overrideTable; } bool DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID) { const ResultClass *resClass = _resultConfig->LookupResultClass(classID); if (resClass == nullptr || _defaultOutputClass != ResultConfig::NoClassID()) { if (resClass == nullptr) { LOG(warning, "cannot set default output docsum class to %d; class not defined", classID); } else if (_defaultOutputClass != ResultConfig::NoClassID()) { LOG(warning, "cannot set default output docsum class to %d; value already set", classID); } return false; } _defaultOutputClass = classID; return true; } bool DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer) { uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName); if (fieldEnumValue >= _numEnumValues || _overrideTable[fieldEnumValue] != nullptr) { if (fieldEnumValue >= _numEnumValues) { LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName); } else if (_overrideTable[fieldEnumValue] != nullptr) { LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName); } delete writer; return false; } writer->setIndex(fieldEnumValue); _overrideTable[fieldEnumValue] = writer; if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) { ++_numFieldWriterStates; } for (auto & entry : *_resultConfig) { if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) { ResultClass::DynamicInfo *info = entry.getDynamicInfo(); info->_overrideCnt++; if (writer->IsGenerated()) info->_generateCnt++; } } return true; } void DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state) { state->_kwExtractor = _keywordExtractor; state->_attrCtx = attrMan.createContext(); state->_attributes.resize(_numEnumValues); state->_fieldWriterStates.resize(_numFieldWriterStates); for (size_t i(0); i < state->_attributes.size(); i++) { const IDocsumFieldWriter *fw = _overrideTable[i]; if (fw) { const vespalib::string & attributeName = fw->getAttributeName(); if (!attributeName.empty()) { state->_attributes[i] = state->_attrCtx->getAttribute(attributeName); } } } } uint32_t DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target) { vespalib::Slime slime; vespalib::slime::SlimeInserter inserter(slime); ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId()); insertDocsum(rci, docid, state, docinfos, slime, inserter); return slime2RawBuf(slime, *target); } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: runReconstruction.C 23207 2007-12-20 09:59:20Z ivana $ */ /// \ingroup macros /// \file runDataReconstruction.C /// \brief Macro for running reconstruction /// /// Macro for running reconstruction on the cosmics run data. /// /// \author Laurent Aphecetche, Nicole Bastid, Bogdan Vulpescu, ... #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliReconstruction.h" #include <TGrid.h> #include <TSystem.h> #endif void runDataReconstruction(const char* input = "raw://run124360", const char* ocdbPath = "raw://", const char* recoptions="SAVEDIGITS", Int_t numberOfEvents=1000) { AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(ocdbPath); AliReconstruction rec; rec.SetRunReconstruction("MUON"); rec.SetRunQA("MUON:ALL"); rec.SetQARefDefaultStorage("local://$ALICE_ROOT/QAref") ; rec.SetWriteESDfriend(kTRUE); rec.SetWriteAlignmentData(); rec.SetInput(gSystem->ExpandPathName(input)); rec.SetUseTrackingErrorsForAlignment("ITS"); rec.SetCleanESD(kFALSE); rec.SetStopOnError(kFALSE); rec.SetNumberOfEventsPerFile(500); // must set a limit otherwise time per event increases with event number (this is a "bug" of the loaders) rec.SetOption("MUON",recoptions); rec.SetQAWriteExpert(AliQAv1::kMUON); if ( numberOfEvents > 0 ) { rec.SetEventRange(0,numberOfEvents); } AliLog::Flush(); rec.Run(); } <commit_msg>Remove SetNumberOfEventsPerFile which is a priori no longer needed<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: runReconstruction.C 23207 2007-12-20 09:59:20Z ivana $ */ /// \ingroup macros /// \file runDataReconstruction.C /// \brief Macro for running reconstruction /// /// Macro for running reconstruction on the cosmics run data. /// /// \author Laurent Aphecetche, Nicole Bastid, Bogdan Vulpescu, ... #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliReconstruction.h" #include <TGrid.h> #include <TSystem.h> #endif void runDataReconstruction(const char* input = "raw://run124360", const char* ocdbPath = "raw://", const char* recoptions="SAVEDIGITS", Int_t numberOfEvents=1000) { AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(ocdbPath); AliReconstruction rec; rec.SetRunReconstruction("MUON"); rec.SetRunQA("MUON:ALL"); rec.SetQARefDefaultStorage("local://$ALICE_ROOT/QAref") ; rec.SetWriteESDfriend(kTRUE); rec.SetWriteAlignmentData(); rec.SetInput(gSystem->ExpandPathName(input)); rec.SetUseTrackingErrorsForAlignment("ITS"); rec.SetCleanESD(kFALSE); rec.SetStopOnError(kFALSE); rec.SetOption("MUON",recoptions); rec.SetQAWriteExpert(AliQAv1::kMUON); if ( numberOfEvents > 0 ) { rec.SetEventRange(0,numberOfEvents); } AliLog::Flush(); rec.Run(); } <|endoftext|>
<commit_before>#ifndef POSE_STORE_GUI_UTILS_HPP #define POSE_STORE_GUI_UTILS_HPP #define PARAM_STORE "Store" #define PARAM_CLEAR "Clear old" #define PARAM_POSE_NAME "Name:" #include "renderer_robot_state.hpp" using namespace std; using namespace boost; using namespace renderer_robot_state; namespace renderer_robot_state_gui_utils { static void on_afftriggered_popup_close (BotGtkParamWidget *pw, void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; self->afftriggered_popup = NULL; } static void on_pose_storage_popup_param_widget_changed(BotGtkParamWidget *pw, const char *name,void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; std::string otdf_models_path = std::string(getModelsPath()) + "/otdf/"; std::string otdf_filepath,pose_xml_dirpath; otdf_filepath = otdf_models_path + (*self->trigger_source_otdf_id) +".otdf"; pose_xml_dirpath = otdf_models_path + "stored_poses/"; if ((!strcmp(name, PARAM_STORE))) { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer,80,"%Y-%m-%d-%H-%M::",timeinfo); std::string timestamp_str = buffer; std::string pose_name = bot_gtk_param_widget_get_text_entry(pw,PARAM_POSE_NAME); PoseSeed poseSeed; //pose_ref needs to be unique timestamp::Name. poseSeed.pose_ref = timestamp_str+pose_name; if(self->robotStateListener->_gl_robot->is_future_display_active()) { //type = "endpose"; visualization_utils::prepareEndPoseForStorage(self->T_world_trigger_aff, self->robotStateListener->_received_endpose, poseSeed.stateframe_ids, poseSeed.stateframe_values); /* self->robotStateListener->prepareDesiredRobotStateForEndPoseStorage(self->T_world_trigger_aff, poseSeed.pose_type, poseSeed.stateframe_ids, poseSeed.stateframe_values, poseSeed.graspframe_ids, poseSeed.graspframe_values);*/ std::cout << poseSeed.pose_ref << std::endl; poseSeed.writePoseToXMLFile((*self->trigger_source_otdf_id),pose_xml_dirpath); // cross ref in OTDF poseSeed.writeToOtdf(otdf_filepath); } else cout <<"No Active Plan To Store \n"; } /* else if ((!strcmp(name, PARAM_UNSTORE))) { } else if ((!strcmp(name, PARAM_CLEAR))) { PoseSeed poseSeed; poseSeed.clearAllFromOtdf(otdf_filepath,pose_xml_dirpath); }*/ gtk_widget_destroy(self->afftriggered_popup); } static void spawn_endpose_storage_addition_popup (void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; GtkWidget *window, *close_button, *vbox; BotGtkParamWidget *pw; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(self->viewer->window)); gtk_window_set_modal(GTK_WINDOW(window), FALSE); gtk_window_set_decorated (GTK_WINDOW(window),FALSE); gtk_window_stick(GTK_WINDOW(window)); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_MOUSE);//GTK_WIN_POS_CENTER/MOUSE gtk_window_set_default_size(GTK_WINDOW(window), 150, 50); gint pos_x, pos_y; gtk_window_get_position(GTK_WINDOW(window),&pos_x,&pos_y); pos_x+=0; pos_y-=0; gtk_window_move(GTK_WINDOW(window),pos_x,pos_y); gtk_window_set_title(GTK_WINDOW(window), "store pose"); gtk_container_set_border_width(GTK_CONTAINER(window), 5); pw = BOT_GTK_PARAM_WIDGET(bot_gtk_param_widget_new()); std::stringstream oss; oss << bot_timestamp_now(); std::string t_str = oss.str(); bot_gtk_param_widget_add_text_entry(pw,PARAM_POSE_NAME,BOT_GTK_PARAM_WIDGET_ENTRY,""); bot_gtk_param_widget_add_buttons(pw,PARAM_STORE,NULL); //bot_gtk_param_widget_add_buttons(pw,PARAM_CLEAR,NULL); g_signal_connect(G_OBJECT(pw), "changed", G_CALLBACK(on_pose_storage_popup_param_widget_changed), self); self->afftriggered_popup = window; close_button = gtk_button_new_with_label ("Close"); g_signal_connect (G_OBJECT (close_button),"clicked",G_CALLBACK (on_popup_close),(gpointer) window); g_signal_connect(G_OBJECT(pw), "destroy", G_CALLBACK(on_afftriggered_popup_close), self); vbox = gtk_vbox_new (FALSE, 3); gtk_box_pack_end (GTK_BOX (vbox), close_button, FALSE, FALSE, 5); gtk_box_pack_start (GTK_BOX (vbox), GTK_WIDGET(pw), FALSE, FALSE, 5); gtk_container_add (GTK_CONTAINER (window), vbox); gtk_widget_show_all(window); } } #endif <commit_msg>can store current state as a endpose seed<commit_after>#ifndef POSE_STORE_GUI_UTILS_HPP #define POSE_STORE_GUI_UTILS_HPP #define PARAM_STORE "Store" #define PARAM_CLEAR "Clear old" #define PARAM_POSE_NAME "Name:" #include "renderer_robot_state.hpp" using namespace std; using namespace boost; using namespace renderer_robot_state; namespace renderer_robot_state_gui_utils { static void on_afftriggered_popup_close (BotGtkParamWidget *pw, void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; self->afftriggered_popup = NULL; } static void on_pose_storage_popup_param_widget_changed(BotGtkParamWidget *pw, const char *name,void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; std::string otdf_models_path = std::string(getModelsPath()) + "/otdf/"; std::string otdf_filepath,pose_xml_dirpath; otdf_filepath = otdf_models_path + (*self->trigger_source_otdf_id) +".otdf"; pose_xml_dirpath = otdf_models_path + "stored_poses/"; if ((!strcmp(name, PARAM_STORE))) { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer,80,"%Y-%m-%d-%H-%M::",timeinfo); std::string timestamp_str = buffer; std::string pose_name = bot_gtk_param_widget_get_text_entry(pw,PARAM_POSE_NAME); PoseSeed poseSeed; //pose_ref needs to be unique timestamp::Name. poseSeed.pose_ref = timestamp_str+pose_name; if(self->robotStateListener->_gl_robot->is_future_display_active()) { //type = "endpose"; drc::robot_state_t endpose_msg; self->robotStateListener->_gl_robot->get_future_state_as_lcm_msg(endpose_msg); //endpose_msg = self->robotStateListener->_received_endpose; visualization_utils::prepareEndPoseForStorage(self->T_world_trigger_aff, endpose_msg, poseSeed.stateframe_ids, poseSeed.stateframe_values); std::cout << poseSeed.pose_ref << std::endl; poseSeed.writePoseToXMLFile((*self->trigger_source_otdf_id),pose_xml_dirpath); // cross ref in OTDF poseSeed.writeToOtdf(otdf_filepath); } else { cout <<"No Active endpose To Store, storing current robot state \n"; drc::robot_state_t endpose_msg; self->robotStateListener->_gl_robot->get_state_as_lcm_msg(endpose_msg); visualization_utils::prepareEndPoseForStorage(self->T_world_trigger_aff, endpose_msg, poseSeed.stateframe_ids, poseSeed.stateframe_values); std::cout << poseSeed.pose_ref << std::endl; poseSeed.writePoseToXMLFile((*self->trigger_source_otdf_id),pose_xml_dirpath); // cross ref in OTDF poseSeed.writeToOtdf(otdf_filepath); } } /* else if ((!strcmp(name, PARAM_UNSTORE))) { } else if ((!strcmp(name, PARAM_CLEAR))) { PoseSeed poseSeed; poseSeed.clearAllFromOtdf(otdf_filepath,pose_xml_dirpath); }*/ gtk_widget_destroy(self->afftriggered_popup); } static void spawn_endpose_storage_addition_popup (void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; GtkWidget *window, *close_button, *vbox; BotGtkParamWidget *pw; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(self->viewer->window)); gtk_window_set_modal(GTK_WINDOW(window), FALSE); gtk_window_set_decorated (GTK_WINDOW(window),FALSE); gtk_window_stick(GTK_WINDOW(window)); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_MOUSE);//GTK_WIN_POS_CENTER/MOUSE gtk_window_set_default_size(GTK_WINDOW(window), 150, 50); gint pos_x, pos_y; gtk_window_get_position(GTK_WINDOW(window),&pos_x,&pos_y); pos_x+=0; pos_y-=0; gtk_window_move(GTK_WINDOW(window),pos_x,pos_y); gtk_window_set_title(GTK_WINDOW(window), "store pose"); gtk_container_set_border_width(GTK_CONTAINER(window), 5); pw = BOT_GTK_PARAM_WIDGET(bot_gtk_param_widget_new()); std::stringstream oss; oss << bot_timestamp_now(); std::string t_str = oss.str(); bot_gtk_param_widget_add_text_entry(pw,PARAM_POSE_NAME,BOT_GTK_PARAM_WIDGET_ENTRY,""); bot_gtk_param_widget_add_buttons(pw,PARAM_STORE,NULL); //bot_gtk_param_widget_add_buttons(pw,PARAM_CLEAR,NULL); g_signal_connect(G_OBJECT(pw), "changed", G_CALLBACK(on_pose_storage_popup_param_widget_changed), self); self->afftriggered_popup = window; close_button = gtk_button_new_with_label ("Close"); g_signal_connect (G_OBJECT (close_button),"clicked",G_CALLBACK (on_popup_close),(gpointer) window); g_signal_connect(G_OBJECT(pw), "destroy", G_CALLBACK(on_afftriggered_popup_close), self); vbox = gtk_vbox_new (FALSE, 3); gtk_box_pack_end (GTK_BOX (vbox), close_button, FALSE, FALSE, 5); gtk_box_pack_start (GTK_BOX (vbox), GTK_WIDGET(pw), FALSE, FALSE, 5); gtk_container_add (GTK_CONTAINER (window), vbox); gtk_widget_show_all(window); } } #endif <|endoftext|>
<commit_before>namespace mant { namespace robotic { class ParallelKinematicMachine3PUPS { public: inline explicit ParallelKinematicMachine3PUPS() noexcept; inline arma::Row<double>::fixed<3> getMinimalActiveJointActuations() const noexcept; inline void setMinimalActiveJointActuations( const arma::Row<double>::fixed<3>& minimalActiveJointActuations) noexcept; inline arma::Row<double>::fixed<3> getMaximalActiveJointActuations() const noexcept; inline void setMaximalActiveJointActuations( const arma::Row<double>::fixed<3>& maximalActiveJointActuations) noexcept; inline std::vector<arma::Mat<double>> getModelCharacterisation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const; inline arma::Mat<double>::fixed<3, 3> getEndEffectorJointPositions() const noexcept; inline arma::Mat<double> getActuation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const; inline void setEndEffectorJointPositions( const arma::Mat<double>::fixed<3, 3>& endEffectorJointPositions) noexcept; inline double getPositionError( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const; inline arma::Mat<double>::fixed<3, 3> getRedundantJointStartPositions() const noexcept; protected: arma::Mat<double>::fixed<3, 3> endEffectorJointsRelative_; inline void setRedundantJointStartPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointStartPositions) noexcept; inline arma::Mat<double>::fixed<3, 3> getRedundantJointEndPositions() const noexcept; arma::Mat<double>::fixed<3, 3> redundantJointStarts_; arma::Mat<double>::fixed<3, 3> redundantJointEnds_; inline void setRedundantJointEndPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointEndPositions) noexcept; arma::Row<double>::fixed<3> minimalActiveJointActuations_; arma::Row<double>::fixed<3> maximalActiveJointActuations_; arma::Mat<double>::fixed<3, 3> redundantJointsStartToEnd_; arma::Col<unsigned int> redundantJointIndicies_; arma::Mat<double> redundantJointAngles_; }; // // Implementation // inline ParallelKinematicMachine3PUPS::ParallelKinematicMachine3PUPS() noexcept { setMinimalActiveJointActuations({0.39, 0.39, 0.39}); setMaximalActiveJointActuations({0.95, 0.95, 0.95}); setEndEffectorJointPositions({ -0.025561381023353, 0.086293776138137, 0.12, 0.087513292835791, -0.021010082747031, 0.12, -0.061951911812438, -0.065283693391106, 0.12}); setRedundantJointStartPositions({ -0.463708870031622, 0.417029254828353, -0.346410161513775, 0.593012363818459, 0.193069033993384, -0.346410161513775, -0.129303493786837, -0.610098288821738, -0.346410161513775}); setRedundantJointEndPositions({ -0.247202519085512, 0.292029254828353, 0.086602540378444, 0.376506012872349, 0.068069033993384, 0.086602540378444, -0.129303493786837, -0.360098288821738, 0.086602540378444}); redundantJointStartToEndPositions_ = redundantJointEndPositions_ - redundantJointStartPositions_; redundantJointIndicies_ = arma::find(arma::any(redundantJointStartToEndPositions_)); redundantJointAngles_.set_size(3, redundantJointIndicies_.n_elem); for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) { const double& redundantJointXAngle = std::atan2(redundantJointsStartToEnd_.at(1, n), redundantJointsStartToEnd_.at(0, n)); const double& redundantJointYAngle = std::atan2(redundantJointsStartToEnd_.at(2, n), redundantJointsStartToEnd_.at(1, n)); redundantJointAngles_.col(n) = arma::Col<double>::fixed<3>({std::cos(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointYAngle)}); } } inline std::vector<arma::Mat<double>> ParallelKinematicMachine3PUPS::getModelCharacterisation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const { std::vector<arma::Mat<double>> modelCharacterisation; inline arma::Row<double>::fixed<3> ParallelKinematicMachine3PUPS::getMinimalActiveJointActuations() const noexcept { return minimalActiveJointActuations_; } inline void ParallelKinematicMachine3PUPS::setMinimalActiveJointActuations( const arma::Row<double>::fixed<3>& minimalActiveJointActuations) noexcept { minimalActiveJointActuations_ = minimalActiveJointActuations; } inline arma::Row<double>::fixed<3> ParallelKinematicMachine3PUPS::getMaximalActiveJointActuations() const noexcept { return maximalActiveJointActuations_; } inline void ParallelKinematicMachine3PUPS::setMaximalActiveJointActuations( const arma::Row<double>::fixed<3>& maximalActiveJointActuations) noexcept { maximalActiveJointActuations_ = maximalActiveJointActuations; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getEndEffectorJointPositions() const noexcept { return endEffectorJointPositions_; } inline void ParallelKinematicMachine3PUPS::setEndEffectorJointPositions( const arma::Mat<double>::fixed<3, 3>& endEffectorJointPositions) noexcept { endEffectorJointPositions_ = endEffectorJointPositions; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getRedundantJointStartPositions() const noexcept { return redundantJointStartPositions_; } inline void ParallelKinematicMachine3PUPS::setRedundantJointStartPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointStartPositions) noexcept { redundantJointStartPositions_ = redundantJointStartPositions; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getRedundantJointEndPositions() const noexcept { return redundantJointEndPositions_; } inline void ParallelKinematicMachine3PUPS::setRedundantJointEndPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointEndPositions) noexcept { redundantJointEndPositions_ = redundantJointEndPositions; } if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) { throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1]."); } // TODO Check number of redundantJointActuations vs redudantant elements const arma::Col<double>::fixed<3>& endEffectorPosition = endEffectorPose.subvec(0, 2); const double& endEffectorRollAngle = endEffectorPose.at(3); const double& endEffectorPitchAngle = endEffectorPose.at(4); const double& endEffectorYawAngle = endEffectorPose.at(5); arma::Mat<double>::fixed<3, 3> baseJoints = redundantJointStarts_; for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) { const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n); baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointsStartToEnd_.col(redundantJointIndex); } arma::Mat<double>::fixed<3, 3> endEffectorJoints = get3DRotationMatrix(endEffectorRollAngle, endEffectorPitchAngle, endEffectorYawAngle) * endEffectorJointsRelative_; endEffectorJoints.each_col() += endEffectorPosition; modelCharacterisation.push_back(baseJoints); modelCharacterisation.push_back(endEffectorJoints); return modelCharacterisation; } inline arma::Mat<double> ParallelKinematicMachine3PUPS::getActuation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const { const std::vector<arma::Mat<double>>& modelCharacterisation = getModelCharacterisation(endEffectorPose, redundantJointActuations); const arma::Mat<double>::fixed<3, 3>& baseJoints = modelCharacterisation.at(0); const arma::Mat<double>::fixed<3, 3>& endEffectorJoints = modelCharacterisation.at(1); return arma::sqrt(arma::sum(arma::square(endEffectorJoints - baseJoints))); } inline double ParallelKinematicMachine3PUPS::getPositionError( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const { const std::vector<arma::Mat<double>>& modelCharacterisation = getModelCharacterisation(endEffectorPose, redundantJointActuations); const arma::Mat<double>::fixed<3, 3>& baseJoints = modelCharacterisation.at(1); const arma::Mat<double>::fixed<3, 3>& endEffectorJoints = modelCharacterisation.at(1); arma::Mat<double>::fixed<3, 3> endEffectorJointsRotated = endEffectorJoints; endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1); const arma::Mat<double>::fixed<3, 3>& baseToEndEffectorJointPositions = endEffectorJoints - baseJoints; const arma::Row<double>::fixed<3>& baseToEndEffectorJointActuations = arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions))); if (arma::any(baseToEndEffectorJointActuations < minimalActiveJointActuations_) || arma::any(baseToEndEffectorJointActuations > maximalActiveJointActuations_)) { return 0.0; } arma::Mat<double>::fixed<6, 3> forwardKinematic; forwardKinematic.rows(0, 2) = baseToEndEffectorJointPositions; for (std::size_t n = 0; n < baseToEndEffectorJointPositions.n_cols; ++n) { forwardKinematic.submat(3, n, 5, n) = arma::cross(endEffectorJointsRotated.col(n), baseToEndEffectorJointPositions.col(n)); } arma::Mat<double> inverseKinematic(6, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros); inverseKinematic.diag() = -arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions))); for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) { const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n); inverseKinematic.at(n, 3 + n) = arma::dot(baseToEndEffectorJointPositions.col(redundantJointIndex), redundantJointAngles_.col(redundantJointIndex)); } return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic)); } } } <commit_msg>devel: Renamed some API and fixed matrix/vector size<commit_after>namespace mant { namespace robotic { class ParallelKinematicMachine3PUPS { public: inline explicit ParallelKinematicMachine3PUPS() noexcept; inline arma::Row<double>::fixed<3> getMinimalActiveJointActuations() const noexcept; inline void setMinimalActiveJointActuations( const arma::Row<double>::fixed<3>& minimalActiveJointActuations) noexcept; inline arma::Row<double>::fixed<3> getMaximalActiveJointActuations() const noexcept; inline void setMaximalActiveJointActuations( const arma::Row<double>::fixed<3>& maximalActiveJointActuations) noexcept; inline arma::Mat<double>::fixed<3, 3> getEndEffectorJointPositions() const noexcept; inline void setEndEffectorJointPositions( const arma::Mat<double>::fixed<3, 3>& endEffectorJointPositions) noexcept; inline arma::Mat<double>::fixed<3, 3> getRedundantJointStartPositions() const noexcept; arma::Mat<double>::fixed<3, 3> endEffectorJointsRelative_; inline void setRedundantJointStartPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointStartPositions) noexcept; inline arma::Mat<double>::fixed<3, 3> getRedundantJointEndPositions() const noexcept; arma::Mat<double>::fixed<3, 3> redundantJointStarts_; arma::Mat<double>::fixed<3, 3> redundantJointEnds_; inline void setRedundantJointEndPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointEndPositions) noexcept; inline std::vector<arma::Mat<double>::fixed<3, 3>> getModel( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const; inline arma::Row<double>::fixed<3> getActuation( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const; inline arma::Col<double>::fixed<6> getEndEffectorPose( const arma::Row<double>::fixed<3>& actuations, const arma::Row<double>& redundantJointActuations) const; inline double getEndEffectorPoseAccuracy( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const; protected: arma::Row<double>::fixed<3> minimalActiveJointActuations_; arma::Row<double>::fixed<3> maximalActiveJointActuations_; arma::Mat<double>::fixed<3, 3> redundantJointsStartToEnd_; arma::Col<unsigned int> redundantJointIndicies_; arma::Mat<double> redundantJointAngles_; }; // // Implementation // inline ParallelKinematicMachine3PUPS::ParallelKinematicMachine3PUPS() noexcept { setMinimalActiveJointActuations({0.39, 0.39, 0.39}); setMaximalActiveJointActuations({0.95, 0.95, 0.95}); setEndEffectorJointPositions({ -0.025561381023353, 0.086293776138137, 0.12, 0.087513292835791, -0.021010082747031, 0.12, -0.061951911812438, -0.065283693391106, 0.12}); setRedundantJointStartPositions({ -0.463708870031622, 0.417029254828353, -0.346410161513775, 0.593012363818459, 0.193069033993384, -0.346410161513775, -0.129303493786837, -0.610098288821738, -0.346410161513775}); setRedundantJointEndPositions({ -0.247202519085512, 0.292029254828353, 0.086602540378444, 0.376506012872349, 0.068069033993384, 0.086602540378444, -0.129303493786837, -0.360098288821738, 0.086602540378444}); redundantJointStartToEndPositions_ = redundantJointEndPositions_ - redundantJointStartPositions_; redundantJointIndicies_ = arma::find(arma::any(redundantJointStartToEndPositions_)); redundantJointAngles_.set_size(3, redundantJointIndicies_.n_elem); for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) { const double& redundantJointXAngle = std::atan2(redundantJointsStartToEnd_.at(1, n), redundantJointsStartToEnd_.at(0, n)); const double& redundantJointYAngle = std::atan2(redundantJointsStartToEnd_.at(2, n), redundantJointsStartToEnd_.at(1, n)); redundantJointAngles_.col(n) = arma::Col<double>::fixed<3>({std::cos(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointXAngle) * std::cos(redundantJointYAngle), std::sin(redundantJointYAngle)}); } } inline arma::Row<double>::fixed<3> ParallelKinematicMachine3PUPS::getMinimalActiveJointActuations() const noexcept { return minimalActiveJointActuations_; } inline void ParallelKinematicMachine3PUPS::setMinimalActiveJointActuations( const arma::Row<double>::fixed<3>& minimalActiveJointActuations) noexcept { minimalActiveJointActuations_ = minimalActiveJointActuations; } inline arma::Row<double>::fixed<3> ParallelKinematicMachine3PUPS::getMaximalActiveJointActuations() const noexcept { return maximalActiveJointActuations_; } inline void ParallelKinematicMachine3PUPS::setMaximalActiveJointActuations( const arma::Row<double>::fixed<3>& maximalActiveJointActuations) noexcept { maximalActiveJointActuations_ = maximalActiveJointActuations; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getEndEffectorJointPositions() const noexcept { return endEffectorJointPositions_; } inline void ParallelKinematicMachine3PUPS::setEndEffectorJointPositions( const arma::Mat<double>::fixed<3, 3>& endEffectorJointPositions) noexcept { endEffectorJointPositions_ = endEffectorJointPositions; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getRedundantJointStartPositions() const noexcept { return redundantJointStartPositions_; } inline void ParallelKinematicMachine3PUPS::setRedundantJointStartPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointStartPositions) noexcept { redundantJointStartPositions_ = redundantJointStartPositions; } inline arma::Mat<double>::fixed<3, 3> ParallelKinematicMachine3PUPS::getRedundantJointEndPositions() const noexcept { return redundantJointEndPositions_; } inline void ParallelKinematicMachine3PUPS::setRedundantJointEndPositions( const arma::Mat<double>::fixed<3, 3>& redundantJointEndPositions) noexcept { redundantJointEndPositions_ = redundantJointEndPositions; } inline std::vector<arma::Mat<double>::fixed<3, 3>> ParallelKinematicMachine3PUPS::getModel( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const { if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) { throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1]."); } // TODO Check number of redundantJointActuations vs redudantant elements const arma::Col<double>::fixed<3>& endEffectorPosition = endEffectorPose.subvec(0, 2); const double& endEffectorRollAngle = endEffectorPose.at(3); const double& endEffectorPitchAngle = endEffectorPose.at(4); const double& endEffectorYawAngle = endEffectorPose.at(5); arma::Mat<double>::fixed<3, 3> baseJoints = redundantJointStarts_; for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) { const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n); baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointsStartToEnd_.col(redundantJointIndex); } arma::Mat<double>::fixed<3, 3> endEffectorJoints = get3DRotationMatrix(endEffectorRollAngle, endEffectorPitchAngle, endEffectorYawAngle) * endEffectorJointsRelative_; endEffectorJoints.each_col() += endEffectorPosition; std::vector<arma::Mat<double>::fixed<3, 3>> model; model.push_back(baseJoints); model.push_back(endEffectorJoints); return model; } inline arma::Col<double>::fixed<6> ParallelKinematicMachine3PUPS::getEndEffectorPose( const arma::Row<double>::fixed<3>& actuations, const arma::Row<double>& redundantJointActuations) const { // TODO Direct kinematic (estimate position, using a simple HillCLimber algorithm) return {0, 0, 0, 0, 0, 0}; } inline arma::Row<double>::fixed<3> ParallelKinematicMachine3PUPS::getActuation( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const { const std::vector<arma::Mat<double>::fixed<3, 3>>& model = getModel(endEffectorPose, redundantJointActuations); const arma::Mat<double>::fixed<3, 3>& baseJoints = model.at(0); const arma::Mat<double>::fixed<3, 3>& endEffectorJoints = model.at(1); return arma::sqrt(arma::sum(arma::square(endEffectorJoints - baseJoints))); } inline double ParallelKinematicMachine3PUPS::getEndEffectorPoseAccuracy( const arma::Col<double>::fixed<6>& endEffectorPose, const arma::Row<double>& redundantJointActuations) const { const std::vector<arma::Mat<double>::fixed<3, 3>>& model = getModel(endEffectorPose, redundantJointActuations); const arma::Mat<double>::fixed<3, 3>& baseJoints = model.at(0); const arma::Mat<double>::fixed<3, 3>& endEffectorJoints = model.at(1); arma::Mat<double>::fixed<3, 3> endEffectorJointsRotated = endEffectorJoints; endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1); const arma::Mat<double>::fixed<3, 3>& baseToEndEffectorJointPositions = endEffectorJoints - baseJoints; const arma::Row<double>::fixed<3>& baseToEndEffectorJointActuations = arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions))); if (arma::any(baseToEndEffectorJointActuations < minimalActiveJointActuations_) || arma::any(baseToEndEffectorJointActuations > maximalActiveJointActuations_)) { return 0.0; } arma::Mat<double>::fixed<6, 3> forwardKinematic; forwardKinematic.rows(0, 2) = baseToEndEffectorJointPositions; for (std::size_t n = 0; n < baseToEndEffectorJointPositions.n_cols; ++n) { forwardKinematic.submat(3, n, 5, n) = arma::cross(endEffectorJointsRotated.col(n), baseToEndEffectorJointPositions.col(n)); } arma::Mat<double> inverseKinematic(6, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros); inverseKinematic.diag() = -arma::sqrt(arma::sum(arma::square(baseToEndEffectorJointPositions))); for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) { const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n); inverseKinematic.at(n, 3 + n) = arma::dot(baseToEndEffectorJointPositions.col(redundantJointIndex), redundantJointAngles_.col(redundantJointIndex)); } return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic)); } } } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "win_dev_serial_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::get_BytesToRead___U4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeDispose___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeInit___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeConfig___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeWrite___VOID__SZARRAY_U1, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeStore___U4, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeRead___U4__SZARRAY_U1__I4__I4, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeSetWatchChar___VOID, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::GetDeviceSelector___STATIC__STRING, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Windows_Devices_SerialCommunication = { "Windows.Devices.SerialCommunication", 0x5BE1F8A2, method_lookup, { 100, 1, 1, 1 } }; <commit_msg>Fix declaration of Windows.Devices.SerialCommunication (#1587)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "win_dev_serial_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::get_BytesToRead___U4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeDispose___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeInit___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeConfig___VOID, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeWrite___VOID__SZARRAY_U1, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeStore___U4, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeRead___U4__SZARRAY_U1__I4__I4, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::NativeSetWatchChar___VOID, NULL, Library_win_dev_serial_native_Windows_Devices_SerialCommunication_SerialDevice::GetDeviceSelector___STATIC__STRING, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Windows_Devices_SerialCommunication = { "Windows.Devices.SerialCommunication", 0x82260711, method_lookup, { 100, 1, 1, 1 } }; <|endoftext|>
<commit_before>#include <QString> #include <QtTest> #include <mainWindow.h> class TestTest : public QObject { Q_OBJECT public: TestTest(); private Q_SLOTS: void testCase1(); void testInit(); }; TestTest::TestTest() { } void TestTest::testCase1() { QVERIFY2(true, "Failure"); } //void TestTest::testInit() //{ // MainWindow window; // window.initWindow("Title window"); // QCOMPARE(600, window.size().height()); // QCOMPARE(800, window.size().width()); // QCOMPARE(QString("Title window"), window.windowTitle()); //} QTEST_APPLESS_MAIN(TestTest) #include "AurebeshProjectTest.moc" <commit_msg>no message<commit_after>#include <QString> #include <QtTest> #include <mainWindow.h> class TestTest : public QObject { Q_OBJECT public: TestTest(); private Q_SLOTS: void testCase1(); void testInit(); }; TestTest::TestTest() { } void TestTest::testCase1() { QVERIFY2(true, "Failure"); } void TestTest::testInit() { QVERIFY2(true, "Failure"); // MainWindow window; // window.initWindow("Title window"); // QCOMPARE(600, window.size().height()); // QCOMPARE(800, window.size().width()); // QCOMPARE(QString("Title window"), window.windowTitle()); } QTEST_APPLESS_MAIN(TestTest) #include "AurebeshProjectTest.moc" <|endoftext|>
<commit_before>/*! * \page TravelChoiceTestSuite_cpp Command-Line Test to Demonstrate How To Test the Travel CCM Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <sstream> #include <fstream> #include <string> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE TravelCCMTest #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/basic/BasFileMgr.hpp> #include <stdair/basic/PassengerChoiceModel.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/service/Logger.hpp> // TravelCCM #include <travelccm/TRAVELCCM_Service.hpp> #include <travelccm/config/travelccm-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("TravelChoiceTestSuite_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); #if defined(BOOST_VERSION) && BOOST_VERSION >= 105900 boost_utf::unit_test_log.set_format (boost_utf::OF_XML); #else // BOOST_VERSION boost_utf::unit_test_log.set_format (boost_utf::XML); #endif // BOOST_VERSION boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; // ////////////////////////////////////////////////////////////////////// /** * Choose a fare option among the list of travel solutions */ void testTravelCCMHelper (const unsigned short iTestFlag, const stdair::PassengerChoiceModel::EN_PassengerChoiceModel& iPassengerChoiceModel, const unsigned int iExpectedPrice) { // Output log File std::ostringstream oStr; oStr << "TravelChoiceTestSuite_" << iTestFlag << ".log"; const stdair::Filename_T lLogFilename (oStr.str()); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the service context const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Build the BOM tree TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams); travelccmService.buildSampleBom (); // DEBUG STDAIR_LOG_DEBUG ("Welcome to TravelCCM"); // Build a list of travel solutions const stdair::BookingRequestStruct& lBookingRequest = travelccmService.buildSampleBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display()); // Build the sample BOM tree stdair::TravelSolutionList_T lTSList; travelccmService.buildSampleTravelSolutions (lTSList); // DEBUG: Display the list of travel solutions const std::string& lCSVDump = travelccmService.csvDisplay (lTSList); STDAIR_LOG_DEBUG (lCSVDump); // Choose a travel solution const stdair::TravelSolutionStruct* lTS_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, iPassengerChoiceModel); // Check that a solution has been found BOOST_REQUIRE_MESSAGE (lTS_ptr != NULL, "No travel solution can be found for " << lBookingRequest.display() << " within the following list of travel solutions. " << lCSVDump); STDAIR_LOG_DEBUG (lTS_ptr->describe()); // Retrieve the chosen fare option stdair::FareOptionStruct lFareOption = lTS_ptr->getChosenFareOption(); // DEBUG std::ostringstream oMessageExpectedPrice; oMessageExpectedPrice << "The price chosen by the passenger is: " << lFareOption.getFare() << " Euros. It is expected to be " << iExpectedPrice << " Euros."; STDAIR_LOG_DEBUG (oMessageExpectedPrice.str()); // Check that the price corresponds to the expected one BOOST_CHECK_EQUAL (std::floor (lFareOption.getFare() + 0.5), iExpectedPrice); BOOST_CHECK_MESSAGE (std::floor (lFareOption.getFare() + 0.5) == iExpectedPrice, oMessageExpectedPrice.str()); // Close the log file logOutputFile.close(); } /** * Choose a fare option among the list of travel solutions */ void testAllTravelCCMHelper (const unsigned short iTestFlag) { // Output log File std::ostringstream oStr; oStr << "TravelChoiceTestSuite_" << iTestFlag << ".log"; const stdair::Filename_T lLogFilename (oStr.str()); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the service context const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Build the BOM tree TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams); travelccmService.buildSampleBom (); // DEBUG STDAIR_LOG_DEBUG ("Welcome to TravelCCM"); // Build a list of travel solutions const stdair::BookingRequestStruct& lBookingRequest = travelccmService.buildSampleBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display()); // Build the sample BOM tree stdair::TravelSolutionList_T lTSList; travelccmService.buildSampleTravelSolutions (lTSList); // DEBUG: Display the list of travel solutions const std::string& lCSVDump = travelccmService.csvDisplay (lTSList); STDAIR_LOG_DEBUG (lCSVDump); // Choose a travel solution with the hard restriction method. const stdair::TravelSolutionStruct* lTS_HardRestriction_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::HARD_RESTRICTION); STDAIR_LOG_DEBUG ("Chosen travel solution with the Hard Restriction model: " + lTS_HardRestriction_ptr->describe()); // Choose a travel solution with the price oriented model const stdair::TravelSolutionStruct* lTS_Price_Oriented_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::PRICE_ORIENTED); STDAIR_LOG_DEBUG ("Chosen travel solution with the Price Oriented model: " + lTS_Price_Oriented_ptr->describe()); // Choose a travel solution with the hybrid model const stdair::TravelSolutionStruct* lTS_Hybrid_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::HYBRID); STDAIR_LOG_DEBUG ("Chosen travel solution with the Hybrid model: " + lTS_Hybrid_ptr->describe()); // Close the log file logOutputFile.close(); } // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); // Start the test suite BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test the hard restriction model */ BOOST_AUTO_TEST_CASE (simple_hard_restriction_model_test) { /** * As of September 2012, the fare option chosen by the hard restriction model * is valued to 1000 Euros. */ const unsigned int lExpectedPrice = 1000; BOOST_CHECK_NO_THROW (testTravelCCMHelper (0, stdair::PassengerChoiceModel::HARD_RESTRICTION, lExpectedPrice)); } /** * Test the price oriented model */ BOOST_AUTO_TEST_CASE (simple_price_oriented_model_test) { /** * As of September 2012, the fare option chosen by the price oriented model * is valued to 900 Euros. */ const unsigned int lExpectedPrice = 900; BOOST_CHECK_NO_THROW (testTravelCCMHelper (1, stdair::PassengerChoiceModel::PRICE_ORIENTED, lExpectedPrice)); } /** * Test the hybrid model */ BOOST_AUTO_TEST_CASE (simple_hybrid_model_test) { /** * As of September 2012, the fare option chosen by the price oriented model * is valued to 920 Euros. */ const unsigned int lExpectedPrice = 920; BOOST_CHECK_NO_THROW (testTravelCCMHelper (2, stdair::PassengerChoiceModel::HYBRID, lExpectedPrice)); } /** * Test all models. */ BOOST_AUTO_TEST_CASE (all_models_test) { BOOST_CHECK_NO_THROW (testAllTravelCCMHelper(3)); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <commit_msg>BOOST_VERSION => BOOST_VERSION_MACRO<commit_after>/*! * \page TravelChoiceTestSuite_cpp Command-Line Test to Demonstrate How To Test the Travel CCM Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <sstream> #include <fstream> #include <string> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE TravelCCMTest #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/basic/BasFileMgr.hpp> #include <stdair/basic/PassengerChoiceModel.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/service/Logger.hpp> // TravelCCM #include <travelccm/TRAVELCCM_Service.hpp> #include <travelccm/config/travelccm-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("TravelChoiceTestSuite_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); #if BOOST_VERSION_MACRO >= 105900 boost_utf::unit_test_log.set_format (boost_utf::OF_XML); #else // BOOST_VERSION_MACRO boost_utf::unit_test_log.set_format (boost_utf::XML); #endif // BOOST_VERSION_MACRO boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; // ////////////////////////////////////////////////////////////////////// /** * Choose a fare option among the list of travel solutions */ void testTravelCCMHelper (const unsigned short iTestFlag, const stdair::PassengerChoiceModel::EN_PassengerChoiceModel& iPassengerChoiceModel, const unsigned int iExpectedPrice) { // Output log File std::ostringstream oStr; oStr << "TravelChoiceTestSuite_" << iTestFlag << ".log"; const stdair::Filename_T lLogFilename (oStr.str()); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the service context const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Build the BOM tree TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams); travelccmService.buildSampleBom (); // DEBUG STDAIR_LOG_DEBUG ("Welcome to TravelCCM"); // Build a list of travel solutions const stdair::BookingRequestStruct& lBookingRequest = travelccmService.buildSampleBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display()); // Build the sample BOM tree stdair::TravelSolutionList_T lTSList; travelccmService.buildSampleTravelSolutions (lTSList); // DEBUG: Display the list of travel solutions const std::string& lCSVDump = travelccmService.csvDisplay (lTSList); STDAIR_LOG_DEBUG (lCSVDump); // Choose a travel solution const stdair::TravelSolutionStruct* lTS_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, iPassengerChoiceModel); // Check that a solution has been found BOOST_REQUIRE_MESSAGE (lTS_ptr != NULL, "No travel solution can be found for " << lBookingRequest.display() << " within the following list of travel solutions. " << lCSVDump); STDAIR_LOG_DEBUG (lTS_ptr->describe()); // Retrieve the chosen fare option stdair::FareOptionStruct lFareOption = lTS_ptr->getChosenFareOption(); // DEBUG std::ostringstream oMessageExpectedPrice; oMessageExpectedPrice << "The price chosen by the passenger is: " << lFareOption.getFare() << " Euros. It is expected to be " << iExpectedPrice << " Euros."; STDAIR_LOG_DEBUG (oMessageExpectedPrice.str()); // Check that the price corresponds to the expected one BOOST_CHECK_EQUAL (std::floor (lFareOption.getFare() + 0.5), iExpectedPrice); BOOST_CHECK_MESSAGE (std::floor (lFareOption.getFare() + 0.5) == iExpectedPrice, oMessageExpectedPrice.str()); // Close the log file logOutputFile.close(); } /** * Choose a fare option among the list of travel solutions */ void testAllTravelCCMHelper (const unsigned short iTestFlag) { // Output log File std::ostringstream oStr; oStr << "TravelChoiceTestSuite_" << iTestFlag << ".log"; const stdair::Filename_T lLogFilename (oStr.str()); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the service context const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Build the BOM tree TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams); travelccmService.buildSampleBom (); // DEBUG STDAIR_LOG_DEBUG ("Welcome to TravelCCM"); // Build a list of travel solutions const stdair::BookingRequestStruct& lBookingRequest = travelccmService.buildSampleBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display()); // Build the sample BOM tree stdair::TravelSolutionList_T lTSList; travelccmService.buildSampleTravelSolutions (lTSList); // DEBUG: Display the list of travel solutions const std::string& lCSVDump = travelccmService.csvDisplay (lTSList); STDAIR_LOG_DEBUG (lCSVDump); // Choose a travel solution with the hard restriction method. const stdair::TravelSolutionStruct* lTS_HardRestriction_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::HARD_RESTRICTION); STDAIR_LOG_DEBUG ("Chosen travel solution with the Hard Restriction model: " + lTS_HardRestriction_ptr->describe()); // Choose a travel solution with the price oriented model const stdair::TravelSolutionStruct* lTS_Price_Oriented_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::PRICE_ORIENTED); STDAIR_LOG_DEBUG ("Chosen travel solution with the Price Oriented model: " + lTS_Price_Oriented_ptr->describe()); // Choose a travel solution with the hybrid model const stdair::TravelSolutionStruct* lTS_Hybrid_ptr = travelccmService.chooseTravelSolution (lTSList, lBookingRequest, stdair::PassengerChoiceModel::HYBRID); STDAIR_LOG_DEBUG ("Chosen travel solution with the Hybrid model: " + lTS_Hybrid_ptr->describe()); // Close the log file logOutputFile.close(); } // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); // Start the test suite BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test the hard restriction model */ BOOST_AUTO_TEST_CASE (simple_hard_restriction_model_test) { /** * As of September 2012, the fare option chosen by the hard restriction model * is valued to 1000 Euros. */ const unsigned int lExpectedPrice = 1000; BOOST_CHECK_NO_THROW (testTravelCCMHelper (0, stdair::PassengerChoiceModel::HARD_RESTRICTION, lExpectedPrice)); } /** * Test the price oriented model */ BOOST_AUTO_TEST_CASE (simple_price_oriented_model_test) { /** * As of September 2012, the fare option chosen by the price oriented model * is valued to 900 Euros. */ const unsigned int lExpectedPrice = 900; BOOST_CHECK_NO_THROW (testTravelCCMHelper (1, stdair::PassengerChoiceModel::PRICE_ORIENTED, lExpectedPrice)); } /** * Test the hybrid model */ BOOST_AUTO_TEST_CASE (simple_hybrid_model_test) { /** * As of September 2012, the fare option chosen by the price oriented model * is valued to 920 Euros. */ const unsigned int lExpectedPrice = 920; BOOST_CHECK_NO_THROW (testTravelCCMHelper (2, stdair::PassengerChoiceModel::HYBRID, lExpectedPrice)); } /** * Test all models. */ BOOST_AUTO_TEST_CASE (all_models_test) { BOOST_CHECK_NO_THROW (testAllTravelCCMHelper(3)); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperTypes.h" namespace otb { namespace Wrapper { std::string ParameterTypeToString(ParameterType type) { return parameterTypesStrings[type]; } ParameterType ParameterStringToType(const std::string& str) { for (auto i = 0; i < parameterTypesStrings.size(); i++) { if (str == parameterTypesStrings[i]) { return ParameterType(i); } } itkGenericExceptionMacro("Cannot convert string '" << str << "' to parameter type."); } } // namespace Wrapper } // namespace otb <commit_msg>WRG: fix warning about type conversion<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperTypes.h" namespace otb { namespace Wrapper { std::string ParameterTypeToString(ParameterType type) { return parameterTypesStrings[type]; } ParameterType ParameterStringToType(const std::string& str) { for (std::size_t i = 0; i < parameterTypesStrings.size(); i++) { if (str == parameterTypesStrings[i]) { return ParameterType(i); } } itkGenericExceptionMacro("Cannot convert string '" << str << "' to parameter type."); } } // namespace Wrapper } // namespace otb <|endoftext|>
<commit_before>/** * StimulusDisplay.cpp * * History: * Dave Cox on ??/??/?? - Created. * Paul Jankunas on 05/23/05 - Fixed spacing. * * Copyright 2005 MIT. All rights reserved. */ #include "OpenGLContextManager.h" #include "Stimulus.h" #include "StimulusNode.h" #include "Utilities.h" #include "StandardVariables.h" #include "Experiment.h" #include "StandardVariables.h" #include "ComponentRegistry.h" #include "VariableNotification.h" #include "boost/bind.hpp" #ifdef __APPLE__ #include <AGL/agl.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <CoreVideo/CVHostTime.h> #elif linux // TODO: where are these in linux? #endif #if M_OPENGL_SHARED_STATE == 1 #define RENDER_ONCE #endif using namespace mw; /********************************************************************** * StimulusDisplay Methods **********************************************************************/ StimulusDisplay::StimulusDisplay() { current_context_index = -1; // defer creation of the display chain until after the stimulus display has been created display_stack = shared_ptr< LinkedList<StimulusNode> >(new LinkedList<StimulusNode>()); setDisplayBounds(); opengl_context_manager = OpenGLContextManager::instance(); clock = Clock::instance(); if (kCVReturnSuccess != CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)) { throw SimpleException("Unable to create display link"); } stateSystemNotification = shared_ptr<VariableCallbackNotification>(new VariableCallbackNotification(boost::bind(&StimulusDisplay::stateSystemCallback, this, _1, _2))); state_system_mode->addNotification(stateSystemNotification); } StimulusDisplay::~StimulusDisplay(){ stateSystemNotification->remove(); CVDisplayLinkRelease(displayLink); } void StimulusDisplay::setCurrent(int i){ if ((i >= getNContexts()) || (i < 0)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "invalid context index (%d)", i); return; } current_context_index = i; opengl_context_manager->setCurrent(context_ids[i]); } shared_ptr<StimulusNode> StimulusDisplay::addStimulus(shared_ptr<Stimulus> stim) { if(!stim) { mprintf("Attempt to load NULL stimulus"); return shared_ptr<StimulusNode>(); } shared_ptr<StimulusNode> stimnode(new StimulusNode(stim)); display_stack->addToFront(stimnode); return stimnode; } void StimulusDisplay::addStimulusNode(shared_ptr<StimulusNode> stimnode) { if(!stimnode) { mprintf("Attempt to load NULL stimulus"); return; } // remove it, in case it already belongs to a list stimnode->remove(); display_stack->addToFront(stimnode); // TODO } void StimulusDisplay::setDisplayBounds(){ shared_ptr<mw::ComponentRegistry> reg = mw::ComponentRegistry::getSharedRegistry(); shared_ptr<Variable> main_screen_info = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME); Datum display_info = *main_screen_info; // from standard variables if(display_info.getDataType() == M_DICTIONARY && display_info.hasKey(M_DISPLAY_WIDTH_KEY) && display_info.hasKey(M_DISPLAY_HEIGHT_KEY) && display_info.hasKey(M_DISPLAY_DISTANCE_KEY)){ GLdouble width_unknown_units = display_info.getElement(M_DISPLAY_WIDTH_KEY); GLdouble height_unknown_units = display_info.getElement(M_DISPLAY_HEIGHT_KEY); GLdouble distance_unknown_units = display_info.getElement(M_DISPLAY_DISTANCE_KEY); GLdouble half_width_deg = (180. / M_PI) * atan((width_unknown_units/2.)/distance_unknown_units); GLdouble half_height_deg = half_width_deg * height_unknown_units / width_unknown_units; //GLdouble half_height_deg = (180. / M_PI) * atan((height_unknown_units/2.)/distance_unknown_units); left = -half_width_deg; right = half_width_deg; top = half_height_deg; bottom = -half_height_deg; } else { left = M_STIMULUS_DISPLAY_LEFT_EDGE; right = M_STIMULUS_DISPLAY_RIGHT_EDGE; top = M_STIMULUS_DISPLAY_TOP_EDGE; bottom = M_STIMULUS_DISPLAY_BOTTOM_EDGE; } mprintf("Display bounds set to (%g left, %g right, %g top, %g bottom)", left, right, top, bottom); } void StimulusDisplay::getDisplayBounds(GLdouble &left, GLdouble &right, GLdouble &bottom, GLdouble &top) { left = this->left; right = this->right; bottom = this->bottom; top = this->top; } void StimulusDisplay::addContext(int _context_id){ context_ids.push_back(_context_id); current_context_index = context_ids.size() - 1; opengl_context_manager->setCurrent(_context_id); #ifdef RENDER_ONCE if (!(glewIsSupported("GL_EXT_framebuffer_object") && glewIsSupported("GL_EXT_framebuffer_blit"))) { throw SimpleException("renderer does not support required OpenGL framebuffer extensions"); } #endif } void StimulusDisplay::getCurrentViewportSize(GLint &width, GLint &height) { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); width = viewport[2]; height = viewport[3]; } void StimulusDisplay::stateSystemCallback(const Datum &data, MWorksTime time) { boost::mutex::scoped_lock lock(display_lock); int newState = data.getInteger(); if (IDLE == newState) { if (CVDisplayLinkIsRunning(displayLink)) { if (kCVReturnSuccess != CVDisplayLinkStop(displayLink)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Unable to stop display updates"); } else { mprintf(M_DISPLAY_MESSAGE_DOMAIN, "Display updates stopped"); } } } else if (RUNNING == newState) { if (!CVDisplayLinkIsRunning(displayLink)) { if (kCVReturnSuccess != CVDisplayLinkSetOutputCallback(displayLink, &StimulusDisplay::displayLinkCallback, this) || kCVReturnSuccess != opengl_context_manager->prepareDisplayLinkForMainDisplay(displayLink) || kCVReturnSuccess != CVDisplayLinkStart(displayLink)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Unable to schedule display updates"); } else { mprintf(M_DISPLAY_MESSAGE_DOMAIN, "Display updates started (main = %d, current = %d)", CGMainDisplayID(), CVDisplayLinkGetCurrentCGDisplay(displayLink)); } } } } CVReturn StimulusDisplay::displayLinkCallback(CVDisplayLinkRef _displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *_display) { StimulusDisplay *display = static_cast<StimulusDisplay*>(_display); CVReturn status = kCVReturnSuccess; { boost::mutex::scoped_lock lock(display->display_lock); display->refreshDisplay(); //#define ERROR_ON_MISSED_REFRESH #ifdef ERROR_ON_MISSED_REFRESH uint64_t currentTime = CVGetCurrentHostTime(); if (currentTime > outputTime->hostTime) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Display refresh did not complete within vertical blanking interval"); status = kCVReturnError; } #endif display->refreshComplete = true; } // Signal waiting threads that refresh is complete display->refreshCond.notify_all(); return status; } void StimulusDisplay::refreshDisplay() { // // Draw stimuli on main display // MWTime before_draw = clock->getCurrentTimeUS(); setCurrent(0); drawDisplayStack(); #define USE_GL_FENCE #ifdef USE_GL_FENCE if(opengl_context_manager->hasFence()){ glSetFenceAPPLE(opengl_context_manager->getFence()); } #endif opengl_context_manager->flush(0); #ifdef USE_GL_FENCE if(opengl_context_manager->hasFence()){ glFinishFenceAPPLE(opengl_context_manager->getFence()); } #endif MWTime now = clock->getCurrentTimeUS(); stimDisplayUpdate->setValue(getAnnounceData(), now); announceDisplayStack(now); #define ERROR_ON_LATE_FRAMES #ifdef ERROR_ON_LATE_FRAMES int refresh_rate = opengl_context_manager->getDisplayRefreshRate(opengl_context_manager->getMainDisplayIndex()); if(refresh_rate <= 0){ refresh_rate = 60; } MWTime slop = 2*(1000000/refresh_rate); if(now-before_draw > slop) { merror(M_DISPLAY_MESSAGE_DOMAIN, "updating main window display is taking longer than two frames (%lld > %lld) to update", now-before_draw, slop); } #endif // // Draw stimuli on mirror display(s) // if (context_ids.size() > 1) { #ifndef RENDER_ONCE for (int i = 1; i < context_ids.size(); i++) { setCurrent(i); drawDisplayStack(); opengl_context_manager->updateAndFlush(i); } #else GLint srcWidth, srcHeight; getCurrentViewportSize(srcWidth, srcHeight); GLuint framebuffer, renderbuffer; glGenFramebuffersEXT(1, &framebuffer); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); glGenRenderbuffersEXT(1, &renderbuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, srcWidth, srcHeight); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, renderbuffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (GL_FRAMEBUFFER_COMPLETE_EXT != status) { merror(M_DISPLAY_MESSAGE_DOMAIN, "framebuffer setup failed (status = %d)", status); glDeleteRenderbuffersEXT(1, &renderbuffer); glDeleteFramebuffersEXT(1, &framebuffer); return; } glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer); glBlitFramebufferEXT(0, 0, srcWidth, srcHeight, 0, 0, srcWidth, srcHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Send subsequent rendering to back buffer for (int i = 1; i < context_ids.size(); i++) { setCurrent(i); GLint dstWidth, dstHeight; getCurrentViewportSize(dstWidth, dstHeight); glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); glBlitFramebufferEXT(0, 0, srcWidth, srcHeight, 0, 0, dstWidth, dstHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); opengl_context_manager->updateAndFlush(i); } glDeleteRenderbuffersEXT(1, &renderbuffer); glDeleteFramebuffersEXT(1, &framebuffer); #endif /*RENDER_ONCE*/ } } void StimulusDisplay::clearDisplay() { { boost::mutex::scoped_lock lock(display_lock); shared_ptr<StimulusNode> node = display_stack->getFrontmost(); while(node) { node->setVisible(false); node = node->getNext(); } } updateDisplay(); } void StimulusDisplay::glInit() { glShadeModel(GL_FLAT); glDisable(GL_BLEND); glDisable(GL_DITHER); glDisable(GL_FOG); glDisable(GL_LIGHTING); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); // DDC added glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Reset The Projection Matrix gluOrtho2D(left, right, bottom, top); glMatrixMode(GL_MODELVIEW); glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT); } void StimulusDisplay::drawDisplayStack() { // OpenGL setup glInit(); // Draw all of the stimuli in the chain, back to front shared_ptr<StimulusNode> node = display_stack->getBackmost(); while (node) { if (node->isVisible()) { node->draw(shared_from_this()); } node = node->getPrevious(); } } void StimulusDisplay::updateDisplay() { boost::mutex::scoped_lock lock(display_lock); shared_ptr<StimulusNode> node = display_stack->getFrontmost(); while (node) { if (node->isPending()) { // we're taking care of the pending state, so // clear this flag node->clearPending(); // convert "pending visible" stimuli to "visible" ones node->setVisible(node->isPendingVisible()); if (node->isPendingRemoval()) { node->clearPendingRemoval(); node->remove(); continue; } } node = node->getNext(); } if (!CVDisplayLinkIsRunning(displayLink)) { // Need to do the refresh here refreshDisplay(); } else { // Wait for next display refresh to complete refreshComplete = false; do { refreshCond.wait(lock); } while (!refreshComplete); } } void StimulusDisplay::announceDisplayStack(MWTime time) { shared_ptr<StimulusNode> node = display_stack->getBackmost(); //tail; while(node != shared_ptr< LinkedListNode<StimulusNode> >()) { if(node->isVisible()) { node->announceStimulusDraw(time); } node = node->getPrevious(); } } Datum StimulusDisplay::getAnnounceData() { shared_ptr<StimulusNode> node = display_stack->getBackmost(); //tail; Datum stimAnnounce(M_LIST, 1); while(node != shared_ptr< LinkedListNode<StimulusNode> >()) { if(node->isVisible()) { Datum individualAnnounce(node->getCurrentAnnounceDrawData()); if(!individualAnnounce.isUndefined()) { stimAnnounce.addElement(individualAnnounce); } } node = node->getPrevious(); } return stimAnnounce; } <commit_msg>Minor tweak to StimulusDisplay<commit_after>/** * StimulusDisplay.cpp * * History: * Dave Cox on ??/??/?? - Created. * Paul Jankunas on 05/23/05 - Fixed spacing. * * Copyright 2005 MIT. All rights reserved. */ #include "OpenGLContextManager.h" #include "Stimulus.h" #include "StimulusNode.h" #include "Utilities.h" #include "StandardVariables.h" #include "Experiment.h" #include "StandardVariables.h" #include "ComponentRegistry.h" #include "VariableNotification.h" #include "boost/bind.hpp" #ifdef __APPLE__ #include <AGL/agl.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <CoreVideo/CVHostTime.h> #elif linux // TODO: where are these in linux? #endif #if M_OPENGL_SHARED_STATE == 1 #define RENDER_ONCE #endif using namespace mw; /********************************************************************** * StimulusDisplay Methods **********************************************************************/ StimulusDisplay::StimulusDisplay() { current_context_index = -1; // defer creation of the display chain until after the stimulus display has been created display_stack = shared_ptr< LinkedList<StimulusNode> >(new LinkedList<StimulusNode>()); setDisplayBounds(); opengl_context_manager = OpenGLContextManager::instance(); clock = Clock::instance(); if (kCVReturnSuccess != CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)) { throw SimpleException("Unable to create display link"); } stateSystemNotification = shared_ptr<VariableCallbackNotification>(new VariableCallbackNotification(boost::bind(&StimulusDisplay::stateSystemCallback, this, _1, _2))); state_system_mode->addNotification(stateSystemNotification); } StimulusDisplay::~StimulusDisplay(){ stateSystemNotification->remove(); CVDisplayLinkRelease(displayLink); } void StimulusDisplay::setCurrent(int i){ if ((i >= getNContexts()) || (i < 0)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "invalid context index (%d)", i); return; } current_context_index = i; opengl_context_manager->setCurrent(context_ids[i]); } shared_ptr<StimulusNode> StimulusDisplay::addStimulus(shared_ptr<Stimulus> stim) { if(!stim) { mprintf("Attempt to load NULL stimulus"); return shared_ptr<StimulusNode>(); } shared_ptr<StimulusNode> stimnode(new StimulusNode(stim)); display_stack->addToFront(stimnode); return stimnode; } void StimulusDisplay::addStimulusNode(shared_ptr<StimulusNode> stimnode) { if(!stimnode) { mprintf("Attempt to load NULL stimulus"); return; } // remove it, in case it already belongs to a list stimnode->remove(); display_stack->addToFront(stimnode); // TODO } void StimulusDisplay::setDisplayBounds(){ shared_ptr<mw::ComponentRegistry> reg = mw::ComponentRegistry::getSharedRegistry(); shared_ptr<Variable> main_screen_info = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME); Datum display_info = *main_screen_info; // from standard variables if(display_info.getDataType() == M_DICTIONARY && display_info.hasKey(M_DISPLAY_WIDTH_KEY) && display_info.hasKey(M_DISPLAY_HEIGHT_KEY) && display_info.hasKey(M_DISPLAY_DISTANCE_KEY)){ GLdouble width_unknown_units = display_info.getElement(M_DISPLAY_WIDTH_KEY); GLdouble height_unknown_units = display_info.getElement(M_DISPLAY_HEIGHT_KEY); GLdouble distance_unknown_units = display_info.getElement(M_DISPLAY_DISTANCE_KEY); GLdouble half_width_deg = (180. / M_PI) * atan((width_unknown_units/2.)/distance_unknown_units); GLdouble half_height_deg = half_width_deg * height_unknown_units / width_unknown_units; //GLdouble half_height_deg = (180. / M_PI) * atan((height_unknown_units/2.)/distance_unknown_units); left = -half_width_deg; right = half_width_deg; top = half_height_deg; bottom = -half_height_deg; } else { left = M_STIMULUS_DISPLAY_LEFT_EDGE; right = M_STIMULUS_DISPLAY_RIGHT_EDGE; top = M_STIMULUS_DISPLAY_TOP_EDGE; bottom = M_STIMULUS_DISPLAY_BOTTOM_EDGE; } mprintf("Display bounds set to (%g left, %g right, %g top, %g bottom)", left, right, top, bottom); } void StimulusDisplay::getDisplayBounds(GLdouble &left, GLdouble &right, GLdouble &bottom, GLdouble &top) { left = this->left; right = this->right; bottom = this->bottom; top = this->top; } void StimulusDisplay::addContext(int _context_id){ context_ids.push_back(_context_id); current_context_index = context_ids.size() - 1; opengl_context_manager->setCurrent(_context_id); #ifdef RENDER_ONCE if (!(glewIsSupported("GL_EXT_framebuffer_object") && glewIsSupported("GL_EXT_framebuffer_blit"))) { throw SimpleException("renderer does not support required OpenGL framebuffer extensions"); } #endif } void StimulusDisplay::getCurrentViewportSize(GLint &width, GLint &height) { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); width = viewport[2]; height = viewport[3]; } void StimulusDisplay::stateSystemCallback(const Datum &data, MWorksTime time) { boost::mutex::scoped_lock lock(display_lock); int newState = data.getInteger(); if (IDLE == newState) { if (CVDisplayLinkIsRunning(displayLink)) { if (kCVReturnSuccess != CVDisplayLinkStop(displayLink)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Unable to stop display updates"); } else { mprintf(M_DISPLAY_MESSAGE_DOMAIN, "Display updates stopped"); } } } else if (RUNNING == newState) { if (!CVDisplayLinkIsRunning(displayLink)) { if (kCVReturnSuccess != CVDisplayLinkSetOutputCallback(displayLink, &StimulusDisplay::displayLinkCallback, this) || kCVReturnSuccess != opengl_context_manager->prepareDisplayLinkForMainDisplay(displayLink) || kCVReturnSuccess != CVDisplayLinkStart(displayLink)) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Unable to schedule display updates"); } else { mprintf(M_DISPLAY_MESSAGE_DOMAIN, "Display updates started (main = %d, current = %d)", CGMainDisplayID(), CVDisplayLinkGetCurrentCGDisplay(displayLink)); } } } } CVReturn StimulusDisplay::displayLinkCallback(CVDisplayLinkRef _displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *_display) { StimulusDisplay *display = static_cast<StimulusDisplay*>(_display); CVReturn status = kCVReturnSuccess; { boost::mutex::scoped_lock lock(display->display_lock); display->refreshDisplay(); //#define ERROR_ON_MISSED_REFRESH #ifdef ERROR_ON_MISSED_REFRESH uint64_t currentTime = CVGetCurrentHostTime(); if (currentTime > outputTime->hostTime) { merror(M_DISPLAY_MESSAGE_DOMAIN, "Display refresh did not complete within vertical blanking interval"); status = kCVReturnError; } #endif display->refreshComplete = true; } // Signal waiting threads that refresh is complete display->refreshCond.notify_all(); return status; } void StimulusDisplay::refreshDisplay() { // // Draw stimuli on main display // MWTime before_draw = clock->getCurrentTimeUS(); setCurrent(0); drawDisplayStack(); #define USE_GL_FENCE #ifdef USE_GL_FENCE if(opengl_context_manager->hasFence()){ glSetFenceAPPLE(opengl_context_manager->getFence()); } #endif opengl_context_manager->flush(0); #ifdef USE_GL_FENCE if(opengl_context_manager->hasFence()){ glFinishFenceAPPLE(opengl_context_manager->getFence()); } #endif MWTime now = clock->getCurrentTimeUS(); stimDisplayUpdate->setValue(getAnnounceData(), now); announceDisplayStack(now); #define ERROR_ON_LATE_FRAMES #ifdef ERROR_ON_LATE_FRAMES int refresh_rate = opengl_context_manager->getDisplayRefreshRate(opengl_context_manager->getMainDisplayIndex()); if(refresh_rate <= 0){ refresh_rate = 60; } MWTime slop = 2*(1000000/refresh_rate); if(now-before_draw > slop) { merror(M_DISPLAY_MESSAGE_DOMAIN, "updating main window display is taking longer than two frames (%lld > %lld) to update", now-before_draw, slop); } #endif // // Draw stimuli on mirror display(s) // #ifndef RENDER_ONCE for (int i = 1; i < context_ids.size(); i++) { setCurrent(i); drawDisplayStack(); opengl_context_manager->updateAndFlush(i); } #else if (context_ids.size() > 1) { GLint srcWidth, srcHeight; getCurrentViewportSize(srcWidth, srcHeight); GLuint framebuffer, renderbuffer; glGenFramebuffersEXT(1, &framebuffer); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); glGenRenderbuffersEXT(1, &renderbuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, srcWidth, srcHeight); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, renderbuffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (GL_FRAMEBUFFER_COMPLETE_EXT != status) { merror(M_DISPLAY_MESSAGE_DOMAIN, "framebuffer setup failed (status = %d)", status); glDeleteRenderbuffersEXT(1, &renderbuffer); glDeleteFramebuffersEXT(1, &framebuffer); return; } glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer); glBlitFramebufferEXT(0, 0, srcWidth, srcHeight, 0, 0, srcWidth, srcHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Send subsequent rendering to back buffer for (int i = 1; i < context_ids.size(); i++) { setCurrent(i); GLint dstWidth, dstHeight; getCurrentViewportSize(dstWidth, dstHeight); glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); glBlitFramebufferEXT(0, 0, srcWidth, srcHeight, 0, 0, dstWidth, dstHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); opengl_context_manager->updateAndFlush(i); } glDeleteRenderbuffersEXT(1, &renderbuffer); glDeleteFramebuffersEXT(1, &framebuffer); } #endif /*RENDER_ONCE*/ } void StimulusDisplay::clearDisplay() { { boost::mutex::scoped_lock lock(display_lock); shared_ptr<StimulusNode> node = display_stack->getFrontmost(); while(node) { node->setVisible(false); node = node->getNext(); } } updateDisplay(); } void StimulusDisplay::glInit() { glShadeModel(GL_FLAT); glDisable(GL_BLEND); glDisable(GL_DITHER); glDisable(GL_FOG); glDisable(GL_LIGHTING); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); // DDC added glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Reset The Projection Matrix gluOrtho2D(left, right, bottom, top); glMatrixMode(GL_MODELVIEW); glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT); } void StimulusDisplay::drawDisplayStack() { // OpenGL setup glInit(); // Draw all of the stimuli in the chain, back to front shared_ptr<StimulusNode> node = display_stack->getBackmost(); while (node) { if (node->isVisible()) { node->draw(shared_from_this()); } node = node->getPrevious(); } } void StimulusDisplay::updateDisplay() { boost::mutex::scoped_lock lock(display_lock); shared_ptr<StimulusNode> node = display_stack->getFrontmost(); while (node) { if (node->isPending()) { // we're taking care of the pending state, so // clear this flag node->clearPending(); // convert "pending visible" stimuli to "visible" ones node->setVisible(node->isPendingVisible()); if (node->isPendingRemoval()) { node->clearPendingRemoval(); node->remove(); continue; } } node = node->getNext(); } if (!CVDisplayLinkIsRunning(displayLink)) { // Need to do the refresh here refreshDisplay(); } else { // Wait for next display refresh to complete refreshComplete = false; do { refreshCond.wait(lock); } while (!refreshComplete); } } void StimulusDisplay::announceDisplayStack(MWTime time) { shared_ptr<StimulusNode> node = display_stack->getBackmost(); //tail; while(node != shared_ptr< LinkedListNode<StimulusNode> >()) { if(node->isVisible()) { node->announceStimulusDraw(time); } node = node->getPrevious(); } } Datum StimulusDisplay::getAnnounceData() { shared_ptr<StimulusNode> node = display_stack->getBackmost(); //tail; Datum stimAnnounce(M_LIST, 1); while(node != shared_ptr< LinkedListNode<StimulusNode> >()) { if(node->isVisible()) { Datum individualAnnounce(node->getCurrentAnnounceDrawData()); if(!individualAnnounce.isUndefined()) { stimAnnounce.addElement(individualAnnounce); } } node = node->getPrevious(); } return stimAnnounce; } <|endoftext|>
<commit_before>/** * @file Cosa/Pins.cpp * @version 1.0 * * @section License * Copyright (C) 2012, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Arduino pins abstractions; abstract, input, output, interrupt and * analog pin. Captures the mapping from Arduino to processor pins. * Forces declarative programming of pins in sketches. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Pins.h" #include <util/delay_basic.h> #define DELAY(us) _delay_loop_2((us) << 2) uint8_t Pin::await_change(uint8_t us) { uint8_t res = 0; synchronized { if (is_set()) { while (is_set() && us--) res++; } else { while (is_clear() && us--) res++; } } return (res); } void Pin::print(IOStream& stream) { stream.printf_P(PSTR("Pin(pin = %d, sfr = %p, mask = %bd)"), _pin, _sfr, _mask); } void Pin::println(IOStream& stream) { print(); stream.println(); } InterruptPin* InterruptPin::ext[2] = { 0, 0 }; ISR(INT0_vect) { if (InterruptPin::ext[0] != 0) InterruptPin::ext[0]->on_interrupt(); } ISR(INT1_vect) { if (InterruptPin::ext[1] != 0) InterruptPin::ext[1]->on_interrupt(); } void OutputPin::pulse(uint16_t us) { toggle(); DELAY(us); toggle(); } void PWMPin::set(uint8_t duty) { if (_pin == 3) { bit_set(TCCR2A, COM2A1); OCR2A = duty; return; } if (_pin == 5) { bit_set(TCCR0A, COM0B1); OCR0B = duty; return; } if (_pin == 6) { bit_set(TCCR0A, COM0A1); OCR0A = duty; return; } if (_pin == 11) { bit_set(TCCR2A, COM2B1); OCR2B = duty; return; } if (duty < 128) OutputPin::clear(); else OutputPin::set(); } void PWMPin::set(uint16_t value, uint16_t min, uint16_t max) { uint8_t duty; if (value <= min) duty = 0; else if (value >= max) duty = 255; else duty = (((uint32_t) (value - min)) << 8) / (max - min); set(duty); } uint8_t PWMPin::get_duty() { if (_pin == 5) return (OCR0B); if (_pin == 6) return (OCR0A); return (is_set()); } AnalogPin* AnalogPin::sampling_pin = 0; uint16_t AnalogPin::sample() { loop_until_bit_is_clear(ADCSRA, ADSC); ADMUX = (_reference | ((_pin - 14) & 0xf)); bit_mask_set(ADCSRA, _BV(ADEN) | _BV(ADSC)); loop_until_bit_is_clear(ADCSRA, ADSC); return (_value = ADCW); } void AnalogPin::sample_request() { loop_until_bit_is_clear(ADCSRA, ADSC); ADMUX = (_reference | (_pin - 14)); bit_mask_set(ADCSRA, _BV(ADEN) | _BV(ADSC)); if (_handler == 0) return; sampling_pin = this; bit_set(ADCSRA, ADIE); } uint16_t AnalogPin::sample_await() { loop_until_bit_is_clear(ADCSRA, ADSC); return (_value = ADCW); } ISR(ADC_vect) { bit_clear(ADCSRA, ADIE); AnalogPin* pin = AnalogPin::get_sampling_pin(); if (pin != 0) pin->on_sample(ADCW); } void AnalogPins::sample_next(AnalogPin* pin, void* env) { AnalogPins* set = (AnalogPins*) env; if (set->_next != set->_count) { AnalogPin* pin = set->get_pin_at(set->_next++); pin->sample_request(); } else if (set->_handler != 0) { set->_handler(set, set->_env); } } bool AnalogPins::samples_request(InterruptHandler fn, void* env) { if (AnalogPin::get_sampling_pin() != 0) return (0); if (fn != 0) { _handler = fn; _env = env; } get_pin_at(0)->sample_request(); _next = 1; return (1); } <commit_msg>Fixed PWMPin 3/11. Pins where switched.<commit_after>/** * @file Cosa/Pins.cpp * @version 1.0 * * @section License * Copyright (C) 2012, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Arduino pins abstractions; abstract, input, output, interrupt and * analog pin. Captures the mapping from Arduino to processor pins. * Forces declarative programming of pins in sketches. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Pins.h" #include <util/delay_basic.h> #define DELAY(us) _delay_loop_2((us) << 2) uint8_t Pin::await_change(uint8_t us) { uint8_t res = 0; synchronized { if (is_set()) { while (is_set() && us--) res++; } else { while (is_clear() && us--) res++; } } return (res); } void Pin::print(IOStream& stream) { stream.printf_P(PSTR("Pin(pin = %d, sfr = %p, mask = %bd)"), _pin, _sfr, _mask); } void Pin::println(IOStream& stream) { print(); stream.println(); } InterruptPin* InterruptPin::ext[2] = { 0, 0 }; ISR(INT0_vect) { if (InterruptPin::ext[0] != 0) InterruptPin::ext[0]->on_interrupt(); } ISR(INT1_vect) { if (InterruptPin::ext[1] != 0) InterruptPin::ext[1]->on_interrupt(); } void OutputPin::pulse(uint16_t us) { toggle(); DELAY(us); toggle(); } void PWMPin::set(uint8_t duty) { if (_pin == 3) { bit_set(TCCR2A, COM2B1); OCR2B = duty; return; } if (_pin == 5) { bit_set(TCCR0A, COM0B1); OCR0B = duty; return; } if (_pin == 6) { bit_set(TCCR0A, COM0A1); OCR0A = duty; return; } if (_pin == 11) { bit_set(TCCR2A, COM2A1); OCR2A = duty; return; } if (duty < 128) OutputPin::clear(); else OutputPin::set(); } void PWMPin::set(uint16_t value, uint16_t min, uint16_t max) { uint8_t duty; if (value <= min) duty = 0; else if (value >= max) duty = 255; else duty = (((uint32_t) (value - min)) << 8) / (max - min); set(duty); } uint8_t PWMPin::get_duty() { if (_pin == 5) return (OCR0B); if (_pin == 6) return (OCR0A); return (is_set()); } AnalogPin* AnalogPin::sampling_pin = 0; uint16_t AnalogPin::sample() { loop_until_bit_is_clear(ADCSRA, ADSC); ADMUX = (_reference | ((_pin - 14) & 0xf)); bit_mask_set(ADCSRA, _BV(ADEN) | _BV(ADSC)); loop_until_bit_is_clear(ADCSRA, ADSC); return (_value = ADCW); } void AnalogPin::sample_request() { loop_until_bit_is_clear(ADCSRA, ADSC); ADMUX = (_reference | (_pin - 14)); bit_mask_set(ADCSRA, _BV(ADEN) | _BV(ADSC)); if (_handler == 0) return; sampling_pin = this; bit_set(ADCSRA, ADIE); } uint16_t AnalogPin::sample_await() { loop_until_bit_is_clear(ADCSRA, ADSC); return (_value = ADCW); } ISR(ADC_vect) { bit_clear(ADCSRA, ADIE); AnalogPin* pin = AnalogPin::get_sampling_pin(); if (pin != 0) pin->on_sample(ADCW); } void AnalogPins::sample_next(AnalogPin* pin, void* env) { AnalogPins* set = (AnalogPins*) env; if (set->_next != set->_count) { AnalogPin* pin = set->get_pin_at(set->_next++); pin->sample_request(); } else if (set->_handler != 0) { set->_handler(set, set->_env); } } bool AnalogPins::samples_request(InterruptHandler fn, void* env) { if (AnalogPin::get_sampling_pin() != 0) return (0); if (fn != 0) { _handler = fn; _env = env; } get_pin_at(0)->sample_request(); _next = 1; return (1); } <|endoftext|>
<commit_before>#include <algorithm> #include <unordered_map> #include <string> #include <thread> #include <iostream> #include "message.h" #include "message_pipe.h" #include "registry.h" #include "plugin_loader.h" #include "required_messages.h" #include "core_messages.h" using namespace std; static unordered_map<string, message_pipe> out_pipes; static unordered_map<string, registry> message_registrations; static message_pipe in_pipe; static bool verbose; ostream &operator<<(ostream &out, const message &m) { return out << '(' << m.type << ',' << m.priority << ',' << m.getdata() << ')'; } static void to_plugin(message m) { if (message_registrations.count(m.gettype())==0) { //This message type has no registration, so discard it if (verbose) cerr << " was not registered" << endl; return; } auto plugin=message_registrations[m.gettype()].get(m.getpriority()); if (plugin.second=="") { if (verbose) cerr << " has no more registered plugins" << endl; return; } if (out_pipes.count(plugin.second)==0) { //This type does not exist if (verbose) cerr << " is registered to the non-existent plugin " << plugin.second << endl; return; } //Change the message priority to the registered priority out_pipes[plugin.second].write(m.change_priority(plugin.first)); if (verbose) cerr << " was sent to " << plugin.second << " as " << m << endl; } static void add_plugin(const message &m) { auto pa=dynamic_cast<plugin_adder *>(m.getdata()); if (!pa) //The message wasn't a plugin_adder return; if (out_pipes.count(pa->name)!=0) //There's already a plugin with this name return; message_pipe mp; thread t1(load_plugin, pa->filename, plugin_pipe(bidirectional_message_pipe(mp, in_pipe))); t1.detach(); out_pipes[pa->name]=mp; mp.write(hello_message::create(pa->name)); if (verbose) cerr << " loaded plugin " << pa->name << " from " << pa->filename << endl; } static void remove_plugin(const message &m) { auto d=dynamic_cast<done_message *>(m.getdata()); if (!d) return; for (auto &i : message_registrations) i.second.removeall(d->name); decltype(message_registrations.begin()) i; //Who says C++ is verbose? while ((i=std::find_if(message_registrations.begin(), message_registrations.end(), [](decltype(*i) &p) {return p.second.empty();}))!=message_registrations.end()) message_registrations.erase(i); out_pipes.erase(d->name); if (verbose) cerr << " removed plugin " << d->name << endl; } static void add_registration(const message &m) { auto r=dynamic_cast<registration_message *>(m.getdata()); if (!r) return; if (out_pipes.count(r->getname())==0) //We can't talk to this plugin, so ignore its request return; bool b=message_registrations[r->getmessage()].add(r->getpriority(), r->getname()); //Tell the plugin whether it failed or not out_pipes[r->getname()].write(registration_status::create(b, r->getpriority(), r->getmessage())); if (verbose) cerr << " registered " << r->message_type << " to " << r->plugin_name << endl; } static void target_plugin(const message &m) { auto i=dynamic_cast<targeted_message *>(m.getdata()); if (!i) return; if (out_pipes.count(i->name)==0) return; out_pipes[i->name].write(i->mess); if (verbose) cerr << " targeted " << i->mess << " towards " << i->name << endl; } static void process(const message &m) { if (verbose) cerr << "Message " << m; if (m.gettype()=="add_plugin") add_plugin(m); else if (m.gettype()=="register") add_registration(m); else if (m.type=="done") remove_plugin(m); else if (m.type=="target") target_plugin(m); else to_plugin(m); } static void run_core(const vector<message> &vm) { for (auto m : vm) process(m); while (!out_pipes.empty()) { process(in_pipe.blocking_read()); } } int main(int argc, char *argv[]) { vector<message> vm; for (int i=1; i<argc-1; i+=2) { if (argv[i]==string("-v") || argv[i]==string("--verbose")) { verbose=true; --i; } else vm.push_back(plugin_adder::create(argv[i],argv[i+1])); } run_core(vm); } <commit_msg>Use the system locale instead of the default C locale<commit_after>#include <algorithm> #include <unordered_map> #include <string> #include <thread> #include <iostream> #include "message.h" #include "message_pipe.h" #include "registry.h" #include "plugin_loader.h" #include "required_messages.h" #include "core_messages.h" using namespace std; static unordered_map<string, message_pipe> out_pipes; static unordered_map<string, registry> message_registrations; static message_pipe in_pipe; static bool verbose; ostream &operator<<(ostream &out, const message &m) { return out << '(' << m.type << ',' << m.priority << ',' << m.getdata() << ')'; } static void to_plugin(message m) { if (message_registrations.count(m.gettype())==0) { //This message type has no registration, so discard it if (verbose) cerr << " was not registered" << endl; return; } auto plugin=message_registrations[m.gettype()].get(m.getpriority()); if (plugin.second=="") { if (verbose) cerr << " has no more registered plugins" << endl; return; } if (out_pipes.count(plugin.second)==0) { //This type does not exist if (verbose) cerr << " is registered to the non-existent plugin " << plugin.second << endl; return; } //Change the message priority to the registered priority out_pipes[plugin.second].write(m.change_priority(plugin.first)); if (verbose) cerr << " was sent to " << plugin.second << " as " << m << endl; } static void add_plugin(const message &m) { auto pa=dynamic_cast<plugin_adder *>(m.getdata()); if (!pa) //The message wasn't a plugin_adder return; if (out_pipes.count(pa->name)!=0) //There's already a plugin with this name return; message_pipe mp; thread t1(load_plugin, pa->filename, plugin_pipe(bidirectional_message_pipe(mp, in_pipe))); t1.detach(); out_pipes[pa->name]=mp; mp.write(hello_message::create(pa->name)); if (verbose) cerr << " loaded plugin " << pa->name << " from " << pa->filename << endl; } static void remove_plugin(const message &m) { auto d=dynamic_cast<done_message *>(m.getdata()); if (!d) return; for (auto &i : message_registrations) i.second.removeall(d->name); decltype(message_registrations.begin()) i; //Who says C++ is verbose? while ((i=std::find_if(message_registrations.begin(), message_registrations.end(), [](decltype(*i) &p) {return p.second.empty();}))!=message_registrations.end()) message_registrations.erase(i); out_pipes.erase(d->name); if (verbose) cerr << " removed plugin " << d->name << endl; } static void add_registration(const message &m) { auto r=dynamic_cast<registration_message *>(m.getdata()); if (!r) return; if (out_pipes.count(r->getname())==0) //We can't talk to this plugin, so ignore its request return; bool b=message_registrations[r->getmessage()].add(r->getpriority(), r->getname()); //Tell the plugin whether it failed or not out_pipes[r->getname()].write(registration_status::create(b, r->getpriority(), r->getmessage())); if (verbose) cerr << " registered " << r->message_type << " to " << r->plugin_name << endl; } static void target_plugin(const message &m) { auto i=dynamic_cast<targeted_message *>(m.getdata()); if (!i) return; if (out_pipes.count(i->name)==0) return; out_pipes[i->name].write(i->mess); if (verbose) cerr << " targeted " << i->mess << " towards " << i->name << endl; } static void process(const message &m) { if (verbose) cerr << "Message " << m; if (m.gettype()=="add_plugin") add_plugin(m); else if (m.gettype()=="register") add_registration(m); else if (m.type=="done") remove_plugin(m); else if (m.type=="target") target_plugin(m); else to_plugin(m); } static void run_core(const vector<message> &vm) { for (auto m : vm) process(m); while (!out_pipes.empty()) { process(in_pipe.blocking_read()); } } int main(int argc, char *argv[]) { setlocale(LC_ALL,""); vector<message> vm; for (int i=1; i<argc-1; i+=2) { if (argv[i]==string("-v") || argv[i]==string("--verbose")) { verbose=true; --i; } else vm.push_back(plugin_adder::create(argv[i],argv[i+1])); } run_core(vm); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "stdafx.h" #include "config.h" #include "WebFrame.h" #include "WebFramePrivate.h" #include "WebView.h" #include "WebHost.h" #include "Document.h" #include "FrameView.h" #include "FrameWin.h" #include "GraphicsContext.h" #include "Page.h" #include "render_frames.h" #include "cairo.h" #include "cairo-win32.h" #include "TransferJob.h" #include <io.h> #include <fcntl.h> #include <direct.h> #include <WinInet.h> using namespace WebCore; namespace WebKit { class WebFramePrivate::WebFrameData { public: WebFrameData() { } ~WebFrameData() { } RefPtr<Frame> frame; RefPtr<FrameView> frameView; WebView* webView; WebHost* m_host;}; WebFramePrivate::WebFramePrivate(char* name, WebView* view, WebHost* host) : d(new WebFramePrivate::WebFrameData) { d->m_host = host; d->webView = view; Page* page = new Page(); Frame* frame = new FrameWin(page, 0, this); d->frame = frame; frame->deref(); // Frames are created with a refcount of 1. Release this ref, since we've assigned it to a RefPtr page->setMainFrame(frame); FrameView* frameView = new FrameView(frame); d->frameView = frameView; frameView->deref(); // FrameViews are created with a refcount of 1. Release this ref, since we've assigned it to a RefPtr d->frame->setView(frameView); d->frameView->setWindowHandle(view->windowHandle()); } WebFramePrivate::~WebFramePrivate() { delete d->frame->page(); delete d; } void WebFramePrivate::loadFilePath(char* path) { char URL[2048]; strcpy(URL, "file://localhost/"); strncat(URL, path, 2020); d->frame->didOpenURL(URL); d->frame->begin(URL); HANDLE fileHandle = CreateFileA(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); bool result = false; DWORD bytesRead = 0; do { const int bufferSize = 8193; char buffer[bufferSize]; result = ReadFile(fileHandle, &buffer, bufferSize - 1, &bytesRead, NULL); buffer[bytesRead] = '\0'; d->frame->write(buffer); // Check for end of file. } while (result && bytesRead); CloseHandle(fileHandle); d->frame->end(); } void WebFramePrivate::loadHTMLString(char *html, char *baseURL) { d->frame->begin(); d->frame->write(html); d->frame->end(); } void WebFramePrivate::openURL(const DeprecatedString& str) { loadURL(str.ascii()); } void WebFramePrivate::submitForm(const String& method, const KURL& url, const FormData* submitFormData) { // FIXME: This is a dumb implementation, doesn't handle subframes, etc. d->frame->didOpenURL(url); d->frame->begin(url); TransferJob* job; if (method == "GET" || !submitFormData) job = new TransferJob(this, method, url); else job = new TransferJob(this, method, url, *submitFormData); job->start(d->frame->document()->docLoader()); if (d->m_host) { DeprecatedCString urlString = url.prettyURL().utf8(); d->m_host->updateLocationBar(urlString); } } void WebFramePrivate::loadURL(const char* URL) { d->frame->didOpenURL(URL); d->frame->begin(URL); WebCore::TransferJob* job = new TransferJob(this, "GET", URL); job->start(d->frame->document()->docLoader()); if (d->m_host) d->m_host->updateLocationBar(URL); } void WebFramePrivate::getURL(char* url, int length) { if (length <= 0) return; *url = 0; DeprecatedCString urlString = d->frame->url().prettyURL().utf8(); const char* srcURL = urlString; if (srcURL) { int srcURLLength = strlen(srcURL); if (length > srcURLLength) strcpy(url, srcURL); } } void WebFramePrivate::reload() { if (!d->frame->url().url().startsWith("javascript:", false)) d->frame->scheduleLocationChange(d->frame->url().url(), d->frame->referrer(), true/*lock history*/, true/*userGesture*/); } void WebFramePrivate::receivedData(WebCore::TransferJob*, const char* data, int length) { d->frame->write(data, length); } void WebFramePrivate::receivedAllData(WebCore::TransferJob* job, WebCore::PlatformData) { d->frame->end(); } void WebFramePrivate::paint() { d->frameView->layout(); PAINTSTRUCT ps; HDC hdc = BeginPaint(d->webView->windowHandle(), &ps); cairo_surface_t* finalSurface = cairo_win32_surface_create(hdc); cairo_surface_t* surface = cairo_surface_create_similar(finalSurface, CAIRO_CONTENT_COLOR_ALPHA, ps.rcPaint.right, ps.rcPaint.bottom); cairo_t* context = cairo_create(surface); GraphicsContext gc(context); IntRect documentDirtyRect = ps.rcPaint; documentDirtyRect.move(d->frameView->contentsX(), d->frameView->contentsY()); // FIXME: We have to set the transform using both cairo and GDI until we use cairo for text. HDC surfaceDC = cairo_win32_surface_get_dc(surface); SaveDC(surfaceDC); OffsetViewportOrgEx(surfaceDC, -d->frameView->contentsX(), -d->frameView->contentsY(), 0); cairo_translate(context, -d->frameView->contentsX(), -d->frameView->contentsY()); d->frame->paint(&gc, documentDirtyRect); RestoreDC(surfaceDC, -1); cairo_destroy(context); context = cairo_create(finalSurface); cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); cairo_set_source_surface(context, surface, 0, 0); cairo_rectangle(context, 0, 0, ps.rcPaint.right, ps.rcPaint.bottom); cairo_fill(context); cairo_destroy(context); cairo_surface_destroy(surface); cairo_surface_destroy(finalSurface); EndPaint(d->webView->windowHandle(), &ps); } WebCore::Frame* WebFramePrivate::impl() { return d->frame.get(); } WebFramePrivate* WebFramePrivate::toPrivate() { return this; } } <commit_msg>2006-05-01 Steve Falkenburg <[email protected]><commit_after>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "stdafx.h" #include "config.h" #include "WebFrame.h" #include "WebFramePrivate.h" #include "WebView.h" #include "WebHost.h" #include "Document.h" #include "FrameView.h" #include "FrameWin.h" #include "GraphicsContext.h" #include "Page.h" #include "render_frames.h" #include "cairo.h" #include "cairo-win32.h" #include "TransferJob.h" #include <io.h> #include <fcntl.h> #include <direct.h> #include <WinInet.h> using namespace WebCore; namespace WebKit { class WebFramePrivate::WebFrameData { public: WebFrameData() { } ~WebFrameData() { } RefPtr<Frame> frame; RefPtr<FrameView> frameView; WebView* webView; WebHost* m_host; }; WebFramePrivate::WebFramePrivate(char* name, WebView* view, WebHost* host) : d(new WebFramePrivate::WebFrameData) { d->m_host = host; d->webView = view; Page* page = new Page(); Frame* frame = new FrameWin(page, 0, this); d->frame = frame; frame->deref(); // Frames are created with a refcount of 1. Release this ref, since we've assigned it to a RefPtr page->setMainFrame(frame); FrameView* frameView = new FrameView(frame); d->frameView = frameView; frameView->deref(); // FrameViews are created with a refcount of 1. Release this ref, since we've assigned it to a RefPtr d->frame->setView(frameView); d->frameView->setWindowHandle(view->windowHandle()); } WebFramePrivate::~WebFramePrivate() { delete d->frame->page(); delete d; } void WebFramePrivate::loadFilePath(char* path) { char URL[2048]; strcpy(URL, "file://localhost/"); strncat(URL, path, 2020); d->frame->didOpenURL(URL); d->frame->begin(URL); HANDLE fileHandle = CreateFileA(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); bool result = false; DWORD bytesRead = 0; do { const int bufferSize = 8193; char buffer[bufferSize]; result = ReadFile(fileHandle, &buffer, bufferSize - 1, &bytesRead, NULL); buffer[bytesRead] = '\0'; d->frame->write(buffer); // Check for end of file. } while (result && bytesRead); CloseHandle(fileHandle); d->frame->end(); } void WebFramePrivate::loadHTMLString(char *html, char *baseURL) { d->frame->begin(); d->frame->write(html); d->frame->end(); } void WebFramePrivate::openURL(const DeprecatedString& str) { loadURL(str.ascii()); } void WebFramePrivate::submitForm(const String& method, const KURL& url, const FormData* submitFormData) { // FIXME: This is a dumb implementation, doesn't handle subframes, etc. d->frame->didOpenURL(url); d->frame->begin(url); TransferJob* job; if (method == "GET" || !submitFormData) job = new TransferJob(this, method, url); else job = new TransferJob(this, method, url, *submitFormData); job->start(d->frame->document()->docLoader()); if (d->m_host) { DeprecatedCString urlString = url.prettyURL().utf8(); d->m_host->updateLocationBar(urlString); } } void WebFramePrivate::loadURL(const char* URL) { d->frame->didOpenURL(URL); d->frame->begin(URL); WebCore::TransferJob* job = new TransferJob(this, "GET", URL); job->start(d->frame->document()->docLoader()); if (d->m_host) d->m_host->updateLocationBar(URL); } void WebFramePrivate::getURL(char* url, int length) { if (length <= 0) return; *url = 0; DeprecatedCString urlString = d->frame->url().prettyURL().utf8(); const char* srcURL = urlString; if (srcURL) { int srcURLLength = strlen(srcURL); if (length > srcURLLength) strcpy(url, srcURL); } } void WebFramePrivate::reload() { if (!d->frame->url().url().startsWith("javascript:", false)) d->frame->scheduleLocationChange(d->frame->url().url(), d->frame->referrer(), true/*lock history*/, true/*userGesture*/); } void WebFramePrivate::receivedData(WebCore::TransferJob*, const char* data, int length) { d->frame->write(data, length); } void WebFramePrivate::receivedAllData(WebCore::TransferJob* job, WebCore::PlatformData) { d->frame->end(); } void WebFramePrivate::paint() { d->frameView->layout(); PAINTSTRUCT ps; HDC hdc = BeginPaint(d->webView->windowHandle(), &ps); cairo_surface_t* finalSurface = cairo_win32_surface_create(hdc); cairo_surface_t* surface = cairo_surface_create_similar(finalSurface, CAIRO_CONTENT_COLOR_ALPHA, ps.rcPaint.right, ps.rcPaint.bottom); cairo_t* context = cairo_create(surface); GraphicsContext gc(context); IntRect documentDirtyRect = ps.rcPaint; documentDirtyRect.move(d->frameView->contentsX(), d->frameView->contentsY()); // FIXME: We have to set the transform using both cairo and GDI until we use cairo for text. HDC surfaceDC = cairo_win32_surface_get_dc(surface); SaveDC(surfaceDC); OffsetViewportOrgEx(surfaceDC, -d->frameView->contentsX(), -d->frameView->contentsY(), 0); cairo_translate(context, -d->frameView->contentsX(), -d->frameView->contentsY()); d->frame->paint(&gc, documentDirtyRect); RestoreDC(surfaceDC, -1); cairo_destroy(context); context = cairo_create(finalSurface); cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); cairo_set_source_surface(context, surface, 0, 0); cairo_rectangle(context, 0, 0, ps.rcPaint.right, ps.rcPaint.bottom); cairo_fill(context); cairo_destroy(context); cairo_surface_destroy(surface); cairo_surface_destroy(finalSurface); EndPaint(d->webView->windowHandle(), &ps); } WebCore::Frame* WebFramePrivate::impl() { return d->frame.get(); } WebFramePrivate* WebFramePrivate::toPrivate() { return this; } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Problem2.h" /* https://projecteuler.net/problem=2 Even Fibonacci numbers Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ int Problem2::FibonacciSumEven(int range) { auto sum = 0; if (range >= 2) { sum += 2; } if (range == 8) { sum += 8; } return sum; } int Problem2::Fibonacci(int range) { auto value1 = 1; auto value2 = 2; if (value1 == range || value2 == range) { return range; } return value1 + value2; }<commit_msg>green-commit - Fibonacci_Input4_Returns5<commit_after>#include "stdafx.h" #include "Problem2.h" /* https://projecteuler.net/problem=2 Even Fibonacci numbers Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ int Problem2::FibonacciSumEven(int range) { auto sum = 0; if (range >= 2) { sum += 2; } if (range == 8) { sum += 8; } return sum; } int Problem2::Fibonacci(int range) { auto value1 = 1; auto value2 = 2; if (value1 == range || value2 == range) { return range; } else { auto result = 0; for (size_t i = 2; i < range; i++) { result = value1 + value2; value1 = value2; value2 = result; } return result; } }<|endoftext|>
<commit_before>/* * TICKS algorithms * Author: Frederic Devernay * The goal of this algorithm is to compute the position of ticks on an axis. * the ticks are positioned at multiples of 1 and 5 of powers of 10 */ #include "ticks.h" #include <cmath> #include <cassert> // tick_size_10 // // for a range xmin,xmax drawn with a size range_units (in pixels, or cm...), // find the smallest tick size, which is a multiple of a power of ten, // and is drawn larger than min_tick_size_units (in pixels, or cm...). double ticks_size_10(double xmin, double xmax, double range_units, double min_tick_size_units) { // first, compute the size of min_tick_size_units double min_tick_size = min_tick_size_units * (xmax - xmin) / range_units; int next_p10 = std::ceil( std::log10(min_tick_size) ); double tick_size = std::pow(10.,next_p10); assert(tick_size / 10 < min_tick_size); assert(tick_size >= min_tick_size); return tick_size; } // tick_size // // for a range xmin,xmax drawn with a size range_units (in pixels, or cm...), // find the smallest tick size, which is a multiple of a power of ten or of five times a // power of ten, and is drawn larger than min_tick_size_units (in pixels, or cm...). void ticks_size(double xmin, double xmax, double range_units, double min_tick_size_units, double *t_size, bool* half_tick) { // first, compute the size of min_tick_size_units double min_tick_size = min_tick_size_units * (xmax - xmin) / range_units; int next_p10 = std::ceil( std::log10(min_tick_size) ); *t_size = std::pow(10.,next_p10); assert(*t_size / 10 < min_tick_size); assert(*t_size >= min_tick_size); if (*t_size / 2 >= min_tick_size) { *t_size /= 2; if (half_tick) { *half_tick = true; } } else if (half_tick) { *half_tick = false; } } // ticks_bounds // // Find the index of the first and last tick of width tick_width within the interval xmin,xmax. // if tick_max != 0, an offset is computed to avoid overflow on m1 and m2 // (e.g. if xmin=1+1e-10 and xmax = 1+2e-10). // This offset is computed so that the maximum tick value within the interval is below tick_max. // The tick value represents the "majorness" of a tick (tick values are 1, 5, 10, 50, etc.). // tick_max should be a power of 10. A good value for tick_max is 1000. tick_max should be a multiple of 50 void ticks_bounds(double xmin, double xmax, double tick_width, bool half_tick, int tick_max, double *offset, int* m1, int* m2) { *offset = 0.; assert(tick_max >= 0); if ( (tick_max > 0) && ( (xmin > 0) || (xmax < 0) ) ) { const int h = half_tick ? 2 : 1; const int mult = h * tick_width * tick_max; // make sure offset is outside of the range (xmin,xmax) *offset = mult * ( (xmin > 0) ? std::floor(xmin / mult) : std::ceil(xmax / mult) ); } *m1 = std::ceil( (xmin - *offset) / tick_width ); *m2 = std::floor( (xmax - *offset) / tick_width ); } // ticks_fill // // fill a vector of ticks. // the first element in the vector corresponds to m1, the last to m2. // each value stored in the vector contains the tick size at this index, which can be // 1 (minor tick), 5 (regular tick), 10 (major tick), 50, 100, etc. // // If parameter half_tick is true, this means that the minor tick is actually a half tick, // i.e. five times a power of ten, and the tick sizes are // 1 (half minor tick), 2 (minor tick), 10 (regular tick), 20, 100, etc. // // tick_max is the maximum tick value that may be used, see tick_bounds(). void ticks_fill(bool half_tick, int tick_max, int m1, int m2, std::vector<int>* ticks) { ticks->resize(m2 - m1 + 1); // now all ticks can be obtained by dividing tick_largest by 2, then 5, then 2, then 5, etc. int tick_size = 1; bool multiply_by_two = half_tick; while (tick_size <= tick_max) { int tick_1 = std::ceil(m1 / (double)tick_size) * tick_size; int tick_2 = std::floor(m2 / (double)tick_size) * tick_size; for (int tick = tick_1; tick <= tick_2; tick += tick_size) { assert( tick - m1 >= 0 && tick - m1 < (int)ticks->size() ); (*ticks)[tick - m1] = tick_size; } if (multiply_by_two) { tick_size *= 2; } else { tick_size *= 5; } multiply_by_two = !multiply_by_two; } // last, if 0 is within the interval, give it the value tick_max*10 if ( (m1 <= 0) && (m2 >= 0) ) { (*ticks)[-m1] = 10 * tick_max; } } // compute alpha value for drawing the ticks double ticks_alpha(double min, double max, double val) { assert(val > 0. && min > 0. && max > 0. && max > min); const double alpha = sqrt( (val - min) / (max - min) ); return std::max( 0.,std::min(alpha,1.) ); } <commit_msg>ticks.cpp: fix bug NaN<commit_after>/* * TICKS algorithms * Author: Frederic Devernay * The goal of this algorithm is to compute the position of ticks on an axis. * the ticks are positioned at multiples of 1 and 5 of powers of 10 */ #include "ticks.h" #include <cmath> #include <cassert> // tick_size_10 // // for a range xmin,xmax drawn with a size range_units (in pixels, or cm...), // find the smallest tick size, which is a multiple of a power of ten, // and is drawn larger than min_tick_size_units (in pixels, or cm...). double ticks_size_10(double xmin, double xmax, double range_units, double min_tick_size_units) { // first, compute the size of min_tick_size_units double min_tick_size = min_tick_size_units * (xmax - xmin) / range_units; int next_p10 = std::ceil( std::log10(min_tick_size) ); double tick_size = std::pow(10.,next_p10); assert(tick_size / 10 < min_tick_size); assert(tick_size >= min_tick_size); return tick_size; } // tick_size // // for a range xmin,xmax drawn with a size range_units (in pixels, or cm...), // find the smallest tick size, which is a multiple of a power of ten or of five times a // power of ten, and is drawn larger than min_tick_size_units (in pixels, or cm...). void ticks_size(double xmin, double xmax, double range_units, double min_tick_size_units, double *t_size, bool* half_tick) { // first, compute the size of min_tick_size_units double min_tick_size = min_tick_size_units * (xmax - xmin) / range_units; int next_p10 = std::ceil( std::log10(min_tick_size) ); *t_size = std::pow(10.,next_p10); assert(*t_size / 10 < min_tick_size); assert(*t_size >= min_tick_size); if (*t_size / 2 >= min_tick_size) { *t_size /= 2; if (half_tick) { *half_tick = true; } } else if (half_tick) { *half_tick = false; } } // ticks_bounds // // Find the index of the first and last tick of width tick_width within the interval xmin,xmax. // if tick_max != 0, an offset is computed to avoid overflow on m1 and m2 // (e.g. if xmin=1+1e-10 and xmax = 1+2e-10). // This offset is computed so that the maximum tick value within the interval is below tick_max. // The tick value represents the "majorness" of a tick (tick values are 1, 5, 10, 50, etc.). // tick_max should be a power of 10. A good value for tick_max is 1000. tick_max should be a multiple of 50 void ticks_bounds(double xmin, double xmax, double tick_width, bool half_tick, int tick_max, double *offset, int* m1, int* m2) { *offset = 0.; assert(tick_max >= 0); if ( (tick_max > 0) && ( (xmin > 0) || (xmax < 0) ) ) { const int h = half_tick ? 2 : 1; const int mult = h * tick_width * tick_max; // make sure offset is outside of the range (xmin,xmax) if (mult != 0) { *offset = mult * ( (xmin > 0) ? std::floor(xmin / mult) : std::ceil(xmax / mult) ); } else { *offset = 0; } } *m1 = std::ceil( (xmin - *offset) / tick_width ); *m2 = std::floor( (xmax - *offset) / tick_width ); } // ticks_fill // // fill a vector of ticks. // the first element in the vector corresponds to m1, the last to m2. // each value stored in the vector contains the tick size at this index, which can be // 1 (minor tick), 5 (regular tick), 10 (major tick), 50, 100, etc. // // If parameter half_tick is true, this means that the minor tick is actually a half tick, // i.e. five times a power of ten, and the tick sizes are // 1 (half minor tick), 2 (minor tick), 10 (regular tick), 20, 100, etc. // // tick_max is the maximum tick value that may be used, see tick_bounds(). void ticks_fill(bool half_tick, int tick_max, int m1, int m2, std::vector<int>* ticks) { ticks->resize(m2 - m1 + 1); // now all ticks can be obtained by dividing tick_largest by 2, then 5, then 2, then 5, etc. int tick_size = 1; bool multiply_by_two = half_tick; while (tick_size <= tick_max) { int tick_1 = std::ceil(m1 / (double)tick_size) * tick_size; int tick_2 = std::floor(m2 / (double)tick_size) * tick_size; for (int tick = tick_1; tick <= tick_2; tick += tick_size) { assert( tick - m1 >= 0 && tick - m1 < (int)ticks->size() ); (*ticks)[tick - m1] = tick_size; } if (multiply_by_two) { tick_size *= 2; } else { tick_size *= 5; } multiply_by_two = !multiply_by_two; } // last, if 0 is within the interval, give it the value tick_max*10 if ( (m1 <= 0) && (m2 >= 0) ) { (*ticks)[-m1] = 10 * tick_max; } } // compute alpha value for drawing the ticks double ticks_alpha(double min, double max, double val) { assert(val > 0. && min > 0. && max > 0. && max > min); const double alpha = sqrt( (val - min) / (max - min) ); return std::max( 0.,std::min(alpha,1.) ); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // FILE: MCCDAQ.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Measurement Computing DAQ Adapter // COPYRIGHT: University of California, Berkeley, 2013 // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // AUTHOR: Matthew Bakalar, [email protected], 08/22/2013 // // #include "MCCDAQ.h" #include "../../MMDevice/ModuleInterface.h" #include "cbw.h" #include <sstream> const int BOARDREADY = 100; /* MCCDaq board handle */ typedef struct tag_board { int initialized; /* board has been initialized == BOARDREADY */ int board_num; /* board number */ int analog_range; /* voltage range for analog output */ int status; /* board error status */ } MCCBoard; static MCCBoard board; const int NUM_CHANNELS = 8; inline std::string DeviceNameMCCShutter(int channel) { std::ostringstream chanStrm; chanStrm << channel; return "MCC-Shutter-" + chanStrm.str(); } inline std::string DeviceNameMCCDA(int channel) { std::ostringstream chanStrm; chanStrm << channel; return "MCC-DAC-" + chanStrm.str(); } const char* g_volts = "Volts"; const char* g_PropertyMin = "MinV"; const char* g_PropertyMax = "MaxV"; // Global state of the shutter to enable simulation of the shutter device. // The virtual shutter device uses this global variable to restore state of the switch unsigned g_shutterState = 0; using namespace std; /* * Initilize the global board handle */ int InitializeTheBoard() { if (board.initialized == BOARDREADY) return DEVICE_OK; // initialize the board. Use board number 0 // #TODO Load board number, voltage range as a parameter board.board_num = 0; board.analog_range = UNI5VOLTS; board.initialized = BOARDREADY; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { for (int i = 0; i < NUM_CHANNELS; i++) { std::ostringstream chanStrm; chanStrm << i; RegisterDevice(DeviceNameMCCShutter(i).c_str(), MM::ShutterDevice, ("MCC DAQ Shutter " + chanStrm.str()).c_str()); RegisterDevice(DeviceNameMCCDA(i).c_str(), MM::SignalIODevice, ("MCC DAQ DA " + chanStrm.str()).c_str()); } } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; for (int i = 0; i < NUM_CHANNELS; i++) { if (deviceName == DeviceNameMCCShutter(i)) return new MCCDaqShutter(i, deviceName); if (deviceName == DeviceNameMCCDA(i)) return new MCCDaqDA(i, deviceName); } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // MCCDaqDA implementation // ~~~~~~~~~~~~~~~~~~~~~~ MCCDaqDA::MCCDaqDA(unsigned channel, const char* name) : busy_(false), minV_(0.0), maxV_(0.0), volts_(0.0), gatedVolts_(0.0), encoding_(0), resolution_(0), channel_(channel), name_(name), gateOpen_(true) { InitializeDefaultErrorMessages(); // add custom error messages SetErrorText(ERR_UNKNOWN_POSITION, "Invalid position (state) specified"); SetErrorText(ERR_INITIALIZE_FAILED, "Initialization of the device failed"); SetErrorText(ERR_WRITE_FAILED, "Failed to write data to the device"); SetErrorText(ERR_CLOSE_FAILED, "Failed closing the device"); SetErrorText(BADBOARD, "MCC bad board error"); SetErrorText(BADPORTNUM, "MCC bad port num error"); SetErrorText(BADADCHAN, "Bad AD channel error"); CreateProperty(g_PropertyMin, "0.0", MM::Float, false, 0, true); CreateProperty(g_PropertyMax, "5.0", MM::Float, false, 0, true); } MCCDaqDA::~MCCDaqDA() { Shutdown(); } void MCCDaqDA::GetName(char* name) const { CDeviceUtils::CopyLimitedString(name, name_.c_str()); } int MCCDaqDA::Initialize() { int ret = InitializeTheBoard(); if (ret != DEVICE_OK) return ret; // obtain scaling info minV_ = 0.0; maxV_ = 5.0; // set property list // ----------------- // Name int nRet = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != nRet) return nRet; // Description nRet = CreateProperty(MM::g_Keyword_Description, "MCC DAC driver", MM::String, true); if (DEVICE_OK != nRet) return nRet; // Voltage // ----- CPropertyAction* pAct = new CPropertyAction (this, &MCCDaqDA::OnVolts); nRet = CreateProperty(g_volts, "0.0", MM::Float, false, pAct); if (nRet != DEVICE_OK) return nRet; nRet = GetProperty(g_PropertyMin, minV_); assert (nRet == DEVICE_OK); nRet = GetProperty(g_PropertyMax, maxV_); assert (nRet == DEVICE_OK); nRet = SetPropertyLimits(g_volts, minV_, maxV_); if (nRet != DEVICE_OK) return nRet; nRet = UpdateStatus(); if (nRet != DEVICE_OK) return nRet; initialized_ = true; return DEVICE_OK; } int MCCDaqDA::Shutdown() { initialized_ = false; return DEVICE_OK; } int MCCDaqDA::SetGateOpen(bool open) { gateOpen_ = open; SetVolts(volts_); return DEVICE_OK; } int MCCDaqDA::SetSignal(double volts) { return SetProperty(g_volts, CDeviceUtils::ConvertToString(volts)); } int MCCDaqDA::WriteToPort(unsigned short value) { int ret = cbAOut(board.board_num, channel_, board.analog_range, value); if (ret != NOERRORS) return ret; return DEVICE_OK; } int MCCDaqDA::SetVolts(double volts) { if (volts > maxV_ || volts < minV_) return DEVICE_RANGE_EXCEEDED; volts_ = volts; unsigned short value = (unsigned short) ( (volts/maxV_) * 65535 ); if (!gateOpen_) value = 0; return WriteToPort(value); } int MCCDaqDA::GetLimits(double& minVolts, double& maxVolts) { int nRet = GetProperty(g_PropertyMin, minVolts); if (nRet == DEVICE_OK) return nRet; nRet = GetProperty(g_PropertyMax, maxVolts); if (nRet == DEVICE_OK) return nRet; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int MCCDaqDA::OnVolts(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // nothing to do, let the caller to use cached property } else if (eAct == MM::AfterSet) { double volts; pProp->Get(volts); return SetVolts(volts); } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // MCCDaq implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ MCCDaqShutter::MCCDaqShutter(unsigned channel, const char* name) : initialized_(false), channel_(channel), name_(name), openTimeUs_(0), ports_() { InitializeDefaultErrorMessages(); EnableDelay(); SetErrorText(BADBOARD, "MCC bad board error"); SetErrorText(BADPORTNUM, "MCC bad port num error"); SetErrorText(BADADCHAN, "Bad AD channel error"); } MCCDaqShutter::~MCCDaqShutter() { Shutdown(); } void MCCDaqShutter::GetName(char* name) const { assert(name_.length() < CDeviceUtils::GetMaxStringLength()); CDeviceUtils::CopyLimitedString(name, name_.c_str()); } bool MCCDaqShutter::Busy() { long interval = GetClockTicksUs() - openTimeUs_; if (interval/1000.0 < GetDelayMs() && interval > 0) { return true; } else { return false; } } int MCCDaqShutter::Initialize() { int ret = InitializeTheBoard(); if (ret != DEVICE_OK) return ret; // Define ports for this shutter // #TODO Load port from parameter // ports_.push_back(FIRSTPORTA); ports_.push_back(FIRSTPORTB); // initialize the digital ports as output ports // #TODO Only initialize the needed ports for(unsigned int i=0; i < ports_.size(); i++) { int ret = cbDConfigPort(board.board_num, ports_[i], DIGITALOUT); if (ret != NOERRORS) return ret; } // set property list // ----------------- // Name ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "MCC shutter driver", MM::String, true); if (DEVICE_OK != ret) return ret; // OnOff // ------ CPropertyAction* pAct = new CPropertyAction (this, &MCCDaqShutter::OnOnOff); ret = CreateProperty("OnOff", "0", MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; // set shutter into the off state WriteToPort(0); vector<string> vals; vals.push_back("0"); vals.push_back("1"); ret = SetAllowedValues("OnOff", vals); if (ret != DEVICE_OK) return ret; ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; openTimeUs_ = GetClockTicksUs(); return DEVICE_OK; } int MCCDaqShutter::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } int MCCDaqShutter::SetOpen(bool open) { if (open) return SetProperty("OnOff", "1"); else return SetProperty("OnOff", "0"); } int MCCDaqShutter::GetOpen(bool& open) { char buf[MM::MaxStrLength]; int ret = GetProperty("OnOff", buf); if (ret != DEVICE_OK) return ret; long pos = atol(buf); pos > 0 ? open = true : open = false; return DEVICE_OK; } int MCCDaqShutter::Fire(double /*deltaT*/) { return DEVICE_UNSUPPORTED_COMMAND; } int MCCDaqShutter::WriteToPort(unsigned short value) { for(unsigned int i=0; i < ports_.size(); i++) { int ret = cbDOut(board.board_num, ports_[i], value); if (ret != NOERRORS) return ret; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int MCCDaqShutter::OnOnOff(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // use cached state } else if (eAct == MM::AfterSet) { long pos; pProp->Get(pos); int ret; if (pos == 0) ret = WriteToPort(0); // turn everything off else // ret = WriteToPort(g_switchState); // restore old setting ret = WriteToPort(1 << channel_); if (ret != DEVICE_OK) return ret; g_shutterState = pos; openTimeUs_ = GetClockTicksUs(); } return DEVICE_OK; } <commit_msg>[MCCDAQ] Initialize the board's voltage range based on the configured max voltage<commit_after>/////////////////////////////////////////////////////////////////////////////// // FILE: MCCDAQ.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Measurement Computing DAQ Adapter // COPYRIGHT: University of California, Berkeley, 2013 // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // AUTHOR: Matthew Bakalar, [email protected], 08/22/2013 // // #include "MCCDAQ.h" #include "../../MMDevice/ModuleInterface.h" #include "cbw.h" #include <sstream> const int BOARDREADY = 100; /* MCCDaq board handle */ typedef struct tag_board { int initialized; /* board has been initialized == BOARDREADY */ int board_num; /* board number */ int analog_range; /* voltage range for analog output */ int status; /* board error status */ } MCCBoard; static MCCBoard board; const int NUM_CHANNELS = 8; inline std::string DeviceNameMCCShutter(int channel) { std::ostringstream chanStrm; chanStrm << channel; return "MCC-Shutter-" + chanStrm.str(); } inline std::string DeviceNameMCCDA(int channel) { std::ostringstream chanStrm; chanStrm << channel; return "MCC-DAC-" + chanStrm.str(); } const char* g_volts = "Volts"; const char* g_PropertyMin = "MinV"; const char* g_PropertyMax = "MaxV"; // Global state of the shutter to enable simulation of the shutter device. // The virtual shutter device uses this global variable to restore state of the switch unsigned g_shutterState = 0; using namespace std; /* * Initilize the global board handle * voltMode should be e.g. UNI5VOLTS, UNI10VOLTS, etc. */ int InitializeTheBoard(int voltMode) { if (board.initialized == BOARDREADY) return DEVICE_OK; // initialize the board. Use board number 0 // #TODO Load board number, voltage range as a parameter board.board_num = 0; board.analog_range = voltMode; board.initialized = BOARDREADY; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { for (int i = 0; i < NUM_CHANNELS; i++) { std::ostringstream chanStrm; chanStrm << i; RegisterDevice(DeviceNameMCCShutter(i).c_str(), MM::ShutterDevice, ("MCC DAQ Shutter " + chanStrm.str()).c_str()); RegisterDevice(DeviceNameMCCDA(i).c_str(), MM::SignalIODevice, ("MCC DAQ DA " + chanStrm.str()).c_str()); } } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; for (int i = 0; i < NUM_CHANNELS; i++) { if (deviceName == DeviceNameMCCShutter(i)) return new MCCDaqShutter(i, deviceName); if (deviceName == DeviceNameMCCDA(i)) return new MCCDaqDA(i, deviceName); } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // MCCDaqDA implementation // ~~~~~~~~~~~~~~~~~~~~~~ MCCDaqDA::MCCDaqDA(unsigned channel, const char* name) : busy_(false), minV_(0.0), maxV_(0.0), volts_(0.0), gatedVolts_(0.0), encoding_(0), resolution_(0), channel_(channel), name_(name), gateOpen_(true) { InitializeDefaultErrorMessages(); // add custom error messages SetErrorText(ERR_UNKNOWN_POSITION, "Invalid position (state) specified"); SetErrorText(ERR_INITIALIZE_FAILED, "Initialization of the device failed"); SetErrorText(ERR_WRITE_FAILED, "Failed to write data to the device"); SetErrorText(ERR_CLOSE_FAILED, "Failed closing the device"); SetErrorText(BADBOARD, "MCC bad board error"); SetErrorText(BADPORTNUM, "MCC bad port num error"); SetErrorText(BADADCHAN, "Bad AD channel error"); CreateProperty(g_PropertyMin, "0.0", MM::Float, false, 0, true); CreateProperty(g_PropertyMax, "5.0", MM::Float, false, 0, true); } MCCDaqDA::~MCCDaqDA() { Shutdown(); } void MCCDaqDA::GetName(char* name) const { CDeviceUtils::CopyLimitedString(name, name_.c_str()); } int MCCDaqDA::Initialize() { // obtain scaling info minV_ = 0.0; maxV_ = 5.0; // set property list // ----------------- // Name int nRet = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != nRet) return nRet; // Description nRet = CreateProperty(MM::g_Keyword_Description, "MCC DAC driver", MM::String, true); if (DEVICE_OK != nRet) return nRet; // Voltage // ----- CPropertyAction* pAct = new CPropertyAction (this, &MCCDaqDA::OnVolts); nRet = CreateProperty(g_volts, "0.0", MM::Float, false, pAct); if (nRet != DEVICE_OK) return nRet; nRet = GetProperty(g_PropertyMin, minV_); assert (nRet == DEVICE_OK); nRet = GetProperty(g_PropertyMax, maxV_); assert (nRet == DEVICE_OK); nRet = SetPropertyLimits(g_volts, minV_, maxV_); if (nRet != DEVICE_OK) return nRet; // There are a ton of supported voltage modes, and we can't use a switch // statement because of the floating point nature. This approach involves // a lot of redundant assignments but is straightforward. int voltMode = UNIPT01VOLTS; if (maxV_ > .01) { voltMode = UNIPT02VOLTS; } if (maxV_ > .02) { voltMode = UNIPT05VOLTS; } if (maxV_ > .05) { voltMode = UNIPT1VOLTS; } if (maxV_ > .1) { voltMode = UNIPT2VOLTS; } if (maxV_ > .2) { voltMode = UNIPT25VOLTS; } if (maxV_ > .25) { voltMode = UNIPT5VOLTS; } if (maxV_ > .5) { voltMode = UNI1VOLTS; } if (maxV_ > 1) { voltMode = UNI1PT25VOLTS; } if (maxV_ > 1.25) { voltMode = UNI1PT67VOLTS; } if (maxV_ > 1.67) { voltMode = UNI2VOLTS; } if (maxV_ > 2) { voltMode = UNI2PT5VOLTS; } if (maxV_ > 2.5) { voltMode = UNI4VOLTS; } if (maxV_ > 4) { voltMode = UNI5VOLTS; } if (maxV_ > 5) { voltMode = UNI10VOLTS; } int ret = InitializeTheBoard(voltMode); if (ret != DEVICE_OK) return ret; nRet = UpdateStatus(); if (nRet != DEVICE_OK) return nRet; initialized_ = true; return DEVICE_OK; } int MCCDaqDA::Shutdown() { initialized_ = false; return DEVICE_OK; } int MCCDaqDA::SetGateOpen(bool open) { gateOpen_ = open; SetVolts(volts_); return DEVICE_OK; } int MCCDaqDA::SetSignal(double volts) { return SetProperty(g_volts, CDeviceUtils::ConvertToString(volts)); } int MCCDaqDA::WriteToPort(unsigned short value) { int ret = cbAOut(board.board_num, channel_, board.analog_range, value); if (ret != NOERRORS) return ret; return DEVICE_OK; } int MCCDaqDA::SetVolts(double volts) { if (volts > maxV_ || volts < minV_) return DEVICE_RANGE_EXCEEDED; volts_ = volts; unsigned short value = (unsigned short) ( (volts/maxV_) * 65535 ); if (!gateOpen_) value = 0; return WriteToPort(value); } int MCCDaqDA::GetLimits(double& minVolts, double& maxVolts) { int nRet = GetProperty(g_PropertyMin, minVolts); if (nRet == DEVICE_OK) return nRet; nRet = GetProperty(g_PropertyMax, maxVolts); if (nRet == DEVICE_OK) return nRet; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int MCCDaqDA::OnVolts(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // nothing to do, let the caller to use cached property } else if (eAct == MM::AfterSet) { double volts; pProp->Get(volts); return SetVolts(volts); } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // MCCDaq implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ MCCDaqShutter::MCCDaqShutter(unsigned channel, const char* name) : initialized_(false), channel_(channel), name_(name), openTimeUs_(0), ports_() { InitializeDefaultErrorMessages(); EnableDelay(); SetErrorText(BADBOARD, "MCC bad board error"); SetErrorText(BADPORTNUM, "MCC bad port num error"); SetErrorText(BADADCHAN, "Bad AD channel error"); } MCCDaqShutter::~MCCDaqShutter() { Shutdown(); } void MCCDaqShutter::GetName(char* name) const { assert(name_.length() < CDeviceUtils::GetMaxStringLength()); CDeviceUtils::CopyLimitedString(name, name_.c_str()); } bool MCCDaqShutter::Busy() { long interval = GetClockTicksUs() - openTimeUs_; if (interval/1000.0 < GetDelayMs() && interval > 0) { return true; } else { return false; } } int MCCDaqShutter::Initialize() { int ret = InitializeTheBoard(UNI5VOLTS); if (ret != DEVICE_OK) return ret; // Define ports for this shutter // #TODO Load port from parameter // ports_.push_back(FIRSTPORTA); ports_.push_back(FIRSTPORTB); // initialize the digital ports as output ports // #TODO Only initialize the needed ports for(unsigned int i=0; i < ports_.size(); i++) { int ret = cbDConfigPort(board.board_num, ports_[i], DIGITALOUT); if (ret != NOERRORS) return ret; } // set property list // ----------------- // Name ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "MCC shutter driver", MM::String, true); if (DEVICE_OK != ret) return ret; // OnOff // ------ CPropertyAction* pAct = new CPropertyAction (this, &MCCDaqShutter::OnOnOff); ret = CreateProperty("OnOff", "0", MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; // set shutter into the off state WriteToPort(0); vector<string> vals; vals.push_back("0"); vals.push_back("1"); ret = SetAllowedValues("OnOff", vals); if (ret != DEVICE_OK) return ret; ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; openTimeUs_ = GetClockTicksUs(); return DEVICE_OK; } int MCCDaqShutter::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } int MCCDaqShutter::SetOpen(bool open) { if (open) return SetProperty("OnOff", "1"); else return SetProperty("OnOff", "0"); } int MCCDaqShutter::GetOpen(bool& open) { char buf[MM::MaxStrLength]; int ret = GetProperty("OnOff", buf); if (ret != DEVICE_OK) return ret; long pos = atol(buf); pos > 0 ? open = true : open = false; return DEVICE_OK; } int MCCDaqShutter::Fire(double /*deltaT*/) { return DEVICE_UNSUPPORTED_COMMAND; } int MCCDaqShutter::WriteToPort(unsigned short value) { for(unsigned int i=0; i < ports_.size(); i++) { int ret = cbDOut(board.board_num, ports_[i], value); if (ret != NOERRORS) return ret; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int MCCDaqShutter::OnOnOff(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // use cached state } else if (eAct == MM::AfterSet) { long pos; pProp->Get(pos); int ret; if (pos == 0) ret = WriteToPort(0); // turn everything off else // ret = WriteToPort(g_switchState); // restore old setting ret = WriteToPort(1 << channel_); if (ret != DEVICE_OK) return ret; g_shutterState = pos; openTimeUs_ = GetClockTicksUs(); } return DEVICE_OK; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include "caf/config.hpp" #include <new> #include <memory> #include <ostream> #include <type_traits> #include "caf/unit.hpp" #include "caf/error.hpp" #include "caf/unifyn.hpp" namespace caf { /// Helper class to construct an `expected<T>` that represents no error. /// @relates expected struct no_error_t {}; /// The only instance of ::no_error_t. /// @relates expected constexpr no_error_t no_error = no_error_t{}; /// Represents the result of a computation which can either complete /// successfully with an instance of type `T` or fail with an `error`. /// @tparam T The type of the result. template <typename T> class expected { public: // -- member types ----------------------------------------------------------- using value_type = T; // -- static member variables ------------------------------------------------ /// Stores whether move construct and move assign never throw. static constexpr bool nothrow_move = std::is_nothrow_move_constructible<T>::value && std::is_nothrow_move_assignable<T>::value; /// Stores whether copy construct and copy assign never throw. static constexpr bool nothrow_copy = std::is_nothrow_copy_constructible<T>::value && std::is_nothrow_copy_assignable<T>::value; // -- constructors, destructors, and assignment operators -------------------- template <class U> expected(U x, typename std::enable_if<std::is_convertible<U, T>::value>::type* = nullptr) : engaged_(true) { new (&value_) T(std::move(x)); } expected(T&& x) noexcept(nothrow_move) : engaged_(true) { new (&value_) T(std::move(x)); } expected(const T& x) noexcept(nothrow_copy) : engaged_(true) { new (&value_) T(x); } expected(caf::error e) noexcept : engaged_(false) { new (&error_) caf::error{std::move(e)}; } expected(no_error_t) noexcept : engaged_(false) { new (&error_) caf::error{}; } expected(const expected& other) noexcept(nothrow_copy) { construct(other); } template <class Code, class E = enable_if_has_make_error_t<Code>> expected(Code code) : engaged_(false) { new (&error_) caf::error(make_error(code)); } expected(expected&& other) noexcept(nothrow_move) { construct(std::move(other)); } ~expected() { destroy(); } expected& operator=(const expected& other) noexcept(nothrow_copy) { if (engaged_ && other.engaged_) value_ = other.value_; else if (!engaged_ && !other.engaged_) error_ = other.error_; else { destroy(); construct(other); } return *this; } expected& operator=(expected&& other) noexcept(nothrow_move) { if (engaged_ && other.engaged_) value_ = std::move(other.value_); else if (!engaged_ && !other.engaged_) error_ = std::move(other.error_); else { destroy(); construct(std::move(other)); } return *this; } expected& operator=(const T& x) noexcept(nothrow_copy) { if (engaged_) { value_ = x; } else { destroy(); engaged_ = true; new (&value_) T(x); } return *this; } expected& operator=(T&& x) noexcept(nothrow_move) { if (engaged_) { value_ = std::move(x); } else { destroy(); engaged_ = true; new (&value_) T(std::move(x)); } return *this; } template <class U> typename std::enable_if<std::is_convertible<U, T>::value, expected&>::type operator=(U x) { return *this = T{std::move(x)}; } expected& operator=(caf::error e) noexcept { if (!engaged_) error_ = std::move(e); else { destroy(); engaged_ = false; new (&error_) caf::error(std::move(e)); } return *this; } template <class Code> enable_if_has_make_error_t<Code, expected&> operator=(Code code) { return *this = make_error(code); } // -- modifiers -------------------------------------------------------------- /// @copydoc cvalue T& value() noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue T& operator*() noexcept { return value(); } /// @copydoc cvalue T* operator->() noexcept { return &value(); } /// @copydoc cerror caf::error& error() noexcept { CAF_ASSERT(!engaged_); return error_; } // -- observers -------------------------------------------------------------- /// Returns the contained value. /// @pre `engaged() == true`. const T& cvalue() const noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue const T& value() const noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue const T& operator*() const noexcept { return value(); } /// @copydoc cvalue const T* operator->() const noexcept { return &value(); } /// @copydoc engaged explicit operator bool() const noexcept { return engaged(); } /// Returns `true` if the object holds a value (is engaged). bool engaged() const noexcept { return engaged_; } /// Returns the contained error. /// @pre `engaged() == false`. const caf::error& cerror() const noexcept { CAF_ASSERT(!engaged_); return error_; } /// @copydoc cerror const caf::error& error() const noexcept { CAF_ASSERT(!engaged_); return error_; } private: void construct(expected&& other) noexcept(nothrow_move) { if (other.engaged_) new (&value_) T(std::move(other.value_)); else new (&error_) caf::error(std::move(other.error_)); engaged_ = other.engaged_; } void construct(const expected& other) noexcept(nothrow_copy) { if (other.engaged_) new (&value_) T(other.value_); else new (&error_) caf::error(other.error_); engaged_ = other.engaged_; } void destroy() { if (engaged_) value_.~T(); else error_.~error(); } bool engaged_; union { T value_; caf::error error_; }; }; /// @relates expected template <class T> auto operator==(const expected<T>& x, const expected<T>& y) -> decltype(*x == *y) { return x && y ? *x == *y : (!x && !y ? x.error() == y.error() : false); } /// @relates expected template <class T, class U> auto operator==(const expected<T>& x, const U& y) -> decltype(*x == y) { return x ? *x == y : false; } /// @relates expected template <class T, class U> auto operator==(const T& x, const expected<U>& y) -> decltype(x == *y) { return y == x; } /// @relates expected template <class T> bool operator==(const expected<T>& x, const error& y) { return x ? false : x.error() == y; } /// @relates expected template <class T> bool operator==(const error& x, const expected<T>& y) { return y == x; } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator==(const expected<T>& x, E y) { return x == make_error(y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator==(E x, const expected<T>& y) { return y == make_error(x); } /// @relates expected template <class T> auto operator!=(const expected<T>& x, const expected<T>& y) -> decltype(*x == *y) { return !(x == y); } /// @relates expected template <class T, class U> auto operator!=(const expected<T>& x, const U& y) -> decltype(*x == y) { return !(x == y); } /// @relates expected template <class T, class U> auto operator!=(const T& x, const expected<U>& y) -> decltype(x == *y) { return !(x == y); } /// @relates expected template <class T> bool operator!=(const expected<T>& x, const error& y) { return !(x == y); } /// @relates expected template <class T> bool operator!=(const error& x, const expected<T>& y) { return !(x == y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator!=(const expected<T>& x, E y) { return !(x == y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator!=(E x, const expected<T>& y) { return !(x == y); } /// The pattern `expected<void>` shall be used for functions that may generate /// an error but would otherwise return `bool`. template <> class expected<void> { public: expected() = default; expected(unit_t) noexcept { // nop } expected(no_error_t) noexcept { // nop } expected(caf::error e) noexcept : error_(std::move(e)) { // nop } expected(const expected& other) noexcept : error_(other.error_) { // nop } expected(expected&& other) noexcept : error_(std::move(other.error_)) { // nop } template <class Code, class E = enable_if_has_make_error_t<Code>> expected(Code code) : error_(make_error(code)) { // nop } expected& operator=(const expected& other) = default; expected& operator=(expected&& other) noexcept { error_ = std::move(other.error_); return *this; } explicit operator bool() const { return !error_; } const caf::error& error() const { return error_; } private: caf::error error_; }; /// @relates expected inline bool operator==(const expected<void>& x, const expected<void>& y) { return (x && y) || (!x && !y && x.error() == y.error()); } /// @relates expected inline bool operator!=(const expected<void>& x, const expected<void>& y) { return !(x == y); } template <> class expected<unit_t> : public expected<void> { public: using expected<void>::expected; }; template <class T> std::string to_string(const expected<T>& x) { if (x) return deep_to_string(*x); return "!" + to_string(x.error()); } inline std::string to_string(const expected<void>& x) { if (x) return "unit"; return "!" + to_string(x.error()); } /// @cond PRIVATE /// Assigns the value of `expr` (which must return an `expected`) /// to a new variable named `var` or throws a `std::runtime_error` on error. /// @relates expected /// @experimental #define CAF_EXP_THROW(var, expr) \ auto CAF_UNIFYN(tmp_var_) = expr; \ if (!CAF_UNIFYN(tmp_var_)) \ CAF_RAISE_ERROR(to_string(CAF_UNIFYN(tmp_var_).error())); \ auto& var = *CAF_UNIFYN(tmp_var_) /// @endcond } // namespace caf namespace std { template <class T> auto operator<<(ostream& oss, const caf::expected<T>& x) -> decltype(oss << *x) { if (x) oss << *x; else oss << "!" << to_string(x.error()); return oss; } } // namespace std <commit_msg>Add missing include<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include "caf/config.hpp" #include <new> #include <memory> #include <ostream> #include <type_traits> #include "caf/deep_to_string.hpp" #include "caf/error.hpp" #include "caf/unifyn.hpp" #include "caf/unit.hpp" namespace caf { /// Helper class to construct an `expected<T>` that represents no error. /// @relates expected struct no_error_t {}; /// The only instance of ::no_error_t. /// @relates expected constexpr no_error_t no_error = no_error_t{}; /// Represents the result of a computation which can either complete /// successfully with an instance of type `T` or fail with an `error`. /// @tparam T The type of the result. template <typename T> class expected { public: // -- member types ----------------------------------------------------------- using value_type = T; // -- static member variables ------------------------------------------------ /// Stores whether move construct and move assign never throw. static constexpr bool nothrow_move = std::is_nothrow_move_constructible<T>::value && std::is_nothrow_move_assignable<T>::value; /// Stores whether copy construct and copy assign never throw. static constexpr bool nothrow_copy = std::is_nothrow_copy_constructible<T>::value && std::is_nothrow_copy_assignable<T>::value; // -- constructors, destructors, and assignment operators -------------------- template <class U> expected(U x, typename std::enable_if<std::is_convertible<U, T>::value>::type* = nullptr) : engaged_(true) { new (&value_) T(std::move(x)); } expected(T&& x) noexcept(nothrow_move) : engaged_(true) { new (&value_) T(std::move(x)); } expected(const T& x) noexcept(nothrow_copy) : engaged_(true) { new (&value_) T(x); } expected(caf::error e) noexcept : engaged_(false) { new (&error_) caf::error{std::move(e)}; } expected(no_error_t) noexcept : engaged_(false) { new (&error_) caf::error{}; } expected(const expected& other) noexcept(nothrow_copy) { construct(other); } template <class Code, class E = enable_if_has_make_error_t<Code>> expected(Code code) : engaged_(false) { new (&error_) caf::error(make_error(code)); } expected(expected&& other) noexcept(nothrow_move) { construct(std::move(other)); } ~expected() { destroy(); } expected& operator=(const expected& other) noexcept(nothrow_copy) { if (engaged_ && other.engaged_) value_ = other.value_; else if (!engaged_ && !other.engaged_) error_ = other.error_; else { destroy(); construct(other); } return *this; } expected& operator=(expected&& other) noexcept(nothrow_move) { if (engaged_ && other.engaged_) value_ = std::move(other.value_); else if (!engaged_ && !other.engaged_) error_ = std::move(other.error_); else { destroy(); construct(std::move(other)); } return *this; } expected& operator=(const T& x) noexcept(nothrow_copy) { if (engaged_) { value_ = x; } else { destroy(); engaged_ = true; new (&value_) T(x); } return *this; } expected& operator=(T&& x) noexcept(nothrow_move) { if (engaged_) { value_ = std::move(x); } else { destroy(); engaged_ = true; new (&value_) T(std::move(x)); } return *this; } template <class U> typename std::enable_if<std::is_convertible<U, T>::value, expected&>::type operator=(U x) { return *this = T{std::move(x)}; } expected& operator=(caf::error e) noexcept { if (!engaged_) error_ = std::move(e); else { destroy(); engaged_ = false; new (&error_) caf::error(std::move(e)); } return *this; } template <class Code> enable_if_has_make_error_t<Code, expected&> operator=(Code code) { return *this = make_error(code); } // -- modifiers -------------------------------------------------------------- /// @copydoc cvalue T& value() noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue T& operator*() noexcept { return value(); } /// @copydoc cvalue T* operator->() noexcept { return &value(); } /// @copydoc cerror caf::error& error() noexcept { CAF_ASSERT(!engaged_); return error_; } // -- observers -------------------------------------------------------------- /// Returns the contained value. /// @pre `engaged() == true`. const T& cvalue() const noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue const T& value() const noexcept { CAF_ASSERT(engaged_); return value_; } /// @copydoc cvalue const T& operator*() const noexcept { return value(); } /// @copydoc cvalue const T* operator->() const noexcept { return &value(); } /// @copydoc engaged explicit operator bool() const noexcept { return engaged(); } /// Returns `true` if the object holds a value (is engaged). bool engaged() const noexcept { return engaged_; } /// Returns the contained error. /// @pre `engaged() == false`. const caf::error& cerror() const noexcept { CAF_ASSERT(!engaged_); return error_; } /// @copydoc cerror const caf::error& error() const noexcept { CAF_ASSERT(!engaged_); return error_; } private: void construct(expected&& other) noexcept(nothrow_move) { if (other.engaged_) new (&value_) T(std::move(other.value_)); else new (&error_) caf::error(std::move(other.error_)); engaged_ = other.engaged_; } void construct(const expected& other) noexcept(nothrow_copy) { if (other.engaged_) new (&value_) T(other.value_); else new (&error_) caf::error(other.error_); engaged_ = other.engaged_; } void destroy() { if (engaged_) value_.~T(); else error_.~error(); } bool engaged_; union { T value_; caf::error error_; }; }; /// @relates expected template <class T> auto operator==(const expected<T>& x, const expected<T>& y) -> decltype(*x == *y) { return x && y ? *x == *y : (!x && !y ? x.error() == y.error() : false); } /// @relates expected template <class T, class U> auto operator==(const expected<T>& x, const U& y) -> decltype(*x == y) { return x ? *x == y : false; } /// @relates expected template <class T, class U> auto operator==(const T& x, const expected<U>& y) -> decltype(x == *y) { return y == x; } /// @relates expected template <class T> bool operator==(const expected<T>& x, const error& y) { return x ? false : x.error() == y; } /// @relates expected template <class T> bool operator==(const error& x, const expected<T>& y) { return y == x; } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator==(const expected<T>& x, E y) { return x == make_error(y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator==(E x, const expected<T>& y) { return y == make_error(x); } /// @relates expected template <class T> auto operator!=(const expected<T>& x, const expected<T>& y) -> decltype(*x == *y) { return !(x == y); } /// @relates expected template <class T, class U> auto operator!=(const expected<T>& x, const U& y) -> decltype(*x == y) { return !(x == y); } /// @relates expected template <class T, class U> auto operator!=(const T& x, const expected<U>& y) -> decltype(x == *y) { return !(x == y); } /// @relates expected template <class T> bool operator!=(const expected<T>& x, const error& y) { return !(x == y); } /// @relates expected template <class T> bool operator!=(const error& x, const expected<T>& y) { return !(x == y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator!=(const expected<T>& x, E y) { return !(x == y); } /// @relates expected template <class T, class E> enable_if_has_make_error_t<E, bool> operator!=(E x, const expected<T>& y) { return !(x == y); } /// The pattern `expected<void>` shall be used for functions that may generate /// an error but would otherwise return `bool`. template <> class expected<void> { public: expected() = default; expected(unit_t) noexcept { // nop } expected(no_error_t) noexcept { // nop } expected(caf::error e) noexcept : error_(std::move(e)) { // nop } expected(const expected& other) noexcept : error_(other.error_) { // nop } expected(expected&& other) noexcept : error_(std::move(other.error_)) { // nop } template <class Code, class E = enable_if_has_make_error_t<Code>> expected(Code code) : error_(make_error(code)) { // nop } expected& operator=(const expected& other) = default; expected& operator=(expected&& other) noexcept { error_ = std::move(other.error_); return *this; } explicit operator bool() const { return !error_; } const caf::error& error() const { return error_; } private: caf::error error_; }; /// @relates expected inline bool operator==(const expected<void>& x, const expected<void>& y) { return (x && y) || (!x && !y && x.error() == y.error()); } /// @relates expected inline bool operator!=(const expected<void>& x, const expected<void>& y) { return !(x == y); } template <> class expected<unit_t> : public expected<void> { public: using expected<void>::expected; }; template <class T> std::string to_string(const expected<T>& x) { if (x) return deep_to_string(*x); return "!" + to_string(x.error()); } inline std::string to_string(const expected<void>& x) { if (x) return "unit"; return "!" + to_string(x.error()); } /// @cond PRIVATE /// Assigns the value of `expr` (which must return an `expected`) /// to a new variable named `var` or throws a `std::runtime_error` on error. /// @relates expected /// @experimental #define CAF_EXP_THROW(var, expr) \ auto CAF_UNIFYN(tmp_var_) = expr; \ if (!CAF_UNIFYN(tmp_var_)) \ CAF_RAISE_ERROR(to_string(CAF_UNIFYN(tmp_var_).error())); \ auto& var = *CAF_UNIFYN(tmp_var_) /// @endcond } // namespace caf namespace std { template <class T> auto operator<<(ostream& oss, const caf::expected<T>& x) -> decltype(oss << *x) { if (x) oss << *x; else oss << "!" << to_string(x.error()); return oss; } } // namespace std <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/detail/uri_impl.hpp" #include "caf/detail/parser/read_uri.hpp" #include "caf/error.hpp" #include "caf/ip_address.hpp" #include "caf/string_algorithms.hpp" namespace caf { namespace detail { // -- constructors, destructors, and assignment operators ---------------------- uri_impl::uri_impl() : rc_(1) { // nop } // -- member variables --------------------------------------------------------- uri_impl uri_impl::default_instance; // -- modifiers ---------------------------------------------------------------- void uri_impl::assemble_str() { add_encoded(scheme); str += ':'; if (authority.empty()) { CAF_ASSERT(!path.empty()); add_encoded(path, true); } else { str += "//"; if (!authority.userinfo.empty()) { add_encoded(authority.userinfo); str += '@'; } auto addr = get_if<ip_address>(&authority.host); if (addr == nullptr) { add_encoded(get<std::string>(authority.host)); } else { str += '['; str += to_string(*addr); str += ']'; } if (authority.port != 0) { str += ':'; str += std::to_string(authority.port); } if (!path.empty()) { addr += '/'; add_encoded(path, true); } } if (!query.empty()) { str += '?'; auto i = query.begin(); auto add_kvp = [&](decltype(*i) kvp) { add_encoded(kvp.first); str += '='; add_encoded(kvp.second); }; add_kvp(*i); ++i; for (; i != query.end(); ++i) { str += '&'; add_kvp(*i); } } if (!fragment.empty()) { str += '#'; add_encoded(fragment); } } void uri_impl::add_encoded(string_view x, bool is_path) { for (auto ch : x) switch (ch) { case '/': if (is_path) { str += ch; break; } // fall through case ' ': case ':': case '?': case '#': case '[': case ']': case '@': case '!': case '$': case '&': case '\'': case '"': case '(': case ')': case '*': case '+': case ',': case ';': case '=': str += '%'; detail::append_hex(str, reinterpret_cast<uint8_t*>(&ch), 1); break; default: str += ch; } } // -- friend functions --------------------------------------------------------- void intrusive_ptr_add_ref(const uri_impl* p) { p->rc_.fetch_add(1, std::memory_order_relaxed); } void intrusive_ptr_release(const uri_impl* p) { if (p->rc_ == 1 || p->rc_.fetch_sub(1, std::memory_order_acq_rel) == 1) delete p; } } // namespace detail } // namespace caf <commit_msg>Fix assembly of the path component<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/detail/uri_impl.hpp" #include "caf/detail/parser/read_uri.hpp" #include "caf/error.hpp" #include "caf/ip_address.hpp" #include "caf/string_algorithms.hpp" namespace caf { namespace detail { // -- constructors, destructors, and assignment operators ---------------------- uri_impl::uri_impl() : rc_(1) { // nop } // -- member variables --------------------------------------------------------- uri_impl uri_impl::default_instance; // -- modifiers ---------------------------------------------------------------- void uri_impl::assemble_str() { add_encoded(scheme); str += ':'; if (authority.empty()) { CAF_ASSERT(!path.empty()); add_encoded(path, true); } else { str += "//"; if (!authority.userinfo.empty()) { add_encoded(authority.userinfo); str += '@'; } auto addr = get_if<ip_address>(&authority.host); if (addr == nullptr) { add_encoded(get<std::string>(authority.host)); } else { str += '['; str += to_string(*addr); str += ']'; } if (authority.port != 0) { str += ':'; str += std::to_string(authority.port); } if (!path.empty()) { str += '/'; add_encoded(path, true); } } if (!query.empty()) { str += '?'; auto i = query.begin(); auto add_kvp = [&](decltype(*i) kvp) { add_encoded(kvp.first); str += '='; add_encoded(kvp.second); }; add_kvp(*i); for (++i; i != query.end(); ++i) { str += '&'; add_kvp(*i); } } if (!fragment.empty()) { str += '#'; add_encoded(fragment); } } void uri_impl::add_encoded(string_view x, bool is_path) { for (auto ch : x) switch (ch) { case '/': if (is_path) { str += ch; break; } // fall through case ' ': case ':': case '?': case '#': case '[': case ']': case '@': case '!': case '$': case '&': case '\'': case '"': case '(': case ')': case '*': case '+': case ',': case ';': case '=': str += '%'; detail::append_hex(str, reinterpret_cast<uint8_t*>(&ch), 1); break; default: str += ch; } } // -- friend functions --------------------------------------------------------- void intrusive_ptr_add_ref(const uri_impl* p) { p->rc_.fetch_add(1, std::memory_order_relaxed); } void intrusive_ptr_release(const uri_impl* p) { if (p->rc_ == 1 || p->rc_.fetch_sub(1, std::memory_order_acq_rel) == 1) delete p; } } // namespace detail } // namespace caf <|endoftext|>
<commit_before>#include "union_storage.h" #include "storage/memstorage.h" #include "storage/capacitor.h" #include "utils/exception.h" #include "utils/locker.h" #include "storage/page_manager.h" #include <cassert> #include <algorithm> using namespace dariadb; using namespace dariadb::storage; class UnionStorage::Private { public: Private(const PageManager::Params&page_storage_params, dariadb::storage::Capacitor::Params cap_params, dariadb::storage::UnionStorage::Limits limits) : mem_storage{ new MemoryStorage(page_storage_params.chunk_size) }, _page_manager_params(page_storage_params), _cap_params(cap_params), _limits(limits) { dariadb::storage::ChunkPool::instance()->start(_limits.max_mem_chunks); mem_cap = new Capacitor(mem_storage, _cap_params); mem_storage_raw = dynamic_cast<MemoryStorage*>(mem_storage.get()); assert(mem_storage_raw != nullptr); PageManager::start(_page_manager_params); auto open_chunks = PageManager::instance()->get_open_chunks(); mem_storage_raw->append(open_chunks); } ~Private() { this->flush(); if (_limits.max_mem_chunks != 0) { auto all_chunks = this->mem_storage_raw->drop_all(); PageManager::instance()->append(all_chunks); //use specified in ctor } delete mem_cap; PageManager::stop(); } Time minTime() { std::lock_guard<std::recursive_mutex> lg(_locker); if(PageManager::instance()->chunks_in_cur_page()>0){ return PageManager::instance()->minTime(); }else{ return mem_storage->minTime(); } } Time maxTime() { return mem_storage->maxTime(); } append_result append(const Meas::PMeas begin, const size_t size) { append_result result{}; for (size_t i = 0; i < size; i++) { result = result + this->append(begin[i]); } return result; } append_result append(const Meas &value) { //std::lock_guard<std::mutex> lg(_locker); append_result result{}; if (!mem_cap->append(value)){ //if(mem_storage_raw->append(value).writed!=1){ assert(false); result.ignored++; } else { result.writed++; } drop_old_chunks(); return result; } void drop_old_chunks() { if (_limits.max_mem_chunks == 0) { if (_limits.old_mem_chunks != 0) { //std::lock_guard<std::mutex> lg(_drop_locker); auto old_chunks = mem_storage_raw->drop_old_chunks(_limits.old_mem_chunks); PageManager::instance()->append(old_chunks); } } else { //std::lock_guard<std::mutex> lg(_drop_locker); auto old_chunks = mem_storage_raw->drop_old_chunks_by_limit(_limits.max_mem_chunks); #ifdef DEBUG for(auto c:old_chunks){ assert(c->_buffer_t.size()!=0); } #endif PageManager::instance()->append(old_chunks); } } void subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) { mem_storage->subscribe(ids, flag, clbk); } Reader_ptr currentValue(const IdArray&ids, const Flag& flag) { return mem_storage->currentValue(ids, flag); } void flush() { std::lock_guard<std::recursive_mutex> lg(_locker); this->mem_cap->flush(); this->drop_old_chunks(); PageManager::instance()->flush(); } UnionStorage::QueueSizes queue_size() const { QueueSizes result; result.page = PageManager::instance()->in_queue_size(); result.mem = this->mem_storage_raw->queue_size(); result.cap = this->mem_cap->size(); return result; } class UnionCursor : public Cursor { public: Cursor_ptr _page_cursor; Cursor_ptr _mem_cursor; UnionCursor(Cursor_ptr &page_cursor, Cursor_ptr&mem_cursor): _page_cursor{page_cursor}, _mem_cursor(mem_cursor) { this->reset_pos(); } ~UnionCursor() { _page_cursor = nullptr; _mem_cursor = nullptr; } bool is_end()const override { return (_page_cursor==nullptr?true:_page_cursor->is_end()) && (_mem_cursor==nullptr?true:_mem_cursor->is_end()); } void readNext(Cursor::Callback*cbk) override { if (!is_end()) { if ((_page_cursor!=nullptr) && (!_page_cursor->is_end())) { _page_cursor->readNext(cbk); return; } else { if ((_mem_cursor!=nullptr)&&(!_mem_cursor->is_end())) { _mem_cursor->readNext(cbk); return; } } } } void reset_pos() override { if (_page_cursor != nullptr) { _page_cursor->reset_pos(); } if (_mem_cursor != nullptr) { _mem_cursor->reset_pos(); } } }; class UnionCursorSet : public Cursor { public: CursorList _cursors; CursorList::iterator it; bool _is_end; UnionCursorSet() { } ~UnionCursorSet() { _cursors.clear(); } void add_cursor(const Cursor_ptr &cptr) { _cursors.push_back(cptr); reset_pos(); } bool is_end()const override { return _is_end; } void readNext(Cursor::Callback*cbk) override { if (it == _cursors.end()) { _is_end = true; } else { Cursor_ptr c = *it; if (c->is_end()) {//TODO refact. if (it == _cursors.end()) { _is_end = true; Chunk_Ptr empty; cbk->call(empty); return; } else { ++it; if (it == _cursors.end()) { _is_end = true; Chunk_Ptr empty; cbk->call(empty); return; } } } c = *it; c->readNext(cbk); } if (_is_end) { Chunk_Ptr empty; cbk->call(empty); } } void reset_pos() override { it = _cursors.begin(); _is_end = false; for (auto&c : _cursors) { c->reset_pos(); } } }; Cursor_ptr chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) { std::lock_guard<std::recursive_mutex> lg(_locker); IdArray id_a = ids; if (id_a.empty()) { id_a = getIds(); } UnionCursorSet *raw_result = new UnionCursorSet(); Cursor_ptr result{ raw_result }; for (auto id : id_a) { IdArray cur_ids(1); cur_ids[0] = id; Cursor_ptr page_chunks, mem_chunks; dariadb::Time minT, maxT; if (!mem_storage_raw->minMaxTime(id, &minT, &maxT)) { page_chunks = PageManager::instance()->chunksByIterval(cur_ids, flag, from, to); } else { if (minT <= from && maxT >= to) { mem_chunks = mem_storage_raw->chunksByIterval(cur_ids, flag, from, to); } else { page_chunks = PageManager::instance()->chunksByIterval(cur_ids, flag, from, PageManager::instance()->maxTime()); mem_chunks = mem_storage_raw->chunksByIterval(cur_ids, flag, minT, to); } } Cursor_ptr sub_result{ new UnionCursor{page_chunks,mem_chunks} }; raw_result->add_cursor(sub_result); } return result; } IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) { std::lock_guard<std::recursive_mutex> lg(_locker); IdArray id_a = ids; if (id_a.empty()) { id_a = getIds(); } IdToChunkMap result; for(auto id:id_a){ dariadb::Time minT, maxT; IdToChunkMap subRes; if (!mem_storage_raw->minMaxTime(id, &minT, &maxT)) { subRes = PageManager::instance()->chunksBeforeTimePoint(ids, flag, timePoint); }else{ if (minT <= timePoint) { subRes = mem_storage_raw->chunksBeforeTimePoint(ids, flag, timePoint); } else { subRes=PageManager::instance()->chunksBeforeTimePoint(ids, flag, timePoint); } } for(auto kv:subRes){ result[kv.first]=kv.second; } } return result; } bool minMaxTime(dariadb::Id id, dariadb::Time*minResult, dariadb::Time*maxResult) { dariadb::Time subMin1, subMax1; auto pr = PageManager::instance()->minMaxTime(id, &subMin1, &subMax1); dariadb::Time subMin2, subMax2; auto mr = mem_storage_raw->minMaxTime(id, &subMin2, &subMax2); if (!pr) { *minResult = subMin2; *maxResult = subMax2; return mr; } if (!mr) { *minResult = subMin1; *maxResult = subMax1; return pr; } *minResult = std::min(subMin1, subMin2); *maxResult = std::max(subMax1, subMax2); return true; } IdArray getIds() { std::lock_guard<std::recursive_mutex> lg(_locker); auto page_ids = PageManager::instance()->getIds(); auto mem_ids = mem_storage_raw->getIds(); dariadb::IdSet s; for (auto v : page_ids) { s.insert(v); } for (auto v : mem_ids) { s.insert(v); } return dariadb::IdArray{ s.begin(),s.end() }; } size_t chunks_in_memory()const{ std::lock_guard<std::recursive_mutex> lg(_locker); return mem_storage_raw->chunks_total_size(); } storage::BaseStorage_ptr mem_storage; storage::MemoryStorage* mem_storage_raw; storage::Capacitor* mem_cap; storage::PageManager::Params _page_manager_params; dariadb::storage::Capacitor::Params _cap_params; dariadb::storage::UnionStorage::Limits _limits; mutable std::recursive_mutex _locker, _drop_locker; }; UnionStorage::UnionStorage(storage::PageManager::Params page_manager_params, dariadb::storage::Capacitor::Params cap_params, const dariadb::storage::UnionStorage::Limits&limits): _impl{ new UnionStorage::Private(page_manager_params, cap_params, limits) } { } UnionStorage::~UnionStorage() { _impl=nullptr; } Time UnionStorage::minTime() { return _impl->minTime(); } Time UnionStorage::maxTime() { return _impl->maxTime(); } append_result UnionStorage::append(const Meas::PMeas begin, const size_t size) { return _impl->append(begin, size); } append_result UnionStorage::append(const Meas &value) { return _impl->append(value); } void UnionStorage::subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) { _impl->subscribe(ids, flag, clbk); } Reader_ptr UnionStorage::currentValue(const IdArray&ids, const Flag& flag) { return _impl->currentValue(ids, flag); } void UnionStorage::flush() { _impl->flush(); } bool UnionStorage::minMaxTime(dariadb::Id id, dariadb::Time*minResult, dariadb::Time*maxResult) { return _impl->minMaxTime(id, minResult, maxResult); } Cursor_ptr UnionStorage::chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) { return _impl->chunksByIterval(ids, flag, from, to); } IdToChunkMap UnionStorage::chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) { return _impl->chunksBeforeTimePoint(ids, flag, timePoint); } IdArray UnionStorage::getIds() { return _impl->getIds(); } size_t UnionStorage::chunks_in_memory()const{ return _impl->chunks_in_memory(); } UnionStorage::QueueSizes UnionStorage::queue_size() const{ return _impl->queue_size(); } <commit_msg>US: chunkBefore alg change.<commit_after>#include "union_storage.h" #include "storage/memstorage.h" #include "storage/capacitor.h" #include "utils/exception.h" #include "utils/locker.h" #include "storage/page_manager.h" #include <cassert> #include <algorithm> using namespace dariadb; using namespace dariadb::storage; class UnionStorage::Private { public: Private(const PageManager::Params&page_storage_params, dariadb::storage::Capacitor::Params cap_params, dariadb::storage::UnionStorage::Limits limits) : mem_storage{ new MemoryStorage(page_storage_params.chunk_size) }, _page_manager_params(page_storage_params), _cap_params(cap_params), _limits(limits) { dariadb::storage::ChunkPool::instance()->start(_limits.max_mem_chunks); mem_cap = new Capacitor(mem_storage, _cap_params); mem_storage_raw = dynamic_cast<MemoryStorage*>(mem_storage.get()); assert(mem_storage_raw != nullptr); PageManager::start(_page_manager_params); auto open_chunks = PageManager::instance()->get_open_chunks(); mem_storage_raw->append(open_chunks); } ~Private() { this->flush(); if (_limits.max_mem_chunks != 0) { auto all_chunks = this->mem_storage_raw->drop_all(); PageManager::instance()->append(all_chunks); //use specified in ctor } delete mem_cap; PageManager::stop(); } Time minTime() { std::lock_guard<std::recursive_mutex> lg(_locker); if(PageManager::instance()->chunks_in_cur_page()>0){ return PageManager::instance()->minTime(); }else{ return mem_storage->minTime(); } } Time maxTime() { return mem_storage->maxTime(); } append_result append(const Meas::PMeas begin, const size_t size) { append_result result{}; for (size_t i = 0; i < size; i++) { result = result + this->append(begin[i]); } return result; } append_result append(const Meas &value) { //std::lock_guard<std::mutex> lg(_locker); append_result result{}; if (!mem_cap->append(value)){ //if(mem_storage_raw->append(value).writed!=1){ assert(false); result.ignored++; } else { result.writed++; } drop_old_chunks(); return result; } void drop_old_chunks() { if (_limits.max_mem_chunks == 0) { if (_limits.old_mem_chunks != 0) { //std::lock_guard<std::mutex> lg(_drop_locker); auto old_chunks = mem_storage_raw->drop_old_chunks(_limits.old_mem_chunks); PageManager::instance()->append(old_chunks); } } else { //std::lock_guard<std::mutex> lg(_drop_locker); auto old_chunks = mem_storage_raw->drop_old_chunks_by_limit(_limits.max_mem_chunks); #ifdef DEBUG for(auto c:old_chunks){ assert(c->_buffer_t.size()!=0); } #endif PageManager::instance()->append(old_chunks); } } void subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) { mem_storage->subscribe(ids, flag, clbk); } Reader_ptr currentValue(const IdArray&ids, const Flag& flag) { return mem_storage->currentValue(ids, flag); } void flush() { std::lock_guard<std::recursive_mutex> lg(_locker); this->mem_cap->flush(); this->drop_old_chunks(); PageManager::instance()->flush(); } UnionStorage::QueueSizes queue_size() const { QueueSizes result; result.page = PageManager::instance()->in_queue_size(); result.mem = this->mem_storage_raw->queue_size(); result.cap = this->mem_cap->size(); return result; } class UnionCursor : public Cursor { public: Cursor_ptr _page_cursor; Cursor_ptr _mem_cursor; UnionCursor(Cursor_ptr &page_cursor, Cursor_ptr&mem_cursor): _page_cursor{page_cursor}, _mem_cursor(mem_cursor) { this->reset_pos(); } ~UnionCursor() { _page_cursor = nullptr; _mem_cursor = nullptr; } bool is_end()const override { return (_page_cursor==nullptr?true:_page_cursor->is_end()) && (_mem_cursor==nullptr?true:_mem_cursor->is_end()); } void readNext(Cursor::Callback*cbk) override { if (!is_end()) { if ((_page_cursor!=nullptr) && (!_page_cursor->is_end())) { _page_cursor->readNext(cbk); return; } else { if ((_mem_cursor!=nullptr)&&(!_mem_cursor->is_end())) { _mem_cursor->readNext(cbk); return; } } } } void reset_pos() override { if (_page_cursor != nullptr) { _page_cursor->reset_pos(); } if (_mem_cursor != nullptr) { _mem_cursor->reset_pos(); } } }; class UnionCursorSet : public Cursor { public: CursorList _cursors; CursorList::iterator it; bool _is_end; UnionCursorSet() { } ~UnionCursorSet() { _cursors.clear(); } void add_cursor(const Cursor_ptr &cptr) { _cursors.push_back(cptr); reset_pos(); } bool is_end()const override { return _is_end; } void readNext(Cursor::Callback*cbk) override { if (it == _cursors.end()) { _is_end = true; } else { Cursor_ptr c = *it; if (c->is_end()) {//TODO refact. if (it == _cursors.end()) { _is_end = true; Chunk_Ptr empty; cbk->call(empty); return; } else { ++it; if (it == _cursors.end()) { _is_end = true; Chunk_Ptr empty; cbk->call(empty); return; } } } c = *it; c->readNext(cbk); } if (_is_end) { Chunk_Ptr empty; cbk->call(empty); } } void reset_pos() override { it = _cursors.begin(); _is_end = false; for (auto&c : _cursors) { c->reset_pos(); } } }; Cursor_ptr chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) { std::lock_guard<std::recursive_mutex> lg(_locker); IdArray id_a = ids; if (id_a.empty()) { id_a = getIds(); } UnionCursorSet *raw_result = new UnionCursorSet(); Cursor_ptr result{ raw_result }; for (auto id : id_a) { IdArray cur_ids(1); cur_ids[0] = id; Cursor_ptr page_chunks, mem_chunks; dariadb::Time minT, maxT; if (!mem_storage_raw->minMaxTime(id, &minT, &maxT)) { page_chunks = PageManager::instance()->chunksByIterval(cur_ids, flag, from, to); } else { if (minT <= from && maxT >= to) { mem_chunks = mem_storage_raw->chunksByIterval(cur_ids, flag, from, to); } else { page_chunks = PageManager::instance()->chunksByIterval(cur_ids, flag, from, PageManager::instance()->maxTime()); mem_chunks = mem_storage_raw->chunksByIterval(cur_ids, flag, minT, to); } } Cursor_ptr sub_result{ new UnionCursor{page_chunks,mem_chunks} }; raw_result->add_cursor(sub_result); } return result; } IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) { std::lock_guard<std::recursive_mutex> lg(_locker); IdArray id_a = ids; if (id_a.empty()) { id_a = getIds(); } IdToChunkMap result; IdArray cur_ids{1}; for(auto id:id_a){ cur_ids[0]=id; dariadb::Time minT, maxT; IdToChunkMap subRes; if (!mem_storage_raw->minMaxTime(id, &minT, &maxT)) { subRes = PageManager::instance()->chunksBeforeTimePoint(cur_ids, flag, timePoint); }else{ if (minT <= timePoint) { subRes = mem_storage_raw->chunksBeforeTimePoint(cur_ids, flag, timePoint); } else { subRes=PageManager::instance()->chunksBeforeTimePoint(cur_ids, flag, timePoint); } } for(auto kv:subRes){ result[kv.first]=kv.second; } } return result; } bool minMaxTime(dariadb::Id id, dariadb::Time*minResult, dariadb::Time*maxResult) { dariadb::Time subMin1, subMax1; auto pr = PageManager::instance()->minMaxTime(id, &subMin1, &subMax1); dariadb::Time subMin2, subMax2; auto mr = mem_storage_raw->minMaxTime(id, &subMin2, &subMax2); if (!pr) { *minResult = subMin2; *maxResult = subMax2; return mr; } if (!mr) { *minResult = subMin1; *maxResult = subMax1; return pr; } *minResult = std::min(subMin1, subMin2); *maxResult = std::max(subMax1, subMax2); return true; } IdArray getIds() { std::lock_guard<std::recursive_mutex> lg(_locker); auto page_ids = PageManager::instance()->getIds(); auto mem_ids = mem_storage_raw->getIds(); dariadb::IdSet s; for (auto v : page_ids) { s.insert(v); } for (auto v : mem_ids) { s.insert(v); } return dariadb::IdArray{ s.begin(),s.end() }; } size_t chunks_in_memory()const{ std::lock_guard<std::recursive_mutex> lg(_locker); return mem_storage_raw->chunks_total_size(); } storage::BaseStorage_ptr mem_storage; storage::MemoryStorage* mem_storage_raw; storage::Capacitor* mem_cap; storage::PageManager::Params _page_manager_params; dariadb::storage::Capacitor::Params _cap_params; dariadb::storage::UnionStorage::Limits _limits; mutable std::recursive_mutex _locker, _drop_locker; }; UnionStorage::UnionStorage(storage::PageManager::Params page_manager_params, dariadb::storage::Capacitor::Params cap_params, const dariadb::storage::UnionStorage::Limits&limits): _impl{ new UnionStorage::Private(page_manager_params, cap_params, limits) } { } UnionStorage::~UnionStorage() { _impl=nullptr; } Time UnionStorage::minTime() { return _impl->minTime(); } Time UnionStorage::maxTime() { return _impl->maxTime(); } append_result UnionStorage::append(const Meas::PMeas begin, const size_t size) { return _impl->append(begin, size); } append_result UnionStorage::append(const Meas &value) { return _impl->append(value); } void UnionStorage::subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) { _impl->subscribe(ids, flag, clbk); } Reader_ptr UnionStorage::currentValue(const IdArray&ids, const Flag& flag) { return _impl->currentValue(ids, flag); } void UnionStorage::flush() { _impl->flush(); } bool UnionStorage::minMaxTime(dariadb::Id id, dariadb::Time*minResult, dariadb::Time*maxResult) { return _impl->minMaxTime(id, minResult, maxResult); } Cursor_ptr UnionStorage::chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) { return _impl->chunksByIterval(ids, flag, from, to); } IdToChunkMap UnionStorage::chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) { return _impl->chunksBeforeTimePoint(ids, flag, timePoint); } IdArray UnionStorage::getIds() { return _impl->getIds(); } size_t UnionStorage::chunks_in_memory()const{ return _impl->chunks_in_memory(); } UnionStorage::QueueSizes UnionStorage::queue_size() const{ return _impl->queue_size(); } <|endoftext|>
<commit_before>/* kopetepassword.cpp - Kopete Password Copyright (c) 2004 by Richard Smith <[email protected]> Kopete (c) 2002-2004 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteuiglobal.h" #include "kopetepassword.h" #include "kopetepassworddialog.h" #include "kopetewalletmanager.h" #include <kwallet.h> #include <qapplication.h> #include <qlabel.h> #include <qlineedit.h> #include <qcheckbox.h> #include <kactivelabel.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <kdialogbase.h> #include <klocale.h> #include <kmessagebox.h> #include <kiconloader.h> #include <kpassdlg.h> /** * Function for symmetrically (en/de)crypting strings for config file, * taken from KMail. * * @author Stefan Taferner <[email protected]> */ static QString cryptStr( const QString &aStr ) { //Once Kopete depends on 3.2 just remove this function and use KStringHandler::obscure QString result; for ( uint i = 0; i < aStr.length(); i++ ) result += ( aStr[ i ].unicode() < 0x20) ? aStr[ i ] : QChar( 0x1001F - aStr[ i ].unicode() ); return result; } class Kopete::Password::Private { public: Private( const QString &group, uint maxLen ) : refCount( 1 ), configGroup( group ), remembered( false ), maximumLength( maxLen ), isWrong( false ) { } Private *incRef() { ++refCount; return this; } void decRef() { if( --refCount == 0 ) delete this; } /** Reference count */ int refCount; /** Group to use for KConfig and KWallet */ const QString configGroup; /** Is the password being remembered? */ bool remembered; /** The current password in the KConfig file, or QString::null if no password there */ QString passwordFromKConfig; /** The maximum length allowed for this password, or -1 if there is no limit */ uint maximumLength; /** Is the current password known to be wrong? */ bool isWrong; /** The cached password */ QString cachedValue; }; /** * Implementation detail of Kopete::Password: manages a single password request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordRequest : public KopetePasswordRequestBase { public: KopetePasswordRequest( QObject *owner, Kopete::Password &pass ) : QObject( owner ), mPassword( pass ), mWallet( 0 ) { } /** * Start the request - ask for the wallet */ void begin() { kdDebug( 14010 ) << k_funcinfo << endl; Kopete::WalletManager::self()->openWallet( this, SLOT( walletReceived( KWallet::Wallet* ) ) ); } void walletReceived( KWallet::Wallet *wallet ) { kdDebug( 14010 ) << k_funcinfo << endl; mWallet = wallet; processRequest(); } /** * Got wallet; now carry out whatever action this request represents */ virtual void processRequest() = 0; void slotOkPressed() {} void slotCancelPressed() {} protected: Kopete::Password mPassword; KWallet::Wallet *mWallet; }; /** * Implementation detail of Kopete::Password: manages a single password retrieval request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordGetRequest : public KopetePasswordRequest { public: KopetePasswordGetRequest( QObject *owner, Kopete::Password &pass ) : KopetePasswordRequest( owner, pass ) { } QString grabPassword() { // Before trying to read from the wallet, check if the config file holds a password. // If so, remove it from the config and set it through KWallet instead. QString pwd; if ( mPassword.d->remembered && !mPassword.d->passwordFromKConfig.isNull() ) { pwd = mPassword.d->passwordFromKConfig; mPassword.set( pwd ); return pwd; } if ( mWallet && mWallet->readPassword( mPassword.d->configGroup, pwd ) == 0 && !pwd.isNull() ) return pwd; if ( mPassword.d->remembered && !mPassword.d->passwordFromKConfig.isNull() ) return mPassword.d->passwordFromKConfig; return QString::null; } void finished( const QString &result ) { mPassword.d->cachedValue = result; emit requestFinished( result ); delete this; } }; class KopetePasswordGetRequestPrompt : public KopetePasswordGetRequest { public: KopetePasswordGetRequestPrompt( QObject *owner, Kopete::Password &pass, const QPixmap &image, const QString &prompt, Kopete::Password::PasswordSource source ) : KopetePasswordGetRequest( owner, pass ), mImage( image ), mPrompt( prompt ), mSource( source ), mView( 0 ) { } void processRequest() { QString result = grabPassword(); if ( mSource == Kopete::Password::FromUser || result.isNull() ) doPasswordDialog( result ); else finished( result ); } void doPasswordDialog( const QString &password ) { kdDebug( 14010 ) << k_funcinfo << endl; KDialogBase *passwdDialog = new KDialogBase( Kopete::UI::Global::mainWidget(), "passwdDialog", true, i18n( "Password Required" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); mView = new KopetePasswordDialog( passwdDialog ); passwdDialog->setMainWidget( mView ); mView->m_text->setText( mPrompt ); mView->m_image->setPixmap( mImage ); mView->m_password->insert( password ); int maxLength = mPassword.maximumLength(); if ( maxLength != 0 ) mView->m_password->setMaxLength( maxLength ); mView->m_password->setFocus(); // FIXME: either document what these are for or remove them - lilac mView->adjustSize(); passwdDialog->adjustSize(); connect( passwdDialog, SIGNAL( okClicked() ), SLOT( slotOkPressed() ) ); connect( passwdDialog, SIGNAL( cancelClicked() ), SLOT( slotCancelPressed() ) ); connect( this, SIGNAL( destroyed() ), passwdDialog, SLOT( deleteLater() ) ); passwdDialog->show(); } void slotOkPressed() { QString result = QString::fromLocal8Bit( mView->m_password->password() ); if ( mView->m_save_passwd->isChecked() ) mPassword.set( result ); finished( result ); } void slotCancelPressed() { finished( QString::null ); } private: QPixmap mImage; QString mPrompt; Kopete::Password::PasswordSource mSource; unsigned int mMaxLength; KopetePasswordDialog *mView; }; class KopetePasswordGetRequestNoPrompt : public KopetePasswordGetRequest { public: KopetePasswordGetRequestNoPrompt( QObject *owner, Kopete::Password &pass ) : KopetePasswordGetRequest( owner, pass ) { } void processRequest() { finished( grabPassword() ); } }; /** * Implementation detail of Kopete::Password: manages a single password change request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordSetRequest : public KopetePasswordRequest { public: KopetePasswordSetRequest( Kopete::Password &pass, const QString &newPass ) : KopetePasswordRequest( 0, pass ), mNewPass( newPass ) { if ( KApplication *app = KApplication::kApplication() ) app->ref(); } ~KopetePasswordSetRequest() { if ( KApplication *app = KApplication::kApplication() ) app->deref(); kdDebug( 14010 ) << k_funcinfo << "job complete" << endl; } void processRequest() { if ( setPassword() ) { mPassword.setWrong( false ); mPassword.d->cachedValue = mNewPass; } delete this; } bool setPassword() { //TODO: refactor this function to remove duplication // and possibly to make it not need to be a friend of Kopete::Password if ( mNewPass.isNull() ) { kdDebug( 14010 ) << k_funcinfo << " clearing password" << endl; mPassword.d->remembered = false; mPassword.d->passwordFromKConfig = QString::null; mPassword.writeConfig(); if ( mWallet ) mWallet->removeEntry( mPassword.d->configGroup ); return true; } kdDebug( 14010 ) << k_funcinfo << " setting password for " << mPassword.d->configGroup << endl; if ( mWallet && mWallet->writePassword( mPassword.d->configGroup, mNewPass ) == 0 ) { mPassword.d->remembered = true; mPassword.d->passwordFromKConfig = QString::null; mPassword.writeConfig(); return true; } if ( KWallet::Wallet::isEnabled() ) { // If we end up here, the wallet is enabled, but failed somehow. // Ask the user what to do now. //NOTE: This will start a nested event loop. However, this is fine; the only code we // call after this point is in Kopete::Password, so as long as we've not been deleted // everything should work out OK. We have no parent QObject, so we should survive. if ( KMessageBox::warningContinueCancel( Kopete::UI::Global::mainWidget(), i18n( "<qt>Kopete is unable to save your password securely in your wallet;<br>" "do you want to save the password in the <b>unsafe</b> configuration file instead?</qt>" ), i18n( "Unable to Store Secure Password" ), KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ) ), QString::fromLatin1( "KWalletFallbackToKConfig" ) ) != KMessageBox::Continue ) { return false; } } mPassword.d->remembered = true; mPassword.d->passwordFromKConfig = mNewPass; mPassword.writeConfig(); return true; } private: QString mNewPass; }; Kopete::Password::Password( const QString &configGroup, uint maximumLength, const char *name ) : QObject( 0, name ), d( new Private( configGroup, maximumLength ) ) { readConfig(); } Kopete::Password::Password( Password &other, const char *name ) : QObject( 0, name ), d( other.d->incRef() ) { } Kopete::Password::~Password() { d->decRef(); } Kopete::Password &Kopete::Password::operator=( Password &other ) { if ( d == other.d ) return *this; d->decRef(); d = other.d->incRef(); return *this; } void Kopete::Password::readConfig() { KConfig *config = KGlobal::config(); config->setGroup( d->configGroup ); QString passwordCrypted = config->readEntry( "Password" ); if ( passwordCrypted.isNull() ) d->passwordFromKConfig = QString::null; else d->passwordFromKConfig = cryptStr( passwordCrypted ); d->remembered = config->readBoolEntry( "RememberPassword", false ); d->isWrong = config->readBoolEntry( "PasswordIsWrong", false ); } void Kopete::Password::writeConfig() { KConfig *config = KGlobal::config(); config->setGroup( d->configGroup ); if ( d->remembered && !d->passwordFromKConfig.isNull() ) config->writeEntry( "Password", cryptStr( d->passwordFromKConfig ) ); else config->deleteEntry( "Password" ); config->writeEntry( "RememberPassword", d->remembered ); config->writeEntry( "PasswordIsWrong", d->isWrong ); } int Kopete::Password::preferredImageSize() { return IconSize(KIcon::Toolbar); } uint Kopete::Password::maximumLength() { return d->maximumLength; } void Kopete::Password::setMaximumLength( uint max ) { d->maximumLength = max; } bool Kopete::Password::isWrong() { return d->isWrong; } void Kopete::Password::setWrong( bool bWrong ) { d->isWrong = bWrong; writeConfig(); if ( bWrong ) d->cachedValue = QString::null; } void Kopete::Password::requestWithoutPrompt( QObject *returnObj, const char *slot ) { KopetePasswordRequest *request = new KopetePasswordGetRequestNoPrompt( returnObj, *this ); // call connect on returnObj so we can still connect if 'slot' is protected/private returnObj->connect( request, SIGNAL( requestFinished( const QString & ) ), slot ); request->begin(); } void Kopete::Password::request( QObject *returnObj, const char *slot, const QPixmap &image, const QString &prompt, Kopete::Password::PasswordSource source ) { KopetePasswordRequest *request = new KopetePasswordGetRequestPrompt( returnObj, *this, image, prompt, source ); returnObj->connect( request, SIGNAL( requestFinished( const QString & ) ), slot ); request->begin(); } QString Kopete::Password::cachedValue() { return d->cachedValue; } void Kopete::Password::set( const QString &pass ) { // if we're being told to forget the password, and we aren't remembering one, // don't try to open the wallet. fixes bug #71804. if ( pass.isNull() && !remembered() ) return; KopetePasswordRequest *request = new KopetePasswordSetRequest( *this, pass ); request->begin(); } bool Kopete::Password::remembered() { return d->remembered; } #include "kopetepassword.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg><commit_after>/* kopetepassword.cpp - Kopete Password Copyright (c) 2004 by Richard Smith <[email protected]> Kopete (c) 2002-2004 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteuiglobal.h" #include "kopetepassword.h" #include "kopetepassworddialog.h" #include "kopetewalletmanager.h" #include <kwallet.h> #include <qapplication.h> #include <qlabel.h> #include <qlineedit.h> #include <qcheckbox.h> #include <kactivelabel.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <kdialogbase.h> #include <klocale.h> #include <kmessagebox.h> #include <kiconloader.h> #include <kpassdlg.h> /** * Function for symmetrically (en/de)crypting strings for config file, * taken from KMail. * * @author Stefan Taferner <[email protected]> */ static QString cryptStr( const QString &aStr ) { //Once Kopete depends on 3.2 just remove this function and use KStringHandler::obscure QString result; for ( uint i = 0; i < aStr.length(); i++ ) result += ( aStr[ i ].unicode() < 0x20) ? aStr[ i ] : QChar( 0x1001F - aStr[ i ].unicode() ); return result; } class Kopete::Password::Private { public: Private( const QString &group, uint maxLen ) : refCount( 1 ), configGroup( group ), remembered( false ), maximumLength( maxLen ), isWrong( false ) { } Private *incRef() { ++refCount; return this; } void decRef() { if( --refCount == 0 ) delete this; } /** Reference count */ int refCount; /** Group to use for KConfig and KWallet */ const QString configGroup; /** Is the password being remembered? */ bool remembered; /** The current password in the KConfig file, or QString::null if no password there */ QString passwordFromKConfig; /** The maximum length allowed for this password, or -1 if there is no limit */ uint maximumLength; /** Is the current password known to be wrong? */ bool isWrong; /** The cached password */ QString cachedValue; }; /** * Implementation detail of Kopete::Password: manages a single password request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordRequest : public KopetePasswordRequestBase { public: KopetePasswordRequest( QObject *owner, Kopete::Password &pass ) : QObject( owner ), mPassword( pass ), mWallet( 0 ) { } /** * Start the request - ask for the wallet */ void begin() { kdDebug( 14010 ) << k_funcinfo << endl; Kopete::WalletManager::self()->openWallet( this, SLOT( walletReceived( KWallet::Wallet* ) ) ); } void walletReceived( KWallet::Wallet *wallet ) { kdDebug( 14010 ) << k_funcinfo << endl; mWallet = wallet; processRequest(); } /** * Got wallet; now carry out whatever action this request represents */ virtual void processRequest() = 0; void slotOkPressed() {} void slotCancelPressed() {} protected: Kopete::Password mPassword; KWallet::Wallet *mWallet; }; /** * Implementation detail of Kopete::Password: manages a single password retrieval request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordGetRequest : public KopetePasswordRequest { public: KopetePasswordGetRequest( QObject *owner, Kopete::Password &pass ) : KopetePasswordRequest( owner, pass ) { } QString grabPassword() { // Before trying to read from the wallet, check if the config file holds a password. // If so, remove it from the config and set it through KWallet instead. QString pwd; if ( mPassword.d->remembered && !mPassword.d->passwordFromKConfig.isNull() ) { pwd = mPassword.d->passwordFromKConfig; mPassword.set( pwd ); return pwd; } if ( mWallet && mWallet->readPassword( mPassword.d->configGroup, pwd ) == 0 && !pwd.isNull() ) return pwd; if ( mPassword.d->remembered && !mPassword.d->passwordFromKConfig.isNull() ) return mPassword.d->passwordFromKConfig; return QString::null; } void finished( const QString &result ) { mPassword.d->cachedValue = result; emit requestFinished( result ); delete this; } }; class KopetePasswordGetRequestPrompt : public KopetePasswordGetRequest { public: KopetePasswordGetRequestPrompt( QObject *owner, Kopete::Password &pass, const QPixmap &image, const QString &prompt, Kopete::Password::PasswordSource source ) : KopetePasswordGetRequest( owner, pass ), mImage( image ), mPrompt( prompt ), mSource( source ), mView( 0 ) { } void processRequest() { QString result = grabPassword(); if ( mSource == Kopete::Password::FromUser || result.isNull() ) doPasswordDialog( result ); else finished( result ); } void doPasswordDialog( const QString &password ) { kdDebug( 14010 ) << k_funcinfo << endl; KDialogBase *passwdDialog = new KDialogBase( Kopete::UI::Global::mainWidget(), "passwdDialog", true, i18n( "Password Required" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); mView = new KopetePasswordDialog( passwdDialog ); passwdDialog->setMainWidget( mView ); mView->m_text->setText( mPrompt ); mView->m_image->setPixmap( mImage ); mView->m_password->insert( password ); int maxLength = mPassword.maximumLength(); if ( maxLength != 0 ) mView->m_password->setMaxPasswordLength( maxLength ); mView->m_password->setFocus(); // FIXME: either document what these are for or remove them - lilac mView->adjustSize(); passwdDialog->adjustSize(); connect( passwdDialog, SIGNAL( okClicked() ), SLOT( slotOkPressed() ) ); connect( passwdDialog, SIGNAL( cancelClicked() ), SLOT( slotCancelPressed() ) ); connect( this, SIGNAL( destroyed() ), passwdDialog, SLOT( deleteLater() ) ); passwdDialog->show(); } void slotOkPressed() { QString result = QString::fromLocal8Bit( mView->m_password->password() ); if ( mView->m_save_passwd->isChecked() ) mPassword.set( result ); finished( result ); } void slotCancelPressed() { finished( QString::null ); } private: QPixmap mImage; QString mPrompt; Kopete::Password::PasswordSource mSource; unsigned int mMaxLength; KopetePasswordDialog *mView; }; class KopetePasswordGetRequestNoPrompt : public KopetePasswordGetRequest { public: KopetePasswordGetRequestNoPrompt( QObject *owner, Kopete::Password &pass ) : KopetePasswordGetRequest( owner, pass ) { } void processRequest() { finished( grabPassword() ); } }; /** * Implementation detail of Kopete::Password: manages a single password change request * @internal * @author Richard Smith <[email protected]> */ class KopetePasswordSetRequest : public KopetePasswordRequest { public: KopetePasswordSetRequest( Kopete::Password &pass, const QString &newPass ) : KopetePasswordRequest( 0, pass ), mNewPass( newPass ) { if ( KApplication *app = KApplication::kApplication() ) app->ref(); } ~KopetePasswordSetRequest() { if ( KApplication *app = KApplication::kApplication() ) app->deref(); kdDebug( 14010 ) << k_funcinfo << "job complete" << endl; } void processRequest() { if ( setPassword() ) { mPassword.setWrong( false ); mPassword.d->cachedValue = mNewPass; } delete this; } bool setPassword() { //TODO: refactor this function to remove duplication // and possibly to make it not need to be a friend of Kopete::Password if ( mNewPass.isNull() ) { kdDebug( 14010 ) << k_funcinfo << " clearing password" << endl; mPassword.d->remembered = false; mPassword.d->passwordFromKConfig = QString::null; mPassword.writeConfig(); if ( mWallet ) mWallet->removeEntry( mPassword.d->configGroup ); return true; } kdDebug( 14010 ) << k_funcinfo << " setting password for " << mPassword.d->configGroup << endl; if ( mWallet && mWallet->writePassword( mPassword.d->configGroup, mNewPass ) == 0 ) { mPassword.d->remembered = true; mPassword.d->passwordFromKConfig = QString::null; mPassword.writeConfig(); return true; } if ( KWallet::Wallet::isEnabled() ) { // If we end up here, the wallet is enabled, but failed somehow. // Ask the user what to do now. //NOTE: This will start a nested event loop. However, this is fine; the only code we // call after this point is in Kopete::Password, so as long as we've not been deleted // everything should work out OK. We have no parent QObject, so we should survive. if ( KMessageBox::warningContinueCancel( Kopete::UI::Global::mainWidget(), i18n( "<qt>Kopete is unable to save your password securely in your wallet;<br>" "do you want to save the password in the <b>unsafe</b> configuration file instead?</qt>" ), i18n( "Unable to Store Secure Password" ), KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ) ), QString::fromLatin1( "KWalletFallbackToKConfig" ) ) != KMessageBox::Continue ) { return false; } } mPassword.d->remembered = true; mPassword.d->passwordFromKConfig = mNewPass; mPassword.writeConfig(); return true; } private: QString mNewPass; }; Kopete::Password::Password( const QString &configGroup, uint maximumLength, const char *name ) : QObject( 0, name ), d( new Private( configGroup, maximumLength ) ) { readConfig(); } Kopete::Password::Password( Password &other, const char *name ) : QObject( 0, name ), d( other.d->incRef() ) { } Kopete::Password::~Password() { d->decRef(); } Kopete::Password &Kopete::Password::operator=( Password &other ) { if ( d == other.d ) return *this; d->decRef(); d = other.d->incRef(); return *this; } void Kopete::Password::readConfig() { KConfig *config = KGlobal::config(); config->setGroup( d->configGroup ); QString passwordCrypted = config->readEntry( "Password" ); if ( passwordCrypted.isNull() ) d->passwordFromKConfig = QString::null; else d->passwordFromKConfig = cryptStr( passwordCrypted ); d->remembered = config->readBoolEntry( "RememberPassword", false ); d->isWrong = config->readBoolEntry( "PasswordIsWrong", false ); } void Kopete::Password::writeConfig() { KConfig *config = KGlobal::config(); config->setGroup( d->configGroup ); if ( d->remembered && !d->passwordFromKConfig.isNull() ) config->writeEntry( "Password", cryptStr( d->passwordFromKConfig ) ); else config->deleteEntry( "Password" ); config->writeEntry( "RememberPassword", d->remembered ); config->writeEntry( "PasswordIsWrong", d->isWrong ); } int Kopete::Password::preferredImageSize() { return IconSize(KIcon::Toolbar); } uint Kopete::Password::maximumLength() { return d->maximumLength; } void Kopete::Password::setMaximumLength( uint max ) { d->maximumLength = max; } bool Kopete::Password::isWrong() { return d->isWrong; } void Kopete::Password::setWrong( bool bWrong ) { d->isWrong = bWrong; writeConfig(); if ( bWrong ) d->cachedValue = QString::null; } void Kopete::Password::requestWithoutPrompt( QObject *returnObj, const char *slot ) { KopetePasswordRequest *request = new KopetePasswordGetRequestNoPrompt( returnObj, *this ); // call connect on returnObj so we can still connect if 'slot' is protected/private returnObj->connect( request, SIGNAL( requestFinished( const QString & ) ), slot ); request->begin(); } void Kopete::Password::request( QObject *returnObj, const char *slot, const QPixmap &image, const QString &prompt, Kopete::Password::PasswordSource source ) { KopetePasswordRequest *request = new KopetePasswordGetRequestPrompt( returnObj, *this, image, prompt, source ); returnObj->connect( request, SIGNAL( requestFinished( const QString & ) ), slot ); request->begin(); } QString Kopete::Password::cachedValue() { return d->cachedValue; } void Kopete::Password::set( const QString &pass ) { // if we're being told to forget the password, and we aren't remembering one, // don't try to open the wallet. fixes bug #71804. if ( pass.isNull() && !remembered() ) return; KopetePasswordRequest *request = new KopetePasswordSetRequest( *this, pass ); request->begin(); } bool Kopete::Password::remembered() { return d->remembered; } #include "kopetepassword.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* LibMary - C++ library for high-performance network servers Copyright (C) 2011 Dmitry Shatrov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <libmary/types.h> #include <unistd.h> #include <errno.h> #include <sys/epoll.h> #include <libmary/util_posix.h> #include <libmary/log.h> #include <libmary/epoll_poll_group.h> namespace M { namespace { LogGroup libMary_logGroup_epoll ("epoll", LogLevel::D); } mt_mutex (mutex) void EpollPollGroup::processPollableDeletionQueue () { PollableDeletionQueue::iter iter (pollable_deletion_queue); while (!pollable_deletion_queue.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_deletion_queue.iter_next (iter); delete pollable_entry; } pollable_deletion_queue.clear (); } mt_throws Result EpollPollGroup::triggerPipeWrite () { return commonTriggerPipeWrite (trigger_pipe [1]); } mt_throws PollGroup::PollableKey EpollPollGroup::addPollable (CbDesc<Pollable> const &pollable, DeferredProcessor::Registration * const ret_reg, bool const activate) { PollableEntry * const pollable_entry = new PollableEntry; logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry, ", " "cb_data: 0x", fmt_hex, (UintPtr) pollable.cb_data); pollable_entry->epoll_poll_group = this; pollable_entry->pollable = pollable; // We're making an unsafe call, assuming that the pollable is available. pollable_entry->fd = pollable->getFd (pollable.cb_data); pollable_entry->valid = true; mutex.lock (); pollable_list.append (pollable_entry); mutex.unlock (); if (activate) { if (!doActivate (pollable_entry)) goto _failure; } if (ret_reg) ret_reg->setDeferredProcessor (&deferred_processor); return pollable_entry; _failure: mutex.lock (); pollable_list.remove (pollable_entry); mutex.unlock (); delete pollable_entry; return NULL; } mt_throws Result EpollPollGroup::doActivate (PollableEntry * const mt_nonnull pollable_entry) { logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); struct epoll_event event; event.events = EPOLLET | EPOLLIN | EPOLLOUT | EPOLLRDHUP; event.data.u64 = 0; // For valgrind. event.data.ptr = pollable_entry; int const res = epoll_ctl (efd, EPOLL_CTL_ADD, pollable_entry->fd, &event); if (res == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); return Result::Failure; } if (res != 0) { exc_throw <InternalException> (InternalException::BackendMalfunction); logE_ (_func, "epoll_ctl(): unexpected return value: ", res); return Result::Failure; } if (!trigger ()) { logE_ (_func, "trigger() failed: ", exc->toString()); return Result::Failure; } return Result::Success; } mt_throws Result EpollPollGroup::activatePollable (PollableKey const mt_nonnull key) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (key); logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); return doActivate (pollable_entry); } void EpollPollGroup::removePollable (PollableKey const mt_nonnull key) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (key); logD_ (_func, "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); { int const res = epoll_ctl (efd, EPOLL_CTL_DEL, pollable_entry->fd, NULL /* event */); if (res == -1) { logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); } else { if (res != 0) logE_ (_func, "epoll_ctl(): unexpected return value: ", res); } } mutex.lock (); pollable_entry->valid = false; pollable_list.remove (pollable_entry); pollable_deletion_queue.append (pollable_entry); mutex.unlock (); } mt_throws Result EpollPollGroup::poll (Uint64 const timeout_microsec) { // logD_ (_func, "timeout: ", timeout_microsec); Time const start_microsec = getTimeMicroseconds (); struct epoll_event events [4096]; for (;;) { Time const cur_microsec = getTimeMicroseconds (); Time const elapsed_microsec = cur_microsec - start_microsec; // logD_ (_func, "start: ", start_microsec, ", cur: ", cur_microsec, ", elapsed: ", elapsed_microsec); int timeout; if (!got_deferred_tasks) { if (timeout_microsec != (Uint64) -1) { if (timeout_microsec > elapsed_microsec) { timeout = (timeout_microsec - elapsed_microsec) / 1000; if (timeout == 0) timeout = 1; } else { timeout = 0; } } else { timeout = -1; } } else { // We've got deferred tasks to process, hence we shouldn't block. timeout = 0; } int const nfds = epoll_wait (efd, events, sizeof (events) / sizeof (events [0]), timeout); if (nfds == -1) { if (errno == EINTR) continue; exc_throw <PosixException> (errno); logE_ (_func, "epoll_wait() failed: ", errnoString (errno)); return Result::Failure; } if (nfds < 0 || (Size) nfds > sizeof (events) / sizeof (events [0])) { logE_ (_func, "epoll_wait(): unexpected return value: ", nfds); return Result::Failure; } got_deferred_tasks = false; if (frontend) frontend.call (frontend->pollIterationBegin); bool trigger_pipe_ready = false; mutex.lock (); block_trigger_pipe = true; if (nfds > 0) { // We keep the mutex locked to ensure that we see valid contents // of PollableEntry objects. for (int i = 0; i < nfds; ++i) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (events [i].data.ptr); uint32_t const epoll_event_flags = events [i].events; Uint32 event_flags = 0; if (pollable_entry == NULL) { // Trigger pipe event. if (epoll_event_flags & EPOLLIN) trigger_pipe_ready = true; if (epoll_event_flags & EPOLLOUT) logW_ (_func, "Unexpected EPOLLOUT event for trigger pipe"); if (epoll_event_flags & EPOLLHUP || epoll_event_flags & EPOLLRDHUP || epoll_event_flags & EPOLLERR) { logE_ (_func, "Trigger pipe error: 0x", fmt_hex, epoll_event_flags); } continue; } // This check is not really necessary, but we have 'mutex' locked anyway. if (pollable_entry->valid) { if (epoll_event_flags & EPOLLIN) event_flags |= PollGroup::Input; if (epoll_event_flags & EPOLLOUT) event_flags |= PollGroup::Output; if (epoll_event_flags & EPOLLHUP || epoll_event_flags & EPOLLRDHUP) { event_flags |= PollGroup::Hup; } if (epoll_event_flags & EPOLLERR) event_flags |= PollGroup::Error; if (event_flags) { pollable_entry->pollable.call_mutex ( pollable_entry->pollable->processEvents, mutex, /* ( */ event_flags /* ) */); } } } // for (;;) - for all fds. } // if (nfds > 0) processPollableDeletionQueue (); mutex.unlock (); bool trigger_break = false; { // Dealing with trigger() logics. // It is important to allow re-triggering the PollGroup before calling // frontend->pollIterationEnd(), so that no trigger requests get lost. if (trigger_pipe_ready) { if (!commonTriggerPipeRead (trigger_pipe [0])) return Result::Failure; } mutex.lock (); // TODO We can keep 'block_trigger_pipe' set till the next call to epoll_wait(). block_trigger_pipe = false; if (triggered) { triggered = false; mutex.unlock (); trigger_break = true; } else { mutex.unlock (); } } if (frontend) { bool extra_iteration_needed = false; frontend.call_ret (&extra_iteration_needed, frontend->pollIterationEnd); if (extra_iteration_needed) got_deferred_tasks = true; } if (deferred_processor.process ()) got_deferred_tasks = true; if (trigger_break) break; if (elapsed_microsec >= timeout_microsec) { // Timeout expired. break; } } // for (;;) return Result::Success; } mt_throws Result EpollPollGroup::trigger () { if (poll_tlocal && poll_tlocal == libMary_getThreadLocal()) return Result::Success; mutex.lock (); triggered = true; if (block_trigger_pipe) { mutex.unlock (); return Result::Success; } mutex.unlock (); return triggerPipeWrite (); } mt_throws Result EpollPollGroup::open () { efd = epoll_create (1 /* size, unused */); if (efd == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_create() failed: ", errnoString (errno)); return Result::Failure; } if (!posix_createNonblockingPipe (&trigger_pipe)) return Result::Failure; { struct epoll_event event; event.events = EPOLLET | EPOLLIN | EPOLLRDHUP; event.data.u64 = 0; // For valgrind. event.data.ptr = NULL; // 'NULL' tells that this is trigger pipe. int const res = epoll_ctl (efd, EPOLL_CTL_ADD, trigger_pipe [0], &event); if (res == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); return Result::Failure; } if (res != 0) { exc_throw <InternalException> (InternalException::BackendMalfunction); logE_ (_func, "epoll_ctl(): unexpected return value: ", res); return Result::Failure; } } return Result::Success; } namespace { void deferred_processor_trigger (void * const active_poll_group_) { ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (active_poll_group_); active_poll_group->trigger (); } DeferredProcessor::Backend deferred_processor_backend = { deferred_processor_trigger }; } EpollPollGroup::EpollPollGroup (Object * const coderef_container) : DependentCodeReferenced (coderef_container), efd (-1), triggered (false), block_trigger_pipe (false), // Initializing to 'true' to process deferred tasks scheduled before we // enter poll() the first time. got_deferred_tasks (true), poll_tlocal (NULL) { trigger_pipe [0] = -1; trigger_pipe [1] = -1; deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> ( &deferred_processor_backend, static_cast <ActivePollGroup*> (this) /* cb_data */, NULL /* coderef_container */)); } EpollPollGroup::~EpollPollGroup () { mutex.lock (); { PollableList::iter iter (pollable_list); while (!pollable_list.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_list.iter_next (iter); delete pollable_entry; } } { PollableDeletionQueue::iter iter (pollable_deletion_queue); while (!pollable_deletion_queue.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_deletion_queue.iter_next (iter); delete pollable_entry; } } mutex.unlock (); if (efd != -1) { for (;;) { int const res = close (efd); if (res == -1) { if (errno == EINTR) continue; logE_ (_func, "close() failed (efd): ", errnoString (errno)); } else if (res != 0) { logE_ (_func, "close() (efd): unexpected return value: ", res); } break; } } for (int i = 0; i < 2; ++i) { if (trigger_pipe [i] != -1) { for (;;) { int const res = close (trigger_pipe [i]); if (res == -1) { if (errno == EINTR) continue; logE_ (_func, "close() failed (trigger_pipe[", i, "]): ", errnoString (errno)); } else if (res != 0) { logE_ (_func, "close(): unexpected return value (trigger_pipe[", i, "]): ", res); } break; } } } } } <commit_msg>trigger() fix for EpollPollGroup<commit_after>/* LibMary - C++ library for high-performance network servers Copyright (C) 2011 Dmitry Shatrov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <libmary/types.h> #include <unistd.h> #include <errno.h> #include <sys/epoll.h> #include <libmary/util_posix.h> #include <libmary/log.h> #include <libmary/epoll_poll_group.h> namespace M { namespace { LogGroup libMary_logGroup_epoll ("epoll", LogLevel::D); } mt_mutex (mutex) void EpollPollGroup::processPollableDeletionQueue () { PollableDeletionQueue::iter iter (pollable_deletion_queue); while (!pollable_deletion_queue.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_deletion_queue.iter_next (iter); delete pollable_entry; } pollable_deletion_queue.clear (); } mt_throws Result EpollPollGroup::triggerPipeWrite () { return commonTriggerPipeWrite (trigger_pipe [1]); } mt_throws PollGroup::PollableKey EpollPollGroup::addPollable (CbDesc<Pollable> const &pollable, DeferredProcessor::Registration * const ret_reg, bool const activate) { PollableEntry * const pollable_entry = new PollableEntry; logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry, ", " "cb_data: 0x", fmt_hex, (UintPtr) pollable.cb_data); pollable_entry->epoll_poll_group = this; pollable_entry->pollable = pollable; // We're making an unsafe call, assuming that the pollable is available. pollable_entry->fd = pollable->getFd (pollable.cb_data); pollable_entry->valid = true; mutex.lock (); pollable_list.append (pollable_entry); mutex.unlock (); if (activate) { if (!doActivate (pollable_entry)) goto _failure; } if (ret_reg) ret_reg->setDeferredProcessor (&deferred_processor); return pollable_entry; _failure: mutex.lock (); pollable_list.remove (pollable_entry); mutex.unlock (); delete pollable_entry; return NULL; } mt_throws Result EpollPollGroup::doActivate (PollableEntry * const mt_nonnull pollable_entry) { logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); struct epoll_event event; event.events = EPOLLET | EPOLLIN | EPOLLOUT | EPOLLRDHUP; event.data.u64 = 0; // For valgrind. event.data.ptr = pollable_entry; int const res = epoll_ctl (efd, EPOLL_CTL_ADD, pollable_entry->fd, &event); if (res == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); return Result::Failure; } if (res != 0) { exc_throw <InternalException> (InternalException::BackendMalfunction); logE_ (_func, "epoll_ctl(): unexpected return value: ", res); return Result::Failure; } if (!trigger ()) { logE_ (_func, "trigger() failed: ", exc->toString()); return Result::Failure; } return Result::Success; } mt_throws Result EpollPollGroup::activatePollable (PollableKey const mt_nonnull key) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (key); logD (epoll, _func, "0x", fmt_hex, (UintPtr) this, ": " "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); return doActivate (pollable_entry); } void EpollPollGroup::removePollable (PollableKey const mt_nonnull key) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (key); logD_ (_func, "pollable_entry: 0x", fmt_hex, (UintPtr) pollable_entry); { int const res = epoll_ctl (efd, EPOLL_CTL_DEL, pollable_entry->fd, NULL /* event */); if (res == -1) { logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); } else { if (res != 0) logE_ (_func, "epoll_ctl(): unexpected return value: ", res); } } mutex.lock (); pollable_entry->valid = false; pollable_list.remove (pollable_entry); pollable_deletion_queue.append (pollable_entry); mutex.unlock (); } mt_throws Result EpollPollGroup::poll (Uint64 const timeout_microsec) { logD (epoll, _func, "timeout: ", timeout_microsec); Time const start_microsec = getTimeMicroseconds (); struct epoll_event events [4096]; for (;;) { Time const cur_microsec = getTimeMicroseconds (); Time const elapsed_microsec = cur_microsec - start_microsec; // logD_ (_func, "start: ", start_microsec, ", cur: ", cur_microsec, ", elapsed: ", elapsed_microsec); int timeout; if (!got_deferred_tasks) { if (timeout_microsec != (Uint64) -1) { if (timeout_microsec > elapsed_microsec) { timeout = (timeout_microsec - elapsed_microsec) / 1000; if (timeout == 0) timeout = 1; } else { timeout = 0; } } else { timeout = -1; } } else { // We've got deferred tasks to process, hence we shouldn't block. timeout = 0; } int const nfds = epoll_wait (efd, events, sizeof (events) / sizeof (events [0]), timeout); if (nfds == -1) { if (errno == EINTR) continue; exc_throw <PosixException> (errno); logE_ (_func, "epoll_wait() failed: ", errnoString (errno)); return Result::Failure; } if (nfds < 0 || (Size) nfds > sizeof (events) / sizeof (events [0])) { logE_ (_func, "epoll_wait(): unexpected return value: ", nfds); return Result::Failure; } got_deferred_tasks = false; if (frontend) frontend.call (frontend->pollIterationBegin); bool trigger_pipe_ready = false; mutex.lock (); block_trigger_pipe = true; if (nfds > 0) { // We keep the mutex locked to ensure that we see valid contents // of PollableEntry objects. for (int i = 0; i < nfds; ++i) { PollableEntry * const pollable_entry = static_cast <PollableEntry*> (events [i].data.ptr); uint32_t const epoll_event_flags = events [i].events; Uint32 event_flags = 0; if (pollable_entry == NULL) { // Trigger pipe event. if (epoll_event_flags & EPOLLIN) trigger_pipe_ready = true; if (epoll_event_flags & EPOLLOUT) logW_ (_func, "Unexpected EPOLLOUT event for trigger pipe"); if (epoll_event_flags & EPOLLHUP || epoll_event_flags & EPOLLRDHUP || epoll_event_flags & EPOLLERR) { logE_ (_func, "Trigger pipe error: 0x", fmt_hex, epoll_event_flags); } continue; } // This check is not really necessary, but we have 'mutex' locked anyway. if (pollable_entry->valid) { if (epoll_event_flags & EPOLLIN) event_flags |= PollGroup::Input; if (epoll_event_flags & EPOLLOUT) event_flags |= PollGroup::Output; if (epoll_event_flags & EPOLLHUP || epoll_event_flags & EPOLLRDHUP) { event_flags |= PollGroup::Hup; } if (epoll_event_flags & EPOLLERR) event_flags |= PollGroup::Error; if (event_flags) { pollable_entry->pollable.call_mutex ( pollable_entry->pollable->processEvents, mutex, /* ( */ event_flags /* ) */); } } } // for (;;) - for all fds. } // if (nfds > 0) processPollableDeletionQueue (); mutex.unlock (); bool trigger_break = false; { // Dealing with trigger() logics. // It is important to allow re-triggering the PollGroup before calling // frontend->pollIterationEnd(), so that no trigger requests get lost. if (trigger_pipe_ready) { if (!commonTriggerPipeRead (trigger_pipe [0])) return Result::Failure; } mutex.lock (); // TODO We can keep 'block_trigger_pipe' set till the next call to epoll_wait(). block_trigger_pipe = false; if (triggered) { triggered = false; mutex.unlock (); trigger_break = true; } else { mutex.unlock (); } } if (frontend) { bool extra_iteration_needed = false; frontend.call_ret (&extra_iteration_needed, frontend->pollIterationEnd); if (extra_iteration_needed) got_deferred_tasks = true; } if (deferred_processor.process ()) got_deferred_tasks = true; if (trigger_break) { logD (epoll, _func, "trigger_break"); break; } if (elapsed_microsec >= timeout_microsec) { // Timeout expired. break; } } // for (;;) return Result::Success; } mt_throws Result EpollPollGroup::trigger () { if (poll_tlocal && poll_tlocal == libMary_getThreadLocal()) { mutex.lock (); triggered = true; mutex.unlock (); return Result::Success; } mutex.lock (); triggered = true; if (block_trigger_pipe) { mutex.unlock (); return Result::Success; } mutex.unlock (); return triggerPipeWrite (); } mt_throws Result EpollPollGroup::open () { efd = epoll_create (1 /* size, unused */); if (efd == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_create() failed: ", errnoString (errno)); return Result::Failure; } if (!posix_createNonblockingPipe (&trigger_pipe)) return Result::Failure; { struct epoll_event event; event.events = EPOLLET | EPOLLIN | EPOLLRDHUP; event.data.u64 = 0; // For valgrind. event.data.ptr = NULL; // 'NULL' tells that this is trigger pipe. int const res = epoll_ctl (efd, EPOLL_CTL_ADD, trigger_pipe [0], &event); if (res == -1) { exc_throw <PosixException> (errno); logE_ (_func, "epoll_ctl() failed: ", errnoString (errno)); return Result::Failure; } if (res != 0) { exc_throw <InternalException> (InternalException::BackendMalfunction); logE_ (_func, "epoll_ctl(): unexpected return value: ", res); return Result::Failure; } } return Result::Success; } namespace { void deferred_processor_trigger (void * const active_poll_group_) { ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (active_poll_group_); active_poll_group->trigger (); } DeferredProcessor::Backend deferred_processor_backend = { deferred_processor_trigger }; } EpollPollGroup::EpollPollGroup (Object * const coderef_container) : DependentCodeReferenced (coderef_container), efd (-1), triggered (false), block_trigger_pipe (false), // Initializing to 'true' to process deferred tasks scheduled before we // enter poll() the first time. got_deferred_tasks (true), poll_tlocal (NULL) { trigger_pipe [0] = -1; trigger_pipe [1] = -1; deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> ( &deferred_processor_backend, static_cast <ActivePollGroup*> (this) /* cb_data */, NULL /* coderef_container */)); } EpollPollGroup::~EpollPollGroup () { mutex.lock (); { PollableList::iter iter (pollable_list); while (!pollable_list.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_list.iter_next (iter); delete pollable_entry; } } { PollableDeletionQueue::iter iter (pollable_deletion_queue); while (!pollable_deletion_queue.iter_done (iter)) { PollableEntry * const pollable_entry = pollable_deletion_queue.iter_next (iter); delete pollable_entry; } } mutex.unlock (); if (efd != -1) { for (;;) { int const res = close (efd); if (res == -1) { if (errno == EINTR) continue; logE_ (_func, "close() failed (efd): ", errnoString (errno)); } else if (res != 0) { logE_ (_func, "close() (efd): unexpected return value: ", res); } break; } } for (int i = 0; i < 2; ++i) { if (trigger_pipe [i] != -1) { for (;;) { int const res = close (trigger_pipe [i]); if (res == -1) { if (errno == EINTR) continue; logE_ (_func, "close() failed (trigger_pipe[", i, "]): ", errnoString (errno)); } else if (res != 0) { logE_ (_func, "close(): unexpected return value (trigger_pipe[", i, "]): ", res); } break; } } } } } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/bitmap_index.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/base.hpp" #include "vast/concept/printable/vast/data.hpp" #include "vast/concept/printable/vast/operator.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/overload.hpp" #include "vast/die.hpp" #include "vast/error.hpp" #include "vast/ewah_bitmap.hpp" #include "vast/ids.hpp" #include "vast/type.hpp" #include "vast/value_index_factory.hpp" #include "vast/view.hpp" #include <caf/deserializer.hpp> #include <caf/error.hpp> #include <caf/expected.hpp> #include <caf/serializer.hpp> #include <caf/settings.hpp> #include <algorithm> #include <memory> #include <type_traits> namespace vast { using value_index_ptr = std::unique_ptr<value_index>; /// An index for a ::value that supports appending and looking up values. /// @warning A lookup result does *not include* `nil` values, regardless of the /// relational operator. Include them requires performing an OR of the result /// and an explit query for nil, e.g., `x != 42 || x == nil`. class value_index { public: value_index(vast::type x, caf::settings opts); virtual ~value_index(); using size_type = typename ids::size_type; /// Appends a data value. /// @param x The data to append to the index. /// @returns `true` if appending succeeded. caf::expected<void> append(data_view x); /// Appends a data value. /// @param x The data to append to the index. /// @param pos The positional identifier of *x*. /// @returns `true` if appending succeeded. caf::expected<void> append(data_view x, id pos); /// Looks up data under a relational operator. If the value to look up is /// `nil`, only `==` and `!=` are valid operations. The concrete index /// type determines validity of other values. /// @param op The relation operator. /// @param x The value to lookup. /// @returns The result of the lookup or an error upon failure. caf::expected<ids> lookup(relational_operator op, data_view x) const; /// Merges another value index with this one. /// @param other The value index to merge. /// @returns `true` on success. //bool merge(const value_index& other); /// Retrieves the ID of the last append operation. /// @returns The largest ID in the index. size_type offset() const; /// @returns the type of the index. const vast::type& type() const; /// @returns the options of the index. const caf::settings& options() const; // -- persistence ----------------------------------------------------------- virtual caf::error serialize(caf::serializer& sink) const; virtual caf::error deserialize(caf::deserializer& source); protected: const ewah_bitmap& mask() const; const ewah_bitmap& none() const; private: virtual bool append_impl(data_view x, id pos) = 0; virtual caf::expected<ids> lookup_impl(relational_operator op, data_view x) const = 0; ewah_bitmap mask_; ///< The position of all values excluding nil. ewah_bitmap none_; ///< The positions of nil values. const vast::type type_; ///< The type of this index. const caf::settings opts_; ///< Runtime context with additional parameters. }; /// @relates value_index caf::error inspect(caf::serializer& sink, const value_index& x); /// @relates value_index caf::error inspect(caf::deserializer& source, value_index& x); /// @relates value_index caf::error inspect(caf::serializer& sink, const value_index_ptr& x); /// @relates value_index caf::error inspect(caf::deserializer& source, value_index_ptr& x); namespace detail { template <class Index, class Sequence> caf::expected<ids> container_lookup_impl(const Index& idx, relational_operator op, const Sequence& xs) { ids result; if (op == in) { result = bitmap{idx.offset(), false}; for (auto x : xs) { auto r = idx.lookup(equal, x); if (r) result |= *r; else return r; if (all<1>(result)) // short-circuit return result; } } else if (op == not_in) { result = bitmap{idx.offset(), true}; for (auto x : xs) { auto r = idx.lookup(equal, x); if (r) result -= *r; else return r; if (all<0>(result)) // short-circuit return result; } } else { return make_error(ec::unsupported_operator, op); } return result; } template <class Index> caf::expected<ids> container_lookup(const Index& idx, relational_operator op, view<vector> xs) { VAST_ASSERT(xs); return container_lookup_impl(idx, op, *xs); } template <class Index> caf::expected<ids> container_lookup(const Index& idx, relational_operator op, view<set> xs) { VAST_ASSERT(xs); return container_lookup_impl(idx, op, *xs); } } // namespace detail /// An index for arithmetic values. template <class T, class Binner = void> class arithmetic_index : public value_index { public: // clang-format off using value_type = std::conditional_t< detail::is_any_v<T, time, duration>, duration::rep, std::conditional_t< detail::is_any_v<T, bool, integer, count, real>, T, std::false_type > >; // clang-format on static_assert(!std::is_same_v<value_type, std::false_type>, "invalid type T for arithmetic_index"); using multi_level_range_coder = multi_level_coder<range_coder<ids>>; // clang-format off using coder_type = std::conditional_t< std::is_same_v<T, bool>, singleton_coder<ids>, multi_level_range_coder >; // clang-format on // clang-format off using binner_type = std::conditional_t< std::is_void_v<Binner>, // Choose a space-efficient binner if none specified. std::conditional_t< detail::is_any_v<T, time, duration>, decimal_binner<9>, // nanoseconds -> seconds std::conditional_t< std::is_same_v<T, real>, precision_binner<10>, // no fractional part identity_binner > >, Binner >; // clang-format on using bitmap_index_type = bitmap_index<value_type, coder_type, binner_type>; /// Constructs an arithmetic index. /// @param t An arithmetic type. /// @param opts Runtime context for index parameterization. explicit arithmetic_index(vast::type t, caf::settings opts = {}) : value_index{std::move(t), std::move(opts)} { if constexpr (std::is_same_v<coder_type, multi_level_range_coder>) { auto i = opts.find("base"); if (i == opts.end()) { // Some early experiments found that 8 yields the best average // performance, presumably because it's a power of 2. bmi_ = bitmap_index_type{base::uniform<64>(8)}; } else { auto str = caf::get<caf::config_value::string>(i->second); auto b = to<base>(str); VAST_ASSERT(b != nullptr); // pre-condition is that this was validated bmi_ = bitmap_index_type{base{std::move(*b)}}; } } } caf::error serialize(caf::serializer& sink) const override { return caf::error::eval([&] { return value_index::serialize(sink); }, [&] { return sink(bmi_); }); } caf::error deserialize(caf::deserializer& source) override { return caf::error::eval([&] { return value_index::deserialize(source); }, [&] { return source(bmi_); }); } private: bool append_impl(data_view d, id pos) override { auto append = [&](auto x) { bmi_.skip(pos - bmi_.size()); bmi_.append(x); return true; }; auto f = detail::overload([&](auto&&) { return false; }, [&](view<bool> x) { return append(x); }, [&](view<integer> x) { return append(x); }, [&](view<count> x) { return append(x); }, [&](view<real> x) { return append(x); }, [&](view<duration> x) { return append(x.count()); }, [&](view<time> x) { return append(x.time_since_epoch().count()); }); return caf::visit(f, d); } caf::expected<ids> lookup_impl(relational_operator op, data_view d) const override { auto f = detail::overload( [&](auto x) -> caf::expected<ids> { return make_error(ec::type_clash, value_type{}, materialize(x)); }, [&](view<bool> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<integer> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<count> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<real> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<duration> x) -> caf::expected<ids> { return bmi_.lookup(op, x.count()); }, [&](view<time> x) -> caf::expected<ids> { return bmi_.lookup(op, x.time_since_epoch().count()); }, [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); }, [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }); return caf::visit(f, d); }; bitmap_index_type bmi_; }; /// An index for strings. class string_index : public value_index { public: /// Constructs a string index. /// @param t An instance of `string_type`. /// @param opts Runtime context for index parameterization. explicit string_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: /// The index which holds each character. using char_bitmap_index = bitmap_index<uint8_t, bitslice_coder<ewah_bitmap>>; /// The index which holds the string length. using length_bitmap_index = bitmap_index<uint32_t, multi_level_coder<range_coder<ids>>>; bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; size_t max_length_; length_bitmap_index length_; std::vector<char_bitmap_index> chars_; }; /// An index for enumerations. class enumeration_index : public value_index { public: using index = bitmap_index<enumeration, equality_coder<ewah_bitmap>>; explicit enumeration_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; index index_; }; /// An index for IP addresses. class address_index : public value_index { public: using byte_index = bitmap_index<uint8_t, bitslice_coder<ewah_bitmap>>; using type_index = bitmap_index<bool, singleton_coder<ewah_bitmap>>; explicit address_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; std::array<byte_index, 16> bytes_; type_index v4_; }; /// An index for subnets. class subnet_index : public value_index { public: using prefix_index = bitmap_index<uint8_t, equality_coder<ewah_bitmap>>; explicit subnet_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; address_index network_; prefix_index length_; }; /// An index for ports. class port_index : public value_index { public: using number_index = bitmap_index< port::number_type, multi_level_coder<range_coder<ewah_bitmap>> >; using protocol_index = bitmap_index< std::underlying_type<port::port_type>::type, equality_coder<ewah_bitmap> >; explicit port_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; number_index num_; protocol_index proto_; }; /// An index for vectors and sets. class sequence_index : public value_index { public: /// Constructs a sequence index of a given type. /// @param t The sequence type. /// @param opts Runtime options for element type construction. explicit sequence_index(vast::type t, caf::settings opts = {}); /// The bitmap index holding the sequence size. using size_bitmap_index = bitmap_index<uint32_t, multi_level_coder<range_coder<ids>>>; caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; std::vector<value_index_ptr> elements_; size_t max_size_; size_bitmap_index size_; vast::type value_type_; }; } // namespace vast <commit_msg>Fix check whether expected<T> holds a value<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/bitmap_index.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/base.hpp" #include "vast/concept/printable/vast/data.hpp" #include "vast/concept/printable/vast/operator.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/overload.hpp" #include "vast/die.hpp" #include "vast/error.hpp" #include "vast/ewah_bitmap.hpp" #include "vast/ids.hpp" #include "vast/type.hpp" #include "vast/value_index_factory.hpp" #include "vast/view.hpp" #include <caf/deserializer.hpp> #include <caf/error.hpp> #include <caf/expected.hpp> #include <caf/serializer.hpp> #include <caf/settings.hpp> #include <algorithm> #include <memory> #include <type_traits> namespace vast { using value_index_ptr = std::unique_ptr<value_index>; /// An index for a ::value that supports appending and looking up values. /// @warning A lookup result does *not include* `nil` values, regardless of the /// relational operator. Include them requires performing an OR of the result /// and an explit query for nil, e.g., `x != 42 || x == nil`. class value_index { public: value_index(vast::type x, caf::settings opts); virtual ~value_index(); using size_type = typename ids::size_type; /// Appends a data value. /// @param x The data to append to the index. /// @returns `true` if appending succeeded. caf::expected<void> append(data_view x); /// Appends a data value. /// @param x The data to append to the index. /// @param pos The positional identifier of *x*. /// @returns `true` if appending succeeded. caf::expected<void> append(data_view x, id pos); /// Looks up data under a relational operator. If the value to look up is /// `nil`, only `==` and `!=` are valid operations. The concrete index /// type determines validity of other values. /// @param op The relation operator. /// @param x The value to lookup. /// @returns The result of the lookup or an error upon failure. caf::expected<ids> lookup(relational_operator op, data_view x) const; /// Merges another value index with this one. /// @param other The value index to merge. /// @returns `true` on success. //bool merge(const value_index& other); /// Retrieves the ID of the last append operation. /// @returns The largest ID in the index. size_type offset() const; /// @returns the type of the index. const vast::type& type() const; /// @returns the options of the index. const caf::settings& options() const; // -- persistence ----------------------------------------------------------- virtual caf::error serialize(caf::serializer& sink) const; virtual caf::error deserialize(caf::deserializer& source); protected: const ewah_bitmap& mask() const; const ewah_bitmap& none() const; private: virtual bool append_impl(data_view x, id pos) = 0; virtual caf::expected<ids> lookup_impl(relational_operator op, data_view x) const = 0; ewah_bitmap mask_; ///< The position of all values excluding nil. ewah_bitmap none_; ///< The positions of nil values. const vast::type type_; ///< The type of this index. const caf::settings opts_; ///< Runtime context with additional parameters. }; /// @relates value_index caf::error inspect(caf::serializer& sink, const value_index& x); /// @relates value_index caf::error inspect(caf::deserializer& source, value_index& x); /// @relates value_index caf::error inspect(caf::serializer& sink, const value_index_ptr& x); /// @relates value_index caf::error inspect(caf::deserializer& source, value_index_ptr& x); namespace detail { template <class Index, class Sequence> caf::expected<ids> container_lookup_impl(const Index& idx, relational_operator op, const Sequence& xs) { ids result; if (op == in) { result = bitmap{idx.offset(), false}; for (auto x : xs) { auto r = idx.lookup(equal, x); if (r) result |= *r; else return r; if (all<1>(result)) // short-circuit return result; } } else if (op == not_in) { result = bitmap{idx.offset(), true}; for (auto x : xs) { auto r = idx.lookup(equal, x); if (r) result -= *r; else return r; if (all<0>(result)) // short-circuit return result; } } else { return make_error(ec::unsupported_operator, op); } return result; } template <class Index> caf::expected<ids> container_lookup(const Index& idx, relational_operator op, view<vector> xs) { VAST_ASSERT(xs); return container_lookup_impl(idx, op, *xs); } template <class Index> caf::expected<ids> container_lookup(const Index& idx, relational_operator op, view<set> xs) { VAST_ASSERT(xs); return container_lookup_impl(idx, op, *xs); } } // namespace detail /// An index for arithmetic values. template <class T, class Binner = void> class arithmetic_index : public value_index { public: // clang-format off using value_type = std::conditional_t< detail::is_any_v<T, time, duration>, duration::rep, std::conditional_t< detail::is_any_v<T, bool, integer, count, real>, T, std::false_type > >; // clang-format on static_assert(!std::is_same_v<value_type, std::false_type>, "invalid type T for arithmetic_index"); using multi_level_range_coder = multi_level_coder<range_coder<ids>>; // clang-format off using coder_type = std::conditional_t< std::is_same_v<T, bool>, singleton_coder<ids>, multi_level_range_coder >; // clang-format on // clang-format off using binner_type = std::conditional_t< std::is_void_v<Binner>, // Choose a space-efficient binner if none specified. std::conditional_t< detail::is_any_v<T, time, duration>, decimal_binner<9>, // nanoseconds -> seconds std::conditional_t< std::is_same_v<T, real>, precision_binner<10>, // no fractional part identity_binner > >, Binner >; // clang-format on using bitmap_index_type = bitmap_index<value_type, coder_type, binner_type>; /// Constructs an arithmetic index. /// @param t An arithmetic type. /// @param opts Runtime context for index parameterization. explicit arithmetic_index(vast::type t, caf::settings opts = {}) : value_index{std::move(t), std::move(opts)} { if constexpr (std::is_same_v<coder_type, multi_level_range_coder>) { auto i = opts.find("base"); if (i == opts.end()) { // Some early experiments found that 8 yields the best average // performance, presumably because it's a power of 2. bmi_ = bitmap_index_type{base::uniform<64>(8)}; } else { auto str = caf::get<caf::config_value::string>(i->second); auto b = to<base>(str); VAST_ASSERT(b); // pre-condition is that this was validated bmi_ = bitmap_index_type{base{std::move(*b)}}; } } } caf::error serialize(caf::serializer& sink) const override { return caf::error::eval([&] { return value_index::serialize(sink); }, [&] { return sink(bmi_); }); } caf::error deserialize(caf::deserializer& source) override { return caf::error::eval([&] { return value_index::deserialize(source); }, [&] { return source(bmi_); }); } private: bool append_impl(data_view d, id pos) override { auto append = [&](auto x) { bmi_.skip(pos - bmi_.size()); bmi_.append(x); return true; }; auto f = detail::overload([&](auto&&) { return false; }, [&](view<bool> x) { return append(x); }, [&](view<integer> x) { return append(x); }, [&](view<count> x) { return append(x); }, [&](view<real> x) { return append(x); }, [&](view<duration> x) { return append(x.count()); }, [&](view<time> x) { return append(x.time_since_epoch().count()); }); return caf::visit(f, d); } caf::expected<ids> lookup_impl(relational_operator op, data_view d) const override { auto f = detail::overload( [&](auto x) -> caf::expected<ids> { return make_error(ec::type_clash, value_type{}, materialize(x)); }, [&](view<bool> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<integer> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<count> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<real> x) -> caf::expected<ids> { return bmi_.lookup(op, x); }, [&](view<duration> x) -> caf::expected<ids> { return bmi_.lookup(op, x.count()); }, [&](view<time> x) -> caf::expected<ids> { return bmi_.lookup(op, x.time_since_epoch().count()); }, [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); }, [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }); return caf::visit(f, d); }; bitmap_index_type bmi_; }; /// An index for strings. class string_index : public value_index { public: /// Constructs a string index. /// @param t An instance of `string_type`. /// @param opts Runtime context for index parameterization. explicit string_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: /// The index which holds each character. using char_bitmap_index = bitmap_index<uint8_t, bitslice_coder<ewah_bitmap>>; /// The index which holds the string length. using length_bitmap_index = bitmap_index<uint32_t, multi_level_coder<range_coder<ids>>>; bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; size_t max_length_; length_bitmap_index length_; std::vector<char_bitmap_index> chars_; }; /// An index for enumerations. class enumeration_index : public value_index { public: using index = bitmap_index<enumeration, equality_coder<ewah_bitmap>>; explicit enumeration_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; index index_; }; /// An index for IP addresses. class address_index : public value_index { public: using byte_index = bitmap_index<uint8_t, bitslice_coder<ewah_bitmap>>; using type_index = bitmap_index<bool, singleton_coder<ewah_bitmap>>; explicit address_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; std::array<byte_index, 16> bytes_; type_index v4_; }; /// An index for subnets. class subnet_index : public value_index { public: using prefix_index = bitmap_index<uint8_t, equality_coder<ewah_bitmap>>; explicit subnet_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; address_index network_; prefix_index length_; }; /// An index for ports. class port_index : public value_index { public: using number_index = bitmap_index< port::number_type, multi_level_coder<range_coder<ewah_bitmap>> >; using protocol_index = bitmap_index< std::underlying_type<port::port_type>::type, equality_coder<ewah_bitmap> >; explicit port_index(vast::type t, caf::settings opts = {}); caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; number_index num_; protocol_index proto_; }; /// An index for vectors and sets. class sequence_index : public value_index { public: /// Constructs a sequence index of a given type. /// @param t The sequence type. /// @param opts Runtime options for element type construction. explicit sequence_index(vast::type t, caf::settings opts = {}); /// The bitmap index holding the sequence size. using size_bitmap_index = bitmap_index<uint32_t, multi_level_coder<range_coder<ids>>>; caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; private: bool append_impl(data_view x, id pos) override; caf::expected<ids> lookup_impl(relational_operator op, data_view x) const override; std::vector<value_index_ptr> elements_; size_t max_size_; size_bitmap_index size_; vast::type value_type_; }; } // namespace vast <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_LINGUISTIC_SOURCE_LNGOPT_HXX #define INCLUDED_LINGUISTIC_SOURCE_LNGOPT_HXX #include <cppuhelper/implbase5.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/XFastPropertySet.hpp> #include <com/sun/star/beans/XPropertyAccess.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/linguistic2/XLinguProperties.hpp> #include <unotools/lingucfg.hxx> #include <svl/itemprop.hxx> #include <unotools/configitem.hxx> #include <unotools/linguprops.hxx> #include <com/sun/star/uno/Any.h> #include <tools/solar.h> #include "linguistic/misc.hxx" #include "defs.hxx" namespace com { namespace sun { namespace star { namespace beans { struct PropertyChangeEvent; } }}} // LinguOptions // This class represents all Linguistik relevant options. class LinguOptions { static SvtLinguOptions *pData; static oslInterlockedCount nRefCount; // number of objects of this class public: LinguOptions(); LinguOptions(const LinguOptions &rOpt); ~LinguOptions(); static OUString GetName( sal_Int32 nWID ); const ::com::sun::star::uno::Sequence< OUString > GetActiveDics() const { return pData->aActiveDics; } const ::com::sun::star::uno::Sequence< OUString > GetActiveConvDics() const { return pData->aActiveConvDics; } }; // uses templates from <cppuhelper/interfacecontainer.h> // helper function call class struct PropHashType_Impl { size_t operator()(const sal_Int32 &s) const { return s; } }; typedef cppu::OMultiTypeInterfaceContainerHelperVar < sal_Int32, PropHashType_Impl > OPropertyListenerContainerHelper; class LinguProps : public cppu::WeakImplHelper5 < com::sun::star::linguistic2::XLinguProperties, com::sun::star::beans::XFastPropertySet, com::sun::star::beans::XPropertyAccess, com::sun::star::lang::XComponent, com::sun::star::lang::XServiceInfo > { ::cppu::OInterfaceContainerHelper aEvtListeners; OPropertyListenerContainerHelper aPropListeners; SfxItemPropertyMap aPropertyMap; SvtLinguConfig aConfig; sal_Bool bDisposing; // disallow copy-constructor and assignment-operator for now LinguProps(const LinguProps &); LinguProps & operator = (const LinguProps &); void launchEvent( const ::com::sun::star::beans::PropertyChangeEvent &rEvt ) const; sal_Bool getPropertyBool(const OUString& aPropertyName) throw (css::uno::RuntimeException); sal_Int16 getPropertyInt16(const OUString& aPropertyName) throw (css::uno::RuntimeException); css::lang::Locale getPropertyLocale(const OUString& aPropertyName) throw (css::uno::RuntimeException); void setProperty(const OUString& aPropertyName, sal_Bool p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } void setProperty(const OUString& aPropertyName, sal_Int16 p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } void setProperty(const OUString& aPropertyName, css::lang::Locale p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } public: LinguProps(); virtual sal_Bool SAL_CALL getIsUseDictionaryList() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_USE_DICTIONARY_LIST); } virtual void SAL_CALL setIsUseDictionaryList(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_USE_DICTIONARY_LIST, p1); } virtual sal_Bool SAL_CALL getIsIgnoreControlCharacters() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_IGNORE_CONTROL_CHARACTERS); } virtual void SAL_CALL setIsIgnoreControlCharacters(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_IGNORE_CONTROL_CHARACTERS, p1); } virtual sal_Bool SAL_CALL getIsSpellUpperCase() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_UPPER_CASE); } virtual void SAL_CALL setIsSpellUpperCase(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_UPPER_CASE, p1); } virtual sal_Bool SAL_CALL getIsSpellWithDigits() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_WITH_DIGITS); } virtual void SAL_CALL setIsSpellWithDigits(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_WITH_DIGITS, p1); } virtual sal_Bool SAL_CALL getIsSpellCapitalization() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_CAPITALIZATION); } virtual void SAL_CALL setIsSpellCapitalization(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_CAPITALIZATION, p1); } virtual sal_Int16 SAL_CALL getHyphMinLeading() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_HYPH_MIN_LEADING); } virtual void SAL_CALL setHyphMinLeading(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_LEADING, p1); } virtual sal_Int16 SAL_CALL getHyphMinTrailing() throw (css::uno::RuntimeException) { return getPropertyInt16(UPN_HYPH_MIN_TRAILING); } virtual void SAL_CALL setHyphMinTrailing(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_TRAILING, p1); } virtual sal_Int16 SAL_CALL getHyphMinWordLength() throw (css::uno::RuntimeException) { return getPropertyInt16(UPN_HYPH_MIN_WORD_LENGTH); } virtual void SAL_CALL setHyphMinWordLength(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_WORD_LENGTH, p1); } virtual com::sun::star::lang::Locale SAL_CALL getDefaultLocale() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE); } virtual void SAL_CALL setDefaultLocale(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE, p1); } virtual sal_Bool SAL_CALL getIsHyphAuto() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_HYPH_AUTO); } virtual void SAL_CALL setIsHyphAuto(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_HYPH_AUTO, p1); } virtual sal_Bool SAL_CALL getIsHyphSpecial() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_HYPH_SPECIAL); } virtual void SAL_CALL setIsHyphSpecial(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_HYPH_SPECIAL, p1); } virtual sal_Bool SAL_CALL getIsSpellAuto() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_AUTO); } virtual void SAL_CALL setIsSpellAuto(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_AUTO, p1); } virtual sal_Bool SAL_CALL getIsSpellSpecial() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_SPECIAL); } virtual void SAL_CALL setIsSpellSpecial(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_SPECIAL, p1); } virtual sal_Bool SAL_CALL getIsWrapReverse() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_WRAP_REVERSE); } virtual void SAL_CALL setIsWrapReverse(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_WRAP_REVERSE, p1); } virtual com::sun::star::lang::Locale SAL_CALL getDefaultLocale_CJK() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE_CJK); } virtual void SAL_CALL setDefaultLocale_CJK(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE_CJK, p1); } virtual css::lang::Locale SAL_CALL getDefaultLocale_CTL() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE_CTL); } virtual void SAL_CALL setDefaultLocale_CTL(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE_CTL, p1); } // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XFastPropertySet virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyValue( sal_Int32 nHandle ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XPropertyAccess virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getPropertyValues() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); static inline OUString getImplementationName_Static() throw(); static com::sun::star::uno::Sequence< OUString > getSupportedServiceNames_Static() throw(); }; inline OUString LinguProps::getImplementationName_Static() throw() { return OUString( "com.sun.star.lingu2.LinguProps" ); } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Resolves: fdo#72464 Character line break is set to 0 Options/.../Writing Aids<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_LINGUISTIC_SOURCE_LNGOPT_HXX #define INCLUDED_LINGUISTIC_SOURCE_LNGOPT_HXX #include <cppuhelper/implbase5.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/XFastPropertySet.hpp> #include <com/sun/star/beans/XPropertyAccess.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/linguistic2/XLinguProperties.hpp> #include <unotools/lingucfg.hxx> #include <svl/itemprop.hxx> #include <unotools/configitem.hxx> #include <unotools/linguprops.hxx> #include <com/sun/star/uno/Any.h> #include <tools/solar.h> #include "linguistic/misc.hxx" #include "defs.hxx" namespace com { namespace sun { namespace star { namespace beans { struct PropertyChangeEvent; } }}} // LinguOptions // This class represents all Linguistik relevant options. class LinguOptions { static SvtLinguOptions *pData; static oslInterlockedCount nRefCount; // number of objects of this class public: LinguOptions(); LinguOptions(const LinguOptions &rOpt); ~LinguOptions(); static OUString GetName( sal_Int32 nWID ); const ::com::sun::star::uno::Sequence< OUString > GetActiveDics() const { return pData->aActiveDics; } const ::com::sun::star::uno::Sequence< OUString > GetActiveConvDics() const { return pData->aActiveConvDics; } }; // uses templates from <cppuhelper/interfacecontainer.h> // helper function call class struct PropHashType_Impl { size_t operator()(const sal_Int32 &s) const { return s; } }; typedef cppu::OMultiTypeInterfaceContainerHelperVar < sal_Int32, PropHashType_Impl > OPropertyListenerContainerHelper; class LinguProps : public cppu::WeakImplHelper5 < com::sun::star::linguistic2::XLinguProperties, com::sun::star::beans::XFastPropertySet, com::sun::star::beans::XPropertyAccess, com::sun::star::lang::XComponent, com::sun::star::lang::XServiceInfo > { ::cppu::OInterfaceContainerHelper aEvtListeners; OPropertyListenerContainerHelper aPropListeners; SfxItemPropertyMap aPropertyMap; SvtLinguConfig aConfig; sal_Bool bDisposing; // disallow copy-constructor and assignment-operator for now LinguProps(const LinguProps &); LinguProps & operator = (const LinguProps &); void launchEvent( const ::com::sun::star::beans::PropertyChangeEvent &rEvt ) const; sal_Bool getPropertyBool(const OUString& aPropertyName) throw (css::uno::RuntimeException); sal_Int16 getPropertyInt16(const OUString& aPropertyName) throw (css::uno::RuntimeException); css::lang::Locale getPropertyLocale(const OUString& aPropertyName) throw (css::uno::RuntimeException); void setProperty(const OUString& aPropertyName, sal_Bool p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } void setProperty(const OUString& aPropertyName, sal_Int16 p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } void setProperty(const OUString& aPropertyName, css::lang::Locale p1) throw (css::uno::RuntimeException) { setPropertyValue( aPropertyName, css::uno::Any(p1) ); } public: LinguProps(); virtual sal_Bool SAL_CALL getIsUseDictionaryList() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_USE_DICTIONARY_LIST); } virtual void SAL_CALL setIsUseDictionaryList(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_USE_DICTIONARY_LIST, p1); } virtual sal_Bool SAL_CALL getIsIgnoreControlCharacters() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_IGNORE_CONTROL_CHARACTERS); } virtual void SAL_CALL setIsIgnoreControlCharacters(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_IGNORE_CONTROL_CHARACTERS, p1); } virtual sal_Bool SAL_CALL getIsSpellUpperCase() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_UPPER_CASE); } virtual void SAL_CALL setIsSpellUpperCase(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_UPPER_CASE, p1); } virtual sal_Bool SAL_CALL getIsSpellWithDigits() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_WITH_DIGITS); } virtual void SAL_CALL setIsSpellWithDigits(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_WITH_DIGITS, p1); } virtual sal_Bool SAL_CALL getIsSpellCapitalization() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_CAPITALIZATION); } virtual void SAL_CALL setIsSpellCapitalization(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_CAPITALIZATION, p1); } virtual sal_Int16 SAL_CALL getHyphMinLeading() throw (css::uno::RuntimeException) { return getPropertyInt16(UPN_HYPH_MIN_LEADING); } virtual void SAL_CALL setHyphMinLeading(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_LEADING, p1); } virtual sal_Int16 SAL_CALL getHyphMinTrailing() throw (css::uno::RuntimeException) { return getPropertyInt16(UPN_HYPH_MIN_TRAILING); } virtual void SAL_CALL setHyphMinTrailing(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_TRAILING, p1); } virtual sal_Int16 SAL_CALL getHyphMinWordLength() throw (css::uno::RuntimeException) { return getPropertyInt16(UPN_HYPH_MIN_WORD_LENGTH); } virtual void SAL_CALL setHyphMinWordLength(sal_Int16 p1) throw (css::uno::RuntimeException) { setProperty(UPN_HYPH_MIN_WORD_LENGTH, p1); } virtual com::sun::star::lang::Locale SAL_CALL getDefaultLocale() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE); } virtual void SAL_CALL setDefaultLocale(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE, p1); } virtual sal_Bool SAL_CALL getIsHyphAuto() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_HYPH_AUTO); } virtual void SAL_CALL setIsHyphAuto(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_HYPH_AUTO, p1); } virtual sal_Bool SAL_CALL getIsHyphSpecial() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_HYPH_SPECIAL); } virtual void SAL_CALL setIsHyphSpecial(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_HYPH_SPECIAL, p1); } virtual sal_Bool SAL_CALL getIsSpellAuto() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_AUTO); } virtual void SAL_CALL setIsSpellAuto(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_AUTO, p1); } virtual sal_Bool SAL_CALL getIsSpellSpecial() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_SPELL_SPECIAL); } virtual void SAL_CALL setIsSpellSpecial(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_SPELL_SPECIAL, p1); } virtual sal_Bool SAL_CALL getIsWrapReverse() throw (css::uno::RuntimeException) { return getPropertyBool(UPN_IS_WRAP_REVERSE); } virtual void SAL_CALL setIsWrapReverse(sal_Bool p1) throw (css::uno::RuntimeException) { setProperty(UPN_IS_WRAP_REVERSE, p1); } virtual com::sun::star::lang::Locale SAL_CALL getDefaultLocale_CJK() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE_CJK); } virtual void SAL_CALL setDefaultLocale_CJK(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE_CJK, p1); } virtual css::lang::Locale SAL_CALL getDefaultLocale_CTL() throw (css::uno::RuntimeException) { return getPropertyLocale(UPN_DEFAULT_LOCALE_CTL); } virtual void SAL_CALL setDefaultLocale_CTL(const com::sun::star::lang::Locale& p1) throw (css::uno::RuntimeException) { setProperty(UPN_DEFAULT_LOCALE_CTL, p1); } // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& rxListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XFastPropertySet virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyValue( sal_Int32 nHandle ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XPropertyAccess virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getPropertyValues() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); static inline OUString getImplementationName_Static() throw(); static com::sun::star::uno::Sequence< OUString > getSupportedServiceNames_Static() throw(); }; inline OUString LinguProps::getImplementationName_Static() throw() { return OUString( "com.sun.star.lingu2.LinguProps" ); } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdint.h> #include <vector> #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <process/collect.hpp> #include <process/defer.hpp> #include <process/delay.hpp> #include <process/io.hpp> #include <process/pid.hpp> #include <process/reap.hpp> #include <process/subprocess.hpp> #include <stout/bytes.hpp> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/foreach.hpp> #include <stout/hashset.hpp> #include <stout/lambda.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "linux/cgroups.hpp" #include "linux/perf.hpp" #include "slave/containerizer/isolators/cgroups/perf_event.hpp" using mesos::slave::ContainerLimitation; using mesos::slave::ContainerPrepareInfo; using mesos::slave::ContainerState; using mesos::slave::Isolator; using std::list; using std::set; using std::string; using std::vector; using process::Clock; using process::Failure; using process::Future; using process::PID; using process::Time; namespace mesos { namespace internal { namespace slave { Try<Isolator*> CgroupsPerfEventIsolatorProcess::create(const Flags& flags) { LOG(INFO) << "Creating PerfEvent isolator"; if (!perf::supported()) { return Error("Perf is not supported"); } if (flags.perf_duration > flags.perf_interval) { return Error("Sampling perf for duration (" + stringify(flags.perf_duration) + ") > interval (" + stringify(flags.perf_interval) + ") is not supported."); } if (!flags.perf_events.isSome()) { return Error("No perf events specified."); } set<string> events; foreach (const string& event, strings::tokenize(flags.perf_events.get(), ",")) { events.insert(event); } if (!perf::valid(events)) { return Error("Failed to create PerfEvent isolator, invalid events: " + stringify(events)); } Try<string> hierarchy = cgroups::prepare( flags.cgroups_hierarchy, "perf_event", flags.cgroups_root); if (hierarchy.isError()) { return Error("Failed to create perf_event cgroup: " + hierarchy.error()); } LOG(INFO) << "PerfEvent isolator will profile for " << flags.perf_duration << " every " << flags.perf_interval << " for events: " << stringify(events); process::Owned<MesosIsolatorProcess> process( new CgroupsPerfEventIsolatorProcess(flags, hierarchy.get(), events)); return new MesosIsolator(process); } CgroupsPerfEventIsolatorProcess::~CgroupsPerfEventIsolatorProcess() {} void CgroupsPerfEventIsolatorProcess::initialize() { // Start sampling. sample(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::recover( const list<ContainerState>& states, const hashset<ContainerID>& orphans) { foreach (const ContainerState& state, states) { const ContainerID& containerId = state.container_id(); const string cgroup = path::join(flags.cgroups_root, containerId.value()); Try<bool> exists = cgroups::exists(hierarchy, cgroup); if (exists.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure("Failed to check cgroup " + cgroup + " for container '" + stringify(containerId) + "'"); } if (!exists.get()) { // This may occur if the executor is exiting and the isolator has // destroyed the cgroup but the slave dies before noticing this. This // will be detected when the containerizer tries to monitor the // executor's pid. // NOTE: This could also occur if this isolator is now enabled for a // container that was started without this isolator. For this // particular isolator it is acceptable to continue running this // container without a perf_event cgroup because we don't ever // query it and the destroy will succeed immediately. VLOG(1) << "Couldn't find perf event cgroup for container " << containerId << ", perf statistics will not be available"; continue; } infos[containerId] = new Info(containerId, cgroup); } // Remove orphan cgroups. Try<vector<string>> cgroups = cgroups::get(hierarchy, flags.cgroups_root); if (cgroups.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure(cgroups.error()); } foreach (const string& cgroup, cgroups.get()) { // Ignore the slave cgroup (see the --slave_subsystems flag). // TODO(idownes): Remove this when the cgroups layout is updated, // see MESOS-1185. if (cgroup == path::join(flags.cgroups_root, "slave")) { continue; } ContainerID containerId; containerId.set_value(Path(cgroup).basename()); if (infos.contains(containerId)) { continue; } // Known orphan cgroups will be destroyed by the containerizer // using the normal cleanup path. See details in MESOS-2367. if (orphans.contains(containerId)) { infos[containerId] = new Info(containerId, cgroup); continue; } LOG(INFO) << "Removing unknown orphaned cgroup '" << cgroup << "'"; // We don't wait on the destroy as we don't want to block recovery. cgroups::destroy(hierarchy, cgroup, cgroups::DESTROY_TIMEOUT); } return Nothing(); } Future<Option<ContainerPrepareInfo>> CgroupsPerfEventIsolatorProcess::prepare( const ContainerID& containerId, const ExecutorInfo& executorInfo, const string& directory, const Option<string>& user) { if (infos.contains(containerId)) { return Failure("Container has already been prepared"); } LOG(INFO) << "Preparing perf event cgroup for " << containerId; Info* info = new Info( containerId, path::join(flags.cgroups_root, containerId.value())); infos[containerId] = CHECK_NOTNULL(info); // Create a cgroup for this container. Try<bool> exists = cgroups::exists(hierarchy, info->cgroup); if (exists.isError()) { return Failure("Failed to prepare isolator: " + exists.error()); } if (exists.get()) { return Failure("Failed to prepare isolator: cgroup already exists"); } if (!exists.get()) { Try<Nothing> create = cgroups::create(hierarchy, info->cgroup); if (create.isError()) { return Failure("Failed to prepare isolator: " + create.error()); } } // Chown the cgroup so the executor can create nested cgroups. Do // not recurse so the control files are still owned by the slave // user and thus cannot be changed by the executor. if (user.isSome()) { Try<Nothing> chown = os::chown( user.get(), path::join(hierarchy, info->cgroup), false); if (chown.isError()) { return Failure("Failed to prepare isolator: " + chown.error()); } } return None(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::isolate( const ContainerID& containerId, pid_t pid) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); Try<Nothing> assign = cgroups::assign(hierarchy, info->cgroup, pid); if (assign.isError()) { return Failure("Failed to assign container '" + stringify(info->containerId) + "' to its own cgroup '" + path::join(hierarchy, info->cgroup) + "' : " + assign.error()); } return Nothing(); } Future<ContainerLimitation> CgroupsPerfEventIsolatorProcess::watch( const ContainerID& containerId) { // No resources are limited. return Future<ContainerLimitation>(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::update( const ContainerID& containerId, const Resources& resources) { // Nothing to update. return Nothing(); } Future<ResourceStatistics> CgroupsPerfEventIsolatorProcess::usage( const ContainerID& containerId) { if (!infos.contains(containerId)) { // Return an empty ResourceStatistics, i.e., without // PerfStatistics, if we don't know about this container. return ResourceStatistics(); } CHECK_NOTNULL(infos[containerId]); ResourceStatistics statistics; statistics.mutable_perf()->CopyFrom(infos[containerId]->statistics); return statistics; } Future<Nothing> CgroupsPerfEventIsolatorProcess::cleanup( const ContainerID& containerId) { // Tolerate clean up attempts for unknown containers which may arise from // repeated clean up attempts (during test cleanup). if (!infos.contains(containerId)) { VLOG(1) << "Ignoring cleanup request for unknown container: " << containerId; return Nothing(); } Info* info = CHECK_NOTNULL(infos[containerId]); info->destroying = true; return cgroups::destroy(hierarchy, info->cgroup) .then(defer(PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::_cleanup, containerId)); } Future<Nothing> CgroupsPerfEventIsolatorProcess::_cleanup( const ContainerID& containerId) { if (!infos.contains(containerId)) { return Nothing(); } delete infos[containerId]; infos.erase(containerId); return Nothing(); } Future<hashmap<string, PerfStatistics>> discardSample( Future<hashmap<string, PerfStatistics>> future, const Duration& duration, const Duration& timeout) { LOG(ERROR) << "Perf sample of " << stringify(duration) << " failed to complete within " << stringify(timeout) << "; sampling will be halted"; future.discard(); return future; } void CgroupsPerfEventIsolatorProcess::sample() { // Collect a perf sample for all cgroups that are not being // destroyed. Since destroyal is asynchronous, 'perf stat' may // fail if the cgroup is destroyed before running perf. set<string> cgroups; foreachvalue (Info* info, infos) { CHECK_NOTNULL(info); if (!info->destroying) { cgroups.insert(info->cgroup); } } // The timeout includes an allowance of twice the process::reap // interval to ensure we see the perf process exit. If the sample // is not ready after the timeout something very unexpected has // occurred so we discard it and halt all sampling. Duration timeout = flags.perf_duration + process::MAX_REAP_INTERVAL() * 2; perf::sample(events, cgroups, flags.perf_duration) .after(timeout, lambda::bind(&discardSample, lambda::_1, flags.perf_duration, timeout)) .onAny(defer(PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::_sample, Clock::now() + flags.perf_interval, lambda::_1)); } void CgroupsPerfEventIsolatorProcess::_sample( const Time& next, const Future<hashmap<string, PerfStatistics>>& statistics) { if (!statistics.isReady()) { // Failure can occur for many reasons but all are unexpected and // indicate something is not right so we'll stop sampling. LOG(ERROR) << "Failed to get perf sample, sampling will be halted: " << (statistics.isFailed() ? statistics.failure() : "discarded due to timeout"); return; } // Store the latest statistics, note that cgroups added in the // interim will be picked up by the next sample. foreachvalue (Info* info, infos) { CHECK_NOTNULL(info); if (statistics->contains(info->cgroup)) { info->statistics = statistics->get(info->cgroup).get(); } } // Schedule sample for the next time. delay(next - Clock::now(), PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::sample); } } // namespace slave { } // namespace internal { } // namespace mesos { <commit_msg>Fixed the perf event isolator to continue sampling in the presence of failures.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdint.h> #include <vector> #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <process/collect.hpp> #include <process/defer.hpp> #include <process/delay.hpp> #include <process/io.hpp> #include <process/pid.hpp> #include <process/reap.hpp> #include <process/subprocess.hpp> #include <stout/bytes.hpp> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/foreach.hpp> #include <stout/hashset.hpp> #include <stout/lambda.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "linux/cgroups.hpp" #include "linux/perf.hpp" #include "slave/containerizer/isolators/cgroups/perf_event.hpp" using mesos::slave::ContainerLimitation; using mesos::slave::ContainerPrepareInfo; using mesos::slave::ContainerState; using mesos::slave::Isolator; using std::list; using std::set; using std::string; using std::vector; using process::Clock; using process::Failure; using process::Future; using process::PID; using process::Time; namespace mesos { namespace internal { namespace slave { Try<Isolator*> CgroupsPerfEventIsolatorProcess::create(const Flags& flags) { LOG(INFO) << "Creating PerfEvent isolator"; if (!perf::supported()) { return Error("Perf is not supported"); } if (flags.perf_duration > flags.perf_interval) { return Error("Sampling perf for duration (" + stringify(flags.perf_duration) + ") > interval (" + stringify(flags.perf_interval) + ") is not supported."); } if (!flags.perf_events.isSome()) { return Error("No perf events specified."); } set<string> events; foreach (const string& event, strings::tokenize(flags.perf_events.get(), ",")) { events.insert(event); } if (!perf::valid(events)) { return Error("Failed to create PerfEvent isolator, invalid events: " + stringify(events)); } Try<string> hierarchy = cgroups::prepare( flags.cgroups_hierarchy, "perf_event", flags.cgroups_root); if (hierarchy.isError()) { return Error("Failed to create perf_event cgroup: " + hierarchy.error()); } LOG(INFO) << "PerfEvent isolator will profile for " << flags.perf_duration << " every " << flags.perf_interval << " for events: " << stringify(events); process::Owned<MesosIsolatorProcess> process( new CgroupsPerfEventIsolatorProcess(flags, hierarchy.get(), events)); return new MesosIsolator(process); } CgroupsPerfEventIsolatorProcess::~CgroupsPerfEventIsolatorProcess() {} void CgroupsPerfEventIsolatorProcess::initialize() { // Start sampling. sample(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::recover( const list<ContainerState>& states, const hashset<ContainerID>& orphans) { foreach (const ContainerState& state, states) { const ContainerID& containerId = state.container_id(); const string cgroup = path::join(flags.cgroups_root, containerId.value()); Try<bool> exists = cgroups::exists(hierarchy, cgroup); if (exists.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure("Failed to check cgroup " + cgroup + " for container '" + stringify(containerId) + "'"); } if (!exists.get()) { // This may occur if the executor is exiting and the isolator has // destroyed the cgroup but the slave dies before noticing this. This // will be detected when the containerizer tries to monitor the // executor's pid. // NOTE: This could also occur if this isolator is now enabled for a // container that was started without this isolator. For this // particular isolator it is acceptable to continue running this // container without a perf_event cgroup because we don't ever // query it and the destroy will succeed immediately. VLOG(1) << "Couldn't find perf event cgroup for container " << containerId << ", perf statistics will not be available"; continue; } infos[containerId] = new Info(containerId, cgroup); } // Remove orphan cgroups. Try<vector<string>> cgroups = cgroups::get(hierarchy, flags.cgroups_root); if (cgroups.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure(cgroups.error()); } foreach (const string& cgroup, cgroups.get()) { // Ignore the slave cgroup (see the --slave_subsystems flag). // TODO(idownes): Remove this when the cgroups layout is updated, // see MESOS-1185. if (cgroup == path::join(flags.cgroups_root, "slave")) { continue; } ContainerID containerId; containerId.set_value(Path(cgroup).basename()); if (infos.contains(containerId)) { continue; } // Known orphan cgroups will be destroyed by the containerizer // using the normal cleanup path. See details in MESOS-2367. if (orphans.contains(containerId)) { infos[containerId] = new Info(containerId, cgroup); continue; } LOG(INFO) << "Removing unknown orphaned cgroup '" << cgroup << "'"; // We don't wait on the destroy as we don't want to block recovery. cgroups::destroy(hierarchy, cgroup, cgroups::DESTROY_TIMEOUT); } return Nothing(); } Future<Option<ContainerPrepareInfo>> CgroupsPerfEventIsolatorProcess::prepare( const ContainerID& containerId, const ExecutorInfo& executorInfo, const string& directory, const Option<string>& user) { if (infos.contains(containerId)) { return Failure("Container has already been prepared"); } LOG(INFO) << "Preparing perf event cgroup for " << containerId; Info* info = new Info( containerId, path::join(flags.cgroups_root, containerId.value())); infos[containerId] = CHECK_NOTNULL(info); // Create a cgroup for this container. Try<bool> exists = cgroups::exists(hierarchy, info->cgroup); if (exists.isError()) { return Failure("Failed to prepare isolator: " + exists.error()); } if (exists.get()) { return Failure("Failed to prepare isolator: cgroup already exists"); } if (!exists.get()) { Try<Nothing> create = cgroups::create(hierarchy, info->cgroup); if (create.isError()) { return Failure("Failed to prepare isolator: " + create.error()); } } // Chown the cgroup so the executor can create nested cgroups. Do // not recurse so the control files are still owned by the slave // user and thus cannot be changed by the executor. if (user.isSome()) { Try<Nothing> chown = os::chown( user.get(), path::join(hierarchy, info->cgroup), false); if (chown.isError()) { return Failure("Failed to prepare isolator: " + chown.error()); } } return None(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::isolate( const ContainerID& containerId, pid_t pid) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); Try<Nothing> assign = cgroups::assign(hierarchy, info->cgroup, pid); if (assign.isError()) { return Failure("Failed to assign container '" + stringify(info->containerId) + "' to its own cgroup '" + path::join(hierarchy, info->cgroup) + "' : " + assign.error()); } return Nothing(); } Future<ContainerLimitation> CgroupsPerfEventIsolatorProcess::watch( const ContainerID& containerId) { // No resources are limited. return Future<ContainerLimitation>(); } Future<Nothing> CgroupsPerfEventIsolatorProcess::update( const ContainerID& containerId, const Resources& resources) { // Nothing to update. return Nothing(); } Future<ResourceStatistics> CgroupsPerfEventIsolatorProcess::usage( const ContainerID& containerId) { if (!infos.contains(containerId)) { // Return an empty ResourceStatistics, i.e., without // PerfStatistics, if we don't know about this container. return ResourceStatistics(); } CHECK_NOTNULL(infos[containerId]); ResourceStatistics statistics; statistics.mutable_perf()->CopyFrom(infos[containerId]->statistics); return statistics; } Future<Nothing> CgroupsPerfEventIsolatorProcess::cleanup( const ContainerID& containerId) { // Tolerate clean up attempts for unknown containers which may arise from // repeated clean up attempts (during test cleanup). if (!infos.contains(containerId)) { VLOG(1) << "Ignoring cleanup request for unknown container: " << containerId; return Nothing(); } Info* info = CHECK_NOTNULL(infos[containerId]); info->destroying = true; return cgroups::destroy(hierarchy, info->cgroup) .then(defer(PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::_cleanup, containerId)); } Future<Nothing> CgroupsPerfEventIsolatorProcess::_cleanup( const ContainerID& containerId) { if (!infos.contains(containerId)) { return Nothing(); } delete infos[containerId]; infos.erase(containerId); return Nothing(); } Future<hashmap<string, PerfStatistics>> discardSample( Future<hashmap<string, PerfStatistics>> future, const Duration& duration, const Duration& timeout) { LOG(ERROR) << "Perf sample of " << stringify(duration) << " failed to complete within " << stringify(timeout) << "; sampling will be halted"; future.discard(); return future; } void CgroupsPerfEventIsolatorProcess::sample() { // Collect a perf sample for all cgroups that are not being // destroyed. Since destroyal is asynchronous, 'perf stat' may // fail if the cgroup is destroyed before running perf. set<string> cgroups; foreachvalue (Info* info, infos) { CHECK_NOTNULL(info); if (!info->destroying) { cgroups.insert(info->cgroup); } } // The discard timeout includes an allowance of twice the // reaper interval to ensure we see the perf process exit. Duration timeout = flags.perf_duration + process::MAX_REAP_INTERVAL() * 2; perf::sample(events, cgroups, flags.perf_duration) .after(timeout, lambda::bind(&discardSample, lambda::_1, flags.perf_duration, timeout)) .onAny(defer(PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::_sample, Clock::now() + flags.perf_interval, lambda::_1)); } void CgroupsPerfEventIsolatorProcess::_sample( const Time& next, const Future<hashmap<string, PerfStatistics>>& statistics) { if (!statistics.isReady()) { // In case the failure is transient or this is due to a timeout, // we continue sampling. Note that since sampling is done on an // interval, it should be ok if this is a non-transient failure. LOG(ERROR) << "Failed to get perf sample: " << (statistics.isFailed() ? statistics.failure() : "discarded due to timeout"); } else { // Store the latest statistics, note that cgroups added in the // interim will be picked up by the next sample. foreachvalue (Info* info, infos) { CHECK_NOTNULL(info); if (statistics->contains(info->cgroup)) { info->statistics = statistics->get(info->cgroup).get(); } } } // Schedule sample for the next time. delay(next - Clock::now(), PID<CgroupsPerfEventIsolatorProcess>(this), &CgroupsPerfEventIsolatorProcess::sample); } } // namespace slave { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <tools/stream.hxx> #include <rsc/rscsfx.hxx> // wg. pSlotPool #include "appdata.hxx" #include <sfx2/msgpool.hxx> #include <sfx2/minarray.hxx> #include <sfx2/msg.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include "sfxtypes.hxx" #include <sfx2/macrconf.hxx> #include "sfxresid.hxx" #include "arrdecl.hxx" #include <sfx2/module.hxx> #include <sfx2/sfx.hrc> //==================================================================== struct SfxSIDRegistration_Impl { String _aGroup; String _aName; USHORT _nSID; }; struct SfxSlotType_Impl { USHORT nId; TypeId nType; SfxSlotType_Impl( USHORT nTheId, TypeId nTheType ): nId(nTheId), nType(nTheType) {} }; DECL_2BYTEARRAY(SfxSlotGroupArr_Impl, USHORT, 6, 4) DECL_PTRARRAY(SfxInterfaceArr_Impl, SfxInterface*, 6, 3) DECL_PTRARRAY(SfxSlotTypeArr_Impl, SfxSlotType_Impl*, 8, 8) //==================================================================== SfxSlotPool::SfxSlotPool( SfxSlotPool *pParent, ResMgr* pResManager ) : _pGroups(0) , _pTypes(0) , _pParentPool( pParent ) , _pResMgr( pResManager ) , _pInterfaces(0) , _nCurGroup(0) , _nCurInterface(0) , _nCurMsg(0) , _pUnoSlots( 0 ) { if ( !_pResMgr ) _pResMgr = SfxApplication::GetOrCreate()->GetOffResManager_Impl(); } //==================================================================== SfxSlotPool::~SfxSlotPool() { _pParentPool = 0; for ( SfxInterface *pIF = FirstInterface(); pIF; pIF = FirstInterface() ) delete pIF; delete _pInterfaces; delete _pGroups; if ( _pTypes ) { for ( USHORT n =_pTypes->Count(); n--; ) delete _pTypes->GetObject(n); delete _pTypes; } } //==================================================================== // registers the availability of the Interface of functions void SfxSlotPool::RegisterInterface( SfxInterface& rInterface ) { DBG_MEMTEST(); // add to the list of SfxObjectInterface instances if ( _pInterfaces == 0 ) _pInterfaces = new SfxInterfaceArr_Impl; _pInterfaces->Append(&rInterface); // bei einem (einzelnen) Null-Slot abbrechen (aus syntaktischen Gr"unden // enthalten interfaces immer mindestens einen Slot) if ( rInterface.Count() == 1 && !rInterface[0]->nSlotId ) return; // possibly add Interface-id and group-ids of funcs to the list of groups if ( !_pGroups ) { _pGroups = new SfxSlotGroupArr_Impl; if ( _pParentPool ) { // Die Groups im parent Slotpool sind auch hier bekannt SfxSlotGroupArr_Impl& rGroups = *_pParentPool->_pGroups; for ( USHORT n=0; n<rGroups.Count(); n++ ) _pGroups->Append( rGroups[n] ); } } if ( !_pTypes ) _pTypes = new SfxSlotTypeArr_Impl; for ( USHORT nFunc = 0; nFunc < rInterface.Count(); ++nFunc ) { SfxSlot *pDef = rInterface[nFunc]; if ( pDef->GetGroupId() && /* pDef->GetGroupId() != GID_INTERN && */ !_pGroups->Contains(pDef->GetGroupId()) ) { if (pDef->GetGroupId() == GID_INTERN) _pGroups->Insert(0, pDef->GetGroupId()); else _pGroups->Append(pDef->GetGroupId()); } } } //==================================================================== TypeId SfxSlotPool::GetSlotType( USHORT nId ) const { const SfxSlot* pSlot = (const_cast <SfxSlotPool*> (this))->GetSlot( nId ); return pSlot ? pSlot->GetType()->Type() : 0; /* for ( USHORT nPos = 0; nPos < _pTypes->Count(); ++nPos ) { if ( _pTypes->GetObject(nPos)->nId == nId ) return _pTypes->GetObject(nPos)->nType; } return _pParentPool ? _pParentPool->GetSlotType( nId ) : 0; */ } //==================================================================== // unregisters the availability of the Interface of functions void SfxSlotPool::ReleaseInterface( SfxInterface& rInterface ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces, "releasing SfxInterface, but there are none" ); // remove from the list of SfxInterface instances _pInterfaces->Remove(&rInterface); } //-------------------------------------------------------------------- // get the first SfxMessage for a special Id (e.g. for getting check-mode) const SfxSlot* SfxSlotPool::GetSlot( USHORT nId ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Zun"achst die eigenen Interfaces absuchen for ( USHORT nInterf = 0; nInterf < _pInterfaces->Count(); ++nInterf ) { const SfxSlot *pDef = _pInterfaces->GetObject(nInterf)->GetSlot(nId); if ( pDef ) return pDef; } // Dann beim eventuell vorhandenen parent versuchen return _pParentPool ? _pParentPool->GetSlot( nId ) : 0; } //-------------------------------------------------------------------- // skips to the next group String SfxSlotPool::SeekGroup( USHORT nNo ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // if the group exists, use it if ( _pGroups && nNo < _pGroups->Count() ) { _nCurGroup = nNo; if ( _pParentPool ) { // Meistens stimmt die Reihenfolge der Ids "uberein USHORT nParentCount = _pParentPool->_pGroups->Count(); if ( nNo < nParentCount && (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[nNo] ) _pParentPool->_nCurGroup = nNo; else { // Ansonsten mu\s gesucht werden // Wenn die Gruppe im parent pool nicht gefunden wird, wird // _nCurGroup au\serhalb des g"ultigen Bereiches gesetzt USHORT i; for ( i=1; i<nParentCount; i++ ) if ( (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[i] ) break; _pParentPool->_nCurGroup = i; } } SfxResId aResId( (*_pGroups)[_nCurGroup] ); aResId.SetRT(RSC_STRING); if ( !aResId.GetResMgr()->IsAvailable(aResId) ) { DBG_ERROR( "GroupId-Name nicht im SFX definiert!" ); return String(); } return String( aResId ); } return String(); } //-------------------------------------------------------------------- USHORT SfxSlotPool::GetGroupCount() { return _pGroups->Count(); } //-------------------------------------------------------------------- // internal search loop const SfxSlot* SfxSlotPool::SeekSlot( USHORT nStartInterface ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Die Numerierung der interfaces startet beim parent pool USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; // sind wir am Ende des Parent-Pools angekommen? if ( nStartInterface < nFirstInterface && _pParentPool->_nCurGroup >= _pParentPool->_pGroups->Count() ) nStartInterface = nFirstInterface; // liegt das Interface noch im Parent-Pool? if ( nStartInterface < nFirstInterface ) { DBG_ASSERT( _pParentPool, "Kein parent pool!" ); _nCurInterface = nStartInterface; return _pParentPool->SeekSlot( nStartInterface ); } // find the first func-def with the current group id USHORT nCount = _pInterfaces->Count() + nFirstInterface; for ( _nCurInterface = nStartInterface; _nCurInterface < nCount; ++_nCurInterface ) { SfxInterface* pInterface = (*_pInterfaces)[_nCurInterface-nFirstInterface]; for ( _nCurMsg = 0; _nCurMsg < pInterface->Count(); ++_nCurMsg ) { const SfxSlot* pMsg = (*pInterface)[_nCurMsg]; if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) ) return pMsg; } } return 0; } //-------------------------------------------------------------------- // skips to the next func in the current group const SfxSlot* SfxSlotPool::NextSlot() { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Die Numerierung der interfaces startet beim parent pool USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; if ( _nCurInterface < nFirstInterface && _nCurGroup >= _pParentPool->_pGroups->Count() ) _nCurInterface = nFirstInterface; if ( _nCurInterface < nFirstInterface ) { DBG_ASSERT( _pParentPool, "Kein parent pool!" ); const SfxSlot *pSlot = _pParentPool->NextSlot(); _nCurInterface = _pParentPool->_nCurInterface; if ( pSlot ) return pSlot; if ( _nCurInterface == nFirstInterface ) // parent pool ist fertig return SeekSlot( nFirstInterface ); } USHORT nInterface = _nCurInterface - nFirstInterface; // possibly we are already at the end if ( nInterface >= _pInterfaces->Count() ) return 0; // look for further matching func-defs within the same Interface SfxInterface* pInterface = (*_pInterfaces)[nInterface]; while ( ++_nCurMsg < pInterface->Count() ) { SfxSlot* pMsg = (*pInterface)[_nCurMsg]; if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) ) return pMsg; } return SeekSlot(++_nCurInterface ); } //-------------------------------------------------------------------- // SlotName erfragen, gfs. mit HilfeText //-------------------------------------------------------------------- SfxInterface* SfxSlotPool::FirstInterface() { _nCurInterface = 0; if ( !_pInterfaces || !_pInterfaces->Count() ) return 0; return _pParentPool ? _pParentPool->FirstInterface() : (*_pInterfaces)[0]; } //-------------------------------------------------------------------- SfxInterface* SfxSlotPool::NextInterface() { _nCurInterface++; USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; if ( _nCurInterface < nFirstInterface ) return (*_pParentPool->_pInterfaces)[_nCurInterface]; USHORT nInterface = _nCurInterface - nFirstInterface; return nInterface < _pInterfaces->Count() ? (*_pInterfaces)[nInterface] : 0; } const SfxSlot* SfxSlotPool::GetUnoSlot( const String& rName ) { const SfxSlot *pSlot = NULL; for ( USHORT nInterface=0; nInterface<_pInterfaces->Count(); nInterface++ ) { pSlot = (*_pInterfaces)[nInterface]->GetSlot( rName ); if ( pSlot ) break; } if ( !pSlot && _pParentPool ) pSlot = _pParentPool->GetUnoSlot( rName ); return pSlot; } SfxSlotPool& SfxSlotPool::GetSlotPool( SfxViewFrame *pFrame ) { SfxModule *pMod = SfxModule::GetActiveModule( pFrame ); if ( pMod && pMod->GetSlotPool() ) return *pMod->GetSlotPool(); else return *SFX_APP()->Get_Impl()->pSlotPool; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck reports unused struct<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <tools/stream.hxx> #include <rsc/rscsfx.hxx> // wg. pSlotPool #include "appdata.hxx" #include <sfx2/msgpool.hxx> #include <sfx2/minarray.hxx> #include <sfx2/msg.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include "sfxtypes.hxx" #include <sfx2/macrconf.hxx> #include "sfxresid.hxx" #include "arrdecl.hxx" #include <sfx2/module.hxx> #include <sfx2/sfx.hrc> //==================================================================== struct SfxSlotType_Impl { USHORT nId; TypeId nType; SfxSlotType_Impl( USHORT nTheId, TypeId nTheType ): nId(nTheId), nType(nTheType) {} }; DECL_2BYTEARRAY(SfxSlotGroupArr_Impl, USHORT, 6, 4) DECL_PTRARRAY(SfxInterfaceArr_Impl, SfxInterface*, 6, 3) DECL_PTRARRAY(SfxSlotTypeArr_Impl, SfxSlotType_Impl*, 8, 8) //==================================================================== SfxSlotPool::SfxSlotPool( SfxSlotPool *pParent, ResMgr* pResManager ) : _pGroups(0) , _pTypes(0) , _pParentPool( pParent ) , _pResMgr( pResManager ) , _pInterfaces(0) , _nCurGroup(0) , _nCurInterface(0) , _nCurMsg(0) , _pUnoSlots( 0 ) { if ( !_pResMgr ) _pResMgr = SfxApplication::GetOrCreate()->GetOffResManager_Impl(); } //==================================================================== SfxSlotPool::~SfxSlotPool() { _pParentPool = 0; for ( SfxInterface *pIF = FirstInterface(); pIF; pIF = FirstInterface() ) delete pIF; delete _pInterfaces; delete _pGroups; if ( _pTypes ) { for ( USHORT n =_pTypes->Count(); n--; ) delete _pTypes->GetObject(n); delete _pTypes; } } //==================================================================== // registers the availability of the Interface of functions void SfxSlotPool::RegisterInterface( SfxInterface& rInterface ) { DBG_MEMTEST(); // add to the list of SfxObjectInterface instances if ( _pInterfaces == 0 ) _pInterfaces = new SfxInterfaceArr_Impl; _pInterfaces->Append(&rInterface); // bei einem (einzelnen) Null-Slot abbrechen (aus syntaktischen Gr"unden // enthalten interfaces immer mindestens einen Slot) if ( rInterface.Count() == 1 && !rInterface[0]->nSlotId ) return; // possibly add Interface-id and group-ids of funcs to the list of groups if ( !_pGroups ) { _pGroups = new SfxSlotGroupArr_Impl; if ( _pParentPool ) { // Die Groups im parent Slotpool sind auch hier bekannt SfxSlotGroupArr_Impl& rGroups = *_pParentPool->_pGroups; for ( USHORT n=0; n<rGroups.Count(); n++ ) _pGroups->Append( rGroups[n] ); } } if ( !_pTypes ) _pTypes = new SfxSlotTypeArr_Impl; for ( USHORT nFunc = 0; nFunc < rInterface.Count(); ++nFunc ) { SfxSlot *pDef = rInterface[nFunc]; if ( pDef->GetGroupId() && /* pDef->GetGroupId() != GID_INTERN && */ !_pGroups->Contains(pDef->GetGroupId()) ) { if (pDef->GetGroupId() == GID_INTERN) _pGroups->Insert(0, pDef->GetGroupId()); else _pGroups->Append(pDef->GetGroupId()); } } } //==================================================================== TypeId SfxSlotPool::GetSlotType( USHORT nId ) const { const SfxSlot* pSlot = (const_cast <SfxSlotPool*> (this))->GetSlot( nId ); return pSlot ? pSlot->GetType()->Type() : 0; /* for ( USHORT nPos = 0; nPos < _pTypes->Count(); ++nPos ) { if ( _pTypes->GetObject(nPos)->nId == nId ) return _pTypes->GetObject(nPos)->nType; } return _pParentPool ? _pParentPool->GetSlotType( nId ) : 0; */ } //==================================================================== // unregisters the availability of the Interface of functions void SfxSlotPool::ReleaseInterface( SfxInterface& rInterface ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces, "releasing SfxInterface, but there are none" ); // remove from the list of SfxInterface instances _pInterfaces->Remove(&rInterface); } //-------------------------------------------------------------------- // get the first SfxMessage for a special Id (e.g. for getting check-mode) const SfxSlot* SfxSlotPool::GetSlot( USHORT nId ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Zun"achst die eigenen Interfaces absuchen for ( USHORT nInterf = 0; nInterf < _pInterfaces->Count(); ++nInterf ) { const SfxSlot *pDef = _pInterfaces->GetObject(nInterf)->GetSlot(nId); if ( pDef ) return pDef; } // Dann beim eventuell vorhandenen parent versuchen return _pParentPool ? _pParentPool->GetSlot( nId ) : 0; } //-------------------------------------------------------------------- // skips to the next group String SfxSlotPool::SeekGroup( USHORT nNo ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // if the group exists, use it if ( _pGroups && nNo < _pGroups->Count() ) { _nCurGroup = nNo; if ( _pParentPool ) { // Meistens stimmt die Reihenfolge der Ids "uberein USHORT nParentCount = _pParentPool->_pGroups->Count(); if ( nNo < nParentCount && (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[nNo] ) _pParentPool->_nCurGroup = nNo; else { // Ansonsten mu\s gesucht werden // Wenn die Gruppe im parent pool nicht gefunden wird, wird // _nCurGroup au\serhalb des g"ultigen Bereiches gesetzt USHORT i; for ( i=1; i<nParentCount; i++ ) if ( (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[i] ) break; _pParentPool->_nCurGroup = i; } } SfxResId aResId( (*_pGroups)[_nCurGroup] ); aResId.SetRT(RSC_STRING); if ( !aResId.GetResMgr()->IsAvailable(aResId) ) { DBG_ERROR( "GroupId-Name nicht im SFX definiert!" ); return String(); } return String( aResId ); } return String(); } //-------------------------------------------------------------------- USHORT SfxSlotPool::GetGroupCount() { return _pGroups->Count(); } //-------------------------------------------------------------------- // internal search loop const SfxSlot* SfxSlotPool::SeekSlot( USHORT nStartInterface ) { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Die Numerierung der interfaces startet beim parent pool USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; // sind wir am Ende des Parent-Pools angekommen? if ( nStartInterface < nFirstInterface && _pParentPool->_nCurGroup >= _pParentPool->_pGroups->Count() ) nStartInterface = nFirstInterface; // liegt das Interface noch im Parent-Pool? if ( nStartInterface < nFirstInterface ) { DBG_ASSERT( _pParentPool, "Kein parent pool!" ); _nCurInterface = nStartInterface; return _pParentPool->SeekSlot( nStartInterface ); } // find the first func-def with the current group id USHORT nCount = _pInterfaces->Count() + nFirstInterface; for ( _nCurInterface = nStartInterface; _nCurInterface < nCount; ++_nCurInterface ) { SfxInterface* pInterface = (*_pInterfaces)[_nCurInterface-nFirstInterface]; for ( _nCurMsg = 0; _nCurMsg < pInterface->Count(); ++_nCurMsg ) { const SfxSlot* pMsg = (*pInterface)[_nCurMsg]; if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) ) return pMsg; } } return 0; } //-------------------------------------------------------------------- // skips to the next func in the current group const SfxSlot* SfxSlotPool::NextSlot() { DBG_MEMTEST(); DBG_ASSERT( _pInterfaces != 0, "no Interfaces registered" ); // Die Numerierung der interfaces startet beim parent pool USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; if ( _nCurInterface < nFirstInterface && _nCurGroup >= _pParentPool->_pGroups->Count() ) _nCurInterface = nFirstInterface; if ( _nCurInterface < nFirstInterface ) { DBG_ASSERT( _pParentPool, "Kein parent pool!" ); const SfxSlot *pSlot = _pParentPool->NextSlot(); _nCurInterface = _pParentPool->_nCurInterface; if ( pSlot ) return pSlot; if ( _nCurInterface == nFirstInterface ) // parent pool ist fertig return SeekSlot( nFirstInterface ); } USHORT nInterface = _nCurInterface - nFirstInterface; // possibly we are already at the end if ( nInterface >= _pInterfaces->Count() ) return 0; // look for further matching func-defs within the same Interface SfxInterface* pInterface = (*_pInterfaces)[nInterface]; while ( ++_nCurMsg < pInterface->Count() ) { SfxSlot* pMsg = (*pInterface)[_nCurMsg]; if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) ) return pMsg; } return SeekSlot(++_nCurInterface ); } //-------------------------------------------------------------------- // SlotName erfragen, gfs. mit HilfeText //-------------------------------------------------------------------- SfxInterface* SfxSlotPool::FirstInterface() { _nCurInterface = 0; if ( !_pInterfaces || !_pInterfaces->Count() ) return 0; return _pParentPool ? _pParentPool->FirstInterface() : (*_pInterfaces)[0]; } //-------------------------------------------------------------------- SfxInterface* SfxSlotPool::NextInterface() { _nCurInterface++; USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0; if ( _nCurInterface < nFirstInterface ) return (*_pParentPool->_pInterfaces)[_nCurInterface]; USHORT nInterface = _nCurInterface - nFirstInterface; return nInterface < _pInterfaces->Count() ? (*_pInterfaces)[nInterface] : 0; } const SfxSlot* SfxSlotPool::GetUnoSlot( const String& rName ) { const SfxSlot *pSlot = NULL; for ( USHORT nInterface=0; nInterface<_pInterfaces->Count(); nInterface++ ) { pSlot = (*_pInterfaces)[nInterface]->GetSlot( rName ); if ( pSlot ) break; } if ( !pSlot && _pParentPool ) pSlot = _pParentPool->GetUnoSlot( rName ); return pSlot; } SfxSlotPool& SfxSlotPool::GetSlotPool( SfxViewFrame *pFrame ) { SfxModule *pMod = SfxModule::GetActiveModule( pFrame ); if ( pMod && pMod->GetSlotPool() ) return *pMod->GetSlotPool(); else return *SFX_APP()->Get_Impl()->pSlotPool; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: storagehelper.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-11-26 16:36:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COMPHELPER_STORAGEHELPER_HXX #define _COMPHELPER_STORAGEHELPER_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif namespace comphelper { class OStorageHelper { public: static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > GetStorageFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetTemporaryStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromURL( const ::rtl::OUString& aURL, sal_Int32 nStorageMode, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromInputStream( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromStream( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream, sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static void CopyInputToOutput( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetInputStreamFromURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static void SetCommonStoragePassword( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aPass ) throw ( ::com::sun::star::uno::Exception ); static sal_Int32 GetXStorageFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ) throw ( ::com::sun::star::uno::Exception ); }; } #endif <commit_msg>INTEGRATION: CWS visibility02 (1.3.10); FILE MERGED 2005/01/05 05:54:12 mnicel 1.3.10.1: Issue number: 38608 Part of symbol visibility work.<commit_after>/************************************************************************* * * $RCSfile: storagehelper.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-02-16 16:02:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COMPHELPER_STORAGEHELPER_HXX #define _COMPHELPER_STORAGEHELPER_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif #ifndef INCLUDED_COMPHELPERDLLAPI_H #include "comphelper/comphelperdllapi.h" #endif namespace comphelper { class COMPHELPER_DLLPUBLIC OStorageHelper { public: static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > GetStorageFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetTemporaryStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromURL( const ::rtl::OUString& aURL, sal_Int32 nStorageMode, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromInputStream( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > GetStorageFromStream( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream, sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static void CopyInputToOutput( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput ) throw ( ::com::sun::star::uno::Exception ); static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetInputStreamFromURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() ) throw ( ::com::sun::star::uno::Exception ); static void SetCommonStoragePassword( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aPass ) throw ( ::com::sun::star::uno::Exception ); static sal_Int32 GetXStorageFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ) throw ( ::com::sun::star::uno::Exception ); }; } #endif <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include <vector> #include <iostream> #include <sstream> #include <zorba/singleton_item_sequence.h> #include <zorba/empty_sequence.h> #include <api/unmarshaller.h> #include "http_util.h" #include "error_util.h" namespace zorba { HttpStream::HttpStream(const zstring& aUri) : theDidInit(false), theUri(aUri) { } HttpStream::~HttpStream() { if (theIterator) { theIterator->close(); } } void HttpStream::init() { Zorba* lInstance = Zorba::getInstance(0); theStaticContext = lInstance->createStaticContext(); ItemFactory* lFactory = lInstance->getItemFactory(); Item lNodeName = lFactory->createQName("http://expath.org/ns/http-client", "http", "request"); Item lEmptyItem; std::vector<std::pair<String, String> > nsPairs; nsPairs.push_back(std::make_pair(String("xs"), String("http://www.w3.org/2001/XMLSchema"))); Item lRequestElement = lFactory->createElementNode(lEmptyItem, lNodeName, lFactory->createQName("http://www.w3.org/2001/XMLSchema", "xs", "untyped"), true, false, nsPairs); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "method"), Item(), lFactory->createString("GET")); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "href"), Item(), lFactory->createString(theUri.c_str())); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "override-media-type"), Item(), lFactory->createString("text/plain")); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "follow-redirect"), Item(), lFactory->createString("false")); Zorba_CompilerHints_t lHints; lHints.opt_level = ZORBA_OPT_LEVEL_O1; theStaticContext->loadProlog("import module namespace httpc = \"http://www.zorba-xquery.com/modules/http-client\";", lHints); Item lQName = lFactory->createQName("http://www.zorba-xquery.com/modules/http-client", "httpc", "send-request"); std::vector<ItemSequence_t> lArgs; lArgs.push_back(new SingletonItemSequence(lRequestElement)); lArgs.push_back(new EmptySequence()); lArgs.push_back(new EmptySequence()); theItemSequence = theStaticContext->invoke(lQName, lArgs); theIterator = theItemSequence->getIterator(); theIterator->open(); Item lItem; theIterator->next(lItem); Iterator_t lIter = lItem.getAttributes(); lIter->open(); Item lAttr; bool succeed = true; while (lIter->next(lAttr)) { Item lName; lAttr.getNodeName(lName); String lNameString = lName.getStringValue(); if (lNameString == "status") { std::stringstream lStream(lAttr.getStringValue().c_str()); int status; lStream >> status; succeed = status < 400; break; } } lIter->close(); if (!succeed) throw os_error::exception("", theUri.c_str(), "Could not create stream resource"); theIterator->next(theStreamableString); } std::istream& HttpStream::getStream() { return theStreamableString.getStream(); } StreamReleaser HttpStream::getStreamReleaser() { store::Item* lItem = Unmarshaller::getInternalItem(theStreamableString); return lItem->getStreamReleaser(); } void HttpStream::setStreamReleaser(StreamReleaser aReleaser) { store::Item* lItem = Unmarshaller::getInternalItem(theStreamableString); lItem->setStreamReleaser(aReleaser); } } <commit_msg>Following redirects when resolving URLs. Mostly used when importing modules or schemas.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include <vector> #include <iostream> #include <sstream> #include <zorba/singleton_item_sequence.h> #include <zorba/empty_sequence.h> #include <api/unmarshaller.h> #include "http_util.h" #include "error_util.h" namespace zorba { HttpStream::HttpStream(const zstring& aUri) : theDidInit(false), theUri(aUri) { } HttpStream::~HttpStream() { if (theIterator) { theIterator->close(); } } void HttpStream::init() { Zorba* lInstance = Zorba::getInstance(0); theStaticContext = lInstance->createStaticContext(); ItemFactory* lFactory = lInstance->getItemFactory(); Item lNodeName = lFactory->createQName("http://expath.org/ns/http-client", "http", "request"); Item lEmptyItem; std::vector<std::pair<String, String> > nsPairs; nsPairs.push_back(std::make_pair(String("xs"), String("http://www.w3.org/2001/XMLSchema"))); Item lRequestElement = lFactory->createElementNode(lEmptyItem, lNodeName, lFactory->createQName("http://www.w3.org/2001/XMLSchema", "xs", "untyped"), true, false, nsPairs); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "method"), Item(), lFactory->createString("GET")); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "href"), Item(), lFactory->createString(theUri.c_str())); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "override-media-type"), Item(), lFactory->createString("text/plain")); lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "follow-redirect"), Item(), lFactory->createString("true")); Zorba_CompilerHints_t lHints; lHints.opt_level = ZORBA_OPT_LEVEL_O1; theStaticContext->loadProlog("import module namespace httpc = \"http://www.zorba-xquery.com/modules/http-client\";", lHints); Item lQName = lFactory->createQName("http://www.zorba-xquery.com/modules/http-client", "httpc", "send-request"); std::vector<ItemSequence_t> lArgs; lArgs.push_back(new SingletonItemSequence(lRequestElement)); lArgs.push_back(new EmptySequence()); lArgs.push_back(new EmptySequence()); theItemSequence = theStaticContext->invoke(lQName, lArgs); theIterator = theItemSequence->getIterator(); theIterator->open(); Item lItem; theIterator->next(lItem); Iterator_t lIter = lItem.getAttributes(); lIter->open(); Item lAttr; bool succeed = true; while (lIter->next(lAttr)) { Item lName; lAttr.getNodeName(lName); String lNameString = lName.getStringValue(); if (lNameString == "status") { std::stringstream lStream(lAttr.getStringValue().c_str()); int status; lStream >> status; succeed = status < 400; break; } } lIter->close(); if (!succeed) throw os_error::exception("", theUri.c_str(), "Could not create stream resource"); theIterator->next(theStreamableString); } std::istream& HttpStream::getStream() { return theStreamableString.getStream(); } StreamReleaser HttpStream::getStreamReleaser() { store::Item* lItem = Unmarshaller::getInternalItem(theStreamableString); return lItem->getStreamReleaser(); } void HttpStream::setStreamReleaser(StreamReleaser aReleaser) { store::Item* lItem = Unmarshaller::getInternalItem(theStreamableString); lItem->setStreamReleaser(aReleaser); } } <|endoftext|>
<commit_before> #include "CReportDefinition.h" #include "CReportBody.h" #include "CReport.h" #include "CCopasiContainer.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(): CCopasiObject("Report", NULL, "Report", CCopasiObject::Container), ostream(NULL), mpReportDef(NULL), mTarget(""), mAppend(true) //,mKey(CKeyFactory::add("Report", this)) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { // Please Dont clear the objectList, as all pointers are also referred swh else unsigned C_INT32 i; for (i = 0; i < headerObjectList.size(); i++) headerObjectList[i] = NULL; for (i = 0; i < bodyObjectList.size(); i++) bodyObjectList[i] = NULL; for (i = 0; i < footerObjectList.size(); i++) footerObjectList[i] = NULL; headerObjectList.clear(); bodyObjectList.clear(); footerObjectList.clear(); // CKeyFactory::remove(mKey); // mpReportDef pointer shall be dealt outside, where it is created // pdelete(mpReportDef); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::printHeader() { // for loop print out mpReportDef->getHeader() unsigned C_INT32 i; for (i = 0; i < headerObjectList.size(); i++) headerObjectList[i]->print(*ostream); } void CReport::printBody() { // for loop print out mpReportDef->getBody() unsigned C_INT32 i; for (i = 0; i < bodyObjectList.size(); i++) bodyObjectList[i]->print(*ostream); } void CReport::printFooter() { // for loop print out mpReportDef->getFooter() unsigned C_INT32 i; for (i = 0; i < footerObjectList.size(); i++) footerObjectList[i]->print(*ostream); } // Compile the List of Report Objects; // Support Parellel void CReport::compile(const std::vector< CCopasiContainer * > * pListOfContainer) { generateObjectsFromName(pListOfContainer, headerObjectList, mpReportDef->getHeaderAddr()); generateObjectsFromName(pListOfContainer, bodyObjectList, mpReportDef->getBodyAddr()); generateObjectsFromName(pListOfContainer, footerObjectList, mpReportDef->getFooterAddr()); } void CReport::printBody(CReport * pReport) { if (pReport) pReport->printBody(); } // make to support parallel tasks void CReport::generateObjectsFromName(const std::vector< CCopasiContainer * > * pListOfContainer, std::vector<CCopasiObject*> & objectList, std::vector<CCopasiObjectName>* nameVector) { unsigned C_INT32 i; CCopasiObject* pSelected; // if no specified container list if (!pListOfContainer) for (i = 0; i < nameVector->size(); i++) { pSelected = NULL; pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(nameVector))[i]); if (pSelected) objectList.push_back(pSelected); } else { CCopasiContainer* pCopasiObject; unsigned C_INT32 containerIndex; for (i = 0; i < nameVector->size(); i++) { //favor to search the list of container first pSelected = NULL; for (containerIndex = 0; containerIndex < pListOfContainer->size(); containerIndex++) { pCopasiObject = (*pListOfContainer)[containerIndex]; pSelected = (CCopasiObject*)pCopasiObject->getObject((*(nameVector))[i]); if (pSelected) { objectList.push_back(pSelected); break; } } // if not find search the root if (!pSelected) { pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(nameVector))[i]); // has been deleted all where if (pSelected) objectList.push_back(pSelected); } } } } void CReport::getObjectFromName( const std::vector< CCopasiContainer * > * pListOfContainer, CCopasiObject* pObject, const CCopasiObjectName& objName) { // if no specified container list if (!pListOfContainer) { pObject = NULL; pObject = (CCopasiObject*)CCopasiContainer::Root->getObject(objName); } else { CCopasiContainer* pCopasiObject; unsigned C_INT32 containerIndex; //favor to search the list of container first pObject = NULL; for (containerIndex = 0; containerIndex < pListOfContainer->size(); containerIndex++) { pCopasiObject = (*pListOfContainer)[containerIndex]; pObject = (CCopasiObject*)pCopasiObject->getObject(objName); } // if not find search the root if (!pObject) pObject = (CCopasiObject*)CCopasiContainer::Root->getObject(objName); // has been deleted all where } } <commit_msg>if there is NULL ostream, do nothing,<commit_after> #include "CReportDefinition.h" #include "CReportBody.h" #include "CReport.h" #include "CCopasiContainer.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(): CCopasiObject("Report", NULL, "Report", CCopasiObject::Container), ostream(NULL), mpReportDef(NULL), mTarget(""), mAppend(true) //,mKey(CKeyFactory::add("Report", this)) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { // Please Dont clear the objectList, as all pointers are also referred swh else unsigned C_INT32 i; for (i = 0; i < headerObjectList.size(); i++) headerObjectList[i] = NULL; for (i = 0; i < bodyObjectList.size(); i++) bodyObjectList[i] = NULL; for (i = 0; i < footerObjectList.size(); i++) footerObjectList[i] = NULL; headerObjectList.clear(); bodyObjectList.clear(); footerObjectList.clear(); // CKeyFactory::remove(mKey); // mpReportDef pointer shall be dealt outside, where it is created // pdelete(mpReportDef); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::printHeader() { // check if there is a target defined, if (!ostream) return; // for loop print out mpReportDef->getHeader() unsigned C_INT32 i; for (i = 0; i < headerObjectList.size(); i++) headerObjectList[i]->print(*ostream); } void CReport::printBody() { // check if there is a target defined, if (!ostream) return; // for loop print out mpReportDef->getBody() unsigned C_INT32 i; for (i = 0; i < bodyObjectList.size(); i++) bodyObjectList[i]->print(*ostream); } void CReport::printFooter() { // check if there is a target defined, if (!ostream) return; // for loop print out mpReportDef->getFooter() unsigned C_INT32 i; for (i = 0; i < footerObjectList.size(); i++) footerObjectList[i]->print(*ostream); } // Compile the List of Report Objects; // Support Parellel void CReport::compile(const std::vector< CCopasiContainer * > * pListOfContainer) { generateObjectsFromName(pListOfContainer, headerObjectList, mpReportDef->getHeaderAddr()); generateObjectsFromName(pListOfContainer, bodyObjectList, mpReportDef->getBodyAddr()); generateObjectsFromName(pListOfContainer, footerObjectList, mpReportDef->getFooterAddr()); } void CReport::printBody(CReport * pReport) { if (pReport) pReport->printBody(); } // make to support parallel tasks void CReport::generateObjectsFromName(const std::vector< CCopasiContainer * > * pListOfContainer, std::vector<CCopasiObject*> & objectList, std::vector<CCopasiObjectName>* nameVector) { unsigned C_INT32 i; CCopasiObject* pSelected; // if no specified container list if (!pListOfContainer) for (i = 0; i < nameVector->size(); i++) { pSelected = NULL; pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(nameVector))[i]); if (pSelected) objectList.push_back(pSelected); } else { CCopasiContainer* pCopasiObject; unsigned C_INT32 containerIndex; for (i = 0; i < nameVector->size(); i++) { //favor to search the list of container first pSelected = NULL; for (containerIndex = 0; containerIndex < pListOfContainer->size(); containerIndex++) { pCopasiObject = (*pListOfContainer)[containerIndex]; pSelected = (CCopasiObject*)pCopasiObject->getObject((*(nameVector))[i]); if (pSelected) { objectList.push_back(pSelected); break; } } // if not find search the root if (!pSelected) { pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(nameVector))[i]); // has been deleted all where if (pSelected) objectList.push_back(pSelected); } } } } void CReport::getObjectFromName( const std::vector< CCopasiContainer * > * pListOfContainer, CCopasiObject* pObject, const CCopasiObjectName& objName) { // if no specified container list if (!pListOfContainer) { pObject = NULL; pObject = (CCopasiObject*)CCopasiContainer::Root->getObject(objName); } else { CCopasiContainer* pCopasiObject; unsigned C_INT32 containerIndex; //favor to search the list of container first pObject = NULL; for (containerIndex = 0; containerIndex < pListOfContainer->size(); containerIndex++) { pCopasiObject = (*pListOfContainer)[containerIndex]; pObject = (CCopasiObject*)pCopasiObject->getObject(objName); } // if not find search the root if (!pObject) pObject = (CCopasiObject*)CCopasiContainer::Root->getObject(objName); // has been deleted all where } } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ $Revision: 1.51 $ $Name: $ $Author: shoops $ $Date: 2005/04/25 18:16:13 $ End CVS Header */ /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); // mpMethod->setObjectParent(this); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(* (CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); // mpMethod->setObjectParent(this); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() { //pdelete(mpProblem); //pdelete(mpMethod); // pdelete(mpOutEnd); //-pdelete(mReport); } bool CScanTask::initialize(std::ostream * out) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); bool success = true; if (!pProblem->getModel()->compileIfNecessary()) success = false; // pdelete(mpOutEnd); //mpOut = & out; // added by Liang for Scan Report //mReport.open(mpOut); //mReport.compile(); assert(pProblem); // for Steadystate Report // if (pProblem->processSteadyState()) // pProblem->getSteadyStateTask()->initialize(mpOut); // for Trajectory Report // if (pProblem->processTrajectory()) // pProblem->getTrajectoryTask()->initialize(mpOut); return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); assert(pProblem); //pProblem->load(configBuffer); } bool CScanTask::process() { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; initSubtask(); pMethod->setProblem(pProblem); //TODO: reports //initialize the method (parsing the ScanItems) if (!pMethod->init()) return false; //init progress bar mProgress = 0; /* if (mpProgressHandler) mpProgressHandler->init(pMethod->getTotalNumberOfSteps(), "performing parameter scan...", true); */ if (mpProgressHandler) { mpProgressHandler->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpProgressHandler->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); } //init output handler (plotting) if (mpOutputHandler) mpOutputHandler->init(); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output if (mpProgressHandler) mpProgressHandler->finish(); if (mpOutputHandler) mpOutputHandler->finish(); return success; } bool CScanTask::processCallback() { //do tasks CSteadyStateProblem * ssProblem = dynamic_cast<CSteadyStateProblem*>(mpSubtask->getProblem()); if (ssProblem) {ssProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());} CTrajectoryProblem * ttProblem = dynamic_cast<CTrajectoryProblem*>(mpSubtask->getProblem()); if (ttProblem) {ttProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());} mpSubtask->processForScan(!mAdjustInitialConditions, mOutputInSubtask); //do output if (mpOutputHandler && (!mOutputInSubtask)) mpOutputHandler->doOutput(); //do progress bar ++mProgress; if (mpProgressHandler) return !mpProgressHandler->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) if (mpOutputHandler) return mpOutputHandler->doSeparator(); return true; } bool CScanTask::initSubtask() { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*)(pProblem->getValue("Subtask")); CTrajectoryProblem* trajProblem; CSteadyStateProblem* ssProblem; switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Steady-State"]); ssProblem = dynamic_cast<CSteadyStateProblem*>(mpSubtask->getProblem()); ssProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState()); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Time-Course"]); trajProblem = dynamic_cast<CTrajectoryProblem*>(mpSubtask->getProblem()); trajProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState()); break; default: mpSubtask = NULL; } /* if (type == CCopasiTask::steadyState) { mpSubtask=const_cast<CCopasiTask*> (dynamic_cast<const CCopasiTask*> (CCopasiContainer::Root->getObject(CCopasiObjectName("Task=Steady-State")))); } else {mpSubtask=NULL;}*/ if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(CCopasiDataModel::Global->getModel()); mpSubtask->setProgressHandler(NULL); mpSubtask->initialize(); mOutputInSubtask = *(bool*)(pProblem->getValue("Output in subtask")); if (type != CCopasiTask::timeCourse) mOutputInSubtask = false; mAdjustInitialConditions = *(bool*)(pProblem->getValue("Adjust initial conditions")); return true; } <commit_msg>adapted to changes in the semantics of the progress bar handler<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ $Revision: 1.52 $ $Name: $ $Author: ssahle $ $Date: 2005/05/24 12:37:23 $ End CVS Header */ /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); // mpMethod->setObjectParent(this); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(* (CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); // mpMethod->setObjectParent(this); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() { //pdelete(mpProblem); //pdelete(mpMethod); // pdelete(mpOutEnd); //-pdelete(mReport); } bool CScanTask::initialize(std::ostream * out) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); bool success = true; if (!pProblem->getModel()->compileIfNecessary()) success = false; // pdelete(mpOutEnd); //mpOut = & out; // added by Liang for Scan Report //mReport.open(mpOut); //mReport.compile(); assert(pProblem); // for Steadystate Report // if (pProblem->processSteadyState()) // pProblem->getSteadyStateTask()->initialize(mpOut); // for Trajectory Report // if (pProblem->processTrajectory()) // pProblem->getTrajectoryTask()->initialize(mpOut); return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); assert(pProblem); //pProblem->load(configBuffer); } bool CScanTask::process() { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; initSubtask(); pMethod->setProblem(pProblem); //TODO: reports //initialize the method (parsing the ScanItems) if (!pMethod->init()) return false; //init progress bar mProgress = 0; /* if (mpProgressHandler) mpProgressHandler->init(pMethod->getTotalNumberOfSteps(), "performing parameter scan...", true); */ if (mpProgressHandler) { mpProgressHandler->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpProgressHandler->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); } //init output handler (plotting) if (mpOutputHandler) mpOutputHandler->init(); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output if (mpProgressHandler) mpProgressHandler->finish(); if (mpOutputHandler) mpOutputHandler->finish(); return success; } bool CScanTask::processCallback() { //do tasks CSteadyStateProblem * ssProblem = dynamic_cast<CSteadyStateProblem*>(mpSubtask->getProblem()); if (ssProblem) {ssProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());} CTrajectoryProblem * ttProblem = dynamic_cast<CTrajectoryProblem*>(mpSubtask->getProblem()); if (ttProblem) {ttProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());} mpSubtask->processForScan(!mAdjustInitialConditions, mOutputInSubtask); //do output if (mpOutputHandler && (!mOutputInSubtask)) mpOutputHandler->doOutput(); //do progress bar ++mProgress; if (mpProgressHandler) return mpProgressHandler->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) if (mpOutputHandler) return mpOutputHandler->doSeparator(); return true; } bool CScanTask::initSubtask() { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*)(pProblem->getValue("Subtask")); CTrajectoryProblem* trajProblem; CSteadyStateProblem* ssProblem; switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Steady-State"]); ssProblem = dynamic_cast<CSteadyStateProblem*>(mpSubtask->getProblem()); ssProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState()); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Time-Course"]); trajProblem = dynamic_cast<CTrajectoryProblem*>(mpSubtask->getProblem()); trajProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState()); break; default: mpSubtask = NULL; } /* if (type == CCopasiTask::steadyState) { mpSubtask=const_cast<CCopasiTask*> (dynamic_cast<const CCopasiTask*> (CCopasiContainer::Root->getObject(CCopasiObjectName("Task=Steady-State")))); } else {mpSubtask=NULL;}*/ if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(CCopasiDataModel::Global->getModel()); mpSubtask->setProgressHandler(NULL); mpSubtask->initialize(); mOutputInSubtask = *(bool*)(pProblem->getValue("Output in subtask")); if (type != CCopasiTask::timeCourse) mOutputInSubtask = false; mAdjustInitialConditions = *(bool*)(pProblem->getValue("Adjust initial conditions")); return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2012 J-P Nurmi <[email protected]> * * This test is free, and not covered by LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. By using it you may give me some credits in your * program, but you don't have to. */ #include "irccommand.h" #include <QtTest/QtTest> class tst_IrcCommand : public QObject { Q_OBJECT private slots: void testDefaults(); void testAway(); void testCtcpAction(); void testCtcpReply(); void testCtcpRequest(); void testInvite(); void testJoin(); void testKick(); void testList(); void testMessage(); void testMode(); void testNames(); void testNick(); void testNotice(); void testPart(); void testPing(); void testPong(); void testQuit(); void testQuote(); void testTopic(); void testWho(); void testWhois(); void testWhowas(); }; void tst_IrcCommand::testDefaults() { IrcCommand cmd; QVERIFY(cmd.type() == IrcCommand::Custom); QVERIFY(cmd.parameters().isEmpty()); } void tst_IrcCommand::testAway() { } void tst_IrcCommand::testCtcpAction() { } void tst_IrcCommand::testCtcpReply() { } void tst_IrcCommand::testCtcpRequest() { } void tst_IrcCommand::testInvite() { } void tst_IrcCommand::testJoin() { } void tst_IrcCommand::testKick() { } void tst_IrcCommand::testList() { } void tst_IrcCommand::testMessage() { } void tst_IrcCommand::testMode() { } void tst_IrcCommand::testNames() { } void tst_IrcCommand::testNick() { } void tst_IrcCommand::testNotice() { } void tst_IrcCommand::testPart() { } void tst_IrcCommand::testPing() { } void tst_IrcCommand::testPong() { } void tst_IrcCommand::testQuit() { } void tst_IrcCommand::testQuote() { } void tst_IrcCommand::testTopic() { } void tst_IrcCommand::testWho() { } void tst_IrcCommand::testWhois() { } void tst_IrcCommand::testWhowas() { } QTEST_MAIN(tst_IrcCommand) #include "tst_irccommand.moc" <commit_msg>Update tst_irccommand with very basic tests<commit_after>/* * Copyright (C) 2008-2012 J-P Nurmi <[email protected]> * * This test is free, and not covered by LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. By using it you may give me some credits in your * program, but you don't have to. */ #include "irccommand.h" #include <QtTest/QtTest> class tst_IrcCommand : public QObject { Q_OBJECT private slots: void testDefaults(); void testAdmin(); void testAway(); void testCapability(); void testCtcpAction(); void testCtcpReply(); void testCtcpRequest(); void testInfo(); void testInvite(); void testJoin(); void testKick(); void testKnock(); void testList(); void testMessage(); void testMode(); void testMotd(); void testNames(); void testNick(); void testNotice(); void testPart(); void testQuit(); void testQuote(); void testStats(); void testTime(); void testTopic(); void testTrace(); void testUsers(); void testVersion(); void testWho(); void testWhois(); void testWhowas(); }; void tst_IrcCommand::testDefaults() { IrcCommand cmd; QVERIFY(cmd.type() == IrcCommand::Custom); QVERIFY(cmd.parameters().isEmpty()); } void tst_IrcCommand::testAdmin() { IrcCommand* cmd = IrcCommand::createAdmin(); QVERIFY(cmd->type() == IrcCommand::Admin); QVERIFY(cmd->toString().contains(QRegExp("\\bADMIN\\b"))); delete cmd; } void tst_IrcCommand::testAway() { IrcCommand* cmd = IrcCommand::createAway(); QVERIFY(cmd->type() == IrcCommand::Away); QVERIFY(cmd->toString().contains(QRegExp("\\bAWAY\\b"))); delete cmd; } void tst_IrcCommand::testCapability() { IrcCommand* cmd = IrcCommand::createCapability("sub"); QVERIFY(cmd->type() == IrcCommand::Capability); QVERIFY(cmd->toString().contains(QRegExp("\\bCAP\\b"))); delete cmd; } void tst_IrcCommand::testCtcpAction() { IrcCommand* cmd = IrcCommand::createCtcpAction("tgt", "act"); QVERIFY(cmd->type() == IrcCommand::CtcpAction); QVERIFY(cmd->toString().contains(QRegExp("\\bPRIVMSG\\b"))); delete cmd; } void tst_IrcCommand::testCtcpReply() { IrcCommand* cmd = IrcCommand::createCtcpReply("tgt", "rpl"); QVERIFY(cmd->type() == IrcCommand::CtcpReply); QVERIFY(cmd->toString().contains(QRegExp("\\bNOTICE\\b"))); delete cmd; } void tst_IrcCommand::testCtcpRequest() { IrcCommand* cmd = IrcCommand::createCtcpRequest("tgt", "req"); QVERIFY(cmd->type() == IrcCommand::CtcpRequest); QVERIFY(cmd->toString().contains(QRegExp("\\bPRIVMSG\\b"))); delete cmd; } void tst_IrcCommand::testInfo() { IrcCommand* cmd = IrcCommand::createInfo(); QVERIFY(cmd->type() == IrcCommand::Info); QVERIFY(cmd->toString().contains(QRegExp("\\bINFO\\b"))); delete cmd; } void tst_IrcCommand::testInvite() { IrcCommand* cmd = IrcCommand::createInvite("usr", "chan"); QVERIFY(cmd->type() == IrcCommand::Invite); QVERIFY(cmd->toString().contains(QRegExp("\\bINVITE\\b"))); delete cmd; } void tst_IrcCommand::testJoin() { IrcCommand* cmd = IrcCommand::createJoin("chan"); QVERIFY(cmd->type() == IrcCommand::Join); QVERIFY(cmd->toString().contains(QRegExp("\\bJOIN\\b"))); delete cmd; } void tst_IrcCommand::testKick() { IrcCommand* cmd = IrcCommand::createKick("chan", "usr"); QVERIFY(cmd->type() == IrcCommand::Kick); QVERIFY(cmd->toString().contains(QRegExp("\\bKICK\\b"))); delete cmd; } void tst_IrcCommand::testKnock() { IrcCommand* cmd = IrcCommand::createKnock("chan"); QVERIFY(cmd->type() == IrcCommand::Knock); QVERIFY(cmd->toString().contains(QRegExp("\\bKNOCK\\b"))); delete cmd; } void tst_IrcCommand::testList() { IrcCommand* cmd = IrcCommand::createList(); QVERIFY(cmd->type() == IrcCommand::List); QVERIFY(cmd->toString().contains(QRegExp("\\bLIST\\b"))); delete cmd; } void tst_IrcCommand::testMessage() { IrcCommand* cmd = IrcCommand::createMessage("tgt", "msg"); QVERIFY(cmd->type() == IrcCommand::Message); QVERIFY(cmd->toString().contains(QRegExp("\\bPRIVMSG\\b"))); delete cmd; } void tst_IrcCommand::testMode() { IrcCommand* cmd = IrcCommand::createMode("tgt", "mode"); QVERIFY(cmd->type() == IrcCommand::Mode); QVERIFY(cmd->toString().contains(QRegExp("\\bMODE\\b"))); delete cmd; } void tst_IrcCommand::testMotd() { IrcCommand* cmd = IrcCommand::createMotd(); QVERIFY(cmd->type() == IrcCommand::Motd); QVERIFY(cmd->toString().contains(QRegExp("\\bMOTD\\b"))); delete cmd; } void tst_IrcCommand::testNames() { IrcCommand* cmd = IrcCommand::createNames(); QVERIFY(cmd->type() == IrcCommand::Names); QVERIFY(cmd->toString().contains(QRegExp("\\bNAMES\\b"))); delete cmd; } void tst_IrcCommand::testNick() { IrcCommand* cmd = IrcCommand::createNick("nick"); QVERIFY(cmd->type() == IrcCommand::Nick); QVERIFY(cmd->toString().contains(QRegExp("\\bNICK\\b"))); delete cmd; } void tst_IrcCommand::testNotice() { IrcCommand* cmd = IrcCommand::createNotice("tgt", "msg"); QVERIFY(cmd->type() == IrcCommand::Notice); QVERIFY(cmd->toString().contains(QRegExp("\\bNOTICE\\b"))); delete cmd; } void tst_IrcCommand::testPart() { IrcCommand* cmd = IrcCommand::createPart("chan"); QVERIFY(cmd->type() == IrcCommand::Part); QVERIFY(cmd->toString().contains(QRegExp("\\bPART\\b"))); delete cmd; } void tst_IrcCommand::testQuit() { IrcCommand* cmd = IrcCommand::createQuit(); QVERIFY(cmd->type() == IrcCommand::Quit); QVERIFY(cmd->toString().contains(QRegExp("\\bQUIT\\b"))); delete cmd; } void tst_IrcCommand::testQuote() { IrcCommand* cmd = IrcCommand::createQuote("CUSTOM"); QVERIFY(cmd->type() == IrcCommand::Quote); QVERIFY(cmd->toString().contains(QRegExp("\\bCUSTOM\\b"))); delete cmd; } void tst_IrcCommand::testStats() { IrcCommand* cmd = IrcCommand::createStats("qry"); QVERIFY(cmd->type() == IrcCommand::Stats); QVERIFY(cmd->toString().contains(QRegExp("\\bSTATS\\b"))); delete cmd; } void tst_IrcCommand::testTime() { IrcCommand* cmd = IrcCommand::createTime(); QVERIFY(cmd->type() == IrcCommand::Time); QVERIFY(cmd->toString().contains(QRegExp("\\bTIME\\b"))); delete cmd; } void tst_IrcCommand::testTopic() { IrcCommand* cmd = IrcCommand::createTopic("chan"); QVERIFY(cmd->type() == IrcCommand::Topic); QVERIFY(cmd->toString().contains(QRegExp("\\bTOPIC\\b"))); delete cmd; } void tst_IrcCommand::testTrace() { IrcCommand* cmd = IrcCommand::createTrace(); QVERIFY(cmd->type() == IrcCommand::Trace); QVERIFY(cmd->toString().contains(QRegExp("\\bTRACE\\b"))); delete cmd; } void tst_IrcCommand::testUsers() { IrcCommand* cmd = IrcCommand::createUsers(); QVERIFY(cmd->type() == IrcCommand::Users); QVERIFY(cmd->toString().contains(QRegExp("\\bUSERS\\b"))); delete cmd; } void tst_IrcCommand::testVersion() { IrcCommand* cmd = IrcCommand::createVersion(); QVERIFY(cmd->type() == IrcCommand::Version); QVERIFY(cmd->toString().contains(QRegExp("\\bVERSION\\b"))); delete cmd; } void tst_IrcCommand::testWho() { IrcCommand* cmd = IrcCommand::createWho("msk"); QVERIFY(cmd->type() == IrcCommand::Who); QVERIFY(cmd->toString().contains(QRegExp("\\bWHO\\b"))); delete cmd; } void tst_IrcCommand::testWhois() { IrcCommand* cmd = IrcCommand::createWhois("usr"); QVERIFY(cmd->type() == IrcCommand::Whois); QVERIFY(cmd->toString().contains(QRegExp("\\bWHOIS\\b"))); delete cmd; } void tst_IrcCommand::testWhowas() { IrcCommand* cmd = IrcCommand::createWhowas("usr"); QVERIFY(cmd->type() == IrcCommand::Whowas); QVERIFY(cmd->toString().contains(QRegExp("\\bWHOWAS\\b"))); delete cmd; } QTEST_MAIN(tst_IrcCommand) #include "tst_irccommand.moc" <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015-2021 Ivan Gagis <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* ================ LICENSE END ================ */ #pragma once #include <exception> #include <string> namespace utki{ /** * @brief Generic exception. * * This class allows throwing an std::exception-derived exception with text message. * This exception class is to be mainly used for adding additional text message to already * thrown exception via std::throw_with_nested. */ class exception : public std::exception{ std::string message; public: /** * @brief Constructor. * * @param message - text message to be stored in the exception object. */ exception(std::string&& message) : message(message) {} const char* what()const noexcept override{ return this->message.c_str(); } }; } <commit_msg>change exception class description<commit_after>/* The MIT License (MIT) Copyright (c) 2015-2021 Ivan Gagis <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* ================ LICENSE END ================ */ #pragma once #include <exception> #include <string> namespace utki{ /** * @brief Generic exception. * * This class allows throwing an std::exception-derived exception with text message. * This class is for the cases when none of the std::logic_error nor the std::runtime_error suits. */ class exception : public std::exception{ std::string message; public: /** * @brief Constructor. * * @param message - text message to be stored in the exception object. */ exception(std::string&& message) : message(message) {} const char* what()const noexcept override{ return this->message.c_str(); } }; } <|endoftext|>
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/valid/validator.hpp> #include <nix/valid/checks.hpp> #include <nix/valid/conditions.hpp> #include <nix/valid/result.hpp> #include <nix.hpp> namespace nix { namespace valid { // --------------------------------------------------------------------- // Templated, hidden validation utils that are only here in the cpp, // not in the header (hides them from user) // --------------------------------------------------------------------- /** * @brief base entity validator * * Function taking a base entity and returning {@link Result} object * * @param entity base entity * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity(const base::Entity<T> &entity) { return validator({ must(entity, &base::Entity<T>::id, notEmpty(), "id is not set!"), must(entity, &base::Entity<T>::createdAt, notFalse(), "date is not set!") }); } /** * @brief base named entity validator * * Function taking a base named entity and returning {@link Result} * object * * @param named_entity base named entity * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_named_entity(const base::NamedEntity<T> &named_entity) { Result result_base = validate_entity<T>(named_entity); Result result = validator({ must(named_entity, &base::NamedEntity<T>::name, notEmpty(), "no name set!"), must(named_entity, &base::NamedEntity<T>::type, notEmpty(), "no type set!") }); return result.concat(result_base); } /** * @brief base entity with metadata validator * * Function taking a base entity with metadata and returning * {@link Result} object * * @param entity_with_metadata base entity with metadata * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity_with_metadata(const base::EntityWithMetadata<T> &entity_with_metadata) { return validate_named_entity<T>(entity_with_metadata); } /** * @brief base entity with sources validator * * Function taking a base entity with sources and returning * {@link Result} object * * @param entity_with_sources base entity with sources * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity_with_sources(const base::EntityWithSources<T> &entity_with_sources) { return validate_entity_with_metadata<T>(entity_with_sources); } // --------------------------------------------------------------------- // Regular validaton utils split in header & cpp part // --------------------------------------------------------------------- Result validate(const Block &block) { return validate_entity_with_metadata(block); } Result validate(const DataArray &data_array) { Result result_base = validate_entity_with_sources(data_array); Result result = validator({ must(data_array, &DataArray::dataType, notEqual<DataType>(DataType::Nothing), "data type is not set!"), must(data_array, &DataArray::dimensionCount, isEqual<size_t>(data_array.dataExtent().size()), "data dimensionality does not match number of defined dimensions!", { could(data_array, &DataArray::dimensions, notEmpty(), { should(data_array, &DataArray::dimensions, dimTicksMatchData(data_array), "in some of the Range dimensions the number of ticks differs from the number of data entries along the corresponding data dimension!"), must(data_array, &DataArray::dimensions, dimLabelsMatchData(data_array), "in some of the Set dimensions the number of labels differs from the number of data entries along the corresponding data dimension!") }) }), could(data_array, &DataArray::unit, notFalse(), { must(data_array, &DataArray::unit, isValidUnit(), "Unit is not SI or composite of SI units.") }), could(data_array, &DataArray::polynomCoefficients, notEmpty(), { should(data_array, &DataArray::expansionOrigin, notFalse(), "polynomial coefficients for calibration are set, but expansion origin is missing!") }), could(data_array, &DataArray::expansionOrigin, notFalse(), { should(data_array, &DataArray::polynomCoefficients, notEmpty(), "expansion origin for calibration is set, but polynomial coefficients are missing!") }) }); return result.concat(result_base); } Result validate(const Tag &tag) { Result result_base = validate_entity_with_sources(tag); Result result = validator({ must(tag, &Tag::position, notEmpty(), "position is not set!"), could(tag, &Tag::references, notEmpty(), { must(tag, &Tag::position, positionsMatchRefs(tag.references()), "number of entries in position does not match number of dimensions in all referenced DataArrays!"), could(tag, &Tag::extent, notEmpty(), { must(tag, &Tag::extent, extentsMatchRefs(tag.references()), "number of entries in extent does not match number of dimensions in all referenced DataArrays!") }) }), // check units for validity could(tag, &Tag::units, notEmpty(), { must(tag, &Tag::units, isValidUnit(), "Unit is invalid: not an atomic SI. Note: So far composite units are not supported!"), must(tag, &Tag::references, tagRefsHaveUnits(tag.units()), "Some of the referenced DataArrays' dimensions don't have units where the tag has. Make sure that all references have the same number of dimensions as the tag has units and that each dimension has a unit set."), must(tag, &Tag::references, tagUnitsMatchRefsUnits(tag.units()), "Some of the referenced DataArrays' dimensions have units that are not convertible to the units set in tag. Note: So far composite SI units are not supported!")}), // check positions & extents could(tag, &Tag::extent, notEmpty(), { must(tag, &Tag::position, extentsMatchPositions(tag.extent()), "Number of entries in position and extent do not match!"), must(tag, &Tag::extent, extentsMatchRefs(tag.references()), "number of entries in extent does not match number of dimensions in all referenced DataArrays!") }) }); return result.concat(result_base); } Result validate(const Property &property) { Result result_base = validate_entity(property); Result result = validator({ must(property, &Property::name, notEmpty(), "name is not set!"), could(property, &Property::valueCount, notFalse(), { should(property, &Property::unit, notFalse(), "values are set, but unit is missing!") }), could(property, &Property::unit, notFalse(), { must(property, &Property::unit, isValidUnit(), "Unit is not SI or composite of SI units.") }) // TODO: dataType to be tested too? }); return result.concat(result_base); } Result validate(const MultiTag &multi_tag) { Result result_base = validate_entity_with_sources(multi_tag); Result result = validator({ must(multi_tag, &MultiTag::positions, notFalse(), "positions are not set!"), // since extents & positions DataArray stores a vector of position / extent vectors it has to be 2-dim could(multi_tag, &MultiTag::positions, notFalse(), { must(multi_tag, &MultiTag::positions, dimEquals(2), "dimensionality of positions DataArray must be two!") }), could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::extents, dimEquals(2), "dimensionality of extents DataArray must be two!") }), // check units for validity could(multi_tag, &MultiTag::units, notEmpty(), { must(multi_tag, &MultiTag::units, isValidUnit(), "Some of the units in tag are invalid: not an atomic SI. Note: So far composite SI units are not supported!"), must(multi_tag, &MultiTag::references, tagUnitsMatchRefsUnits(multi_tag.units()), "Some of the referenced DataArrays' dimensions have units that are not convertible to the units set in tag. Note: So far composite SI units are not supported!")}), // check positions & extents could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::positions, extentsMatchPositions(multi_tag.extents()), "Number of entries in positions and extents do not match!") }), could(multi_tag, &MultiTag::references, notEmpty(), { could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::extents, extentsMatchRefs(multi_tag.references()), "number of entries (in 2nd dim) in extents does not match number of dimensions in all referenced DataArrays!") }), must(multi_tag, &MultiTag::positions, positionsMatchRefs(multi_tag.references()), "number of entries (in 2nd dim) in positions does not match number of dimensions in all referenced DataArrays!") }) }); return result.concat(result_base); } Result validate(const Dimension &dim) { return validator({ must(dim, &Dimension::index, notSmaller(1), "index is not set to valid value (> 0)!") }); } Result validate(const RangeDimension &range_dim) { return validator({ must(range_dim, &RangeDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(range_dim, &RangeDimension::ticks, notEmpty(), "ticks are not set!"), must(range_dim, &RangeDimension::dimensionType, isEqual<DimensionType>(DimensionType::Range), "dimension type is not correct!"), could(range_dim, &RangeDimension::unit, notFalse(), { must(range_dim, &RangeDimension::unit, isAtomicUnit(), "Unit is set but not an atomic SI. Note: So far composite units are not supported!") }), must(range_dim, &RangeDimension::ticks, isSorted(), "Ticks are not sorted!") }); } Result validate(const SampledDimension &sampled_dim) { return validator({ must(sampled_dim, &SampledDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(sampled_dim, &SampledDimension::samplingInterval, isGreater(0), "samplingInterval is not set to valid value (> 0)!"), must(sampled_dim, &SampledDimension::dimensionType, isEqual<DimensionType>(DimensionType::Sample), "dimension type is not correct!"), could(sampled_dim, &SampledDimension::offset, notFalse(), { should(sampled_dim, &SampledDimension::unit, isAtomicUnit(), "offset is set, but no valid unit set!") }), could(sampled_dim, &SampledDimension::unit, notFalse(), { must(sampled_dim, &SampledDimension::unit, isAtomicUnit(), "Unit is set but not an atomic SI. Note: So far composite units are not supported!") }) }); } Result validate(const SetDimension &set_dim) { return validator({ must(set_dim, &SetDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(set_dim, &SetDimension::dimensionType, isEqual<DimensionType>(DimensionType::Set), "dimension type is not correct!") }); } Result validate(const Feature &feature) { Result result_base = validate_entity(feature); Result result = validator({ must(feature, &Feature::data, notFalse(), "data is not set!"), must(feature, &Feature::linkType, notSmaller(0), "linkType is not set!") }); return result.concat(result_base); } Result validate(const Section &section) { return validate_named_entity(section); } Result validate(const Source &source) { return validate_entity_with_metadata(source); } Result validate(const File &file) { return validator({ could(file, &File::isOpen, notFalse(), { must(file, &File::createdAt, notFalse(), "date is not set!"), should(file, &File::version, notEmpty(), "version is not set!"), should(file, &File::format, notEmpty(), "format is not set!"), should(file, &File::location, notEmpty(), "location is not set!") }) }); } } // namespace valid } // namespace nix <commit_msg>[validate] the number of ticks **must** match the number of entries!<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/valid/validator.hpp> #include <nix/valid/checks.hpp> #include <nix/valid/conditions.hpp> #include <nix/valid/result.hpp> #include <nix.hpp> namespace nix { namespace valid { // --------------------------------------------------------------------- // Templated, hidden validation utils that are only here in the cpp, // not in the header (hides them from user) // --------------------------------------------------------------------- /** * @brief base entity validator * * Function taking a base entity and returning {@link Result} object * * @param entity base entity * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity(const base::Entity<T> &entity) { return validator({ must(entity, &base::Entity<T>::id, notEmpty(), "id is not set!"), must(entity, &base::Entity<T>::createdAt, notFalse(), "date is not set!") }); } /** * @brief base named entity validator * * Function taking a base named entity and returning {@link Result} * object * * @param named_entity base named entity * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_named_entity(const base::NamedEntity<T> &named_entity) { Result result_base = validate_entity<T>(named_entity); Result result = validator({ must(named_entity, &base::NamedEntity<T>::name, notEmpty(), "no name set!"), must(named_entity, &base::NamedEntity<T>::type, notEmpty(), "no type set!") }); return result.concat(result_base); } /** * @brief base entity with metadata validator * * Function taking a base entity with metadata and returning * {@link Result} object * * @param entity_with_metadata base entity with metadata * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity_with_metadata(const base::EntityWithMetadata<T> &entity_with_metadata) { return validate_named_entity<T>(entity_with_metadata); } /** * @brief base entity with sources validator * * Function taking a base entity with sources and returning * {@link Result} object * * @param entity_with_sources base entity with sources * * @returns The validation results as {@link Result} object */ template<typename T> Result validate_entity_with_sources(const base::EntityWithSources<T> &entity_with_sources) { return validate_entity_with_metadata<T>(entity_with_sources); } // --------------------------------------------------------------------- // Regular validaton utils split in header & cpp part // --------------------------------------------------------------------- Result validate(const Block &block) { return validate_entity_with_metadata(block); } Result validate(const DataArray &data_array) { Result result_base = validate_entity_with_sources(data_array); Result result = validator({ must(data_array, &DataArray::dataType, notEqual<DataType>(DataType::Nothing), "data type is not set!"), must(data_array, &DataArray::dimensionCount, isEqual<size_t>(data_array.dataExtent().size()), "data dimensionality does not match number of defined dimensions!", { could(data_array, &DataArray::dimensions, notEmpty(), { must(data_array, &DataArray::dimensions, dimTicksMatchData(data_array), "in some of the Range dimensions the number of ticks differs from the number of data entries along the corresponding data dimension!"), must(data_array, &DataArray::dimensions, dimLabelsMatchData(data_array), "in some of the Set dimensions the number of labels differs from the number of data entries along the corresponding data dimension!") }) }), could(data_array, &DataArray::unit, notFalse(), { must(data_array, &DataArray::unit, isValidUnit(), "Unit is not SI or composite of SI units.") }), could(data_array, &DataArray::polynomCoefficients, notEmpty(), { should(data_array, &DataArray::expansionOrigin, notFalse(), "polynomial coefficients for calibration are set, but expansion origin is missing!") }), could(data_array, &DataArray::expansionOrigin, notFalse(), { should(data_array, &DataArray::polynomCoefficients, notEmpty(), "expansion origin for calibration is set, but polynomial coefficients are missing!") }) }); return result.concat(result_base); } Result validate(const Tag &tag) { Result result_base = validate_entity_with_sources(tag); Result result = validator({ must(tag, &Tag::position, notEmpty(), "position is not set!"), could(tag, &Tag::references, notEmpty(), { must(tag, &Tag::position, positionsMatchRefs(tag.references()), "number of entries in position does not match number of dimensions in all referenced DataArrays!"), could(tag, &Tag::extent, notEmpty(), { must(tag, &Tag::extent, extentsMatchRefs(tag.references()), "number of entries in extent does not match number of dimensions in all referenced DataArrays!") }) }), // check units for validity could(tag, &Tag::units, notEmpty(), { must(tag, &Tag::units, isValidUnit(), "Unit is invalid: not an atomic SI. Note: So far composite units are not supported!"), must(tag, &Tag::references, tagRefsHaveUnits(tag.units()), "Some of the referenced DataArrays' dimensions don't have units where the tag has. Make sure that all references have the same number of dimensions as the tag has units and that each dimension has a unit set."), must(tag, &Tag::references, tagUnitsMatchRefsUnits(tag.units()), "Some of the referenced DataArrays' dimensions have units that are not convertible to the units set in tag. Note: So far composite SI units are not supported!")}), // check positions & extents could(tag, &Tag::extent, notEmpty(), { must(tag, &Tag::position, extentsMatchPositions(tag.extent()), "Number of entries in position and extent do not match!"), must(tag, &Tag::extent, extentsMatchRefs(tag.references()), "number of entries in extent does not match number of dimensions in all referenced DataArrays!") }) }); return result.concat(result_base); } Result validate(const Property &property) { Result result_base = validate_entity(property); Result result = validator({ must(property, &Property::name, notEmpty(), "name is not set!"), could(property, &Property::valueCount, notFalse(), { should(property, &Property::unit, notFalse(), "values are set, but unit is missing!") }), could(property, &Property::unit, notFalse(), { must(property, &Property::unit, isValidUnit(), "Unit is not SI or composite of SI units.") }) // TODO: dataType to be tested too? }); return result.concat(result_base); } Result validate(const MultiTag &multi_tag) { Result result_base = validate_entity_with_sources(multi_tag); Result result = validator({ must(multi_tag, &MultiTag::positions, notFalse(), "positions are not set!"), // since extents & positions DataArray stores a vector of position / extent vectors it has to be 2-dim could(multi_tag, &MultiTag::positions, notFalse(), { must(multi_tag, &MultiTag::positions, dimEquals(2), "dimensionality of positions DataArray must be two!") }), could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::extents, dimEquals(2), "dimensionality of extents DataArray must be two!") }), // check units for validity could(multi_tag, &MultiTag::units, notEmpty(), { must(multi_tag, &MultiTag::units, isValidUnit(), "Some of the units in tag are invalid: not an atomic SI. Note: So far composite SI units are not supported!"), must(multi_tag, &MultiTag::references, tagUnitsMatchRefsUnits(multi_tag.units()), "Some of the referenced DataArrays' dimensions have units that are not convertible to the units set in tag. Note: So far composite SI units are not supported!")}), // check positions & extents could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::positions, extentsMatchPositions(multi_tag.extents()), "Number of entries in positions and extents do not match!") }), could(multi_tag, &MultiTag::references, notEmpty(), { could(multi_tag, &MultiTag::extents, notFalse(), { must(multi_tag, &MultiTag::extents, extentsMatchRefs(multi_tag.references()), "number of entries (in 2nd dim) in extents does not match number of dimensions in all referenced DataArrays!") }), must(multi_tag, &MultiTag::positions, positionsMatchRefs(multi_tag.references()), "number of entries (in 2nd dim) in positions does not match number of dimensions in all referenced DataArrays!") }) }); return result.concat(result_base); } Result validate(const Dimension &dim) { return validator({ must(dim, &Dimension::index, notSmaller(1), "index is not set to valid value (> 0)!") }); } Result validate(const RangeDimension &range_dim) { return validator({ must(range_dim, &RangeDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(range_dim, &RangeDimension::ticks, notEmpty(), "ticks are not set!"), must(range_dim, &RangeDimension::dimensionType, isEqual<DimensionType>(DimensionType::Range), "dimension type is not correct!"), could(range_dim, &RangeDimension::unit, notFalse(), { must(range_dim, &RangeDimension::unit, isAtomicUnit(), "Unit is set but not an atomic SI. Note: So far composite units are not supported!") }), must(range_dim, &RangeDimension::ticks, isSorted(), "Ticks are not sorted!") }); } Result validate(const SampledDimension &sampled_dim) { return validator({ must(sampled_dim, &SampledDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(sampled_dim, &SampledDimension::samplingInterval, isGreater(0), "samplingInterval is not set to valid value (> 0)!"), must(sampled_dim, &SampledDimension::dimensionType, isEqual<DimensionType>(DimensionType::Sample), "dimension type is not correct!"), could(sampled_dim, &SampledDimension::offset, notFalse(), { should(sampled_dim, &SampledDimension::unit, isAtomicUnit(), "offset is set, but no valid unit set!") }), could(sampled_dim, &SampledDimension::unit, notFalse(), { must(sampled_dim, &SampledDimension::unit, isAtomicUnit(), "Unit is set but not an atomic SI. Note: So far composite units are not supported!") }) }); } Result validate(const SetDimension &set_dim) { return validator({ must(set_dim, &SetDimension::index, notSmaller(1), "index is not set to valid value (size_t > 0)!"), must(set_dim, &SetDimension::dimensionType, isEqual<DimensionType>(DimensionType::Set), "dimension type is not correct!") }); } Result validate(const Feature &feature) { Result result_base = validate_entity(feature); Result result = validator({ must(feature, &Feature::data, notFalse(), "data is not set!"), must(feature, &Feature::linkType, notSmaller(0), "linkType is not set!") }); return result.concat(result_base); } Result validate(const Section &section) { return validate_named_entity(section); } Result validate(const Source &source) { return validate_entity_with_metadata(source); } Result validate(const File &file) { return validator({ could(file, &File::isOpen, notFalse(), { must(file, &File::createdAt, notFalse(), "date is not set!"), should(file, &File::version, notEmpty(), "version is not set!"), should(file, &File::format, notEmpty(), "format is not set!"), should(file, &File::location, notEmpty(), "location is not set!") }) }); } } // namespace valid } // namespace nix <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <algorithm> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <dlfcn.h> #include <limits.h> #include <bh_config_parser.hpp> #define HOME_INI_PATH "~/.bohrium/config.ini" #define SYSTEM_INI_PATH_1 "/usr/local/etc/bohrium/config.ini" #define SYSTEM_INI_PATH_2 "/usr/etc/bohrium/config.ini" using namespace std; using namespace boost; namespace bohrium { namespace { // Path to the config file e.g. ~/.bohrium/config.ini string get_config_path() { const char *homepath = HOME_INI_PATH; const char *syspath1 = SYSTEM_INI_PATH_1; const char *syspath2 = SYSTEM_INI_PATH_2; // // Find the configuration file // // Start by looking a path set via environment variable. const char *env = getenv("BH_CONFIG"); if (env != NULL) { FILE *fp = fopen(env, "r"); if (fp) fclose(fp); else env = NULL;//Did not exist. } // Then the home directory. if (env == NULL) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( homepath, _expand_buffer, MAX_PATH-1 ); if (result != 0) { homepath = _expand_buffer; } #else char *h = getenv("HOME"); if (h != NULL) { char _expand_buffer[PATH_MAX]; snprintf(_expand_buffer, PATH_MAX, "%s/%s", h, homepath + 1); homepath = _expand_buffer; } #endif FILE *fp = fopen(homepath, "r"); if (fp) { env = homepath; fclose(fp); } } //And then system-wide. if (env == NULL) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( syspath1, _expand_buffer, MAX_PATH-1 ); if(result != 0) { syspath1 = _expand_buffer; } #endif FILE *fp = fopen(syspath1, "r"); if (fp) { env = syspath1; fclose(fp); } } //And then system-wide. if (env == NULL) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( syspath2, _expand_buffer, MAX_PATH-1 ); if(result != 0) { syspath2 = _expand_buffer; } #endif FILE *fp = fopen(syspath2, "r"); if (fp) { env = syspath2; fclose(fp); } } // We could not find the configuration file anywhere if (env == NULL) { fprintf(stderr, "Error: Bohrium could not find the config file.\n" " The search is:\n" "\t* The environment variable BH_CONFIG.\n" "\t* The home directory \"%s\".\n" "\t* The local directory \"%s\".\n" "\t* And system-wide \"%s\".\n", homepath, syspath1, syspath2); throw invalid_argument("No config file"); } return string(env); } // Return section/option as an environment variable // or the empty string if the environment variable wasn't found string lookup_env(const string &section, const string &option) { string s = "BH_" + section + "_" + option; to_upper(s); std::replace(s.begin(), s.end(), '-', '_'); // replace all '-' to '_' std::replace(s.begin(), s.end(), ' ', '_'); // replace all ' ' to '_' const char *env = getenv(s.c_str()); if (env == NULL) { return string(); } else { return string(env); } } }// namespace unnamed string ConfigParser::lookup(const string &section, const string &option) const { //Check environment variable string ret = lookup_env(section, option); if (not ret.empty()) return ret; //Check config file ret = _config.get<string>(section + "." + option); //Remove quotes "" or '' and return if (ret.find_first_of("\"'") == 0 and ret.find_last_of("\"'") == ret.size() - 1) { return ret.substr(1, ret.size() - 2); } else { return ret; } } ConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()), file_dir(boost::filesystem::path(file_path).remove_filename()), stack_level(stack_level) { // Load the bohrium configuration file property_tree::ini_parser::read_ini(file_path.string(), _config); // Find the stack name specified by 'BH_STACK' const char *env = getenv("BH_STACK"); string stack_name; if (env == nullptr) { stack_name = "default"; } else { stack_name = env; } // Read stack, which is a comma separated list of component names, // into a vector of component names. _stack_list = getList("stacks", stack_name); if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) { throw ConfigError("ConfigParser: stack level is out of bound"); } if (stack_level == -1) { _default_section = "bridge"; } else { _default_section = _stack_list[stack_level]; } } boost::filesystem::path ConfigParser::expand(boost::filesystem::path path) const { if (path.empty()) return path; string s = path.string(); if (s[0] == '~') { const char *home = getenv("HOME"); if (home == nullptr) { throw std::invalid_argument("Couldn't expand `~` since $HOME environment variable not set."); } return boost::filesystem::path(home) / boost::filesystem::path(s.substr(1)); } else { return path; } } vector<string> ConfigParser::getList(const std::string &section, const std::string &option) const { vector<string> ret; string s = get<string>(section, option); algorithm::split(ret, s, is_any_of("\t, "), token_compress_on); return ret; } vector<boost::filesystem::path> ConfigParser::getListOfPaths(const std::string &section, const std::string &option) const { vector<boost::filesystem::path> ret; for (const string &path_str: getList(section, option)) { const auto path = expand(boost::filesystem::path(path_str)); if (path.is_absolute() or path.empty()) { ret.push_back(path); } else { ret.push_back(file_dir / path); } } return ret; } string ConfigParser::getChildLibraryPath() const { // Do we have a child? if (static_cast<int>(_stack_list.size()) <= stack_level + 1) { return string(); } // Our child is our stack level plus one const string child_name = _stack_list[stack_level + 1]; return get<boost::filesystem::path>(child_name, "impl").string(); } } //namespace bohrium <commit_msg>config parser: clean up<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <algorithm> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <dlfcn.h> #include <limits.h> #include <bh_config_parser.hpp> #define HOME_INI_PATH "~/.bohrium/config.ini" #define SYSTEM_INI_PATH_1 "/usr/local/etc/bohrium/config.ini" #define SYSTEM_INI_PATH_2 "/usr/etc/bohrium/config.ini" using namespace std; using namespace boost; namespace bohrium { namespace { /// Path to the config file e.g. ~/.bohrium/config.ini string get_config_path() { const char *homepath = HOME_INI_PATH; const char *syspath1 = SYSTEM_INI_PATH_1; const char *syspath2 = SYSTEM_INI_PATH_2; // // Find the configuration file // // Start by looking a path set via environment variable. const char *env = getenv("BH_CONFIG"); if (env != nullptr) { FILE *fp = fopen(env, "r"); if (fp) fclose(fp); else env = nullptr;//Did not exist. } // Then the home directory. if (env == nullptr) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( homepath, _expand_buffer, MAX_PATH-1 ); if (result != 0) { homepath = _expand_buffer; } #else char *h = getenv("HOME"); if (h != nullptr) { char _expand_buffer[PATH_MAX]; snprintf(_expand_buffer, PATH_MAX, "%s/%s", h, homepath + 1); homepath = _expand_buffer; } #endif FILE *fp = fopen(homepath, "r"); if (fp) { env = homepath; fclose(fp); } } //And then system-wide. if (env == nullptr) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( syspath1, _expand_buffer, MAX_PATH-1 ); if(result != 0) { syspath1 = _expand_buffer; } #endif FILE *fp = fopen(syspath1, "r"); if (fp) { env = syspath1; fclose(fp); } } //And then system-wide. if (env == nullptr) { #if _WIN32 char _expand_buffer[MAX_PATH]; DWORD result = ExpandEnvironmentStrings( syspath2, _expand_buffer, MAX_PATH-1 ); if(result != 0) { syspath2 = _expand_buffer; } #endif FILE *fp = fopen(syspath2, "r"); if (fp) { env = syspath2; fclose(fp); } } // We could not find the configuration file anywhere if (env == nullptr) { fprintf(stderr, "Error: Bohrium could not find the config file.\n" " The search is:\n" "\t* The environment variable BH_CONFIG.\n" "\t* The home directory \"%s\".\n" "\t* The local directory \"%s\".\n" "\t* And system-wide \"%s\".\n", homepath, syspath1, syspath2); throw invalid_argument("No config file"); } return string(env); } /// Return section/option as an environment variable /// or the empty string if the environment variable wasn't found string lookup_env(const string &section, const string &option) { string s = "BH_" + section + "_" + option; to_upper(s); std::replace(s.begin(), s.end(), '-', '_'); // replace all '-' to '_' std::replace(s.begin(), s.end(), ' ', '_'); // replace all ' ' to '_' const char *env = getenv(s.c_str()); if (env == nullptr) { return string(); } else { return string(env); } } }// namespace unnamed string ConfigParser::lookup(const string &section, const string &option) const { //Check environment variable string ret = lookup_env(section, option); if (not ret.empty()) return ret; //Check config file ret = _config.get<string>(section + "." + option); //Remove quotes "" or '' and return if (ret.find_first_of("\"'") == 0 and ret.find_last_of("\"'") == ret.size() - 1) { return ret.substr(1, ret.size() - 2); } else { return ret; } } ConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()), file_dir(boost::filesystem::path(file_path).remove_filename()), stack_level(stack_level) { // Load the bohrium configuration file property_tree::ini_parser::read_ini(file_path.string(), _config); // Find the stack name specified by 'BH_STACK' const char *env = getenv("BH_STACK"); string stack_name; if (env == nullptr) { stack_name = "default"; } else { stack_name = env; } // Read stack, which is a comma separated list of component names, // into a vector of component names. _stack_list = getList("stacks", stack_name); if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) { throw ConfigError("ConfigParser: stack level is out of bound"); } if (stack_level == -1) { _default_section = "bridge"; } else { _default_section = _stack_list[stack_level]; } } boost::filesystem::path ConfigParser::expand(boost::filesystem::path path) const { if (path.empty()) return path; string s = path.string(); if (s[0] == '~') { const char *home = getenv("HOME"); if (home == nullptr) { throw std::invalid_argument("Couldn't expand `~` since $HOME environment variable not set."); } return boost::filesystem::path(home) / boost::filesystem::path(s.substr(1)); } else { return path; } } vector<string> ConfigParser::getList(const std::string &section, const std::string &option) const { vector<string> ret; string s = get<string>(section, option); algorithm::split(ret, s, is_any_of("\t, "), token_compress_on); return ret; } vector<boost::filesystem::path> ConfigParser::getListOfPaths(const std::string &section, const std::string &option) const { vector<boost::filesystem::path> ret; for (const string &path_str: getList(section, option)) { const auto path = expand(boost::filesystem::path(path_str)); if (path.is_absolute() or path.empty()) { ret.push_back(path); } else { ret.push_back(file_dir / path); } } return ret; } string ConfigParser::getChildLibraryPath() const { // Do we have a child? if (static_cast<int>(_stack_list.size()) <= stack_level + 1) { return string(); } // Our child is our stack level plus one const string child_name = _stack_list[stack_level + 1]; return get<boost::filesystem::path>(child_name, "impl").string(); } } //namespace bohrium <|endoftext|>
<commit_before> // Copyright (c) 2015-2016 niXman (i dot nixman dog gmail dot com). All // rights reserved. // // This file is part of CSPROT(https://github.com/niXman/csprot) project. // // 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) // // // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef _csprot_hpp_ #define _csprot_hpp_ #include <cstdint> #if __cplusplus < 201402L # error C++14 or greater is required #endif namespace csprot { /**************************************************************************/ namespace { template<typename> struct xor_char_type; template<> struct xor_char_type<char> { static constexpr const char plain_xor = 0; static constexpr const char xored_xor = 177; }; template<> struct xor_char_type<wchar_t> { static constexpr const wchar_t plain_xor = 0; static constexpr const wchar_t xored_xor = 157; }; // holder template<bool, typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder; } // anon ns /**************************************************************************/ namespace { // spec for plain strings template<typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder<false, CharType, XorChar, FirstChar, SecondChars...> { protected: static constexpr CharType _data[] = { FirstChar^XorChar, SecondChars^XorChar ..., '\0' }; constexpr const CharType* c_str() const { return _data; } }; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> constexpr const CharType string_holder<false, CharType, XorChar, FirstChar, SecondChars...>::_data[]; // spec for xor`ed strings template<typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder<true, CharType, XorChar, FirstChar, SecondChars...> { static constexpr CharType _data[] = { FirstChar^XorChar, SecondChars^XorChar ..., '\0' }; mutable char _plain[sizeof(_data)]; constexpr const CharType* c_str() const { std::size_t i = 0; for ( ; i < 1+sizeof...(SecondChars); ++i ) { _plain[i] = _data[i]^XorChar; } _plain[i]=0; return _plain; } }; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> constexpr const CharType string_holder<true, CharType, XorChar, FirstChar, SecondChars...>::_data[]; } // anon ns /**************************************************************************/ template <typename CharType, CharType XorChar, CharType... Chars> class cstring; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct cstring<CharType, XorChar, FirstChar, SecondChars...> :string_holder<XorChar==xor_char_type<CharType>::xored_xor, CharType, XorChar, FirstChar, SecondChars...> { private: using holder_type = string_holder<XorChar==xor_char_type<CharType>::xored_xor, CharType, XorChar, FirstChar, SecondChars...>; public: constexpr cstring() = default; constexpr std::size_t size() const { return 1+sizeof...(SecondChars); } constexpr std::size_t length() const { return size(); } constexpr bool empty() const { return false; } constexpr bool is_plain() const { return XorChar == xor_char_type<CharType>::plain_xor; } constexpr bool is_xored() const { return XorChar == xor_char_type<CharType>::xored_xor; } constexpr const CharType* data() const { return holder_type::_data; } using holder_type::c_str; template< CharType XorChar2 ,CharType... Chars > constexpr int compare(const cstring<CharType, XorChar2, Chars...>& other) const { for ( std::size_t i = 0; i < size() && i < other.size(); ++i ) { if (data()[i] < other.data()[i]) return -1; if (data()[i] > other.data()[i]) return 1; } if (size() < other.size()) return -1; if (size() > other.size()) return 1; return 0; } }; // spec for empty strings template<typename CharType, CharType XorChar> struct cstring<CharType, XorChar> { private: static constexpr CharType _data = '\0'; public: constexpr cstring() = default; constexpr std::size_t size() const { return 0; } constexpr std::size_t length() const { return 0; } constexpr bool empty() const { return true; } constexpr bool is_plain() const { return XorChar == xor_char_type<CharType>::plain_xor; } constexpr bool is_xored() const { return XorChar == xor_char_type<CharType>::xored_xor; } constexpr const CharType* data() const { return &_data; } constexpr const CharType* c_str() const { return &_data; } template <CharType... OtherChars> constexpr int compare(const cstring<CharType, XorChar, OtherChars...>& other) const { return other.empty() ? 0 : -1; } }; template<typename CharType, CharType XorChar> constexpr const CharType cstring<CharType, XorChar>::_data; /*****************************************************************************/ // for plain strings template<typename CharType, CharType... Chars> constexpr cstring<CharType, xor_char_type<CharType>::plain_xor, Chars...> operator"" _S() { return cstring<CharType, xor_char_type<CharType>::plain_xor, Chars...>(); } // for xor`ed strings template<typename CharType, CharType... Chars> constexpr cstring<CharType, xor_char_type<CharType>::xored_xor, Chars...> operator"" _XS() { return cstring<CharType, xor_char_type<CharType>::xored_xor, Chars...>(); } /**************************************************************************/ template< typename CharType ,CharType XorChar ,CharType... LeftChars ,CharType... RightChars > constexpr auto operator+ (const cstring<CharType, XorChar, LeftChars...> &, const cstring<CharType, XorChar, RightChars...> &) { return cstring<CharType, XorChar, LeftChars..., RightChars...>(); } template< typename CharType ,CharType XorChar ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator== (const cstring<CharType, XorChar, LeftChars...>& lhs, const cstring<CharType, XorChar, RightChars...>& rhs) { return (lhs.compare(rhs) == 0); } template< typename CharType ,CharType XorCharLeft ,CharType XorCharRight ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator== (const cstring<CharType, XorCharLeft, LeftChars...>& lhs, const cstring<CharType, XorCharRight, RightChars...>& rhs) { return (lhs.compare(rhs) == 0); } template< typename CharType ,CharType XorChar ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator!= (const cstring<CharType, XorChar, LeftChars...>& lhs, const cstring<CharType, XorChar, RightChars...>& rhs) { return !operator==(lhs, rhs); } template< typename CharType ,CharType XorCharLeft ,CharType XorCharRight ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator!= (const cstring<CharType, XorCharLeft, LeftChars...>& lhs, const cstring<CharType, XorCharRight, RightChars...>& rhs) { return !operator==(lhs, rhs); } /**************************************************************************/ } // ns csprot #endif // _csprot_hpp_ <commit_msg>some simplifications<commit_after> // Copyright (c) 2015-2016 niXman (i dot nixman dog gmail dot com). All // rights reserved. // // This file is part of CSPROT(https://github.com/niXman/csprot) project. // // 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) // // // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef _csprot_hpp_ #define _csprot_hpp_ #include <cstdint> #if __cplusplus < 201402L # error C++14 or greater is required #endif namespace csprot { /**************************************************************************/ namespace { template<typename> struct xor_char_type; template<> struct xor_char_type<char> { static constexpr const char plain_xor = 0; static constexpr const char xored_xor = 177; }; template<> struct xor_char_type<wchar_t> { static constexpr const wchar_t plain_xor = 0; static constexpr const wchar_t xored_xor = 157; }; // holder template<bool, typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder; } // anon ns /**************************************************************************/ namespace { // spec for plain strings template<typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder<false, CharType, XorChar, FirstChar, SecondChars...> { protected: static constexpr CharType _data[] = { FirstChar^XorChar, SecondChars^XorChar ..., '\0' }; constexpr const CharType* c_str() const { return _data; } }; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> constexpr const CharType string_holder<false, CharType, XorChar, FirstChar, SecondChars...>::_data[]; // spec for xor`ed strings template<typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct string_holder<true, CharType, XorChar, FirstChar, SecondChars...> { static constexpr CharType _data[] = { FirstChar^XorChar, SecondChars^XorChar ..., '\0' }; mutable char _plain[sizeof(_data)]; constexpr const CharType* c_str() const { std::size_t i = 0; for ( ; i < 1+sizeof...(SecondChars); ++i ) { _plain[i] = _data[i]^XorChar; } _plain[i]=0; return _plain; } }; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> constexpr const CharType string_holder<true, CharType, XorChar, FirstChar, SecondChars...>::_data[]; } // anon ns /**************************************************************************/ template <typename CharType, CharType XorChar, CharType... Chars> class cstring; template <typename CharType, CharType XorChar, CharType FirstChar, CharType... SecondChars> struct cstring<CharType, XorChar, FirstChar, SecondChars...> :string_holder<XorChar==xor_char_type<CharType>::xored_xor, CharType, XorChar, FirstChar, SecondChars...> { private: using holder_type = string_holder<XorChar==xor_char_type<CharType>::xored_xor, CharType, XorChar, FirstChar, SecondChars...>; public: constexpr cstring() = default; constexpr std::size_t size() const { return 1+sizeof...(SecondChars); } constexpr std::size_t length() const { return size(); } constexpr bool empty() const { return false; } constexpr bool is_plain() const { return XorChar == xor_char_type<CharType>::plain_xor; } constexpr bool is_xored() const { return XorChar == xor_char_type<CharType>::xored_xor; } constexpr const CharType* data() const { return holder_type::_data; } using holder_type::c_str; template< CharType XorChar2 ,CharType... Chars > constexpr int compare(const cstring<CharType, XorChar2, Chars...>& other) const { for ( std::size_t i = 0; i < size() && i < other.size(); ++i ) { if (data()[i] < other.data()[i]) return -1; if (data()[i] > other.data()[i]) return 1; } if (size() < other.size()) return -1; if (size() > other.size()) return 1; return 0; } }; // spec for empty strings template<typename CharType, CharType XorChar> struct cstring<CharType, XorChar> { private: static constexpr CharType _data = '\0'; public: constexpr cstring() = default; constexpr std::size_t size() const { return 0; } constexpr std::size_t length() const { return 0; } constexpr bool empty() const { return true; } constexpr bool is_plain() const { return XorChar == xor_char_type<CharType>::plain_xor; } constexpr bool is_xored() const { return XorChar == xor_char_type<CharType>::xored_xor; } constexpr const CharType* data() const { return &_data; } constexpr const CharType* c_str() const { return &_data; } template <CharType... OtherChars> constexpr int compare(const cstring<CharType, XorChar, OtherChars...>& other) const { return other.empty() ? 0 : -1; } }; template<typename CharType, CharType XorChar> constexpr const CharType cstring<CharType, XorChar>::_data; /*****************************************************************************/ // for plain strings template<typename CharType, CharType... Chars> constexpr auto operator"" _S() { return cstring<CharType, xor_char_type<CharType>::plain_xor, Chars...>(); } // for xor`ed strings template<typename CharType, CharType... Chars> constexpr auto operator"" _XS() { return cstring<CharType, xor_char_type<CharType>::xored_xor, Chars...>(); } /**************************************************************************/ template< typename CharType ,CharType XorChar ,CharType... LeftChars ,CharType... RightChars > constexpr auto operator+ (const cstring<CharType, XorChar, LeftChars...> &, const cstring<CharType, XorChar, RightChars...> &) { return cstring<CharType, XorChar, LeftChars..., RightChars...>(); } template< typename CharType ,CharType XorCharLeft ,CharType XorCharRight ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator== (const cstring<CharType, XorCharLeft, LeftChars...>& lhs, const cstring<CharType, XorCharRight, RightChars...>& rhs) { return (lhs.compare(rhs) == 0); } template< typename CharType ,CharType XorCharLeft ,CharType XorCharRight ,CharType... LeftChars ,CharType... RightChars > constexpr bool operator!= (const cstring<CharType, XorCharLeft, LeftChars...>& lhs, const cstring<CharType, XorCharRight, RightChars...>& rhs) { return !operator==(lhs, rhs); } /**************************************************************************/ } // ns csprot #endif // _csprot_hpp_ <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: rdrand.cc 11496 2012-10-09 15:16:48Z sshwarts $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2012 The Bochs Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA // ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR #include <openssl/aes.h> #include <stdlib.h> #define HW_RANDOM_GENERATOR_READY (1) BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ew(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit16u val_16 = 0; if (HW_RANDOM_GENERATOR_READY) { val_16 |= rand() & 0xff; // hack using std C rand() function val_16 <<= 8; val_16 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_16BIT_REG(i->dst(), val_16); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ed(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit32u val_32 = 0; if (HW_RANDOM_GENERATOR_READY) { val_32 |= rand() & 0xff; // hack using std C rand() function val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_32BIT_REGZ(i->dst(), val_32); BX_NEXT_INSTR(i); } /* this is the one we want to use as output covert channel */ #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Eq(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit64u val_64 = 0; uint8_t ibuf [16]; /* input buffer is organized like this: 8 bytes -- counter 6 bytes of padding 1 byte -- evilstatus 1 byte -- evilbyte */ uint8_t obuf [16]; AES_KEY keyctx; if (HW_RANDOM_GENERATOR_READY) { AES_set_encrypt_key(BX_CPU_THIS_PTR evil.aes_key, 128, &keyctx); memcpy(ibuf, &(BX_CPU_THIS_PTR evil.counter), 8); memset(ibuf + 8, 0xfe, 6); memcpy(ibuf + 8 + 6, &(BX_CPU_THIS_PTR evil.evilstatus), 1); memcpy(ibuf + 8 + 6 + 1, &(BX_CPU_THIS_PTR evil.evilbyte), 1); AES_encrypt(ibuf, obuf, &keyctx); if (BX_CPU_THIS_PTR evil.out_stat == 0) { /* output high half */ memcpy(&val_64, obuf, 8); BX_CPU_THIS_PTR evil.out_stat = 1; } else { /* output lo half */ memcpy(&val_64, obuf + 8, 8); BX_CPU_THIS_PTR evil.out_stat = 0; /* BX_CPU_THIS_PTR evil.counter++; */ } setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_64BIT_REG(i->dst(), val_64); BX_NEXT_INSTR(i); } #endif BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ew(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit16u val_16 = 0; if (HW_RANDOM_GENERATOR_READY) { val_16 |= rand() & 0xff; // hack using std C rand() function val_16 <<= 8; val_16 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_16BIT_REG(i->dst(), val_16); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ed(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit32u val_32 = 0; if (HW_RANDOM_GENERATOR_READY) { val_32 |= rand() & 0xff; // hack using std C rand() function val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_32BIT_REGZ(i->dst(), val_32); BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Eq(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit64u val_64 = 0; if (HW_RANDOM_GENERATOR_READY) { val_64 |= rand() & 0xff; // hack using std C rand() function val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_64BIT_REG(i->dst(), val_64); BX_NEXT_INSTR(i); } #endif <commit_msg>move the counter<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: rdrand.cc 11496 2012-10-09 15:16:48Z sshwarts $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2012 The Bochs Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA // ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR #include <openssl/aes.h> #include <stdlib.h> #define HW_RANDOM_GENERATOR_READY (1) BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ew(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit16u val_16 = 0; if (HW_RANDOM_GENERATOR_READY) { val_16 |= rand() & 0xff; // hack using std C rand() function val_16 <<= 8; val_16 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_16BIT_REG(i->dst(), val_16); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ed(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit32u val_32 = 0; if (HW_RANDOM_GENERATOR_READY) { val_32 |= rand() & 0xff; // hack using std C rand() function val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_32BIT_REGZ(i->dst(), val_32); BX_NEXT_INSTR(i); } /* this is the one we want to use as output covert channel */ #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Eq(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) { VMexit(VMX_VMEXIT_RDRAND, 0); } } #endif Bit64u val_64 = 0; uint8_t ibuf [16]; /* input buffer is organized like this: 8 bytes -- counter 6 bytes of padding 1 byte -- evilstatus 1 byte -- evilbyte */ uint8_t obuf [16]; AES_KEY keyctx; if (HW_RANDOM_GENERATOR_READY) { AES_set_encrypt_key(BX_CPU_THIS_PTR evil.aes_key, 128, &keyctx); memcpy(ibuf, &(BX_CPU_THIS_PTR evil.counter), 8); memset(ibuf + 8, 0xfe, 6); memcpy(ibuf + 8 + 6, &(BX_CPU_THIS_PTR evil.evilstatus), 1); memcpy(ibuf + 8 + 6 + 1, &(BX_CPU_THIS_PTR evil.evilbyte), 1); AES_encrypt(ibuf, obuf, &keyctx); if (BX_CPU_THIS_PTR evil.out_stat == 0) { /* output high half */ memcpy(&val_64, obuf, 8); BX_CPU_THIS_PTR evil.out_stat = 1; } else { /* output lo half */ memcpy(&val_64, obuf + 8, 8); BX_CPU_THIS_PTR evil.out_stat = 0; BX_CPU_THIS_PTR evil.counter++; } setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_64BIT_REG(i->dst(), val_64); BX_NEXT_INSTR(i); } #endif BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ew(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit16u val_16 = 0; if (HW_RANDOM_GENERATOR_READY) { val_16 |= rand() & 0xff; // hack using std C rand() function val_16 <<= 8; val_16 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_16BIT_REG(i->dst(), val_16); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ed(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit32u val_32 = 0; if (HW_RANDOM_GENERATOR_READY) { val_32 |= rand() & 0xff; // hack using std C rand() function val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; val_32 <<= 8; val_32 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_32BIT_REGZ(i->dst(), val_32); BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Eq(bxInstruction_c *i) { #if BX_SUPPORT_VMX if (BX_CPU_THIS_PTR in_vmx_guest) { if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) { VMexit(VMX_VMEXIT_RDSEED, 0); } } #endif Bit64u val_64 = 0; if (HW_RANDOM_GENERATOR_READY) { val_64 |= rand() & 0xff; // hack using std C rand() function val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; val_64 <<= 8; val_64 |= rand() & 0xff; setEFlagsOSZAPC(EFlagsCFMask); } else { setEFlagsOSZAPC(0); } BX_WRITE_64BIT_REG(i->dst(), val_64); BX_NEXT_INSTR(i); } #endif <|endoftext|>
<commit_before>#include "vboMesh.h" #include "platform.h" #define MAX_INDEX_VALUE 65535 // Maximum value of GLushort int VboMesh::s_validGeneration = 0; VboMesh::VboMesh() { m_glVertexBuffer = 0; m_glIndexBuffer = 0; m_nVertices = 0; m_nIndices = 0; m_dirtyOffset = 0; m_dirtySize = 0; m_dirty = false; m_isUploaded = false; m_isCompiled = false; m_generation = -1; } VboMesh::VboMesh(std::shared_ptr<VertexLayout> _vertexLayout, GLenum _drawMode, GLenum _hint) : VboMesh() { m_vertexLayout = _vertexLayout; m_hint = _hint; setDrawMode(_drawMode); } VboMesh::~VboMesh() { if (m_glVertexBuffer) glDeleteBuffers(1, &m_glVertexBuffer); if (m_glIndexBuffer) glDeleteBuffers(1, &m_glIndexBuffer); delete[] m_glVertexData; delete[] m_glIndexData; } void VboMesh::setVertexLayout(std::shared_ptr<VertexLayout> _vertexLayout) { m_vertexLayout = _vertexLayout; } void VboMesh::setDrawMode(GLenum _drawMode) { switch (_drawMode) { case GL_POINTS: case GL_LINE_STRIP: case GL_LINE_LOOP: case GL_LINES: case GL_TRIANGLE_STRIP: case GL_TRIANGLE_FAN: case GL_TRIANGLES: m_drawMode = _drawMode; break; default: logMsg("WARNING: Invalid draw mode for mesh! Defaulting to GL_TRIANGLES\n"); m_drawMode = GL_TRIANGLES; } } void VboMesh::update(intptr_t _offset, long _size, unsigned char* _data) { if (m_hint == GL_STATIC_DRAW) { logMsg("WARNING: wrong usage hint provided to the Vbo\n"); } std::memcpy(m_glVertexData + _offset, _data, _size); m_dirtyOffset = _offset; m_dirtySize = _size; m_dirty = true; } void VboMesh::subDataUpload() { if (m_dirtySize != 0) { glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); long vertexBytes = m_nVertices * m_vertexLayout->getStride(); // updating the entire buffer if (std::abs(m_dirtySize - vertexBytes) < m_vertexLayout->getStride()) { // invalidate the data store on the driver glBufferData(GL_ARRAY_BUFFER, vertexBytes, NULL, m_hint); // if this buffer is still used by gpu on current frame this call will not wait // for the frame to finish using the vbo but directly upload the data glBufferData(GL_ARRAY_BUFFER, vertexBytes, m_glVertexData, m_hint); } else { // perform simple sub data upload for part of the buffer glBufferSubData(GL_ARRAY_BUFFER, m_dirtyOffset, m_dirtySize, m_glVertexData + m_dirtyOffset); } m_dirtyOffset = 0; m_dirtySize = 0; } m_dirty = false; } void VboMesh::upload() { // Generate vertex buffer, if needed if (m_glVertexBuffer == 0) { glGenBuffers(1, &m_glVertexBuffer); } // TODO check if compiled? // Buffer vertex data int vertexBytes = m_nVertices * m_vertexLayout->getStride(); glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertexBytes, m_glVertexData, m_hint); if (m_glIndexData) { if (m_glIndexBuffer == 0) { glGenBuffers(1, &m_glIndexBuffer); } // Buffer element index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_glIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_nIndices * sizeof(GLushort), m_glIndexData, m_hint); } // m_glVertexData.resize(0); // m_glIndexData.resize(0); // TODO: For now, we retain copies of the vertex and index data in CPU memory to allow VBOs // to easily rebuild themselves after GL context loss. For optimizing memory usage (and for // other reasons) we'll want to change this in the future. This probably means going back to // data sources and styles to rebuild the vertex data. m_generation = s_validGeneration; m_isUploaded = true; } void VboMesh::draw(const std::shared_ptr<ShaderProgram> _shader) { checkValidity(); if (!m_isCompiled) return; if (m_nVertices == 0) return; // Ensure that geometry is buffered into GPU if (!m_isUploaded) { upload(); } if (m_dirty) { subDataUpload(); } // Bind buffers for drawing glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); if (m_nIndices > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_glIndexBuffer); } // Enable shader program _shader->use(); size_t indiceOffset = 0; size_t vertexOffset = 0; for (auto& o : m_vertexOffsets) { uint32_t nIndices = o.first; uint32_t nVertices = o.second; size_t byteOffset = vertexOffset * m_vertexLayout->getStride(); // Enable vertex attribs via vertex layout object m_vertexLayout->enable(_shader, byteOffset); // Draw as elements or arrays if (nIndices > 0) { glDrawElements(m_drawMode, nIndices, GL_UNSIGNED_SHORT, (void*)(indiceOffset * sizeof(GLushort))); } else if (nVertices > 0) { glDrawArrays(m_drawMode, 0, nVertices); } vertexOffset += nVertices; indiceOffset += nIndices; } } void VboMesh::checkValidity() { if (m_generation != s_validGeneration) { m_isUploaded = false; m_glVertexBuffer = 0; m_glIndexBuffer = 0; m_generation = s_validGeneration; } } void VboMesh::invalidateAllVBOs() { ++s_validGeneration; } <commit_msg>subDataUpload<commit_after>#include "vboMesh.h" #include "platform.h" #define MAX_INDEX_VALUE 65535 // Maximum value of GLushort int VboMesh::s_validGeneration = 0; VboMesh::VboMesh() { m_glVertexBuffer = 0; m_glIndexBuffer = 0; m_nVertices = 0; m_nIndices = 0; m_dirtyOffset = 0; m_dirtySize = 0; m_dirty = false; m_isUploaded = false; m_isCompiled = false; m_generation = -1; } VboMesh::VboMesh(std::shared_ptr<VertexLayout> _vertexLayout, GLenum _drawMode, GLenum _hint) : VboMesh() { m_vertexLayout = _vertexLayout; m_hint = _hint; setDrawMode(_drawMode); } VboMesh::~VboMesh() { if (m_glVertexBuffer) glDeleteBuffers(1, &m_glVertexBuffer); if (m_glIndexBuffer) glDeleteBuffers(1, &m_glIndexBuffer); delete[] m_glVertexData; delete[] m_glIndexData; } void VboMesh::setVertexLayout(std::shared_ptr<VertexLayout> _vertexLayout) { m_vertexLayout = _vertexLayout; } void VboMesh::setDrawMode(GLenum _drawMode) { switch (_drawMode) { case GL_POINTS: case GL_LINE_STRIP: case GL_LINE_LOOP: case GL_LINES: case GL_TRIANGLE_STRIP: case GL_TRIANGLE_FAN: case GL_TRIANGLES: m_drawMode = _drawMode; break; default: logMsg("WARNING: Invalid draw mode for mesh! Defaulting to GL_TRIANGLES\n"); m_drawMode = GL_TRIANGLES; } } void VboMesh::update(intptr_t _offset, long _size, unsigned char* _data) { if (m_hint == GL_STATIC_DRAW) { logMsg("WARNING: wrong usage hint provided to the Vbo\n"); } std::memcpy(m_glVertexData + _offset, _data, _size); m_dirtyOffset = _offset; m_dirtySize = _size; m_dirty = true; } void VboMesh::subDataUpload() { if (m_dirtySize != 0) { glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); long vertexBytes = m_nVertices * m_vertexLayout->getStride(); // updating the entire buffer if (std::abs(m_dirtySize - vertexBytes) < m_vertexLayout->getStride()) { // invalidate the data store on the driver glBufferData(GL_ARRAY_BUFFER, vertexBytes, NULL, m_hint); // if this buffer is still used by gpu on current frame this call will not wait // for the frame to finish using the vbo but directly upload the data glBufferData(GL_ARRAY_BUFFER, vertexBytes, m_glVertexData, m_hint); } else { // perform simple sub data upload for part of the buffer glBufferSubData(GL_ARRAY_BUFFER, m_dirtyOffset, m_dirtySize, m_glVertexData + m_dirtyOffset); } m_dirtyOffset = 0; m_dirtySize = 0; } m_dirty = false; } void VboMesh::upload() { // Generate vertex buffer, if needed if (m_glVertexBuffer == 0) { glGenBuffers(1, &m_glVertexBuffer); } // TODO check if compiled? // Buffer vertex data int vertexBytes = m_nVertices * m_vertexLayout->getStride(); glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertexBytes, m_glVertexData, m_hint); if (m_glIndexData) { if (m_glIndexBuffer == 0) { glGenBuffers(1, &m_glIndexBuffer); } // Buffer element index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_glIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_nIndices * sizeof(GLushort), m_glIndexData, m_hint); } // m_glVertexData.resize(0); // m_glIndexData.resize(0); // TODO: For now, we retain copies of the vertex and index data in CPU memory to allow VBOs // to easily rebuild themselves after GL context loss. For optimizing memory usage (and for // other reasons) we'll want to change this in the future. This probably means going back to // data sources and styles to rebuild the vertex data. m_generation = s_validGeneration; m_isUploaded = true; } void VboMesh::draw(const std::shared_ptr<ShaderProgram> _shader) { checkValidity(); if (!m_isCompiled) return; if (m_nVertices == 0) return; // Ensure that geometry is buffered into GPU if (!m_isUploaded) { upload(); } else if (m_dirty) { subDataUpload(); } // Bind buffers for drawing glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer); if (m_nIndices > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_glIndexBuffer); } // Enable shader program _shader->use(); size_t indiceOffset = 0; size_t vertexOffset = 0; for (auto& o : m_vertexOffsets) { uint32_t nIndices = o.first; uint32_t nVertices = o.second; size_t byteOffset = vertexOffset * m_vertexLayout->getStride(); // Enable vertex attribs via vertex layout object m_vertexLayout->enable(_shader, byteOffset); // Draw as elements or arrays if (nIndices > 0) { glDrawElements(m_drawMode, nIndices, GL_UNSIGNED_SHORT, (void*)(indiceOffset * sizeof(GLushort))); } else if (nVertices > 0) { glDrawArrays(m_drawMode, 0, nVertices); } vertexOffset += nVertices; indiceOffset += nIndices; } } void VboMesh::checkValidity() { if (m_generation != s_validGeneration) { m_isUploaded = false; m_glVertexBuffer = 0; m_glIndexBuffer = 0; m_generation = s_validGeneration; } } void VboMesh::invalidateAllVBOs() { ++s_validGeneration; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file df_ms5607_wrapper.cpp * Lightweight driver to access the MS5607 of the DriverFramework. */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_baro.h> #include <board_config.h> #include <ms5607/MS5607.hpp> #include <DevMgr.hpp> extern "C" { __EXPORT int df_ms5607_wrapper_main(int argc, char *argv[]); } using namespace DriverFramework; class DfMS5607Wrapper : public MS5607 { public: DfMS5607Wrapper(); ~DfMS5607Wrapper(); /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: int _publish(struct baro_sensor_data &data); orb_advert_t _baro_topic; int _baro_orb_class_instance; perf_counter_t _baro_sample_perf; }; DfMS5607Wrapper::DfMS5607Wrapper() : MS5607(BARO_DEVICE_PATH), _baro_topic(nullptr), _baro_orb_class_instance(-1), _baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read")) { } DfMS5607Wrapper::~DfMS5607Wrapper() { perf_free(_baro_sample_perf); } int DfMS5607Wrapper::start() { /* Init device and start sensor. */ int ret = init(); if (ret != 0) { PX4_ERR("MS5607 init fail: %d", ret); return ret; } ret = MS5607::start(); if (ret != 0) { PX4_ERR("MS5607 start fail: %d", ret); return ret; } return 0; } int DfMS5607Wrapper::stop() { /* Stop sensor. */ int ret = MS5607::stop(); if (ret != 0) { PX4_ERR("MS5607 stop fail: %d", ret); return ret; } return 0; } int DfMS5607Wrapper::_publish(struct baro_sensor_data &data) { perf_begin(_baro_sample_perf); baro_report baro_report = {}; baro_report.timestamp = hrt_absolute_time(); baro_report.pressure = data.pressure_pa; baro_report.temperature = data.temperature_c; // TODO: verify this, it's just copied from the MS5611 driver. // Constant for now const double MSL_PRESSURE_KPA = 101325.0 / 1000.0; /* tropospheric properties (0-11km) for standard atmosphere */ const double T1 = 15.0 + 273.15; /* temperature at base height in Kelvin */ const double a = -6.5 / 1000; /* temperature gradient in degrees per metre */ const double g = 9.80665; /* gravity constant in m/s/s */ const double R = 287.05; /* ideal gas constant in J/kg/K */ /* current pressure at MSL in kPa */ double p1 = MSL_PRESSURE_KPA; /* measured pressure in kPa */ double p = static_cast<double>(data.pressure_pa) / 1000.0; /* * Solve: * * / -(aR / g) \ * | (p / p1) . T1 | - T1 * \ / * h = ------------------------------- + h1 * a */ baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_baro_topic == nullptr) { _baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report, &_baro_orb_class_instance, ORB_PRIO_DEFAULT); } else { orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report); } } /* Notify anyone waiting for data. */ DevMgr::updateNotify(*this); perf_end(_baro_sample_perf); return 0; }; namespace df_ms5607_wrapper { DfMS5607Wrapper *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfMS5607Wrapper(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfMS5607Wrapper object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfMS5607Wrapper start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(BARO_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", BARO_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_ms5607_wrapper 'start', 'info', 'stop'"); } } // namespace df_ms5607_wrapper int df_ms5607_wrapper_main(int argc, char *argv[]) { int ret = 0; int myoptind = 1; if (argc <= 1) { df_ms5607_wrapper::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_ms5607_wrapper::start(); } else if (!strcmp(verb, "stop")) { ret = df_ms5607_wrapper::stop(); } else if (!strcmp(verb, "info")) { ret = df_ms5607_wrapper::info(); } else { df_ms5607_wrapper::usage(); return 1; } return ret; } <commit_msg>df_ms5607_wrapper: astyle (#4853)<commit_after>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file df_ms5607_wrapper.cpp * Lightweight driver to access the MS5607 of the DriverFramework. */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_baro.h> #include <board_config.h> #include <ms5607/MS5607.hpp> #include <DevMgr.hpp> extern "C" { __EXPORT int df_ms5607_wrapper_main(int argc, char *argv[]); } using namespace DriverFramework; class DfMS5607Wrapper : public MS5607 { public: DfMS5607Wrapper(); ~DfMS5607Wrapper(); /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: int _publish(struct baro_sensor_data &data); orb_advert_t _baro_topic; int _baro_orb_class_instance; perf_counter_t _baro_sample_perf; }; DfMS5607Wrapper::DfMS5607Wrapper() : MS5607(BARO_DEVICE_PATH), _baro_topic(nullptr), _baro_orb_class_instance(-1), _baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read")) { } DfMS5607Wrapper::~DfMS5607Wrapper() { perf_free(_baro_sample_perf); } int DfMS5607Wrapper::start() { /* Init device and start sensor. */ int ret = init(); if (ret != 0) { PX4_ERR("MS5607 init fail: %d", ret); return ret; } ret = MS5607::start(); if (ret != 0) { PX4_ERR("MS5607 start fail: %d", ret); return ret; } return 0; } int DfMS5607Wrapper::stop() { /* Stop sensor. */ int ret = MS5607::stop(); if (ret != 0) { PX4_ERR("MS5607 stop fail: %d", ret); return ret; } return 0; } int DfMS5607Wrapper::_publish(struct baro_sensor_data &data) { perf_begin(_baro_sample_perf); baro_report baro_report = {}; baro_report.timestamp = hrt_absolute_time(); baro_report.pressure = data.pressure_pa; baro_report.temperature = data.temperature_c; // TODO: verify this, it's just copied from the MS5611 driver. // Constant for now const double MSL_PRESSURE_KPA = 101325.0 / 1000.0; /* tropospheric properties (0-11km) for standard atmosphere */ const double T1 = 15.0 + 273.15; /* temperature at base height in Kelvin */ const double a = -6.5 / 1000; /* temperature gradient in degrees per metre */ const double g = 9.80665; /* gravity constant in m/s/s */ const double R = 287.05; /* ideal gas constant in J/kg/K */ /* current pressure at MSL in kPa */ double p1 = MSL_PRESSURE_KPA; /* measured pressure in kPa */ double p = static_cast<double>(data.pressure_pa) / 1000.0; /* * Solve: * * / -(aR / g) \ * | (p / p1) . T1 | - T1 * \ / * h = ------------------------------- + h1 * a */ baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_baro_topic == nullptr) { _baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report, &_baro_orb_class_instance, ORB_PRIO_DEFAULT); } else { orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report); } } /* Notify anyone waiting for data. */ DevMgr::updateNotify(*this); perf_end(_baro_sample_perf); return 0; }; namespace df_ms5607_wrapper { DfMS5607Wrapper *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfMS5607Wrapper(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfMS5607Wrapper object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfMS5607Wrapper start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(BARO_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", BARO_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_ms5607_wrapper 'start', 'info', 'stop'"); } } // namespace df_ms5607_wrapper int df_ms5607_wrapper_main(int argc, char *argv[]) { int ret = 0; int myoptind = 1; if (argc <= 1) { df_ms5607_wrapper::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_ms5607_wrapper::start(); } else if (!strcmp(verb, "stop")) { ret = df_ms5607_wrapper::stop(); } else if (!strcmp(verb, "info")) { ret = df_ms5607_wrapper::info(); } else { df_ms5607_wrapper::usage(); return 1; } return ret; } <|endoftext|>
<commit_before>// Parse test application // Based upon: parsetest.cpp from xmlpp // needed includes #include <fstream> #include <iostream> //#include <ctime> #include <cppdom/cppdom.h> #include <testHelpers.h> // namespace includes using namespace cppdom; using namespace std; void process_xml( std::string filename ) { cout << "processing [" << filename << "] ..." << endl; ContextPtr context( new Context ); Document node( context ); ifstream istr( filename.c_str() ); // Verify that file opened if(!istr) { std::cerr << "Bad file: " << filename << std::endl; return; } try { // clock_t tstart = ::clock(); node.load( istr, context ); // clock_t tstop = ::clock(); // cout << " needed " << // (tstop-tstart)/static_cast<float>(CLOCKS_PER_SEC) // << " seconds." << endl; testHelpers::dump_node( node ); ofstream ostr( "parsetest.xml" ); node.save( ostr ); ostr.close(); } catch (Error e) { Location where( context->getLocation() ); std::string errmsg; e.getStrError(errmsg); // print out where the error occured cout << filename << ":" << where.getLine() << " "; cout << "at position " << where.getPos(); cout << ": error: " << errmsg.c_str(); cout << endl; // print out line where the error occured ifstream errfile( filename.c_str() ); if(!errfile) { std::cerr << "Can't open file [" << filename << "] to output error" << std::endl; } int linenr = where.getLine(); char linebuffer[1024]; for(int i=0; i<linenr && !errfile.eof(); i++) errfile.getline( linebuffer,1024 ); int pos = where.getPos(); if (pos>=80) pos %= 80; std::string err_line( linebuffer + (where.getPos()-pos) ); if (err_line.length()>=79) err_line.erase(79); cout << err_line << std::flush; cout << err_line.c_str() << std::endl; cout << linebuffer << std::endl; for(int j=2;j<pos;j++) std::cout << " "; cout << '^' << endl; } } int main(int argc, char* argv[]) { for(int i=1;i<argc;i++) { process_xml( std::string(argv[i]) ); } return 0; } <commit_msg>Fix up the test build that someone broke a couple of days ago.<commit_after>// Parse test application // Based upon: parsetest.cpp from xmlpp // needed includes #include <fstream> #include <iostream> //#include <ctime> #include <cppdom/cppdom.h> #include <testHelpers.h> // namespace includes using namespace cppdom; using namespace std; void process_xml( std::string filename ) { cout << "processing [" << filename << "] ..." << endl; ContextPtr context( new Context ); Document node( context ); ifstream istr( filename.c_str() ); // Verify that file opened if(!istr) { std::cerr << "Bad file: " << filename << std::endl; return; } try { // clock_t tstart = ::clock(); node.load( istr, context ); // clock_t tstop = ::clock(); // cout << " needed " << // (tstop-tstart)/static_cast<float>(CLOCKS_PER_SEC) // << " seconds." << endl; testHelpers::dump_node( node ); ofstream ostr( "parsetest.xml" ); node.save( ostr ); ostr.close(); } catch (Error e) { Location where( context->getLocation() ); std::string errmsg = e.getStrError(); // print out where the error occured cout << filename << ":" << where.getLine() << " "; cout << "at position " << where.getPos(); cout << ": error: " << errmsg.c_str(); cout << endl; // print out line where the error occured ifstream errfile( filename.c_str() ); if(!errfile) { std::cerr << "Can't open file [" << filename << "] to output error" << std::endl; } int linenr = where.getLine(); char linebuffer[1024]; for(int i=0; i<linenr && !errfile.eof(); i++) errfile.getline( linebuffer,1024 ); int pos = where.getPos(); if (pos>=80) pos %= 80; std::string err_line( linebuffer + (where.getPos()-pos) ); if (err_line.length()>=79) err_line.erase(79); cout << err_line << std::flush; cout << err_line.c_str() << std::endl; cout << linebuffer << std::endl; for(int j=2;j<pos;j++) std::cout << " "; cout << '^' << endl; } } int main(int argc, char* argv[]) { for(int i=1;i<argc;i++) { process_xml( std::string(argv[i]) ); } return 0; } <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifdef GOOGLE_CUDA #include "tensorflow/stream_executor/cuda/cuda_activation.h" #include "third_party/gpus/cuda/include/cuda.h" #include "third_party/gpus/cuda/include/cuda_runtime_api.h" #endif // GOOGLE_CUDA #include "tensorflow/core/common_runtime/gpu/gpu_cudamallocasync_allocator.h" #include "tensorflow/core/common_runtime/device/device_id_utils.h" #include "tensorflow/core/common_runtime/gpu/gpu_id.h" #include "tensorflow/core/common_runtime/gpu/gpu_init.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/platform/stream_executor.h" #include "tensorflow/core/util/env_var.h" namespace tensorflow { GpuCudaMallocAsyncAllocator::GpuCudaMallocAsyncAllocator( PlatformGpuId platform_gpu_id, size_t pool_size, bool reserve_memory, bool compute_stats) : name_(absl::StrCat("gpu_async_", platform_gpu_id.value())) { stream_exec_ = DeviceIdUtil::ExecutorForPlatformDeviceId(GPUMachineManager(), platform_gpu_id).ValueOrDie(); #if CUDA_VERSION < 11020 LOG(FATAL) << "TF_GPU_ALLOCATOR=cuda_malloc_async need CUDA 11.2 or higher to compile."; #elif !defined(GOOGLE_CUDA) LOG(FATAL) << "GOOGLE_CUDA not defined"; #else // Initialized here as it only exist if compiled with a recent // enough CUDA. pool_ = nullptr; cuda_stream_ = nullptr; // WAR an CUDA 11.2 driver bug for multiple-GPU. It currently // request that the context on GPU 0 is initialized. Which isn't the // case for TF+horovod. if (platform_gpu_id.value() > 0) { CUcontext pctx; // We loose track of it. But this is fine. CUresult err = cuDevicePrimaryCtxRetain(&pctx, 0); if (err != CUDA_SUCCESS){ LOG(FATAL) << "Failed to create the context on device 0."; } } se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; int cuda_malloc_async_supported; cudaDeviceGetAttribute(&cuda_malloc_async_supported, cudaDevAttrMemoryPoolsSupported, platform_gpu_id.value()); if (!cuda_malloc_async_supported) { LOG(FATAL) << "TF_GPU_ALLOCATOR=cuda_malloc_async isn't currently supported." << " Possible causes: device not supported, driver too old, " << " OS not supported, CUDA version too old."; } cudaError_t cerr = cudaStreamCreate(&cuda_stream_); if (cerr != cudaSuccess) { LOG(FATAL) << "could not allocate CUDA stream for context : " << cudaGetErrorString(cerr); } cerr = cudaDeviceGetDefaultMemPool(&pool_, platform_gpu_id.value()); if (cerr != cudaSuccess) { LOG(FATAL) << "could not get the default CUDA pool : " << cudaGetErrorString(cerr); } VLOG(1) << Name() << " CudaMallocAsync initialized on platform: " << platform_gpu_id.value() << " with pool size of: " << pool_size << " this ptr: " << this; cerr = cudaMemPoolSetAttribute(pool_, cudaMemPoolAttrReleaseThreshold, reinterpret_cast<void*>(&pool_size)); if (compute_stats) { mutex_lock lock(lock_); stats_.bytes_limit = static_cast<int64>(pool_size); } // If not set, it means we do not compute stats. if (cerr != cudaSuccess) { LOG(FATAL) << "could not set the default CUDA pool memory threshold : " << cudaGetErrorString(cerr); pool_ = nullptr; } // If in TF_DETERMINISTIC_OPS is set, then make the allocator behave // determistically. bool deterministic_ops = false; TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar("TF_DETERMINISTIC_OPS", /*default_val=*/false, &deterministic_ops)); if (deterministic_ops) { cudaMemPoolSetAttribute(pool_, cudaMemPoolReuseAllowOpportunistic, 0); cudaMemPoolSetAttribute(pool_, cudaMemPoolReuseAllowInternalDependencies, 0); } #endif VLOG(2) << Name() << " GpuCudaMallocAsyncAllocator PoolSize " << pool_size; if (reserve_memory) { void* ptr = AllocateRaw(0, pool_size); DeallocateRaw(ptr); VLOG(2) << Name() << " GpuCudaMallocAsyncAllocator reserved the pool"; ClearStats(); } } GpuCudaMallocAsyncAllocator::~GpuCudaMallocAsyncAllocator() { #ifdef GOOGLE_CUDA cuStreamDestroy(cuda_stream_); #endif } void* GpuCudaMallocAsyncAllocator::AllocateRaw(size_t alignment, size_t num_bytes) { #if CUDA_VERSION < 11020 || !defined(GOOGLE_CUDA) return nullptr; #else if (pool_ == nullptr) { LOG(FATAL) << "The instantiation of GpuCudaMallocAsyncAllocator failed." << " See previous errors."; } se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; void* ptr = 0; cudaError_t res = cudaMallocFromPoolAsync(&ptr, num_bytes, pool_, cuda_stream_); if (res != cudaSuccess) { size_t free, total; cudaMemGetInfo(&free, &total); mutex_lock lock(lock_); LOG(ERROR) << Name() << " cudaMallocAsync failed to allocate " << num_bytes << "\n Error name: " << cudaGetErrorName(res) << "\n Error string: " << cudaGetErrorString(res) << "\n Free memory/Total memory: " << free << "/" << total << "\n Stats: \n" << stats_.DebugString(); return nullptr; } // Update stats. if (stats_.bytes_limit.has_value()) { mutex_lock lock(lock_); ++stats_.num_allocs; stats_.bytes_in_use += num_bytes; stats_.peak_bytes_in_use = std::max(stats_.peak_bytes_in_use, stats_.bytes_in_use); stats_.largest_alloc_size = std::max<std::size_t>(stats_.largest_alloc_size, num_bytes); size_map_[ptr] = num_bytes; } VLOG(10) << Name() << " Allocated " << num_bytes << " at " << ptr; return ptr; #endif } void GpuCudaMallocAsyncAllocator::DeallocateRaw(void* ptr) { #if CUDA_VERSION < 11020 || !defined(GOOGLE_CUDA) #else cudaError_t res = cudaFreeAsync(ptr, cuda_stream_); if (res == cudaErrorCudartUnloading) { // It happens with multi-GPU that TF free the GPU allocation after // the driver is unloaded. It is safe to ignore this error here. // TODO: Find how to fix the shutdown steps in TF. VLOG(1) << "Ignoring Error: " << cudaGetErrorName(res) << " \nError string: " << cudaGetErrorString(res); } else if (res != cudaSuccess) { size_t free, total; se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; cudaMemGetInfo(&free, &total); LOG(ERROR) << "cudaFreeAsync failed to free " << ptr << "\n Error name: " << cudaGetErrorName(res) << "\n Error string: " << cudaGetErrorString(res) << "\n Free memory/Total memory: " << free << "/" << total << "\n Stats: \n" << stats_.DebugString(); } // Updates the stats. if (stats_.bytes_limit.has_value()) { mutex_lock lock(lock_); DCHECK(size_map_.contains(ptr)); size_t size = size_map_[ptr]; stats_.bytes_in_use -= size; size_map_.erase(ptr); } VLOG(10) << Name() << " Freed ptr: " << ptr; #endif // GOOGLE_CUDA } bool GpuCudaMallocAsyncAllocator::TracksAllocationSizes() const { return stats_.bytes_limit.has_value(); } size_t GpuCudaMallocAsyncAllocator::RequestedSize(const void* ptr) const { CHECK(ptr); return size_map_.at(ptr); } size_t GpuCudaMallocAsyncAllocator::AllocatedSize(const void* ptr) const { CHECK(ptr); return size_map_.at(ptr); } absl::optional<AllocatorStats> GpuCudaMallocAsyncAllocator::GetStats() { mutex_lock l(lock_); return stats_; } void GpuCudaMallocAsyncAllocator::ClearStats() { mutex_lock l(lock_); stats_.num_allocs = 0; stats_.peak_bytes_in_use = stats_.bytes_in_use; stats_.largest_alloc_size = 0; } } // namespace tensorflow <commit_msg>cudaMallocAsync: allow to preallocate memory with the env variable TF_CUDA_MALLOC_ASYNC_PREALLOC=num_bytes. -1 preallocate the full pool size.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifdef GOOGLE_CUDA #include "tensorflow/stream_executor/cuda/cuda_activation.h" #include "third_party/gpus/cuda/include/cuda.h" #include "third_party/gpus/cuda/include/cuda_runtime_api.h" #endif // GOOGLE_CUDA #include "tensorflow/core/common_runtime/gpu/gpu_cudamallocasync_allocator.h" #include "tensorflow/core/common_runtime/device/device_id_utils.h" #include "tensorflow/core/common_runtime/gpu/gpu_id.h" #include "tensorflow/core/common_runtime/gpu/gpu_init.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/platform/stream_executor.h" #include "tensorflow/core/util/env_var.h" namespace tensorflow { GpuCudaMallocAsyncAllocator::GpuCudaMallocAsyncAllocator( PlatformGpuId platform_gpu_id, size_t pool_size, bool reserve_memory, bool compute_stats) : name_(absl::StrCat("gpu_async_", platform_gpu_id.value())) { stream_exec_ = DeviceIdUtil::ExecutorForPlatformDeviceId(GPUMachineManager(), platform_gpu_id).ValueOrDie(); #if CUDA_VERSION < 11020 LOG(FATAL) << "TF_GPU_ALLOCATOR=cuda_malloc_async need CUDA 11.2 or higher to compile."; #elif !defined(GOOGLE_CUDA) LOG(FATAL) << "GOOGLE_CUDA not defined"; #else // Initialized here as it only exist if compiled with a recent // enough CUDA. pool_ = nullptr; cuda_stream_ = nullptr; // WAR an CUDA 11.2 driver bug for multiple-GPU. It currently // request that the context on GPU 0 is initialized. Which isn't the // case for TF+horovod. if (platform_gpu_id.value() > 0) { CUcontext pctx; // We loose track of it. But this is fine. CUresult err = cuDevicePrimaryCtxRetain(&pctx, 0); if (err != CUDA_SUCCESS){ LOG(FATAL) << "Failed to create the context on device 0."; } } se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; int cuda_malloc_async_supported; cudaDeviceGetAttribute(&cuda_malloc_async_supported, cudaDevAttrMemoryPoolsSupported, platform_gpu_id.value()); if (!cuda_malloc_async_supported) { LOG(FATAL) << "TF_GPU_ALLOCATOR=cuda_malloc_async isn't currently supported." << " Possible causes: device not supported, driver too old, " << " OS not supported, CUDA version too old."; } cudaError_t cerr = cudaStreamCreate(&cuda_stream_); if (cerr != cudaSuccess) { LOG(FATAL) << "could not allocate CUDA stream for context : " << cudaGetErrorString(cerr); } cerr = cudaDeviceGetDefaultMemPool(&pool_, platform_gpu_id.value()); if (cerr != cudaSuccess) { LOG(FATAL) << "could not get the default CUDA pool : " << cudaGetErrorString(cerr); } VLOG(1) << Name() << " CudaMallocAsync initialized on platform: " << platform_gpu_id.value() << " with pool size of: " << pool_size << " this ptr: " << this; cerr = cudaMemPoolSetAttribute(pool_, cudaMemPoolAttrReleaseThreshold, reinterpret_cast<void*>(&pool_size)); if (compute_stats) { mutex_lock lock(lock_); stats_.bytes_limit = static_cast<int64>(pool_size); } // If not set, it means we do not compute stats. if (cerr != cudaSuccess) { LOG(FATAL) << "could not set the default CUDA pool memory threshold : " << cudaGetErrorString(cerr); pool_ = nullptr; } // If in TF_DETERMINISTIC_OPS is set, then make the allocator behave // determistically. bool deterministic_ops = false; TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar("TF_DETERMINISTIC_OPS", /*default_val=*/false, &deterministic_ops)); if (deterministic_ops) { cudaMemPoolSetAttribute(pool_, cudaMemPoolReuseAllowOpportunistic, 0); cudaMemPoolSetAttribute(pool_, cudaMemPoolReuseAllowInternalDependencies, 0); } #endif VLOG(2) << Name() << " GpuCudaMallocAsyncAllocator PoolSize " << pool_size; int64 prealloc_size = 0; // TF_CUDA_MALLOC_ASYNC_PREALLOC=-1 is a special value that // preallocates the total pool size. ReadInt64FromEnvVar("TF_CUDA_MALLOC_ASYNC_PREALLOC", 0, &prealloc_size); if (prealloc_size == -1) { prealloc_size = pool_size; } else if (reserve_memory) { prealloc_size = pool_size; } if (prealloc_size != 0) { void* ptr = AllocateRaw(0, prealloc_size); DeallocateRaw(ptr); VLOG(2) << Name() << " GpuCudaMallocAsyncAllocator reserved the pool for " << prealloc_size << " bytes"; ClearStats(); } } GpuCudaMallocAsyncAllocator::~GpuCudaMallocAsyncAllocator() { #ifdef GOOGLE_CUDA cuStreamDestroy(cuda_stream_); #endif } void* GpuCudaMallocAsyncAllocator::AllocateRaw(size_t alignment, size_t num_bytes) { #if CUDA_VERSION < 11020 || !defined(GOOGLE_CUDA) return nullptr; #else if (pool_ == nullptr) { LOG(FATAL) << "The instantiation of GpuCudaMallocAsyncAllocator failed." << " See previous errors."; } se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; void* ptr = 0; cudaError_t res = cudaMallocFromPoolAsync(&ptr, num_bytes, pool_, cuda_stream_); if (res != cudaSuccess) { size_t free, total; cudaMemGetInfo(&free, &total); mutex_lock lock(lock_); LOG(ERROR) << Name() << " cudaMallocAsync failed to allocate " << num_bytes << "\n Error name: " << cudaGetErrorName(res) << "\n Error string: " << cudaGetErrorString(res) << "\n Free memory/Total memory: " << free << "/" << total << "\n Stats: \n" << stats_.DebugString(); return nullptr; } // Update stats. if (stats_.bytes_limit.has_value()) { mutex_lock lock(lock_); ++stats_.num_allocs; stats_.bytes_in_use += num_bytes; stats_.peak_bytes_in_use = std::max(stats_.peak_bytes_in_use, stats_.bytes_in_use); stats_.largest_alloc_size = std::max<std::size_t>(stats_.largest_alloc_size, num_bytes); size_map_[ptr] = num_bytes; } VLOG(10) << Name() << " Allocated " << num_bytes << " at " << ptr; return ptr; #endif } void GpuCudaMallocAsyncAllocator::DeallocateRaw(void* ptr) { #if CUDA_VERSION < 11020 || !defined(GOOGLE_CUDA) #else cudaError_t res = cudaFreeAsync(ptr, cuda_stream_); if (res == cudaErrorCudartUnloading) { // It happens with multi-GPU that TF free the GPU allocation after // the driver is unloaded. It is safe to ignore this error here. // TODO: Find how to fix the shutdown steps in TF. VLOG(1) << "Ignoring Error: " << cudaGetErrorName(res) << " \nError string: " << cudaGetErrorString(res); } else if (res != cudaSuccess) { size_t free, total; se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_}; cudaMemGetInfo(&free, &total); LOG(ERROR) << "cudaFreeAsync failed to free " << ptr << "\n Error name: " << cudaGetErrorName(res) << "\n Error string: " << cudaGetErrorString(res) << "\n Free memory/Total memory: " << free << "/" << total << "\n Stats: \n" << stats_.DebugString(); } // Updates the stats. if (stats_.bytes_limit.has_value()) { mutex_lock lock(lock_); DCHECK(size_map_.contains(ptr)); size_t size = size_map_[ptr]; stats_.bytes_in_use -= size; size_map_.erase(ptr); } VLOG(10) << Name() << " Freed ptr: " << ptr; #endif // GOOGLE_CUDA } bool GpuCudaMallocAsyncAllocator::TracksAllocationSizes() const { return stats_.bytes_limit.has_value(); } size_t GpuCudaMallocAsyncAllocator::RequestedSize(const void* ptr) const { CHECK(ptr); return size_map_.at(ptr); } size_t GpuCudaMallocAsyncAllocator::AllocatedSize(const void* ptr) const { CHECK(ptr); return size_map_.at(ptr); } absl::optional<AllocatorStats> GpuCudaMallocAsyncAllocator::GetStats() { mutex_lock l(lock_); return stats_; } void GpuCudaMallocAsyncAllocator::ClearStats() { mutex_lock l(lock_); stats_.num_allocs = 0; stats_.peak_bytes_in_use = stats_.bytes_in_use; stats_.largest_alloc_size = 0; } } // namespace tensorflow <|endoftext|>
<commit_before>// $Header$ #include "StraightLineSetGL.h" #include <Reve/StraightLineSet.h> #include <Reve/GLUtilNS.h> #include <TGLDrawFlags.h> #ifdef WIN32 #include "Windows4root.h" #endif #include <GL/gl.h> #include <GL/glu.h> using namespace Reve; //______________________________________________________________________ // StraightLineSetGL // ClassImp(StraightLineSetGL) StraightLineSetGL::StraightLineSetGL() : TGLObject(), fM(0) { // fCached = false; // Disable display list. } StraightLineSetGL::~StraightLineSetGL() {} /**************************************************************************/ Bool_t StraightLineSetGL::SetModel(TObject* obj) { if(SetModelCheckClass(obj, StraightLineSet::Class())) { fM = dynamic_cast<StraightLineSet*>(obj); return kTRUE; } return kFALSE; } void StraightLineSetGL::SetBBox() { // !! This ok if master sub-classed from TAttBBox SetAxisAlignedBBox(((StraightLineSet*)fExternalObj)->AssertBBox()); } //______________________________________________________________________________ Bool_t StraightLineSetGL::ShouldCache(const TGLDrawFlags & flags) const { // Override from TGLDrawable. // To account for large point-sizes we modify the projection matrix // during selection and thus we need a direct draw. if (flags.Selection()) return kFALSE; return fCached; } /**************************************************************************/ void StraightLineSetGL::DirectDraw(const TGLDrawFlags & flags) const { // printf("StraightLineSetGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD()); StraightLineSet& mL = * fM; glPushAttrib(GL_POINT_BIT | GL_LINE_BIT | GL_ENABLE_BIT); GLUtilNS::GL_Capability_Switch lights_off(GL_LIGHTING, false); if(mL.fRnrLines) { UChar_t color[4]; ColorFromIdx(mL.GetMainColor(), color); glColor4ubv(color); VoidCPlex::iterator li(mL.fLinePlex); if(flags.SecSelection()) { GLuint name = 0; glPushName(1); glPushName(0); while (li.next()) { StraightLineSet::Line& l = * (StraightLineSet::Line*) li(); glLoadName(name); { glBegin(GL_LINES); glVertex3f(l.fV1[0], l.fV1[1], l.fV1[2]); glVertex3f(l.fV2[0], l.fV2[1], l.fV2[2]); glEnd(); } name ++; } glPopName(); glPopName(); } else { glBegin(GL_LINES); while (li.next()) { StraightLineSet::Line& l = * (StraightLineSet::Line*) li(); glVertex3f(l.fV1[0], l.fV1[1], l.fV1[2]); glVertex3f(l.fV2[0], l.fV2[1], l.fV2[2]); } glEnd(); } } if(mL.fRnrMarkers) { UChar_t color[4]; ColorFromIdx(mL.GetMarkerColor(), color); glColor4ubv(color); VoidCPlex::iterator mi(mL.fMarkerPlex); Float_t* pnts = new Float_t[mL.fMarkerPlex.Size()*3]; Float_t* pnt = pnts; Int_t lidx = -1; while (mi.next()) { StraightLineSet::Marker& m = * (StraightLineSet::Marker*) mi(); lidx = m.fLineID; StraightLineSet::Line& l = * (StraightLineSet::Line*) mL.fLinePlex.Atom(lidx); pnt[0] = l.fV1[0] + (l.fV2[0] - l.fV1[0])*m.fPos; pnt[1] = l.fV1[1] + (l.fV2[1] - l.fV1[1])*m.fPos; pnt[2] = l.fV1[2] + (l.fV2[2] - l.fV1[2])*m.fPos;; pnt += 3; } if(flags.SecSelection()) glPushName(2); GLUtilNS::RenderPolyMarkers((TAttMarker&)mL, pnts, mL.fLinePlex.Size(), flags.Selection(), flags.SecSelection()); if(flags.SecSelection()) glPopName(); delete [] pnts; } glPopAttrib(); } /**************************************************************************/ void StraightLineSetGL::ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*) { if (ptr[0] != 3) return; ptr += 3; // skip n, zmin, zmax if(ptr[1] == 1) { printf("selected line %d\n", ptr[2]); } else { StraightLineSet::Marker& m = * (StraightLineSet::Marker*) fM->fMarkerPlex.Atom(ptr[2]); printf("Selected point %d on line %d\n", ptr[2], m.fLineID); } } <commit_msg>Bugfix; wrong size passed to marker renderer.<commit_after>// $Header$ #include "StraightLineSetGL.h" #include <Reve/StraightLineSet.h> #include <Reve/GLUtilNS.h> #include <TGLDrawFlags.h> #ifdef WIN32 #include "Windows4root.h" #endif #include <GL/gl.h> #include <GL/glu.h> using namespace Reve; //______________________________________________________________________ // StraightLineSetGL // ClassImp(StraightLineSetGL) StraightLineSetGL::StraightLineSetGL() : TGLObject(), fM(0) { // fCached = false; // Disable display list. } StraightLineSetGL::~StraightLineSetGL() {} /**************************************************************************/ Bool_t StraightLineSetGL::SetModel(TObject* obj) { if(SetModelCheckClass(obj, StraightLineSet::Class())) { fM = dynamic_cast<StraightLineSet*>(obj); return kTRUE; } return kFALSE; } void StraightLineSetGL::SetBBox() { // !! This ok if master sub-classed from TAttBBox SetAxisAlignedBBox(((StraightLineSet*)fExternalObj)->AssertBBox()); } //______________________________________________________________________________ Bool_t StraightLineSetGL::ShouldCache(const TGLDrawFlags & flags) const { // Override from TGLDrawable. // To account for large point-sizes we modify the projection matrix // during selection and thus we need a direct draw. if (flags.Selection()) return kFALSE; return fCached; } /**************************************************************************/ void StraightLineSetGL::DirectDraw(const TGLDrawFlags & flags) const { // printf("StraightLineSetGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD()); StraightLineSet& mL = * fM; glPushAttrib(GL_POINT_BIT | GL_LINE_BIT | GL_ENABLE_BIT); GLUtilNS::GL_Capability_Switch lights_off(GL_LIGHTING, false); if(mL.fRnrLines && mL.fLinePlex.Size() > 0) { UChar_t color[4]; ColorFromIdx(mL.GetMainColor(), color); glColor4ubv(color); VoidCPlex::iterator li(mL.fLinePlex); if(flags.SecSelection()) { GLuint name = 0; glPushName(1); glPushName(0); while (li.next()) { StraightLineSet::Line& l = * (StraightLineSet::Line*) li(); glLoadName(name); { glBegin(GL_LINES); glVertex3f(l.fV1[0], l.fV1[1], l.fV1[2]); glVertex3f(l.fV2[0], l.fV2[1], l.fV2[2]); glEnd(); } name ++; } glPopName(); glPopName(); } else { glBegin(GL_LINES); while (li.next()) { StraightLineSet::Line& l = * (StraightLineSet::Line*) li(); glVertex3f(l.fV1[0], l.fV1[1], l.fV1[2]); glVertex3f(l.fV2[0], l.fV2[1], l.fV2[2]); } glEnd(); } } if(mL.fRnrMarkers && mL.fMarkerPlex.Size() > 0) { UChar_t color[4]; ColorFromIdx(mL.GetMarkerColor(), color); glColor4ubv(color); VoidCPlex::iterator mi(mL.fMarkerPlex); Float_t* pnts = new Float_t[mL.fMarkerPlex.Size()*3]; Float_t* pnt = pnts; Int_t lidx = -1; while (mi.next()) { StraightLineSet::Marker& m = * (StraightLineSet::Marker*) mi(); lidx = m.fLineID; StraightLineSet::Line& l = * (StraightLineSet::Line*) mL.fLinePlex.Atom(lidx); pnt[0] = l.fV1[0] + (l.fV2[0] - l.fV1[0])*m.fPos; pnt[1] = l.fV1[1] + (l.fV2[1] - l.fV1[1])*m.fPos; pnt[2] = l.fV1[2] + (l.fV2[2] - l.fV1[2])*m.fPos;; pnt += 3; } if(flags.SecSelection()) glPushName(2); GLUtilNS::RenderPolyMarkers((TAttMarker&)mL, pnts, mL.fMarkerPlex.Size(), flags.Selection(), flags.SecSelection()); if(flags.SecSelection()) glPopName(); delete [] pnts; } glPopAttrib(); } /**************************************************************************/ void StraightLineSetGL::ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*) { if (ptr[0] != 3) return; ptr += 3; // skip n, zmin, zmax if(ptr[1] == 1) { printf("selected line %d\n", ptr[2]); } else { StraightLineSet::Marker& m = * (StraightLineSet::Marker*) fM->fMarkerPlex.Atom(ptr[2]); printf("Selected point %d on line %d\n", ptr[2], m.fLineID); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "../elib/lang.h" #include "common.h" #include <io.h> #include "elib.h" PFN_NOTIFY_SYS g_fnNotifySys = NULL; HWND ehwnd = NULL; string epath; extern bool CompileILByFile(const char* path, const char* savePath); INT WINAPI NotifySys(INT nMsg, DWORD dwParam1, DWORD dwParam2) { if (g_fnNotifySys != NULL) return g_fnNotifySys(nMsg, dwParam1, dwParam2); else return 0; } INT WINAPI notify_lib(INT nMsg, DWORD dwParam1, DWORD dwParam2) { switch (nMsg) { case NL_SYS_NOTIFY_FUNCTION: g_fnNotifySys = (PFN_NOTIFY_SYS)dwParam1; ehwnd = (HWND)g_fnNotifySys(NES_GET_MAIN_HWND, 0, 0); char path[MAX_PATH]; g_fnNotifySys(NAS_GET_PATH, 1002, D(path)); epath = path; return NR_OK; default: return NR_ERR; } } LIB_CONST_INFO s_const_info[] = { { TEXT(""), TEXT("null"), NULL, LVL_SIMPLE, CT_NULL, NULL, NULL } }; INT WINAPI addin_func(INT nAddInFnIndex) { char title[MAX_PATH]; GetWindowText(ehwnd, title, MAX_PATH); vector<string> arr = split(title, " - "); if (arr.size() > 2) { string path = arr[1]; if (access(path.c_str(), 0) == 0) { switch (nAddInFnIndex) { case 0: { int index = path.find_last_of("\\"); string dic = path.substr(0, index); CompileILByFile(path.c_str(), dic.c_str()); break; } case 1: { path = epath + "gff.exe \"" + path + "\""; WinExec(path.c_str(), SW_SHOWNORMAL); break; } } } } return TRUE; } LIB_INFO s_lib_info = { LIB_FORMAT_VER, TEXT(LI_LIB_GUID_STR), 1, 0, 0, 0, 0, 0, 0, TEXT(".net"), __GBK_LANG_VER, TEXT("ԴΪ.net"), NULL, TEXT("Ϊо"), TEXT("100000"), TEXT("qq:514543271"), TEXT("qq:514543271"), TEXT("514543271"), TEXT("[email protected]"), TEXT("http://wnxd.me"), TEXT("ΪԴĿ https://github.com/wnxd/e.net"), 0, NULL, 1, TEXT("0000.net\0"), 0, NULL, NULL, addin_func, TEXT("e.net\0Ϊ.net\0DoNET\0޸ĵǰԴ\0\0"), notify_lib, NULL, NULL, sizeof(s_const_info) / sizeof(LIB_CONST_INFO), s_const_info, NULL }; extern "C" PLIB_INFO WINAPI GetNewInf() { return &s_lib_info; }<commit_msg>dir切换<commit_after>#include "stdafx.h" #include "../elib/lang.h" #include "common.h" #include <io.h> #include "elib.h" PFN_NOTIFY_SYS g_fnNotifySys = NULL; HWND ehwnd = NULL; string epath; extern bool CompileILByFile(const char* path, const char* savePath); INT WINAPI NotifySys(INT nMsg, DWORD dwParam1, DWORD dwParam2) { if (g_fnNotifySys != NULL) return g_fnNotifySys(nMsg, dwParam1, dwParam2); else return 0; } INT WINAPI notify_lib(INT nMsg, DWORD dwParam1, DWORD dwParam2) { switch (nMsg) { case NL_SYS_NOTIFY_FUNCTION: g_fnNotifySys = (PFN_NOTIFY_SYS)dwParam1; ehwnd = (HWND)g_fnNotifySys(NES_GET_MAIN_HWND, 0, 0); char path[MAX_PATH]; g_fnNotifySys(NAS_GET_PATH, 1002, D(path)); epath = path; return NR_OK; default: return NR_ERR; } } LIB_CONST_INFO s_const_info[] = { { TEXT(""), TEXT("null"), NULL, LVL_SIMPLE, CT_NULL, NULL, NULL } }; INT WINAPI addin_func(INT nAddInFnIndex) { char title[MAX_PATH]; GetWindowText(ehwnd, title, MAX_PATH); vector<string> arr = split(title, " - "); if (arr.size() > 2) { string path = arr[1]; if (access(path.c_str(), 0) == 0) { switch (nAddInFnIndex) { case 0: { int index = path.find_last_of("\\"); string dic = path.substr(0, index); char cur[MAX_PATH]; GetCurrentDirectory(MAX_PATH, cur); SetCurrentDirectory(dic.c_str()); CompileILByFile(path.c_str(), dic.c_str()); SetCurrentDirectory(cur); break; } case 1: { path = epath + "gff.exe \"" + path + "\""; WinExec(path.c_str(), SW_SHOWNORMAL); break; } } } } return TRUE; } LIB_INFO s_lib_info = { LIB_FORMAT_VER, TEXT(LI_LIB_GUID_STR), 1, 1, 1120, 0, 0, 0, 0, TEXT(".net"), __GBK_LANG_VER, TEXT("ԴΪ.net"), NULL, TEXT("Ϊо"), TEXT("100000"), TEXT("qq:514543271"), TEXT("qq:514543271"), TEXT("514543271"), TEXT("[email protected]"), TEXT("http://wnxd.me"), TEXT("ΪԴĿ https://github.com/wnxd/e.net"), 0, NULL, 1, TEXT("0000.net\0"), 0, NULL, NULL, addin_func, TEXT("e.net\0Ϊ.net\0DoNET\0޸ĵǰԴ\0\0"), notify_lib, NULL, NULL, sizeof(s_const_info) / sizeof(LIB_CONST_INFO), s_const_info, NULL }; extern "C" PLIB_INFO WINAPI GetNewInf() { return &s_lib_info; }<|endoftext|>
<commit_before>// Implements file reader for an XML format #include "xml_file_loader.h" #include <algorithm> #include <fstream> #include <set> #include <streambuf> #include <boost/filesystem.hpp> #include "agent.h" #include "blob.h" #include "context.h" #include "cyc_std.h" #include "env.h" #include "error.h" #include "exchange_solver.h" #include "greedy_preconditioner.h" #include "greedy_solver.h" #include "infile_tree.h" #include "logger.h" #include "sim_init.h" #include "toolkit/infile_converters.h" namespace cyclus { namespace fs = boost::filesystem; void LoadRawStringstreamFromFile(std::stringstream& stream, std::string file) { std::ifstream file_stream(file.c_str()); if (!file_stream) { throw IOError("The file '" + file + "' could not be loaded."); } stream << file_stream.rdbuf(); file_stream.close(); } void LoadStringstreamFromFile(std::stringstream& stream, std::string file) { LoadRawStringstreamFromFile(stream, file); std::string inext = fs::path(file).extension().string(); if (inext == ".json") { std::string inxml = cyclus::toolkit::JsonToXml(stream.str()); stream.str(inxml); } } std::vector<AgentSpec> ParseSpecs(std::string infile) { std::stringstream input; LoadStringstreamFromFile(input, infile); XMLParser parser_; parser_.Init(input); InfileTree xqe(parser_); std::vector<AgentSpec> specs; std::set<std::string> unique; std::string p = "/simulation/archetypes/spec"; int n = xqe.NMatches(p); for (int i = 0; i < n; ++i) { AgentSpec spec(xqe.SubTree(p, i)); if (unique.count(spec.str()) == 0) { specs.push_back(spec); unique.insert(spec.str()); } } if (specs.size() == 0) { throw ValidationError("failed to parse archetype specs from input file"); } return specs; } std::string BuildMasterSchema(std::string schema_path, std::string infile) { Timer ti; Recorder rec; Context ctx(&ti, &rec); std::stringstream schema(""); LoadStringstreamFromFile(schema, schema_path); std::string master = schema.str(); std::vector<AgentSpec> specs = ParseSpecs(infile); std::map<std::string, std::string> subschemas; // force element types to exist so we always replace the config string subschemas["region"] = ""; subschemas["inst"] = ""; subschemas["facility"] = ""; for (int i = 0; i < specs.size(); ++i) { Agent* m = DynamicModule::Make(&ctx, specs[i]); subschemas[m->kind()] += "<element name=\"" + specs[i].alias() + "\">\n"; subschemas[m->kind()] += m->schema() + "\n"; subschemas[m->kind()] += "</element>\n"; ctx.DelAgent(m); } // replace refs in master rng template file std::map<std::string, std::string>::iterator it; for (it = subschemas.begin(); it != subschemas.end(); ++it) { std::string search_str = std::string("@") + it->first + std::string("_REFS@"); size_t pos = master.find(search_str); if (pos != std::string::npos) { master.replace(pos, search_str.size(), it->second); } } return master; } Composition::Ptr ReadRecipe(InfileTree* qe) { bool atom_basis; std::string basis_str = qe->GetString("basis"); if (basis_str == "atom") { atom_basis = true; } else if (basis_str == "mass") { atom_basis = false; } else { throw IOError(basis_str + " basis is not 'mass' or 'atom'."); } double value; int key; std::string query = "nuclide"; int nnucs = qe->NMatches(query); CompMap v; for (int i = 0; i < nnucs; i++) { InfileTree* nuclide = qe->SubTree(query, i); key = pyne::nucname::id(nuclide->GetString("id")); value = strtod(nuclide->GetString("comp").c_str(), NULL); v[key] = value; CLOG(LEV_DEBUG3) << " Nuclide: " << key << " Value: " << v[key]; } if (atom_basis) { return Composition::CreateFromAtom(v); } else { return Composition::CreateFromMass(v); } } XMLFileLoader::XMLFileLoader(Recorder* r, QueryableBackend* b, std::string schema_file, const std::string input_file) : b_(b), rec_(r) { ctx_ = new Context(&ti_, rec_); schema_path_ = schema_file; file_ = input_file; std::stringstream input; LoadStringstreamFromFile(input, file_); parser_ = boost::shared_ptr<XMLParser>(new XMLParser()); parser_->Init(input); std::stringstream orig_input; LoadRawStringstreamFromFile(orig_input, file_); ctx_->NewDatum("InputFiles") ->AddVal("Data", Blob(orig_input.str())) ->Record(); } XMLFileLoader::~XMLFileLoader() { delete ctx_; } std::string XMLFileLoader::master_schema() { return BuildMasterSchema(schema_path_, file_); } void XMLFileLoader::LoadSim() { std::stringstream ss(master_schema()); parser_->Validate(ss); LoadControlParams(); // must be first LoadSolver(); LoadRecipes(); LoadSpecs(); LoadInitialAgents(); // must be last SimInit::Snapshot(ctx_); rec_->Flush(); } void XMLFileLoader::LoadSolver() { using std::string; InfileTree xqe(*parser_); InfileTree* qe; std::string query = "/*/commodity"; std::map<std::string, double> commod_priority; std::string name; double priority; int num_commods = xqe.NMatches(query); for (int i = 0; i < num_commods; i++) { qe = xqe.SubTree(query, i); name = qe->GetString("name"); priority = OptionalQuery<double>(qe, "solution_priority", -1); commod_priority[name] = priority; } ProcessCommodities(&commod_priority); std::map<std::string, double>::iterator it; for (it = commod_priority.begin(); it != commod_priority.end(); ++it) { ctx_->NewDatum("CommodPriority") ->AddVal("Commodity", it->first) ->AddVal("SolutionPriority", it->second) ->Record(); } // now load the solver info string config = "config"; string greedy = "greedy"; string coinor = "coin-or"; string solver_name = greedy; bool exclusive = ExchangeSolver::kDefaultExclusive; if (xqe.NMatches("/*/control/solver") == 1) { qe = xqe.SubTree("/*/control/solver"); if (qe->NMatches(config) == 1) { solver_name = qe->SubTree(config)->GetElementName(0); } exclusive = cyclus::OptionalQuery<bool>(qe, "allow_exclusive_orders", exclusive); } if (!exclusive) { std::stringstream ss; ss << "You have set allow_exclusive_orders to False." << " Many archetypes (e.g., :cycamore:Reactor will not work" << " as intended with this feature turned off."; Warn<VALUE_WARNING>(ss.str()); } ctx_->NewDatum("SolverInfo") ->AddVal("Solver", solver_name) ->AddVal("ExclusiveOrders", exclusive) ->Record(); // @TODO remove this after release 1.5 // check for deprecated input values if (qe->NMatches("exclusive_orders_only") > 0) { std::stringstream ss; ss << "Use of 'exclusive_orders_only' is deprecated." << " Please see http://fuelcycle.org/user/input_specs/control.html"; Warn<DEPRECATION_WARNING>(ss.str()); } // now load the actual solver if (solver_name == greedy) { query = string("/*/control/solver/config/greedy/preconditioner"); string precon_name = cyclus::OptionalQuery<string>(&xqe, query, greedy); ctx_->NewDatum("GreedySolverInfo") ->AddVal("Preconditioner", precon_name) ->Record(); } else if (solver_name == coinor) { query = string("/*/control/solver/config/coin-or/timeout"); double timeout = cyclus::OptionalQuery<double>(&xqe, query, -1); query = string("/*/control/solver/config/coin-or/verbose"); bool verbose = cyclus::OptionalQuery<bool>(&xqe, query, false); query = string("/*/control/solver/config/coin-or/mps"); bool mps = cyclus::OptionalQuery<bool>(&xqe, query, false); ctx_->NewDatum("CoinSolverInfo") ->AddVal("Timeout", timeout) ->AddVal("Verbose", verbose) ->AddVal("Mps", mps) ->Record(); } else { throw ValueError("unknown solver name: " + solver_name); } } void XMLFileLoader::ProcessCommodities( std::map<std::string, double>* commod_priority) { double max = std::max_element( commod_priority->begin(), commod_priority->end(), SecondLT< std::pair<std::string, double> >())->second; if (max < 1) { max = 0; // in case no priorities are specified } std::map<std::string, double>::iterator it; for (it = commod_priority->begin(); it != commod_priority->end(); ++it) { if (it->second < 1) { it->second = max + 1; } CLOG(LEV_INFO1) << "Commodity priority for " << it->first << " is " << it->second; } } void XMLFileLoader::LoadRecipes() { InfileTree xqe(*parser_); std::string query = "/*/recipe"; int num_recipes = xqe.NMatches(query); for (int i = 0; i < num_recipes; i++) { InfileTree* qe = xqe.SubTree(query, i); std::string name = qe->GetString("name"); CLOG(LEV_DEBUG3) << "loading recipe: " << name; Composition::Ptr comp = ReadRecipe(qe); comp->Record(ctx_); ctx_->AddRecipe(name, comp); } } void XMLFileLoader::LoadSpecs() { std::vector<AgentSpec> specs = ParseSpecs(file_); for (int i = 0; i < specs.size(); ++i) { specs_[specs[i].alias()] = specs[i]; } } void XMLFileLoader::LoadInitialAgents() { std::map<std::string, std::string> schema_paths; schema_paths["Region"] = "/*/region"; schema_paths["Inst"] = "/*/region/institution"; schema_paths["Facility"] = "/*/facility"; InfileTree xqe(*parser_); // create prototypes std::string prototype; // defined here for force-create AgentExit tbl std::map<std::string, std::string>::iterator it; for (it = schema_paths.begin(); it != schema_paths.end(); it++) { int num_agents = xqe.NMatches(it->second); for (int i = 0; i < num_agents; i++) { InfileTree* qe = xqe.SubTree(it->second, i); prototype = qe->GetString("name"); std::string alias = qe->SubTree("config")->GetElementName(0); AgentSpec spec = specs_[alias]; Agent* agent = DynamicModule::Make(ctx_, spec); // call manually without agent impl injected to keep all Agent state in a // single, consolidated db table agent->Agent::InfileToDb(qe, DbInit(agent, true)); agent->InfileToDb(qe, DbInit(agent)); rec_->Flush(); std::vector<Cond> conds; conds.push_back(Cond("SimId", "==", rec_->sim_id())); conds.push_back(Cond("SimTime", "==", static_cast<int>(0))); conds.push_back(Cond("AgentId", "==", agent->id())); CondInjector ci(b_, conds); PrefixInjector pi(&ci, "AgentState"); // call manually without agent impl injected agent->Agent::InitFrom(&pi); pi = PrefixInjector(&ci, "AgentState" + spec.Sanitize()); agent->InitFrom(&pi); ctx_->AddPrototype(prototype, agent); } } // build initial agent instances int nregions = xqe.NMatches(schema_paths["Region"]); for (int i = 0; i < nregions; ++i) { InfileTree* qe = xqe.SubTree(schema_paths["Region"], i); std::string region_proto = qe->GetString("name"); Agent* reg = BuildAgent(region_proto, NULL); int ninsts = qe->NMatches("institution"); for (int j = 0; j < ninsts; ++j) { InfileTree* qe2 = qe->SubTree("institution", j); std::string inst_proto = qe2->GetString("name"); Agent* inst = BuildAgent(inst_proto, reg); int nfac = qe2->NMatches("initialfacilitylist/entry"); for (int k = 0; k < nfac; ++k) { InfileTree* qe3 = qe2->SubTree("initialfacilitylist/entry", k); std::string fac_proto = qe3->GetString("prototype"); int number = atoi(qe3->GetString("number").c_str()); for (int z = 0; z < number; ++z) { Agent* fac = BuildAgent(fac_proto, inst); } } } } } Agent* XMLFileLoader::BuildAgent(std::string proto, Agent* parent) { Agent* m = ctx_->CreateAgent<Agent>(proto); m->Build(parent); if (parent != NULL) { parent->BuildNotify(m); } return m; } void XMLFileLoader::LoadControlParams() { InfileTree xqe(*parser_); std::string query = "/*/control"; InfileTree* qe = xqe.SubTree(query); std::string handle; if (qe->NMatches("simhandle") > 0) { handle = qe->GetString("simhandle"); } // get duration std::string dur_str = qe->GetString("duration"); int dur = strtol(dur_str.c_str(), NULL, 10); // get start month std::string m0_str = qe->GetString("startmonth"); int m0 = strtol(m0_str.c_str(), NULL, 10); // get start year std::string y0_str = qe->GetString("startyear"); int y0 = strtol(y0_str.c_str(), NULL, 10); // get decay mode std::string d = OptionalQuery<std::string>(qe, "decay", "manual"); SimInfo si(dur, y0, m0, handle, d); // get time step duration si.dt = OptionalQuery<int>(qe, "dt", kDefaultTimeStepDur); ctx_->InitSim(si); } } // namespace cyclus <commit_msg>correctly checks old exclusive flag when query engine exists in scope<commit_after>// Implements file reader for an XML format #include "xml_file_loader.h" #include <algorithm> #include <fstream> #include <set> #include <streambuf> #include <boost/filesystem.hpp> #include "agent.h" #include "blob.h" #include "context.h" #include "cyc_std.h" #include "env.h" #include "error.h" #include "exchange_solver.h" #include "greedy_preconditioner.h" #include "greedy_solver.h" #include "infile_tree.h" #include "logger.h" #include "sim_init.h" #include "toolkit/infile_converters.h" namespace cyclus { namespace fs = boost::filesystem; void LoadRawStringstreamFromFile(std::stringstream& stream, std::string file) { std::ifstream file_stream(file.c_str()); if (!file_stream) { throw IOError("The file '" + file + "' could not be loaded."); } stream << file_stream.rdbuf(); file_stream.close(); } void LoadStringstreamFromFile(std::stringstream& stream, std::string file) { LoadRawStringstreamFromFile(stream, file); std::string inext = fs::path(file).extension().string(); if (inext == ".json") { std::string inxml = cyclus::toolkit::JsonToXml(stream.str()); stream.str(inxml); } } std::vector<AgentSpec> ParseSpecs(std::string infile) { std::stringstream input; LoadStringstreamFromFile(input, infile); XMLParser parser_; parser_.Init(input); InfileTree xqe(parser_); std::vector<AgentSpec> specs; std::set<std::string> unique; std::string p = "/simulation/archetypes/spec"; int n = xqe.NMatches(p); for (int i = 0; i < n; ++i) { AgentSpec spec(xqe.SubTree(p, i)); if (unique.count(spec.str()) == 0) { specs.push_back(spec); unique.insert(spec.str()); } } if (specs.size() == 0) { throw ValidationError("failed to parse archetype specs from input file"); } return specs; } std::string BuildMasterSchema(std::string schema_path, std::string infile) { Timer ti; Recorder rec; Context ctx(&ti, &rec); std::stringstream schema(""); LoadStringstreamFromFile(schema, schema_path); std::string master = schema.str(); std::vector<AgentSpec> specs = ParseSpecs(infile); std::map<std::string, std::string> subschemas; // force element types to exist so we always replace the config string subschemas["region"] = ""; subschemas["inst"] = ""; subschemas["facility"] = ""; for (int i = 0; i < specs.size(); ++i) { Agent* m = DynamicModule::Make(&ctx, specs[i]); subschemas[m->kind()] += "<element name=\"" + specs[i].alias() + "\">\n"; subschemas[m->kind()] += m->schema() + "\n"; subschemas[m->kind()] += "</element>\n"; ctx.DelAgent(m); } // replace refs in master rng template file std::map<std::string, std::string>::iterator it; for (it = subschemas.begin(); it != subschemas.end(); ++it) { std::string search_str = std::string("@") + it->first + std::string("_REFS@"); size_t pos = master.find(search_str); if (pos != std::string::npos) { master.replace(pos, search_str.size(), it->second); } } return master; } Composition::Ptr ReadRecipe(InfileTree* qe) { bool atom_basis; std::string basis_str = qe->GetString("basis"); if (basis_str == "atom") { atom_basis = true; } else if (basis_str == "mass") { atom_basis = false; } else { throw IOError(basis_str + " basis is not 'mass' or 'atom'."); } double value; int key; std::string query = "nuclide"; int nnucs = qe->NMatches(query); CompMap v; for (int i = 0; i < nnucs; i++) { InfileTree* nuclide = qe->SubTree(query, i); key = pyne::nucname::id(nuclide->GetString("id")); value = strtod(nuclide->GetString("comp").c_str(), NULL); v[key] = value; CLOG(LEV_DEBUG3) << " Nuclide: " << key << " Value: " << v[key]; } if (atom_basis) { return Composition::CreateFromAtom(v); } else { return Composition::CreateFromMass(v); } } XMLFileLoader::XMLFileLoader(Recorder* r, QueryableBackend* b, std::string schema_file, const std::string input_file) : b_(b), rec_(r) { ctx_ = new Context(&ti_, rec_); schema_path_ = schema_file; file_ = input_file; std::stringstream input; LoadStringstreamFromFile(input, file_); parser_ = boost::shared_ptr<XMLParser>(new XMLParser()); parser_->Init(input); std::stringstream orig_input; LoadRawStringstreamFromFile(orig_input, file_); ctx_->NewDatum("InputFiles") ->AddVal("Data", Blob(orig_input.str())) ->Record(); } XMLFileLoader::~XMLFileLoader() { delete ctx_; } std::string XMLFileLoader::master_schema() { return BuildMasterSchema(schema_path_, file_); } void XMLFileLoader::LoadSim() { std::stringstream ss(master_schema()); parser_->Validate(ss); LoadControlParams(); // must be first LoadSolver(); LoadRecipes(); LoadSpecs(); LoadInitialAgents(); // must be last SimInit::Snapshot(ctx_); rec_->Flush(); } void XMLFileLoader::LoadSolver() { using std::string; InfileTree xqe(*parser_); InfileTree* qe; std::string query = "/*/commodity"; std::map<std::string, double> commod_priority; std::string name; double priority; int num_commods = xqe.NMatches(query); for (int i = 0; i < num_commods; i++) { qe = xqe.SubTree(query, i); name = qe->GetString("name"); priority = OptionalQuery<double>(qe, "solution_priority", -1); commod_priority[name] = priority; } ProcessCommodities(&commod_priority); std::map<std::string, double>::iterator it; for (it = commod_priority.begin(); it != commod_priority.end(); ++it) { ctx_->NewDatum("CommodPriority") ->AddVal("Commodity", it->first) ->AddVal("SolutionPriority", it->second) ->Record(); } // now load the solver info string config = "config"; string greedy = "greedy"; string coinor = "coin-or"; string solver_name = greedy; bool exclusive = ExchangeSolver::kDefaultExclusive; if (xqe.NMatches("/*/control/solver") == 1) { qe = xqe.SubTree("/*/control/solver"); if (qe->NMatches(config) == 1) { solver_name = qe->SubTree(config)->GetElementName(0); } exclusive = cyclus::OptionalQuery<bool>(qe, "allow_exclusive_orders", exclusive); // @TODO remove this after release 1.5 // check for deprecated input values if (qe->NMatches(std::string("exclusive_orders_only")) != 0) { std::stringstream ss; ss << "Use of 'exclusive_orders_only' is deprecated." << " Please see http://fuelcycle.org/user/input_specs/control.html"; Warn<DEPRECATION_WARNING>(ss.str()); } } if (!exclusive) { std::stringstream ss; ss << "You have set allow_exclusive_orders to False." << " Many archetypes (e.g., :cycamore:Reactor will not work" << " as intended with this feature turned off."; Warn<VALUE_WARNING>(ss.str()); } ctx_->NewDatum("SolverInfo") ->AddVal("Solver", solver_name) ->AddVal("ExclusiveOrders", exclusive) ->Record(); // now load the actual solver if (solver_name == greedy) { query = string("/*/control/solver/config/greedy/preconditioner"); string precon_name = cyclus::OptionalQuery<string>(&xqe, query, greedy); ctx_->NewDatum("GreedySolverInfo") ->AddVal("Preconditioner", precon_name) ->Record(); } else if (solver_name == coinor) { query = string("/*/control/solver/config/coin-or/timeout"); double timeout = cyclus::OptionalQuery<double>(&xqe, query, -1); query = string("/*/control/solver/config/coin-or/verbose"); bool verbose = cyclus::OptionalQuery<bool>(&xqe, query, false); query = string("/*/control/solver/config/coin-or/mps"); bool mps = cyclus::OptionalQuery<bool>(&xqe, query, false); ctx_->NewDatum("CoinSolverInfo") ->AddVal("Timeout", timeout) ->AddVal("Verbose", verbose) ->AddVal("Mps", mps) ->Record(); } else { throw ValueError("unknown solver name: " + solver_name); } } void XMLFileLoader::ProcessCommodities( std::map<std::string, double>* commod_priority) { double max = std::max_element( commod_priority->begin(), commod_priority->end(), SecondLT< std::pair<std::string, double> >())->second; if (max < 1) { max = 0; // in case no priorities are specified } std::map<std::string, double>::iterator it; for (it = commod_priority->begin(); it != commod_priority->end(); ++it) { if (it->second < 1) { it->second = max + 1; } CLOG(LEV_INFO1) << "Commodity priority for " << it->first << " is " << it->second; } } void XMLFileLoader::LoadRecipes() { InfileTree xqe(*parser_); std::string query = "/*/recipe"; int num_recipes = xqe.NMatches(query); for (int i = 0; i < num_recipes; i++) { InfileTree* qe = xqe.SubTree(query, i); std::string name = qe->GetString("name"); CLOG(LEV_DEBUG3) << "loading recipe: " << name; Composition::Ptr comp = ReadRecipe(qe); comp->Record(ctx_); ctx_->AddRecipe(name, comp); } } void XMLFileLoader::LoadSpecs() { std::vector<AgentSpec> specs = ParseSpecs(file_); for (int i = 0; i < specs.size(); ++i) { specs_[specs[i].alias()] = specs[i]; } } void XMLFileLoader::LoadInitialAgents() { std::map<std::string, std::string> schema_paths; schema_paths["Region"] = "/*/region"; schema_paths["Inst"] = "/*/region/institution"; schema_paths["Facility"] = "/*/facility"; InfileTree xqe(*parser_); // create prototypes std::string prototype; // defined here for force-create AgentExit tbl std::map<std::string, std::string>::iterator it; for (it = schema_paths.begin(); it != schema_paths.end(); it++) { int num_agents = xqe.NMatches(it->second); for (int i = 0; i < num_agents; i++) { InfileTree* qe = xqe.SubTree(it->second, i); prototype = qe->GetString("name"); std::string alias = qe->SubTree("config")->GetElementName(0); AgentSpec spec = specs_[alias]; Agent* agent = DynamicModule::Make(ctx_, spec); // call manually without agent impl injected to keep all Agent state in a // single, consolidated db table agent->Agent::InfileToDb(qe, DbInit(agent, true)); agent->InfileToDb(qe, DbInit(agent)); rec_->Flush(); std::vector<Cond> conds; conds.push_back(Cond("SimId", "==", rec_->sim_id())); conds.push_back(Cond("SimTime", "==", static_cast<int>(0))); conds.push_back(Cond("AgentId", "==", agent->id())); CondInjector ci(b_, conds); PrefixInjector pi(&ci, "AgentState"); // call manually without agent impl injected agent->Agent::InitFrom(&pi); pi = PrefixInjector(&ci, "AgentState" + spec.Sanitize()); agent->InitFrom(&pi); ctx_->AddPrototype(prototype, agent); } } // build initial agent instances int nregions = xqe.NMatches(schema_paths["Region"]); for (int i = 0; i < nregions; ++i) { InfileTree* qe = xqe.SubTree(schema_paths["Region"], i); std::string region_proto = qe->GetString("name"); Agent* reg = BuildAgent(region_proto, NULL); int ninsts = qe->NMatches("institution"); for (int j = 0; j < ninsts; ++j) { InfileTree* qe2 = qe->SubTree("institution", j); std::string inst_proto = qe2->GetString("name"); Agent* inst = BuildAgent(inst_proto, reg); int nfac = qe2->NMatches("initialfacilitylist/entry"); for (int k = 0; k < nfac; ++k) { InfileTree* qe3 = qe2->SubTree("initialfacilitylist/entry", k); std::string fac_proto = qe3->GetString("prototype"); int number = atoi(qe3->GetString("number").c_str()); for (int z = 0; z < number; ++z) { Agent* fac = BuildAgent(fac_proto, inst); } } } } } Agent* XMLFileLoader::BuildAgent(std::string proto, Agent* parent) { Agent* m = ctx_->CreateAgent<Agent>(proto); m->Build(parent); if (parent != NULL) { parent->BuildNotify(m); } return m; } void XMLFileLoader::LoadControlParams() { InfileTree xqe(*parser_); std::string query = "/*/control"; InfileTree* qe = xqe.SubTree(query); std::string handle; if (qe->NMatches("simhandle") > 0) { handle = qe->GetString("simhandle"); } // get duration std::string dur_str = qe->GetString("duration"); int dur = strtol(dur_str.c_str(), NULL, 10); // get start month std::string m0_str = qe->GetString("startmonth"); int m0 = strtol(m0_str.c_str(), NULL, 10); // get start year std::string y0_str = qe->GetString("startyear"); int y0 = strtol(y0_str.c_str(), NULL, 10); // get decay mode std::string d = OptionalQuery<std::string>(qe, "decay", "manual"); SimInfo si(dur, y0, m0, handle, d); // get time step duration si.dt = OptionalQuery<int>(qe, "dt", kDefaultTimeStepDur); ctx_->InitSim(si); } } // namespace cyclus <|endoftext|>
<commit_before>#ifndef YQVMC_OBSERVER_PLAIN_HPP #define YQVMC_OBSERVER_PLAIN_HPP #include "impl_/mean_and_error.hpp" #include <iostream> namespace yqvmc { template <class M, class ACC = impl_::MeanAndErrorAcc<typename M::result_type> > class PlainObserver { public: typedef M Measure; typedef typename M::result_type input_type; typedef ACC Accumulator; PlainObserver(std::string name, Measure& measure) : m_name(name), m_measure(measure) {} template <typename Conf> void measure(const Conf& conf, std::size_t stamp) { m_measure.measure(conf, stamp); } void closeBin(std::size_t iBin) { auto result = m_measure.result(); m_acc(result); std::cout << m_name << ": " << result << std::endl; } void report() const { auto mean = m_acc.mean(); auto error = m_acc.error(); std::cout << m_name << " : " << mean << " +/- " << error << std::endl; } private: std::string m_name; Measure& m_measure; Accumulator m_acc; }; template <class M> PlainObserver<M> MakePlainObserver(std::string name, M& m) { return PlainObserver<M>(name, m); } template <typename M> class EmptyObserver { public: typedef M Measure; EmptyObserver(Measure& measure) : m_measure(measure) {} template <typename Conf> void measure(const Conf& conf, std::size_t stamp) { m_measure.measure(conf, stamp); } void closeBin(std::size_t iBin) {} private: Measure& m_measure; }; } #endif <commit_msg>new emptyobserver interface. needed by the SLEEP project.<commit_after>#ifndef YQVMC_OBSERVER_PLAIN_HPP #define YQVMC_OBSERVER_PLAIN_HPP #include "impl_/mean_and_error.hpp" #include <iostream> namespace yqvmc { template <class M, class ACC = impl_::MeanAndErrorAcc<typename M::result_type> > class PlainObserver { public: typedef M Measure; typedef typename M::result_type input_type; typedef ACC Accumulator; PlainObserver(std::string name, Measure& measure) : m_name(name), m_measure(measure) {} template <typename Conf> void measure(const Conf& conf, std::size_t stamp) { m_measure.measure(conf, stamp); } void closeBin(std::size_t iBin) { auto result = m_measure.result(); m_acc(result); std::cout << m_name << ": " << result << std::endl; } void report() const { auto mean = m_acc.mean(); auto error = m_acc.error(); std::cout << m_name << " : " << mean << " +/- " << error << std::endl; } private: std::string m_name; Measure& m_measure; Accumulator m_acc; }; template <class M> PlainObserver<M> MakePlainObserver(std::string name, M& m) { return PlainObserver<M>(name, m); } template <typename M> class EmptyObserver { public: typedef M Measure; EmptyObserver(Measure& measure) : m_measure(measure) {} template <typename Conf> void measure(const Conf& conf, std::size_t stamp) { m_measure.measure(conf, stamp); } void closeBin(std::size_t iBin) {} private: Measure& m_measure; }; template <class M> EmptyObserver<M> MakeEmptyObserver(M& m) { return EmptyObserver<M>(m); } } #endif <|endoftext|>
<commit_before>#include <gtk/gtk.h> #include <gdk/gdk.h> #include <openvibe/ov_directories.h> #include <openvibe/ovCString.h> #include <vrpn_Button.h> #include <vrpn_Analog.h> #include <vrpn_Connection.h> #include <iostream> #define _vrpn_peripheral_name_ "openvibe-vrpn@localhost" // #define _DEBUG ::vrpn_Connection* g_pConnection=NULL; ::vrpn_Button_Server* g_pButtonServer=NULL; ::vrpn_Analog_Server* g_pAnalogServer=NULL; long g_iAnalogCount=0; long g_iButtonCount=0; typedef union { gpointer pUserData; int iData; } TUserData; void fScrollCB(::GtkRange* pRange, gpointer pUserData) { TUserData l_oUserData; l_oUserData.pUserData=pUserData; g_pAnalogServer->channels()[l_oUserData.iData]=gtk_range_get_value(pRange); #if defined _DEBUG std::cout << (int)(pUserData) << " value changed\n"; #endif } void fSwitchCB(::GtkToggleButton* pTogglebutton, gpointer pUserData) { TUserData l_oUserData; l_oUserData.pUserData=pUserData; g_pButtonServer->set_button(l_oUserData.iData, gtk_toggle_button_get_active(pTogglebutton)); #if defined _DEBUG std::cout << (int)(pUserData) << " toggled\n"; #endif } void fConnectCB(::GtkWidget* pWidget, gpointer data) { if(GTK_IS_RANGE(pWidget)) { g_signal_connect(G_OBJECT(pWidget), "value-changed", G_CALLBACK(fScrollCB), (gpointer) g_iAnalogCount); g_iAnalogCount++; } if(GTK_IS_TOGGLE_BUTTON(pWidget)) { g_signal_connect(G_OBJECT(pWidget), "toggled", G_CALLBACK(fSwitchCB), (void*)g_iButtonCount); g_iButtonCount++; } } gboolean fIdleApplicationLoop(gpointer pUserData) { g_pButtonServer->mainloop(); g_pAnalogServer->report_changes(); g_pAnalogServer->mainloop(); g_pConnection->mainloop(); return TRUE; } int main(int argc, char ** argv) { gtk_init(&argc, &argv); // g_pConnection=new ::vrpn_Connection; g_pConnection=vrpn_create_server_connection(); g_pButtonServer=new ::vrpn_Button_Server(_vrpn_peripheral_name_, g_pConnection, 10); g_pAnalogServer=new ::vrpn_Analog_Server(_vrpn_peripheral_name_, g_pConnection); g_pAnalogServer->setNumChannels(10); ::GtkBuilder* l_pInterface=gtk_builder_new(); // glade_xml_new(OpenViBE::Directories::getDataDir() + "/openvibe-applications/vrpn-simulator/interface.ui", "window", NULL); gtk_builder_add_from_file(l_pInterface, OpenViBE::Directories::getDataDir() + "/openvibe-applications/vrpn-simulator/interface.ui", NULL); ::GtkWidget* l_pMainWindow=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "window")); ::GtkWidget* l_pHBoxButton=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "hbox_button")); ::GtkWidget* l_pHBoxAnalog=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "hbox_analog")); g_signal_connect(G_OBJECT(l_pMainWindow), "destroy", gtk_main_quit, NULL); gtk_container_foreach(GTK_CONTAINER(l_pHBoxButton), fConnectCB, NULL); gtk_container_foreach(GTK_CONTAINER(l_pHBoxAnalog), fConnectCB, NULL); gtk_builder_connect_signals(l_pInterface, NULL); std::cout << "got " << g_iAnalogCount << " analogs...\n"; std::cout << "got " << g_iButtonCount << " buttons...\n"; g_idle_add(fIdleApplicationLoop, NULL); gtk_widget_show(l_pMainWindow); gtk_main(); delete g_pAnalogServer; delete g_pButtonServer; delete g_pConnection; return 0; } <commit_msg>openvibe-applications/vrpn-stimulator: + added #ifdef guard to check for VRPN library availability<commit_after>#if defined TARGET_HAS_ThirdPartyVRPN #include <gtk/gtk.h> #include <gdk/gdk.h> #include <openvibe/ov_directories.h> #include <openvibe/ovCString.h> #include <vrpn_Button.h> #include <vrpn_Analog.h> #include <vrpn_Connection.h> #include <iostream> #define _vrpn_peripheral_name_ "openvibe-vrpn@localhost" // #define _DEBUG ::vrpn_Connection* g_pConnection=NULL; ::vrpn_Button_Server* g_pButtonServer=NULL; ::vrpn_Analog_Server* g_pAnalogServer=NULL; long g_iAnalogCount=0; long g_iButtonCount=0; typedef union { gpointer pUserData; int iData; } TUserData; void fScrollCB(::GtkRange* pRange, gpointer pUserData) { TUserData l_oUserData; l_oUserData.pUserData=pUserData; g_pAnalogServer->channels()[l_oUserData.iData]=gtk_range_get_value(pRange); #if defined _DEBUG std::cout << (int)(pUserData) << " value changed\n"; #endif } void fSwitchCB(::GtkToggleButton* pTogglebutton, gpointer pUserData) { TUserData l_oUserData; l_oUserData.pUserData=pUserData; g_pButtonServer->set_button(l_oUserData.iData, gtk_toggle_button_get_active(pTogglebutton)); #if defined _DEBUG std::cout << (int)(pUserData) << " toggled\n"; #endif } void fConnectCB(::GtkWidget* pWidget, gpointer data) { if(GTK_IS_RANGE(pWidget)) { g_signal_connect(G_OBJECT(pWidget), "value-changed", G_CALLBACK(fScrollCB), (gpointer) g_iAnalogCount); g_iAnalogCount++; } if(GTK_IS_TOGGLE_BUTTON(pWidget)) { g_signal_connect(G_OBJECT(pWidget), "toggled", G_CALLBACK(fSwitchCB), (void*)g_iButtonCount); g_iButtonCount++; } } gboolean fIdleApplicationLoop(gpointer pUserData) { g_pButtonServer->mainloop(); g_pAnalogServer->report_changes(); g_pAnalogServer->mainloop(); g_pConnection->mainloop(); return TRUE; } int main(int argc, char ** argv) { gtk_init(&argc, &argv); // g_pConnection=new ::vrpn_Connection; g_pConnection=vrpn_create_server_connection(); g_pButtonServer=new ::vrpn_Button_Server(_vrpn_peripheral_name_, g_pConnection, 10); g_pAnalogServer=new ::vrpn_Analog_Server(_vrpn_peripheral_name_, g_pConnection); g_pAnalogServer->setNumChannels(10); ::GtkBuilder* l_pInterface=gtk_builder_new(); // glade_xml_new(OpenViBE::Directories::getDataDir() + "/openvibe-applications/vrpn-simulator/interface.ui", "window", NULL); gtk_builder_add_from_file(l_pInterface, OpenViBE::Directories::getDataDir() + "/openvibe-applications/vrpn-simulator/interface.ui", NULL); ::GtkWidget* l_pMainWindow=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "window")); ::GtkWidget* l_pHBoxButton=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "hbox_button")); ::GtkWidget* l_pHBoxAnalog=GTK_WIDGET(gtk_builder_get_object(l_pInterface, "hbox_analog")); g_signal_connect(G_OBJECT(l_pMainWindow), "destroy", gtk_main_quit, NULL); gtk_container_foreach(GTK_CONTAINER(l_pHBoxButton), fConnectCB, NULL); gtk_container_foreach(GTK_CONTAINER(l_pHBoxAnalog), fConnectCB, NULL); gtk_builder_connect_signals(l_pInterface, NULL); std::cout << "got " << g_iAnalogCount << " analogs...\n"; std::cout << "got " << g_iButtonCount << " buttons...\n"; g_idle_add(fIdleApplicationLoop, NULL); gtk_widget_show(l_pMainWindow); gtk_main(); delete g_pAnalogServer; delete g_pButtonServer; delete g_pConnection; return 0; } #endif // TARGET_HAS_ThirdPartyVRPN <|endoftext|>
<commit_before>#include <catch/catch.hpp> #include <Transform/Referential.hpp> using namespace obe::Transform; using FlipAxis = Referential::FlipAxis; TEST_CASE("Flipping Referentials should give correct results", "[obe.Transform.Referential.flip]") { SECTION("Flipping both axis of known referentials") { REQUIRE(Referential::TopLeft.flip() == Referential::BottomRight); REQUIRE(Referential::Top.flip() == Referential::Bottom); REQUIRE(Referential::TopRight.flip() == Referential::BottomLeft); REQUIRE(Referential::Left.flip() == Referential::Right); REQUIRE(Referential::Center.flip() == Referential::Center); REQUIRE(Referential::Right.flip() == Referential::Left); REQUIRE(Referential::BottomLeft.flip() == Referential::TopRight); REQUIRE(Referential::Bottom.flip() == Referential::Top); REQUIRE(Referential::BottomRight.flip() == Referential::TopLeft); } SECTION("Flipping only horizontal axis of known referentials") { REQUIRE(Referential::TopLeft.flip(FlipAxis::Horizontal) == Referential::TopRight); REQUIRE(Referential::Top.flip(FlipAxis::Horizontal) == Referential::Top); REQUIRE(Referential::TopRight.flip(FlipAxis::Horizontal) == Referential::TopLeft); REQUIRE(Referential::Left.flip(FlipAxis::Horizontal) == Referential::Right); REQUIRE(Referential::Center.flip(FlipAxis::Horizontal) == Referential::Center); REQUIRE(Referential::Right.flip(FlipAxis::Horizontal) == Referential::Left); REQUIRE(Referential::BottomLeft.flip(FlipAxis::Horizontal) == Referential::BottomRight); REQUIRE(Referential::Bottom.flip(FlipAxis::Horizontal) == Referential::Bottom); REQUIRE(Referential::BottomRight.flip(FlipAxis::Horizontal) == Referential::BottomLeft); } SECTION("Flipping only vertical axis of known referentials") { REQUIRE(Referential::TopLeft.flip(FlipAxis::Vertical) == Referential::BottomLeft); REQUIRE(Referential::Top.flip(FlipAxis::Vertical) == Referential::Bottom); REQUIRE( Referential::TopRight.flip(FlipAxis::Vertical) == Referential::BottomRight); REQUIRE(Referential::Left.flip(FlipAxis::Vertical) == Referential::Left); REQUIRE(Referential::Center.flip(FlipAxis::Vertical) == Referential::Center); REQUIRE(Referential::Right.flip(FlipAxis::Vertical) == Referential::Right); REQUIRE(Referential::BottomLeft.flip(FlipAxis::Vertical) == Referential::TopLeft); REQUIRE(Referential::Bottom.flip(FlipAxis::Vertical) == Referential::Top); REQUIRE( Referential::BottomRight.flip(FlipAxis::Vertical) == Referential::TopRight); } SECTION("Flipping both axis of random referentials") { REQUIRE(Referential(0.1, 0.4).flip() == Referential(0.9, 0.6)); REQUIRE(Referential(0.4, 0.6).flip() == Referential(0.6, 0.4)); REQUIRE(Referential(0.2, 0.2).flip() == Referential(0.8, 0.8)); REQUIRE(Referential(0.3, 0.5).flip() == Referential(0.7, 0.5)); } } TEST_CASE("We should be able to test the position of referentials based on criterias", "[obe.Transform.Referential.isOn...]") { SECTION("Testing if known referentials are on a corner") { REQUIRE(Referential::TopLeft.isOnCorner()); REQUIRE(Referential::TopRight.isOnCorner()); REQUIRE(Referential::BottomLeft.isOnCorner()); REQUIRE(Referential::BottomRight.isOnCorner()); REQUIRE_FALSE(Referential::Top.isOnCorner()); REQUIRE_FALSE(Referential::Left.isOnCorner()); REQUIRE_FALSE(Referential::Center.isOnCorner()); REQUIRE_FALSE(Referential::Right.isOnCorner()); REQUIRE_FALSE(Referential::Bottom.isOnCorner()); } SECTION("Testing if known referentials are on a side") { REQUIRE_FALSE(Referential::TopLeft.isOnSide()); REQUIRE_FALSE(Referential::TopRight.isOnSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnSide()); REQUIRE_FALSE(Referential::BottomRight.isOnSide()); REQUIRE(Referential::Top.isOnSide()); REQUIRE(Referential::Left.isOnSide()); REQUIRE_FALSE(Referential::Center.isOnSide()); REQUIRE(Referential::Right.isOnSide()); REQUIRE(Referential::Bottom.isOnSide()); } SECTION("Testing if known referentials are on the left") { REQUIRE(Referential::TopLeft.isOnLeftSide()); REQUIRE_FALSE(Referential::Top.isOnLeftSide()); REQUIRE_FALSE(Referential::TopRight.isOnLeftSide()); REQUIRE(Referential::Left.isOnLeftSide()); REQUIRE_FALSE(Referential::Center.isOnLeftSide()); REQUIRE_FALSE(Referential::Right.isOnLeftSide()); REQUIRE(Referential::BottomLeft.isOnLeftSide()); REQUIRE_FALSE(Referential::Bottom.isOnLeftSide()); REQUIRE_FALSE(Referential::BottomRight.isOnLeftSide()); } SECTION("Testing if known referentials are on the right") { REQUIRE_FALSE(Referential::TopLeft.isOnRightSide()); REQUIRE_FALSE(Referential::Top.isOnRightSide()); REQUIRE(Referential::TopRight.isOnRightSide()); REQUIRE_FALSE(Referential::Left.isOnRightSide()); REQUIRE_FALSE(Referential::Center.isOnRightSide()); REQUIRE(Referential::Right.isOnRightSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnRightSide()); REQUIRE_FALSE(Referential::Bottom.isOnRightSide()); REQUIRE(Referential::BottomRight.isOnRightSide()); } SECTION("Testing if known referentials are on the top") { REQUIRE(Referential::TopLeft.isOnTopSide()); REQUIRE(Referential::Top.isOnTopSide()); REQUIRE(Referential::TopRight.isOnTopSide()); REQUIRE_FALSE(Referential::Left.isOnTopSide()); REQUIRE_FALSE(Referential::Center.isOnTopSide()); REQUIRE_FALSE(Referential::Right.isOnTopSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnTopSide()); REQUIRE_FALSE(Referential::Bottom.isOnTopSide()); REQUIRE_FALSE(Referential::BottomRight.isOnTopSide()); } SECTION("Testing if known referentials are on the bottom") { REQUIRE_FALSE(Referential::TopLeft.isOnBottomSide()); REQUIRE_FALSE(Referential::Top.isOnBottomSide()); REQUIRE_FALSE(Referential::TopRight.isOnBottomSide()); REQUIRE_FALSE(Referential::Left.isOnBottomSide()); REQUIRE_FALSE(Referential::Center.isOnBottomSide()); REQUIRE_FALSE(Referential::Right.isOnBottomSide()); REQUIRE(Referential::BottomLeft.isOnBottomSide()); REQUIRE(Referential::Bottom.isOnBottomSide()); REQUIRE(Referential::BottomRight.isOnBottomSide()); } SECTION("Testing random referentials and their positions") { REQUIRE(Referential(1, 0.33).isOnRightSide()); REQUIRE(Referential(0, 0.66).isOnLeftSide()); REQUIRE(Referential(0.22, 1).isOnBottomSide()); REQUIRE(Referential(-0.11, 0).isOnTopSide()); REQUIRE(Referential(0.99, 1).isOnSide()); REQUIRE(Referential(0, 0).isOnCorner()); REQUIRE_FALSE(Referential(0.999, 0.33).isOnRightSide()); REQUIRE_FALSE(Referential(1, 0.66).isOnLeftSide()); REQUIRE_FALSE(Referential(0.22, 0).isOnBottomSide()); REQUIRE_FALSE(Referential(0.11, 1).isOnTopSide()); REQUIRE_FALSE(Referential(0.99, 0.99).isOnSide()); REQUIRE_FALSE(Referential(0.4, 0).isOnCorner()); } } TEST_CASE("We should be able to represent a Referential as a string", "[obe.Transform.Referential.toString]") { SECTION("Transforming known referentials to string with default formatter") { REQUIRE(Referential::TopLeft.toString() == "Referential<TopLeft>"); REQUIRE(Referential::Top.toString() == "Referential<Top>"); REQUIRE(Referential::TopRight.toString() == "Referential<TopRight>"); REQUIRE(Referential::Left.toString() == "Referential<Left>"); REQUIRE(Referential::Center.toString() == "Referential<Center>"); REQUIRE(Referential::Right.toString() == "Referential<Right>"); REQUIRE(Referential::BottomLeft.toString() == "Referential<BottomLeft>"); REQUIRE(Referential::Bottom.toString() == "Referential<Bottom>"); REQUIRE(Referential::BottomRight.toString() == "Referential<BottomRight>"); } SECTION("Transforming known referentials to string with custom formatter") { REQUIRE(Referential::TopLeft.toString("A({})") == "A(TopLeft)"); REQUIRE(Referential::Top.toString("+{}") == "+Top"); REQUIRE(Referential::TopRight.toString("/{}/") == "/TopRight/"); REQUIRE(Referential::Left.toString("Why did you {} me") == "Why did you Left me"); REQUIRE(Referential::Center.toString("{} of the Earth") == "Center of the Earth"); REQUIRE(Referential::Right.toString("You were actually {}") == "You were actually Right"); REQUIRE(Referential::BottomLeft.toString("1+2={}") == "1+2=BottomLeft"); REQUIRE(Referential::Bottom.toString("Bikini {}") == "Bikini Bottom"); REQUIRE(Referential::BottomRight.toString("{0} == {0}") == "BottomRight == BottomRight"); } SECTION("Transforming random referentials to string with default formatter") { REQUIRE(Referential(0.123, 0.456).toString() == "Referential<0.123, 0.456>"); REQUIRE(Referential(0.6666, 0.9999).toString() == "Referential<0.6666, 0.9999>"); } SECTION("Transforming random referentials to string with custom formatter") { REQUIRE(Referential(0.9, 0.1).toString("{}") == "0.9, 0.1"); REQUIRE(Referential(0.1234, 0.5678).toString("Referential => {}") == "Referential => 0.1234, 0.5678"); REQUIRE(Referential(0.666, 1).toString("The devil is == {1}") == "The devil is == 0.666"); REQUIRE(Referential(0.1, 0.42).toString("I wonder why {2} is the answer") == "I wonder why 0.42 is the answer"); REQUIRE(Referential(0.456, 0.123).toString("y = {2}, x = {1}") == "y = 0.123, x = 0.456"); } } TEST_CASE("We should be able to load a Referential from a string", "[obe.Transform.Referential.FromString]") { SECTION("Loading known referentials from a string") { REQUIRE(Referential::FromString("TopLeft") == Referential::TopLeft); REQUIRE(Referential::FromString("Top") == Referential::Top); REQUIRE(Referential::FromString("TopRight") == Referential::TopRight); REQUIRE(Referential::FromString("Left") == Referential::Left); REQUIRE(Referential::FromString("Center") == Referential::Center); REQUIRE(Referential::FromString("Right") == Referential::Right); REQUIRE(Referential::FromString("BottomLeft") == Referential::BottomLeft); REQUIRE(Referential::FromString("Bottom") == Referential::Bottom); REQUIRE(Referential::FromString("BottomRight") == Referential::BottomRight); } SECTION("Loading random referentials from a string") { REQUIRE(Referential::FromString("Referential<0.1, 0.666>") == Referential(0.1, 0.666)); REQUIRE( Referential::FromString("Referential<-0.55, -1>") == Referential(-0.55, -1)); REQUIRE_THROWS(Referential::FromString("?")); } }<commit_msg>Fixed tests<commit_after>#include <catch/catch.hpp> #include <Transform/Referential.hpp> using namespace obe::Transform; TEST_CASE("Flipping Referentials should give correct results", "[obe.Transform.Referential.flip]") { SECTION("Flipping both axis of known referentials") { REQUIRE(Referential::TopLeft.flip() == Referential::BottomRight); REQUIRE(Referential::Top.flip() == Referential::Bottom); REQUIRE(Referential::TopRight.flip() == Referential::BottomLeft); REQUIRE(Referential::Left.flip() == Referential::Right); REQUIRE(Referential::Center.flip() == Referential::Center); REQUIRE(Referential::Right.flip() == Referential::Left); REQUIRE(Referential::BottomLeft.flip() == Referential::TopRight); REQUIRE(Referential::Bottom.flip() == Referential::Top); REQUIRE(Referential::BottomRight.flip() == Referential::TopLeft); } SECTION("Flipping only horizontal axis of known referentials") { REQUIRE(Referential::TopLeft.flip(FlipAxis::Horizontal) == Referential::TopRight); REQUIRE(Referential::Top.flip(FlipAxis::Horizontal) == Referential::Top); REQUIRE(Referential::TopRight.flip(FlipAxis::Horizontal) == Referential::TopLeft); REQUIRE(Referential::Left.flip(FlipAxis::Horizontal) == Referential::Right); REQUIRE(Referential::Center.flip(FlipAxis::Horizontal) == Referential::Center); REQUIRE(Referential::Right.flip(FlipAxis::Horizontal) == Referential::Left); REQUIRE(Referential::BottomLeft.flip(FlipAxis::Horizontal) == Referential::BottomRight); REQUIRE(Referential::Bottom.flip(FlipAxis::Horizontal) == Referential::Bottom); REQUIRE(Referential::BottomRight.flip(FlipAxis::Horizontal) == Referential::BottomLeft); } SECTION("Flipping only vertical axis of known referentials") { REQUIRE(Referential::TopLeft.flip(FlipAxis::Vertical) == Referential::BottomLeft); REQUIRE(Referential::Top.flip(FlipAxis::Vertical) == Referential::Bottom); REQUIRE( Referential::TopRight.flip(FlipAxis::Vertical) == Referential::BottomRight); REQUIRE(Referential::Left.flip(FlipAxis::Vertical) == Referential::Left); REQUIRE(Referential::Center.flip(FlipAxis::Vertical) == Referential::Center); REQUIRE(Referential::Right.flip(FlipAxis::Vertical) == Referential::Right); REQUIRE(Referential::BottomLeft.flip(FlipAxis::Vertical) == Referential::TopLeft); REQUIRE(Referential::Bottom.flip(FlipAxis::Vertical) == Referential::Top); REQUIRE( Referential::BottomRight.flip(FlipAxis::Vertical) == Referential::TopRight); } SECTION("Flipping both axis of random referentials") { REQUIRE(Referential(0.1, 0.4).flip() == Referential(0.9, 0.6)); REQUIRE(Referential(0.4, 0.6).flip() == Referential(0.6, 0.4)); REQUIRE(Referential(0.2, 0.2).flip() == Referential(0.8, 0.8)); REQUIRE(Referential(0.3, 0.5).flip() == Referential(0.7, 0.5)); } } TEST_CASE("We should be able to test the position of referentials based on criterias", "[obe.Transform.Referential.isOn...]") { SECTION("Testing if known referentials are on a corner") { REQUIRE(Referential::TopLeft.isOnCorner()); REQUIRE(Referential::TopRight.isOnCorner()); REQUIRE(Referential::BottomLeft.isOnCorner()); REQUIRE(Referential::BottomRight.isOnCorner()); REQUIRE_FALSE(Referential::Top.isOnCorner()); REQUIRE_FALSE(Referential::Left.isOnCorner()); REQUIRE_FALSE(Referential::Center.isOnCorner()); REQUIRE_FALSE(Referential::Right.isOnCorner()); REQUIRE_FALSE(Referential::Bottom.isOnCorner()); } SECTION("Testing if known referentials are on a side") { REQUIRE_FALSE(Referential::TopLeft.isOnSide()); REQUIRE_FALSE(Referential::TopRight.isOnSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnSide()); REQUIRE_FALSE(Referential::BottomRight.isOnSide()); REQUIRE(Referential::Top.isOnSide()); REQUIRE(Referential::Left.isOnSide()); REQUIRE_FALSE(Referential::Center.isOnSide()); REQUIRE(Referential::Right.isOnSide()); REQUIRE(Referential::Bottom.isOnSide()); } SECTION("Testing if known referentials are on the left") { REQUIRE(Referential::TopLeft.isOnLeftSide()); REQUIRE_FALSE(Referential::Top.isOnLeftSide()); REQUIRE_FALSE(Referential::TopRight.isOnLeftSide()); REQUIRE(Referential::Left.isOnLeftSide()); REQUIRE_FALSE(Referential::Center.isOnLeftSide()); REQUIRE_FALSE(Referential::Right.isOnLeftSide()); REQUIRE(Referential::BottomLeft.isOnLeftSide()); REQUIRE_FALSE(Referential::Bottom.isOnLeftSide()); REQUIRE_FALSE(Referential::BottomRight.isOnLeftSide()); } SECTION("Testing if known referentials are on the right") { REQUIRE_FALSE(Referential::TopLeft.isOnRightSide()); REQUIRE_FALSE(Referential::Top.isOnRightSide()); REQUIRE(Referential::TopRight.isOnRightSide()); REQUIRE_FALSE(Referential::Left.isOnRightSide()); REQUIRE_FALSE(Referential::Center.isOnRightSide()); REQUIRE(Referential::Right.isOnRightSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnRightSide()); REQUIRE_FALSE(Referential::Bottom.isOnRightSide()); REQUIRE(Referential::BottomRight.isOnRightSide()); } SECTION("Testing if known referentials are on the top") { REQUIRE(Referential::TopLeft.isOnTopSide()); REQUIRE(Referential::Top.isOnTopSide()); REQUIRE(Referential::TopRight.isOnTopSide()); REQUIRE_FALSE(Referential::Left.isOnTopSide()); REQUIRE_FALSE(Referential::Center.isOnTopSide()); REQUIRE_FALSE(Referential::Right.isOnTopSide()); REQUIRE_FALSE(Referential::BottomLeft.isOnTopSide()); REQUIRE_FALSE(Referential::Bottom.isOnTopSide()); REQUIRE_FALSE(Referential::BottomRight.isOnTopSide()); } SECTION("Testing if known referentials are on the bottom") { REQUIRE_FALSE(Referential::TopLeft.isOnBottomSide()); REQUIRE_FALSE(Referential::Top.isOnBottomSide()); REQUIRE_FALSE(Referential::TopRight.isOnBottomSide()); REQUIRE_FALSE(Referential::Left.isOnBottomSide()); REQUIRE_FALSE(Referential::Center.isOnBottomSide()); REQUIRE_FALSE(Referential::Right.isOnBottomSide()); REQUIRE(Referential::BottomLeft.isOnBottomSide()); REQUIRE(Referential::Bottom.isOnBottomSide()); REQUIRE(Referential::BottomRight.isOnBottomSide()); } SECTION("Testing random referentials and their positions") { REQUIRE(Referential(1, 0.33).isOnRightSide()); REQUIRE(Referential(0, 0.66).isOnLeftSide()); REQUIRE(Referential(0.22, 1).isOnBottomSide()); REQUIRE(Referential(-0.11, 0).isOnTopSide()); REQUIRE(Referential(0.99, 1).isOnSide()); REQUIRE(Referential(0, 0).isOnCorner()); REQUIRE_FALSE(Referential(0.999, 0.33).isOnRightSide()); REQUIRE_FALSE(Referential(1, 0.66).isOnLeftSide()); REQUIRE_FALSE(Referential(0.22, 0).isOnBottomSide()); REQUIRE_FALSE(Referential(0.11, 1).isOnTopSide()); REQUIRE_FALSE(Referential(0.99, 0.99).isOnSide()); REQUIRE_FALSE(Referential(0.4, 0).isOnCorner()); } } TEST_CASE("We should be able to represent a Referential as a string", "[obe.Transform.Referential.toString]") { SECTION("Transforming known referentials to string with default formatter") { REQUIRE(Referential::TopLeft.toString() == "Referential<TopLeft>"); REQUIRE(Referential::Top.toString() == "Referential<Top>"); REQUIRE(Referential::TopRight.toString() == "Referential<TopRight>"); REQUIRE(Referential::Left.toString() == "Referential<Left>"); REQUIRE(Referential::Center.toString() == "Referential<Center>"); REQUIRE(Referential::Right.toString() == "Referential<Right>"); REQUIRE(Referential::BottomLeft.toString() == "Referential<BottomLeft>"); REQUIRE(Referential::Bottom.toString() == "Referential<Bottom>"); REQUIRE(Referential::BottomRight.toString() == "Referential<BottomRight>"); } SECTION("Transforming known referentials to string with custom formatter") { REQUIRE(Referential::TopLeft.toString("A({})") == "A(TopLeft)"); REQUIRE(Referential::Top.toString("+{}") == "+Top"); REQUIRE(Referential::TopRight.toString("/{}/") == "/TopRight/"); REQUIRE(Referential::Left.toString("Why did you {} me") == "Why did you Left me"); REQUIRE(Referential::Center.toString("{} of the Earth") == "Center of the Earth"); REQUIRE(Referential::Right.toString("You were actually {}") == "You were actually Right"); REQUIRE(Referential::BottomLeft.toString("1+2={}") == "1+2=BottomLeft"); REQUIRE(Referential::Bottom.toString("Bikini {}") == "Bikini Bottom"); REQUIRE(Referential::BottomRight.toString("{0} == {0}") == "BottomRight == BottomRight"); } SECTION("Transforming random referentials to string with default formatter") { REQUIRE(Referential(0.123, 0.456).toString() == "Referential<0.123, 0.456>"); REQUIRE(Referential(0.6666, 0.9999).toString() == "Referential<0.6666, 0.9999>"); } SECTION("Transforming random referentials to string with custom formatter") { REQUIRE(Referential(0.9, 0.1).toString("{}") == "0.9, 0.1"); REQUIRE(Referential(0.1234, 0.5678).toString("Referential => {}") == "Referential => 0.1234, 0.5678"); REQUIRE(Referential(0.666, 1).toString("The devil is == {1}") == "The devil is == 0.666"); REQUIRE(Referential(0.1, 0.42).toString("I wonder why {2} is the answer") == "I wonder why 0.42 is the answer"); REQUIRE(Referential(0.456, 0.123).toString("y = {2}, x = {1}") == "y = 0.123, x = 0.456"); } } TEST_CASE("We should be able to load a Referential from a string", "[obe.Transform.Referential.FromString]") { SECTION("Loading known referentials from a string") { REQUIRE(Referential::FromString("TopLeft") == Referential::TopLeft); REQUIRE(Referential::FromString("Top") == Referential::Top); REQUIRE(Referential::FromString("TopRight") == Referential::TopRight); REQUIRE(Referential::FromString("Left") == Referential::Left); REQUIRE(Referential::FromString("Center") == Referential::Center); REQUIRE(Referential::FromString("Right") == Referential::Right); REQUIRE(Referential::FromString("BottomLeft") == Referential::BottomLeft); REQUIRE(Referential::FromString("Bottom") == Referential::Bottom); REQUIRE(Referential::FromString("BottomRight") == Referential::BottomRight); } SECTION("Loading random referentials from a string") { REQUIRE(Referential::FromString("Referential<0.1, 0.666>") == Referential(0.1, 0.666)); REQUIRE( Referential::FromString("Referential<-0.55, -1>") == Referential(-0.55, -1)); REQUIRE_THROWS(Referential::FromString("?")); } }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 6/17/2019, 12:04:14 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) typedef long long ll; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } const int MAX_SIZE = 1000010; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } mint inv[MAX_SIZE]; mint fact[MAX_SIZE]; mint factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint choose(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // const double epsilon = 1e-10; // const ll infty = 1000000000000000LL; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; int N, M; int S[2010]; int T[2010]; mint dp0[2010][2010]; mint dp1[2010][2010]; int main() { // init(); cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> S[i]; } for (auto i = 0; i < M; i++) { cin >> T[i]; } dp0[0][0] = 1; for (auto i = 0; i < N; i++) { for (auto j = 0; j < M; j++) { dp0[i + 1][j] += dp0[i][j]; dp1[i][j + 1] += dp0[i][j]; dp1[i][j + 1] += dp1[i][j]; if (S[i] == T[j]) { dp0[i + 1][j + 1] += dp1[i][j]; } } } mint ans = dp1[N][M]; cout << ans << endl; }<commit_msg>submit E2.cpp to 'E - Common Subsequence' (abc130) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 6/17/2019, 12:04:14 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) typedef long long ll; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } const int MAX_SIZE = 1000010; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } mint inv[MAX_SIZE]; mint fact[MAX_SIZE]; mint factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint choose(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // const double epsilon = 1e-10; // const ll infty = 1000000000000000LL; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; int N, M; int S[2010]; int T[2010]; mint dp0[2010][2010]; mint dp1[2010][2010]; int main() { // init(); cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> S[i]; } for (auto i = 0; i < M; i++) { cin >> T[i]; } dp0[0][0] = 1; for (auto i = 0; i <= N; i++) { for (auto j = 0; j <= M; j++) { dp0[i + 1][j] += dp0[i][j]; dp1[i][j] += dp0[i][j]; dp1[i][j + 1] += dp1[i][j]; if (i < N && j < M && S[i] == T[j]) { dp0[i + 1][j + 1] += dp1[i][j]; } } } mint ans = dp1[N][M]; cout << ans << endl; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: updatedispatch.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:11:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include "updatedispatch.hxx" #ifndef CONFIGMGR_CONFIGPATH_HXX_ #include "configpath.hxx" #endif #ifndef INCLUDED_SHARABLE_NODE_HXX #include "node.hxx" #endif #ifndef CONFIGMGR_TREEACCESSOR_HXX #include "treeaccessor.hxx" #endif #ifndef CONFIGMGR_VALUENODEACCESS_HXX #include "valuenodeaccess.hxx" #endif #ifndef CONFIGMGR_GROUPNODEACCESS_HXX #include "groupnodeaccess.hxx" #endif #ifndef CONFIGMGR_SETNODEACCESS_HXX #include "setnodeaccess.hxx" #endif #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif #include <com/sun/star/configuration/backend/XUpdateHandler.hpp> #include <com/sun/star/configuration/backend/NodeAttribute.hpp> namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- UpdateDispatcher::UpdateDispatcher(UpdateHandler const & _xUpdateHandler, OUString const & _aLocale) : m_pContextPath(NULL) , m_xUpdateHandler(_xUpdateHandler) , m_aLocale(_aLocale) , m_aElementName() , m_bInValueSet(false) , m_bInLocalizedValues(false) { } // ----------------------------------------------------------------------------- UpdateDispatcher::~UpdateDispatcher() { } // ----------------------------------------------------------------------------- void UpdateDispatcher::dispatchUpdate(configuration::AbsolutePath const & _aRootPath, SubtreeChange const& _anUpdate) { if (!m_xUpdateHandler.is()) { OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("ERROR: Cannot dispatch update - no handler found") ); throw uno::RuntimeException(sMsg,NULL); } OSL_PRECOND( !_aRootPath.isRoot(), "Cannot apply update, where root is outside a component" ); OSL_PRECOND( m_pContextPath == NULL, "Update Dispatcher already has a context path" ); if (!_aRootPath.getParentPath().isRoot()) { OSL_ENSURE(false,"Obsolete functionality used: starting update with non-empty context"); m_pContextPath = &_aRootPath; } this->startUpdate(); this->applyToChange(_anUpdate); this->endUpdate(); m_pContextPath = NULL; } // ----------------------------------------------------------------------------- void UpdateDispatcher::startUpdate() { m_xUpdateHandler->startUpdate(); m_bInValueSet = false; m_bInLocalizedValues = false; m_aElementName = OUString(); if (m_pContextPath) { configuration::AbsolutePath::Iterator it = m_pContextPath->begin(); configuration::AbsolutePath::Iterator stop = m_pContextPath->end(); OSL_ASSERT(it != stop); --stop; for ( ; it != stop; ++it) { m_xUpdateHandler->modifyNode(it->getName().toString(),0,0,false); } } } // ----------------------------------------------------------------------------- void UpdateDispatcher::endUpdate() { if (m_pContextPath) { configuration::AbsolutePath::Iterator it = m_pContextPath->begin(); configuration::AbsolutePath::Iterator stop = m_pContextPath->end(); OSL_ASSERT(it != stop); --stop; for ( ; it != stop; ++it) { m_xUpdateHandler->endNode(); } } m_xUpdateHandler->endUpdate(); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(ValueChange const& aValueNode) { // special case: doing members of a localized property (as set) if (m_bInLocalizedValues) { OUString aLocale = aValueNode.getNodeName(); if (aLocale.getLength()) { if ( aValueNode.isToDefault() ) m_xUpdateHandler->resetPropertyValueForLocale( aLocale ); else m_xUpdateHandler->setPropertyValueForLocale( aValueNode.getNewValue(), aLocale ); } else { if ( aValueNode.isToDefault() ) m_xUpdateHandler->resetPropertyValue( ); else m_xUpdateHandler->setPropertyValue( aValueNode.getNewValue() ); } return; } // normal case: updating a single property switch (aValueNode.getMode()) { case ValueChange::wasDefault: if (aValueNode.isReplacedValue()) { OSL_ENSURE(m_bInValueSet, "UpdateDispatcher: Cannot add/replace a value in a nonextensible node"); OSL_ENSURE(!aValueNode.isLocalizedValue(), "UpdateDispatcher: Cannot add a localized value in a layer"); sal_Int16 nAttr = getUpdateAttributes(aValueNode.getAttributes(),true); if (aValueNode.getNewValue().hasValue()) { m_xUpdateHandler->addOrReplacePropertyWithValue( aValueNode.getNodeName(), nAttr, aValueNode.getNewValue()); } else { m_xUpdateHandler->addOrReplaceProperty( aValueNode.getNodeName(), nAttr, aValueNode.getValueType()); } break; } // else fall thru to changeValue case case ValueChange::changeValue: { sal_Int16 nAttr = getUpdateAttributes(aValueNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(aValueNode.getAttributes()); m_xUpdateHandler->modifyProperty( aValueNode.getNodeName(), nAttr, nAttrMask, aValueNode.getValueType() ); if (aValueNode.isLocalizedValue() && m_aLocale.getLength()) { m_xUpdateHandler->setPropertyValueForLocale( aValueNode.getNewValue(), m_aLocale ); } else { m_xUpdateHandler->setPropertyValue( aValueNode.getNewValue() ); } m_xUpdateHandler->endProperty(); } break; case ValueChange::setToDefault: m_xUpdateHandler->resetProperty( aValueNode.getNodeName() ); break; case ValueChange::changeDefault: OSL_ENSURE(false, "Illegal mode in ValueChange"); break; default: OSL_ENSURE(false, "Illegal mode in ValueChange"); break; }; } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(AddNode const& aAddNode) { data::TreeSegment aAddedTree = aAddNode.getNewTree(); OSL_ENSURE(aAddedTree.is(), "AddNode has no new data -> cannot add anything"); OSL_ENSURE( !aAddedTree.is() || ((m_bInValueSet||m_bInLocalizedValues) == aAddedTree.getSegmentRootNode()->isValue()), "Found added subtree in value set (extensible group)\n" ); this->visitTree( aAddedTree.getTreeAccess() ); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(RemoveNode const& aRemoveNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: Removing values for a specific locale is currently not supported"); data::TreeSegment aRemovedTree = aRemoveNode.getRemovedTree(); OSL_ENSURE( !aRemovedTree.is() || ((m_bInValueSet||m_bInLocalizedValues) == aRemovedTree.getSegmentRootNode()->isValue()), "Found removed subtree in value set (extensible group)\n" ); if (m_bInLocalizedValues) OSL_TRACE("configmgr: UpdateDispatcher - Removing value for locale ignored"); else if (m_bInValueSet) m_xUpdateHandler->removeProperty( aRemoveNode.getNodeName() ); else m_xUpdateHandler->removeNode( aRemoveNode.getNodeName() ); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(SubtreeChange const& aSubtree) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete subtree"); OSL_ENSURE( !m_bInValueSet, "UpdateDispatcher: A dynamic property cannot be a complete subtree"); sal_Int16 nAttr = getUpdateAttributes(aSubtree.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(aSubtree.getAttributes()); if (isLocalizedValueSet(aSubtree)) { m_xUpdateHandler->modifyProperty( aSubtree.getNodeName(), nAttr, nAttrMask, uno::Type() ); m_bInLocalizedValues = true; this->applyToChildren(aSubtree); m_bInLocalizedValues = false; m_xUpdateHandler->endProperty(); } else { m_xUpdateHandler->modifyNode( aSubtree.getNodeName(), nAttr, nAttrMask, aSubtree.isToDefault() ); m_bInValueSet = isValueSet(aSubtree); this->applyToChildren(aSubtree); m_bInValueSet = false; m_xUpdateHandler->endNode(); } } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::ValueNodeAccess const& _aNode) { OUString aName; // special case: doing members of a localized property (as set) if (m_bInLocalizedValues) { // the node name is the locale OUString aLocale; OSL_VERIFY(testReplacedAndGetName(_aNode,aLocale)); // "Adding a localized subvalue but not as root of element tree" if (aLocale.getLength() && ! localehelper::isDefaultLanguage(aLocale)) { m_xUpdateHandler->setPropertyValueForLocale( _aNode.getValue(), aLocale ); } else { m_xUpdateHandler->setPropertyValue( _aNode.getValue() ); } } else if (testReplacedAndGetName(_aNode,aName)&& (_aNode.getAttributes().isRemovable()) ) // we must be inside a set of values { OSL_ENSURE(!_aNode.isLocalized(), "UpdateDispatcher: Cannot add a localized value in a layer ."); sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); if (!_aNode.isNull()) { m_xUpdateHandler->addOrReplacePropertyWithValue( aName, nAttr, _aNode.getValue()); } else { m_xUpdateHandler->addOrReplaceProperty( aName, nAttr, _aNode.getValueType()); } } else // normal case: updating a single property //Inserting set { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); m_xUpdateHandler->modifyProperty( aName, nAttr, nAttrMask, _aNode.getValueType() ); if (_aNode.isLocalized() && m_aLocale.getLength()) { m_xUpdateHandler->setPropertyValueForLocale( _aNode.getValue(), m_aLocale ); } else { m_xUpdateHandler->setPropertyValue( _aNode.getValue() ); } m_xUpdateHandler->endProperty(); } return CONTINUE; } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::GroupNodeAccess const& _aNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete group"); OUString aName; if ( testReplacedAndGetName(_aNode,aName) ) { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); m_xUpdateHandler->addOrReplaceNode( aName, nAttr ); this->visitChildren(_aNode); m_xUpdateHandler->endNode(); } else { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); m_xUpdateHandler->modifyNode( aName, nAttr, nAttrMask, false ); this->visitChildren(_aNode); m_xUpdateHandler->endNode(); } return CONTINUE; } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::SetNodeAccess const& _aNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete set"); OUString aName; if ( testReplacedAndGetName(_aNode,aName) ) { OSL_ENSURE( !_aNode.isLocalizedValueSetNode(), "UpdateDispatcher: Cannot add a localized value in a layer." ); sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); m_xUpdateHandler->addOrReplaceNode( aName, nAttr ); this->visitElements(_aNode); m_xUpdateHandler->endNode(); } else { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); if (_aNode.isLocalizedValueSetNode()) { m_xUpdateHandler->modifyProperty( aName, nAttr, nAttrMask, uno::Type() ); m_bInLocalizedValues = true; this->visitElements(_aNode); m_bInLocalizedValues = false; m_xUpdateHandler->endProperty(); } else { m_xUpdateHandler->modifyNode( aName, nAttr, nAttrMask, false ); this->visitElements(_aNode); m_xUpdateHandler->endNode(); } } return CONTINUE; } // ----------------------------------------------------------------------------- bool UpdateDispatcher::testReplacedAndGetName(data::NodeAccess const & _aNode, OUString & _aName) { if (m_aElementName.getLength()) { OSL_ENSURE( _aNode->isFragmentRoot(), "ERROR - UpdateDispatcher: Found orphaned 'element' name for inner node"); _aName = m_aElementName; m_aElementName = OUString(); return true; } else { OSL_ENSURE(!_aNode->isFragmentRoot(), "ERROR - UpdateDispatcher: Found no 'element' name for fragment root node"); _aName = _aNode.getName().toString(); return false; } } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::TreeAccessor const& _aElement) { m_aElementName = _aElement.getName().toString(); Result aRes = SetVisitor::handle(_aElement); // dispatch to root node m_aElementName = OUString(); // clear - just to be safe return aRes; } // ----------------------------------------------------------------------------- sal_Int16 UpdateDispatcher::getUpdateAttributes(node::Attributes const & _aAttributes, bool bAdded) { namespace NodeAttribute = backenduno::NodeAttribute; // no support for post-creation attribute changes yet if (!bAdded) { OSL_ENSURE( getUpdateAttributeMask(_aAttributes) == 0, "Incomplete support for attribute changes" ); return 0; } sal_Int16 nResult = 0; if (_aAttributes.isReadonly()) nResult = NodeAttribute::READONLY; if (_aAttributes.isFinalized()) nResult |= NodeAttribute::FINALIZED; if (!_aAttributes.isNullable()) nResult |= NodeAttribute::MANDATORY; return nResult; } // ----------------------------------------------------------------------------- sal_Int16 UpdateDispatcher::getUpdateAttributeMask(node::Attributes const & /*_aAttributes*/) { // no support for post-creation attribute changes yet return 0; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace backend // ------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS changefileheader (1.11.16); FILE MERGED 2008/04/01 12:27:19 thb 1.11.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:41 rt 1.11.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: updatedispatch.cxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include "updatedispatch.hxx" #include "configpath.hxx" #include "node.hxx" #include "treeaccessor.hxx" #include "valuenodeaccess.hxx" #include "groupnodeaccess.hxx" #include "setnodeaccess.hxx" #include "matchlocale.hxx" #include <com/sun/star/configuration/backend/XUpdateHandler.hpp> #include <com/sun/star/configuration/backend/NodeAttribute.hpp> namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- UpdateDispatcher::UpdateDispatcher(UpdateHandler const & _xUpdateHandler, OUString const & _aLocale) : m_pContextPath(NULL) , m_xUpdateHandler(_xUpdateHandler) , m_aLocale(_aLocale) , m_aElementName() , m_bInValueSet(false) , m_bInLocalizedValues(false) { } // ----------------------------------------------------------------------------- UpdateDispatcher::~UpdateDispatcher() { } // ----------------------------------------------------------------------------- void UpdateDispatcher::dispatchUpdate(configuration::AbsolutePath const & _aRootPath, SubtreeChange const& _anUpdate) { if (!m_xUpdateHandler.is()) { OUString sMsg( RTL_CONSTASCII_USTRINGPARAM("ERROR: Cannot dispatch update - no handler found") ); throw uno::RuntimeException(sMsg,NULL); } OSL_PRECOND( !_aRootPath.isRoot(), "Cannot apply update, where root is outside a component" ); OSL_PRECOND( m_pContextPath == NULL, "Update Dispatcher already has a context path" ); if (!_aRootPath.getParentPath().isRoot()) { OSL_ENSURE(false,"Obsolete functionality used: starting update with non-empty context"); m_pContextPath = &_aRootPath; } this->startUpdate(); this->applyToChange(_anUpdate); this->endUpdate(); m_pContextPath = NULL; } // ----------------------------------------------------------------------------- void UpdateDispatcher::startUpdate() { m_xUpdateHandler->startUpdate(); m_bInValueSet = false; m_bInLocalizedValues = false; m_aElementName = OUString(); if (m_pContextPath) { configuration::AbsolutePath::Iterator it = m_pContextPath->begin(); configuration::AbsolutePath::Iterator stop = m_pContextPath->end(); OSL_ASSERT(it != stop); --stop; for ( ; it != stop; ++it) { m_xUpdateHandler->modifyNode(it->getName().toString(),0,0,false); } } } // ----------------------------------------------------------------------------- void UpdateDispatcher::endUpdate() { if (m_pContextPath) { configuration::AbsolutePath::Iterator it = m_pContextPath->begin(); configuration::AbsolutePath::Iterator stop = m_pContextPath->end(); OSL_ASSERT(it != stop); --stop; for ( ; it != stop; ++it) { m_xUpdateHandler->endNode(); } } m_xUpdateHandler->endUpdate(); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(ValueChange const& aValueNode) { // special case: doing members of a localized property (as set) if (m_bInLocalizedValues) { OUString aLocale = aValueNode.getNodeName(); if (aLocale.getLength()) { if ( aValueNode.isToDefault() ) m_xUpdateHandler->resetPropertyValueForLocale( aLocale ); else m_xUpdateHandler->setPropertyValueForLocale( aValueNode.getNewValue(), aLocale ); } else { if ( aValueNode.isToDefault() ) m_xUpdateHandler->resetPropertyValue( ); else m_xUpdateHandler->setPropertyValue( aValueNode.getNewValue() ); } return; } // normal case: updating a single property switch (aValueNode.getMode()) { case ValueChange::wasDefault: if (aValueNode.isReplacedValue()) { OSL_ENSURE(m_bInValueSet, "UpdateDispatcher: Cannot add/replace a value in a nonextensible node"); OSL_ENSURE(!aValueNode.isLocalizedValue(), "UpdateDispatcher: Cannot add a localized value in a layer"); sal_Int16 nAttr = getUpdateAttributes(aValueNode.getAttributes(),true); if (aValueNode.getNewValue().hasValue()) { m_xUpdateHandler->addOrReplacePropertyWithValue( aValueNode.getNodeName(), nAttr, aValueNode.getNewValue()); } else { m_xUpdateHandler->addOrReplaceProperty( aValueNode.getNodeName(), nAttr, aValueNode.getValueType()); } break; } // else fall thru to changeValue case case ValueChange::changeValue: { sal_Int16 nAttr = getUpdateAttributes(aValueNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(aValueNode.getAttributes()); m_xUpdateHandler->modifyProperty( aValueNode.getNodeName(), nAttr, nAttrMask, aValueNode.getValueType() ); if (aValueNode.isLocalizedValue() && m_aLocale.getLength()) { m_xUpdateHandler->setPropertyValueForLocale( aValueNode.getNewValue(), m_aLocale ); } else { m_xUpdateHandler->setPropertyValue( aValueNode.getNewValue() ); } m_xUpdateHandler->endProperty(); } break; case ValueChange::setToDefault: m_xUpdateHandler->resetProperty( aValueNode.getNodeName() ); break; case ValueChange::changeDefault: OSL_ENSURE(false, "Illegal mode in ValueChange"); break; default: OSL_ENSURE(false, "Illegal mode in ValueChange"); break; }; } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(AddNode const& aAddNode) { data::TreeSegment aAddedTree = aAddNode.getNewTree(); OSL_ENSURE(aAddedTree.is(), "AddNode has no new data -> cannot add anything"); OSL_ENSURE( !aAddedTree.is() || ((m_bInValueSet||m_bInLocalizedValues) == aAddedTree.getSegmentRootNode()->isValue()), "Found added subtree in value set (extensible group)\n" ); this->visitTree( aAddedTree.getTreeAccess() ); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(RemoveNode const& aRemoveNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: Removing values for a specific locale is currently not supported"); data::TreeSegment aRemovedTree = aRemoveNode.getRemovedTree(); OSL_ENSURE( !aRemovedTree.is() || ((m_bInValueSet||m_bInLocalizedValues) == aRemovedTree.getSegmentRootNode()->isValue()), "Found removed subtree in value set (extensible group)\n" ); if (m_bInLocalizedValues) OSL_TRACE("configmgr: UpdateDispatcher - Removing value for locale ignored"); else if (m_bInValueSet) m_xUpdateHandler->removeProperty( aRemoveNode.getNodeName() ); else m_xUpdateHandler->removeNode( aRemoveNode.getNodeName() ); } // ----------------------------------------------------------------------------- void UpdateDispatcher::handle(SubtreeChange const& aSubtree) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete subtree"); OSL_ENSURE( !m_bInValueSet, "UpdateDispatcher: A dynamic property cannot be a complete subtree"); sal_Int16 nAttr = getUpdateAttributes(aSubtree.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(aSubtree.getAttributes()); if (isLocalizedValueSet(aSubtree)) { m_xUpdateHandler->modifyProperty( aSubtree.getNodeName(), nAttr, nAttrMask, uno::Type() ); m_bInLocalizedValues = true; this->applyToChildren(aSubtree); m_bInLocalizedValues = false; m_xUpdateHandler->endProperty(); } else { m_xUpdateHandler->modifyNode( aSubtree.getNodeName(), nAttr, nAttrMask, aSubtree.isToDefault() ); m_bInValueSet = isValueSet(aSubtree); this->applyToChildren(aSubtree); m_bInValueSet = false; m_xUpdateHandler->endNode(); } } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::ValueNodeAccess const& _aNode) { OUString aName; // special case: doing members of a localized property (as set) if (m_bInLocalizedValues) { // the node name is the locale OUString aLocale; OSL_VERIFY(testReplacedAndGetName(_aNode,aLocale)); // "Adding a localized subvalue but not as root of element tree" if (aLocale.getLength() && ! localehelper::isDefaultLanguage(aLocale)) { m_xUpdateHandler->setPropertyValueForLocale( _aNode.getValue(), aLocale ); } else { m_xUpdateHandler->setPropertyValue( _aNode.getValue() ); } } else if (testReplacedAndGetName(_aNode,aName)&& (_aNode.getAttributes().isRemovable()) ) // we must be inside a set of values { OSL_ENSURE(!_aNode.isLocalized(), "UpdateDispatcher: Cannot add a localized value in a layer ."); sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); if (!_aNode.isNull()) { m_xUpdateHandler->addOrReplacePropertyWithValue( aName, nAttr, _aNode.getValue()); } else { m_xUpdateHandler->addOrReplaceProperty( aName, nAttr, _aNode.getValueType()); } } else // normal case: updating a single property //Inserting set { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); m_xUpdateHandler->modifyProperty( aName, nAttr, nAttrMask, _aNode.getValueType() ); if (_aNode.isLocalized() && m_aLocale.getLength()) { m_xUpdateHandler->setPropertyValueForLocale( _aNode.getValue(), m_aLocale ); } else { m_xUpdateHandler->setPropertyValue( _aNode.getValue() ); } m_xUpdateHandler->endProperty(); } return CONTINUE; } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::GroupNodeAccess const& _aNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete group"); OUString aName; if ( testReplacedAndGetName(_aNode,aName) ) { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); m_xUpdateHandler->addOrReplaceNode( aName, nAttr ); this->visitChildren(_aNode); m_xUpdateHandler->endNode(); } else { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); m_xUpdateHandler->modifyNode( aName, nAttr, nAttrMask, false ); this->visitChildren(_aNode); m_xUpdateHandler->endNode(); } return CONTINUE; } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::SetNodeAccess const& _aNode) { OSL_ENSURE( !m_bInLocalizedValues, "UpdateDispatcher: A localized value cannot be a complete set"); OUString aName; if ( testReplacedAndGetName(_aNode,aName) ) { OSL_ENSURE( !_aNode.isLocalizedValueSetNode(), "UpdateDispatcher: Cannot add a localized value in a layer." ); sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),true); m_xUpdateHandler->addOrReplaceNode( aName, nAttr ); this->visitElements(_aNode); m_xUpdateHandler->endNode(); } else { sal_Int16 nAttr = getUpdateAttributes(_aNode.getAttributes(),false); sal_Int16 nAttrMask = getUpdateAttributeMask(_aNode.getAttributes()); if (_aNode.isLocalizedValueSetNode()) { m_xUpdateHandler->modifyProperty( aName, nAttr, nAttrMask, uno::Type() ); m_bInLocalizedValues = true; this->visitElements(_aNode); m_bInLocalizedValues = false; m_xUpdateHandler->endProperty(); } else { m_xUpdateHandler->modifyNode( aName, nAttr, nAttrMask, false ); this->visitElements(_aNode); m_xUpdateHandler->endNode(); } } return CONTINUE; } // ----------------------------------------------------------------------------- bool UpdateDispatcher::testReplacedAndGetName(data::NodeAccess const & _aNode, OUString & _aName) { if (m_aElementName.getLength()) { OSL_ENSURE( _aNode->isFragmentRoot(), "ERROR - UpdateDispatcher: Found orphaned 'element' name for inner node"); _aName = m_aElementName; m_aElementName = OUString(); return true; } else { OSL_ENSURE(!_aNode->isFragmentRoot(), "ERROR - UpdateDispatcher: Found no 'element' name for fragment root node"); _aName = _aNode.getName().toString(); return false; } } // ----------------------------------------------------------------------------- data::SetVisitor::Result UpdateDispatcher::handle(data::TreeAccessor const& _aElement) { m_aElementName = _aElement.getName().toString(); Result aRes = SetVisitor::handle(_aElement); // dispatch to root node m_aElementName = OUString(); // clear - just to be safe return aRes; } // ----------------------------------------------------------------------------- sal_Int16 UpdateDispatcher::getUpdateAttributes(node::Attributes const & _aAttributes, bool bAdded) { namespace NodeAttribute = backenduno::NodeAttribute; // no support for post-creation attribute changes yet if (!bAdded) { OSL_ENSURE( getUpdateAttributeMask(_aAttributes) == 0, "Incomplete support for attribute changes" ); return 0; } sal_Int16 nResult = 0; if (_aAttributes.isReadonly()) nResult = NodeAttribute::READONLY; if (_aAttributes.isFinalized()) nResult |= NodeAttribute::FINALIZED; if (!_aAttributes.isNullable()) nResult |= NodeAttribute::MANDATORY; return nResult; } // ----------------------------------------------------------------------------- sal_Int16 UpdateDispatcher::getUpdateAttributeMask(node::Attributes const & /*_aAttributes*/) { // no support for post-creation attribute changes yet return 0; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace backend // ------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: disposetimer.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: jb $ $Date: 2002-03-28 09:08:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include "disposetimer.hxx" #ifndef CONFIGMGR_BACKEND_CACHECONTROLLER_HXX #include "cachecontroller.hxx" #endif #ifndef CONFIGMGR_CONFIGEXCEPT_HXX_ #include "configexcept.hxx" #endif #ifndef _CONFIGMGR_TRACER_HXX_ #include "tracer.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif namespace configmgr { //========================================================================== //= //========================================================================== void OTreeDisposeScheduler::scheduleCleanup(RequestOptions const& _aOptions) { OSL_ENSURE(_aOptions.hasLocale(), "ERROR: OTreeDisposeScheduler: cannot handle complete user scheduling"); osl::MutexGuard aGuard( m_aMutex ); CFG_TRACE_INFO("Scheduling data cleanup for user '%s' with locale '%s'", OUSTRING2ASCII(_aOptions.getEntity()), OUSTRING2ASCII(_aOptions.getLocale())); CFG_TRACE_INFO_NI("- Cleanup will be started in about %d seconds", int(m_aCleanupDelay.getTimeValue().Seconds)); TimeStamp aNewTime = implGetCleanupTime(TimeStamp::getCurrentTime(), m_aCleanupDelay); OSL_ASSERT(!aNewTime.isNever()); TimeStamp aScheduleTime = implAddTask(_aOptions, aNewTime); OSL_ASSERT(aScheduleTime <= aNewTime); OSL_ASSERT(!aScheduleTime.isNever()); implStartBefore(aNewTime); } // ------------------------------------------------------------------------- static inline bool equivalentOptions(RequestOptions const& lhs, RequestOptions const& rhs) { lessRequestOptions lessThan; return ! (lessThan(lhs,rhs) || lessThan(rhs,lhs)); } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::clearTasks(RequestOptions const& _aOptions) { osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO("Cancelling all data cleanup tasks for user '%s' with locale '%s'", OUSTRING2ASCII(_aOptions.getEntity()), OUSTRING2ASCII(_aOptions.getLocale())); Agenda::iterator it = m_aAgenda.begin(); while(it != m_aAgenda.end()) { Agenda::iterator cur = it++; if (equivalentOptions(_aOptions,cur->second)) { m_aAgenda.erase(cur); CFG_TRACE_INFO_NI("- One pending task canceled"); } } } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::stopAndClearTasks() { osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO("Cancelling all data cleanup tasks, Stopping Cleanup timer"); CFG_TRACE_INFO_NI("- %d cleanup tasks were pending", int(m_aAgenda.size()) ); if (m_xTimer.isValid()) m_xTimer->dispose(); // just to be sure m_aAgenda.clear(); } // ------------------------------------------------------------------------- OTreeDisposeScheduler::Task OTreeDisposeScheduler::getTask(TimeStamp const& _aActualTime, TimeStamp& _rNextTime) { OSL_ASSERT( _rNextTime.isNever() ); // internal contract, we set this only in the positive case osl::MutexGuard aOwnGuard( m_aMutex ); Task aTask( false, RequestOptions() ); if (!m_aAgenda.empty()) { Agenda::iterator const it = m_aAgenda.begin(); if (it->first <= _aActualTime) { aTask = std::make_pair(true,it->second); m_aAgenda.erase(it); } } if (!m_aAgenda.empty()) { Agenda::iterator const it = m_aAgenda.begin(); _rNextTime = it->first; } return aTask; } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::Timer::onShot() { osl::MutexGuard aGuard(m_aMutex); if (pParent) pParent->onTimerShot(); } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::onTimerShot() { CFG_TRACE_INFO("Cleanup Timer invoked - executing dispose task"); TimeStamp aActualTime = TimeStamp::getCurrentTime(); TimeStamp aNextTime = implGetCleanupTime(aActualTime, getCleanupInterval()); try { TimeStamp aNextDisposeTime = runDisposer(aActualTime); if (aNextTime < aNextDisposeTime) aNextTime = aNextDisposeTime; } catch (uno::Exception& ue) { OSL_ENSURE(false, "ERROR: UNO Exception left a disposer"); ue; } catch (configuration::Exception& ce) { OSL_ENSURE(false, "ERROR: configuration::Exception left a disposer"); ce; } catch (...) { OSL_ENSURE(false, "ERROR: Unknown Exception left a disposer"); } osl::MutexGuard aGuard(m_aMutex); implStartBefore(aNextTime); } // ------------------------------------------------------------------------- // this really should be a member of the TreeManager (see TreeManager::disposeOne etc.) TimeStamp OTreeDisposeScheduler::runDisposer(TimeStamp const& _aActualTime) { TimeStamp aNextTime = TimeStamp::never(); OSL_ASSERT(aNextTime.isNever()); osl::ClearableMutexGuard aGuard( m_rTreeManager.m_aCacheList.mutex() ); Task aTask = this->getTask( _aActualTime, aNextTime ); if (aTask.first) { RequestOptions & rTaskOptions = aTask.second; CFG_TRACE_INFO("Found cleanup task for user %s and locale %s", OUSTRING2ASCII(rTaskOptions.getEntity()), OUSTRING2ASCII(rTaskOptions.getLocale())); CacheManager::CacheRef aCache = m_rTreeManager.m_aCacheList.get(rTaskOptions); if (aCache.is()) { CFG_TRACE_INFO_NI("- Found matching data container (TreeInfo) - collecting data"); CacheLoadingAccess::DisposeList aDisposeList; TimeStamp aNextTaskTime = aCache->collectDisposeList(aDisposeList, _aActualTime, m_aCleanupDelay); CFG_TRACE_INFO_NI("- Found %d module trees to dispose", int(aDisposeList.size()) ); if (!aNextTaskTime.isNever()) { OSL_ENSURE( !aCache->isEmpty(), "ERROR: Empty TreeInfo returning finite dispose time"); // repost with new time osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO_NI("- Rescheduling current option set" ); aNextTime = this->implAddTask(rTaskOptions,aNextTaskTime); } else if (aCache->isEmpty())// may have been the last one - check that { // currently it is not possible to release options which are // because it is not save to delete the info if another thread is running in // a read request /* CFG_TRACE_INFO_NI("- Disposing last data for this options set => Removing TreeInfo" ); // get rid of it - see TreeManager::disposeOne std::auto_ptr<TreeInfo> pDisposeInfo(pInfo); m_rTreeManager.m_aTreeList.erase(xTaskOption); // got it out of reachability - now dispose/notify without lock aGuard.clear(); m_rTreeManager.ConfigChangeBroadcaster::disposeBroadcastHelper(pInfo->pBroadcastHelper); OSL_ENSURE(pInfo->m_aNotificationList.empty(), "WARNING: Empty TreeInfo still has notifications registered - will be leaked"); pInfo = NULL; */ } else CFG_TRACE_INFO_NI("- Currently no more cleanup tasks for this options set" ); // clear the guard and throw away the nodes aGuard.clear(); if (!aDisposeList.empty()) { CFG_TRACE_INFO_NI("- Closing %d modules", int(aDisposeList.size()) ); m_rTreeManager.closeModules(aDisposeList,rTaskOptions); } else CFG_TRACE_INFO_NI("- No modules trees to dispose"); } else CFG_TRACE_INFO_NI("- No matching data container (TreeInfo) found - task is obsolete"); } else CFG_TRACE_INFO("No eligible task found - may reschedule"); return aNextTime; } // ------------------------------------------------------------------------- static inline TimeStamp getExpirationTime( vos::OTimer const& aTimer ) { OSL_ENSURE(aTimer.isTicking(), "Timer is already expired !"); // note: order ensures that result time may be earlier, but not later TimeStamp const now ( TimeStamp::getCurrentTime() ); TimeInterval const left( aTimer.getRemainingTime() ); TimeStamp const expires = now + left; return expires; } // ------------------------------------------------------------------------- #ifdef _DEBUG static void checkTimerStarted( vos::OTimer const& aTimer, TimeStamp const& _aLimit) { const TimeInterval tolerance( vos::TTimeValue(1) ); // milliseconds if (aTimer.isTicking()) { TimeStamp const expires = getExpirationTime(aTimer); TimeStamp const limit = _aLimit + tolerance; OSL_ENSURE(expires <= limit, "Timer does not expire within expected time (tolerance 1 ms) !"); // OSL_ENSURE(expires <= _aLimit, "Timer does not expire within expected time !"); OSL_ENSURE(aTimer.isTicking(), "Timer just started already expired ?!"); } else { OSL_ENSURE(false, "Timer just started is not ticking ?!"); } } #endif // ------------------------------------------------------------------------- // should be called guarded only void OTreeDisposeScheduler::implStartBefore(TimeStamp const& _aTime) { // check if we were cleared if (!m_aAgenda.empty() && !_aTime.isNever()) { if (!m_xTimer->isTicking() || _aTime < getExpirationTime(*m_xTimer)) { m_xTimer->setAbsoluteTime(_aTime.getTimeValue()); if (!m_xTimer->isTicking()) m_xTimer->start(); OSL_DEBUG_ONLY( checkTimerStarted(*m_xTimer,_aTime) ); } CFG_TRACE_INFO_NI("- Cleanup timer running - next execution in %d seconds", int (m_xTimer->getRemainingTime().Seconds) ); CFG_TRACE_INFO_NI("- %d cleanup tasks are pending", int(m_aAgenda.size()) ); } else { m_xTimer->stop(); CFG_TRACE_INFO_NI("- Stopped timer - no more open cleanup tasks"); } } // ------------------------------------------------------------------------- // should be called guarded only (m_aMutex must be locked) TimeStamp OTreeDisposeScheduler::implAddTask(RequestOptions const& _aOptions, TimeStamp const& _aTime) { typedef Agenda::value_type Task; // try to insert after euivalent entries (but STL may ignore the hint) Agenda::iterator where = m_aAgenda.upper_bound(_aTime); m_aAgenda.insert(where, Task(_aTime,_aOptions)); OSL_ASSERT(!m_aAgenda.empty()); return m_aAgenda.begin()->first; } // ------------------------------------------------------------------------- } // namespace <commit_msg>INTEGRATION: CWS dbgmacros1 (1.17.40); FILE MERGED 2003/04/09 10:21:07 kso 1.17.40.1: #108413# - debug macro unification.<commit_after>/************************************************************************* * * $RCSfile: disposetimer.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:18:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include "disposetimer.hxx" #ifndef CONFIGMGR_BACKEND_CACHECONTROLLER_HXX #include "cachecontroller.hxx" #endif #ifndef CONFIGMGR_CONFIGEXCEPT_HXX_ #include "configexcept.hxx" #endif #ifndef _CONFIGMGR_TRACER_HXX_ #include "tracer.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif namespace configmgr { //========================================================================== //= //========================================================================== void OTreeDisposeScheduler::scheduleCleanup(RequestOptions const& _aOptions) { OSL_ENSURE(_aOptions.hasLocale(), "ERROR: OTreeDisposeScheduler: cannot handle complete user scheduling"); osl::MutexGuard aGuard( m_aMutex ); CFG_TRACE_INFO("Scheduling data cleanup for user '%s' with locale '%s'", OUSTRING2ASCII(_aOptions.getEntity()), OUSTRING2ASCII(_aOptions.getLocale())); CFG_TRACE_INFO_NI("- Cleanup will be started in about %d seconds", int(m_aCleanupDelay.getTimeValue().Seconds)); TimeStamp aNewTime = implGetCleanupTime(TimeStamp::getCurrentTime(), m_aCleanupDelay); OSL_ASSERT(!aNewTime.isNever()); TimeStamp aScheduleTime = implAddTask(_aOptions, aNewTime); OSL_ASSERT(aScheduleTime <= aNewTime); OSL_ASSERT(!aScheduleTime.isNever()); implStartBefore(aNewTime); } // ------------------------------------------------------------------------- static inline bool equivalentOptions(RequestOptions const& lhs, RequestOptions const& rhs) { lessRequestOptions lessThan; return ! (lessThan(lhs,rhs) || lessThan(rhs,lhs)); } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::clearTasks(RequestOptions const& _aOptions) { osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO("Cancelling all data cleanup tasks for user '%s' with locale '%s'", OUSTRING2ASCII(_aOptions.getEntity()), OUSTRING2ASCII(_aOptions.getLocale())); Agenda::iterator it = m_aAgenda.begin(); while(it != m_aAgenda.end()) { Agenda::iterator cur = it++; if (equivalentOptions(_aOptions,cur->second)) { m_aAgenda.erase(cur); CFG_TRACE_INFO_NI("- One pending task canceled"); } } } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::stopAndClearTasks() { osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO("Cancelling all data cleanup tasks, Stopping Cleanup timer"); CFG_TRACE_INFO_NI("- %d cleanup tasks were pending", int(m_aAgenda.size()) ); if (m_xTimer.isValid()) m_xTimer->dispose(); // just to be sure m_aAgenda.clear(); } // ------------------------------------------------------------------------- OTreeDisposeScheduler::Task OTreeDisposeScheduler::getTask(TimeStamp const& _aActualTime, TimeStamp& _rNextTime) { OSL_ASSERT( _rNextTime.isNever() ); // internal contract, we set this only in the positive case osl::MutexGuard aOwnGuard( m_aMutex ); Task aTask( false, RequestOptions() ); if (!m_aAgenda.empty()) { Agenda::iterator const it = m_aAgenda.begin(); if (it->first <= _aActualTime) { aTask = std::make_pair(true,it->second); m_aAgenda.erase(it); } } if (!m_aAgenda.empty()) { Agenda::iterator const it = m_aAgenda.begin(); _rNextTime = it->first; } return aTask; } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::Timer::onShot() { osl::MutexGuard aGuard(m_aMutex); if (pParent) pParent->onTimerShot(); } // ------------------------------------------------------------------------- void OTreeDisposeScheduler::onTimerShot() { CFG_TRACE_INFO("Cleanup Timer invoked - executing dispose task"); TimeStamp aActualTime = TimeStamp::getCurrentTime(); TimeStamp aNextTime = implGetCleanupTime(aActualTime, getCleanupInterval()); try { TimeStamp aNextDisposeTime = runDisposer(aActualTime); if (aNextTime < aNextDisposeTime) aNextTime = aNextDisposeTime; } catch (uno::Exception& ue) { OSL_ENSURE(false, "ERROR: UNO Exception left a disposer"); ue; } catch (configuration::Exception& ce) { OSL_ENSURE(false, "ERROR: configuration::Exception left a disposer"); ce; } catch (...) { OSL_ENSURE(false, "ERROR: Unknown Exception left a disposer"); } osl::MutexGuard aGuard(m_aMutex); implStartBefore(aNextTime); } // ------------------------------------------------------------------------- // this really should be a member of the TreeManager (see TreeManager::disposeOne etc.) TimeStamp OTreeDisposeScheduler::runDisposer(TimeStamp const& _aActualTime) { TimeStamp aNextTime = TimeStamp::never(); OSL_ASSERT(aNextTime.isNever()); osl::ClearableMutexGuard aGuard( m_rTreeManager.m_aCacheList.mutex() ); Task aTask = this->getTask( _aActualTime, aNextTime ); if (aTask.first) { RequestOptions & rTaskOptions = aTask.second; CFG_TRACE_INFO("Found cleanup task for user %s and locale %s", OUSTRING2ASCII(rTaskOptions.getEntity()), OUSTRING2ASCII(rTaskOptions.getLocale())); CacheManager::CacheRef aCache = m_rTreeManager.m_aCacheList.get(rTaskOptions); if (aCache.is()) { CFG_TRACE_INFO_NI("- Found matching data container (TreeInfo) - collecting data"); CacheLoadingAccess::DisposeList aDisposeList; TimeStamp aNextTaskTime = aCache->collectDisposeList(aDisposeList, _aActualTime, m_aCleanupDelay); CFG_TRACE_INFO_NI("- Found %d module trees to dispose", int(aDisposeList.size()) ); if (!aNextTaskTime.isNever()) { OSL_ENSURE( !aCache->isEmpty(), "ERROR: Empty TreeInfo returning finite dispose time"); // repost with new time osl::MutexGuard aOwnGuard( m_aMutex ); CFG_TRACE_INFO_NI("- Rescheduling current option set" ); aNextTime = this->implAddTask(rTaskOptions,aNextTaskTime); } else if (aCache->isEmpty())// may have been the last one - check that { // currently it is not possible to release options which are // because it is not save to delete the info if another thread is running in // a read request /* CFG_TRACE_INFO_NI("- Disposing last data for this options set => Removing TreeInfo" ); // get rid of it - see TreeManager::disposeOne std::auto_ptr<TreeInfo> pDisposeInfo(pInfo); m_rTreeManager.m_aTreeList.erase(xTaskOption); // got it out of reachability - now dispose/notify without lock aGuard.clear(); m_rTreeManager.ConfigChangeBroadcaster::disposeBroadcastHelper(pInfo->pBroadcastHelper); OSL_ENSURE(pInfo->m_aNotificationList.empty(), "WARNING: Empty TreeInfo still has notifications registered - will be leaked"); pInfo = NULL; */ } else CFG_TRACE_INFO_NI("- Currently no more cleanup tasks for this options set" ); // clear the guard and throw away the nodes aGuard.clear(); if (!aDisposeList.empty()) { CFG_TRACE_INFO_NI("- Closing %d modules", int(aDisposeList.size()) ); m_rTreeManager.closeModules(aDisposeList,rTaskOptions); } else CFG_TRACE_INFO_NI("- No modules trees to dispose"); } else CFG_TRACE_INFO_NI("- No matching data container (TreeInfo) found - task is obsolete"); } else CFG_TRACE_INFO("No eligible task found - may reschedule"); return aNextTime; } // ------------------------------------------------------------------------- static inline TimeStamp getExpirationTime( vos::OTimer const& aTimer ) { OSL_ENSURE(aTimer.isTicking(), "Timer is already expired !"); // note: order ensures that result time may be earlier, but not later TimeStamp const now ( TimeStamp::getCurrentTime() ); TimeInterval const left( aTimer.getRemainingTime() ); TimeStamp const expires = now + left; return expires; } // ------------------------------------------------------------------------- #if OSL_DEBUG_LEVEL > 0 static void checkTimerStarted( vos::OTimer const& aTimer, TimeStamp const& _aLimit) { const TimeInterval tolerance( vos::TTimeValue(1) ); // milliseconds if (aTimer.isTicking()) { TimeStamp const expires = getExpirationTime(aTimer); TimeStamp const limit = _aLimit + tolerance; OSL_ENSURE(expires <= limit, "Timer does not expire within expected time (tolerance 1 ms) !"); // OSL_ENSURE(expires <= _aLimit, "Timer does not expire within expected time !"); OSL_ENSURE(aTimer.isTicking(), "Timer just started already expired ?!"); } else { OSL_ENSURE(false, "Timer just started is not ticking ?!"); } } #endif // ------------------------------------------------------------------------- // should be called guarded only void OTreeDisposeScheduler::implStartBefore(TimeStamp const& _aTime) { // check if we were cleared if (!m_aAgenda.empty() && !_aTime.isNever()) { if (!m_xTimer->isTicking() || _aTime < getExpirationTime(*m_xTimer)) { m_xTimer->setAbsoluteTime(_aTime.getTimeValue()); if (!m_xTimer->isTicking()) m_xTimer->start(); OSL_DEBUG_ONLY( checkTimerStarted(*m_xTimer,_aTime) ); } CFG_TRACE_INFO_NI("- Cleanup timer running - next execution in %d seconds", int (m_xTimer->getRemainingTime().Seconds) ); CFG_TRACE_INFO_NI("- %d cleanup tasks are pending", int(m_aAgenda.size()) ); } else { m_xTimer->stop(); CFG_TRACE_INFO_NI("- Stopped timer - no more open cleanup tasks"); } } // ------------------------------------------------------------------------- // should be called guarded only (m_aMutex must be locked) TimeStamp OTreeDisposeScheduler::implAddTask(RequestOptions const& _aOptions, TimeStamp const& _aTime) { typedef Agenda::value_type Task; // try to insert after euivalent entries (but STL may ignore the hint) Agenda::iterator where = m_aAgenda.upper_bound(_aTime); m_aAgenda.insert(where, Task(_aTime,_aOptions)); OSL_ASSERT(!m_aAgenda.empty()); return m_aAgenda.begin()->first; } // ------------------------------------------------------------------------- } // namespace <|endoftext|>
<commit_before>#include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include <functional> #define __STDC_LIMIT_MACROS #include <stdint.h> #define LOG_AT_W /* warning only */ extern "C" { #include "stinger_core/xmalloc.h" #include "stinger_core/stinger_error.h" } #include "rapidjson/document.h" #include "rapidjson/rapidjson.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "json_rpc_server.h" #include "json_rpc.h" #include "rpc_state.h" #include "mon_handling.h" #include "session_handling.h" #include "mongoose/mongoose.h" using namespace gt::stinger; #define MAX_REQUEST_SIZE (1ULL << 22ULL) static int begin_request_handler(struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); LOG_D_A("Receiving request for %s", request_info->uri); if (strncmp(request_info->uri, "/data/", 6)==0) { return 0; } if (strncmp(request_info->uri, "/jsonrpc", 8)==0) { uint8_t * storage = (uint8_t *) xcalloc (1, MAX_REQUEST_SIZE); int64_t read = mg_read(conn, storage, MAX_REQUEST_SIZE); if (read > MAX_REQUEST_SIZE-2) { LOG_E_A("Request was too large: %ld", read); return -1; } storage[read] = '\0'; LOG_D_A("Parsing request:\n%.*s", read, storage); rapidjson::Document input, output; input.Parse<0>((char *)storage); json_rpc_process_request(input, output); rapidjson::StringBuffer out_buf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(out_buf); output.Accept(writer); const char * out_ch = out_buf.GetString(); int out_len = out_buf.Size(); LOG_D_A("RapidJSON parsed :%d\n%s", out_len, out_ch); int code = mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" // Always set Content-Length "Access-Control-Allow-Origin: *\r\n" "\r\n" "%s", out_len, out_ch); LOG_D_A("Code was %d", code); free(storage); return 1; } return 0; } int main (int argc, char ** argv) { int unleash_daemon = 0; int opt = 0; while(-1 != (opt = getopt(argc, argv, "h?d"))) { switch(opt) { default: { LOG_E_A("Unknwon option %c", opt); } /* no break */ case '?': case 'h': { printf("Usage: %s [-d]\n", argv[0]); printf("-d\tdaemon mode\n"); exit(-1); } break; case 'd': { unleash_daemon = 1; } break; } } JSON_RPCServerState & server_state = JSON_RPCServerState::get_server_state(); server_state.add_rpc_function("get_algorithms", new JSON_RPC_get_algorithms(&server_state)); server_state.add_rpc_function("get_data_description", new JSON_RPC_get_data_description(&server_state)); server_state.add_rpc_function("get_data_array_range", new JSON_RPC_get_data_array_range(&server_state)); server_state.add_rpc_function("get_data_array_sorted_range", new JSON_RPC_get_data_array_sorted_range(&server_state)); server_state.add_rpc_function("get_data_array", new JSON_RPC_get_data_array(&server_state)); server_state.add_rpc_function("get_data_array_set", new JSON_RPC_get_data_array_set(&server_state)); server_state.add_rpc_function("get_graph_stats", new JSON_RPC_get_graph_stats(&server_state)); server_state.add_rpc_function("label_breadth_first_search", new JSON_RPC_label_breadth_first_search(&server_state)); server_state.add_rpc_function("breadth_first_search", new JSON_RPC_breadth_first_search(&server_state)); server_state.add_rpc_function("register", new JSON_RPC_register(&server_state)); server_state.add_rpc_function("request", new JSON_RPC_request(&server_state)); server_state.add_rpc_function("get_data_array_reduction", new JSON_RPC_get_data_array_reduction(&server_state)); server_state.add_rpc_session("subgraph", new JSON_RPC_community_subgraph(0, &server_state)); server_state.add_rpc_session("vertex_event_notifier", new JSON_RPC_vertex_event_notifier(0, &server_state)); server_state.add_rpc_session("get_latlon", new JSON_RPC_get_latlon(0, &server_state)); server_state.add_rpc_session("get_latlon_gnip", new JSON_RPC_get_latlon_gnip(0, &server_state)); mon_connect(10103, "localhost", "json_rpc"); /* Mongoose setup and start */ struct mg_context *ctx; struct mg_callbacks callbacks; // List of options. Last element must be NULL. const char *opts[] = {"listening_ports", "8088", "document_root", "data", NULL}; // Prepare callbacks structure. We have only one callback, the rest are NULL. memset(&callbacks, 0, sizeof(callbacks)); callbacks.begin_request = begin_request_handler; // Start the web server. ctx = mg_start(&callbacks, NULL, opts); /* infinite loop */ if(unleash_daemon) { while(1) { sleep(10); } } else { printf("Press <q> to shut down the server...\n"); while (getchar() != 'q'); } return 0; } <commit_msg>Changing JSON-RPC Server to use TCLAP for commandline arguments.<commit_after>#include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include <functional> #define __STDC_LIMIT_MACROS #include <stdint.h> #include <tclap/CmdLine.h> #define LOG_AT_W /* warning only */ extern "C" { #include "stinger_core/xmalloc.h" #include "stinger_core/stinger_error.h" } #include "rapidjson/document.h" #include "rapidjson/rapidjson.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "json_rpc_server.h" #include "json_rpc.h" #include "rpc_state.h" #include "mon_handling.h" #include "session_handling.h" #include "mongoose/mongoose.h" using namespace gt::stinger; #define MAX_REQUEST_SIZE (1ULL << 22ULL) static int begin_request_handler(struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); LOG_D_A("Receiving request for %s", request_info->uri); if (strncmp(request_info->uri, "/data/", 6)==0) { return 0; } if (strncmp(request_info->uri, "/jsonrpc", 8)==0) { uint8_t * storage = (uint8_t *) xcalloc (1, MAX_REQUEST_SIZE); int64_t read = mg_read(conn, storage, MAX_REQUEST_SIZE); if (read > MAX_REQUEST_SIZE-2) { LOG_E_A("Request was too large: %ld", read); return -1; } storage[read] = '\0'; LOG_D_A("Parsing request:\n%.*s", read, storage); rapidjson::Document input, output; input.Parse<0>((char *)storage); json_rpc_process_request(input, output); rapidjson::StringBuffer out_buf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(out_buf); output.Accept(writer); const char * out_ch = out_buf.GetString(); int out_len = out_buf.Size(); LOG_D_A("RapidJSON parsed :%d\n%s", out_len, out_ch); int code = mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" // Always set Content-Length "Access-Control-Allow-Origin: *\r\n" "\r\n" "%s", out_len, out_ch); LOG_D_A("Code was %d", code); free(storage); return 1; } return 0; } int main (int argc, char ** argv) { bool unleash_daemon = false; try { /* parse command line configuration */ TCLAP::CmdLine cmd("JSON-RPC Server", ' ', "2.0"); TCLAP::SwitchArg daemonSwitch ("d", "daemon", "Daemon mode", cmd, false); cmd.parse (argc, argv); unleash_daemon = daemonSwitch.getValue(); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 0; } JSON_RPCServerState & server_state = JSON_RPCServerState::get_server_state(); server_state.add_rpc_function("get_algorithms", new JSON_RPC_get_algorithms(&server_state)); server_state.add_rpc_function("get_data_description", new JSON_RPC_get_data_description(&server_state)); server_state.add_rpc_function("get_data_array_range", new JSON_RPC_get_data_array_range(&server_state)); server_state.add_rpc_function("get_data_array_sorted_range", new JSON_RPC_get_data_array_sorted_range(&server_state)); server_state.add_rpc_function("get_data_array", new JSON_RPC_get_data_array(&server_state)); server_state.add_rpc_function("get_data_array_set", new JSON_RPC_get_data_array_set(&server_state)); server_state.add_rpc_function("get_graph_stats", new JSON_RPC_get_graph_stats(&server_state)); server_state.add_rpc_function("label_breadth_first_search", new JSON_RPC_label_breadth_first_search(&server_state)); server_state.add_rpc_function("breadth_first_search", new JSON_RPC_breadth_first_search(&server_state)); server_state.add_rpc_function("register", new JSON_RPC_register(&server_state)); server_state.add_rpc_function("request", new JSON_RPC_request(&server_state)); server_state.add_rpc_function("get_data_array_reduction", new JSON_RPC_get_data_array_reduction(&server_state)); server_state.add_rpc_session("subgraph", new JSON_RPC_community_subgraph(0, &server_state)); server_state.add_rpc_session("vertex_event_notifier", new JSON_RPC_vertex_event_notifier(0, &server_state)); server_state.add_rpc_session("get_latlon", new JSON_RPC_get_latlon(0, &server_state)); server_state.add_rpc_session("get_latlon_gnip", new JSON_RPC_get_latlon_gnip(0, &server_state)); mon_connect(10103, "localhost", "json_rpc"); /* Mongoose setup and start */ struct mg_context *ctx; struct mg_callbacks callbacks; // List of options. Last element must be NULL. const char *opts[] = {"listening_ports", "8088", "document_root", "data", NULL}; // Prepare callbacks structure. We have only one callback, the rest are NULL. memset(&callbacks, 0, sizeof(callbacks)); callbacks.begin_request = begin_request_handler; // Start the web server. ctx = mg_start(&callbacks, NULL, opts); /* infinite loop */ if(unleash_daemon) { while(1) { sleep(10); } } else { printf("Press <q> to shut down the server...\n"); while (getchar() != 'q'); } return 0; } <|endoftext|>
<commit_before>#ifndef INCLUDED_SROOK_IOS_BIFSTREAM_HPP #define INCLUDED_SROOK_IOS_BIFSTREAM_HPP #include<srook/config/noexcept_detection.hpp> #include<srook/cstddef/byte.hpp> #include<srook/config/require.hpp> #include<srook/type_traits/is_callable.hpp> #include<srook/type_traits/has_iterator.hpp> #include<srook/optional.hpp> #include<fstream> #include<type_traits> #include<array> #include<memory> #include<algorithm> namespace srook{ inline namespace v1{ struct bifstream final : std::ifstream { using std::ifstream::ifstream; explicit bifstream(const char* filename,const std::ios_base::openmode& open_mode = std::ios::in | std::ios::binary) :std::ifstream{}, buffer{}, last(nullptr), forward_iter(nullptr) { try{ exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); open(filename,open_mode); seekg(0,std::fstream::end); const std::size_t end_pos = std::size_t(tellg()); clear(); seekg(0,std::fstream::beg); const std::size_t begin_pos = std::size_t(tellg()); const std::size_t size = end_pos - begin_pos; buffer = std::make_unique<srook::byte[]>(size); exceptions(std::ios::badbit); read(reinterpret_cast<char*>(buffer.get()),long(size)); close(); forward_iter = buffer.get(); last = std::next(buffer.get(),size); }catch(const std::ios_base::failure& e){ buffer.reset(); nextflag = readflag = false; last = forward_iter = nullptr; bit_position = srook::nullopt; } } void skip_byte(std::size_t n) { if(forward_iter + n > last)throw std::out_of_range(__func__); if((forward_iter += n) >= last)readflag = false; bit_position = 7; } explicit operator bool()const noexcept { return readflag; } std::size_t size()const noexcept { return last - buffer.get(); } srook::byte* next_address()const noexcept { if(!bit_position)return nullptr; else if(bit_position.value() == 7)return forward_iter; else if(forward_iter < last)return forward_iter + 1; else return nullptr; } private: struct tag_argument{ explicit constexpr tag_argument(int num):n(std::move(num)){} int n; }; public: static constexpr auto Byte = []{}; static constexpr auto Word = []{}; static constexpr auto Bytes = []{}; struct Byte_n : tag_argument{ using tag_argument::tag_argument; }; struct Bits : tag_argument{ using tag_argument::tag_argument; }; private: std::unique_ptr<srook::byte[]> buffer; srook::byte* last; srook::byte* forward_iter; srook::optional<int> bit_position = 7u; const std::array<int,8> bit_fullmask {{ 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80 }}; bool nextflag = true; bool readflag = true; private: void increment_buffer()noexcept { if(++forward_iter >= last)readflag = false; } template<class T,std::size_t v> friend std::pair<const decltype(Bytes)&,bifstream&> operator>>(std::pair<const decltype(Bytes)&,bifstream&> p,const std::array<T,v>& ar)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } if(this_.forward_iter + ar.size() > this_.last)throw std::out_of_range(__func__); std::copy(this_.forward_iter,this_.forward_iter + ar.size(),std::begin(ar)); if((this_.forward_iter += ar.size()) >= this_.last)this_.readflag = false; return p; } template<class Value,REQUIRES(!srook::is_callable_v<std::decay_t<Value>> and !srook::has_iterator_v<std::decay_t<Value>>)> friend std::pair<const decltype(Byte)&,bifstream&> operator>>(std::pair<const decltype(Byte)&,bifstream&> p,Value& src)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.readflag){ if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } src = Value(*this_.forward_iter); this_.increment_buffer(); this_.nextflag = true; }else{ throw std::runtime_error(__func__); } return p; } template<class T,REQUIRES(std::is_integral<std::decay_t<T>>::value)> friend std::pair<const decltype(Word)&,bifstream&> operator>>(std::pair<const decltype(Word)&,bifstream&> p,T& value)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.readflag){ if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } value = srook::to_integer<T>(*this_.forward_iter) << 8; this_.increment_buffer(); value |= srook::to_integer<T>(*this_.forward_iter); this_.increment_buffer(); }else{ throw std::runtime_error(__func__); } return p; } template<class T,REQUIRES(std::is_integral<std::decay_t<std::decay_t<T>>>::value)> friend std::pair<Bits,bifstream&> operator>>(std::pair<Bits,bifstream&> p,T& value)noexcept(false) { if(p.first.n <= 0)throw std::invalid_argument(__func__); bifstream& this_ = p.second; if(!this_.bit_position) throw std::runtime_error("invalid construct"); int r = 0; for(srook::byte c{}; p.first.n; --p.first.n){ if(this_.bit_position.value() < 0){ this_.bit_position = 7; this_.increment_buffer(); if(!this_.nextflag){ this_.increment_buffer(); this_.nextflag = true; } c = *this_.forward_iter; if(srook::to_integer<std::underlying_type_t<srook::byte>>(c) == 0xff){ c = *(this_.forward_iter + 1); if(srook::to_integer<bool>(c)){ throw std::runtime_error(__func__); } this_.nextflag = false; } } r <<= 1; r |= (srook::to_integer<int>(*this_.forward_iter) & this_.bit_fullmask[std::size_t(this_.bit_position.value())]) ? 1 : 0; this_.bit_position = this_.bit_position.value() - 1; } value = T(r); return p; } template<class Range,REQUIRES(srook::has_iterator_v<std::decay_t<Range>>)> friend std::pair<const Byte_n&,bifstream&> operator>>(std::pair<const Byte_n&,bifstream&> p,Range& r)noexcept(false) { bifstream& this_ = p.second; if(this_.bit_position != 7){ this_.increment_buffer(); this_.bit_position = 7; } if(this_.forward_iter + p.first.n > this_.last)throw std::out_of_range(__func__); if(r.size() >= std::size_t(p.first.n)){ std::generate(std::begin(r),std::end(r),[&this_]{return typename Range::value_type(*this_.forward_iter++);}); }else{ r.resize(std::size_t(p.first.n)); std::generate(std::begin(r),std::end(r),[&this_]{return typename Range::value_type(*this_.forward_iter++);}); } if(this_.forward_iter >= this_.last)this_.readflag = false; return p; } template<class Tag> constexpr friend std::pair<Tag,bifstream&> operator|(bifstream& ofps,const Tag& t) SROOK_NOEXCEPT(std::make_pair(t,std::ref(ofps))) { static_assert( std::is_same_v<Tag,Byte_n> or std::is_same_v<Tag,std::decay_t<decltype(Byte)>> or std::is_same_v<Tag,std::decay_t<decltype(Bytes)>> or std::is_same_v<Tag,std::decay_t<decltype(Word)>> or "Invalid tag" ); return std::make_pair(t,std::ref(ofps)); } friend std::pair<Bits,bifstream&> operator|(bifstream& ofps,const Bits& bits) SROOK_NOEXCEPT(std::make_pair(bits,std::ref(ofps))) { return std::make_pair(bits,std::ref(ofps)); } }; } // inline namespace v1 } // namespace srook #endif <commit_msg>fix bifstream<commit_after>#ifndef INCLUDED_SROOK_IOS_BIFSTREAM_HPP #define INCLUDED_SROOK_IOS_BIFSTREAM_HPP #include<srook/config/noexcept_detection.hpp> #include<srook/cstddef/byte.hpp> #include<srook/config/require.hpp> #include<srook/type_traits/is_callable.hpp> #include<srook/type_traits/has_iterator.hpp> #include<srook/optional.hpp> #include<fstream> #include<type_traits> #include<array> #include<memory> #include<algorithm> namespace srook{ inline namespace v1{ struct bifstream final : std::ifstream { using std::ifstream::ifstream; explicit bifstream(const char* filename,const std::ios_base::openmode& open_mode = std::ios::in | std::ios::binary) :std::ifstream{}, buffer{}, last(nullptr), forward_iter(nullptr) { try{ exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); open(filename,open_mode); seekg(0,std::fstream::end); const std::size_t end_pos = std::size_t(tellg()); clear(); seekg(0,std::fstream::beg); const std::size_t begin_pos = std::size_t(tellg()); const std::size_t size = end_pos - begin_pos; buffer = std::make_unique<srook::byte[]>(size); exceptions(std::ios::badbit); read(reinterpret_cast<char*>(buffer.get()),long(size)); close(); forward_iter = buffer.get(); last = std::next(buffer.get(),size); }catch(const std::ios_base::failure& e){ buffer.reset(); nextflag = readflag = false; last = forward_iter = nullptr; bit_position = srook::nullopt; } } void skip_byte(std::size_t n) { if(forward_iter + n > last)throw std::out_of_range(__func__); if((forward_iter += n) >= last)readflag = false; bit_position = 7; } explicit operator bool()const noexcept { return readflag; } std::size_t size()const noexcept { return last - buffer.get(); } srook::byte* next_address()const noexcept { if(bit_position == 7){ return forward_iter; }else if(forward_iter < last){ return forward_iter + 1; }else{ return nullptr; } } private: struct tag_argument{ explicit constexpr tag_argument(int num):n(std::move(num)){} int n; }; public: static constexpr auto Byte = []{}; static constexpr auto Word = []{}; static constexpr auto Bytes = []{}; struct Byte_n : tag_argument{ using tag_argument::tag_argument; }; struct Bits : tag_argument{ using tag_argument::tag_argument; }; private: std::unique_ptr<srook::byte[]> buffer; srook::byte* last; srook::byte* forward_iter; srook::optional<int> bit_position = 7; const std::array<int,8> bit_fullmask {{ 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80 }}; bool nextflag = true; bool readflag = true; private: void increment_buffer()noexcept { if(++forward_iter >= last)readflag = false; } template<class Range,REQUIRES(srook::has_iterator_v<std::decay_t<Range>>)> friend std::pair<const decltype(Bytes)&,bifstream&> operator>>(std::pair<const decltype(Bytes)&,bifstream&> p,Range& ar)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } if(this_.forward_iter + ar.size() > this_.last)throw std::out_of_range("Bytes operator<<"); std::generate(std::begin(ar),std::end(ar),[&this_](){return typename std::decay_t<Range>::value_type(*this_.forward_iter++);}); if((this_.forward_iter) >= this_.last)this_.readflag = false; return p; } template<class Value,REQUIRES(!srook::is_callable_v<std::decay_t<Value>> and !srook::has_iterator_v<std::decay_t<Value>>)> friend std::pair<const decltype(Byte)&,bifstream&> operator>>(std::pair<const decltype(Byte)&,bifstream&> p,Value& src)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.readflag){ if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } src = Value(*this_.forward_iter); this_.increment_buffer(); this_.nextflag = true; }else{ throw std::runtime_error("Byte operator<<: cannot read"); } return p; } template<class T,REQUIRES(std::is_integral<std::decay_t<T>>::value)> friend std::pair<const decltype(Word)&,bifstream&> operator>>(std::pair<const decltype(Word)&,bifstream&> p,T& value)noexcept(false) { bifstream& this_ = p.second; if(!this_.bit_position)throw std::runtime_error("invalid construct"); if(this_.readflag){ if(this_.bit_position.value() != 7){ this_.increment_buffer(); this_.bit_position = 7; } unsigned int r = srook::to_integer<unsigned>(*this_.forward_iter) << 8; this_.increment_buffer(); r |= srook::to_integer<unsigned>(*this_.forward_iter); this_.increment_buffer(); value = T(r); }else{ throw std::runtime_error("Word operator<<: cannot read"); } return p; } template<class T,REQUIRES(std::is_integral<std::decay_t<std::decay_t<T>>>::value)> friend std::pair<Bits,bifstream&> operator>>(std::pair<Bits,bifstream&> p,T& value)noexcept(false) { if(p.first.n <= 0){ value = T(0); return p; } bifstream& this_ = p.second; if(!this_.bit_position) throw std::runtime_error("invalid construct"); int r = 0; for(srook::byte c{}; p.first.n; --p.first.n){ if(this_.bit_position.value() < 0){ this_.bit_position = 7; this_.increment_buffer(); if(!this_.nextflag){ this_.increment_buffer(); this_.nextflag = true; } c = *this_.forward_iter; if(srook::to_integer<std::underlying_type_t<srook::byte>>(c) == 0xff){ c = *(this_.forward_iter + 1); if(srook::to_integer<std::underlying_type_t<srook::byte>>(c) != 0){ value = -srook::to_integer<std::underlying_type_t<srook::byte>>(c); } this_.nextflag = false; } } r <<= 1; r |= (srook::to_integer<std::underlying_type_t<srook::byte>>(*this_.forward_iter) & this_.bit_fullmask[std::size_t(this_.bit_position.value())]) ? 1 : 0; this_.bit_position = this_.bit_position.value() - 1; } value = T(r); return p; } template<class Range,REQUIRES(srook::has_iterator_v<std::decay_t<Range>>)> friend std::pair<const Byte_n&,bifstream&> operator>>(std::pair<const Byte_n&,bifstream&> p,Range& r)noexcept(false) { bifstream& this_ = p.second; if(this_.bit_position != 7){ this_.increment_buffer(); this_.bit_position = 7; } if(this_.forward_iter + p.first.n > this_.last)throw std::out_of_range("Byte_n operator>> out of range"); if(r.size() >= std::size_t(p.first.n)){ std::generate(std::begin(r),std::end(r),[&this_]{return typename Range::value_type(*this_.forward_iter++);}); }else{ r.resize(std::size_t(p.first.n)); std::generate(std::begin(r),std::end(r),[&this_]{return typename Range::value_type(*this_.forward_iter++);}); } if(this_.forward_iter >= this_.last)this_.readflag = false; return p; } template<class Tag> constexpr friend std::pair<Tag,bifstream&> operator|(bifstream& ofps,const Tag& t) SROOK_NOEXCEPT(std::make_pair(t,std::ref(ofps))) { static_assert( std::is_same_v<Tag,Byte_n> or std::is_same_v<Tag,std::decay_t<decltype(Byte)>> or std::is_same_v<Tag,std::decay_t<decltype(Bytes)>> or std::is_same_v<Tag,std::decay_t<decltype(Word)>> or "Invalid tag" ); return std::make_pair(t,std::ref(ofps)); } friend std::pair<Bits,bifstream&> operator|(bifstream& ofps,const Bits& bits) SROOK_NOEXCEPT(std::make_pair(bits,std::ref(ofps))) { return std::make_pair(bits,std::ref(ofps)); } }; } // inline namespace v1 } // namespace srook #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AConnection.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2004-03-02 12:35:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #define _CONNECTIVITY_ADO_ACONNECTION_HXX_ #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_ #include "OSubComponent.hxx" #endif #include <map> #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _CONNECTIVITY_OTYPEINFO_HXX_ #include "OTypeInfo.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #include "ado/Awrapado.hxx" namespace connectivity { namespace ado { struct OExtendedTypeInfo { ::connectivity::OTypeInfo aSimpleType; // the general type info inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; } }; class WpADOConnection; class ODriver; class OCatalog; typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*> OTypeInfoMap; typedef connectivity::OMetaConnection OConnection_BASE; class OConnection : public OConnection_BASE, public connectivity::OSubComponent<OConnection, OConnection_BASE> { friend class connectivity::OSubComponent<OConnection, OConnection_BASE>; protected: //==================================================================== // Data attributes //==================================================================== OTypeInfoMap m_aTypeInfo; // vector containing an entry // for each row returned by // DatabaseMetaData.getTypeInfo. ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData; connectivity::OWeakRefArray m_aStatements; // vector containing a list // of all the Statement objects // for this Connection ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog; ODriver* m_pDriver; private: WpADOConnection* m_pAdoConnection; OCatalog* m_pCatalog; sal_Int32 m_nEngineType; sal_Bool m_bClosed; sal_Bool m_bAutocommit; protected: void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException); public: OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info, ODriver* _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // OConnection(const SQLHANDLE _pConnectionHandle); ~OConnection(); void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info); void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId(); // XServiceInfo DECLARE_SERVICE_INFO(); // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException); // XConnection virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XWarningsSupplier virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // WpADOConnection* getConnection() { return m_pAdoConnection; } void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; } void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; } const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;} OCatalog* getAdoCatalog() const { if ( m_xCatalog.get().is() ) return m_pCatalog; return NULL; } sal_Int32 getEngineType() const { return m_nEngineType; } ODriver* getDriver() const { return m_pDriver; } static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo, DataTypeEnum _nType, const ::rtl::OUString& _sTypeName, sal_Int32 _nPrecision, sal_Int32 _nScale, sal_Bool& _brForceToType); }; } } #endif // _CONNECTIVITY_ADO_ACONNECTION_HXX_ <commit_msg>INTEGRATION: CWS insight01 (1.13.26); FILE MERGED 2004/06/01 13:27:56 oj 1.13.26.1: merge<commit_after>/************************************************************************* * * $RCSfile: AConnection.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2004-08-02 17:11:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #define _CONNECTIVITY_ADO_ACONNECTION_HXX_ #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_ #include "OSubComponent.hxx" #endif #include <map> #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _CONNECTIVITY_OTYPEINFO_HXX_ #include "OTypeInfo.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #include "ado/Awrapado.hxx" namespace connectivity { namespace ado { struct OExtendedTypeInfo { ::connectivity::OTypeInfo aSimpleType; // the general type info DataTypeEnum eType; inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; } }; class WpADOConnection; class ODriver; class OCatalog; typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*> OTypeInfoMap; typedef connectivity::OMetaConnection OConnection_BASE; class OConnection : public OConnection_BASE, public connectivity::OSubComponent<OConnection, OConnection_BASE> { friend class connectivity::OSubComponent<OConnection, OConnection_BASE>; protected: //==================================================================== // Data attributes //==================================================================== OTypeInfoMap m_aTypeInfo; // vector containing an entry // for each row returned by // DatabaseMetaData.getTypeInfo. ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData; connectivity::OWeakRefArray m_aStatements; // vector containing a list // of all the Statement objects // for this Connection ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog; ODriver* m_pDriver; private: WpADOConnection* m_pAdoConnection; OCatalog* m_pCatalog; sal_Int32 m_nEngineType; sal_Bool m_bClosed; sal_Bool m_bAutocommit; protected: void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException); public: OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info, ODriver* _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // OConnection(const SQLHANDLE _pConnectionHandle); ~OConnection(); void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info); void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId(); // XServiceInfo DECLARE_SERVICE_INFO(); // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException); // XConnection virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XWarningsSupplier virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // WpADOConnection* getConnection() { return m_pAdoConnection; } void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; } void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; } const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;} OCatalog* getAdoCatalog() const { if ( m_xCatalog.get().is() ) return m_pCatalog; return NULL; } sal_Int32 getEngineType() const { return m_nEngineType; } ODriver* getDriver() const { return m_pDriver; } static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo, DataTypeEnum _nType, const ::rtl::OUString& _sTypeName, sal_Int32 _nPrecision, sal_Int32 _nScale, sal_Bool& _brForceToType); }; } } #endif // _CONNECTIVITY_ADO_ACONNECTION_HXX_ <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 6/15/2020, 11:46:33 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; constexpr int dx[4] = {1, 0, -1, 0}; constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- 2D, 3D, 4D vectors ----- // Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7018300 template <typename T> vector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{}) { return vector<vector<T>>(d0, vector<T>(d1, v)); } template <typename T> vector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{}) { return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v)); } template <typename T> vector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{}) { return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v)); } // ----- Solve ----- using Point = tuple<int, int>; class Solve { int H, W, K; vector<vector<int>> V; int sx, sy, gx, gy; public: Solve(int H, int W) : H{H}, W{W}, V{Make2DVector(H, W, Infty<int>())} { cin >> K; cin >> sx >> sy >> gx >> gy; --sx; --sy; --gx; --gy; for (auto i{0}; i < H; ++i) { for (auto j{0}; j < W; ++j) { char c; cin >> c; if (c == '@') { V[i][j] = -1; } } } } void flush() { queue<Point> Q; Q.push(Point{sx, sy}); V[sx][sy] = 0; while (!Q.empty()) { auto p{Q.front()}; auto [x, y] = p; Q.pop(); for (auto k{0}; k < 4; ++k) { for (auto i{1}; i <= K; ++i) { auto nx{x + dx[k] * i}; auto ny{y + dy[k] * i}; if (!valid(nx, ny)) { break; } else if (V[nx][ny] == Infty<int>()) { V[nx][ny] = V[x][y] + 1; Q.push(Point{nx, ny}); } else if (V[nx][ny] == V[x][y]) { continue; } } } } auto ans{V[gx][gy]}; if (ans == Infty<int>()) { cout << -1 << endl; } else { cout << ans << endl; } } private: bool valid(int x, int y) { return 0 <= x && x < H && 0 <= y && y < W && V[x][y] != -1; } }; // ----- main() ----- int main() { int H, W; cin >> H >> W; Solve solve(H, W); solve.flush(); } <commit_msg>submit F2.cpp to 'F - Pond Skater' (abc170) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 6/15/2020, 11:46:33 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; constexpr int dx[4] = {1, 0, -1, 0}; constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- 2D, 3D, 4D vectors ----- // Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7018300 template <typename T> vector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{}) { return vector<vector<T>>(d0, vector<T>(d1, v)); } template <typename T> vector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{}) { return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v)); } template <typename T> vector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{}) { return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v)); } // ----- Solve ----- using Point = tuple<int, int>; class Solve { int H, W, K; vector<vector<int>> V; int sx, sy, gx, gy; public: Solve(int H, int W) : H{H}, W{W}, V{Make2DVector(H, W, Infty<int>())} { cin >> K; cin >> sx >> sy >> gx >> gy; --sx; --sy; --gx; --gy; for (auto i{0}; i < H; ++i) { for (auto j{0}; j < W; ++j) { char c; cin >> c; if (c == '@') { V[i][j] = -1; } } } } void flush() { queue<Point> Q; Q.push(Point{sx, sy}); V[sx][sy] = 0; while (!Q.empty()) { auto p{Q.front()}; auto [x, y] = p; Q.pop(); for (auto k{0}; k < 4; ++k) { for (auto i{1}; i <= K; ++i) { auto nx{x + dx[k] * i}; auto ny{y + dy[k] * i}; if (!valid(nx, ny)) { break; } else if (V[nx][ny] == Infty<int>()) { V[nx][ny] = V[x][y] + 1; Q.push(Point{nx, ny}); } else if (V[nx][ny] <= V[x][y] + 1) { continue; } } } } auto ans{V[gx][gy]}; if (ans == Infty<int>()) { cout << -1 << endl; } else { cout << ans << endl; } } private: bool valid(int x, int y) { return 0 <= x && x < H && 0 <= y && y < W && V[x][y] != -1; } }; // ----- main() ----- int main() { int H, W; cin >> H >> W; Solve solve(H, W); solve.flush(); } <|endoftext|>
<commit_before>#include "game/apocresources/apocpalette.h" #include "framework/palette.h" #include "framework/data.h" #include "framework/logger.h" namespace OpenApoc { sp<Palette> loadApocPalette(Data &data, const UString fileName) { auto f = data.fs.open(fileName); if (!f) return nullptr; auto numEntries = f.size() / 3; auto p = std::make_shared<Palette>(numEntries); for (unsigned int i = 0; i < numEntries; i++) { uint8_t colour[3]; Colour c; f.read(reinterpret_cast<char *>(&colour), 3); if (!f) break; if (i == 0) c = {0, 0, 0, 0}; else { /* Scale from 0-64 to 0-255 */ uint8_t r = colour[0] << 2 | (colour[0] >> 4 & 0x3); uint8_t g = colour[1] << 2 | (colour[1] >> 4 & 0x3); uint8_t b = colour[2] << 2 | (colour[2] >> 4 & 0x3); uint8_t a = 255; c = {r, g, b, a}; } p->SetColour(i, c); } return p; } struct PcxHeader { uint8_t Identifier; /* PCX Id Number (Always 0x0A) */ uint8_t Version; /* Version Number */ uint8_t Encoding; /* Encoding Format */ uint8_t BitsPerPixel; /* Bits per Pixel */ uint16_t XStart; /* Left of image */ uint16_t YStart; /* Top of Image */ uint16_t XEnd; /* Right of Image */ uint16_t YEnd; /* Bottom of image */ uint16_t HorzRes; /* Horizontal Resolution */ uint16_t VertRes; /* Vertical Resolution */ uint8_t Palette[48]; /* 16-Color EGA Palette */ uint8_t Reserved1; /* Reserved (Always 0) */ uint8_t NumBitPlanes; /* Number of Bit Planes */ uint16_t BytesPerLine; /* Bytes per Scan-line */ uint16_t PaletteType; /* Palette Type */ uint16_t HorzScreenSize; /* Horizontal Screen Size */ uint16_t VertScreenSize; /* Vertical Screen Size */ uint8_t Reserved2[54]; /* Reserved (Always 0) */ }; static const uint8_t PcxIdentifier = 0x0A; static_assert(sizeof(struct PcxHeader) == 128, "PcxHeader unexpected size"); sp<Palette> loadPCXPalette(Data &data, const UString fileName) { auto length = fileName.length(); if (length < 4 || fileName.substr(length - 4, 4).toUpper() != ".PCX") { LogInfo("Skipping file \"%s\" as it doesn't look like a .pcx", fileName.c_str()); return nullptr; } auto file = data.fs.open(fileName); if (!file) { LogInfo("File \"%s\" failed to be opened", fileName.c_str()); return nullptr; } // We only support images with 256-colour palettes, so even if it has a pcx header supported // files will never be smaller than sizeof(header) + sizeof(palette) if (file.size() < sizeof(PcxHeader) + 256 * 3) { LogInfo("File \"%s\" has size %zu - too small for header and palette", fileName.c_str(), file.size()); return nullptr; } PcxHeader header; file.read(reinterpret_cast<char *>(&header), sizeof(header)); if (!file) { LogInfo("File \"%s\" failed to read PCX header", fileName.c_str()); return nullptr; } if (header.Identifier != PcxIdentifier) { LogInfo("File \"%s\" doesn't have PCX header magic", fileName.c_str()); return nullptr; } if (header.BitsPerPixel != 8) { LogInfo("File \"%s\" has non-8-bit image", fileName.c_str()); return nullptr; } file.seekg(file.size() - (256 * 3)); auto p = std::make_shared<Palette>(256); for (unsigned int i = 0; i < 256; i++) { uint8_t colour[3]; Colour c; file.read(reinterpret_cast<char *>(&colour), 3); if (!file) { LogWarning("Unexpected EOF at index %u", i); return nullptr; } if (i == 0) c = {0, 0, 0, 0}; else c = {static_cast<uint8_t>(colour[0]), static_cast<uint8_t>(colour[1]), static_cast<uint8_t>(colour[2]), 255}; p->SetColour(i, c); } return p; } }; // namespace OpenApoc <commit_msg>Fix typo in comment<commit_after>#include "game/apocresources/apocpalette.h" #include "framework/palette.h" #include "framework/data.h" #include "framework/logger.h" namespace OpenApoc { sp<Palette> loadApocPalette(Data &data, const UString fileName) { auto f = data.fs.open(fileName); if (!f) return nullptr; auto numEntries = f.size() / 3; auto p = std::make_shared<Palette>(numEntries); for (unsigned int i = 0; i < numEntries; i++) { uint8_t colour[3]; Colour c; f.read(reinterpret_cast<char *>(&colour), 3); if (!f) break; if (i == 0) c = {0, 0, 0, 0}; else { /* Scale from 0-63 to 0-255 */ uint8_t r = colour[0] << 2 | (colour[0] >> 4 & 0x3); uint8_t g = colour[1] << 2 | (colour[1] >> 4 & 0x3); uint8_t b = colour[2] << 2 | (colour[2] >> 4 & 0x3); uint8_t a = 255; c = {r, g, b, a}; } p->SetColour(i, c); } return p; } struct PcxHeader { uint8_t Identifier; /* PCX Id Number (Always 0x0A) */ uint8_t Version; /* Version Number */ uint8_t Encoding; /* Encoding Format */ uint8_t BitsPerPixel; /* Bits per Pixel */ uint16_t XStart; /* Left of image */ uint16_t YStart; /* Top of Image */ uint16_t XEnd; /* Right of Image */ uint16_t YEnd; /* Bottom of image */ uint16_t HorzRes; /* Horizontal Resolution */ uint16_t VertRes; /* Vertical Resolution */ uint8_t Palette[48]; /* 16-Color EGA Palette */ uint8_t Reserved1; /* Reserved (Always 0) */ uint8_t NumBitPlanes; /* Number of Bit Planes */ uint16_t BytesPerLine; /* Bytes per Scan-line */ uint16_t PaletteType; /* Palette Type */ uint16_t HorzScreenSize; /* Horizontal Screen Size */ uint16_t VertScreenSize; /* Vertical Screen Size */ uint8_t Reserved2[54]; /* Reserved (Always 0) */ }; static const uint8_t PcxIdentifier = 0x0A; static_assert(sizeof(struct PcxHeader) == 128, "PcxHeader unexpected size"); sp<Palette> loadPCXPalette(Data &data, const UString fileName) { auto length = fileName.length(); if (length < 4 || fileName.substr(length - 4, 4).toUpper() != ".PCX") { LogInfo("Skipping file \"%s\" as it doesn't look like a .pcx", fileName.c_str()); return nullptr; } auto file = data.fs.open(fileName); if (!file) { LogInfo("File \"%s\" failed to be opened", fileName.c_str()); return nullptr; } // We only support images with 256-colour palettes, so even if it has a pcx header supported // files will never be smaller than sizeof(header) + sizeof(palette) if (file.size() < sizeof(PcxHeader) + 256 * 3) { LogInfo("File \"%s\" has size %zu - too small for header and palette", fileName.c_str(), file.size()); return nullptr; } PcxHeader header; file.read(reinterpret_cast<char *>(&header), sizeof(header)); if (!file) { LogInfo("File \"%s\" failed to read PCX header", fileName.c_str()); return nullptr; } if (header.Identifier != PcxIdentifier) { LogInfo("File \"%s\" doesn't have PCX header magic", fileName.c_str()); return nullptr; } if (header.BitsPerPixel != 8) { LogInfo("File \"%s\" has non-8-bit image", fileName.c_str()); return nullptr; } file.seekg(file.size() - (256 * 3)); auto p = std::make_shared<Palette>(256); for (unsigned int i = 0; i < 256; i++) { uint8_t colour[3]; Colour c; file.read(reinterpret_cast<char *>(&colour), 3); if (!file) { LogWarning("Unexpected EOF at index %u", i); return nullptr; } if (i == 0) c = {0, 0, 0, 0}; else c = {static_cast<uint8_t>(colour[0]), static_cast<uint8_t>(colour[1]), static_cast<uint8_t>(colour[2]), 255}; p->SetColour(i, c); } return p; } }; // namespace OpenApoc <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Get basic type definitions. #define IPC_MESSAGE_IMPL #include "content/common/content_message_generator.h" // Generate constructors. #include "ipc/struct_constructor_macros.h" #include "content/common/content_message_generator.h" // Generate destructors. #include "ipc/struct_destructor_macros.h" #include "content/common/content_message_generator.h" #if defined(USE_AURA) && defined(OS_WIN) #include "ui/gfx/native_widget_types.h" namespace IPC { // TODO(beng): Figure out why this is needed, fix that issue and remove // this. Brett and I were unable to figure out why, but he // thought this should be harmless. template <> struct ParamTraits<gfx::PluginWindowHandle> { typedef gfx::PluginWindowHandle param_type; static void Write(Message* m, const param_type& p) { m->WriteUInt32(reinterpret_cast<uint32>(p)); } static bool Read(const Message* m, void** iter, param_type* r) { DCHECK_EQ(sizeof(param_type), sizeof(uint32)); return m->ReadUInt32(iter, reinterpret_cast<uint32*>(r)); } static void Log(const param_type& p, std::string* l) { l->append(StringPrintf("0x%X", p)); } }; } // namespace IPC #endif // Generate param traits write methods. #include "ipc/param_traits_write_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC // Generate param traits read methods. #include "ipc/param_traits_read_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC // Generate param traits log methods. #include "ipc/param_traits_log_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC <commit_msg>fix win_aura TBR=akalin<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Get basic type definitions. #define IPC_MESSAGE_IMPL #include "content/common/content_message_generator.h" // Generate constructors. #include "ipc/struct_constructor_macros.h" #include "content/common/content_message_generator.h" // Generate destructors. #include "ipc/struct_destructor_macros.h" #include "content/common/content_message_generator.h" #if defined(USE_AURA) && defined(OS_WIN) #include "ui/gfx/native_widget_types.h" namespace IPC { // TODO(beng): Figure out why this is needed, fix that issue and remove // this. Brett and I were unable to figure out why, but he // thought this should be harmless. template <> struct ParamTraits<gfx::PluginWindowHandle> { typedef gfx::PluginWindowHandle param_type; static void Write(Message* m, const param_type& p) { m->WriteUInt32(reinterpret_cast<uint32>(p)); } static bool Read(const Message* m, PickleIterator* iter, param_type* r) { DCHECK_EQ(sizeof(param_type), sizeof(uint32)); return m->ReadUInt32(iter, reinterpret_cast<uint32*>(r)); } static void Log(const param_type& p, std::string* l) { l->append(StringPrintf("0x%X", p)); } }; } // namespace IPC #endif // Generate param traits write methods. #include "ipc/param_traits_write_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC // Generate param traits read methods. #include "ipc/param_traits_read_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC // Generate param traits log methods. #include "ipc/param_traits_log_macros.h" namespace IPC { #include "content/common/content_message_generator.h" } // namespace IPC <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" using content::WebContents; class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest { public: // Checks that a theme info bar is currently visible and issues an undo to // revert to the previous theme. void VerifyThemeInfoBarAndUndoInstall() { TabContentsWrapper* tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(tab); InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper(); ASSERT_EQ(1U, infobar_helper->infobar_count()); ConfirmInfoBarDelegate* delegate = infobar_helper-> GetInfoBarDelegateAt(0)->AsConfirmInfoBarDelegate(); ASSERT_TRUE(delegate); delegate->Cancel(); ASSERT_EQ(0U, infobar_helper->infobar_count()); } const Extension* GetTheme() const { return ThemeServiceFactory::GetThemeForProfile(browser()->profile()); } }; IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, TestThemeInstallUndoResetsToDefault) { // Install theme once and undo to verify we go back to default theme. FilePath theme_crx = PackExtension(test_data_dir_.AppendASCII("theme")); ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 1)); const Extension* theme = GetTheme(); ASSERT_TRUE(theme); std::string theme_id = theme->id(); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, GetTheme()); // Set the same theme twice and undo to verify we go back to default theme. // We set the |expected_change| to zero in these 'InstallExtensionWithUI' // calls since the theme has already been installed above and this is an // overinstall to set the active theme. ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0)); theme = GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_id, theme->id()); ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0)); theme = GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_id, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, GetTheme()); } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, TestThemeInstallUndoResetsToPreviousTheme) { // Install first theme. FilePath theme_path = test_data_dir_.AppendASCII("theme"); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1)); const Extension* theme = GetTheme(); ASSERT_TRUE(theme); std::string theme_id = theme->id(); // Then install second theme. FilePath theme_path2 = test_data_dir_.AppendASCII("theme2"); ASSERT_TRUE(InstallExtensionWithUI(theme_path2, 1)); const Extension* theme2 = GetTheme(); ASSERT_TRUE(theme2); EXPECT_FALSE(theme_id == theme2->id()); // Undo second theme will revert to first theme. VerifyThemeInfoBarAndUndoInstall(); EXPECT_EQ(theme, GetTheme()); } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, AppInstallConfirmation) { int num_tabs = browser()->tab_count(); FilePath app_dir = test_data_dir_.AppendASCII("app"); ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1, browser()->profile())); if (NewTabUI::ShouldShowApps()) { EXPECT_EQ(num_tabs + 1, browser()->tab_count()); WebContents* web_contents = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents); EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(), "chrome://newtab/", false)); } else { // TODO(xiyuan): Figure out how to test extension installed bubble? } } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, AppInstallConfirmation_Incognito) { Profile* incognito_profile = browser()->profile()->GetOffTheRecordProfile(); Browser* incognito_browser = Browser::GetOrCreateTabbedBrowser( incognito_profile); int num_incognito_tabs = incognito_browser->tab_count(); int num_normal_tabs = browser()->tab_count(); FilePath app_dir = test_data_dir_.AppendASCII("app"); ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1, incognito_profile)); EXPECT_EQ(num_incognito_tabs, incognito_browser->tab_count()); if (NewTabUI::ShouldShowApps()) { EXPECT_EQ(num_normal_tabs + 1, browser()->tab_count()); WebContents* web_contents = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents); EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(), "chrome://newtab/", false)); } else { // TODO(xiyuan): Figure out how to test extension installed bubble? } } <commit_msg>Disable failing test (ExtensionInstallUIBrowserTest.TestThemeInstallUndoResetsToDefault) on Linux due to persistent failures on bot chromium.chromiumos : Linux.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" using content::WebContents; class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest { public: // Checks that a theme info bar is currently visible and issues an undo to // revert to the previous theme. void VerifyThemeInfoBarAndUndoInstall() { TabContentsWrapper* tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(tab); InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper(); ASSERT_EQ(1U, infobar_helper->infobar_count()); ConfirmInfoBarDelegate* delegate = infobar_helper-> GetInfoBarDelegateAt(0)->AsConfirmInfoBarDelegate(); ASSERT_TRUE(delegate); delegate->Cancel(); ASSERT_EQ(0U, infobar_helper->infobar_count()); } const Extension* GetTheme() const { return ThemeServiceFactory::GetThemeForProfile(browser()->profile()); } }; #if defined(OS_LINUX) // Fails consistently on bot chromium.chromiumos \ Linux. // See: http://crbug.com/120647. #define MAYBE_TestThemeInstallUndoResetsToDefault DISABLED_TestThemeInstallUndoResetsToDefault #else #define MAYBE_TestThemeInstallUndoResetsToDefault TestThemeInstallUndoResetsToDefault #endif IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, MAYBE_TestThemeInstallUndoResetsToDefault) { // Install theme once and undo to verify we go back to default theme. FilePath theme_crx = PackExtension(test_data_dir_.AppendASCII("theme")); ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 1)); const Extension* theme = GetTheme(); ASSERT_TRUE(theme); std::string theme_id = theme->id(); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, GetTheme()); // Set the same theme twice and undo to verify we go back to default theme. // We set the |expected_change| to zero in these 'InstallExtensionWithUI' // calls since the theme has already been installed above and this is an // overinstall to set the active theme. ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0)); theme = GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_id, theme->id()); ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0)); theme = GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_id, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, GetTheme()); } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, TestThemeInstallUndoResetsToPreviousTheme) { // Install first theme. FilePath theme_path = test_data_dir_.AppendASCII("theme"); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1)); const Extension* theme = GetTheme(); ASSERT_TRUE(theme); std::string theme_id = theme->id(); // Then install second theme. FilePath theme_path2 = test_data_dir_.AppendASCII("theme2"); ASSERT_TRUE(InstallExtensionWithUI(theme_path2, 1)); const Extension* theme2 = GetTheme(); ASSERT_TRUE(theme2); EXPECT_FALSE(theme_id == theme2->id()); // Undo second theme will revert to first theme. VerifyThemeInfoBarAndUndoInstall(); EXPECT_EQ(theme, GetTheme()); } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, AppInstallConfirmation) { int num_tabs = browser()->tab_count(); FilePath app_dir = test_data_dir_.AppendASCII("app"); ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1, browser()->profile())); if (NewTabUI::ShouldShowApps()) { EXPECT_EQ(num_tabs + 1, browser()->tab_count()); WebContents* web_contents = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents); EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(), "chrome://newtab/", false)); } else { // TODO(xiyuan): Figure out how to test extension installed bubble? } } IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, AppInstallConfirmation_Incognito) { Profile* incognito_profile = browser()->profile()->GetOffTheRecordProfile(); Browser* incognito_browser = Browser::GetOrCreateTabbedBrowser( incognito_profile); int num_incognito_tabs = incognito_browser->tab_count(); int num_normal_tabs = browser()->tab_count(); FilePath app_dir = test_data_dir_.AppendASCII("app"); ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1, incognito_profile)); EXPECT_EQ(num_incognito_tabs, incognito_browser->tab_count()); if (NewTabUI::ShouldShowApps()) { EXPECT_EQ(num_normal_tabs + 1, browser()->tab_count()); WebContents* web_contents = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents); EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(), "chrome://newtab/", false)); } else { // TODO(xiyuan): Figure out how to test extension installed bubble? } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/wifi_data_provider_win.h" #include <vector> #include "base/scoped_ptr.h" #include "base/string_util.h" #include "chrome/browser/geolocation/wifi_data_provider_common.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MockWlanApi : public Win32WifiDataProvider::WlanApiInterface { public: MockWlanApi() : calls_(0), bool_return_(true) { } virtual bool GetAccessPointData(WifiData::AccessPointDataSet* data) { ++calls_; *data = data_out_; return bool_return_; } int calls_; bool bool_return_; WifiData::AccessPointDataSet data_out_; }; class MockPollingPolicy : public PollingPolicyInterface { public: virtual void UpdatePollingInterval(bool scan_results_differ) { results_differed_.push_back(scan_results_differ); } virtual int PollingInterval() { return 1; } std::vector<bool> results_differed_; }; // Stops the specified (nested) message loop when the listener is called back. class MessageLoopQuitListener : public Win32WifiDataProvider::ListenerInterface { public: explicit MessageLoopQuitListener(MessageLoop* message_loop) : message_loop_to_quit_(message_loop) { assert(message_loop_to_quit_ != NULL); } // ListenerInterface virtual void DeviceDataUpdateAvailable( DeviceDataProvider<WifiData>* provider) { // We expect the callback to come from the provider's internal worker // thread. This is not a strict requirement, just a lot of the complexity // here is predicated on the need to cope with this scenario! EXPECT_NE(MessageLoop::current(), message_loop_to_quit_); provider_ = provider; // Can't call Quit() directly on another thread's message loop. message_loop_to_quit_->PostTask(FROM_HERE, new MessageLoop::QuitTask); } MessageLoop* message_loop_to_quit_; DeviceDataProvider<WifiData>* provider_; }; // Main test fixture class Win32WifiDataProviderTest : public testing::Test { public: static Win32WifiDataProvider* CreateWin32WifiDataProvider( MockWlanApi** wlan_api_out) { Win32WifiDataProvider* provider = new Win32WifiDataProvider; *wlan_api_out = new MockWlanApi; provider->inject_mock_wlan_api(*wlan_api_out); // Takes ownership. provider->inject_mock_polling_policy(new MockPollingPolicy); // ditto return provider; } virtual void SetUp() { provider_.reset(CreateWin32WifiDataProvider(&wlan_api_)); } virtual void TearDown() { provider_.reset(NULL); } protected: MessageLoop main_message_loop_; scoped_ptr<Win32WifiDataProvider> provider_; MockWlanApi* wlan_api_; }; WifiDataProviderImplBase* CreateWin32WifiDataProviderStatic() { MockWlanApi* wlan_api; return Win32WifiDataProviderTest::CreateWin32WifiDataProvider(&wlan_api); } } // namespace TEST_F(Win32WifiDataProviderTest, CreateDestroy) { // Test fixture members were SetUp correctly. EXPECT_EQ(&main_message_loop_, MessageLoop::current()); EXPECT_TRUE(NULL != provider_.get()); EXPECT_TRUE(NULL != wlan_api_); } TEST_F(Win32WifiDataProviderTest, StartThread) { EXPECT_TRUE(provider_->StartDataProvider()); provider_.reset(NULL); // Stop()s the thread. SUCCEED(); } TEST_F(Win32WifiDataProviderTest, DoAnEmptyScan) { MessageLoopQuitListener quit_listener(&main_message_loop_); provider_->AddListener(&quit_listener); EXPECT_TRUE(provider_->StartDataProvider()); main_message_loop_.Run(); EXPECT_EQ(1, wlan_api_->calls_); WifiData data; EXPECT_TRUE(provider_->GetData(&data)); EXPECT_EQ(0, data.access_point_data.size()); } TEST_F(Win32WifiDataProviderTest, DoScanWithResults) { MessageLoopQuitListener quit_listener(&main_message_loop_); provider_->AddListener(&quit_listener); AccessPointData single_access_point; single_access_point.age = 1; single_access_point.channel = 2; single_access_point.mac_address = 3; single_access_point.radio_signal_strength = 4; single_access_point.signal_to_noise = 5; single_access_point.ssid = L"foossid"; wlan_api_->data_out_.insert(single_access_point); EXPECT_TRUE(provider_->StartDataProvider()); main_message_loop_.Run(); EXPECT_EQ(1, wlan_api_->calls_); WifiData data; EXPECT_TRUE(provider_->GetData(&data)); EXPECT_EQ(1, data.access_point_data.size()); EXPECT_EQ(single_access_point.age, data.access_point_data.begin()->age); EXPECT_EQ(single_access_point.ssid, data.access_point_data.begin()->ssid); } TEST_F(Win32WifiDataProviderTest, StartThreadViaDeviceDataProvider) { MessageLoopQuitListener quit_listener(&main_message_loop_); DeviceDataProvider<WifiData>::SetFactory(CreateWin32WifiDataProviderStatic); DeviceDataProvider<WifiData>::Register(&quit_listener); main_message_loop_.Run(); DeviceDataProvider<WifiData>::Unregister(&quit_listener); DeviceDataProvider<WifiData>::ResetFactory(); } <commit_msg>Fix flaky test causing tree to go red<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/wifi_data_provider_win.h" #include <vector> #include "base/scoped_ptr.h" #include "base/string_util.h" #include "chrome/browser/geolocation/wifi_data_provider_common.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MockWlanApi : public Win32WifiDataProvider::WlanApiInterface { public: MockWlanApi() : calls_(0), bool_return_(true) { } virtual bool GetAccessPointData(WifiData::AccessPointDataSet* data) { ++calls_; *data = data_out_; return bool_return_; } int calls_; bool bool_return_; WifiData::AccessPointDataSet data_out_; }; class MockPollingPolicy : public PollingPolicyInterface { public: virtual void UpdatePollingInterval(bool scan_results_differ) { results_differed_.push_back(scan_results_differ); } virtual int PollingInterval() { return 1; } std::vector<bool> results_differed_; }; // Stops the specified (nested) message loop when the listener is called back. class MessageLoopQuitListener : public Win32WifiDataProvider::ListenerInterface { public: explicit MessageLoopQuitListener(MessageLoop* message_loop) : message_loop_to_quit_(message_loop) { assert(message_loop_to_quit_ != NULL); } // ListenerInterface virtual void DeviceDataUpdateAvailable( DeviceDataProvider<WifiData>* provider) { // We expect the callback to come from the provider's internal worker // thread. This is not a strict requirement, just a lot of the complexity // here is predicated on the need to cope with this scenario! EXPECT_NE(MessageLoop::current(), message_loop_to_quit_); provider_ = provider; // Can't call Quit() directly on another thread's message loop. message_loop_to_quit_->PostTask(FROM_HERE, new MessageLoop::QuitTask); } MessageLoop* message_loop_to_quit_; DeviceDataProvider<WifiData>* provider_; }; // Main test fixture class Win32WifiDataProviderTest : public testing::Test { public: static Win32WifiDataProvider* CreateWin32WifiDataProvider( MockWlanApi** wlan_api_out) { Win32WifiDataProvider* provider = new Win32WifiDataProvider; *wlan_api_out = new MockWlanApi; provider->inject_mock_wlan_api(*wlan_api_out); // Takes ownership. provider->inject_mock_polling_policy(new MockPollingPolicy); // ditto return provider; } virtual void SetUp() { provider_.reset(CreateWin32WifiDataProvider(&wlan_api_)); } virtual void TearDown() { provider_.reset(NULL); } protected: MessageLoop main_message_loop_; scoped_ptr<Win32WifiDataProvider> provider_; MockWlanApi* wlan_api_; }; WifiDataProviderImplBase* CreateWin32WifiDataProviderStatic() { MockWlanApi* wlan_api; return Win32WifiDataProviderTest::CreateWin32WifiDataProvider(&wlan_api); } } // namespace TEST_F(Win32WifiDataProviderTest, CreateDestroy) { // Test fixture members were SetUp correctly. EXPECT_EQ(&main_message_loop_, MessageLoop::current()); EXPECT_TRUE(NULL != provider_.get()); EXPECT_TRUE(NULL != wlan_api_); } TEST_F(Win32WifiDataProviderTest, StartThread) { EXPECT_TRUE(provider_->StartDataProvider()); provider_.reset(NULL); // Stop()s the thread. SUCCEED(); } TEST_F(Win32WifiDataProviderTest, DoAnEmptyScan) { MessageLoopQuitListener quit_listener(&main_message_loop_); provider_->AddListener(&quit_listener); EXPECT_TRUE(provider_->StartDataProvider()); main_message_loop_.Run(); // Check we had at least one call. The worker thread may have raced ahead // and made multiple calls. EXPECT_GT(wlan_api_->calls_, 0); WifiData data; EXPECT_TRUE(provider_->GetData(&data)); EXPECT_EQ(0, data.access_point_data.size()); provider_->RemoveListener(&quit_listener); } TEST_F(Win32WifiDataProviderTest, DoScanWithResults) { MessageLoopQuitListener quit_listener(&main_message_loop_); provider_->AddListener(&quit_listener); AccessPointData single_access_point; single_access_point.age = 1; single_access_point.channel = 2; single_access_point.mac_address = 3; single_access_point.radio_signal_strength = 4; single_access_point.signal_to_noise = 5; single_access_point.ssid = L"foossid"; wlan_api_->data_out_.insert(single_access_point); EXPECT_TRUE(provider_->StartDataProvider()); main_message_loop_.Run(); EXPECT_GT(wlan_api_->calls_, 0); WifiData data; EXPECT_TRUE(provider_->GetData(&data)); EXPECT_EQ(1, data.access_point_data.size()); EXPECT_EQ(single_access_point.age, data.access_point_data.begin()->age); EXPECT_EQ(single_access_point.ssid, data.access_point_data.begin()->ssid); provider_->RemoveListener(&quit_listener); } TEST_F(Win32WifiDataProviderTest, StartThreadViaDeviceDataProvider) { MessageLoopQuitListener quit_listener(&main_message_loop_); DeviceDataProvider<WifiData>::SetFactory(CreateWin32WifiDataProviderStatic); DeviceDataProvider<WifiData>::Register(&quit_listener); main_message_loop_.Run(); DeviceDataProvider<WifiData>::Unregister(&quit_listener); DeviceDataProvider<WifiData>::ResetFactory(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SMDLL_HXX #define SMDLL_HXX #include <tools/resid.hxx> #include <sfx2/sfxdefs.hxx> #include "smmod.hxx" class SmData; class SfxMedium; class SfxFilter; class SmDLL { static bool bInitialized; public: static void Init(); static void Exit(); static sal_uLong DetectFilter( SfxMedium& rMedium, const SfxFilter **ppFilter, SfxFilterFlags nMust, SfxFilterFlags nDont ); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>DetectFilter declared but not defined<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SMDLL_HXX #define SMDLL_HXX #include <tools/resid.hxx> #include <sfx2/sfxdefs.hxx> #include "smmod.hxx" class SmData; class SfxMedium; class SfxFilter; class SmDLL { static bool bInitialized; public: static void Init(); static void Exit(); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBoundingShapeVtkMapper3D.h" #include "../DataManagement/mitkBoundingShapeUtil.h" #include <mitkBaseProperty.h> #include <vtkAppendPolyData.h> #include <vtkCamera.h> #include <vtkCubeSource.h> #include <vtkDataSetMapper.h> #include <vtkMath.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <vtkTransformFilter.h> namespace mitk { class BoundingShapeVtkMapper3D::Impl { class LocalStorage : public Mapper::BaseLocalStorage { public: LocalStorage(); ~LocalStorage(); LocalStorage(const LocalStorage &) = delete; LocalStorage &operator=(const LocalStorage &) = delete; std::vector<vtkSmartPointer<vtkSphereSource>> Handles; vtkSmartPointer<vtkActor> Actor; vtkSmartPointer<vtkActor> HandleActor; vtkSmartPointer<vtkActor> SelectedHandleActor; vtkSmartPointer<vtkPropAssembly> PropAssembly; }; public: Impl() : DistanceFromCam(1.0) { Point3D initialPoint; initialPoint.Fill(0); for (int i = 0; i < 6; ++i) HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i))); } double DistanceFromCam; std::vector<Handle> HandlePropertyList; mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler; }; } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage() : Actor(vtkSmartPointer<vtkActor>::New()), HandleActor(vtkSmartPointer<vtkActor>::New()), SelectedHandleActor(vtkSmartPointer<vtkActor>::New()), PropAssembly(vtkSmartPointer<vtkPropAssembly>::New()) { for (int i = 0; i < 6; i++) Handles.push_back(vtkSmartPointer<vtkSphereSource>::New()); } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage() { } void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite) { Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl) { } mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D() { delete m_Impl; } void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor) { Superclass::ApplyColorAndOpacityProperties(renderer, actor); } void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor) { if (actor == nullptr) return; auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; bool isVisible = false; dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer); actor->SetVisibility(isVisible); float lineWidth = 1.0f; dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer); auto property = actor->GetProperty(); property->SetLineWidth(lineWidth); } void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer) { auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera(); auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer); bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime(); double distance = camera->GetDistance(); if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps) { m_Impl->DistanceFromCam = distance; needGenerateData = true; } if (needGenerateData) { bool isVisible = true; dataNode->GetVisibility(isVisible, renderer); if (!isVisible) { localStorage->Actor->VisibilityOff(); return; } // set the input-object at time t for the mapper GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData()); if (geometryData == nullptr) return; mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry(); mitk::Vector3D spacing = geometry->GetSpacing(); // calculate cornerpoints from geometry std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true); Point3D p0 = cornerPoints[0]; Point3D p1 = cornerPoints[1]; Point3D p2 = cornerPoints[2]; Point3D p4 = cornerPoints[4]; Point3D extent; extent[0] = sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2])); extent[1] = sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2])); extent[2] = sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2])); // calculate center based on half way of the distance between two opposing cornerpoints mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]); if (m_Impl->HandlePropertyList.size() == 6) { // set handle positions Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]); Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]); Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]); Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]); Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]); Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]); m_Impl->HandlePropertyList[0].SetPosition(pointLeft); m_Impl->HandlePropertyList[1].SetPosition(pointRight); m_Impl->HandlePropertyList[2].SetPosition(pointTop); m_Impl->HandlePropertyList[3].SetPosition(pointBottom); m_Impl->HandlePropertyList[4].SetPosition(pointFront); m_Impl->HandlePropertyList[5].SetPosition(pointBack); } auto cube = vtkCubeSource::New(); cube->SetXLength(extent[0] / spacing[0]); cube->SetYLength(extent[1] / spacing[1]); cube->SetZLength(extent[2] / spacing[2]); // calculates translation based on offset+extent not on the transformation matrix vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix(); auto translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(center[0] - imageTransform->GetElement(0, 3), center[1] - imageTransform->GetElement(1, 3), center[2] - imageTransform->GetElement(2, 3)); auto transform = vtkSmartPointer<vtkTransform>::New(); transform->SetMatrix(imageTransform); transform->PostMultiply(); transform->Concatenate(translation); transform->Update(); cube->Update(); auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New(); transformFilter->SetInputData(cube->GetOutput()); transformFilter->SetTransform(transform); transformFilter->Update(); cube->Delete(); vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput(); if (polydata == nullptr) { localStorage->Actor->VisibilityOff(); return; } mitk::DoubleProperty::Pointer handleSizeProperty = dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor")); ScalarType initialHandleSize; if (handleSizeProperty != nullptr) initialHandleSize = handleSizeProperty->GetValue(); else initialHandleSize = 1.0 / 40.0; double handlesize = ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) * initialHandleSize; if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor)) localStorage->PropAssembly->RemovePart(localStorage->HandleActor); if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor)) localStorage->PropAssembly->RemovePart(localStorage->Actor); auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New(); mitk::IntProperty::Pointer activeHandleId = dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID")); int i = 0; for (auto &handle : localStorage->Handles) { Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition(); handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]); handle->SetRadius(handlesize); handle->Update(); if (activeHandleId == nullptr) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex()) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { selectedhandlemapper->SetInputData(handle->GetOutput()); localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper); localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0); localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput()); localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor); } } i++; } appendPoly->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(polydata); auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); handlemapper->SetInputData(appendPoly->GetOutput()); localStorage->Actor->SetMapper(mapper); localStorage->Actor->GetMapper()->SetInputDataObject(polydata); localStorage->Actor->GetProperty()->SetOpacity(0.3); mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color")); if (selectedColor != nullptr) { mitk::Color color = selectedColor->GetColor(); localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]); } localStorage->HandleActor->SetMapper(handlemapper); if (activeHandleId == nullptr) { localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1); } else { localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0); } localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput()); this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor); this->ApplyBoundingShapeProperties(renderer, localStorage->Actor); this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor); this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor); // apply properties read from the PropertyList // this->ApplyProperties(localStorage->m_Actor, renderer); // this->ApplyProperties(localStorage->m_HandleActor, renderer); // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer); localStorage->Actor->VisibilityOn(); localStorage->HandleActor->VisibilityOn(); localStorage->SelectedHandleActor->VisibilityOn(); localStorage->PropAssembly->AddPart(localStorage->Actor); localStorage->PropAssembly->AddPart(localStorage->HandleActor); localStorage->PropAssembly->VisibilityOn(); localStorage->UpdateGenerateDataTime(); } } vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer) { return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly; } <commit_msg>removed Superclass call to visualize colored handles<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBoundingShapeVtkMapper3D.h" #include "../DataManagement/mitkBoundingShapeUtil.h" #include <mitkBaseProperty.h> #include <vtkAppendPolyData.h> #include <vtkCamera.h> #include <vtkCubeSource.h> #include <vtkDataSetMapper.h> #include <vtkMath.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <vtkTransformFilter.h> namespace mitk { class BoundingShapeVtkMapper3D::Impl { class LocalStorage : public Mapper::BaseLocalStorage { public: LocalStorage(); ~LocalStorage(); LocalStorage(const LocalStorage &) = delete; LocalStorage &operator=(const LocalStorage &) = delete; std::vector<vtkSmartPointer<vtkSphereSource>> Handles; vtkSmartPointer<vtkActor> Actor; vtkSmartPointer<vtkActor> HandleActor; vtkSmartPointer<vtkActor> SelectedHandleActor; vtkSmartPointer<vtkPropAssembly> PropAssembly; }; public: Impl() : DistanceFromCam(1.0) { Point3D initialPoint; initialPoint.Fill(0); for (int i = 0; i < 6; ++i) HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i))); } double DistanceFromCam; std::vector<Handle> HandlePropertyList; mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler; }; } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage() : Actor(vtkSmartPointer<vtkActor>::New()), HandleActor(vtkSmartPointer<vtkActor>::New()), SelectedHandleActor(vtkSmartPointer<vtkActor>::New()), PropAssembly(vtkSmartPointer<vtkPropAssembly>::New()) { for (int i = 0; i < 6; i++) Handles.push_back(vtkSmartPointer<vtkSphereSource>::New()); } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage() { } void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite) { Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl) { } mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D() { delete m_Impl; } void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor) { //Superclass::ApplyColorAndOpacityProperties(renderer, actor); } void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor) { if (actor == nullptr) return; auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; bool isVisible = false; dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer); actor->SetVisibility(isVisible); float lineWidth = 1.0f; dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer); auto property = actor->GetProperty(); property->SetLineWidth(lineWidth); } void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer) { auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera(); auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer); bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime(); double distance = camera->GetDistance(); if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps) { m_Impl->DistanceFromCam = distance; needGenerateData = true; } if (needGenerateData) { bool isVisible = true; dataNode->GetVisibility(isVisible, renderer); if (!isVisible) { localStorage->Actor->VisibilityOff(); return; } // set the input-object at time t for the mapper GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData()); if (geometryData == nullptr) return; mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry(); mitk::Vector3D spacing = geometry->GetSpacing(); // calculate cornerpoints from geometry std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true); Point3D p0 = cornerPoints[0]; Point3D p1 = cornerPoints[1]; Point3D p2 = cornerPoints[2]; Point3D p4 = cornerPoints[4]; Point3D extent; extent[0] = sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2])); extent[1] = sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2])); extent[2] = sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2])); // calculate center based on half way of the distance between two opposing cornerpoints mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]); if (m_Impl->HandlePropertyList.size() == 6) { // set handle positions Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]); Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]); Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]); Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]); Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]); Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]); m_Impl->HandlePropertyList[0].SetPosition(pointLeft); m_Impl->HandlePropertyList[1].SetPosition(pointRight); m_Impl->HandlePropertyList[2].SetPosition(pointTop); m_Impl->HandlePropertyList[3].SetPosition(pointBottom); m_Impl->HandlePropertyList[4].SetPosition(pointFront); m_Impl->HandlePropertyList[5].SetPosition(pointBack); } auto cube = vtkCubeSource::New(); cube->SetXLength(extent[0] / spacing[0]); cube->SetYLength(extent[1] / spacing[1]); cube->SetZLength(extent[2] / spacing[2]); // calculates translation based on offset+extent not on the transformation matrix vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix(); auto translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(center[0] - imageTransform->GetElement(0, 3), center[1] - imageTransform->GetElement(1, 3), center[2] - imageTransform->GetElement(2, 3)); auto transform = vtkSmartPointer<vtkTransform>::New(); transform->SetMatrix(imageTransform); transform->PostMultiply(); transform->Concatenate(translation); transform->Update(); cube->Update(); auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New(); transformFilter->SetInputData(cube->GetOutput()); transformFilter->SetTransform(transform); transformFilter->Update(); cube->Delete(); vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput(); if (polydata == nullptr) { localStorage->Actor->VisibilityOff(); return; } mitk::DoubleProperty::Pointer handleSizeProperty = dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor")); ScalarType initialHandleSize; if (handleSizeProperty != nullptr) initialHandleSize = handleSizeProperty->GetValue(); else initialHandleSize = 1.0 / 40.0; double handlesize = ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) * initialHandleSize; if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor)) localStorage->PropAssembly->RemovePart(localStorage->HandleActor); if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor)) localStorage->PropAssembly->RemovePart(localStorage->Actor); auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New(); mitk::IntProperty::Pointer activeHandleId = dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID")); int i = 0; for (auto &handle : localStorage->Handles) { Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition(); handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]); handle->SetRadius(handlesize); handle->Update(); if (activeHandleId == nullptr) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex()) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { selectedhandlemapper->SetInputData(handle->GetOutput()); localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper); localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0); localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput()); localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor); } } i++; } appendPoly->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(polydata); auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); handlemapper->SetInputData(appendPoly->GetOutput()); localStorage->Actor->SetMapper(mapper); localStorage->Actor->GetMapper()->SetInputDataObject(polydata); localStorage->Actor->GetProperty()->SetOpacity(0.3); mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color")); if (selectedColor != nullptr) { mitk::Color color = selectedColor->GetColor(); localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]); } localStorage->HandleActor->SetMapper(handlemapper); if (activeHandleId == nullptr) { localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1); } else { localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0); } localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput()); this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor); this->ApplyBoundingShapeProperties(renderer, localStorage->Actor); this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor); this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor); // apply properties read from the PropertyList // this->ApplyProperties(localStorage->m_Actor, renderer); // this->ApplyProperties(localStorage->m_HandleActor, renderer); // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer); localStorage->Actor->VisibilityOn(); localStorage->HandleActor->VisibilityOn(); localStorage->SelectedHandleActor->VisibilityOn(); localStorage->PropAssembly->AddPart(localStorage->Actor); localStorage->PropAssembly->AddPart(localStorage->HandleActor); localStorage->PropAssembly->VisibilityOn(); localStorage->UpdateGenerateDataTime(); } } vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer) { return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/highgui/highgui.hpp" using namespace cv; using namespace std; class CV_GrfmtWriteBigImageTest : public cvtest::BaseTest { public: void run(int) { try { ts->printf(cvtest::TS::LOG, "start reading big image\n"); Mat img = imread(string(ts->get_data_path()) + "readwrite/read.png"); ts->printf(cvtest::TS::LOG, "finish reading big image\n"); if (img.empty()) ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); ts->printf(cvtest::TS::LOG, "start writing big image\n"); imwrite(cv::tempfile(".png"), img); ts->printf(cvtest::TS::LOG, "finish writing big image\n"); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; string ext_from_int(int ext) { #ifdef HAVE_PNG if (ext == 0) return ".png"; #endif if (ext == 1) return ".bmp"; if (ext == 2) return ".pgm"; #ifdef HAVE_TIFF if (ext == 3) return ".tiff"; #endif return ""; } class CV_GrfmtWriteSequenceImageTest : public cvtest::BaseTest { public: void run(int) { try { const int img_r = 640; const int img_c = 480; for (int k = 1; k <= 5; ++k) { for (int ext = 0; ext < 4; ++ext) // 0 - png, 1 - bmp, 2 - pgm, 3 - tiff { if(ext_from_int(ext).empty()) continue; for (int num_channels = 1; num_channels <= 3; num_channels+=2) { ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ext_from_int(ext).c_str()); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string img_path = cv::tempfile(ext_from_int(ext).c_str()); ts->printf(ts->LOG, "writing image : %s\n", img_path.c_str()); imwrite(img_path, img); ts->printf(ts->LOG, "reading test image : %s\n", img_path.c_str()); Mat img_test = imread(img_path, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } if (ext == 3 /*TIFF*/) { /* 4 channels should stay 4 channels */ int num_channels = 4; ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U,num_channels, ext_from_int(ext).c_str()); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string img_path = cv::tempfile(ext_from_int(ext).c_str()); ts->printf(ts->LOG, "writing image : %s\n", img_path.c_str()); imwrite(img_path, img); ts->printf(ts->LOG, "reading test image : %s\n", img_path.c_str()); Mat img_test = imread(img_path, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); CV_Assert(img.channels() == 4); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } } #ifdef HAVE_JPEG for (int num_channels = 1; num_channels <= 3; num_channels+=2) { // jpeg ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ".jpg"); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string filename = cv::tempfile(".jpg"); imwrite(filename, img); img = imread(filename, CV_LOAD_IMAGE_UNCHANGED); filename = string(ts->get_data_path() + "readwrite/test_" + char(k + 48) + "_c" + char(num_channels + 48) + ".jpg"); ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str()); Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } #endif #ifdef HAVE_TIFF for (int num_channels = 1; num_channels <= 3; num_channels+=2) { // tiff ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_16U, num_channels, ".tiff"); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_16U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string filename = cv::tempfile(".tiff"); imwrite(filename, img); ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str()); Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); ts->printf(ts->LOG, "img : %d ; %d \n", img.channels(), img.depth()); ts->printf(ts->LOG, "img_test : %d ; %d \n", img_test.channels(), img_test.depth()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } #endif } } catch(const cv::Exception & e) { ts->printf(ts->LOG, "Exception: %s\n" , e.what()); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } }; class CV_GrfmtReadBMPRLE8Test : public cvtest::BaseTest { public: void run(int) { try { Mat rle = imread(string(ts->get_data_path()) + "readwrite/rle8.bmp"); Mat bmp = imread(string(ts->get_data_path()) + "readwrite/ordinary.bmp"); if (norm(rle-bmp)>1.e-10) ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; #ifdef HAVE_PNG TEST(Highgui_Image, write_big) { CV_GrfmtWriteBigImageTest test; test.safe_run(); } #endif TEST(Highgui_Image, write_imageseq) { CV_GrfmtWriteSequenceImageTest test; test.safe_run(); } TEST(Highgui_Image, read_bmp_rle8) { CV_GrfmtReadBMPRLE8Test test; test.safe_run(); } #ifdef HAVE_PNG class CV_GrfmtPNGEncodeTest : public cvtest::BaseTest { public: void run(int) { try { vector<uchar> buff; Mat im = Mat::zeros(1000,1000, CV_8U); //randu(im, 0, 256); vector<int> param; param.push_back(CV_IMWRITE_PNG_COMPRESSION); param.push_back(3); //default(3) 0-9. cv::imencode(".png" ,im ,buff, param); // hangs Mat im2 = imdecode(buff,CV_LOAD_IMAGE_ANYDEPTH); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; TEST(Highgui_Image, encode_png) { CV_GrfmtPNGEncodeTest test; test.safe_run(); } TEST(Highgui_ImreadVSCvtColor, regression) { cvtest::TS& ts = *cvtest::TS::ptr(); const int MAX_MEAN_DIFF = 1; const int MAX_ABS_DIFF = 10; string imgName = string(ts.get_data_path()) + "/../cv/shared/lena.png"; Mat original_image = imread(imgName); Mat gray_by_codec = imread(imgName, 0); Mat gray_by_cvt; cvtColor(original_image, gray_by_cvt, CV_BGR2GRAY); Mat diff; absdiff(gray_by_codec, gray_by_cvt, diff); double actual_avg_diff = (double)mean(diff)[0]; double actual_maxval, actual_minval; minMaxLoc(diff, &actual_minval, &actual_maxval); //printf("actual avg = %g, actual maxdiff = %g, npixels = %d\n", actual_avg_diff, actual_maxval, (int)diff.total()); EXPECT_LT(actual_avg_diff, MAX_MEAN_DIFF); EXPECT_LT(actual_maxval, MAX_ABS_DIFF); } #endif #ifdef HAVE_JPEG TEST(Highgui_Jpeg, encode_empty) { cv::Mat img; std::vector<uchar> jpegImg; ASSERT_THROW(cv::imencode(".jpg", img, jpegImg), cv::Exception); } #endif #ifdef HAVE_TIFF // these defines are used to resolve conflict between tiff.h and opencv2/core/types_c.h #define uint64 uint64_hack_ #define int64 int64_hack_ #include "tiff.h" TEST(Highgui_Tiff, decode_tile16384x16384) { // see issue #2161 cv::Mat big(16384, 16384, CV_8UC1, cv::Scalar::all(0)); string file3 = cv::tempfile(".tiff"); string file4 = cv::tempfile(".tiff"); std::vector<int> params; params.push_back(TIFFTAG_ROWSPERSTRIP); params.push_back(big.rows); cv::imwrite(file4, big, params); cv::imwrite(file3, big.colRange(0, big.cols - 1), params); big.release(); try { cv::imread(file3); EXPECT_NO_THROW(cv::imread(file4)); } catch(const std::bad_alloc&) { // have no enough memory } remove(file3.c_str()); remove(file4.c_str()); } #endif <commit_msg>* img_test is now tested for channel numbers instead of img * fixed indentation to use spaces and trailing spaces<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/highgui/highgui.hpp" using namespace cv; using namespace std; class CV_GrfmtWriteBigImageTest : public cvtest::BaseTest { public: void run(int) { try { ts->printf(cvtest::TS::LOG, "start reading big image\n"); Mat img = imread(string(ts->get_data_path()) + "readwrite/read.png"); ts->printf(cvtest::TS::LOG, "finish reading big image\n"); if (img.empty()) ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); ts->printf(cvtest::TS::LOG, "start writing big image\n"); imwrite(cv::tempfile(".png"), img); ts->printf(cvtest::TS::LOG, "finish writing big image\n"); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; string ext_from_int(int ext) { #ifdef HAVE_PNG if (ext == 0) return ".png"; #endif if (ext == 1) return ".bmp"; if (ext == 2) return ".pgm"; #ifdef HAVE_TIFF if (ext == 3) return ".tiff"; #endif return ""; } class CV_GrfmtWriteSequenceImageTest : public cvtest::BaseTest { public: void run(int) { try { const int img_r = 640; const int img_c = 480; for (int k = 1; k <= 5; ++k) { for (int ext = 0; ext < 4; ++ext) // 0 - png, 1 - bmp, 2 - pgm, 3 - tiff { if(ext_from_int(ext).empty()) continue; for (int num_channels = 1; num_channels <= 3; num_channels+=2) { ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ext_from_int(ext).c_str()); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string img_path = cv::tempfile(ext_from_int(ext).c_str()); ts->printf(ts->LOG, "writing image : %s\n", img_path.c_str()); imwrite(img_path, img); ts->printf(ts->LOG, "reading test image : %s\n", img_path.c_str()); Mat img_test = imread(img_path, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } if (ext == 3 /*TIFF*/) { /* 4 channels should stay 4 channels */ int num_channels = 4; ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U,num_channels, ext_from_int(ext).c_str()); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string img_path = cv::tempfile(ext_from_int(ext).c_str()); ts->printf(ts->LOG, "writing image : %s\n", img_path.c_str()); imwrite(img_path, img); ts->printf(ts->LOG, "reading test image : %s\n", img_path.c_str()); Mat img_test = imread(img_path, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); CV_Assert(img_test.channels() == 4); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } } #ifdef HAVE_JPEG for (int num_channels = 1; num_channels <= 3; num_channels+=2) { // jpeg ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ".jpg"); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string filename = cv::tempfile(".jpg"); imwrite(filename, img); img = imread(filename, CV_LOAD_IMAGE_UNCHANGED); filename = string(ts->get_data_path() + "readwrite/test_" + char(k + 48) + "_c" + char(num_channels + 48) + ".jpg"); ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str()); Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } #endif #ifdef HAVE_TIFF for (int num_channels = 1; num_channels <= 3; num_channels+=2) { // tiff ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_16U, num_channels, ".tiff"); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_16U, num_channels), Scalar::all(0)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); string filename = cv::tempfile(".tiff"); imwrite(filename, img); ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str()); Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); CV_Assert(img.size() == img_test.size()); ts->printf(ts->LOG, "img : %d ; %d \n", img.channels(), img.depth()); ts->printf(ts->LOG, "img_test : %d ; %d \n", img_test.channels(), img_test.depth()); CV_Assert(img.type() == img_test.type()); double n = norm(img, img_test); if ( n > 1.0) { ts->printf(ts->LOG, "norm = %f \n", n); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } #endif } } catch(const cv::Exception & e) { ts->printf(ts->LOG, "Exception: %s\n" , e.what()); ts->set_failed_test_info(ts->FAIL_MISMATCH); } } }; class CV_GrfmtReadBMPRLE8Test : public cvtest::BaseTest { public: void run(int) { try { Mat rle = imread(string(ts->get_data_path()) + "readwrite/rle8.bmp"); Mat bmp = imread(string(ts->get_data_path()) + "readwrite/ordinary.bmp"); if (norm(rle-bmp)>1.e-10) ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; #ifdef HAVE_PNG TEST(Highgui_Image, write_big) { CV_GrfmtWriteBigImageTest test; test.safe_run(); } #endif TEST(Highgui_Image, write_imageseq) { CV_GrfmtWriteSequenceImageTest test; test.safe_run(); } TEST(Highgui_Image, read_bmp_rle8) { CV_GrfmtReadBMPRLE8Test test; test.safe_run(); } #ifdef HAVE_PNG class CV_GrfmtPNGEncodeTest : public cvtest::BaseTest { public: void run(int) { try { vector<uchar> buff; Mat im = Mat::zeros(1000,1000, CV_8U); //randu(im, 0, 256); vector<int> param; param.push_back(CV_IMWRITE_PNG_COMPRESSION); param.push_back(3); //default(3) 0-9. cv::imencode(".png" ,im ,buff, param); // hangs Mat im2 = imdecode(buff,CV_LOAD_IMAGE_ANYDEPTH); } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } }; TEST(Highgui_Image, encode_png) { CV_GrfmtPNGEncodeTest test; test.safe_run(); } TEST(Highgui_ImreadVSCvtColor, regression) { cvtest::TS& ts = *cvtest::TS::ptr(); const int MAX_MEAN_DIFF = 1; const int MAX_ABS_DIFF = 10; string imgName = string(ts.get_data_path()) + "/../cv/shared/lena.png"; Mat original_image = imread(imgName); Mat gray_by_codec = imread(imgName, 0); Mat gray_by_cvt; cvtColor(original_image, gray_by_cvt, CV_BGR2GRAY); Mat diff; absdiff(gray_by_codec, gray_by_cvt, diff); double actual_avg_diff = (double)mean(diff)[0]; double actual_maxval, actual_minval; minMaxLoc(diff, &actual_minval, &actual_maxval); //printf("actual avg = %g, actual maxdiff = %g, npixels = %d\n", actual_avg_diff, actual_maxval, (int)diff.total()); EXPECT_LT(actual_avg_diff, MAX_MEAN_DIFF); EXPECT_LT(actual_maxval, MAX_ABS_DIFF); } #endif #ifdef HAVE_JPEG TEST(Highgui_Jpeg, encode_empty) { cv::Mat img; std::vector<uchar> jpegImg; ASSERT_THROW(cv::imencode(".jpg", img, jpegImg), cv::Exception); } #endif #ifdef HAVE_TIFF // these defines are used to resolve conflict between tiff.h and opencv2/core/types_c.h #define uint64 uint64_hack_ #define int64 int64_hack_ #include "tiff.h" TEST(Highgui_Tiff, decode_tile16384x16384) { // see issue #2161 cv::Mat big(16384, 16384, CV_8UC1, cv::Scalar::all(0)); string file3 = cv::tempfile(".tiff"); string file4 = cv::tempfile(".tiff"); std::vector<int> params; params.push_back(TIFFTAG_ROWSPERSTRIP); params.push_back(big.rows); cv::imwrite(file4, big, params); cv::imwrite(file3, big.colRange(0, big.cols - 1), params); big.release(); try { cv::imread(file3); EXPECT_NO_THROW(cv::imread(file4)); } catch(const std::bad_alloc&) { // have no enough memory } remove(file3.c_str()); remove(file4.c_str()); } #endif <|endoftext|>
<commit_before>// Copyright 2016 Google Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <google_smart_card_pcsc_lite_server/global.h> #include <stdint.h> #include <sys/stat.h> #include <sys/types.h> #include <string> #include <thread> #include <utility> extern "C" { #include "winscard.h" #include "debuglog.h" #include "hotplug.h" #include "readerfactory.h" #include "sys_generic.h" #include "winscard_svc.h" } #include <google_smart_card_common/ipc_emulation.h> #include <google_smart_card_common/logging/logging.h> #include <google_smart_card_common/messaging/typed_message.h> #include <google_smart_card_common/value.h> #include <google_smart_card_common/value_conversion.h> #include "server_sockets_manager.h" // Old versions of Emscripten have buggy multi-threading - so bail out if the // developer still hasn't updated their local Emscripten version. #ifdef __EMSCRIPTEN__ #if __EMSCRIPTEN_major__ < 2 || \ (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \ __EMSCRIPTEN_tiny__ < 31) #error "Emscripten >=2.0.31 must be used" #endif #endif // __EMSCRIPTEN__ namespace google_smart_card { namespace { PcscLiteServerGlobal* g_pcsc_lite_server = nullptr; constexpr char kLoggingPrefix[] = "[PC/SC-Lite NaCl port] "; // Constants for message types that are sent to the JavaScript side. These // strings must match the ones in reader-tracker.js. constexpr char kReaderInitAddMessageType[] = "reader_init_add"; constexpr char kReaderFinishAddMessageType[] = "reader_finish_add"; constexpr char kReaderRemoveMessageType[] = "reader_remove"; // Message data for the message that notifies the JavaScript side that a reader // is being added by the PC/SC-Lite daemon. struct ReaderInitAddMessageData { std::string reader_name; int port; std::string device; }; // Message data for the message that notifies the JavaScript side that a reader // is completely added by the PC/SC-Lite daemon. struct ReaderFinishAddMessageData { std::string reader_name; int port; std::string device; long return_code; }; // Message data for the message that notifies the JavaScript side that a reader // is removed by the PC/SC-Lite daemon. struct ReaderRemoveMessageData { std::string reader_name; int port; }; void PcscLiteServerDaemonThreadMain() { // TODO(emaxx): Stop the event loop during pp::Instance destruction. while (true) { GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "[daemon thread] " << "Waiting for the new connected clients..."; uint32_t server_socket_file_descriptor = static_cast<uint32_t>( PcscLiteServerSocketsManager::GetInstance()->WaitAndPop()); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "[daemon thread] A new " << "client was connected, starting a handler thread..."; // Note: even though the CreateContextThread function accepts its // server_socket_file_descriptor argument by pointer, it doesn't store the // pointer itself anywhere - so it's safe to use a local variable here. // FIXME(emaxx): Deal with cases when CreateContextThread returns errors. // Looks like it may happen legitimately when the abusive client(s) request // to establish too many requests. Probably, some limitation should be // applied to all clients. GOOGLE_SMART_CARD_CHECK( ::CreateContextThread(&server_socket_file_descriptor) == SCARD_S_SUCCESS); } } } // namespace template <> StructValueDescriptor<ReaderInitAddMessageData>::Description StructValueDescriptor<ReaderInitAddMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderInitAddMessageData") .WithField(&ReaderInitAddMessageData::reader_name, "readerName") .WithField(&ReaderInitAddMessageData::port, "port") .WithField(&ReaderInitAddMessageData::device, "device"); } template <> StructValueDescriptor<ReaderFinishAddMessageData>::Description StructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderFinishAddMessageData") .WithField(&ReaderFinishAddMessageData::reader_name, "readerName") .WithField(&ReaderFinishAddMessageData::port, "port") .WithField(&ReaderFinishAddMessageData::device, "device") .WithField(&ReaderFinishAddMessageData::return_code, "returnCode"); } template <> StructValueDescriptor<ReaderRemoveMessageData>::Description StructValueDescriptor<ReaderRemoveMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderRemoveMessageData") .WithField(&ReaderRemoveMessageData::reader_name, "readerName") .WithField(&ReaderRemoveMessageData::port, "port"); } PcscLiteServerGlobal::PcscLiteServerGlobal(GlobalContext* global_context) : global_context_(global_context) { GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server); g_pcsc_lite_server = this; } PcscLiteServerGlobal::~PcscLiteServerGlobal() { GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this); g_pcsc_lite_server = nullptr; } // static const PcscLiteServerGlobal* PcscLiteServerGlobal::GetInstance() { GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server); return g_pcsc_lite_server; } void PcscLiteServerGlobal::InitializeAndRunDaemonThread() { GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initialization..."; IpcEmulation::CreateGlobalInstance(); PcscLiteServerSocketsManager::CreateGlobalInstance(); ::SYS_InitRandom(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Setting up PC/SC-Lite " << "logging..."; ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG); #ifdef NDEBUG ::DebugLogSetLevel(PCSC_LOG_ERROR); #else ::DebugLogSetLevel(PCSC_LOG_DEBUG); ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW); #endif GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "PC/SC-Lite logging was " << "set up."; LONG return_code; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Allocating reader " << "structures..."; return_code = ::RFAllocateReaderSpace(0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Reader structures " << "allocation finished with the following result: \"" << ::pcsc_stringify_error(return_code) << "\"."; GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Performing initial hot " << "plug drivers search..."; return_code = ::HPSearchHotPluggables(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initial hot plug " << "drivers search finished with the following result code: " << return_code << "."; GOOGLE_SMART_CARD_CHECK(return_code == 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Registering for hot " << "plug events..."; // FIXME(emaxx): Currently this ends up on polling the libusb each second, as // it doesn't provide any way to subscribe for the device list change. But // it's possible to optimize this onto publisher-pattern-style implementation, // by handling the chrome.usb API events (see // <https://developer.chrome.com/apps/usb#Events>) and using them in a // replacement implementation of the currently used original hotplug_libusb.c // source file. return_code = ::HPRegisterForHotplugEvents(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Registering for hot " << "plug events finished with the following result code: " << return_code << "."; GOOGLE_SMART_CARD_CHECK(return_code == 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Allocating client " << "structures..."; return_code = ::ContextsInitialize(0, 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Client structures " << "allocation finished with the following result code: " << return_code << "..."; GOOGLE_SMART_CARD_CHECK(return_code == 1); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Waiting for the readers " << "initialization..."; ::RFWaitForReaderInit(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Waiting for the readers " << "initialization finished."; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Starting PC/SC-Lite " << "daemon thread..."; std::thread daemon_thread(PcscLiteServerDaemonThreadMain); daemon_thread.detach(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "PC/SC-Lite daemon " << "thread has started."; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initialization " << "successfully finished."; } void PcscLiteServerGlobal::PostReaderInitAddMessage(const char* reader_name, int port, const char* device) const { ReaderInitAddMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; message_data.device = device; PostMessage(kReaderInitAddMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostReaderFinishAddMessage(const char* reader_name, int port, const char* device, long return_code) const { ReaderFinishAddMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; message_data.device = device; message_data.return_code = return_code; PostMessage(kReaderFinishAddMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostReaderRemoveMessage(const char* reader_name, int port) const { ReaderRemoveMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; PostMessage(kReaderRemoveMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostMessage(const char* type, Value message_data) const { TypedMessage typed_message; typed_message.type = type; typed_message.data = std::move(message_data); global_context_->PostMessageToJs( ConvertToValueOrDie(std::move(typed_message))); } } // namespace google_smart_card <commit_msg>Fix preprocessor issue with PC/SC and std headers (#557)<commit_after>// Copyright 2016 Google Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <google_smart_card_pcsc_lite_server/global.h> #include <stdint.h> #include <sys/stat.h> #include <sys/types.h> #include <string> #include <thread> #include <utility> #include <google_smart_card_common/ipc_emulation.h> #include <google_smart_card_common/logging/logging.h> #include <google_smart_card_common/messaging/typed_message.h> #include <google_smart_card_common/value.h> #include <google_smart_card_common/value_conversion.h> #include "server_sockets_manager.h" // Include the C headers after all other includes, because the preprocessor // definitions from them interfere with the symbols from the standard C++ // library. extern "C" { #include "winscard.h" #include "debuglog.h" #include "hotplug.h" #include "readerfactory.h" #include "sys_generic.h" #include "winscard_svc.h" } // Old versions of Emscripten have buggy multi-threading - so bail out if the // developer still hasn't updated their local Emscripten version. #ifdef __EMSCRIPTEN__ #if __EMSCRIPTEN_major__ < 2 || \ (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \ __EMSCRIPTEN_tiny__ < 31) #error "Emscripten >=2.0.31 must be used" #endif #endif // __EMSCRIPTEN__ namespace google_smart_card { namespace { PcscLiteServerGlobal* g_pcsc_lite_server = nullptr; constexpr char kLoggingPrefix[] = "[PC/SC-Lite NaCl port] "; // Constants for message types that are sent to the JavaScript side. These // strings must match the ones in reader-tracker.js. constexpr char kReaderInitAddMessageType[] = "reader_init_add"; constexpr char kReaderFinishAddMessageType[] = "reader_finish_add"; constexpr char kReaderRemoveMessageType[] = "reader_remove"; // Message data for the message that notifies the JavaScript side that a reader // is being added by the PC/SC-Lite daemon. struct ReaderInitAddMessageData { std::string reader_name; int port; std::string device; }; // Message data for the message that notifies the JavaScript side that a reader // is completely added by the PC/SC-Lite daemon. struct ReaderFinishAddMessageData { std::string reader_name; int port; std::string device; long return_code; }; // Message data for the message that notifies the JavaScript side that a reader // is removed by the PC/SC-Lite daemon. struct ReaderRemoveMessageData { std::string reader_name; int port; }; void PcscLiteServerDaemonThreadMain() { // TODO(emaxx): Stop the event loop during pp::Instance destruction. while (true) { GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "[daemon thread] " << "Waiting for the new connected clients..."; uint32_t server_socket_file_descriptor = static_cast<uint32_t>( PcscLiteServerSocketsManager::GetInstance()->WaitAndPop()); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "[daemon thread] A new " << "client was connected, starting a handler thread..."; // Note: even though the CreateContextThread function accepts its // server_socket_file_descriptor argument by pointer, it doesn't store the // pointer itself anywhere - so it's safe to use a local variable here. // FIXME(emaxx): Deal with cases when CreateContextThread returns errors. // Looks like it may happen legitimately when the abusive client(s) request // to establish too many requests. Probably, some limitation should be // applied to all clients. GOOGLE_SMART_CARD_CHECK( ::CreateContextThread(&server_socket_file_descriptor) == SCARD_S_SUCCESS); } } } // namespace template <> StructValueDescriptor<ReaderInitAddMessageData>::Description StructValueDescriptor<ReaderInitAddMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderInitAddMessageData") .WithField(&ReaderInitAddMessageData::reader_name, "readerName") .WithField(&ReaderInitAddMessageData::port, "port") .WithField(&ReaderInitAddMessageData::device, "device"); } template <> StructValueDescriptor<ReaderFinishAddMessageData>::Description StructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderFinishAddMessageData") .WithField(&ReaderFinishAddMessageData::reader_name, "readerName") .WithField(&ReaderFinishAddMessageData::port, "port") .WithField(&ReaderFinishAddMessageData::device, "device") .WithField(&ReaderFinishAddMessageData::return_code, "returnCode"); } template <> StructValueDescriptor<ReaderRemoveMessageData>::Description StructValueDescriptor<ReaderRemoveMessageData>::GetDescription() { // Note: Strings passed to WithField() below must match the property names in // reader-tracker.js. return Describe("ReaderRemoveMessageData") .WithField(&ReaderRemoveMessageData::reader_name, "readerName") .WithField(&ReaderRemoveMessageData::port, "port"); } PcscLiteServerGlobal::PcscLiteServerGlobal(GlobalContext* global_context) : global_context_(global_context) { GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server); g_pcsc_lite_server = this; } PcscLiteServerGlobal::~PcscLiteServerGlobal() { GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this); g_pcsc_lite_server = nullptr; } // static const PcscLiteServerGlobal* PcscLiteServerGlobal::GetInstance() { GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server); return g_pcsc_lite_server; } void PcscLiteServerGlobal::InitializeAndRunDaemonThread() { GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initialization..."; IpcEmulation::CreateGlobalInstance(); PcscLiteServerSocketsManager::CreateGlobalInstance(); ::SYS_InitRandom(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Setting up PC/SC-Lite " << "logging..."; ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG); #ifdef NDEBUG ::DebugLogSetLevel(PCSC_LOG_ERROR); #else ::DebugLogSetLevel(PCSC_LOG_DEBUG); ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW); #endif GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "PC/SC-Lite logging was " << "set up."; LONG return_code; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Allocating reader " << "structures..."; return_code = ::RFAllocateReaderSpace(0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Reader structures " << "allocation finished with the following result: \"" << ::pcsc_stringify_error(return_code) << "\"."; GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Performing initial hot " << "plug drivers search..."; return_code = ::HPSearchHotPluggables(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initial hot plug " << "drivers search finished with the following result code: " << return_code << "."; GOOGLE_SMART_CARD_CHECK(return_code == 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Registering for hot " << "plug events..."; // FIXME(emaxx): Currently this ends up on polling the libusb each second, as // it doesn't provide any way to subscribe for the device list change. But // it's possible to optimize this onto publisher-pattern-style implementation, // by handling the chrome.usb API events (see // <https://developer.chrome.com/apps/usb#Events>) and using them in a // replacement implementation of the currently used original hotplug_libusb.c // source file. return_code = ::HPRegisterForHotplugEvents(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Registering for hot " << "plug events finished with the following result code: " << return_code << "."; GOOGLE_SMART_CARD_CHECK(return_code == 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Allocating client " << "structures..."; return_code = ::ContextsInitialize(0, 0); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Client structures " << "allocation finished with the following result code: " << return_code << "..."; GOOGLE_SMART_CARD_CHECK(return_code == 1); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Waiting for the readers " << "initialization..."; ::RFWaitForReaderInit(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Waiting for the readers " << "initialization finished."; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Starting PC/SC-Lite " << "daemon thread..."; std::thread daemon_thread(PcscLiteServerDaemonThreadMain); daemon_thread.detach(); GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "PC/SC-Lite daemon " << "thread has started."; GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << "Initialization " << "successfully finished."; } void PcscLiteServerGlobal::PostReaderInitAddMessage(const char* reader_name, int port, const char* device) const { ReaderInitAddMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; message_data.device = device; PostMessage(kReaderInitAddMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostReaderFinishAddMessage(const char* reader_name, int port, const char* device, long return_code) const { ReaderFinishAddMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; message_data.device = device; message_data.return_code = return_code; PostMessage(kReaderFinishAddMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostReaderRemoveMessage(const char* reader_name, int port) const { ReaderRemoveMessageData message_data; message_data.reader_name = reader_name; message_data.port = port; PostMessage(kReaderRemoveMessageType, ConvertToValueOrDie(std::move(message_data))); } void PcscLiteServerGlobal::PostMessage(const char* type, Value message_data) const { TypedMessage typed_message; typed_message.type = type; typed_message.data = std::move(message_data); global_context_->PostMessageToJs( ConvertToValueOrDie(std::move(typed_message))); } } // namespace google_smart_card <|endoftext|>
<commit_before>#include "MLP.h" MLP::MLP() { //ctor } MLP::MLP(int h1pNo, int h2pNo, double qtty, int maxIter, bool validationMethod) { //no of neurons in hidden layer h1No = h1pNo; h2No = h2pNo; // param = qtty; // this->dL = dL; //learning // this->dT = dT; //testing // this->decay = wDecay; this->maxIter = maxIter; this->kFoldValidation = validationMethod; alglib::mlpcreatetrainercls(X.getObjectAt(0).getFeatureCount(), X.getClassCount(), trn); //qtt of input features, number of classes to be produced double wstep = 0.000; mlpsetdecay(trn, 0.001); // by default we set moderate weight decay mlpsetcond(trn, wstep, this->maxIter); // * we choose iterations limit as stopping condition (another condition - step size - is zero, which means than this condition is not active) alglib::mlpcreatec2(X.getObjectAt(0).getFeatureCount(), h1No, h2No, X.getClassCount(), network); //create nn network with noofinput features, 2 hidden layers, noofclasses (and sore to network variable) if (this->kFoldValidation == true) //do kfold validation { ClusterizationMethods::initializeData(); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlpkfoldcv(trn, network, 1, int(qtty), rep); } else { ClusterizationMethods::initializeData(qtty, 100 - qtty); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlptrainnetwork(trn, network, 1, rep); // train network NRestarts=1, network is trained from random initial state. With NRestarts=0, network is trained without randomization (original state is used as initial point). alglib::integer_1d_array Subset; Subset.setlength(10); alglib::mlpallerrorssubset(network, testSet, testObjQtty, Subset, -1, repp); } //ctor // now get network error // do not calculate cross-validation since it validates the topology of the network } MLP::~MLP() { //dtor } ObjectMatrix MLP::getProjection() { //int cols = X.getClassCount(); int ftCount = X.getObjectAt(0).getFeatureCount(); int objCount = X.getObjectCount(); initializeYMatrix(objCount, ftCount + X.getClassCount()); alglib::real_1d_array tmpYObj; alglib::real_1d_array tmpXObj; tmpYObj.setlength(ftCount); tmpXObj.setlength(X.getClassCount()); DataObject tmpO; for (int i = 0; i < objCount; i++) { tmpO = X.getObjectAt(i); for (int ft = 0; ft < ftCount; ft++) { double feature = tmpO.getFeatureAt(ft); tmpYObj(ft) = feature; Y.updateDataObject(i, ft, feature); } alglib::mlpprocess(network, tmpYObj, tmpXObj); double max_prob = tmpXObj(0); int indx = 0; for (int j = 0; j < X.getClassCount(); j++) { Y.updateDataObject(i, j + ftCount, tmpXObj(j)); if (max_prob < tmpXObj(j)) { max_prob = tmpXObj(j); indx = j; } } if (tmpO.getClassLabel() != -1) Y.updateDataObjectClass(i, tmpO.getClassLabel()); else Y.updateDataObjectClass(i, indx); } std::vector <std::string > probabilities; probabilities.reserve(0); for (int i = 0; i < X.getClassCount(); i++) probabilities.push_back("probability_" + X.getStringClassAttributes().at(i)); Y.addAtributes(probabilities); Y.setPrintClass(X.getStringClassAttributes()); return Y; } double MLP::getStress() { if (this->kFoldValidation) { return rep.avgrelerror; } else { return repp.avgrelerror; } //} /* * Rep.RelCLSError - fraction of misclassified cases. * Rep.AvgCE - acerage cross-entropy * Rep.RMSError - root-mean-square error * Rep.AvgError - average error * Rep.AvgRelError - average relative error */ return rep.rmserror; } <commit_msg>Updated MLP network construction regarding passed parameters<commit_after>#include "MLP.h" MLP::MLP() { //ctor } MLP::MLP(int h1pNo, int h2pNo, double qtty, int maxIter, bool validationMethod) { //no of neurons in hidden layer h1No = h1pNo; h2No = h2pNo; // param = qtty; // this->dL = dL; //learning // this->dT = dT; //testing // this->decay = wDecay; this->maxIter = maxIter; this->kFoldValidation = validationMethod; alglib::mlpcreatetrainercls(X.getObjectAt(0).getFeatureCount(), X.getClassCount(), trn); //qtt of input features, number of classes to be produced double wstep = 0.000; mlpsetdecay(trn, 0.001); // by default we set moderate weight decay mlpsetcond(trn, wstep, this->maxIter); // * we choose iterations limit as stopping condition (another condition - step size - is zero, which means than this condition is not active) if ((h1No > 0) && (h2No > 0)) alglib::mlpcreatec2(X.getObjectAt(0).getFeatureCount(), h1No, h2No, X.getClassCount(), network); //create nn network with noofinput features, 2 hidden layers, noofclasses (and sore to network variable) if ((h1No > 0) && (h2No == 0)) alglib::mlpcreatec1(X.getObjectAt(0).getFeatureCount(), h1No, X.getClassCount(), network); //create nn network with no of input features, 1 hidden layer, noofclasses (and sore to network variable) if ((h1No == 0) && (h2No == 0)) alglib::mlpcreatec0(X.getObjectAt(0).getFeatureCount(), X.getClassCount(), network); //create nn network with no of input features, 0 hidden layer, noofclasses (and sore to network variable) ///h2No must be non zero if (this->kFoldValidation == true) //do kfold validation { ClusterizationMethods::initializeData(); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlpkfoldcv(trn, network, 1, int(qtty), rep); } else { ClusterizationMethods::initializeData(qtty, 100 - qtty); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlptrainnetwork(trn, network, 1, rep); // train network NRestarts=1, network is trained from random initial state. With NRestarts=0, network is trained without randomization (original state is used as initial point). alglib::integer_1d_array Subset; Subset.setlength(10); alglib::mlpallerrorssubset(network, testSet, testObjQtty, Subset, -1, repp); } //ctor // now get network error // do not calculate cross-validation since it validates the topology of the network } MLP::~MLP() { //dtor } ObjectMatrix MLP::getProjection() { //int cols = X.getClassCount(); int ftCount = X.getObjectAt(0).getFeatureCount(); int objCount = X.getObjectCount(); initializeYMatrix(objCount, ftCount + X.getClassCount()); alglib::real_1d_array tmpYObj; alglib::real_1d_array tmpXObj; tmpYObj.setlength(ftCount); tmpXObj.setlength(X.getClassCount()); DataObject tmpO; for (int i = 0; i < objCount; i++) { tmpO = X.getObjectAt(i); for (int ft = 0; ft < ftCount; ft++) { double feature = tmpO.getFeatureAt(ft); tmpYObj(ft) = feature; Y.updateDataObject(i, ft, feature); } alglib::mlpprocess(network, tmpYObj, tmpXObj); double max_prob = tmpXObj(0); int indx = 0; for (int j = 0; j < X.getClassCount(); j++) { Y.updateDataObject(i, j + ftCount, tmpXObj(j)); if (max_prob < tmpXObj(j)) { max_prob = tmpXObj(j); indx = j; } } if (tmpO.getClassLabel() != -1) Y.updateDataObjectClass(i, tmpO.getClassLabel()); else Y.updateDataObjectClass(i, indx); } std::vector <std::string > probabilities; probabilities.reserve(0); for (int i = 0; i < X.getClassCount(); i++) probabilities.push_back("probClass" + X.getStringClassAttributes().at(i)); Y.addAtributes(probabilities); Y.setPrintClass(X.getStringClassAttributes()); return Y; } double MLP::getStress() { if (this->kFoldValidation) { return rep.avgrelerror; } else { return repp.avgrelerror; } //} /* * Rep.RelCLSError - fraction of misclassified cases. * Rep.AvgCE - acerage cross-entropy * Rep.RMSError - root-mean-square error * Rep.AvgError - average error * Rep.AvgRelError - average relative error */ return rep.rmserror; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellheadergenerator.h" #include "fileout.h" #include <QtCore/QDir> #include <qdebug.h> QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const { return QString("PythonQtWrapper_%1.h").arg(meta_class->name()); } void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field) { const AbstractMetaFunction *setter = field->setter(); const AbstractMetaFunction *getter = field->getter(); // static fields are not supported (yet?) if (setter->isStatic()) return; // Uuid data4 did not work (TODO: move to typesystem...( if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return; if (field->enclosingClass()->name()=="QIPv6Address") return; if (!field->type()->isConstant()) { writeFunctionSignature(s, setter, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces)); s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n"; } writeFunctionSignature(s, getter, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << "{ return theWrappedObject->" << field->name() << "; }\n"; } void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class) { QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":""; QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri"; priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class)); setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class); QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H"; s << "#ifndef " << include_block << endl << "#define " << include_block << endl << endl; Include inc = meta_class->typeEntry()->include(); ShellGenerator::writeInclude(s, inc); s << "#include <QObject>" << endl << endl; s << "#include <PythonQt.h>" << endl << endl; IncludeList list = meta_class->typeEntry()->extraIncludes(); qSort(list.begin(), list.end()); foreach (const Include &inc, list) { ShellGenerator::writeInclude(s, inc); } s << endl; AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang); if (meta_class->qualifiedCppName().contains("Ssl")) { s << "#ifndef QT_NO_OPENSSL" << endl; } // Shell------------------------------------------------------------------- if (meta_class->generateShellClass()) { AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class); s << "class " << shellClassName(meta_class) << " : public " << meta_class->qualifiedCppName() << endl << "{" << endl; s << "public:" << endl; foreach(AbstractMetaFunction* fun, ctors) { s << " "; writeFunctionSignature(s, fun, 0,"PythonQtShell_", Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ":" << meta_class->qualifiedCppName() << "("; QString scriptFunctionName = fun->originalName(); AbstractMetaArgumentList args = fun->arguments(); for (int i = 0; i < args.size(); ++i) { if (i > 0) s << ", "; s << args.at(i)->argumentName(); } s << "),_wrapper(NULL) {};" << endl; } s << endl; s << " ~" << shellClassName(meta_class) << "();" << endl; foreach(AbstractMetaFunction* fun, virtualsForShell) { s << "virtual "; writeFunctionSignature(s, fun, 0, QString(), Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ";" << endl; } s << endl; s << " PythonQtInstanceWrapper* _wrapper; " << endl; s << "};" << endl << endl; } // Promoter------------------------------------------------------------------- AbstractMetaFunctionList promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class); if (!promoteFunctions.isEmpty()) { s << "class " << promoterClassName(meta_class) << " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl; foreach(AbstractMetaFunction* fun, promoteFunctions) { s << "inline "; writeFunctionSignature(s, fun, 0, "promoted_", Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << " { "; QString scriptFunctionName = fun->originalName(); AbstractMetaArgumentList args = fun->arguments(); if (fun->type()) s << "return "; s << meta_class->qualifiedCppName() << "::"; s << fun->originalName() << "("; for (int i = 0; i < args.size(); ++i) { if (i > 0) s << ", "; s << args.at(i)->argumentName(); } s << "); }" << endl; } s << "};" << endl << endl; } // Wrapper------------------------------------------------------------------- s << "class " << wrapperClassName(meta_class) << " : public QObject" << endl << "{ Q_OBJECT" << endl; s << "public:" << endl; AbstractMetaEnumList enums1 = meta_class->enums(); AbstractMetaEnumList enums; QList<FlagsTypeEntry*> flags; foreach(AbstractMetaEnum* enum1, enums1) { // catch gadgets and enums that are not exported on QObjects... if (enum1->wasPublic() && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) { enums << enum1; if (enum1->typeEntry()->flags()) { flags << enum1->typeEntry()->flags(); } } } if (enums.count()) { s << "Q_ENUMS("; foreach(AbstractMetaEnum* enum1, enums) { s << enum1->name() << " "; } s << ")" << endl; if (flags.count()) { s << "Q_FLAGS("; foreach(FlagsTypeEntry* flag1, flags) { QString origName = flag1->originalName(); int idx = origName.lastIndexOf("::"); if (idx!= -1) { origName = origName.mid(idx+2); } s << origName << " "; } s << ")" << endl; } foreach(AbstractMetaEnum* enum1, enums) { s << "enum " << enum1->name() << "{" << endl; bool first = true; foreach(AbstractMetaEnumValue* value, enum1->values()) { if (first) { first = false; } else { s << ", "; } s << " " << value->name() << " = " << meta_class->qualifiedCppName() << "::" << value->name(); } s << "};" << endl; } if (flags.count()) { foreach(AbstractMetaEnum* enum1, enums) { if (enum1->typeEntry()->flags()) { QString origName = enum1->typeEntry()->flags()->originalName(); int idx = origName.lastIndexOf("::"); if (idx!= -1) { origName = origName.mid(idx+2); } s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl; } } } } s << "public slots:" << endl; if (meta_class->generateShellClass() || !meta_class->isAbstract()) { bool copyConstructorSeen = false; bool defaultConstructorSeen = false; foreach (const AbstractMetaFunction *fun, ctors) { if (!fun->isPublic() || fun->isAbstract()) { continue; } s << meta_class->qualifiedCppName() << "* "; writeFunctionSignature(s, fun, 0, "new_", Option(IncludeDefaultExpression | OriginalName | ShowStatic)); s << ";" << endl; if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) { copyConstructorSeen = true; } if (fun->arguments().size()==0) { defaultConstructorSeen = true; } } if (meta_class->typeEntry()->isValue() && !copyConstructorSeen && defaultConstructorSeen) { QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName(); s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl; s << className << "* a = new " << className << "();" << endl; s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl; s << "return a; }" << endl; } } if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) { s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } "; s << endl; } AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class); foreach (const AbstractMetaFunction *function, functions) { if (!function->isSlot() || function->isVirtual()) { s << " "; writeFunctionSignature(s, function, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ";" << endl; } } if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) { s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl; } if (meta_class->hasDefaultIsNull()) { s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl; } // Field accessors foreach (const AbstractMetaField *field, meta_class->fields()) { if (field->isPublic()) { writeFieldAccessors(s, field); } } writeInjectedCode(s, meta_class); s << "};" << endl << endl; if (meta_class->qualifiedCppName().contains("Ssl")) { s << "#endif" << endl << endl; } s << "#endif // " << include_block << endl; } void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class) { CodeSnipList code_snips = meta_class->typeEntry()->codeSnips(); foreach (const CodeSnip &cs, code_snips) { if (cs.language == TypeSystem::PyWrapperDeclaration) { s << cs.code() << endl; } } } <commit_msg>readded linefeed<commit_after>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellheadergenerator.h" #include "fileout.h" #include <QtCore/QDir> #include <qdebug.h> QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const { return QString("PythonQtWrapper_%1.h").arg(meta_class->name()); } void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field) { const AbstractMetaFunction *setter = field->setter(); const AbstractMetaFunction *getter = field->getter(); // static fields are not supported (yet?) if (setter->isStatic()) return; // Uuid data4 did not work (TODO: move to typesystem...( if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return; if (field->enclosingClass()->name()=="QIPv6Address") return; if (!field->type()->isConstant()) { writeFunctionSignature(s, setter, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces)); s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n"; } writeFunctionSignature(s, getter, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << "{ return theWrappedObject->" << field->name() << "; }\n"; } void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class) { QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":""; QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri"; priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class)); setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class); QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H"; s << "#ifndef " << include_block << endl << "#define " << include_block << endl << endl; Include inc = meta_class->typeEntry()->include(); ShellGenerator::writeInclude(s, inc); s << "#include <QObject>" << endl << endl; s << "#include <PythonQt.h>" << endl << endl; IncludeList list = meta_class->typeEntry()->extraIncludes(); qSort(list.begin(), list.end()); foreach (const Include &inc, list) { ShellGenerator::writeInclude(s, inc); } s << endl; AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang); if (meta_class->qualifiedCppName().contains("Ssl")) { s << "#ifndef QT_NO_OPENSSL" << endl; } // Shell------------------------------------------------------------------- if (meta_class->generateShellClass()) { AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class); s << "class " << shellClassName(meta_class) << " : public " << meta_class->qualifiedCppName() << endl << "{" << endl; s << "public:" << endl; foreach(AbstractMetaFunction* fun, ctors) { s << " "; writeFunctionSignature(s, fun, 0,"PythonQtShell_", Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ":" << meta_class->qualifiedCppName() << "("; QString scriptFunctionName = fun->originalName(); AbstractMetaArgumentList args = fun->arguments(); for (int i = 0; i < args.size(); ++i) { if (i > 0) s << ", "; s << args.at(i)->argumentName(); } s << "),_wrapper(NULL) {};" << endl; } s << endl; s << " ~" << shellClassName(meta_class) << "();" << endl; s << endl; foreach(AbstractMetaFunction* fun, virtualsForShell) { s << "virtual "; writeFunctionSignature(s, fun, 0, QString(), Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ";" << endl; } s << endl; s << " PythonQtInstanceWrapper* _wrapper; " << endl; s << "};" << endl << endl; } // Promoter------------------------------------------------------------------- AbstractMetaFunctionList promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class); if (!promoteFunctions.isEmpty()) { s << "class " << promoterClassName(meta_class) << " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl; foreach(AbstractMetaFunction* fun, promoteFunctions) { s << "inline "; writeFunctionSignature(s, fun, 0, "promoted_", Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << " { "; QString scriptFunctionName = fun->originalName(); AbstractMetaArgumentList args = fun->arguments(); if (fun->type()) s << "return "; s << meta_class->qualifiedCppName() << "::"; s << fun->originalName() << "("; for (int i = 0; i < args.size(); ++i) { if (i > 0) s << ", "; s << args.at(i)->argumentName(); } s << "); }" << endl; } s << "};" << endl << endl; } // Wrapper------------------------------------------------------------------- s << "class " << wrapperClassName(meta_class) << " : public QObject" << endl << "{ Q_OBJECT" << endl; s << "public:" << endl; AbstractMetaEnumList enums1 = meta_class->enums(); AbstractMetaEnumList enums; QList<FlagsTypeEntry*> flags; foreach(AbstractMetaEnum* enum1, enums1) { // catch gadgets and enums that are not exported on QObjects... if (enum1->wasPublic() && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) { enums << enum1; if (enum1->typeEntry()->flags()) { flags << enum1->typeEntry()->flags(); } } } if (enums.count()) { s << "Q_ENUMS("; foreach(AbstractMetaEnum* enum1, enums) { s << enum1->name() << " "; } s << ")" << endl; if (flags.count()) { s << "Q_FLAGS("; foreach(FlagsTypeEntry* flag1, flags) { QString origName = flag1->originalName(); int idx = origName.lastIndexOf("::"); if (idx!= -1) { origName = origName.mid(idx+2); } s << origName << " "; } s << ")" << endl; } foreach(AbstractMetaEnum* enum1, enums) { s << "enum " << enum1->name() << "{" << endl; bool first = true; foreach(AbstractMetaEnumValue* value, enum1->values()) { if (first) { first = false; } else { s << ", "; } s << " " << value->name() << " = " << meta_class->qualifiedCppName() << "::" << value->name(); } s << "};" << endl; } if (flags.count()) { foreach(AbstractMetaEnum* enum1, enums) { if (enum1->typeEntry()->flags()) { QString origName = enum1->typeEntry()->flags()->originalName(); int idx = origName.lastIndexOf("::"); if (idx!= -1) { origName = origName.mid(idx+2); } s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl; } } } } s << "public slots:" << endl; if (meta_class->generateShellClass() || !meta_class->isAbstract()) { bool copyConstructorSeen = false; bool defaultConstructorSeen = false; foreach (const AbstractMetaFunction *fun, ctors) { if (!fun->isPublic() || fun->isAbstract()) { continue; } s << meta_class->qualifiedCppName() << "* "; writeFunctionSignature(s, fun, 0, "new_", Option(IncludeDefaultExpression | OriginalName | ShowStatic)); s << ";" << endl; if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) { copyConstructorSeen = true; } if (fun->arguments().size()==0) { defaultConstructorSeen = true; } } if (meta_class->typeEntry()->isValue() && !copyConstructorSeen && defaultConstructorSeen) { QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName(); s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl; s << className << "* a = new " << className << "();" << endl; s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl; s << "return a; }" << endl; } } if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) { s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } "; s << endl; } AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class); foreach (const AbstractMetaFunction *function, functions) { if (!function->isSlot() || function->isVirtual()) { s << " "; writeFunctionSignature(s, function, 0, QString(), Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces)); s << ";" << endl; } } if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) { s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl; } if (meta_class->hasDefaultIsNull()) { s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl; } // Field accessors foreach (const AbstractMetaField *field, meta_class->fields()) { if (field->isPublic()) { writeFieldAccessors(s, field); } } writeInjectedCode(s, meta_class); s << "};" << endl << endl; if (meta_class->qualifiedCppName().contains("Ssl")) { s << "#endif" << endl << endl; } s << "#endif // " << include_block << endl; } void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class) { CodeSnipList code_snips = meta_class->typeEntry()->codeSnips(); foreach (const CodeSnip &cs, code_snips) { if (cs.language == TypeSystem::PyWrapperDeclaration) { s << cs.code() << endl; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef PRINT_HH_ #define PRINT_HH_ #include <boost/format.hpp> #include <iostream> inline void apply_format(boost::format& fmt) { } template <typename A0, typename... Arest> inline void apply_format(boost::format& fmt, A0&& a0, Arest&&... arest) { apply_format(fmt % std::forward<A0>(a0), std::forward<Arest>(arest)...); } template <typename... A> std::ostream& fprint(std::ostream& os, boost::format& fmt, A&&... a) { apply_format(fmt, std::forward<A>(a)...); return os << fmt; } template <typename... A> void print(boost::format& fmt, A&&... a) { fprint(std::cout, fmt, std::forward<A>(a)...); } template <typename... A> std::ostream& fprint(std::ostream& os, const char* fmt, A&&... a) { boost::format bfmt(fmt); return fprint(os, bfmt, std::forward<A>(a)...); } template <typename... A> void print(const char* fmt, A&&... a) { boost::format bfmt(fmt); return print(bfmt, std::forward<A>(a)...); } template <typename... A> std::string sprint(const char* fmt, A&&... a) { boost::format bfmt(fmt); apply_format(bfmt, std::forward<A>(a)...); return bfmt.str(); } template <typename Iterator> std::string format_separated(Iterator b, Iterator e, const char* sep = ", ") { std::string ret; if (b == e) { return ret; } ret += *b++; while (b != e) { ret += sep; ret += *b++; } return ret; } #endif /* PRINT_HH_ */ <commit_msg>print: add log() function<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef PRINT_HH_ #define PRINT_HH_ #include <boost/format.hpp> #include <iostream> #include <iomanip> #include <chrono> inline void apply_format(boost::format& fmt) { } template <typename A0, typename... Arest> inline void apply_format(boost::format& fmt, A0&& a0, Arest&&... arest) { apply_format(fmt % std::forward<A0>(a0), std::forward<Arest>(arest)...); } template <typename... A> std::ostream& fprint(std::ostream& os, boost::format& fmt, A&&... a) { apply_format(fmt, std::forward<A>(a)...); return os << fmt; } template <typename... A> void print(boost::format& fmt, A&&... a) { fprint(std::cout, fmt, std::forward<A>(a)...); } template <typename... A> std::ostream& fprint(std::ostream& os, const char* fmt, A&&... a) { boost::format bfmt(fmt); return fprint(os, bfmt, std::forward<A>(a)...); } template <typename... A> void print(const char* fmt, A&&... a) { boost::format bfmt(fmt); return print(bfmt, std::forward<A>(a)...); } template <typename... A> std::string sprint(const char* fmt, A&&... a) { boost::format bfmt(fmt); apply_format(bfmt, std::forward<A>(a)...); return bfmt.str(); } template <typename Iterator> std::string format_separated(Iterator b, Iterator e, const char* sep = ", ") { std::string ret; if (b == e) { return ret; } ret += *b++; while (b != e) { ret += sep; ret += *b++; } return ret; } template <typename TimePoint> struct usecfmt_wrapper { TimePoint val; }; template <typename TimePoint> inline usecfmt_wrapper<TimePoint> usecfmt(TimePoint tp) { return { tp }; }; template <typename Clock, typename Rep, typename Period> std::ostream& operator<<(std::ostream& os, usecfmt_wrapper<std::chrono::time_point<Clock, std::chrono::duration<Rep, Period>>> tp) { auto usec = std::chrono::duration_cast<std::chrono::microseconds>(tp.val.time_since_epoch()).count(); std::ostream tmp(os.rdbuf()); tmp << std::setw(12) << (usec / 1000000) << "." << std::setw(6) << std::setfill('0') << (usec % 1000000); return os; } template <typename... A> void log(A&&... a) { std::cout << usecfmt(std::chrono::high_resolution_clock::now()) << " "; print(std::forward<A>(a)...); } #endif /* PRINT_HH_ */ <|endoftext|>
<commit_before>#include "source-manager.hpp" #include <pdal/Options.hpp> #include <pdal/Reader.hpp> #include <pdal/StageFactory.hpp> #include <entwine/types/bbox.hpp> #include <entwine/types/schema.hpp> #include <entwine/types/simple-point-table.hpp> #include <entwine/util/executor.hpp> SourceManager::SourceManager( pdal::StageFactory& stageFactory, std::mutex& factoryMutex, std::string path, std::string driver) : m_stageFactory(stageFactory) , m_factoryMutex(factoryMutex) , m_options(new pdal::Options()) , m_driver(driver) , m_schema(new entwine::Schema()) , m_bbox(new entwine::BBox()) , m_numPoints(0) { m_options->add(pdal::Option("filename", path)); // Use BBox::set() to avoid malformed BBox warning. m_bbox->set( entwine::Point( std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()), entwine::Point( std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest()), true); // Determine the number of points and the bounds for this resource. { entwine::DimList dims; const auto type(pdal::Dimension::Type::Double); dims.push_back(entwine::DimInfo("X", pdal::Dimension::Id::X, type)); dims.push_back(entwine::DimInfo("Y", pdal::Dimension::Id::Y, type)); dims.push_back(entwine::DimInfo("Z", pdal::Dimension::Id::Z, type)); entwine::Schema xyzSchema(dims); entwine::Executor executor(xyzSchema, true); auto bounder([this](pdal::PointView& view) { entwine::Point p; m_numPoints += view.size(); for (std::size_t i = 0; i < view.size(); ++i) { p.x = view.getFieldAs<double>(pdal::Dimension::Id::X, i); p.y = view.getFieldAs<double>(pdal::Dimension::Id::Y, i); p.z = view.getFieldAs<double>(pdal::Dimension::Id::Z, i); m_bbox->grow(p); } }); auto preview(executor.preview(path, nullptr, true)); if (preview) { m_srs = preview->srs; } if (!executor.run(path, nullptr, bounder)) { throw std::runtime_error("Could not execute resource: " + path); } } // Determine the native schema of the resource. { auto reader(createReader()); entwine::SimplePointTable pointTable(*m_schema); reader->prepare(pointTable); m_schema->finalize(); } } std::unique_ptr<pdal::Reader> SourceManager::createReader() { std::unique_lock<std::mutex> lock(m_factoryMutex); std::unique_ptr<pdal::Reader> reader( static_cast<pdal::Reader*>( m_stageFactory.createStage(m_driver))); lock.unlock(); reader->setOptions(*m_options); return reader; } <commit_msg>Update to different entwine API.<commit_after>#include "source-manager.hpp" #include <pdal/Options.hpp> #include <pdal/Reader.hpp> #include <pdal/StageFactory.hpp> #include <entwine/types/bbox.hpp> #include <entwine/types/schema.hpp> #include <entwine/types/simple-point-table.hpp> #include <entwine/util/executor.hpp> SourceManager::SourceManager( pdal::StageFactory& stageFactory, std::mutex& factoryMutex, std::string path, std::string driver) : m_stageFactory(stageFactory) , m_factoryMutex(factoryMutex) , m_options(new pdal::Options()) , m_driver(driver) , m_schema(new entwine::Schema()) , m_bbox(new entwine::BBox()) , m_numPoints(0) { m_options->add(pdal::Option("filename", path)); // Use BBox::set() to avoid malformed BBox warning. m_bbox->set( entwine::Point( std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()), entwine::Point( std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest()), true); // Determine the native schema of the resource. { auto reader(createReader()); entwine::DataPool dataPool(0); entwine::SimplePointTable pointTable(dataPool, *m_schema); reader->prepare(pointTable); m_schema->finalize(); } // Determine the number of points and the bounds for this resource. { entwine::DimList dims; const auto type(pdal::Dimension::Type::Double); dims.push_back(entwine::DimInfo("X", pdal::Dimension::Id::X, type)); dims.push_back(entwine::DimInfo("Y", pdal::Dimension::Id::Y, type)); dims.push_back(entwine::DimInfo("Z", pdal::Dimension::Id::Z, type)); entwine::Schema xyzSchema(dims); entwine::Executor executor(true); entwine::DataPool dataPool(m_schema->pointSize()); entwine::SimplePointTable table(dataPool, *m_schema); auto bounder([this, &table, &dataPool](pdal::PointView& view) { entwine::PooledDataStack stack; entwine::Point p; m_numPoints += view.size(); for (std::size_t i = 0; i < view.size(); ++i) { p.x = view.getFieldAs<double>(pdal::Dimension::Id::X, i); p.y = view.getFieldAs<double>(pdal::Dimension::Id::Y, i); p.z = view.getFieldAs<double>(pdal::Dimension::Id::Z, i); m_bbox->grow(p); stack.push(table.getNode(i)); } dataPool.release(stack); }); auto preview(executor.preview(path, nullptr, true)); if (preview) { m_srs = preview->srs; } if (!executor.run(table, path, nullptr, bounder)) { throw std::runtime_error("Could not execute resource: " + path); } } } std::unique_ptr<pdal::Reader> SourceManager::createReader() { std::unique_lock<std::mutex> lock(m_factoryMutex); std::unique_ptr<pdal::Reader> reader( static_cast<pdal::Reader*>( m_stageFactory.createStage(m_driver))); lock.unlock(); reader->setOptions(*m_options); return reader; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright 2014 Marcelo Sardelich <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include <iostream> #include <string> #include <exception> #include <stdexcept> #include <vector> #include <map> #include <cassert> #include "CJay.hpp" #define MAX_TOLERANCE 1.0e-4 using namespace VM; jint CJ::JNI_VERSION = JNI_VERSION_1_8; // Depends on installed JDK! int main (int argc, char* argv[]) { // Create JVM std::vector<std::string> paramVM{"-ea", "-Xdebug"}; VM::createVM(paramVM); //VM::createVM(); CJ CJ; // Set class try { CJ.setClass("example/Example"); } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Print signatures CJ.printSignatures(); // Call constructor try { CJ.Constructor("<init>"); // contructor has no parameters } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Instantiate caster Converter cnv; // Assertions try { jboolean Z = CJ.call<jboolean>( "parseBoolean", (jboolean) false ); assert (Z == false); jbyte B = CJ.call<jbyte>( "parseByte", (jbyte) 123 ); assert ( (int) B == 123); // convert from signed char to int jchar C = CJ.call<jchar>( "parseChar", (jchar) 'a' ); // single 16-bit unicode assert (C == 'a'); jshort S = CJ.call<jshort>( "parseShort", (jshort) -12 ); assert (S == -12); // coversion to int avoids lost precision jint I = CJ.call<jint>("parseInt", (jint) 123 ); assert (I == 123); jlong J = CJ.call<jlong>( "parseLong", (jlong) 123456 ); assert (J == 123456); jfloat F = CJ.call<float>( "parseFloat", (jfloat) 123.456 ); assert ( abs(F - (float) 123.456) <= MAX_TOLERANCE ); jdouble D = CJ.call<jdouble>( "parseDouble", (jdouble) 123.456789 ); assert ( abs(D - (double) 123.456789) <= MAX_TOLERANCE ); jobject L = CJ.call<jobject>( "parseString", cnv.j_cast<jstring>("foo") ); std::string str = cnv.c_cast<std::string>(L); // From java.lang.String To string assert ( str == std::string("foo") ); L = CJ.call<jobject>( "parseArrayListByte", (jbyte) 123, (jbyte) -123 ); std::vector<jbyte> vb = cnv.c_cast_vector<jbyte>(L, 2); // From java.lang.ArrayList<byte> To vector<jbyte> (or vector<signed char>) assert ( (int) vb[0] == 123 ); assert( (int) vb[1] == -123 ); // convert signed char to int L = CJ.call<jobject>( "parseArrayListInteger", (jint) 123, (jint) 456 ); std::vector<jint> vi = cnv.c_cast_vector<jint>(L, 2); // From ArrayList<Integer> To vector<jint> (or vector<long>) //std::cout << vi[0] << " " << vi[1] << std::endl; assert ( vi[0] == 123 ); assert( vi[1] == 456 ); L = CJ.call<jobject>( "parseArrayListLong", (jlong) 123456, (jlong) 123789 ); std::vector<jlong> vl = cnv.c_cast_vector<jlong>(L, 2); // From ArrayList<Long> To vector<jlong> (or vector<__int64>) assert ( vl[0] == 123456 ); assert( vl[1] == 123789 ); L = CJ.call<jobject>( "parseArrayListShort", (jshort) -12, (jshort) +13 ); std::vector<jshort> vs = cnv.c_cast_vector<jshort>(L, 2); // From ArrayList<Short> To vector<jshort> (or vector<short>) assert ( vs[0] == -12 ); assert( vs[1] == +13 ); L = CJ.call<jobject>( "parseArrayListFloat", (jfloat) -123.123, (jfloat) 123.145 ); std::vector<jfloat> vf = cnv.c_cast_vector<jfloat>(L, 2); // From ArrayList<Float> To vector<jfloat> (or vector<float>) assert ( abs(vf[0] - (float) -123.123) <= MAX_TOLERANCE ); assert ( abs(vf[1] - (float) 123.145) <= MAX_TOLERANCE ); L = CJ.call<jobject>( "parseArrayListDouble", (jdouble) 123.1234, (jdouble) -123.4567 ); std::vector<jdouble> vd = cnv.c_cast_vector<jdouble>(L, 2); // From ArrayList<Double> To vector<jdouble> (or vector<double>) assert ( abs(vd[0] - (double) 123.1234) <= MAX_TOLERANCE ); assert ( abs(vd[1] - (double) -123.4567) <= MAX_TOLERANCE ); L = CJ.call<jobject>( "parseArrayListString", cnv.j_cast<jstring>("foo") , cnv.j_cast<jstring>("bar")); std::vector<std::string> v_str = cnv.c_cast_vector<std::string>(L, 2); // From ArrayList<String> To vector<string> assert ( v_str[0] == "foo" ); assert( v_str[1] == "bar" ); L = CJ.call<jobject>( "parseSimpleMap", cnv.j_cast<jstring>("foo") , cnv.j_cast<jstring>("bar"), cnv.j_cast<jstring>("foo.bar")); std::map<std::string, std::string> m_str_str = cnv.c_cast_map<std::string, std::string>(L); // From java.util.Map<String, String> To std::map<string, string> assert ( m_str_str["arg 1"] == "foo" ); assert ( m_str_str["arg 2"] == "bar" ); assert ( m_str_str["arg 3"] == "foo.bar" ); } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Destroy VM VM::destroyVM(); return EXIT_SUCCESS; } <commit_msg>add jarray test<commit_after>/************************************************************************** * Copyright 2014 Marcelo Sardelich <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include <iostream> #include <string> #include <exception> #include <stdexcept> #include <vector> #include <map> #include <cassert> #include "CJay.hpp" #include "example/Example.hpp" #define MAX_TOLERANCE 1.0e-4 jint VM::CJ::JNI_VERSION = DEFAULT_JNI_VERSION; // Depends on installed JDK! using namespace VM; int main (int argc, char* argv[]) { // Create JVM std::vector<std::string> paramVM{"-ea", "-Xdebug"}; VM::createVM(paramVM); //VM::createVM(); CJ CJ; // Set class try { CJ.setClass("example/Example"); } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Print signatures CJ.printSignatures(); // Call constructor try { CJ.Constructor("<init>"); // contructor has no parameters } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Instantiate caster Converter cnv; // test try { cjay::example::Example example; jboolean test = example.parseBoolean((jboolean) false); assert (test == false); } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Assertions try { std::vector<jboolean> in {true, false}; jbooleanArray Za = CJ.call<jbooleanArray>( "parseArrayBoolean", cnv.j_cast<jbooleanArray>(in) ); std::vector<jboolean> vB = cnv.c_cast_array<jboolean>(Za); assert (vB[0] == true); assert (vB[1] == false); jboolean Z = CJ.call<jboolean>( "parseBoolean", (jboolean) false ); assert (Z == false); jbyte B = CJ.call<jbyte>( "parseByte", (jbyte) 123 ); assert ( (int) B == 123); // convert from signed char to int jchar C = CJ.call<jchar>( "parseChar", (jchar) 'a' ); // single 16-bit unicode assert (C == 'a'); jshort S = CJ.call<jshort>( "parseShort", (jshort) -12 ); assert (S == -12); // coversion to int avoids lost precision jint I = CJ.call<jint>("parseInt", (jint) 123 ); assert (I == 123); jlong J = CJ.call<jlong>( "parseLong", (jlong) 123456 ); assert (J == 123456); jfloat F = CJ.call<float>( "parseFloat", (jfloat) 123.456 ); assert ( abs(F - (float) 123.456) <= MAX_TOLERANCE ); jdouble D = CJ.call<jdouble>( "parseDouble", (jdouble) 123.456789 ); assert ( abs(D - (double) 123.456789) <= MAX_TOLERANCE ); jobject L = CJ.call<jobject>( "parseString", cnv.j_cast<jstring>("foo") ); std::string str = cnv.c_cast<std::string>(L); // From java.lang.String To string assert ( str == std::string("foo") ); L = CJ.call<jobject>( "parseArrayListByte", (jbyte) 123, (jbyte) -123 ); std::vector<jbyte> vb = cnv.c_cast_vector<jbyte>(L, 2); // From java.lang.ArrayList<byte> To vector<jbyte> (or vector<signed char>) assert ( (int) vb[0] == 123 ); assert( (int) vb[1] == -123 ); // convert signed char to int L = CJ.call<jobject>( "parseArrayListInteger", (jint) 123, (jint) 456 ); std::vector<jint> vi = cnv.c_cast_vector<jint>(L, 2); // From ArrayList<Integer> To vector<jint> (or vector<long>) //std::cout << vi[0] << " " << vi[1] << std::endl; assert ( vi[0] == 123 ); assert( vi[1] == 456 ); L = CJ.call<jobject>( "parseArrayListLong", (jlong) 123456, (jlong) 123789 ); std::vector<jlong> vl = cnv.c_cast_vector<jlong>(L, 2); // From ArrayList<Long> To vector<jlong> (or vector<__int64>) assert ( vl[0] == 123456 ); assert( vl[1] == 123789 ); L = CJ.call<jobject>( "parseArrayListShort", (jshort) -12, (jshort) +13 ); std::vector<jshort> vs = cnv.c_cast_vector<jshort>(L, 2); // From ArrayList<Short> To vector<jshort> (or vector<short>) assert ( vs[0] == -12 ); assert( vs[1] == +13 ); L = CJ.call<jobject>( "parseArrayListFloat", (jfloat) -123.123, (jfloat) 123.145 ); std::vector<jfloat> vf = cnv.c_cast_vector<jfloat>(L, 2); // From ArrayList<Float> To vector<jfloat> (or vector<float>) assert ( abs(vf[0] - (float) -123.123) <= MAX_TOLERANCE ); assert ( abs(vf[1] - (float) 123.145) <= MAX_TOLERANCE ); L = CJ.call<jobject>( "parseArrayListDouble", (jdouble) 123.1234, (jdouble) -123.4567 ); std::vector<jdouble> vd = cnv.c_cast_vector<jdouble>(L, 2); // From ArrayList<Double> To vector<jdouble> (or vector<double>) assert ( abs(vd[0] - (double) 123.1234) <= MAX_TOLERANCE ); assert ( abs(vd[1] - (double) -123.4567) <= MAX_TOLERANCE ); L = CJ.call<jobject>( "parseArrayListString", cnv.j_cast<jstring>("foo") , cnv.j_cast<jstring>("bar")); std::vector<std::string> v_str = cnv.c_cast_vector<std::string>(L, 2); // From ArrayList<String> To vector<string> assert ( v_str[0] == "foo" ); assert( v_str[1] == "bar" ); L = CJ.call<jobject>( "parseSimpleMap", cnv.j_cast<jstring>("foo") , cnv.j_cast<jstring>("bar"), cnv.j_cast<jstring>("foo.bar")); std::map<std::string, std::string> m_str_str = cnv.c_cast_map<std::string, std::string>(L); // From java.util.Map<String, String> To std::map<string, string> assert ( m_str_str["arg 1"] == "foo" ); assert ( m_str_str["arg 2"] == "bar" ); assert ( m_str_str["arg 3"] == "foo.bar" ); } catch(std::exception& e) { std::cout << e.what() << std::endl; VM::destroyVM(); return EXIT_FAILURE; } // Destroy VM VM::destroyVM(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef TCL_CONTROLLER_HPP #define TCL_CONTROLLER_HPP #include <string> #include "CLDeviceInformation.hpp" #include "CLInformation.hpp" #include "CLSource.hpp" #include "CLSourceArray.hpp" #include "CLWorkGroupSettings.hpp" #include "CLExecuteProperty.hpp" #include "CLExecute.hpp" #include "CLBuffer.hpp" #include "CLReadBuffer.hpp" #include "CLReadWriteBuffer.hpp" #include "CLWriteBuffer.hpp" namespace tcl { /** * @brief foCX̎ */ enum class DeviceType { GPU, CPU }; /** * @brief TinyCL𐧌䂷邽߂̃Rg[ */ class CLController { CLSource* source; const CLDeviceInformation* device; CLWorkGroupSettings* setting; CLExecute* exec; std::vector<CLBuffer*> argWrite; std::vector<CLBuffer*> argRead; private: void InitSetting(const cl_uint dimension, const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (setting != nullptr) delete setting; // xĂяo΍ setting = new CLWorkGroupSettings(dimension, offset, workerRange, splitSize); setting->Optimize(*device); } public: /** * @brief TinyCL𐧌䂷邽߂̃Rg[ * \param [in] sourcePath \[XR[h̃pX * \param [in] kernelFunction Gg[|CgɂȂ֐ * \param [in] deviceType foCX̎ * \param [in] sourceType \[XR[h̎ */ CLController(const std::string& sourcePath, const std::string& kernelFunction, const DeviceType& deviceType = DeviceType::GPU, const SourceType& sourceType = SourceType::Text) { switch (deviceType) { case DeviceType::GPU: device = &information.GetGPU(); break; case DeviceType::CPU: device = &information.GetCPU(); break; } if (device == nullptr) throw CLDeviceNotFoundException("Ώۂ̃foCX‚܂ł"); source = new CLSource(sourcePath, kernelFunction, sourceType); exec = new CLExecute(*source, *device); } /** * @brief [J[̐ݒׂw肷 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ * @param [in] splitSize [J[̋؂ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (offset.size() != workerRange.size() || offset.size() != splitSize.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, splitSize); return *this; } /** * @brief ɉoffset, workerRange𑵂Ă * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange) { if (offset.size() != workerRange.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief Ƃ肠C[J[𑽎œĂ݂ƂɎg * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& workerRange) { std::vector<size_t> offset(workerRange.size(), 0); std::vector<size_t> splitSize(workerRange.size()); for (int i = 0; i < workerRange.size(); ++i) splitSize[i] = workerRange[i]; InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief 1ƂāCoffsetX^[gCworkerRange̐[J[𓮂 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& offset, const size_t& workerRange) { InitSetting(1, { offset }, { workerRange } , { workerRange }); return *this; } /** * @brief 1ƂāCwokerRange̐[J[𓮂 * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& workerRange) { InitSetting(1, { 0 }, { workerRange }, { workerRange }); return *this; } template <typename T> CLController& Run(CLReadBuffer<T>& buffer) { } template <typename T> CLController& Run(CLWriteBuffer<T>& buffer) { } template <typename T> CLController& Run(CLReadWriteBuffer<T>& buffer) { } /** * J[ls */ template <typename BUFFER, typename... Args> CLController& Run(BUFFER& buffer, Args&... args) { Run(args); return *this; } /** * J[lR[h̎s҂ */ CLController& Wait() { exec->Wait(); return *this; } virtual ~CLController() { delete exec; delete setting; delete source; } }; } #endif<commit_msg>ちょこちょこ追加する<commit_after>#ifndef TCL_CONTROLLER_HPP #define TCL_CONTROLLER_HPP #include <string> #include "CLDeviceInformation.hpp" #include "CLInformation.hpp" #include "CLSource.hpp" #include "CLSourceArray.hpp" #include "CLWorkGroupSettings.hpp" #include "CLExecuteProperty.hpp" #include "CLExecute.hpp" #include "CLBuffer.hpp" #include "CLReadBuffer.hpp" #include "CLReadWriteBuffer.hpp" #include "CLWriteBuffer.hpp" namespace tcl { /** * @brief foCX̎ */ enum class DeviceType { GPU, CPU }; /** * @brief TinyCL𐧌䂷邽߂̃Rg[ */ class CLController { CLSource* source; const CLDeviceInformation* device; CLWorkGroupSettings* setting; CLExecute* exec; std::vector<CLBuffer*> argWrite; std::vector<CLBuffer*> argRead; private: void InitSetting(const cl_uint dimension, const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (setting != nullptr) delete setting; // xĂяo΍ setting = new CLWorkGroupSettings(dimension, offset, workerRange, splitSize); setting->Optimize(*device); } template <typename T> CLController& SetAndRun(T& buffer) { exec->SetArg(buffer); exec->Run(*setting); return *this; } public: /** * @brief TinyCL𐧌䂷邽߂̃Rg[ * \param [in] sourcePath \[XR[h̃pX * \param [in] kernelFunction Gg[|CgɂȂ֐ * \param [in] deviceType foCX̎ * \param [in] sourceType \[XR[h̎ */ CLController(const std::string& sourcePath, const std::string& kernelFunction, const DeviceType& deviceType = DeviceType::GPU, const SourceType& sourceType = SourceType::Text) { switch (deviceType) { case DeviceType::GPU: device = &information.GetGPU(); break; case DeviceType::CPU: device = &information.GetCPU(); break; } if (device == nullptr) throw CLDeviceNotFoundException("Ώۂ̃foCX‚܂ł"); source = new CLSource(sourcePath, kernelFunction, sourceType); exec = new CLExecute(*source, *device); } /** * @brief [J[̐ݒׂw肷 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ * @param [in] splitSize [J[̋؂ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (offset.size() != workerRange.size() || offset.size() != splitSize.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, splitSize); return *this; } /** * @brief ɉoffset, workerRange𑵂Ă * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange) { if (offset.size() != workerRange.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief Ƃ肠C[J[𑽎œĂ݂ƂɎg * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& workerRange) { std::vector<size_t> offset(workerRange.size(), 0); std::vector<size_t> splitSize(workerRange.size()); for (int i = 0; i < workerRange.size(); ++i) splitSize[i] = workerRange[i]; InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief 1ƂāCoffsetX^[gCworkerRange̐[J[𓮂 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& offset, const size_t& workerRange) { InitSetting(1, { offset }, { workerRange } , { workerRange }); return *this; } /** * @brief 1ƂāCwokerRange̐[J[𓮂 * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& workerRange) { InitSetting(1, { 0 }, { workerRange }, { workerRange }); return *this; } template <typename T> CLController& Run(CLReadBuffer<T>& buffer) { argRead.push_back(&buffer); return SetAndRun(buffer); } template <typename T> CLController& Run(CLWriteBuffer<T>& buffer) { argWrite.push_back(&buffer); return SetAndRun(buffer); } template <typename T> CLController& Run(CLReadWriteBuffer<T>& buffer) { argRead.push_back(buffer); argWrite.push_back(buffer); return SetAndRun(buffer); } /** * J[ls */ template <typename BUFFER, typename... Args> CLController& Run(BUFFER& buffer, Args&... args) { Run(args); return *this; } /** * J[lR[h̎s҂ */ CLController& Wait() { exec->Wait(); argRead.clear(); argWrite.clear(); return *this; } virtual ~CLController() { delete exec; delete setting; delete source; } }; } #endif<|endoftext|>
<commit_before>#include "Arduino.h" #include "AddressableLEDStrip.h" // Create the LED strip object with the clock pin, serial data pin and the number of LEDs in the strip. AddressableLEDStrip::AddressableLEDStrip(int clk_pin, int sdi_pin, int num_leds) { allow_out_of_bounds = false; strip_len = num_leds; // Create color arrays red_values = (int *) malloc(num_leds * sizeof(int)); green_values = (int *) malloc(num_leds * sizeof(int)); blue_values = (int *) malloc(num_leds * sizeof(int)); // Set the arrays or return if(red_values) memset(red_values, 0, num_leds); else return; if(green_values) memset(green_values, 0, num_leds); else return; if(blue_values) memset(blue_values, 0, num_leds); else return; // Setup pins clk = clk_pin; sdi = sdi_pin; pinMode(sdi, OUTPUT); pinMode(clk, OUTPUT); } // Set the RGB value on a single LED // This does not write anything to the strip. void AddressableLEDStrip::set_led(uint16_t index, int red, int green, int blue) { // Make sure index is within range if (index < strip_len) { // Update the value to be within the 0 - 255 boundary if (allow_out_of_bounds == false) { if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; } // Set values red_values[index] = red; green_values[index] = green; blue_values[index] = blue; } } // Sets all the LEDs to OFF // This does not write them to the strip. void AddressableLEDStrip::clear_all() { set_all_leds(0, 0, 0); } // Clear the color values for an LED at this index void AddressableLEDStrip::clear_led(int index) { set_led(index, 0, 0, 0); } // Set the red color (0 - 255) for an LED at this index void AddressableLEDStrip::set_red(int index, int color) { set_led(index, color, get_green(index), get_blue(index)); } // Set the green color (0 - 255) for an LED at this index void AddressableLEDStrip::set_green(int index, int color) { set_led(index, get_red(index), color, get_blue(index)); } // Set the blue color (0 - 255) for an LED at this index void AddressableLEDStrip::set_blue(int index, int color) { set_led(index, get_red(index), get_green(index), index); } // Set all the LEDs to the same RGB value. // This does not write them to the strip. void AddressableLEDStrip::set_all_leds(int red, int green, int blue) { for(int i = 0 ; i < strip_len ; i++) { set_led(i, red, green , blue); } } // Push the RGB values to the LED strip. void AddressableLEDStrip::send() { //Each LED requires 24 bits of data //MSB: R7, R6, R5..., G7, G6..., B7, B6... B0 //Once the 24 bits have been delivered, the IC immediately relays these bits to its neighbor //Pulling the clock low for 500us or more causes the IC to post the data. for(int i = 0 ; i < strip_len ; i++) { _send_color_bits(get_red(i)); _send_color_bits(get_green(i)); _send_color_bits(get_blue(i)); } //Pull clock low to put strip into reset/post mode digitalWrite(clk, LOW); delayMicroseconds(500); //Wait for 500us to go into reset } // Send the individual bits from this value to the LED strip. void AddressableLEDStrip::_send_color_bits(int value) { // Value must be between 0 - 255 if (value < 0) value = 0; else if (value > 255) value = 255; // Pull 8 bits from the value //for(int bit_place = 7; bit_place >= 0; bit_place--) { for(int bit_place = 7; bit_place >= 0; bit_place--) { //int bit_mask = pow(2, bit_place); // 128, 64, 32, 16, 8, 4, 2, 1 int bit_mask = 1 << bit_place; // 128, 64, 32, 16, 8, 4, 2, 1 // Pull clock low to set the value digitalWrite(clk, LOW); // Write value if(value & bit_mask) digitalWrite(sdi, HIGH); else digitalWrite(sdi, LOW); // Latch the new value in digitalWrite(clk, HIGH); } } // Get the number of LED that are in this strip (or at least what you set the length to be). int AddressableLEDStrip::length() { return strip_len; } // Get the red value at an LED index int AddressableLEDStrip::get_red(int index) { if (index < strip_len) { return red_values[index]; } return 0; } // Get the green value at an LED index int AddressableLEDStrip::get_green(int index) { if (index < strip_len) { return green_values[index]; } return 0; } // Get the blue value at an LED index int AddressableLEDStrip::get_blue(int index) { if (index < strip_len) { return blue_values[index]; } return 0; }<commit_msg>Fix set_blue() which was setting the color to the index. Whoops<commit_after>#include "Arduino.h" #include "AddressableLEDStrip.h" // Create the LED strip object with the clock pin, serial data pin and the number of LEDs in the strip. AddressableLEDStrip::AddressableLEDStrip(int clk_pin, int sdi_pin, int num_leds) { allow_out_of_bounds = false; strip_len = num_leds; // Create color arrays red_values = (int *) malloc(num_leds * sizeof(int)); green_values = (int *) malloc(num_leds * sizeof(int)); blue_values = (int *) malloc(num_leds * sizeof(int)); // Set the arrays or return if(red_values) memset(red_values, 0, num_leds); else return; if(green_values) memset(green_values, 0, num_leds); else return; if(blue_values) memset(blue_values, 0, num_leds); else return; // Setup pins clk = clk_pin; sdi = sdi_pin; pinMode(sdi, OUTPUT); pinMode(clk, OUTPUT); } // Set the RGB value on a single LED // This does not write anything to the strip. void AddressableLEDStrip::set_led(uint16_t index, int red, int green, int blue) { // Make sure index is within range if (index < strip_len) { // Update the value to be within the 0 - 255 boundary if (allow_out_of_bounds == false) { if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; } // Set values red_values[index] = red; green_values[index] = green; blue_values[index] = blue; } } // Sets all the LEDs to OFF // This does not write them to the strip. void AddressableLEDStrip::clear_all() { set_all_leds(0, 0, 0); } // Clear the color values for an LED at this index void AddressableLEDStrip::clear_led(int index) { set_led(index, 0, 0, 0); } // Set the red color (0 - 255) for an LED at this index void AddressableLEDStrip::set_red(int index, int color) { set_led(index, color, get_green(index), get_blue(index)); } // Set the green color (0 - 255) for an LED at this index void AddressableLEDStrip::set_green(int index, int color) { set_led(index, get_red(index), color, get_blue(index)); } // Set the blue color (0 - 255) for an LED at this index void AddressableLEDStrip::set_blue(int index, int color) { set_led(index, get_red(index), get_green(index), color); } // Set all the LEDs to the same RGB value. // This does not write them to the strip. void AddressableLEDStrip::set_all_leds(int red, int green, int blue) { for(int i = 0 ; i < strip_len ; i++) { set_led(i, red, green , blue); } } // Push the RGB values to the LED strip. void AddressableLEDStrip::send() { //Each LED requires 24 bits of data //MSB: R7, R6, R5..., G7, G6..., B7, B6... B0 //Once the 24 bits have been delivered, the IC immediately relays these bits to its neighbor //Pulling the clock low for 500us or more causes the IC to post the data. for(int i = 0 ; i < strip_len ; i++) { _send_color_bits(get_red(i)); _send_color_bits(get_green(i)); _send_color_bits(get_blue(i)); } //Pull clock low to put strip into reset/post mode digitalWrite(clk, LOW); delayMicroseconds(500); //Wait for 500us to go into reset } // Send the individual bits from this value to the LED strip. void AddressableLEDStrip::_send_color_bits(int value) { // Value must be between 0 - 255 if (value < 0) value = 0; else if (value > 255) value = 255; // Pull 8 bits from the value //for(int bit_place = 7; bit_place >= 0; bit_place--) { for(int bit_place = 7; bit_place >= 0; bit_place--) { //int bit_mask = pow(2, bit_place); // 128, 64, 32, 16, 8, 4, 2, 1 int bit_mask = 1 << bit_place; // 128, 64, 32, 16, 8, 4, 2, 1 // Pull clock low to set the value digitalWrite(clk, LOW); // Write value if(value & bit_mask) digitalWrite(sdi, HIGH); else digitalWrite(sdi, LOW); // Latch the new value in digitalWrite(clk, HIGH); } } // Get the number of LED that are in this strip (or at least what you set the length to be). int AddressableLEDStrip::length() { return strip_len; } // Get the red value at an LED index int AddressableLEDStrip::get_red(int index) { if (index < strip_len) { return red_values[index]; } return 0; } // Get the green value at an LED index int AddressableLEDStrip::get_green(int index) { if (index < strip_len) { return green_values[index]; } return 0; } // Get the blue value at an LED index int AddressableLEDStrip::get_blue(int index) { if (index < strip_len) { return blue_values[index]; } return 0; }<|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.C /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <p9_mss_eff_config.H> // std #include <map> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/spd_decoder.H> #include <lib/spd/spd_factory.H> #include <lib/utils/pos.H> #include <lib/utils/checker.H> #include <lib/utils/find.H> #include <lib/shared/mss_kind.H> #include <lib/utils/find.H> #include <lib/dimm/eff_dimm.H> #include <lib/eff_config/plug_rules.H> /// /// @brief Configure the attributes for each controller /// @param[in] i_target the controller (e.g., MCS) /// @param[in] i_decode_spd_only options to set VPD and SPD attrs only /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target, const bool i_decode_spd_only ) { fapi2::ReturnCode l_rc; std::map<uint32_t, std::shared_ptr<mss::spd::decoder> > l_factory_caches; // Caches FAPI_TRY( mss::spd::populate_decoder_caches(i_target, l_factory_caches) ); // We need to decode the VPD. We don't do this in the ctor as we need // the rank information and for that we need the SPD caches (which we get when we populate the cache.) // However, we need to do the VPD decode before the others so that they might // be able to use VPD information to make decisions about setting up eff attributes. if( !i_decode_spd_only ) { // Always set VPD attributes unless we enable the SPD_ONLY flag // Enables skipping VPD decoder when a valid VPD template isn't available FAPI_TRY( mss::eff_dimm::decode_vpd(i_target), "Unable to decode VPD for %s", mss::c_str(i_target) ); } for( const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target) ) { std::shared_ptr<mss::eff_dimm> l_eff_dimm; const auto l_dimm_pos = mss::pos(l_dimm); // TODO RTC:152390 Create function to do map checking on cached values // Find decoder factory for this dimm position auto l_it = l_factory_caches.find(l_dimm_pos); FAPI_TRY( mss::check::spd::invalid_cache(l_dimm, l_it != l_factory_caches.end(), l_dimm_pos), "Failed to get valid cache (main decoder)"); FAPI_TRY( mss::eff_dimm::eff_dimm_factory( l_dimm, l_it->second, l_eff_dimm)); FAPI_TRY( l_eff_dimm->dram_mfg_id() ); FAPI_TRY( l_eff_dimm->dram_width() ); FAPI_TRY( l_eff_dimm->dram_density() ); FAPI_TRY( l_eff_dimm->ranks_per_dimm() ); FAPI_TRY( l_eff_dimm->primary_stack_type() ); FAPI_TRY( l_eff_dimm->dimm_size() ); FAPI_TRY( l_eff_dimm->hybrid_memory_type() ); FAPI_TRY( l_eff_dimm->temp_refresh_mode() ); FAPI_TRY( l_eff_dimm->dram_trefi() ); FAPI_TRY( l_eff_dimm->dram_trfc() ); FAPI_TRY( l_eff_dimm->dram_trfc_dlr() ); FAPI_TRY( l_eff_dimm->rcd_mirror_mode() ); FAPI_TRY( l_eff_dimm->dram_bank_bits() ); FAPI_TRY( l_eff_dimm->dram_row_bits() ); FAPI_TRY( l_eff_dimm->dram_dqs_time() ); FAPI_TRY( l_eff_dimm->dram_tccd_l() ); FAPI_TRY( l_eff_dimm->dimm_rc00() ); FAPI_TRY( l_eff_dimm->dimm_rc01() ); FAPI_TRY( l_eff_dimm->dimm_rc02() ); FAPI_TRY( l_eff_dimm->dimm_rc03() ); FAPI_TRY( l_eff_dimm->dimm_rc04() ); FAPI_TRY( l_eff_dimm->dimm_rc05() ); FAPI_TRY( l_eff_dimm->dimm_rc06_07() ); FAPI_TRY( l_eff_dimm->dimm_rc08() ); FAPI_TRY( l_eff_dimm->dimm_rc09() ); FAPI_TRY( l_eff_dimm->dimm_rc10() ); FAPI_TRY( l_eff_dimm->dimm_rc11() ); FAPI_TRY( l_eff_dimm->dimm_rc12() ); FAPI_TRY( l_eff_dimm->dimm_rc13() ); FAPI_TRY( l_eff_dimm->dimm_rc14() ); FAPI_TRY( l_eff_dimm->dimm_rc15() ); FAPI_TRY( l_eff_dimm->dimm_rc1x() ); FAPI_TRY( l_eff_dimm->dimm_rc2x() ); FAPI_TRY( l_eff_dimm->dimm_rc3x() ); FAPI_TRY( l_eff_dimm->dimm_rc4x() ); FAPI_TRY( l_eff_dimm->dimm_rc5x() ); FAPI_TRY( l_eff_dimm->dimm_rc6x() ); FAPI_TRY( l_eff_dimm->dimm_rc7x() ); FAPI_TRY( l_eff_dimm->dimm_rc8x() ); FAPI_TRY( l_eff_dimm->dimm_rc9x() ); FAPI_TRY( l_eff_dimm->dimm_rcax() ); FAPI_TRY( l_eff_dimm->dimm_rcbx() ); FAPI_TRY( l_eff_dimm->dram_twr() ); FAPI_TRY( l_eff_dimm->read_burst_type() ); FAPI_TRY( l_eff_dimm->dram_tm() ); FAPI_TRY( l_eff_dimm->dram_cwl() ); FAPI_TRY( l_eff_dimm->dram_lpasr() ); FAPI_TRY( l_eff_dimm->dll_enable() ); FAPI_TRY( l_eff_dimm->dll_reset() ); FAPI_TRY( l_eff_dimm->write_level_enable() ); FAPI_TRY( l_eff_dimm->output_buffer() ); FAPI_TRY( l_eff_dimm->vref_dq_train_value() ); FAPI_TRY( l_eff_dimm->vref_dq_train_range() ); FAPI_TRY( l_eff_dimm->vref_dq_train_enable() ); FAPI_TRY( l_eff_dimm->ca_parity_latency() ); FAPI_TRY( l_eff_dimm->ca_parity_error_status() ); FAPI_TRY( l_eff_dimm->ca_parity() ); FAPI_TRY( l_eff_dimm->crc_error_clear() ); FAPI_TRY( l_eff_dimm->odt_input_buffer() ); FAPI_TRY( l_eff_dimm->post_package_repair() ); FAPI_TRY( l_eff_dimm->read_preamble_train() ); FAPI_TRY( l_eff_dimm->read_preamble() ); FAPI_TRY( l_eff_dimm->write_preamble() ); FAPI_TRY( l_eff_dimm->self_refresh_abort() ); FAPI_TRY( l_eff_dimm->cs_to_cmd_addr_latency() ); FAPI_TRY( l_eff_dimm->internal_vref_monitor() ); FAPI_TRY( l_eff_dimm->max_powerdown_mode() ); FAPI_TRY( l_eff_dimm->mpr_read_format() ); FAPI_TRY( l_eff_dimm->temp_readout() ); FAPI_TRY( l_eff_dimm->crc_wr_latency() ); FAPI_TRY( l_eff_dimm->per_dram_addressability() ); FAPI_TRY( l_eff_dimm->geardown_mode() ); FAPI_TRY( l_eff_dimm->mpr_page() ); FAPI_TRY( l_eff_dimm->mpr_mode() ); FAPI_TRY( l_eff_dimm->write_crc() ); FAPI_TRY( l_eff_dimm->zqcal_interval() ); FAPI_TRY( l_eff_dimm->memcal_interval() ); FAPI_TRY( l_eff_dimm->dram_trp() ); FAPI_TRY( l_eff_dimm->dram_trcd() ); FAPI_TRY( l_eff_dimm->dram_trc() ); FAPI_TRY( l_eff_dimm->dram_twtr_l() ); FAPI_TRY( l_eff_dimm->dram_twtr_s() ); FAPI_TRY( l_eff_dimm->dram_trrd_s() ); FAPI_TRY( l_eff_dimm->dram_trrd_l() ); FAPI_TRY( l_eff_dimm->dram_trrd_dlr() ); FAPI_TRY( l_eff_dimm->dram_tfaw() ); FAPI_TRY( l_eff_dimm->dram_tfaw_dlr() ); FAPI_TRY( l_eff_dimm->dram_tras() ); FAPI_TRY( l_eff_dimm->dram_trtp() ); FAPI_TRY( l_eff_dimm->read_dbi() ); FAPI_TRY( l_eff_dimm->write_dbi() ); FAPI_TRY( l_eff_dimm->additive_latency() ); FAPI_TRY( l_eff_dimm->data_mask() ); FAPI_TRY( l_eff_dimm->dimm_bc00()); FAPI_TRY( l_eff_dimm->dimm_bc01()); FAPI_TRY( l_eff_dimm->dimm_bc02()); FAPI_TRY( l_eff_dimm->dimm_bc03()); FAPI_TRY( l_eff_dimm->dimm_bc04()); FAPI_TRY( l_eff_dimm->dimm_bc05()); FAPI_TRY( l_eff_dimm->dimm_bc07()); FAPI_TRY( l_eff_dimm->dimm_bc08()); FAPI_TRY( l_eff_dimm->dimm_bc09()); FAPI_TRY( l_eff_dimm->dimm_bc0a()); FAPI_TRY( l_eff_dimm->dimm_bc0b()); FAPI_TRY( l_eff_dimm->dimm_bc0c()); FAPI_TRY( l_eff_dimm->dimm_bc0d()); FAPI_TRY( l_eff_dimm->dimm_bc0e()); FAPI_TRY( l_eff_dimm->dimm_bc0f()); FAPI_TRY( l_eff_dimm->dram_rtt_nom () ); FAPI_TRY( l_eff_dimm->dram_rtt_wr () ); FAPI_TRY( l_eff_dimm->dram_rtt_park() ); }// dimm // TODO RTC:160060 Clean up hard coded values at bottom of eff_config // Don't set these attributes if we only want to set VPD attributes // This will be cleaner once we resolve attributes below { uint16_t l_cal_step[mss::PORTS_PER_MCS] = {0xFAC0, 0xFAC0}; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_CAL_STEP_ENABLE, i_target, l_cal_step) ); } // Check plug rules. We check the MCS, and this will iterate down to children as needed. FAPI_TRY( mss::plug_rule::enforce_plug_rules(i_target) ); fapi_try_exit: return fapi2::current_err; } <commit_msg>Disabling temp_refresh_mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.C /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <p9_mss_eff_config.H> // std #include <map> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/spd_decoder.H> #include <lib/spd/spd_factory.H> #include <lib/utils/pos.H> #include <lib/utils/checker.H> #include <lib/utils/find.H> #include <lib/shared/mss_kind.H> #include <lib/utils/find.H> #include <lib/dimm/eff_dimm.H> #include <lib/eff_config/plug_rules.H> /// /// @brief Configure the attributes for each controller /// @param[in] i_target the controller (e.g., MCS) /// @param[in] i_decode_spd_only options to set VPD and SPD attrs only /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target, const bool i_decode_spd_only ) { fapi2::ReturnCode l_rc; std::map<uint32_t, std::shared_ptr<mss::spd::decoder> > l_factory_caches; // Caches FAPI_TRY( mss::spd::populate_decoder_caches(i_target, l_factory_caches) ); // We need to decode the VPD. We don't do this in the ctor as we need // the rank information and for that we need the SPD caches (which we get when we populate the cache.) // However, we need to do the VPD decode before the others so that they might // be able to use VPD information to make decisions about setting up eff attributes. if( !i_decode_spd_only ) { // Always set VPD attributes unless we enable the SPD_ONLY flag // Enables skipping VPD decoder when a valid VPD template isn't available FAPI_TRY( mss::eff_dimm::decode_vpd(i_target), "Unable to decode VPD for %s", mss::c_str(i_target) ); } for( const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target) ) { std::shared_ptr<mss::eff_dimm> l_eff_dimm; const auto l_dimm_pos = mss::pos(l_dimm); // TODO RTC:152390 Create function to do map checking on cached values // Find decoder factory for this dimm position auto l_it = l_factory_caches.find(l_dimm_pos); FAPI_TRY( mss::check::spd::invalid_cache(l_dimm, l_it != l_factory_caches.end(), l_dimm_pos), "Failed to get valid cache (main decoder)"); FAPI_TRY( mss::eff_dimm::eff_dimm_factory( l_dimm, l_it->second, l_eff_dimm)); FAPI_TRY( l_eff_dimm->dram_mfg_id() ); FAPI_TRY( l_eff_dimm->dram_width() ); FAPI_TRY( l_eff_dimm->dram_density() ); FAPI_TRY( l_eff_dimm->ranks_per_dimm() ); FAPI_TRY( l_eff_dimm->primary_stack_type() ); FAPI_TRY( l_eff_dimm->dimm_size() ); FAPI_TRY( l_eff_dimm->hybrid_memory_type() ); FAPI_TRY( l_eff_dimm->dram_trefi() ); FAPI_TRY( l_eff_dimm->dram_trfc() ); FAPI_TRY( l_eff_dimm->dram_trfc_dlr() ); FAPI_TRY( l_eff_dimm->rcd_mirror_mode() ); FAPI_TRY( l_eff_dimm->dram_bank_bits() ); FAPI_TRY( l_eff_dimm->dram_row_bits() ); FAPI_TRY( l_eff_dimm->dram_dqs_time() ); FAPI_TRY( l_eff_dimm->dram_tccd_l() ); FAPI_TRY( l_eff_dimm->dimm_rc00() ); FAPI_TRY( l_eff_dimm->dimm_rc01() ); FAPI_TRY( l_eff_dimm->dimm_rc02() ); FAPI_TRY( l_eff_dimm->dimm_rc03() ); FAPI_TRY( l_eff_dimm->dimm_rc04() ); FAPI_TRY( l_eff_dimm->dimm_rc05() ); FAPI_TRY( l_eff_dimm->dimm_rc06_07() ); FAPI_TRY( l_eff_dimm->dimm_rc08() ); FAPI_TRY( l_eff_dimm->dimm_rc09() ); FAPI_TRY( l_eff_dimm->dimm_rc10() ); FAPI_TRY( l_eff_dimm->dimm_rc11() ); FAPI_TRY( l_eff_dimm->dimm_rc12() ); FAPI_TRY( l_eff_dimm->dimm_rc13() ); FAPI_TRY( l_eff_dimm->dimm_rc14() ); FAPI_TRY( l_eff_dimm->dimm_rc15() ); FAPI_TRY( l_eff_dimm->dimm_rc1x() ); FAPI_TRY( l_eff_dimm->dimm_rc2x() ); FAPI_TRY( l_eff_dimm->dimm_rc3x() ); FAPI_TRY( l_eff_dimm->dimm_rc4x() ); FAPI_TRY( l_eff_dimm->dimm_rc5x() ); FAPI_TRY( l_eff_dimm->dimm_rc6x() ); FAPI_TRY( l_eff_dimm->dimm_rc7x() ); FAPI_TRY( l_eff_dimm->dimm_rc8x() ); FAPI_TRY( l_eff_dimm->dimm_rc9x() ); FAPI_TRY( l_eff_dimm->dimm_rcax() ); FAPI_TRY( l_eff_dimm->dimm_rcbx() ); FAPI_TRY( l_eff_dimm->dram_twr() ); FAPI_TRY( l_eff_dimm->read_burst_type() ); FAPI_TRY( l_eff_dimm->dram_tm() ); FAPI_TRY( l_eff_dimm->dram_cwl() ); FAPI_TRY( l_eff_dimm->dram_lpasr() ); FAPI_TRY( l_eff_dimm->dll_enable() ); FAPI_TRY( l_eff_dimm->dll_reset() ); FAPI_TRY( l_eff_dimm->write_level_enable() ); FAPI_TRY( l_eff_dimm->output_buffer() ); FAPI_TRY( l_eff_dimm->vref_dq_train_value() ); FAPI_TRY( l_eff_dimm->vref_dq_train_range() ); FAPI_TRY( l_eff_dimm->vref_dq_train_enable() ); FAPI_TRY( l_eff_dimm->ca_parity_latency() ); FAPI_TRY( l_eff_dimm->ca_parity_error_status() ); FAPI_TRY( l_eff_dimm->ca_parity() ); FAPI_TRY( l_eff_dimm->crc_error_clear() ); FAPI_TRY( l_eff_dimm->odt_input_buffer() ); FAPI_TRY( l_eff_dimm->post_package_repair() ); FAPI_TRY( l_eff_dimm->read_preamble_train() ); FAPI_TRY( l_eff_dimm->read_preamble() ); FAPI_TRY( l_eff_dimm->write_preamble() ); FAPI_TRY( l_eff_dimm->self_refresh_abort() ); FAPI_TRY( l_eff_dimm->cs_to_cmd_addr_latency() ); FAPI_TRY( l_eff_dimm->internal_vref_monitor() ); FAPI_TRY( l_eff_dimm->max_powerdown_mode() ); FAPI_TRY( l_eff_dimm->mpr_read_format() ); FAPI_TRY( l_eff_dimm->temp_readout() ); FAPI_TRY( l_eff_dimm->crc_wr_latency() ); FAPI_TRY( l_eff_dimm->per_dram_addressability() ); FAPI_TRY( l_eff_dimm->geardown_mode() ); FAPI_TRY( l_eff_dimm->mpr_page() ); FAPI_TRY( l_eff_dimm->mpr_mode() ); FAPI_TRY( l_eff_dimm->write_crc() ); FAPI_TRY( l_eff_dimm->zqcal_interval() ); FAPI_TRY( l_eff_dimm->memcal_interval() ); FAPI_TRY( l_eff_dimm->dram_trp() ); FAPI_TRY( l_eff_dimm->dram_trcd() ); FAPI_TRY( l_eff_dimm->dram_trc() ); FAPI_TRY( l_eff_dimm->dram_twtr_l() ); FAPI_TRY( l_eff_dimm->dram_twtr_s() ); FAPI_TRY( l_eff_dimm->dram_trrd_s() ); FAPI_TRY( l_eff_dimm->dram_trrd_l() ); FAPI_TRY( l_eff_dimm->dram_trrd_dlr() ); FAPI_TRY( l_eff_dimm->dram_tfaw() ); FAPI_TRY( l_eff_dimm->dram_tfaw_dlr() ); FAPI_TRY( l_eff_dimm->dram_tras() ); FAPI_TRY( l_eff_dimm->dram_trtp() ); FAPI_TRY( l_eff_dimm->read_dbi() ); FAPI_TRY( l_eff_dimm->write_dbi() ); FAPI_TRY( l_eff_dimm->additive_latency() ); FAPI_TRY( l_eff_dimm->data_mask() ); FAPI_TRY( l_eff_dimm->dimm_bc00()); FAPI_TRY( l_eff_dimm->dimm_bc01()); FAPI_TRY( l_eff_dimm->dimm_bc02()); FAPI_TRY( l_eff_dimm->dimm_bc03()); FAPI_TRY( l_eff_dimm->dimm_bc04()); FAPI_TRY( l_eff_dimm->dimm_bc05()); FAPI_TRY( l_eff_dimm->dimm_bc07()); FAPI_TRY( l_eff_dimm->dimm_bc08()); FAPI_TRY( l_eff_dimm->dimm_bc09()); FAPI_TRY( l_eff_dimm->dimm_bc0a()); FAPI_TRY( l_eff_dimm->dimm_bc0b()); FAPI_TRY( l_eff_dimm->dimm_bc0c()); FAPI_TRY( l_eff_dimm->dimm_bc0d()); FAPI_TRY( l_eff_dimm->dimm_bc0e()); FAPI_TRY( l_eff_dimm->dimm_bc0f()); FAPI_TRY( l_eff_dimm->dram_rtt_nom () ); FAPI_TRY( l_eff_dimm->dram_rtt_wr () ); FAPI_TRY( l_eff_dimm->dram_rtt_park() ); //Let's do some checking FAPI_TRY( mss::check::temp_refresh_mode()); }// dimm // TODO RTC:160060 Clean up hard coded values at bottom of eff_config // Don't set these attributes if we only want to set VPD attributes // This will be cleaner once we resolve attributes below { uint16_t l_cal_step[mss::PORTS_PER_MCS] = {0xFAC0, 0xFAC0}; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_CAL_STEP_ENABLE, i_target, l_cal_step) ); } // Check plug rules. We check the MCS, and this will iterate down to children as needed. FAPI_TRY( mss::plug_rule::enforce_plug_rules(i_target) ); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unordered_map> #include "io_interface.h" #include "matrix_config.h" #include "mem_worker_thread.h" #include "EM_object.h" #include "local_mem_buffer.h" namespace fm { namespace detail { #ifdef USE_HWLOC std::vector<int> get_cpus(int node_id) { std::vector<int> io_cpus = safs::get_io_cpus(); std::vector<int> logical_units = cpus.get_node(node_id).get_logical_units(); std::set<int> cpu_set(logical_units.begin(), logical_units.end()); // Remove the logical units where I/O threads run. for (size_t j = 0; j < io_cpus.size(); j++) cpu_set.erase(io_cpus[j]); return std::vector<int>(cpu_set.begin(), cpu_set.end()); } #endif mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node) { tot_num_tasks = 0; threads.resize(num_nodes); for (int i = 0; i < num_nodes; i++) { // Get the CPU cores that are in node i. #ifdef USE_HWLOC std::vector<int> cpus = get_cpus(i); #endif threads[i].resize(nthreads_per_node); for (int j = 0; j < nthreads_per_node; j++) { std::string name = std::string("mem-worker-") + itoa(i) + "-" + itoa(j); #ifdef USE_HWLOC if (safs::get_io_cpus().empty()) threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); else threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, cpus, i)); #else threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); #endif threads[i][j]->start(); } } ntasks_per_node.resize(num_nodes); } /* * This method dispatches tasks in a round-robin fashion. */ void mem_thread_pool::process_task(int node_id, thread_task *task) { if (node_id < 0) node_id = tot_num_tasks % get_num_nodes(); assert((size_t) node_id < threads.size()); size_t idx = ntasks_per_node[node_id] % threads[node_id].size(); threads[node_id][idx]->add_task(task); ntasks_per_node[node_id]++; tot_num_tasks++; } void mem_thread_pool::wait4complete() { for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) threads[i][j]->wait4complete(); } // After all workers complete, we should try to clear the memory buffers // in each worker thread to reduce memory consumption. // We might want to keep the memory buffer for I/O on dense matrices. if (matrix_conf.is_keep_mem_buf()) detail::local_mem_buffer::clear_bufs( detail::local_mem_buffer::MAT_PORTION); else detail::local_mem_buffer::clear_bufs(); } size_t mem_thread_pool::get_num_pending() const { size_t ret = 0; for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) ret += threads[i][j]->get_num_pending(); } return ret; } static mem_thread_pool::ptr global_threads; enum thread_pool_state { UNINIT, ACTIVE, INACTIVE, }; static thread_pool_state pool_state = thread_pool_state::UNINIT; /* * When we disable thread pool, we use the main thread to perform * computation. */ bool mem_thread_pool::disable_thread_pool() { pool_state = thread_pool_state::INACTIVE; return true; } bool mem_thread_pool::enable_thread_pool() { pool_state = thread_pool_state::ACTIVE; return true; } mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads() { assert(pool_state != thread_pool_state::INACTIVE); if (global_threads == NULL) { int nthreads_per_node = matrix_conf.get_num_DM_threads() / matrix_conf.get_num_nodes(); assert(nthreads_per_node > 0); global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(), nthreads_per_node); enable_thread_pool(); } return global_threads; } size_t mem_thread_pool::get_global_num_threads() { // When we disable the thread pool, we use the main thread for computation. // So the number of threads is 1. if (pool_state == thread_pool_state::INACTIVE) return 1; else return get_global_mem_threads()->get_num_threads(); } int mem_thread_pool::get_curr_thread_id() { // When we disable the thread pool, we use the main thread for computation. // And we use 0 as the thread id of the main thread. if (pool_state == thread_pool_state::INACTIVE) return 0; else { detail::pool_task_thread *curr = dynamic_cast<detail::pool_task_thread *>(thread::get_curr_thread()); if (curr) return curr->get_pool_thread_id(); else return -1; } } void mem_thread_pool::init_global_mem_threads(int num_nodes, int nthreads_per_node) { if (global_threads == NULL) { global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node); enable_thread_pool(); } } void mem_thread_pool::destroy() { global_threads = NULL; } void io_worker_task::run() { std::vector<safs::io_interface::ptr> ios; pthread_spin_lock(&lock); for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) { std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios(); ios.insert(ios.end(), tmp.begin(), tmp.end()); } pthread_spin_unlock(&lock); safs::io_select::ptr select = safs::create_io_select(ios); // The task runs until there are no tasks left in the queue. while (dispatch->issue_task()) safs::wait4ios(select, max_pending_ios); // Test if all I/O instances have processed all requests. size_t num_pending = safs::wait4ios(select, 0); assert(num_pending == 0); pthread_spin_lock(&lock); EM_objs.clear(); pthread_spin_unlock(&lock); for (size_t i = 0; i < ios.size(); i++) { portion_callback &cb = static_cast<portion_callback &>( ios[i]->get_callback()); assert(!cb.has_callback()); } } global_counter::global_counter() { counts.resize(mem_thread_pool::get_global_num_threads()); reset(); } void global_counter::inc(size_t val) { int id = mem_thread_pool::get_curr_thread_id(); counts[id].count += val; } void global_counter::reset() { for (size_t i = 0; i < counts.size(); i++) counts[i].count = 0; } size_t global_counter::get() const { size_t tot = 0; for (size_t i = 0; i < counts.size(); i++) tot += counts[i].count; return tot; } } } <commit_msg>[Matrix]: fix a bug in global_counter.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unordered_map> #include "io_interface.h" #include "matrix_config.h" #include "mem_worker_thread.h" #include "EM_object.h" #include "local_mem_buffer.h" namespace fm { namespace detail { #ifdef USE_HWLOC std::vector<int> get_cpus(int node_id) { std::vector<int> io_cpus = safs::get_io_cpus(); std::vector<int> logical_units = cpus.get_node(node_id).get_logical_units(); std::set<int> cpu_set(logical_units.begin(), logical_units.end()); // Remove the logical units where I/O threads run. for (size_t j = 0; j < io_cpus.size(); j++) cpu_set.erase(io_cpus[j]); return std::vector<int>(cpu_set.begin(), cpu_set.end()); } #endif mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node) { tot_num_tasks = 0; threads.resize(num_nodes); for (int i = 0; i < num_nodes; i++) { // Get the CPU cores that are in node i. #ifdef USE_HWLOC std::vector<int> cpus = get_cpus(i); #endif threads[i].resize(nthreads_per_node); for (int j = 0; j < nthreads_per_node; j++) { std::string name = std::string("mem-worker-") + itoa(i) + "-" + itoa(j); #ifdef USE_HWLOC if (safs::get_io_cpus().empty()) threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); else threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, cpus, i)); #else threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); #endif threads[i][j]->start(); } } ntasks_per_node.resize(num_nodes); } /* * This method dispatches tasks in a round-robin fashion. */ void mem_thread_pool::process_task(int node_id, thread_task *task) { if (node_id < 0) node_id = tot_num_tasks % get_num_nodes(); assert((size_t) node_id < threads.size()); size_t idx = ntasks_per_node[node_id] % threads[node_id].size(); threads[node_id][idx]->add_task(task); ntasks_per_node[node_id]++; tot_num_tasks++; } void mem_thread_pool::wait4complete() { for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) threads[i][j]->wait4complete(); } // After all workers complete, we should try to clear the memory buffers // in each worker thread to reduce memory consumption. // We might want to keep the memory buffer for I/O on dense matrices. if (matrix_conf.is_keep_mem_buf()) detail::local_mem_buffer::clear_bufs( detail::local_mem_buffer::MAT_PORTION); else detail::local_mem_buffer::clear_bufs(); } size_t mem_thread_pool::get_num_pending() const { size_t ret = 0; for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) ret += threads[i][j]->get_num_pending(); } return ret; } static mem_thread_pool::ptr global_threads; enum thread_pool_state { UNINIT, ACTIVE, INACTIVE, }; static thread_pool_state pool_state = thread_pool_state::UNINIT; /* * When we disable thread pool, we use the main thread to perform * computation. */ bool mem_thread_pool::disable_thread_pool() { pool_state = thread_pool_state::INACTIVE; return true; } bool mem_thread_pool::enable_thread_pool() { pool_state = thread_pool_state::ACTIVE; return true; } mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads() { assert(pool_state != thread_pool_state::INACTIVE); if (global_threads == NULL) { int nthreads_per_node = matrix_conf.get_num_DM_threads() / matrix_conf.get_num_nodes(); assert(nthreads_per_node > 0); global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(), nthreads_per_node); enable_thread_pool(); } return global_threads; } size_t mem_thread_pool::get_global_num_threads() { // When we disable the thread pool, we use the main thread for computation. // So the number of threads is 1. if (pool_state == thread_pool_state::INACTIVE) return 1; else return get_global_mem_threads()->get_num_threads(); } int mem_thread_pool::get_curr_thread_id() { // When we disable the thread pool, we use the main thread for computation. // And we use 0 as the thread id of the main thread. if (pool_state == thread_pool_state::INACTIVE) return 0; else { detail::pool_task_thread *curr = dynamic_cast<detail::pool_task_thread *>(thread::get_curr_thread()); if (curr) return curr->get_pool_thread_id(); else return -1; } } void mem_thread_pool::init_global_mem_threads(int num_nodes, int nthreads_per_node) { if (global_threads == NULL) { global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node); enable_thread_pool(); } } void mem_thread_pool::destroy() { global_threads = NULL; } void io_worker_task::run() { std::vector<safs::io_interface::ptr> ios; pthread_spin_lock(&lock); for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) { std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios(); ios.insert(ios.end(), tmp.begin(), tmp.end()); } pthread_spin_unlock(&lock); safs::io_select::ptr select = safs::create_io_select(ios); // The task runs until there are no tasks left in the queue. while (dispatch->issue_task()) safs::wait4ios(select, max_pending_ios); // Test if all I/O instances have processed all requests. size_t num_pending = safs::wait4ios(select, 0); assert(num_pending == 0); pthread_spin_lock(&lock); EM_objs.clear(); pthread_spin_unlock(&lock); for (size_t i = 0; i < ios.size(); i++) { portion_callback &cb = static_cast<portion_callback &>( ios[i]->get_callback()); assert(!cb.has_callback()); } } global_counter::global_counter() { counts.resize(mem_thread_pool::get_global_num_threads() + 1); reset(); } void global_counter::inc(size_t val) { int id = mem_thread_pool::get_curr_thread_id(); // the main thread has id of -1. counts[id + 1].count += val; } void global_counter::reset() { for (size_t i = 0; i < counts.size(); i++) counts[i].count = 0; } size_t global_counter::get() const { size_t tot = 0; for (size_t i = 0; i < counts.size(); i++) tot += counts[i].count; return tot; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fmobjfac.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2003-12-11 12:17:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _SVDOBJ_HXX #include "svdobj.hxx" #endif #ifndef _SVX_FMTOOLS_HXX #include "fmtools.hxx" #endif #ifndef _SVX_FMSERVS_HXX #include "fmservs.hxx" #endif #ifndef _FM_FMOBJFAC_HXX #include "fmobjfac.hxx" #endif #ifndef _FM_FMGLOB_HXX #include "fmglob.hxx" #endif #ifndef _FM_FMOBJ_HXX #include "fmobj.hxx" #endif #ifndef _SVX_FMSHIMP_HXX #include "fmshimp.hxx" #endif #ifndef _FM_FMSHELL_HXX #include "fmshell.hxx" #endif #ifndef _SVX_SVXIDS_HRC #include "svxids.hrc" #endif #ifndef _SVX_TBXFORM_HXX #include "tbxform.hxx" #endif #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif #ifndef _SVX_FMRESIDS_HRC #include "fmresids.hrc" #endif #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _SVX_FMSERVS_HXX #include "fmservs.hxx" #endif #ifndef _SVX_TABWIN_HXX #include "tabwin.hxx" #endif #ifndef _SVX_FMEXPL_HXX #include "fmexpl.hxx" #endif #ifndef _SVX_FILTNAV_HXX #include "filtnav.hxx" #endif #ifndef _SVX_FMPROP_HRC #include "fmprop.hrc" #endif #ifndef SVX_FMPROPBRW_HXX #include "fmPropBrw.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::svxform; /************************************************************************* |* |* Ctor |* \************************************************************************/ FmFormObjFactory::FmFormObjFactory() { SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject)); ////////////////////////////////////////////////////////////////////// // Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG ); SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE ); SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT ); SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT ); SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL ); SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV ); SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT ); ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE); // Registrieung von globalen fenstern FmFieldWinMgr::RegisterChildWindow(); FmPropBrwMgr::RegisterChildWindow(); NavigatorFrameManager::RegisterChildWindow(); FmFilterNavigatorWinMgr::RegisterChildWindow(); ////////////////////////////////////////////////////////////////////// // Interface fuer die Formshell registrieren FmFormShell::RegisterInterface(0); ImplSmartRegisterUnoServices(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ FmFormObjFactory::~FmFormObjFactory() { } /************************************************************************* |* |* ::com::sun::star::form::Form-Objekte erzeugen |* \************************************************************************/ namespace { void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue ) { try { Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY ); if ( xModelSet.is() ) xModelSet->setPropertyValue( _rPropName, _rValue ); } catch( const Exception& ) { DBG_ERROR( "lcl_initProperty: caught an exception!" ); } } } IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory) { if (pObjFactory->nInventor == FmFormInventor) { switch (pObjFactory->nIdentifier) { case OBJ_FM_CONTROL: // allgemeines Object { pObjFactory->pNewObj = new FmFormObj(pObjFactory->nIdentifier); } break; case OBJ_FM_EDIT: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_EDIT,pObjFactory->nIdentifier); } break; case OBJ_FM_BUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_COMMANDBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_FIXEDTEXT: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FIXEDTEXT,pObjFactory->nIdentifier); } break; case OBJ_FM_LISTBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_LISTBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_CHECKBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_CHECKBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_RADIOBUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_RADIOBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_GROUPBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_GROUPBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_COMBOBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_COMBOBOX,pObjFactory->nIdentifier); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_DROPDOWN, makeAny( sal_True ) ); } break; case OBJ_FM_GRID: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_GRID,pObjFactory->nIdentifier); } break; case OBJ_FM_IMAGEBUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_IMAGEBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_FILECONTROL: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FILECONTROL,pObjFactory->nIdentifier); } break; case OBJ_FM_DATEFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_DATEFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_TIMEFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_TIMEFIELD,pObjFactory->nIdentifier); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ); } break; case OBJ_FM_NUMERICFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_NUMERICFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_CURRENCYFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_CURRENCYFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_PATTERNFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_PATTERNFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_HIDDEN: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_HIDDEN,pObjFactory->nIdentifier); } break; case OBJ_FM_IMAGECONTROL: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_IMAGECONTROL,pObjFactory->nIdentifier); } break; case OBJ_FM_FORMATTEDFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FORMATTEDFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_SCROLLBAR: { pObjFactory->pNewObj = new FmFormObj( FM_SUN_COMPONENT_SCROLLBAR, pObjFactory->nIdentifier ); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ); } break; case OBJ_FM_SPINBUTTON: { pObjFactory->pNewObj = new FmFormObj( FM_SUN_COMPONENT_SPINBUTTON, pObjFactory->nIdentifier ); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ); } break; default: return 0; } } return 0; } <commit_msg>INTEGRATION: CWS dialogdiet (1.8.480); FILE MERGED 2004/01/19 20:50:34 mba 1.8.480.2: RESYNC: (1.8-1.9); FILE MERGED 2003/11/28 17:49:12 mba 1.8.480.1: #i22972#: make factory aware of multiple inits<commit_after>/************************************************************************* * * $RCSfile: fmobjfac.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-02-03 19:07:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _SVDOBJ_HXX #include "svdobj.hxx" #endif #ifndef _SVX_FMTOOLS_HXX #include "fmtools.hxx" #endif #ifndef _SVX_FMSERVS_HXX #include "fmservs.hxx" #endif #ifndef _FM_FMOBJFAC_HXX #include "fmobjfac.hxx" #endif #ifndef _FM_FMGLOB_HXX #include "fmglob.hxx" #endif #ifndef _FM_FMOBJ_HXX #include "fmobj.hxx" #endif #ifndef _SVX_FMSHIMP_HXX #include "fmshimp.hxx" #endif #ifndef _FM_FMSHELL_HXX #include "fmshell.hxx" #endif #ifndef _SVX_SVXIDS_HRC #include "svxids.hrc" #endif #ifndef _SVX_TBXFORM_HXX #include "tbxform.hxx" #endif #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif #ifndef _SVX_FMRESIDS_HRC #include "fmresids.hrc" #endif #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _SVX_FMSERVS_HXX #include "fmservs.hxx" #endif #ifndef _SVX_TABWIN_HXX #include "tabwin.hxx" #endif #ifndef _SVX_FMEXPL_HXX #include "fmexpl.hxx" #endif #ifndef _SVX_FILTNAV_HXX #include "filtnav.hxx" #endif #ifndef _SVX_FMPROP_HRC #include "fmprop.hrc" #endif #ifndef SVX_FMPROPBRW_HXX #include "fmPropBrw.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::svxform; static BOOL bInit = FALSE; /************************************************************************* |* |* Ctor |* \************************************************************************/ FmFormObjFactory::FmFormObjFactory() { if ( !bInit ) { SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject)); ////////////////////////////////////////////////////////////////////// // Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG ); SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE ); SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT ); SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT ); SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL ); SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV ); SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT ); ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE); // Registrieung von globalen fenstern FmFieldWinMgr::RegisterChildWindow(); FmPropBrwMgr::RegisterChildWindow(); NavigatorFrameManager::RegisterChildWindow(); FmFilterNavigatorWinMgr::RegisterChildWindow(); ////////////////////////////////////////////////////////////////////// // Interface fuer die Formshell registrieren FmFormShell::RegisterInterface(0); ImplSmartRegisterUnoServices(); bInit = TRUE; } } /************************************************************************* |* |* Dtor |* \************************************************************************/ FmFormObjFactory::~FmFormObjFactory() { } /************************************************************************* |* |* ::com::sun::star::form::Form-Objekte erzeugen |* \************************************************************************/ namespace { void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue ) { try { Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY ); if ( xModelSet.is() ) xModelSet->setPropertyValue( _rPropName, _rValue ); } catch( const Exception& ) { DBG_ERROR( "lcl_initProperty: caught an exception!" ); } } } IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory) { if (pObjFactory->nInventor == FmFormInventor) { switch (pObjFactory->nIdentifier) { case OBJ_FM_CONTROL: // allgemeines Object { pObjFactory->pNewObj = new FmFormObj(pObjFactory->nIdentifier); } break; case OBJ_FM_EDIT: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_EDIT,pObjFactory->nIdentifier); } break; case OBJ_FM_BUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_COMMANDBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_FIXEDTEXT: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FIXEDTEXT,pObjFactory->nIdentifier); } break; case OBJ_FM_LISTBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_LISTBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_CHECKBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_CHECKBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_RADIOBUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_RADIOBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_GROUPBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_GROUPBOX,pObjFactory->nIdentifier); } break; case OBJ_FM_COMBOBOX: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_COMBOBOX,pObjFactory->nIdentifier); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_DROPDOWN, makeAny( sal_True ) ); } break; case OBJ_FM_GRID: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_GRID,pObjFactory->nIdentifier); } break; case OBJ_FM_IMAGEBUTTON: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_IMAGEBUTTON,pObjFactory->nIdentifier); } break; case OBJ_FM_FILECONTROL: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FILECONTROL,pObjFactory->nIdentifier); } break; case OBJ_FM_DATEFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_DATEFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_TIMEFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_TIMEFIELD,pObjFactory->nIdentifier); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ); } break; case OBJ_FM_NUMERICFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_NUMERICFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_CURRENCYFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_CURRENCYFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_PATTERNFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_PATTERNFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_HIDDEN: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_HIDDEN,pObjFactory->nIdentifier); } break; case OBJ_FM_IMAGECONTROL: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_IMAGECONTROL,pObjFactory->nIdentifier); } break; case OBJ_FM_FORMATTEDFIELD: { pObjFactory->pNewObj = new FmFormObj(FM_COMPONENT_FORMATTEDFIELD,pObjFactory->nIdentifier); } break; case OBJ_FM_SCROLLBAR: { pObjFactory->pNewObj = new FmFormObj( FM_SUN_COMPONENT_SCROLLBAR, pObjFactory->nIdentifier ); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ); } break; case OBJ_FM_SPINBUTTON: { pObjFactory->pNewObj = new FmFormObj( FM_SUN_COMPONENT_SPINBUTTON, pObjFactory->nIdentifier ); lcl_initProperty( static_cast< FmFormObj* >( pObjFactory->pNewObj ), FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ); } break; default: return 0; } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: annotsh.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-02-19 13:55:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWANNOTSH_HXX #define _SWANNOTSH_HXX #include <sfx2/shell.hxx> #include "shellid.hxx" #include "swmodule.hxx" class SwView; class SwAnnotationShell: public SfxShell { SwView& rView; public: SFX_DECL_INTERFACE(SW_ANNOTATIONSHELL) TYPEINFO(); SwAnnotationShell(SwView&); virtual ~SwAnnotationShell(); void StateDisableItems(SfxItemSet &); void Exec(SfxRequest &); void GetState(SfxItemSet &); void StateInsert(SfxItemSet &rSet); void NoteExec(SfxRequest &); void GetNoteState(SfxItemSet &); void ExecLingu(SfxRequest &rReq); void GetLinguState(SfxItemSet &); void ExecClpbrd(SfxRequest &rReq); void StateClpbrd(SfxItemSet &rSet); void ExecTransliteration(SfxRequest &); void ExecUndo(SfxRequest &rReq); void StateUndo(SfxItemSet &rSet); void InsertSymbol(SfxRequest& rReq); virtual SfxUndoManager* GetUndoManager(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.78); FILE MERGED 2008/03/31 16:58:26 rt 1.2.78.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: annotsh.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SWANNOTSH_HXX #define _SWANNOTSH_HXX #include <sfx2/shell.hxx> #include "shellid.hxx" #include "swmodule.hxx" class SwView; class SwAnnotationShell: public SfxShell { SwView& rView; public: SFX_DECL_INTERFACE(SW_ANNOTATIONSHELL) TYPEINFO(); SwAnnotationShell(SwView&); virtual ~SwAnnotationShell(); void StateDisableItems(SfxItemSet &); void Exec(SfxRequest &); void GetState(SfxItemSet &); void StateInsert(SfxItemSet &rSet); void NoteExec(SfxRequest &); void GetNoteState(SfxItemSet &); void ExecLingu(SfxRequest &rReq); void GetLinguState(SfxItemSet &); void ExecClpbrd(SfxRequest &rReq); void StateClpbrd(SfxItemSet &rSet); void ExecTransliteration(SfxRequest &); void ExecUndo(SfxRequest &rReq); void StateUndo(SfxItemSet &rSet); void InsertSymbol(SfxRequest& rReq); virtual SfxUndoManager* GetUndoManager(); }; #endif <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 28.06.2018 /// @brief BS tree links serialization code /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/serialize/tree.h> #include <bs/serialize/boost_uuid.h> #include <bs/serialize/base_types.h> #include <cereal/types/polymorphic.hpp> using namespace cereal; using namespace blue_sky; /*----------------------------------------------------------------------------- * inode *-----------------------------------------------------------------------------*/ BSS_FCN_BEGIN(save, tree::inode) ar( make_nvp("owner", t.owner), make_nvp("group", t.group), make_nvp("suid", t.suid), make_nvp("sgid", t.sgid), make_nvp("sticky", t.sticky), make_nvp("u", t.u), make_nvp("g", t.g), make_nvp("o", t.o) ); BSS_FCN_END BSS_FCN_BEGIN(load, tree::inode) ar( make_nvp("owner", t.owner), make_nvp("group", t.group) ); bool bit; ar(make_nvp("suid", bit)); t.suid = bit; ar(make_nvp("sgid", bit)); t.sgid = bit; ar(make_nvp("sticky", bit)); t.sticky = bit; std::uint8_t flags; ar(make_nvp("u", flags)); t.u = flags; ar(make_nvp("g", flags)); t.g = flags; ar(make_nvp("o", flags)); t.o = flags; BSS_FCN_END BSS_FCN_EXPORT(save, tree::inode) BSS_FCN_EXPORT(load, tree::inode) /*----------------------------------------------------------------------------- * link *-----------------------------------------------------------------------------*/ BSS_FCN_BEGIN(serialize, tree::link) // [NOTE] intentinaly DON'T save name, // because name will be saved in derived classes to invoke minimal constructor // also do not save owner, because owner will be correctly set by `node` ar( // make_nvp("name", t.name_), make_nvp("id", t.id_), make_nvp("flags", t.flags_), make_nvp("inode", t.inode_) // intentionally do net serialize owner, it will be set up when parent node is loaded ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::link) /*----------------------------------------------------------------------------- * hard_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::hard_link) // load name? data & construct instance std::string name; sp_obj data; ar(name, data); construct(std::move(name), std::move(data)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::hard_link) ar( make_nvp("name", t.name_), make_nvp("data", t.data_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::hard_link) /*----------------------------------------------------------------------------- * weak_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::weak_link) // load name? data & construct instance std::string name; sp_obj data; ar(name, data); construct(std::move(name), std::move(data)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::weak_link) ar( make_nvp("name", t.name_), make_nvp("data", t.data_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::weak_link) /*----------------------------------------------------------------------------- * sym_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::sym_link) // load both name and path & construct instance std::string name, path; ar(name, path); construct(std::move(name), std::move(path)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::sym_link) ar( make_nvp("name", t.name_), make_nvp("path", t.path_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::sym_link) // instantiate code for polymorphic types using namespace blue_sky; //CEREAL_REGISTER_TYPE_WITH_NAME(tree::link, "link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link, "hard_link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link, "weak_link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link, "sym_link") BSS_REGISTER_DYNAMIC_INIT(link) <commit_msg>serial/link: add forgotten exports of load_and_construct for links<commit_after>/// @file /// @author uentity /// @date 28.06.2018 /// @brief BS tree links serialization code /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/serialize/tree.h> #include <bs/serialize/boost_uuid.h> #include <bs/serialize/base_types.h> #include <cereal/types/polymorphic.hpp> using namespace cereal; using namespace blue_sky; /*----------------------------------------------------------------------------- * inode *-----------------------------------------------------------------------------*/ BSS_FCN_BEGIN(save, tree::inode) ar( make_nvp("owner", t.owner), make_nvp("group", t.group), make_nvp("suid", t.suid), make_nvp("sgid", t.sgid), make_nvp("sticky", t.sticky), make_nvp("u", t.u), make_nvp("g", t.g), make_nvp("o", t.o) ); BSS_FCN_END BSS_FCN_BEGIN(load, tree::inode) ar( make_nvp("owner", t.owner), make_nvp("group", t.group) ); bool bit; ar(make_nvp("suid", bit)); t.suid = bit; ar(make_nvp("sgid", bit)); t.sgid = bit; ar(make_nvp("sticky", bit)); t.sticky = bit; std::uint8_t flags; ar(make_nvp("u", flags)); t.u = flags; ar(make_nvp("g", flags)); t.g = flags; ar(make_nvp("o", flags)); t.o = flags; BSS_FCN_END BSS_FCN_EXPORT(save, tree::inode) BSS_FCN_EXPORT(load, tree::inode) /*----------------------------------------------------------------------------- * link *-----------------------------------------------------------------------------*/ BSS_FCN_BEGIN(serialize, tree::link) // [NOTE] intentinaly DON'T save name, // because name will be saved in derived classes to invoke minimal constructor // also do not save owner, because owner will be correctly set by `node` ar( // make_nvp("name", t.name_), make_nvp("id", t.id_), make_nvp("flags", t.flags_), make_nvp("inode", t.inode_) // intentionally do net serialize owner, it will be set up when parent node is loaded ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::link) /*----------------------------------------------------------------------------- * hard_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::hard_link) // load name? data & construct instance std::string name; sp_obj data; ar(name, data); construct(std::move(name), std::move(data)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::hard_link) ar( make_nvp("name", t.name_), make_nvp("data", t.data_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::hard_link) BSS_FCN_EXPORT(load_and_construct, tree::hard_link) /*----------------------------------------------------------------------------- * weak_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::weak_link) // load name? data & construct instance std::string name; sp_obj data; ar(name, data); construct(std::move(name), std::move(data)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::weak_link) ar( make_nvp("name", t.name_), make_nvp("data", t.data_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::weak_link) BSS_FCN_EXPORT(load_and_construct, tree::weak_link) /*----------------------------------------------------------------------------- * sym_link *-----------------------------------------------------------------------------*/ // provide non-empty constructor BSS_FCN_BEGIN(load_and_construct, tree::sym_link) // load both name and path & construct instance std::string name, path; ar(name, path); construct(std::move(name), std::move(path)); // load base link ar(base_class<tree::link>(construct.ptr())); BSS_FCN_END BSS_FCN_BEGIN(serialize, tree::sym_link) ar( make_nvp("name", t.name_), make_nvp("path", t.path_), make_nvp("link_base", base_class<tree::link>(&t)) ); BSS_FCN_END BSS_FCN_EXPORT(serialize, tree::sym_link) BSS_FCN_EXPORT(load_and_construct, tree::sym_link) // instantiate code for polymorphic types using namespace blue_sky; //CEREAL_REGISTER_TYPE_WITH_NAME(tree::link, "link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link, "hard_link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link, "weak_link") CEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link, "sym_link") BSS_REGISTER_DYNAMIC_INIT(link) <|endoftext|>
<commit_before>/* * File: other_updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/mo/micro.h" #include "tr/auth/auc.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif void replace(PPOpIn arg) { //1.seq-replaced nodes //2.replacements //3. persistent replacements+their position in 2 seq // xptr addr(0,(void*)0x4acc0000); // check_blk_consistency(addr); xptr node, parent, tmp_node, old_node, node_child, repl_node_child, del_node; schema_node* scm_node; tuple t(arg.ts); descript_sequence arg3seq(2); xptr_sequence arg1seq; xptr_sequence arg1seq_tmp; xptr_sequence arg2seq; upd_ns_map* ins_swiz=NULL; bool is_node_updated=true; arg.op->next(t); while (!t.is_eos()) { if (t.cells[0].is_node()) { node=t.cells[0].get_node(); CHECKP(node); if ((!is_node_updated || is_node_persistent(node))&& !is_node_document(node)) { xptr indir=((n_dsc*)XADDR(node))->indir; if (is_node_updated) { is_node_updated=false; arg1seq.add(indir); arg1seq_tmp.add(node); } else { if (is_node_persistent(node)) { tuple tup(2); tup.copy(tuple_cell::node(node),tuple_cell((__int64)(arg2seq.size()))); arg3seq.add(tup); } arg2seq.add(indir); } } #ifndef IGNORE_UPDATE_ERRORS else { throw USER_EXCEPTION(SE2020); } #endif } else { if (t.cells[0].get_atomic_type()==se_separator) { arg2seq.add(XNULL); is_node_updated=true; } #ifndef IGNORE_UPDATE_ERRORS else throw USER_EXCEPTION(SE2021); #endif } arg.op->next(t); } if (arg1seq.size()<=0) return; //merge 1'st and 3'rd sequences create copy of merged items // Checking authorization if (is_auth_check_needed(REPLACE_STATEMENT)) auth_for_update(&arg1seq, REPLACE_STATEMENT, false); arg1seq_tmp.sort(); arg3seq.sort(); descript_sequence::iterator it3=arg3seq.begin(); xptr_sequence::iterator it1=arg1seq_tmp.begin(); while(it3!=arg3seq.end()&& it1!=arg1seq_tmp.end()) { switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1)) { case 0: { node=copy_to_temp((*it3).cells[0].get_node()); xptr indir=((n_dsc*)XADDR(node))->indir; // arg2seq[(*it3).cells[1].get_xs_integer()]=indir; arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3;//++it1; } break; case 1: ++it1; break; case 2: ++it1; break; case -1: ++it3; break; case -2: { node=copy_to_temp((*it3).cells[0].get_node()); xptr indir=((n_dsc*)XADDR(node))->indir; arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3; } break; } } #ifdef SE_ENABLE_FTSEARCH clear_ft_sequences(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); #endif //sorting arg1seq arg3seq.clear(); xptr_sequence::iterator it=arg1seq.begin(); xptr_sequence::iterator sit=arg2seq.begin(); int ctr=0; do { tuple tup(2); tup.copy(tuple_cell::node(removeIndirection(*it)),tuple_cell((__int64)ctr)); arg3seq.add(tup); while(*sit!=XNULL) { sit++; ctr++; } sit++; ctr++; it++; } while (it!=arg1seq.end()); arg3seq.sort(); it3=arg3seq.begin(); descript_sequence arg4seq(2); do { node=(*it3).cells[0].get_node(); CHECKP(node); xptr tind=((n_dsc*)XADDR(node))->indir; tuple t=(*it3); t.cells[0].set_node(tind); ++it3; arg4seq.add(t); } while (it3!=arg3seq.end()); // deleting- inserting new nodes it3=arg4seq.end(); do { --it3; node = old_node = removeIndirection((*it3).cells[0].get_node()); int pos=(*it3).cells[1].get_xs_integer(); sit=arg2seq.begin()+pos; CHECKP(node); xptr leftn=((n_dsc*)XADDR(old_node))->ldsc; xptr rightn=((n_dsc*)XADDR(old_node))->rdsc; xptr par_ind=((n_dsc*)XADDR(old_node))->pdsc; bool a_m=is_node_attribute(node); bool d_m=a_m||is_node_text(node); #ifdef SE_ENABLE_TRIGGERS CHECKP(old_node); scm_node = GETSCHEMENODEX(old_node); parent=removeIndirection(((n_dsc*)XADDR(old_node))->pdsc); CHECKP(old_node); tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT); #endif #ifdef SE_ENABLE_TRIGGERS // Before-for-each-node triggers (cycle for all inserted nodes) xptr_sequence::iterator tr_it=sit; while(*tr_it!=XNULL) { node_child=*tr_it; parent=removeIndirection(par_ind); if(apply_per_node_triggers(removeIndirection(node_child), old_node, parent, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT) == XNULL) goto next_replacement; tr_it++; } #endif //pre_deletion if (d_m) { delete_node(old_node); } //1.inserting attributes from sequence while(*sit!=XNULL) { node_child=*sit; if (!is_node_attribute(removeIndirection(node_child))) break; parent=removeIndirection(par_ind); if (is_node_persistent(node_child)) node=deep_pers_copy(XNULL, XNULL, parent, removeIndirection(node_child),true); else node=deep_temp_copy(XNULL, XNULL, parent, removeIndirection(node_child),ins_swiz); sit++; #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } //2. finding place of insertion if (a_m) { node=getFirstByOrderChildNode(removeIndirection(par_ind)); if (node!=XNULL) { if (is_node_element(node)) { rightn=node; node=XNULL; } else { rightn=XNULL; } } } else { if (d_m) { if (rightn==XNULL) node=leftn; else node=XNULL; } else { rightn=node; node=XNULL; } } //3.main insert cycle while(*sit!=XNULL) { node_child=*sit; parent=removeIndirection(par_ind); if (is_node_persistent(node_child)) node=deep_pers_copy(node, rightn, parent, removeIndirection(node_child),true); else node=deep_temp_copy(node, rightn, parent, removeIndirection(node_child),ins_swiz); sit++; #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } //post_deletion if (!d_m) { del_node = removeIndirection((*it3).cells[0].get_node()); CHECKP(del_node); delete_node(del_node); } /* #ifdef SE_ENABLE_TRIGGERS CHECKP(old_node); scm_node = GETSCHEMENODEX(old_node); parent=removeIndirection(((n_dsc*)XADDR(old_node))->pdsc); CHECKP(old_node); tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT); #endif //1.insert while(*sit!=XNULL) { node_child=*sit; #ifdef SE_ENABLE_TRIGGERS repl_node_child = apply_per_node_triggers(removeIndirection(node_child), old_node, XNULL, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); if(repl_node_child==XNULL) goto next_replacement; CHECKP(repl_node_child); node_child = ((n_dsc*)XADDR(repl_node_child))->indir; #endif CHECKP(node); if ( is_node_attribute(removeIndirection(node_child))) { parent=removeIndirection(GETPARENTPOINTER(node)); if (is_node_persistent(node_child)) node=deep_pers_copy(XNULL, XNULL, parent, removeIndirection(node_child),true); else node=deep_temp_copy(XNULL, XNULL, parent, removeIndirection(node_child),ins_swiz); } else { if (is_node_persistent(node_child)) node=deep_pers_copy(node, XNULL, XNULL, removeIndirection(node_child),true); else node=deep_temp_copy(node, XNULL, XNULL, removeIndirection(node_child),ins_swiz); } sit++; } //delete node del_node = removeIndirection((*it3).cells[0].get_node()); CHECKP(del_node); delete_node(del_node); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } if (border!=XNULL) { delete_node(removeIndirection(border)); border=XNULL; } */ next_replacement:; } while (it3!=arg4seq.begin()); //3.delete /* arg2seq.clear(); it=arg1seq.begin(); while (it!=arg1seq.end()) { arg2seq.add(removeIndirection(*it)); ++it; } arg2seq.sort(); it=arg2seq.end(); do { --it; delete_node(*it); if (it==arg2seq.begin()) break; } while (true); */ if (ins_swiz!=NULL) { // checkSwiizleTab(ins_swiz); delete ins_swiz; } clear_temp(); #ifdef SE_ENABLE_FTSEARCH execute_modifications(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif }<commit_msg>replace fix<commit_after>/* * File: other_updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/mo/micro.h" #include "tr/auth/auc.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif void replace(PPOpIn arg) { //1.seq-replaced nodes //2.replacements //3. persistent replacements+their position in 2 seq // xptr addr(0,(void*)0x4acc0000); // check_blk_consistency(addr); xptr node, parent, tmp_node, old_node, node_child, repl_node_child, del_node; schema_node* scm_node; tuple t(arg.ts); descript_sequence arg3seq(2); xptr_sequence arg1seq; xptr_sequence arg1seq_tmp; xptr_sequence arg2seq; upd_ns_map* ins_swiz=NULL; bool is_node_updated=true; arg.op->next(t); while (!t.is_eos()) { if (t.cells[0].is_node()) { node=t.cells[0].get_node(); CHECKP(node); if ((!is_node_updated || is_node_persistent(node))&& !is_node_document(node)) { xptr indir=((n_dsc*)XADDR(node))->indir; if (is_node_updated) { is_node_updated=false; arg1seq.add(indir); arg1seq_tmp.add(node); } else { if (is_node_persistent(node)) { tuple tup(2); tup.copy(tuple_cell::node(node),tuple_cell((__int64)(arg2seq.size()))); arg3seq.add(tup); } arg2seq.add(indir); } } #ifndef IGNORE_UPDATE_ERRORS else { throw USER_EXCEPTION(SE2020); } #endif } else { if (t.cells[0].get_atomic_type()==se_separator) { arg2seq.add(XNULL); is_node_updated=true; } #ifndef IGNORE_UPDATE_ERRORS else throw USER_EXCEPTION(SE2021); #endif } arg.op->next(t); } if (arg1seq.size()<=0) return; //merge 1'st and 3'rd sequences create copy of merged items // Checking authorization if (is_auth_check_needed(REPLACE_STATEMENT)) auth_for_update(&arg1seq, REPLACE_STATEMENT, false); arg1seq_tmp.sort(); arg3seq.sort(); descript_sequence::iterator it3=arg3seq.begin(); xptr_sequence::iterator it1=arg1seq_tmp.begin(); while(it3!=arg3seq.end()&& it1!=arg1seq_tmp.end()) { switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1)) { case 0: { node=copy_to_temp((*it3).cells[0].get_node()); xptr indir=((n_dsc*)XADDR(node))->indir; // arg2seq[(*it3).cells[1].get_xs_integer()]=indir; arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3;//++it1; } break; case 1: ++it1; break; case 2: ++it1; break; case -1: ++it3; break; case -2: { node=copy_to_temp((*it3).cells[0].get_node()); xptr indir=((n_dsc*)XADDR(node))->indir; arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3; } break; } } #ifdef SE_ENABLE_FTSEARCH clear_ft_sequences(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); #endif //sorting arg1seq arg3seq.clear(); xptr_sequence::iterator it=arg1seq.begin(); xptr_sequence::iterator sit=arg2seq.begin(); int ctr=0; do { tuple tup(2); tup.copy(tuple_cell::node(removeIndirection(*it)),tuple_cell((__int64)ctr)); arg3seq.add(tup); while(*sit!=XNULL) { sit++; ctr++; } sit++; ctr++; it++; } while (it!=arg1seq.end()); arg3seq.sort(); it3=arg3seq.begin(); descript_sequence arg4seq(2); do { node=(*it3).cells[0].get_node(); CHECKP(node); xptr tind=((n_dsc*)XADDR(node))->indir; tuple t=(*it3); t.cells[0].set_node(tind); ++it3; arg4seq.add(t); } while (it3!=arg3seq.end()); // deleting- inserting new nodes it3=arg4seq.end(); do { --it3; node = old_node = removeIndirection((*it3).cells[0].get_node()); int pos=(*it3).cells[1].get_xs_integer(); sit=arg2seq.begin()+pos; CHECKP(node); xptr leftn=((n_dsc*)XADDR(old_node))->ldsc; xptr rightn=((n_dsc*)XADDR(old_node))->rdsc; xptr par_ind=((n_dsc*)XADDR(old_node))->pdsc; bool a_m=is_node_attribute(node); bool d_m=a_m||is_node_text(node); #ifdef SE_ENABLE_TRIGGERS CHECKP(old_node); scm_node = GETSCHEMENODEX(old_node); parent=removeIndirection(((n_dsc*)XADDR(old_node))->pdsc); CHECKP(old_node); tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT); #endif #ifdef SE_ENABLE_TRIGGERS // Before-for-each-node triggers (cycle for all inserted nodes) xptr_sequence::iterator tr_it=sit; while(*tr_it!=XNULL) { node_child=*tr_it; parent=removeIndirection(par_ind); if(apply_per_node_triggers(removeIndirection(node_child), old_node, parent, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT) == XNULL) goto next_replacement; tr_it++; } #endif //pre_deletion if (d_m) { delete_node(old_node); } //1.inserting attributes from sequence while(*sit!=XNULL) { node_child=*sit; if (!is_node_attribute(removeIndirection(node_child))) break; parent=removeIndirection(par_ind); if (is_node_persistent(node_child)) node=deep_pers_copy(XNULL, XNULL, parent, removeIndirection(node_child),true); else node=deep_temp_copy(XNULL, XNULL, parent, removeIndirection(node_child),ins_swiz); sit++; #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } //2. finding place of insertion if (a_m) { node=getFirstByOrderChildNode(removeIndirection(par_ind)); if (node!=XNULL) { if (is_node_element(node)) { rightn=node; node=XNULL; } else { rightn=XNULL; } } } else { if (d_m) { if (rightn==XNULL) node=leftn; else node=XNULL; } else { } } //3.main insert cycle while(*sit!=XNULL) { node_child=*sit; parent=removeIndirection(par_ind); if (is_node_persistent(node_child)) node=deep_pers_copy(node, rightn, parent, removeIndirection(node_child),true); else node=deep_temp_copy(node, rightn, parent, removeIndirection(node_child),ins_swiz); sit++; #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } //post_deletion if (!d_m) { del_node = removeIndirection((*it3).cells[0].get_node()); CHECKP(del_node); delete_node(del_node); } /* #ifdef SE_ENABLE_TRIGGERS CHECKP(old_node); scm_node = GETSCHEMENODEX(old_node); parent=removeIndirection(((n_dsc*)XADDR(old_node))->pdsc); CHECKP(old_node); tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT); #endif //1.insert while(*sit!=XNULL) { node_child=*sit; #ifdef SE_ENABLE_TRIGGERS repl_node_child = apply_per_node_triggers(removeIndirection(node_child), old_node, XNULL, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); if(repl_node_child==XNULL) goto next_replacement; CHECKP(repl_node_child); node_child = ((n_dsc*)XADDR(repl_node_child))->indir; #endif CHECKP(node); if ( is_node_attribute(removeIndirection(node_child))) { parent=removeIndirection(GETPARENTPOINTER(node)); if (is_node_persistent(node_child)) node=deep_pers_copy(XNULL, XNULL, parent, removeIndirection(node_child),true); else node=deep_temp_copy(XNULL, XNULL, parent, removeIndirection(node_child),ins_swiz); } else { if (is_node_persistent(node_child)) node=deep_pers_copy(node, XNULL, XNULL, removeIndirection(node_child),true); else node=deep_temp_copy(node, XNULL, XNULL, removeIndirection(node_child),ins_swiz); } sit++; } //delete node del_node = removeIndirection((*it3).cells[0].get_node()); CHECKP(del_node); delete_node(del_node); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } if (border!=XNULL) { delete_node(removeIndirection(border)); border=XNULL; } */ next_replacement:; } while (it3!=arg4seq.begin()); //3.delete /* arg2seq.clear(); it=arg1seq.begin(); while (it!=arg1seq.end()) { arg2seq.add(removeIndirection(*it)); ++it; } arg2seq.sort(); it=arg2seq.end(); do { --it; delete_node(*it); if (it==arg2seq.begin()) break; } while (true); */ if (ins_swiz!=NULL) { // checkSwiizleTab(ins_swiz); delete ins_swiz; } clear_temp(); #ifdef SE_ENABLE_FTSEARCH execute_modifications(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif }<|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- wizard.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "wizard.h" #include "wizardpage.h" #include "kleo-assuan.h" #include <KLocale> #include <KPushButton> #include <QDialogButtonBox> #include <QFrame> #include <QLabel> #include <QStackedWidget> #include <QVBoxLayout> #include <QWizard> #include <map> #include <cassert> using namespace Kleo; class Wizard::Private { friend class ::Wizard; Wizard * const q; public: explicit Private( Wizard * qq ); ~Private(); void updateButtonStates(); bool isLastPage( int id ) const; int previousPage() const; private: std::vector<int> pageOrder; std::map<int, WizardPage*> idToPage; int currentId; QStackedWidget* stack; QPushButton* nextButton; QPushButton* backButton; QString finishItem; QString nextItem; QFrame* titleFrame; QLabel* titleLabel; QLabel* subTitleLabel; }; Wizard::Private::Private( Wizard * qq ) : q( qq ), currentId( -1 ), stack( new QStackedWidget ) { const QWizard wiz; nextItem = wiz.buttonText( QWizard::NextButton ); finishItem = wiz.buttonText( QWizard::FinishButton ); QVBoxLayout * const top = new QVBoxLayout( q ); top->setMargin( 0 ); titleFrame = new QFrame; titleFrame->setFrameShape( QFrame::StyledPanel ); titleFrame->setAutoFillBackground( true ); titleFrame->setBackgroundRole( QPalette::Base ); QVBoxLayout* const titleLayout = new QVBoxLayout( titleFrame ); titleLabel = new QLabel; titleLayout->addWidget( titleLabel ); subTitleLabel = new QLabel; subTitleLabel->setWordWrap( true ); titleLayout->addWidget( subTitleLabel ); top->addWidget( titleFrame ); titleFrame->setVisible( false ); QWidget* const contentWidget = new QWidget; QVBoxLayout* const contentLayout = new QVBoxLayout( contentWidget ); contentLayout->addWidget( stack ); QDialogButtonBox * const box = new QDialogButtonBox; QAbstractButton* const cancelButton = box->addButton( QDialogButtonBox::Cancel ); q->connect( cancelButton, SIGNAL( clicked() ), q, SLOT( reject() ) ); backButton = new QPushButton; backButton->setText( wiz.buttonText( QWizard::BackButton ) ); q->connect( backButton, SIGNAL( clicked() ), q, SLOT( back() ) ); box->addButton( backButton, QDialogButtonBox::ActionRole ); nextButton = new QPushButton; nextButton->setText( nextItem ); q->connect( nextButton, SIGNAL( clicked() ), q, SLOT( next() ) ); box->addButton( nextButton, QDialogButtonBox::ActionRole ); contentLayout->addWidget( box ); top->addWidget( contentWidget ); q->connect( q, SIGNAL( rejected() ), q, SIGNAL( canceled() ) ); q->resize( QSize( 640, 480 ).expandedTo( q->sizeHint() ) ); } Wizard::Private::~Private() {} bool Wizard::Private::isLastPage( int id ) const { return !pageOrder.empty() ? pageOrder.back() == id : false; } void Wizard::Private::updateButtonStates() { const bool isLast = isLastPage( currentId ); nextButton->setText( isLast ? finishItem : nextItem ); nextButton->setEnabled( q->canGoToNextPage() ); backButton->setEnabled( q->canGoToPreviousPage() ); } Wizard::Wizard( QWidget * parent, Qt::WFlags f ) : QDialog( parent, f ), d( new Private( this ) ) { } Wizard::~Wizard() {} void Wizard::setPage( int id, WizardPage* widget ) { assuan_assert( id != InvalidPage ); assuan_assert( d->idToPage.find( id ) == d->idToPage.end() ); d->idToPage[id] = widget; d->stack->addWidget( widget ); connect( widget, SIGNAL( completeChanged() ), this, SLOT( updateButtonStates() ) ); } void Wizard::setPageOrder( const std::vector<int>& pageOrder ) { d->pageOrder = pageOrder; if ( pageOrder.empty() ) return; setCurrentPage( pageOrder.front() ); } void Wizard::setCurrentPage( int id ) { d->currentId = id; if ( id == InvalidPage ) return; WizardPage * const widget = page( id ); assert( widget && d->stack->indexOf( widget ) != -1 ); d->stack->setCurrentWidget( widget ); const QString title = widget->title(); const QString subTitle = widget->subTitle(); d->titleFrame->setVisible( !title.isEmpty() || !subTitle.isEmpty() ); d->titleLabel->setText( title ); d->subTitleLabel->setText( subTitle ); d->updateButtonStates(); } void Wizard::skipPage( int id ) { const std::vector<int>::iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), id ); if ( it == d->pageOrder.end() ) return; if ( currentPage() == id ) next(); d->pageOrder.erase( it ); } int Wizard::currentPage() const { return d->currentId; } bool Wizard::canGoToNextPage() const { const WizardPage * const current = currentPageWidget(); return current ? current->isComplete() : false; } bool Wizard::canGoToPreviousPage() const { const int prev = d->previousPage(); if ( prev == InvalidPage ) return false; const WizardPage * const prevPage = page( prev ); assert( prevPage ); return !prevPage->isCommitPage(); } void Wizard::next() { std::vector<int>::const_iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), d->currentId ); assert( it != d->pageOrder.end() ); ++it; if ( it == d->pageOrder.end() ) // "Finish" { d->currentId = InvalidPage; close(); } else // "next" { setCurrentPage( *it ); } } int Wizard::Private::previousPage() const { if ( pageOrder.empty() ) return InvalidPage; std::vector<int>::const_iterator it = qBinaryFind( pageOrder.begin(), pageOrder.end(), currentId ); if ( it == pageOrder.begin() || it == pageOrder.end() ) return InvalidPage; --it; return *it; } void Wizard::back() { const int prev = d->previousPage(); if ( prev == InvalidPage ) return; setCurrentPage( prev ); } const WizardPage* Wizard::page( int id ) const { if ( id == InvalidPage ) return 0; const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id ); assuan_assert( it != d->idToPage.end() ); return (*it).second; } const WizardPage* Wizard::currentPageWidget() const { return page( d->currentId ); } WizardPage* Wizard::currentPageWidget() { return page( d->currentId ); } void Wizard::onNext( int currentId ) { Q_UNUSED( currentId ) } void Wizard::onBack( int currentId ) { Q_UNUSED( currentId ) } WizardPage* Wizard::page( int id ) { if ( id == InvalidPage ) return 0; const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id ); assuan_assert( it != d->idToPage.end() ); return (*it).second; } #include "moc_wizard.cpp" <commit_msg>call onNext/onBack<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- wizard.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "wizard.h" #include "wizardpage.h" #include "kleo-assuan.h" #include <KLocale> #include <KPushButton> #include <QDialogButtonBox> #include <QFrame> #include <QLabel> #include <QStackedWidget> #include <QVBoxLayout> #include <QWizard> #include <map> #include <cassert> using namespace Kleo; class Wizard::Private { friend class ::Wizard; Wizard * const q; public: explicit Private( Wizard * qq ); ~Private(); void updateButtonStates(); bool isLastPage( int id ) const; int previousPage() const; private: std::vector<int> pageOrder; std::map<int, WizardPage*> idToPage; int currentId; QStackedWidget* stack; QPushButton* nextButton; QPushButton* backButton; QString finishItem; QString nextItem; QFrame* titleFrame; QLabel* titleLabel; QLabel* subTitleLabel; }; Wizard::Private::Private( Wizard * qq ) : q( qq ), currentId( -1 ), stack( new QStackedWidget ) { const QWizard wiz; nextItem = wiz.buttonText( QWizard::NextButton ); finishItem = wiz.buttonText( QWizard::FinishButton ); QVBoxLayout * const top = new QVBoxLayout( q ); top->setMargin( 0 ); titleFrame = new QFrame; titleFrame->setFrameShape( QFrame::StyledPanel ); titleFrame->setAutoFillBackground( true ); titleFrame->setBackgroundRole( QPalette::Base ); QVBoxLayout* const titleLayout = new QVBoxLayout( titleFrame ); titleLabel = new QLabel; titleLayout->addWidget( titleLabel ); subTitleLabel = new QLabel; subTitleLabel->setWordWrap( true ); titleLayout->addWidget( subTitleLabel ); top->addWidget( titleFrame ); titleFrame->setVisible( false ); QWidget* const contentWidget = new QWidget; QVBoxLayout* const contentLayout = new QVBoxLayout( contentWidget ); contentLayout->addWidget( stack ); QDialogButtonBox * const box = new QDialogButtonBox; QAbstractButton* const cancelButton = box->addButton( QDialogButtonBox::Cancel ); q->connect( cancelButton, SIGNAL( clicked() ), q, SLOT( reject() ) ); backButton = new QPushButton; backButton->setText( wiz.buttonText( QWizard::BackButton ) ); q->connect( backButton, SIGNAL( clicked() ), q, SLOT( back() ) ); box->addButton( backButton, QDialogButtonBox::ActionRole ); nextButton = new QPushButton; nextButton->setText( nextItem ); q->connect( nextButton, SIGNAL( clicked() ), q, SLOT( next() ) ); box->addButton( nextButton, QDialogButtonBox::ActionRole ); contentLayout->addWidget( box ); top->addWidget( contentWidget ); q->connect( q, SIGNAL( rejected() ), q, SIGNAL( canceled() ) ); q->resize( QSize( 640, 480 ).expandedTo( q->sizeHint() ) ); } Wizard::Private::~Private() {} bool Wizard::Private::isLastPage( int id ) const { return !pageOrder.empty() ? pageOrder.back() == id : false; } void Wizard::Private::updateButtonStates() { const bool isLast = isLastPage( currentId ); nextButton->setText( isLast ? finishItem : nextItem ); nextButton->setEnabled( q->canGoToNextPage() ); backButton->setEnabled( q->canGoToPreviousPage() ); } Wizard::Wizard( QWidget * parent, Qt::WFlags f ) : QDialog( parent, f ), d( new Private( this ) ) { } Wizard::~Wizard() {} void Wizard::setPage( int id, WizardPage* widget ) { assuan_assert( id != InvalidPage ); assuan_assert( d->idToPage.find( id ) == d->idToPage.end() ); d->idToPage[id] = widget; d->stack->addWidget( widget ); connect( widget, SIGNAL( completeChanged() ), this, SLOT( updateButtonStates() ) ); } void Wizard::setPageOrder( const std::vector<int>& pageOrder ) { d->pageOrder = pageOrder; if ( pageOrder.empty() ) return; setCurrentPage( pageOrder.front() ); } void Wizard::setCurrentPage( int id ) { d->currentId = id; if ( id == InvalidPage ) return; WizardPage * const widget = page( id ); assert( widget && d->stack->indexOf( widget ) != -1 ); d->stack->setCurrentWidget( widget ); const QString title = widget->title(); const QString subTitle = widget->subTitle(); d->titleFrame->setVisible( !title.isEmpty() || !subTitle.isEmpty() ); d->titleLabel->setText( title ); d->subTitleLabel->setText( subTitle ); d->updateButtonStates(); } void Wizard::skipPage( int id ) { const std::vector<int>::iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), id ); if ( it == d->pageOrder.end() ) return; if ( currentPage() == id ) next(); d->pageOrder.erase( it ); } int Wizard::currentPage() const { return d->currentId; } bool Wizard::canGoToNextPage() const { const WizardPage * const current = currentPageWidget(); return current ? current->isComplete() : false; } bool Wizard::canGoToPreviousPage() const { const int prev = d->previousPage(); if ( prev == InvalidPage ) return false; const WizardPage * const prevPage = page( prev ); assert( prevPage ); return !prevPage->isCommitPage(); } void Wizard::next() { onNext( d->currentId ); std::vector<int>::const_iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), d->currentId ); assert( it != d->pageOrder.end() ); ++it; if ( it == d->pageOrder.end() ) // "Finish" { d->currentId = InvalidPage; close(); } else // "next" { setCurrentPage( *it ); } } int Wizard::Private::previousPage() const { if ( pageOrder.empty() ) return InvalidPage; std::vector<int>::const_iterator it = qBinaryFind( pageOrder.begin(), pageOrder.end(), currentId ); if ( it == pageOrder.begin() || it == pageOrder.end() ) return InvalidPage; --it; return *it; } void Wizard::back() { onBack( d->currentId ); const int prev = d->previousPage(); if ( prev == InvalidPage ) return; setCurrentPage( prev ); } const WizardPage* Wizard::page( int id ) const { if ( id == InvalidPage ) return 0; const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id ); assuan_assert( it != d->idToPage.end() ); return (*it).second; } const WizardPage* Wizard::currentPageWidget() const { return page( d->currentId ); } WizardPage* Wizard::currentPageWidget() { return page( d->currentId ); } void Wizard::onNext( int currentId ) { Q_UNUSED( currentId ) } void Wizard::onBack( int currentId ) { Q_UNUSED( currentId ) } WizardPage* Wizard::page( int id ) { if ( id == InvalidPage ) return 0; const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id ); assuan_assert( it != d->idToPage.end() ); return (*it).second; } #include "moc_wizard.cpp" <|endoftext|>
<commit_before>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "archivefolderdialog.h" #include "backupjob.h" #include "kmkernel.h" #include "kmfolder.h" #include "kmmainwidget.h" #include "folderrequester.h" #include "util.h" #include <klocale.h> #include <kcombobox.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <qlabel.h> #include <qcheckbox.h> #include <qlayout.h> using namespace KMail; static QString standardArchivePath( const QString &folderName ) { return KGlobalSettings::documentPath() + '/' + i18nc( "Start of the filename for a mail archive file" , "Archive" ) + '_' + folderName + '_' + QDate::currentDate().toString( Qt::ISODate ) + ".zip"; } ArchiveFolderDialog::ArchiveFolderDialog( QWidget *parent ) : KDialog( parent ), mParentWidget( parent ) { setObjectName( "archive_folder_dialog" ); setCaption( i18n( "Archive Folder" ) ); setButtons( Ok|Cancel ); setDefaultButton( Ok ); setModal( true ); QWidget *mainWidget = new QWidget( this ); QGridLayout *mainLayout = new QGridLayout( mainWidget ); mainLayout->setSpacing( KDialog::spacingHint() ); mainLayout->setMargin( KDialog::marginHint() ); setMainWidget( mainWidget ); int row = 0; // TODO: better label for "Ok" button // TODO: Explaination label // TODO: Use QFormLayout in KDE4 QLabel *folderLabel = new QLabel( i18n( "&Folder:" ), mainWidget ); mainLayout->addWidget( folderLabel, row, 0 ); mFolderRequester = new FolderRequester( mainWidget ); mFolderRequester->setMustBeReadWrite( false ); mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() ); connect( mFolderRequester, SIGNAL( folderChanged( KMFolder* ) ), SLOT( slotFolderChanged( KMFolder* ) ) ); folderLabel->setBuddy( mFolderRequester ); mainLayout->addWidget( mFolderRequester, row, 1 ); row++; QLabel *formatLabel = new QLabel( i18n( "F&ormat:" ), mainWidget ); mainLayout->addWidget( formatLabel, row, 0 ); mFormatComboBox = new KComboBox( mainWidget ); formatLabel->setBuddy( mFormatComboBox ); // These combobox values have to stay in sync with the ArchiveType enum from BackupJob! mFormatComboBox->addItem( i18n( "Compressed Zip Archive (.zip)" ) ); mFormatComboBox->addItem( i18n( "Uncompressed Archive (.tar)" ) ); mFormatComboBox->addItem( i18n( "BZ2-Compressed Tar Archive (.tar.bz2)" ) ); mFormatComboBox->addItem( i18n( "GZ-Compressed Tar Archive (.tar.gz)" ) ); mFormatComboBox->setCurrentIndex( 0 ); connect( mFormatComboBox, SIGNAL(activated(int)), this, SLOT(slotFixFileExtension()) ); mainLayout->addWidget( mFormatComboBox, row, 1 ); row++; QLabel *fileNameLabel = new QLabel( i18n( "&Archive File:" ), mainWidget ); mainLayout->addWidget( fileNameLabel, row, 0 ); mUrlRequester = new KUrlRequester( mainWidget ); mUrlRequester->setMode( KFile::LocalOnly | KFile::File ); mUrlRequester->setFilter( "*.tar *.zip *.tar.gz *.tar.bz2" ); fileNameLabel->setBuddy( mUrlRequester ); connect( mUrlRequester->lineEdit(), SIGNAL(textChanged(const QString &)), SLOT( slotUrlChanged(const QString&))); connect( mUrlRequester, SIGNAL(urlSelected(const KUrl&)), this, SLOT(slotFixFileExtension()) ); mainLayout->addWidget( mUrlRequester, row, 1 ); row++; // TODO: Make this appear more dangerous! mDeleteCheckBox = new QCheckBox( i18n( "&Delete folders after completion" ), mainWidget ); mainLayout->addWidget( mDeleteCheckBox, row, 0, 1, 2, Qt::AlignLeft ); row++; // TODO: what's this, tooltips // TODO: Warn that user should do mail check for online IMAP and possibly cached IMAP as well mainLayout->setColumnStretch( 1, 1 ); mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 ); // Make it a bit bigger, else the folder requester cuts off the text too early resize( 500, minimumSize().height() ); } void ArchiveFolderDialog::slotUrlChanged( const QString & text) { enableButtonOk( !text.isEmpty() ); } void ArchiveFolderDialog::slotFolderChanged( KMFolder *folder ) { mDeleteCheckBox->setEnabled( folder->canDeleteMessages() ); } void ArchiveFolderDialog::setFolder( KMFolder *defaultFolder ) { mFolderRequester->setFolder( defaultFolder ); // TODO: what if the file already exists? mUrlRequester->setUrl( standardArchivePath( defaultFolder->name() ) ); mDeleteCheckBox->setEnabled( defaultFolder->canDeleteMessages() ); } void ArchiveFolderDialog::slotButtonClicked( int button ) { if ( button == KDialog::Cancel ) { reject(); return; } Q_ASSERT( button == KDialog::Ok ); if ( !Util::checkOverwrite( mUrlRequester->url(), this ) ) { return; } if ( !mFolderRequester->folder() ) { KMessageBox::information( this, i18n( "Please select the folder that should be archived." ), i18n( "No folder selected" ) ); return; } // TODO: check if url is empty. or better yet, disable ok button until file is chosen KMail::BackupJob *backupJob = new KMail::BackupJob( mParentWidget ); backupJob->setRootFolder( mFolderRequester->folder() ); backupJob->setSaveLocation( mUrlRequester->url() ); backupJob->setArchiveType( static_cast<BackupJob::ArchiveType>( mFormatComboBox->currentIndex() ) ); backupJob->setDeleteFoldersAfterCompletion( mDeleteCheckBox->isChecked() && mFolderRequester->folder()->canDeleteMessages()); backupJob->start(); accept(); } void ArchiveFolderDialog::slotFixFileExtension() { // KDE4: use KMimeType::extractKnownExtension() here const int numExtensions = 4; // These extensions are sorted differently, .tar has to come last, or it will match before giving // the more specific ones time to match. const char *sortedExtensions[numExtensions] = { ".zip", ".tar.bz2", ".tar.gz", ".tar" }; // The extensions here are also sorted, like the enum order of BackupJob::ArchiveType const char *extensions[numExtensions] = { ".zip", ".tar", ".tar.bz2", ".tar.gz" }; QString fileName = mUrlRequester->url().path(); // First, try to find the extension of the file name and remove it for( int i = 0; i < numExtensions; i++ ) { int index = fileName.toLower().lastIndexOf( sortedExtensions[i] ); if ( index != -1 ) { fileName = fileName.left( fileName.length() - QString( sortedExtensions[i] ).length() ); break; } } // Now, we've got a filename without an extension, simply append the correct one fileName += extensions[mFormatComboBox->currentIndex()]; mUrlRequester->setUrl( fileName ); } #include "archivefolderdialog.moc" <commit_msg>Fix crash when we select an nul folder (LocalFolder) and don't select folder which can't have content (as top level in imap account) MERGE: in trunk/e4/e5 and other if necessary (don't know)<commit_after>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "archivefolderdialog.h" #include "backupjob.h" #include "kmkernel.h" #include "kmfolder.h" #include "kmmainwidget.h" #include "folderrequester.h" #include "util.h" #include <klocale.h> #include <kcombobox.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <qlabel.h> #include <qcheckbox.h> #include <qlayout.h> using namespace KMail; static QString standardArchivePath( const QString &folderName ) { return KGlobalSettings::documentPath() + '/' + i18nc( "Start of the filename for a mail archive file" , "Archive" ) + '_' + folderName + '_' + QDate::currentDate().toString( Qt::ISODate ) + ".zip"; } ArchiveFolderDialog::ArchiveFolderDialog( QWidget *parent ) : KDialog( parent ), mParentWidget( parent ) { setObjectName( "archive_folder_dialog" ); setCaption( i18n( "Archive Folder" ) ); setButtons( Ok|Cancel ); setDefaultButton( Ok ); setModal( true ); QWidget *mainWidget = new QWidget( this ); QGridLayout *mainLayout = new QGridLayout( mainWidget ); mainLayout->setSpacing( KDialog::spacingHint() ); mainLayout->setMargin( KDialog::marginHint() ); setMainWidget( mainWidget ); int row = 0; // TODO: better label for "Ok" button // TODO: Explaination label // TODO: Use QFormLayout in KDE4 QLabel *folderLabel = new QLabel( i18n( "&Folder:" ), mainWidget ); mainLayout->addWidget( folderLabel, row, 0 ); mFolderRequester = new FolderRequester( mainWidget ); mFolderRequester->setMustBeReadWrite( false ); mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() ); connect( mFolderRequester, SIGNAL( folderChanged( KMFolder* ) ), SLOT( slotFolderChanged( KMFolder* ) ) ); folderLabel->setBuddy( mFolderRequester ); mainLayout->addWidget( mFolderRequester, row, 1 ); row++; QLabel *formatLabel = new QLabel( i18n( "F&ormat:" ), mainWidget ); mainLayout->addWidget( formatLabel, row, 0 ); mFormatComboBox = new KComboBox( mainWidget ); formatLabel->setBuddy( mFormatComboBox ); // These combobox values have to stay in sync with the ArchiveType enum from BackupJob! mFormatComboBox->addItem( i18n( "Compressed Zip Archive (.zip)" ) ); mFormatComboBox->addItem( i18n( "Uncompressed Archive (.tar)" ) ); mFormatComboBox->addItem( i18n( "BZ2-Compressed Tar Archive (.tar.bz2)" ) ); mFormatComboBox->addItem( i18n( "GZ-Compressed Tar Archive (.tar.gz)" ) ); mFormatComboBox->setCurrentIndex( 0 ); connect( mFormatComboBox, SIGNAL(activated(int)), this, SLOT(slotFixFileExtension()) ); mainLayout->addWidget( mFormatComboBox, row, 1 ); row++; QLabel *fileNameLabel = new QLabel( i18n( "&Archive File:" ), mainWidget ); mainLayout->addWidget( fileNameLabel, row, 0 ); mUrlRequester = new KUrlRequester( mainWidget ); mUrlRequester->setMode( KFile::LocalOnly | KFile::File ); mUrlRequester->setFilter( "*.tar *.zip *.tar.gz *.tar.bz2" ); fileNameLabel->setBuddy( mUrlRequester ); connect( mUrlRequester->lineEdit(), SIGNAL(textChanged(const QString &)), SLOT( slotUrlChanged(const QString&))); connect( mUrlRequester, SIGNAL(urlSelected(const KUrl&)), this, SLOT(slotFixFileExtension()) ); mainLayout->addWidget( mUrlRequester, row, 1 ); row++; // TODO: Make this appear more dangerous! mDeleteCheckBox = new QCheckBox( i18n( "&Delete folders after completion" ), mainWidget ); mainLayout->addWidget( mDeleteCheckBox, row, 0, 1, 2, Qt::AlignLeft ); row++; // TODO: what's this, tooltips // TODO: Warn that user should do mail check for online IMAP and possibly cached IMAP as well mainLayout->setColumnStretch( 1, 1 ); mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 ); // Make it a bit bigger, else the folder requester cuts off the text too early resize( 500, minimumSize().height() ); } void ArchiveFolderDialog::slotUrlChanged( const QString & text) { enableButtonOk( !text.isEmpty() ); } void ArchiveFolderDialog::slotFolderChanged( KMFolder *folder ) { mDeleteCheckBox->setEnabled( folder && folder->canDeleteMessages() && !folder->noContent()); enableButtonOk( folder && !folder->noContent()); } void ArchiveFolderDialog::setFolder( KMFolder *defaultFolder ) { mFolderRequester->setFolder( defaultFolder ); // TODO: what if the file already exists? mUrlRequester->setUrl( standardArchivePath( defaultFolder->name() ) ); mDeleteCheckBox->setEnabled( defaultFolder->canDeleteMessages() ); } void ArchiveFolderDialog::slotButtonClicked( int button ) { if ( button == KDialog::Cancel ) { reject(); return; } Q_ASSERT( button == KDialog::Ok ); if ( !Util::checkOverwrite( mUrlRequester->url(), this ) ) { return; } if ( !mFolderRequester->folder() ) { KMessageBox::information( this, i18n( "Please select the folder that should be archived." ), i18n( "No folder selected" ) ); return; } // TODO: check if url is empty. or better yet, disable ok button until file is chosen KMail::BackupJob *backupJob = new KMail::BackupJob( mParentWidget ); backupJob->setRootFolder( mFolderRequester->folder() ); backupJob->setSaveLocation( mUrlRequester->url() ); backupJob->setArchiveType( static_cast<BackupJob::ArchiveType>( mFormatComboBox->currentIndex() ) ); backupJob->setDeleteFoldersAfterCompletion( mDeleteCheckBox->isChecked() && mFolderRequester->folder()->canDeleteMessages()); backupJob->start(); accept(); } void ArchiveFolderDialog::slotFixFileExtension() { // KDE4: use KMimeType::extractKnownExtension() here const int numExtensions = 4; // These extensions are sorted differently, .tar has to come last, or it will match before giving // the more specific ones time to match. const char *sortedExtensions[numExtensions] = { ".zip", ".tar.bz2", ".tar.gz", ".tar" }; // The extensions here are also sorted, like the enum order of BackupJob::ArchiveType const char *extensions[numExtensions] = { ".zip", ".tar", ".tar.bz2", ".tar.gz" }; QString fileName = mUrlRequester->url().path(); // First, try to find the extension of the file name and remove it for( int i = 0; i < numExtensions; i++ ) { int index = fileName.toLower().lastIndexOf( sortedExtensions[i] ); if ( index != -1 ) { fileName = fileName.left( fileName.length() - QString( sortedExtensions[i] ).length() ); break; } } // Now, we've got a filename without an extension, simply append the correct one fileName += extensions[mFormatComboBox->currentIndex()]; mUrlRequester->setUrl( fileName ); } #include "archivefolderdialog.moc" <|endoftext|>