text
stringlengths
54
60.6k
<commit_before>#include"line.hpp" <commit_msg>In Progress Code for Fitting Splines<commit_after>#include"line.hpp" #include"spline.hpp" bool debug_spline = false; void matrix_multiplication_spline(float* arr1, int arr1_rows, int arr1_cols, float* arr2, int arr2_rows, int arr2_cols, float* r_arr) { for(int i = 0;i<arr1_rows;i++) { for(int j = 0;j < arr2_cols;j++) { *(r_arr + i*arr2_cols + j) = 0; for(int k =0;k<arr1_cols;k++) { *(r_arr + i*arr2_cols + j) = *(r_arr + i*arr2_cols +j) + (*(arr1+ i*arr1_cols + k))*(*(arr2 + k*arr2_cols + j)); } } } } void getRansacSplines(vector<Line>& line_objects, vector<Spline>& spline_objects, Mat& gray_ipm_image) { for(int i = 0;i<line_objects.size();i++) { Spline spline = getLine2Spline(line_objects[i], DEGREE); spline_objects[i] = spline; } //fitSpline(spline_objects); drawSpline(gray_ipm_image, spline_objects); } void drawSpline(Mat& gray_ipm_image, vector<Spline>& spline_objects) { for(int i =0;i<spline_objects.size();i++) { getSplinePoints(spline_objects[i],.05); } } void getSplinePoints(Spline& spline, float resolution) { float* tangents = (float*)malloc(2*2*sizeof(float)); float* points = evaluateSpline(spline, resolution, tangents); if(debug_spline) { for(int i = 0;i<2;i++) { for(int j = 0;j<2;j++) { cout<<*(tangents + i*2 + j)<<"\t"; } cout<<endl; } } if(debug_spline) { for(int i =0;i<20;i++) { for(int j =0;j<2;j++) { cout<<*(points + i*20 +j)<<"\t"; } cout<<endl; } } } float* evaluateSpline(Spline& spline, float resolution, float* tangents) { int n = (int)(1./resolution) + 1; float* points = (float*)malloc(n*2*sizeof(float)); float M3 [] = {-1,3,3,1,3,-6,3,0,-3,3,0,0,1,0,0,0}; float* spline_points = (float*)malloc((spline.degree + 1)*2*sizeof(float)); float P[2], dP[2], ddP[2], dddP[2]; float h2 = resolution*resolution; float h3 = resolution*h2; for(int i =0;i<(spline.degree +1);i++) { *(spline_points + i*2) = (float) spline.points[i].x; *(spline_points + i*2 + 1) = (float) spline.points[i].y; } if(debug_spline) { for(int i = 0;i<(spline.degree + 1);i++) { for(int j =0;j<2;j++) { cout<<"Coordinates \t"<<*(spline_points +i*(2) + j); } cout<<endl; } } float* spline_control_points = (float*)malloc((spline.degree + 1)*2*sizeof(float)); float *M = (float*)malloc(sizeof(float)*4*4); memcpy(M, M3, sizeof(float)*4*4); if(debug_spline) { for(int i = 0;i<4;i++) { for(int j =0;j<4;j++) { cout<<*(M + i*4 + j)<<"\t"; } cout<<endl; } } matrix_multiplication_spline(M, 4, 4, spline_points, (spline.degree + 1), 2, spline_control_points); if(debug_spline) { for(int i = 0;i<4;i++) { for(int j =0;j<2;j++) { cout<<"Points \t"<<*(spline_control_points + i*2 + j)<<"\t"; } cout<<endl; } } int p_col = 2; P[0] = *(spline_control_points + 3*p_col); P[1] = *(spline_control_points + 3*p_col + 1); dP[0] = *(spline_control_points + 2*p_col)*resolution + *(spline_control_points + 1*p_col)*h2 + *(spline_control_points)*h3; dP[1] = *(spline_control_points + 2*p_col + 1)*resolution + *(spline_control_points + 1*p_col + 1)*h2 + *(spline_control_points + 1)*h3; dddP[0] = 6*(*(spline_control_points))*h3; dddP[1] = 6*(*(spline_control_points + 1))*h3; ddP[0] = 2*(*(spline_control_points + 1*p_col))*h2 + dddP[0]; ddP[1] = 2*(*(spline_control_points + 1*p_col + 1))*h2 + dddP[1]; if(debug_spline) { cout<<"Number of Points \t"<<n<<endl; } for(int i = 0;i<n;i++) { *(points + i*p_col) = P[0]; *(points + i*p_col + 1) = P[1]; P[0] += dP[0]; P[1] += dP[1]; dP[0] += ddP[0]; dP[1] += ddP[1]; ddP[0] += dddP[0]; ddP[1] += dddP[1]; } if(tangents) { *(tangents) = *(spline_control_points + 2*p_col); *(tangents + 1) = *(spline_control_points + 2*p_col +1); *(tangents + 1*p_col) = 3*(*(spline_control_points)) + 2*(*(spline_control_points + 1*p_col)) + *(spline_control_points + 2*p_col); *(tangents + 1*p_col) = 3*(*(spline_control_points + 1)) + 2*(*(spline_control_points + 1*p_col + 1)) + *(spline_control_points + 2*p_col + 1); } return points; } /* void fitSpline(vector<Spline>& spline_objects) { int count_spline_objects = spline_objects.size(); for(int i = 0;i<count_spline_objects;i++) { fitbezierSpline(spline_objects[i].spline_x_y_points); } } */ Spline getLine2Spline(Line& line_object, int degree) { Spline spline; spline.degree = 3; spline.points[0] = line_object.startpoint; spline.points[degree] = line_object.endpoint; Linepoint direction = getDirection(line_object.endpoint, line_object.startpoint); for(int i = 1;i<degree;i++) { Linepoint point; float t = i/(float) degree; point.x = line_object.startpoint.x + t*direction.x; point.y = line_object.startpoint.y + t*direction.y; spline.points[i] = point; } spline.spline_x_y_points = line_object.x_y_points; if(debug_spline) { for(int i =0;i<4;i++) { cout<<"Coordinates \t"<<spline.points[i].x<<"\t"<<spline.points[i].y<<endl; } } return spline; } Linepoint getDirection(const Linepoint& v1, const Linepoint& v2) { Linepoint dir = {v1.x - v2.x, v1.y - v2.y}; return dir; } /* void fitbezierSpline(vector<Linepoint>& spline_x_y_points, int degree) { } */ <|endoftext|>
<commit_before>// t0513.cc // sizeof a struct with a bitfield struct S1 { unsigned x : 2; unsigned y : 30; }; int arr1[sizeof(S1)==4? +1 : -1]; struct S2 { unsigned x : 2; unsigned y : 30; unsigned z : 1; }; // edg and icc both say this is 8 ... int arr2[sizeof(S2)==8? +1 : -1]; // this is from a header file somewhere, it shows up in quite a // few of the Debian build failures struct real_value { unsigned int canonical : 1; // 1 signed int exp : (32 - 5); // 27 unsigned long sig[((128 + (8 * 4)) / (8 * 4))]; // 5 }; extern char test_real_width [ sizeof(struct real_value) <= (((128 + (8 * 4)) + 32)/(8 * 4) + (((128 + (8 * 4)) + 32)%(8 * 4) ? 1 : 0))*sizeof(long) ? 1 : -1 ]; <commit_msg>tweak<commit_after>// t0513.cc // sizeof a struct with a bitfield struct S1 { unsigned x : 2; unsigned y : 30; }; int arr1[sizeof(S1)==4? +1 : -1]; struct S2 { unsigned x : 2; unsigned y : 30; unsigned z : 1; }; // edg and icc both say this is 8 ... int arr2[sizeof(S2)==8? +1 : -1]; // this is from a header file somewhere, it shows up in quite a // few of the Debian build failures // // actually, it's gcc's implementation of __real__, and then a // check regarding its size (because gcc must emit machine code // to manipulate it), and this appears in both gcc and mingw32 struct real_value { unsigned int canonical : 1; // 1 signed int exp : (32 - 5); // 27 unsigned long sig[((128 + (8 * 4)) / (8 * 4))]; // 5 }; extern char test_real_width [ sizeof(struct real_value) <= (((128 + (8 * 4)) + 32)/(8 * 4) + (((128 + (8 * 4)) + 32)%(8 * 4) ? 1 : 0))*sizeof(long) ? 1 : -1 ]; <|endoftext|>
<commit_before>#include "nanocv.h" #include "grid_image.h" #include <boost/program_options.hpp> #include <algorithm> int main(int argc, char *argv[]) { ncv::init(); using namespace ncv; // prepare object string-based selection const strings_t task_ids = task_manager_t::instance().ids(); const strings_t loss_ids = loss_manager_t::instance().ids(); const strings_t model_ids = model_manager_t::instance().ids(); // parse the command line boost::program_options::options_description po_desc("", 160); po_desc.add_options()("help,h", "help message"); po_desc.add_options()("task", boost::program_options::value<string_t>(), text::concatenate(task_ids, ", ").c_str()); po_desc.add_options()("task-dir", boost::program_options::value<string_t>(), "directory to load task data from"); po_desc.add_options()("loss", boost::program_options::value<string_t>(), text::concatenate(loss_ids, ", ").c_str()); po_desc.add_options()("model", boost::program_options::value<string_t>(), text::concatenate(model_ids, ", ").c_str()); po_desc.add_options()("model-file", boost::program_options::value<string_t>(), "filepath to load the model from"); po_desc.add_options()("save-dir", boost::program_options::value<string_t>(), "directory to save classification results to"); po_desc.add_options()("save-group-rows", boost::program_options::value<size_t>()->default_value(32), "number of samples to group in a row"); po_desc.add_options()("save-group-cols", boost::program_options::value<size_t>()->default_value(32), "number of samples to group in a column"); boost::program_options::variables_map po_vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(po_desc).run(), po_vm); boost::program_options::notify(po_vm); // check arguments and options if ( po_vm.empty() || !po_vm.count("task") || !po_vm.count("task-dir") || !po_vm.count("loss") || !po_vm.count("model") || !po_vm.count("model-file") || po_vm.count("help")) { std::cout << po_desc; return EXIT_FAILURE; } const string_t cmd_task = po_vm["task"].as<string_t>(); const string_t cmd_task_dir = po_vm["task-dir"].as<string_t>(); const string_t cmd_loss = po_vm["loss"].as<string_t>(); const string_t cmd_model = po_vm["model"].as<string_t>(); const string_t cmd_input = po_vm["model-file"].as<string_t>(); const string_t cmd_save_dir = po_vm.count("save-dir") ? po_vm["save-dir"].as<string_t>() : ""; const size_t cmd_save_group_rows = math::clamp(po_vm["save-group-rows"].as<size_t>(), 1, 128); const size_t cmd_save_group_cols = math::clamp(po_vm["save-group-cols"].as<size_t>(), 1, 128); // create task const rtask_t rtask = task_manager_t::instance().get(cmd_task); // load task data ncv::measure_critical_call( [&] () { return rtask->load(cmd_task_dir); }, "loaded task", "failed to load task <" + cmd_task + "> from directory <" + cmd_task_dir + ">"); // describe task log_info() << "images: " << rtask->n_images() << "."; log_info() << "sample: #rows = " << rtask->n_rows() << ", #cols = " << rtask->n_cols() << ", #outputs = " << rtask->n_outputs() << ", #folds = " << rtask->n_folds() << "."; for (size_t f = 0; f < rtask->n_folds(); f ++) { sampler_t trsampler(*rtask), tesampler(*rtask); trsampler.setup(fold_t{f, protocol::train}); tesampler.setup(fold_t{f, protocol::test}); log_info() << "fold [" << (f + 1) << "/" << rtask->n_folds() << "]: #train samples = " << trsampler.size() << ", #test samples = " << tesampler.size() << "."; } // create loss const rloss_t rloss = loss_manager_t::instance().get(cmd_loss); // create model const rmodel_t rmodel = model_manager_t::instance().get(cmd_model); // load model ncv::measure_critical_call( [&] () { return rmodel->load(cmd_input); }, "loaded model", "failed to load model from <" + cmd_input + ">"); // test model stats_t<scalar_t> lstats, estats; for (size_t f = 0; f < rtask->n_folds(); f ++) { const fold_t test_fold = std::make_pair(f, protocol::test); const ncv::timer_t timer; scalar_t lvalue, lerror; ncv::test(*rtask, test_fold, *rloss, *rmodel, lvalue, lerror); log_info() << "<<< test error: [" << lvalue << "/" << lerror << "] in " << timer.elapsed() << "."; lstats(lvalue); estats(lerror); } // performance statistics log_info() << ">>> performance: loss value = " << lstats.avg() << " +/- " << lstats.stdev() << " in [" << lstats.min() << ", " << lstats.max() << "]."; log_info() << ">>> performance: loss error = " << estats.avg() << " +/- " << estats.stdev() << " in [" << estats.min() << ", " << estats.max() << "]."; // save classification results if (!cmd_save_dir.empty()) { for (size_t f = 0; f < rtask->n_folds(); f ++) { const fold_t test_fold = std::make_pair(f, protocol::test); sampler_t sampler(*rtask); sampler.setup(test_fold); sampler.setup(sampler_t::atype::annotated); sampler.setup(sampler_t::stype::batch); const samples_t samples = sampler.get(); // split test samples into correctly classified & miss-classified samples_t ok_samples; samples_t nk_samples; for (size_t s = 0; s < samples.size(); s ++) { const sample_t& sample = samples[s]; const image_t& image = rtask->image(sample.m_index); const vector_t target = sample.m_target; const vector_t output = rmodel->output(image, sample.m_region).vector(); const indices_t tclasses = ncv::classes(target); const indices_t oclasses = ncv::classes(output); const bool ok = tclasses.size() == oclasses.size() && std::mismatch(tclasses.begin(), tclasses.end(), oclasses.begin()).first == tclasses.end(); (ok ? ok_samples : nk_samples).push_back(sample); } const string_t basepath = cmd_save_dir + "/" + cmd_task + "_test_fold" + text::to_string(f + 1); const size_t grows = cmd_save_group_rows; const size_t gcols = cmd_save_group_cols; const rgba_t ok_bkcolor = color::make_rgba(0, 225, 0); const rgba_t nk_bkcolor = color::make_rgba(225, 0, 0); // further split them by label const strings_t labels = rtask->labels(); for (const string_t& label : labels) { const string_t lbasepath = basepath + "_" + label; sampler_t ok_sampler(ok_samples); ok_sampler.setup(label); sampler_t nk_sampler(nk_samples); nk_sampler.setup(label); sampler_t ll_sampler(samples); ll_sampler.setup(label); const samples_t ok_samples = ok_sampler.get(); const samples_t nk_samples = nk_sampler.get(); const sampler_t ll_samples = ll_sampler.get(); log_info() << "miss-classified " << nk_samples.size() << "/" << ll_samples.size() << " [" << label << "] samples."; rtask->save_as_images(ok_samples, lbasepath + "_ok", grows, gcols, 8, ok_bkcolor); rtask->save_as_images(nk_samples, lbasepath + "_nk", grows, gcols, 8, nk_bkcolor); } } } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>compute the number of miss-matches (globally & per label)<commit_after>#include "nanocv.h" #include "grid_image.h" #include <boost/program_options.hpp> #include <algorithm> int main(int argc, char *argv[]) { ncv::init(); using namespace ncv; // prepare object string-based selection const strings_t task_ids = task_manager_t::instance().ids(); const strings_t loss_ids = loss_manager_t::instance().ids(); const strings_t model_ids = model_manager_t::instance().ids(); // parse the command line boost::program_options::options_description po_desc("", 160); po_desc.add_options()("help,h", "help message"); po_desc.add_options()("task", boost::program_options::value<string_t>(), text::concatenate(task_ids, ", ").c_str()); po_desc.add_options()("task-dir", boost::program_options::value<string_t>(), "directory to load task data from"); po_desc.add_options()("loss", boost::program_options::value<string_t>(), text::concatenate(loss_ids, ", ").c_str()); po_desc.add_options()("model", boost::program_options::value<string_t>(), text::concatenate(model_ids, ", ").c_str()); po_desc.add_options()("model-file", boost::program_options::value<string_t>(), "filepath to load the model from"); po_desc.add_options()("save-dir", boost::program_options::value<string_t>(), "directory to save classification results to"); po_desc.add_options()("save-group-rows", boost::program_options::value<size_t>()->default_value(32), "number of samples to group in a row"); po_desc.add_options()("save-group-cols", boost::program_options::value<size_t>()->default_value(32), "number of samples to group in a column"); boost::program_options::variables_map po_vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(po_desc).run(), po_vm); boost::program_options::notify(po_vm); // check arguments and options if ( po_vm.empty() || !po_vm.count("task") || !po_vm.count("task-dir") || !po_vm.count("loss") || !po_vm.count("model") || !po_vm.count("model-file") || po_vm.count("help")) { std::cout << po_desc; return EXIT_FAILURE; } const string_t cmd_task = po_vm["task"].as<string_t>(); const string_t cmd_task_dir = po_vm["task-dir"].as<string_t>(); const string_t cmd_loss = po_vm["loss"].as<string_t>(); const string_t cmd_model = po_vm["model"].as<string_t>(); const string_t cmd_input = po_vm["model-file"].as<string_t>(); const string_t cmd_save_dir = po_vm.count("save-dir") ? po_vm["save-dir"].as<string_t>() : ""; const size_t cmd_save_group_rows = math::clamp(po_vm["save-group-rows"].as<size_t>(), 1, 128); const size_t cmd_save_group_cols = math::clamp(po_vm["save-group-cols"].as<size_t>(), 1, 128); // create task const rtask_t rtask = task_manager_t::instance().get(cmd_task); // load task data ncv::measure_critical_call( [&] () { return rtask->load(cmd_task_dir); }, "loaded task", "failed to load task <" + cmd_task + "> from directory <" + cmd_task_dir + ">"); // describe task log_info() << "images: " << rtask->n_images() << "."; log_info() << "sample: #rows = " << rtask->n_rows() << ", #cols = " << rtask->n_cols() << ", #outputs = " << rtask->n_outputs() << ", #folds = " << rtask->n_folds() << "."; for (size_t f = 0; f < rtask->n_folds(); f ++) { sampler_t trsampler(*rtask), tesampler(*rtask); trsampler.setup(fold_t{f, protocol::train}); tesampler.setup(fold_t{f, protocol::test}); log_info() << "fold [" << (f + 1) << "/" << rtask->n_folds() << "]: #train samples = " << trsampler.size() << ", #test samples = " << tesampler.size() << "."; } // create loss const rloss_t rloss = loss_manager_t::instance().get(cmd_loss); // create model const rmodel_t rmodel = model_manager_t::instance().get(cmd_model); // load model ncv::measure_critical_call( [&] () { return rmodel->load(cmd_input); }, "loaded model", "failed to load model from <" + cmd_input + ">"); // test model stats_t<scalar_t> lstats, estats; for (size_t f = 0; f < rtask->n_folds(); f ++) { const fold_t test_fold = std::make_pair(f, protocol::test); // error rate const ncv::timer_t timer; scalar_t lvalue, lerror; ncv::test(*rtask, test_fold, *rloss, *rmodel, lvalue, lerror); log_info() << "<<< test error: [" << lvalue << "/" << lerror << "] in " << timer.elapsed() << "."; lstats(lvalue); estats(lerror); // per-label error rates sampler_t sampler(*rtask); sampler.setup(test_fold); sampler.setup(sampler_t::atype::annotated); sampler.setup(sampler_t::stype::batch); const samples_t samples = sampler.get(); // split test samples into correctly classified & miss-classified samples_t ok_samples; samples_t nk_samples; for (size_t s = 0; s < samples.size(); s ++) { const sample_t& sample = samples[s]; const image_t& image = rtask->image(sample.m_index); const vector_t target = sample.m_target; const vector_t output = rmodel->output(image, sample.m_region).vector(); const indices_t tclasses = ncv::classes(target); const indices_t oclasses = ncv::classes(output); const bool ok = tclasses.size() == oclasses.size() && std::mismatch(tclasses.begin(), tclasses.end(), oclasses.begin()).first == tclasses.end(); (ok ? ok_samples : nk_samples).push_back(sample); } log_info() << "miss-classified " << nk_samples.size() << "/" << (samples.size()) << " = " << ((0.0 + nk_samples.size()) / (0.0 + samples.size())) << "."; // save classification results if (!cmd_save_dir.empty()) { const string_t basepath = cmd_save_dir + "/" + cmd_task + "_test_fold" + text::to_string(f + 1); const size_t grows = cmd_save_group_rows; const size_t gcols = cmd_save_group_cols; const rgba_t ok_bkcolor = color::make_rgba(0, 225, 0); const rgba_t nk_bkcolor = color::make_rgba(225, 0, 0); // further split them by label const strings_t labels = rtask->labels(); for (const string_t& label : labels) { const string_t lbasepath = basepath + "_" + label; sampler_t ok_sampler(ok_samples); ok_sampler.setup(label); sampler_t nk_sampler(nk_samples); nk_sampler.setup(label); sampler_t ll_sampler(samples); ll_sampler.setup(label); const samples_t ok_samples = ok_sampler.get(); const samples_t nk_samples = nk_sampler.get(); const sampler_t ll_samples = ll_sampler.get(); log_info() << "miss-classified " << nk_samples.size() << "/" << ll_samples.size() << " = " << ((100.0 * nk_samples.size()) / (0.0 + ll_samples.size())) << " [" << label << "] samples."; rtask->save_as_images(ok_samples, lbasepath + "_ok", grows, gcols, 8, ok_bkcolor); rtask->save_as_images(nk_samples, lbasepath + "_nk", grows, gcols, 8, nk_bkcolor); } } } // performance statistics log_info() << ">>> performance: loss value = " << lstats.avg() << " +/- " << lstats.stdev() << " in [" << lstats.min() << ", " << lstats.max() << "]."; log_info() << ">>> performance: loss error = " << estats.avg() << " +/- " << estats.stdev() << " in [" << estats.min() << ", " << estats.max() << "]."; // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// qual_aux.cc // some auxillary functions for cc_qual.ast #include "cc.ast.gen.h" // C++ AST void TypeSpecifier::printExtras_Q(ostream &os, int indent) const { xassert(q); if (q->ql) { ind(os, indent); os << q->literalsToString() << endl; } } char const *TS_name::getTypeName() const { return name->getName(); } char const *TS_elaborated::getTypeName() const { return name->getName(); } char const *TS_classSpec::getTypeName() const { return name? name->getName() : "anonymous_TypeSpecifier"; } char const *TS_enumSpec::getTypeName() const { return name? name : "anonymous_TypeSpecifier"; } // sm: I reproduced most of the same names that dsw was using // for these names though there were a couple of inconsistencies // that I had to remove char const *TS_simple::getTypeName() const { switch (id) { default: xfailure("bad code"); case ST_CHAR: return "anonymous_char"; case ST_UNSIGNED_CHAR: return "anonymous_unsigned_char"; case ST_SIGNED_CHAR: return "anonymous_signed_char"; case ST_BOOL: return "anonymous_bool"; case ST_INT: return "anonymous_int"; case ST_UNSIGNED_INT: return "anonymous_unsigned_int"; case ST_LONG_INT: return "anonymous_long_int"; case ST_UNSIGNED_LONG_INT: return "anonymous_unsigned_long_int"; case ST_LONG_LONG: return "anonymous_long_long"; case ST_UNSIGNED_LONG_LONG: return "anonymous_unsigned_long_long"; case ST_SHORT_INT: return "anonymous_short_int"; case ST_UNSIGNED_SHORT_INT: return "anonymous_unsigned_short_int"; case ST_WCHAR_T: return "anonymous_wchar_t"; case ST_FLOAT: return "anonymous_float"; case ST_DOUBLE: return "anonymous_double"; case ST_LONG_DOUBLE: return "anonymous_long_double"; case ST_VOID: return "anonymous_void"; case ST_ELLIPSIS: return "anonymous_ellipsis"; case ST_CDTOR: return "<cdtor>"; case ST_ERROR: return "<error>"; case ST_DEPENDENT: return "<dependent>"; } } <commit_msg>moving qual_aux.cc to cc_qual; not added there yet<commit_after><|endoftext|>
<commit_before>/** @file A simple remap plugin for ATS @section license License 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. @section description This is a very simple plugin: it will add headers that are specified on a remap line Example usage: map /foo http://127.0.0.1/ @plugin=remap_header_add.so @pparam=foo:"x" @pparam=@test:"c" @pparam=a:"b" */ #include <cstdio> #include <cstdlib> #include <cstring> #include "ts/ts.h" #include "ts/remap.h" struct remap_line { int argc; char **argv; // store the originals int nvc; // the number of name value pairs, should be argc - 2. char **name; // at load we will parse out the name and values. char **val; }; #define TAG "headeradd_remap" #define NOWARN_UNUSED __attribute__((unused)) #define EXTERN extern "C" EXTERN void ParseArgIntoNv(const char *arg, char **n, char **v) { const char *colon_pos = strchr(arg, ':'); if (colon_pos == nullptr) { *n = nullptr; *v = nullptr; TSDebug(TAG, "No name value pair since it was malformed"); return; } size_t name_len = colon_pos - arg; *n = (char *)TSmalloc(name_len + 1); memcpy(*n, arg, colon_pos - arg); (*n)[name_len] = '\0'; size_t val_len = strlen(colon_pos + 1); // skip past the ':' // check to see if the value is quoted. if (val_len > 1 && colon_pos[1] == '"' && colon_pos[val_len] == '"') { colon_pos++; // advance past the first quote val_len -= 2; // don't include the trailing quote } *v = (char *)TSmalloc(val_len + 1); memcpy(*v, colon_pos + 1, val_len); (*v)[val_len] = '\0'; TSDebug(TAG, "\t name_len=%zu, val_len=%zu, %s=%s", name_len, val_len, *n, *v); } TSReturnCode TSRemapInit(NOWARN_UNUSED TSRemapInterface *api_info, NOWARN_UNUSED char *errbuf, NOWARN_UNUSED int errbuf_size) { return TS_SUCCESS; } TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, NOWARN_UNUSED char *errbuf, NOWARN_UNUSED int errbuf_size) { remap_line *rl = nullptr; TSDebug(TAG, "TSRemapNewInstance()"); if (!argv || !ih) { TSError("[remap_header_add] Unable to load plugin because missing argv or ih."); return TS_ERROR; } // print all arguments for this particular remapping rl = (remap_line *)TSmalloc(sizeof(remap_line)); rl->argc = argc; rl->argv = argv; rl->nvc = argc - 2; // the first two are the remap from and to if (rl->nvc) { rl->name = (char **)TSmalloc(sizeof(char *) * rl->nvc); rl->val = (char **)TSmalloc(sizeof(char *) * rl->nvc); } TSDebug(TAG, "NewInstance:"); for (int i = 2; i < argc; i++) { ParseArgIntoNv(argv[i], &rl->name[i - 2], &rl->val[i - 2]); } *ih = (void *)rl; return TS_SUCCESS; } void TSRemapDeleteInstance(void *ih) { TSDebug(TAG, "deleting instance %p", ih); if (ih) { remap_line *rl = (remap_line *)ih; for (int i = 0; i < rl->nvc; ++i) { TSfree(rl->name[i]); TSfree(rl->val[i]); } TSfree(rl->name); TSfree(rl->val); TSfree(rl); } } TSRemapStatus TSRemapDoRemap(void *ih, NOWARN_UNUSED TSHttpTxn txn, NOWARN_UNUSED TSRemapRequestInfo *rri) { remap_line *rl = (remap_line *)ih; if (!rl || !rri) { TSError("[remap_header_add] rl or rri is null."); return TSREMAP_NO_REMAP; } TSDebug(TAG, "TSRemapDoRemap:"); TSMBuffer req_bufp; TSMLoc req_loc; if (TSHttpTxnClientReqGet(txn, &req_bufp, &req_loc) != TS_SUCCESS) { TSError("[remap_header_add] Error while retrieving client request header"); return TSREMAP_NO_REMAP; } for (int i = 0; i < rl->nvc; ++i) { TSDebug(TAG, R"(Attaching header "%s" with value "%s".)", rl->name[i], rl->val[i]); TSMLoc field_loc; if (TSMimeHdrFieldCreate(req_bufp, req_loc, &field_loc) == TS_SUCCESS) { TSMimeHdrFieldNameSet(req_bufp, req_loc, field_loc, rl->name[i], strlen(rl->name[i])); TSMimeHdrFieldAppend(req_bufp, req_loc, field_loc); TSMimeHdrFieldValueStringInsert(req_bufp, req_loc, field_loc, 0, rl->val[i], strlen(rl->val[i])); } else { TSError("[remap_header_add] Failure on TSMimeHdrFieldCreate"); } } return TSREMAP_NO_REMAP; } <commit_msg>TS-4976: Regularize plugins - remap_header_add<commit_after>/** @file A simple remap plugin for ATS @section license License 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. @section description This is a very simple plugin: it will add headers that are specified on a remap line Example usage: map /foo http://127.0.0.1/ @plugin=remap_header_add.so @pparam=foo:"x" @pparam=@test:"c" @pparam=a:"b" */ #include <cstdio> #include <cstdlib> #include <cstring> #include "ts/ts.h" #include "ts/remap.h" struct remap_line { int argc; char **argv; // store the originals int nvc; // the number of name value pairs, should be argc - 2. char **name; // at load we will parse out the name and values. char **val; }; #define PLUGIN_NAME "headeradd_remap" #define EXTERN extern "C" EXTERN void ParseArgIntoNv(const char *arg, char **n, char **v) { const char *colon_pos = strchr(arg, ':'); if (colon_pos == nullptr) { *n = nullptr; *v = nullptr; TSDebug(PLUGIN_NAME, "No name value pair since it was malformed"); return; } size_t name_len = colon_pos - arg; *n = static_cast<char *>(TSmalloc(name_len + 1)); memcpy(*n, arg, colon_pos - arg); (*n)[name_len] = '\0'; size_t val_len = strlen(colon_pos + 1); // skip past the ':' // check to see if the value is quoted. if (val_len > 1 && colon_pos[1] == '"' && colon_pos[val_len] == '"') { colon_pos++; // advance past the first quote val_len -= 2; // don't include the trailing quote } *v = static_cast<char *>(TSmalloc(val_len + 1)); memcpy(*v, colon_pos + 1, val_len); (*v)[val_len] = '\0'; TSDebug(PLUGIN_NAME, "\t name_len=%zu, val_len=%zu, %s=%s", name_len, val_len, *n, *v); } TSReturnCode TSRemapInit(TSRemapInterface *, char *, int) { return TS_SUCCESS; } TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *, int) { remap_line *rl = nullptr; TSDebug(PLUGIN_NAME, "TSRemapNewInstance()"); if (!argv || !ih) { TSError("[%s] Unable to load plugin because missing argv or ih.", PLUGIN_NAME); return TS_ERROR; } // print all arguments for this particular remapping rl = (remap_line *)TSmalloc(sizeof(remap_line)); rl->argc = argc; rl->argv = argv; rl->nvc = argc - 2; // the first two are the remap from and to if (rl->nvc) { rl->name = static_cast<char **>(TSmalloc(sizeof(char *) * rl->nvc)); rl->val = static_cast<char **>(TSmalloc(sizeof(char *) * rl->nvc)); } TSDebug(PLUGIN_NAME, "NewInstance:"); for (int i = 2; i < argc; i++) { ParseArgIntoNv(argv[i], &rl->name[i - 2], &rl->val[i - 2]); } *ih = rl; return TS_SUCCESS; } void TSRemapDeleteInstance(void *ih) { TSDebug(PLUGIN_NAME, "deleting instance %p", ih); if (ih) { remap_line *rl = static_cast<remap_line *>(ih); for (int i = 0; i < rl->nvc; ++i) { TSfree(rl->name[i]); TSfree(rl->val[i]); } TSfree(rl->name); TSfree(rl->val); TSfree(rl); } } TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn txn, TSRemapRequestInfo *rri) { remap_line *rl = static_cast<remap_line *>(ih); if (!rl || !rri) { TSError("[%s] rl or rri is null.", PLUGIN_NAME); return TSREMAP_NO_REMAP; } TSDebug(PLUGIN_NAME, "TSRemapDoRemap:"); TSMBuffer req_bufp; TSMLoc req_loc; if (TSHttpTxnClientReqGet(txn, &req_bufp, &req_loc) != TS_SUCCESS) { TSError("[%s] Error while retrieving client request header", PLUGIN_NAME); return TSREMAP_NO_REMAP; } for (int i = 0; i < rl->nvc; ++i) { TSDebug(PLUGIN_NAME, R"(Attaching header "%s" with value "%s".)", rl->name[i], rl->val[i]); TSMLoc field_loc; if (TSMimeHdrFieldCreate(req_bufp, req_loc, &field_loc) == TS_SUCCESS) { TSMimeHdrFieldNameSet(req_bufp, req_loc, field_loc, rl->name[i], strlen(rl->name[i])); TSMimeHdrFieldAppend(req_bufp, req_loc, field_loc); TSMimeHdrFieldValueStringInsert(req_bufp, req_loc, field_loc, 0, rl->val[i], strlen(rl->val[i])); } else { TSError("[%s] Failure on TSMimeHdrFieldCreate", PLUGIN_NAME); } } return TSREMAP_NO_REMAP; } <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/normals.hpp * * Copyright 2014-2019 Patrik Huber * * 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. */ #pragma once #ifndef EOS_RENDER_NORMALS_HPP #define EOS_RENDER_NORMALS_HPP #include "glm/vec3.hpp" #include "glm/geometric.hpp" #include "Eigen/Core" namespace eos { namespace render { /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2) { Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2 return n.normalized(); }; /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1, const Eigen::Vector4f& v2) { Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2 return n.head<3>().normalized(); }; /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2) { glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2 n = glm::normalize(n); return n; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_RENDER_NORMALS_HPP */ <commit_msg>Tweak documentation of normals.hpp a bit<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/normals.hpp * * Copyright 2014-2019 Patrik Huber * * 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. */ #pragma once #ifndef EOS_RENDER_NORMALS_HPP #define EOS_RENDER_NORMALS_HPP #include "glm/vec3.hpp" #include "glm/geometric.hpp" #include "Eigen/Core" namespace eos { namespace render { /** * Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2) { Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2 return n.normalized(); }; /** * Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1, const Eigen::Vector4f& v2) { Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2 return n.head<3>().normalized(); }; /** * Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2) { glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2 n = glm::normalize(n); return n; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_RENDER_NORMALS_HPP */ <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include "tests/cql_test_env.hh" #include "tests/cql_assertions.hh" SEASTAR_TEST_CASE(test_secondary_index_regular_column_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (email);").discard_result(); }).then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (shared_ptr<cql_transport::messages::result_message> msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } SEASTAR_TEST_CASE(test_secondary_index_clustering_key_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid, country));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (auto msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } // CQL usually folds identifier names - keyspace, table and column names - // to lowercase. That is, unless the identifier is enclosed in double // quotation marks ("). Let's test that case-sensitive (quoted) column // names can be indexed. This reproduces issues #3154, #3388, #3391, #3401. SEASTAR_TEST_CASE(test_secondary_index_case_sensitive) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE \"FooBar\" (a int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON \"FooBar\" (b)").get(); e.execute_cql("INSERT INTO \"FooBar\" (a, b, c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from \"FooBar\" WHERE b = 1").get(); // Test case-sensitive *indexed column* name. // This not working was issue #3154. The symptom was that the SELECT // below threw a "No index found." runtime error. e.execute_cql("CREATE TABLE tab (a int PRIMARY KEY, \"FooBar\" int, c int)").get(); e.execute_cql("CREATE INDEX ON tab (\"FooBar\")").get(); // This INSERT also had problems (issue #3401) e.execute_cql("INSERT INTO tab (a, \"FooBar\", c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from tab WHERE \"FooBar\" = 2").get(); // Test case-sensitive *partition column* name. // This used to have multiple bugs in SI and MV code, detailed below: e.execute_cql("CREATE TABLE tab2 (\"FooBar\" int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON tab2 (b)").get(); // The following INSERT didn't work because of issues #3388 and #3391. e.execute_cql("INSERT INTO tab2 (\"FooBar\", b, c) VALUES (1, 2, 3)").get(); // After the insert works, add the SELECT and see it works. It used // to fail before the patch to #3210 fixed this incidentally. e.execute_cql("SELECT * from tab2 WHERE b = 2").get(); }); } SEASTAR_TEST_CASE(test_cannot_drop_secondary_index_backing_mv) { return do_with_cql_env_thread([] (cql_test_env& e) { e.execute_cql("create table cf (p int primary key, a int)").get(); e.execute_cql("create index on cf (a)").get(); auto s = e.local_db().find_schema(sstring("ks"), sstring("cf")); auto index_name = s->index_names().front(); assert_that_failed(e.execute_cql(sprint("drop materialized view %s_index", index_name))); }); } // Issue #3210 is about searching the secondary index not working properly // when the *partition key* has multiple columns (a compound partition key), // and this is what we test here. SEASTAR_TEST_CASE(test_secondary_index_case_compound_partition_key) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE tab (a int, b int, c int, PRIMARY KEY ((a, b)))").get(); e.execute_cql("CREATE INDEX ON tab (c)").get(); e.execute_cql("INSERT INTO tab (a, b, c) VALUES (1, 2, 3)").get(); eventually([&] { // We expect this search to find the single row, with the compound // partition key (a, b) = (1, 2). auto res = e.execute_cql("SELECT * from tab WHERE c = 3").get0(); assert_that(res).is_rows() .with_size(1) .with_row({ {int32_type->decompose(1)}, {int32_type->decompose(2)}, {int32_type->decompose(3)}, }); }); }); } <commit_msg>secondary index: add tests for IF NOT EXISTS, IF EXISTS<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include "tests/cql_test_env.hh" #include "tests/cql_assertions.hh" SEASTAR_TEST_CASE(test_secondary_index_regular_column_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (email);").discard_result(); }).then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (shared_ptr<cql_transport::messages::result_message> msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } SEASTAR_TEST_CASE(test_secondary_index_clustering_key_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid, country));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (auto msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } // CQL usually folds identifier names - keyspace, table and column names - // to lowercase. That is, unless the identifier is enclosed in double // quotation marks ("). Let's test that case-sensitive (quoted) column // names can be indexed. This reproduces issues #3154, #3388, #3391, #3401. SEASTAR_TEST_CASE(test_secondary_index_case_sensitive) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE \"FooBar\" (a int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON \"FooBar\" (b)").get(); e.execute_cql("INSERT INTO \"FooBar\" (a, b, c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from \"FooBar\" WHERE b = 1").get(); // Test case-sensitive *indexed column* name. // This not working was issue #3154. The symptom was that the SELECT // below threw a "No index found." runtime error. e.execute_cql("CREATE TABLE tab (a int PRIMARY KEY, \"FooBar\" int, c int)").get(); e.execute_cql("CREATE INDEX ON tab (\"FooBar\")").get(); // This INSERT also had problems (issue #3401) e.execute_cql("INSERT INTO tab (a, \"FooBar\", c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from tab WHERE \"FooBar\" = 2").get(); // Test case-sensitive *partition column* name. // This used to have multiple bugs in SI and MV code, detailed below: e.execute_cql("CREATE TABLE tab2 (\"FooBar\" int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON tab2 (b)").get(); // The following INSERT didn't work because of issues #3388 and #3391. e.execute_cql("INSERT INTO tab2 (\"FooBar\", b, c) VALUES (1, 2, 3)").get(); // After the insert works, add the SELECT and see it works. It used // to fail before the patch to #3210 fixed this incidentally. e.execute_cql("SELECT * from tab2 WHERE b = 2").get(); }); } SEASTAR_TEST_CASE(test_cannot_drop_secondary_index_backing_mv) { return do_with_cql_env_thread([] (cql_test_env& e) { e.execute_cql("create table cf (p int primary key, a int)").get(); e.execute_cql("create index on cf (a)").get(); auto s = e.local_db().find_schema(sstring("ks"), sstring("cf")); auto index_name = s->index_names().front(); assert_that_failed(e.execute_cql(sprint("drop materialized view %s_index", index_name))); }); } // Issue #3210 is about searching the secondary index not working properly // when the *partition key* has multiple columns (a compound partition key), // and this is what we test here. SEASTAR_TEST_CASE(test_secondary_index_case_compound_partition_key) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE tab (a int, b int, c int, PRIMARY KEY ((a, b)))").get(); e.execute_cql("CREATE INDEX ON tab (c)").get(); e.execute_cql("INSERT INTO tab (a, b, c) VALUES (1, 2, 3)").get(); eventually([&] { // We expect this search to find the single row, with the compound // partition key (a, b) = (1, 2). auto res = e.execute_cql("SELECT * from tab WHERE c = 3").get0(); assert_that(res).is_rows() .with_size(1) .with_row({ {int32_type->decompose(1)}, {int32_type->decompose(2)}, {int32_type->decompose(3)}, }); }); }); } // Tests for issue #2991 - test that "IF NOT EXISTS" works as expected for // index creation, and "IF EXISTS" for index drop. SEASTAR_TEST_CASE(test_secondary_index_if_exists) { return do_with_cql_env_thread([] (cql_test_env& e) { e.execute_cql("create table cf (p int primary key, a int)").get(); e.execute_cql("create index on cf (a)").get(); // Confirm that creating the same index again with "if not exists" is // fine, but without "if not exists", it's an error. e.execute_cql("create index if not exists on cf (a)").get(); try { e.execute_cql("create index on cf (a)").get(); BOOST_FAIL("Exception expected"); } catch (exceptions::invalid_request_exception) { } // Confirm that after dropping the index, dropping it again with // "if exists" is fine, but an error without it. e.execute_cql("drop index cf_a_idx").get(); e.execute_cql("drop index if exists cf_a_idx").get(); try { e.execute_cql("drop index cf_a_idx").get(); // Expect exceptions::invalid_request_exception: Index 'cf_a_idx' // could not be found in any of the tables of keyspace 'ks' BOOST_FAIL("Exception expected"); } catch (exceptions::invalid_request_exception) { } }); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef LIBPORT_LOCAL_DATA_HXX # define LIBPORT_LOCAL_DATA_HXX # include <boost/type_traits/is_base_of.hpp> # include <boost/mpl/if.hpp> namespace libport { namespace localdata { /// \brief Handle data with only one encapsulation. template <typename T> struct DataType { typedef typename T::target target; typedef typename T::type type; typedef typename T::container container; static target* get(container& c, bool create = false); static void set(container& c, target* e); }; template <typename T> typename DataType<T>::target* DataType<T>::get(container& c, bool create) { return c.get(); } template <typename T> void DataType<T>::set(container& c, target* e) { c.reset(e); } /// \brief Handle data with multiple local data encapsulation. template <typename T> struct LocalDataType { typedef typename T::target target; typedef typename T::type type; typedef typename T::container container; static target* get(container& c, bool create = false); static void set(container& c, target* e); private: static type* get_type(container& c, bool create); }; template <typename T> typename LocalDataType<T>::type* LocalDataType<T>::get_type(container& c, bool create) { type* e = c.get(); if (!e) { if (create) { e = new type; c.reset(e); } else return 0; } return e; } template <typename T> typename LocalDataType<T>::target* LocalDataType<T>::get(container& c, bool create) { type* e = get_type(c, create); if (e) return e->get(); return 0; } template <typename T> void LocalDataType<T>::set(container& c, target* e) { get_type(c, true)->set(e); } // parametric typedef. template <typename T> struct WrapperFuns : boost::mpl::if_< boost::is_base_of< AbstractLocalData<typename T::target>, typename T::type >, LocalDataType<T>, DataType<T> >::type { }; } template <typename T, typename Enc> T* LocalData<T, Enc>::get() { return localdata::WrapperFuns<traits>::get(container_); } template <typename T, typename Enc> void LocalData<T, Enc>::set(T* v) { localdata::WrapperFuns<traits>::set(container_, v); } template <typename T, typename Enc> T& LocalSingleton<T, Enc>::instance(builder b) { T* e = data_.get(); if (!e) { assert(!b.empty()); e = b(); data_.set(e); } return *e; } } #endif <commit_msg>Libport.LocalData: fix warning.<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef LIBPORT_LOCAL_DATA_HXX # define LIBPORT_LOCAL_DATA_HXX # include <boost/type_traits/is_base_of.hpp> # include <boost/mpl/if.hpp> namespace libport { namespace localdata { /// \brief Handle data with only one encapsulation. template <typename T> struct DataType { typedef typename T::target target; typedef typename T::type type; typedef typename T::container container; static target* get(container& c, bool create = false); static void set(container& c, target* e); }; template <typename T> typename DataType<T>::target* DataType<T>::get(container& c, bool) { return c.get(); } template <typename T> void DataType<T>::set(container& c, target* e) { c.reset(e); } /// \brief Handle data with multiple local data encapsulation. template <typename T> struct LocalDataType { typedef typename T::target target; typedef typename T::type type; typedef typename T::container container; static target* get(container& c, bool create = false); static void set(container& c, target* e); private: static type* get_type(container& c, bool create); }; template <typename T> typename LocalDataType<T>::type* LocalDataType<T>::get_type(container& c, bool create) { type* e = c.get(); if (!e) { if (create) { e = new type; c.reset(e); } else return 0; } return e; } template <typename T> typename LocalDataType<T>::target* LocalDataType<T>::get(container& c, bool create) { type* e = get_type(c, create); if (e) return e->get(); return 0; } template <typename T> void LocalDataType<T>::set(container& c, target* e) { get_type(c, true)->set(e); } // parametric typedef. template <typename T> struct WrapperFuns : boost::mpl::if_< boost::is_base_of< AbstractLocalData<typename T::target>, typename T::type >, LocalDataType<T>, DataType<T> >::type { }; } template <typename T, typename Enc> T* LocalData<T, Enc>::get() { return localdata::WrapperFuns<traits>::get(container_); } template <typename T, typename Enc> void LocalData<T, Enc>::set(T* v) { localdata::WrapperFuns<traits>::set(container_, v); } template <typename T, typename Enc> T& LocalSingleton<T, Enc>::instance(builder b) { T* e = data_.get(); if (!e) { assert(!b.empty()); e = b(); data_.set(e); } return *e; } } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg 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 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. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <ctime> #include <algorithm> #include <vector> #include <set> #include <list> #include <deque> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/path.hpp> #include <boost/thread.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/storage.hpp" #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; namespace fs = boost::filesystem; namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; struct filesystem_init { filesystem_init(); }; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0"); ~session(); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! torrent_handle add_torrent( torrent_info const& ti , fs::path const& save_path , entry const& resume_data = entry() , bool compact_mode = true , bool paused = false , storage_constructor_type sc = default_storage_constructor); torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , fs::path const& save_path , entry const& resume_data = entry() , bool compact_mode = true , bool paused = true , storage_constructor_type sc = default_storage_constructor); session_proxy abort() { return session_proxy(m_impl); } session_status status() const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*)> ext); #endif void set_ip_filter(ip_filter const& f); void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; void remove_torrent(const torrent_handle& h); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); std::auto_ptr<alert> pop_alert(); void set_severity_level(alert::severity_t s); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); void start_natpmp(); void start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // just a way to initialize boost.filesystem // before the session_impl is created aux::filesystem_init m_dummy; // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <commit_msg>fixed default value for paused<commit_after>/* Copyright (c) 2006, Arvid Norberg 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 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. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <ctime> #include <algorithm> #include <vector> #include <set> #include <list> #include <deque> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/path.hpp> #include <boost/thread.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/storage.hpp" #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; namespace fs = boost::filesystem; namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; struct filesystem_init { filesystem_init(); }; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0"); ~session(); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! torrent_handle add_torrent( torrent_info const& ti , fs::path const& save_path , entry const& resume_data = entry() , bool compact_mode = true , bool paused = false , storage_constructor_type sc = default_storage_constructor); torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , fs::path const& save_path , entry const& resume_data = entry() , bool compact_mode = true , bool paused = false , storage_constructor_type sc = default_storage_constructor); session_proxy abort() { return session_proxy(m_impl); } session_status status() const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*)> ext); #endif void set_ip_filter(ip_filter const& f); void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; void remove_torrent(const torrent_handle& h); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); std::auto_ptr<alert> pop_alert(); void set_severity_level(alert::severity_t s); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); void start_natpmp(); void start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // just a way to initialize boost.filesystem // before the session_impl is created aux::filesystem_init m_dummy; // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg 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 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. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/alert.hpp" // alert::error_notification #include "libtorrent/add_torrent_params.hpp" #include "libtorrent/storage.hpp" #include <boost/preprocessor/cat.hpp> #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; class natpmp; class upnp; class alert; // this is used to create linker errors when trying to link to // a library with a conflicting build configuration than the application #ifdef TORRENT_DEBUG #define G _release #else #define G _debug #endif #ifdef TORRENT_USE_OPENSSL #define S _ssl #else #define S _nossl #endif #ifdef TORRENT_DISABLE_DHT #define D _nodht #else #define D _dht #endif #ifdef TORRENT_DISABLE_POOL_ALLOCATOR #define P _nopoolalloc #else #define P _poolalloc #endif #define TORRENT_LINK_TEST_PREFIX libtorrent_build_config #define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G)))) #undef P #undef D #undef S #undef G inline void test_link() { extern void TORRENT_LINK_TEST_NAME(); TORRENT_LINK_TEST_NAME(); } session_settings min_memory_usage(); session_settings high_performance_seed(); namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0) , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0" , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); ~session(); void save_state(entry& e) const; void load_state(lazy_entry const& e); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; io_service& get_io_service(); // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_torrent(add_torrent_params const& params); #endif torrent_handle add_torrent(add_torrent_params const& params, error_code& ec); #ifndef TORRENT_NO_DEPRECATE // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( torrent_info const& ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( boost::intrusive_ptr<torrent_info> ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; #endif session_proxy abort() { return session_proxy(m_impl); } void pause(); void resume(); bool is_paused() const; session_status status() const; cache_status get_cache_status() const; void get_cache_info(sha1_hash const& ih , std::vector<cached_piece_info>& ret) const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); bool is_dht_running() const; #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext); #endif #ifndef TORRENT_DISABLE_GEO_IP int as_for_ip(address const& addr); bool load_asnum_db(char const* file); bool load_country_db(char const* file); #if TORRENT_USE_WSTRING bool load_country_db(wchar_t const* file); bool load_asnum_db(wchar_t const* file); #endif #endif void load_state(entry const& ses_state); entry state() const; void set_ip_filter(ip_filter const& f); ip_filter const& get_ip_filter() const; void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; enum options_t { none = 0, delete_files = 1 }; enum session_flags_t { add_default_plugins = 1, start_default_features = 2 }; void remove_torrent(const torrent_handle& h, int options = none); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif #if TORRENT_USE_I2P void set_i2p_proxy(proxy_settings const& s); proxy_settings const& i2p_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; int local_upload_rate_limit() const; int local_download_rate_limit() const; int max_half_open_connections() const; void set_local_upload_rate_limit(int bytes_per_second); void set_local_download_rate_limit(int bytes_per_second); void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); int max_connections() const; int max_uploads() const; std::auto_ptr<alert> pop_alert(); #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED; #endif void set_alert_mask(int m); size_t set_alert_queue_size_limit(size_t queue_size_limit_); alert const* wait_for_alert(time_duration max_wait); void set_alert_dispatch(boost::function<void(alert const&)> const& fun); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); natpmp* start_natpmp(); upnp* start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <commit_msg>disable exception-only functions when exceptions are disabled<commit_after>/* Copyright (c) 2006, Arvid Norberg 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 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. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/alert.hpp" // alert::error_notification #include "libtorrent/add_torrent_params.hpp" #include "libtorrent/storage.hpp" #include <boost/preprocessor/cat.hpp> #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; class natpmp; class upnp; class alert; // this is used to create linker errors when trying to link to // a library with a conflicting build configuration than the application #ifdef TORRENT_DEBUG #define G _release #else #define G _debug #endif #ifdef TORRENT_USE_OPENSSL #define S _ssl #else #define S _nossl #endif #ifdef TORRENT_DISABLE_DHT #define D _nodht #else #define D _dht #endif #ifdef TORRENT_DISABLE_POOL_ALLOCATOR #define P _nopoolalloc #else #define P _poolalloc #endif #define TORRENT_LINK_TEST_PREFIX libtorrent_build_config #define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G)))) #undef P #undef D #undef S #undef G inline void test_link() { extern void TORRENT_LINK_TEST_NAME(); TORRENT_LINK_TEST_NAME(); } session_settings min_memory_usage(); session_settings high_performance_seed(); namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0) , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0" , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); ~session(); void save_state(entry& e) const; void load_state(lazy_entry const& e); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; io_service& get_io_service(); // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_torrent(add_torrent_params const& params); #endif torrent_handle add_torrent(add_torrent_params const& params, error_code& ec); #ifndef BOOST_NO_EXCEPTIONS #ifndef TORRENT_NO_DEPRECATE // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( torrent_info const& ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( boost::intrusive_ptr<torrent_info> ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; #endif #endif session_proxy abort() { return session_proxy(m_impl); } void pause(); void resume(); bool is_paused() const; session_status status() const; cache_status get_cache_status() const; void get_cache_info(sha1_hash const& ih , std::vector<cached_piece_info>& ret) const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); bool is_dht_running() const; #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext); #endif #ifndef TORRENT_DISABLE_GEO_IP int as_for_ip(address const& addr); bool load_asnum_db(char const* file); bool load_country_db(char const* file); #if TORRENT_USE_WSTRING bool load_country_db(wchar_t const* file); bool load_asnum_db(wchar_t const* file); #endif #endif void load_state(entry const& ses_state); entry state() const; void set_ip_filter(ip_filter const& f); ip_filter const& get_ip_filter() const; void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; enum options_t { none = 0, delete_files = 1 }; enum session_flags_t { add_default_plugins = 1, start_default_features = 2 }; void remove_torrent(const torrent_handle& h, int options = none); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif #if TORRENT_USE_I2P void set_i2p_proxy(proxy_settings const& s); proxy_settings const& i2p_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; int local_upload_rate_limit() const; int local_download_rate_limit() const; int max_half_open_connections() const; void set_local_upload_rate_limit(int bytes_per_second); void set_local_download_rate_limit(int bytes_per_second); void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); int max_connections() const; int max_uploads() const; std::auto_ptr<alert> pop_alert(); #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED; #endif void set_alert_mask(int m); size_t set_alert_queue_size_limit(size_t queue_size_limit_); alert const* wait_for_alert(time_duration max_wait); void set_alert_dispatch(boost::function<void(alert const&)> const& fun); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); natpmp* start_natpmp(); upnp* start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2016 nshcat 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. */ #pragma once #include <string> #include "log_target.hxx" #include "log_entry.hxx" namespace lg { class network_target : public log_target { using handle_type = void*; public: network_target(severity_level p_lvl, const ::std::string& p_host, const ::std::string& p_port); ~network_target(); network_target(const network_target&) = delete; network_target(network_target&&) = default; network_target& operator=(const network_target&) = delete; network_target& operator=(network_target&&) = default; public: virtual void write(const log_entry& entry) override; private: auto connect() -> void; private: ::std::string m_Host; ::std::string m_Port; handle_type m_InternalData{nullptr}; }; } <commit_msg>Added protocol info to network_target header file.<commit_after>/* Copyright (c) 2016 nshcat 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. */ /* PROTOCOL: * * [u32] Length of message string * [u64] Timestamp (time_t) * [u32] Level * [u32] Is Bare? (0x1 or 0x0) * N*[u8] String payload */ #pragma once #include <string> #include "log_target.hxx" #include "log_entry.hxx" namespace lg { class network_target : public log_target { using handle_type = void*; public: network_target(severity_level p_lvl, const ::std::string& p_host, const ::std::string& p_port); ~network_target(); network_target(const network_target&) = delete; network_target(network_target&&) = default; network_target& operator=(const network_target&) = delete; network_target& operator=(network_target&&) = default; public: virtual void write(const log_entry& entry) override; private: auto connect() -> void; private: ::std::string m_Host; ::std::string m_Port; handle_type m_InternalData{nullptr}; }; } <|endoftext|>
<commit_before>#include "DataType.h" #include <iostream> using namespace std; DataType::DataType(Type type) { this->type = type; this->length = 0; } DataType::DataType(DataType::Type type, int length) { this->type = type; this->length = length; } //map<string, DataType::Type> DataType::str_to_type = { // {"int", DataType::INT}, // {"float", DataType::FLOAT}, // {"double", DataType::DOUBLE}, // {"char", DataType::CHAR}, //}; // // //map<DataType::Type, string> reverse_map(map<string, DataType::Type> str_to_type) { // map<DataType::Type, string> reversed; // for (auto it = str_to_type.begin(); it != str_to_type.end(); ++it) // reversed[it->second] = it->first; // return reversed; //}; // //map<DataType::Type, string> DataType::type_to_str = { // {DataType::INT, "int32_t"}, // {DataType::FLOAT, "float"}, // {DataType::DOUBLE, "double"}, // {DataType::CHAR, "char*"}, //}; //string DataType::convert_type_to_str(DataType::Type type) { // auto it = DataType::type_to_str.find(type); // if (it == DataType::type_to_str.end()) // return nullptr; // return it->second; //} //DataType::Type DataType::convert_str_to_type(string str) { // auto it = DataType::str_to_type.find(str); // if (it == DataType::str_to_type.end()) { // return (DataType::Type) (-1); // } // return it->second; //} DataType::Type DataType::get_typecode() { return this->type; } int DataType::get_length() { return this->length; } int DataType::equals(DataType *that) { if (this->get_typecode() != that->get_typecode()) return 0; if (this->get_typecode() == DataType::INT) return 1; if (this->get_typecode() == DataType::DOUBLE) return 1; if (this->get_typecode() == DataType::FLOAT) return 1; if (this->get_typecode() == DataType::CHAR) return this->get_length() == that->get_length(); return 0; } string DataType::str(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { string s("char " + name + "[" + to_string(this->get_length()) + "]"); return s; } return ""; } string DataType::str_out(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { string s("char " + name + "[" + to_string(this->get_length()+1) + "]"); return s; } return ""; } string DataType::signature(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { return "const char* " + name; } return ""; } string DataType::get_format_specifier() { if (this->get_typecode() == DataType::INT) return "%d"; if (this->get_typecode() == DataType::DOUBLE) return "%f"; if (this->get_typecode() == DataType::FLOAT) return "%f"; if (this->get_typecode() == DataType::CHAR) { return "\\\"%s\\\""; } return ""; } string DataType::scan_expr(string column_name) { if (this->get_typecode() == DataType::INT) return "sscanf(token, \"%d\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::DOUBLE) return "sscanf(token, \"%lf\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::FLOAT) return "sscanf(token, \"%f\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::CHAR) { return "memcpy(arg->" + column_name + ", token + sizeof(char), strlen(token)-2);"; } return ""; } string DataType::init_expr(string column_name) { if (this->get_typecode() == DataType::INT) return "new->" + column_name + " = 0;"; if (this->get_typecode() == DataType::DOUBLE) return "new->" + column_name + " = 0.0;"; if (this->get_typecode() == DataType::FLOAT) return "new->" + column_name + " = 0.0;"; if (this->get_typecode() == DataType::CHAR) { return "memset(new->" + column_name + ", 0, " + to_string(this->get_length()) + ");"; } return ""; } string DataType::select_expr(std::string param, std::string column) { if (this->get_typecode() == DataType::INT) return "inserted->" + param + " = page.items[i]->" + column + ";"; if (this->get_typecode() == DataType::DOUBLE) return "inserted->" + param + " = page.items[i]->" + column + ";"; if (this->get_typecode() == DataType::FLOAT) return "inserted->" + param + " = page.items[i]->" + column + ";"; if (this->get_typecode() == DataType::CHAR) { return "memcpy(inserted->" + column + ", page.items[i]." + param + ", " + to_string(this->get_length()) + "); inserted->" + column + "[" + to_string(this->get_length()) + "] = '\\0';"; } return ""; } string DataType::compare_less_expr(string s1, string col1, string s2, string col2) { if (this->get_typecode() == DataType::INT) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::DOUBLE) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::FLOAT) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::CHAR) { return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") < 0"; } return ""; } string DataType::compare_greater_expr(string s1, string col1, string s2, string col2) { if (this->get_typecode() == DataType::INT) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::DOUBLE) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::FLOAT) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::CHAR) { return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") > 0"; } return ""; }<commit_msg>generation 5<commit_after>#include "DataType.h" #include <iostream> using namespace std; DataType::DataType(Type type) { this->type = type; this->length = 0; } DataType::DataType(DataType::Type type, int length) { this->type = type; this->length = length; } //map<string, DataType::Type> DataType::str_to_type = { // {"int", DataType::INT}, // {"float", DataType::FLOAT}, // {"double", DataType::DOUBLE}, // {"char", DataType::CHAR}, //}; // // //map<DataType::Type, string> reverse_map(map<string, DataType::Type> str_to_type) { // map<DataType::Type, string> reversed; // for (auto it = str_to_type.begin(); it != str_to_type.end(); ++it) // reversed[it->second] = it->first; // return reversed; //}; // //map<DataType::Type, string> DataType::type_to_str = { // {DataType::INT, "int32_t"}, // {DataType::FLOAT, "float"}, // {DataType::DOUBLE, "double"}, // {DataType::CHAR, "char*"}, //}; //string DataType::convert_type_to_str(DataType::Type type) { // auto it = DataType::type_to_str.find(type); // if (it == DataType::type_to_str.end()) // return nullptr; // return it->second; //} //DataType::Type DataType::convert_str_to_type(string str) { // auto it = DataType::str_to_type.find(str); // if (it == DataType::str_to_type.end()) { // return (DataType::Type) (-1); // } // return it->second; //} DataType::Type DataType::get_typecode() { return this->type; } int DataType::get_length() { return this->length; } int DataType::equals(DataType *that) { if (this->get_typecode() != that->get_typecode()) return 0; if (this->get_typecode() == DataType::INT) return 1; if (this->get_typecode() == DataType::DOUBLE) return 1; if (this->get_typecode() == DataType::FLOAT) return 1; if (this->get_typecode() == DataType::CHAR) return this->get_length() == that->get_length(); return 0; } string DataType::str(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { string s("char " + name + "[" + to_string(this->get_length()) + "]"); return s; } return ""; } string DataType::str_out(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { string s("char " + name + "[" + to_string(this->get_length()+1) + "]"); return s; } return ""; } string DataType::signature(string name) { if (this->get_typecode() == DataType::INT) return "int32_t " + name; if (this->get_typecode() == DataType::DOUBLE) return "double " + name; if (this->get_typecode() == DataType::FLOAT) return "float " + name; if (this->get_typecode() == DataType::CHAR) { return "const char* " + name; } return ""; } string DataType::get_format_specifier() { if (this->get_typecode() == DataType::INT) return "%d"; if (this->get_typecode() == DataType::DOUBLE) return "%f"; if (this->get_typecode() == DataType::FLOAT) return "%f"; if (this->get_typecode() == DataType::CHAR) { return "\\\"%s\\\""; } return ""; } string DataType::scan_expr(string column_name) { if (this->get_typecode() == DataType::INT) return "sscanf(token, \"%d\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::DOUBLE) return "sscanf(token, \"%lf\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::FLOAT) return "sscanf(token, \"%f\", &(arg->" + column_name + "));"; if (this->get_typecode() == DataType::CHAR) { return "memcpy(arg->" + column_name + ", token + sizeof(char), strlen(token)-2);"; } return ""; } string DataType::init_expr(string column_name) { if (this->get_typecode() == DataType::INT) return "new->" + column_name + " = 0;"; if (this->get_typecode() == DataType::DOUBLE) return "new->" + column_name + " = 0.0;"; if (this->get_typecode() == DataType::FLOAT) return "new->" + column_name + " = 0.0;"; if (this->get_typecode() == DataType::CHAR) { return "memset(new->" + column_name + ", 0, " + to_string(this->get_length()) + ");"; } return ""; } string DataType::select_expr(std::string param, std::string column) { if (this->get_typecode() == DataType::INT) return "inserted->" + param + " = page.items[i]." + column + ";"; if (this->get_typecode() == DataType::DOUBLE) return "inserted->" + param + " = page.items[i]." + column + ";"; if (this->get_typecode() == DataType::FLOAT) return "inserted->" + param + " = page.items[i]." + column + ";"; if (this->get_typecode() == DataType::CHAR) { return "memcpy(inserted->" + column + ", page.items[i]." + param + ", " + to_string(this->get_length()) + "); inserted->" + column + "[" + to_string(this->get_length()) + "] = '\\0';"; } return ""; } string DataType::compare_less_expr(string s1, string col1, string s2, string col2) { if (this->get_typecode() == DataType::INT) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::DOUBLE) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::FLOAT) return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::CHAR) { return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") < 0"; } return ""; } string DataType::compare_greater_expr(string s1, string col1, string s2, string col2) { if (this->get_typecode() == DataType::INT) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::DOUBLE) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::FLOAT) return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")"; if (this->get_typecode() == DataType::CHAR) { return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") > 0"; } return ""; }<|endoftext|>
<commit_before>#ifndef SQUALL__EVENT_BUFFER_HXX #define SQUALL__EVENT_BUFFER_HXX #include <vector> #include <algorithm> #include "NonCopyable.hxx" #include "PlatformLoop.hxx" #include "PlatformWatcher.hxx" #ifdef HAVE_UNISTD_H #include <errno.h> #include <fcntl.h> #include <unistd.h> #endif // HAVE_UNISTD_H using std::placeholders::_1; namespace squall { /* Event-driven I/O buffer. */ class EventBuffer : public IoWatcher, NonCopyable { using watcher = IoWatcher; template <typename T> friend class Dispatcher; public: /** Buffer block size */ size_t blockSize() noexcept { return block_size; } /** Maximum buffer size */ size_t bufferSize() noexcept { return buffer_size; } /** Incomming buffer size */ size_t incomingSize() noexcept { return in.size(); } /** Outcomming buffer size */ size_t outcomingSize() noexcept { return out.size(); } /* Returns `Event::Read` or `Event::Write` if there is waiting a buffer events. otherwise 0. */ int pendingEvent() { return pending_event; } /* Destructor */ ~EventBuffer() {} /** Sets up a buffer for watching receiver events */ int setup_receiver(size_t threshold) { return setup_buffer(Event::Read, threshold, std::vector<char>()); } /** Sets up a buffer for watching receiver events */ int setup_receiver(const std::vector<char>& delimiter, size_t threshold = 0) { return setup_buffer(Event::Read, threshold, delimiter); } /** Sets up a buffer for watching transmiter events */ int setup_transmiter(size_t threshold = 0) { return setup_buffer(Event::Write, threshold, std::vector<char>()); } /** * Read bytes from incoming buffer how much is there, but not more `size`. * If `size == 0` tries to read bytes block defined with used threshold * and/or delimiter. */ std::vector<char> read(size_t size = 0) { std::vector<char> result; size = (size < in.size()) ? size : in.size(); if (pending_event == Event::Read) { size = ((size == 0) && (threshold < in.size())) ? threshold : size; cancel(); } if (size > 0) { std::copy(in.begin(), in.begin() + size, std::back_inserter(result)); in.erase(in.begin(), in.begin() + size); watcher::setup(fd(), mode() | Event::Read); } return result; } /** Writes data to the outcoming buffer. Returns number of written bytes. */ size_t write(std::vector<char> data) { if (pending_event == Event::Write) cancel(); auto size = (data.size() < buffer_size - out.size()) ? data.size() : buffer_size - out.size(); std::copy(data.begin(), data.begin() + size, std::back_inserter(out)); watcher::setup(fd(), mode() | Event::Write); return size; } /* Cancels a buffer event watching */ bool cancel() { if (pending_event) { threshold = 0; delimiter.clear(); pending_event = 0; return true; } return false; } protected: /* Constructor */ EventBuffer(OnEvent&& on_event, const std::shared_ptr<PlatformLoop>& sp_loop, int fd, size_t block_size = 0, size_t buffer_size = 0) : IoWatcher(std::bind(&EventBuffer::event_handler, this, _1), sp_loop), on_event(std::forward<OnEvent>(on_event)), block_size(block_size), buffer_size(buffer_size) { watcher::setup(fd, static_cast<int>(Event::Read)); adjust_buffer_size(); } /* Return true if is buffer watcher */ virtual bool is_buffer() noexcept { return true; } #ifndef _POSIX_VERSION public: /** Returns last error code. */ virtual int lastErrno() noexcept { return last_errno; }; protected: virtual bool set_non_block(int fd); virtual std::pair<size_t, int> write_block(char* buff, size_t block_size) = 0; virtual std::pair<size_t, int> read_block(const char* buff, size_t block_size) = 0; #else public: /** Returns last error code. */ virtual int lastErrno() noexcept { return last_errno >= 0 ? last_errno : EIO; }; protected: /* Sets non block */ virtual bool set_non_block() { auto flags = fcntl(fd(), F_GETFL, 0); flags = (flags == -1) ? 0 : flags; if (fcntl(fd(), F_SETFL, flags | O_NONBLOCK) == -1) last_errno = errno; return (last_errno == 0); } /* Reads block of bytes from device. */ std::pair<size_t, int> read_block(char* buff, size_t block_size) { auto size = ::read(fd(), buff, block_size); if (size > 0) return std::make_pair(size, 0); else if (size == 0) return std::make_pair(0, ECONNRESET); else if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) return std::make_pair(0, 0); else return std::make_pair(0, errno); } /* Write block of bytes to device. */ std::pair<size_t, int> write_block(const char* buff, size_t block_size) { auto size = ::write(fd(), buff, block_size); if (size >= 0) return std::make_pair(size, 0); else if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) return std::make_pair(0, 0); else return std::make_pair(0, errno); } #endif private: OnEvent on_event; int last_errno = 0; std::vector<char> in; std::vector<char> out; int pending_event = 0; std::vector<char> delimiter; size_t block_size, buffer_size, threshold; using watcher::setup; int setup_buffer(int pending_event_, size_t threshold_, const std::vector<char>& delimiter_) { cancel(); if (pending_event_ == Event::Read) threshold = threshold_ < buffer_size ? threshold_ : buffer_size; else if (pending_event_ == Event::Write) threshold = threshold_ < (buffer_size - block_size) ? threshold_ : (buffer_size - block_size); else { return 0; } delimiter = delimiter_; if (!delimiter.empty() && (threshold == 0)) threshold = buffer_size; pending_event = pending_event_; threshold = threshold > 0 ? threshold : 0; auto early_events = check_buffer_task(); if (early_events == 0) { watcher::setup(fd(), mode() | pending_event); return -1; } else return early_events; } int check_buffer_task() { int result = 0; if (pending_event == Event::Read) { if (delimiter.size() > 0) { auto found = std::search(in.begin(), in.end(), delimiter.begin(), delimiter.end()); if (found == in.end()) { if (threshold <= incomingSize()) // delimiter not found but max_size result = Event::Error; } else // delimiter found; move threshold threshold = std::distance(in.begin(), found) + delimiter.size(); } if (threshold <= incomingSize()) result |= Event::Read; } else if (pending_event == Event::Write) { if (out.size() <= threshold) result = Event::Write; } return result; } void adjust_buffer_size() { block_size = (block_size > 1024) ? block_size : 1024; block_size += (block_size % 1024) ? 1024 : 0; block_size = (block_size / 1024) * 1024; buffer_size = (buffer_size > 1024 * 4) ? buffer_size : 1024 * 4; buffer_size = (buffer_size / block_size) * block_size; threshold = 0; } void event_handler(int revents) { if (revents & Event::Error) last_errno = -1; else { size_t from = 0; size_t size = 0; last_errno = 0; if (revents & Event::Read) { size = buffer_size - in.size(); size = (size < block_size) ? size : block_size; if (size > 0) { from = in.size(); in.resize(in.size() + size); auto result = read_block(&(*(in.begin() + from)), size); if (result.first > 0) { if (result.first != size) in.resize(in.size() - size + result.first); } else last_errno = result.second; // read error } } if (revents & Event::Write) { size = out.size() < block_size ? out.size() : block_size; if (size > 0) { auto result = write_block(&(*out.begin()), size); if (result.first > 0) out.erase(out.begin(), out.begin() + result.first); else last_errno = result.second; // write error } } } // update I/O buffer mode if (last_errno == 0) { if ((revents & Event::Read) && (in.size() >= buffer_size)) watcher::setup(fd(), mode() & Event::Write); if ((revents & Event::Write) && out.empty()) watcher::setup(fd(), mode() & Event::Read); } else watcher::setup(fd(), 0); // generate buffer events if (pending_event) { auto buffer_events = check_buffer_task(); if (buffer_events) on_event(buffer_events); } } }; } #endif // SQUALL__EVENT_BUFFER_HXX<commit_msg>fixes<commit_after>#ifndef SQUALL__EVENT_BUFFER_HXX #define SQUALL__EVENT_BUFFER_HXX #include <vector> #include <algorithm> #include "NonCopyable.hxx" #include "PlatformLoop.hxx" #include "PlatformWatcher.hxx" #ifdef HAVE_UNISTD_H #include <errno.h> #include <fcntl.h> #include <unistd.h> #endif // HAVE_UNISTD_H using std::placeholders::_1; namespace squall { /* Event-driven I/O buffer. */ class EventBuffer : public IoWatcher, NonCopyable { using watcher = IoWatcher; template <typename T> friend class Dispatcher; public: /** Buffer block size */ size_t blockSize() noexcept { return block_size; } /** Maximum buffer size */ size_t bufferSize() noexcept { return buffer_size; } /** Incomming buffer size */ size_t incomingSize() noexcept { return in.size(); } /** Outcomming buffer size */ size_t outcomingSize() noexcept { return out.size(); } /* Returns `Event::Read` or `Event::Write` if there is waiting a buffer events. otherwise 0. */ int pendingEvent() { return pending_event; } /* Destructor */ ~EventBuffer() {} /** Sets up a buffer for watching receiver events */ int setup_receiver(size_t threshold) { return setup_buffer(Event::Read, threshold, std::vector<char>()); } /** Sets up a buffer for watching receiver events */ int setup_receiver(const std::vector<char>& delimiter, size_t threshold = 0) { return setup_buffer(Event::Read, threshold, delimiter); } /** Sets up a buffer for watching transmiter events */ int setup_transmiter(size_t threshold = 0) { return setup_buffer(Event::Write, threshold, std::vector<char>()); } /** * Read bytes from incoming buffer how much is there, but not more `size`. * If `size == 0` tries to read bytes block defined with used threshold * and/or delimiter. */ std::vector<char> read(size_t size = 0) { std::vector<char> result; size = (size < in.size()) ? size : in.size(); if (pending_event == Event::Read) { size = ((size == 0) && (threshold < in.size())) ? threshold : size; cancel(); } if (size > 0) { std::copy(in.begin(), in.begin() + size, std::back_inserter(result)); in.erase(in.begin(), in.begin() + size); watcher::setup(fd(), mode() | Event::Read); } return result; } /** Writes data to the outcoming buffer. Returns number of written bytes. */ size_t write(std::vector<char> data) { if (pending_event == Event::Write) cancel(); auto size = (data.size() < buffer_size - out.size()) ? data.size() : buffer_size - out.size(); std::copy(data.begin(), data.begin() + size, std::back_inserter(out)); watcher::setup(fd(), mode() | Event::Write); return size; } /* Cancels a buffer event watching */ bool cancel() { if (pending_event) { threshold = 0; delimiter.clear(); pending_event = 0; return true; } return false; } protected: /* Constructor */ EventBuffer(OnEvent&& on_event, const std::shared_ptr<PlatformLoop>& sp_loop, int fd, size_t block_size = 0, size_t buffer_size = 0) : IoWatcher(std::bind(&EventBuffer::event_handler, this, _1), sp_loop), on_event(std::forward<OnEvent>(on_event)), block_size(block_size), buffer_size(buffer_size) { watcher::setup(fd, static_cast<int>(Event::Read)); adjust_buffer_size(); set_non_block(fd); } /* Return true if is buffer watcher */ virtual bool is_buffer() noexcept { return true; } #ifndef _POSIX_VERSION public: /** Returns last error code. */ virtual int lastErrno() noexcept { return last_errno; }; protected: virtual bool set_non_block(int fd); virtual std::pair<size_t, int> write_block(char* buff, size_t block_size) = 0; virtual std::pair<size_t, int> read_block(const char* buff, size_t block_size) = 0; #else public: /** Returns last error code. */ virtual int lastErrno() noexcept { return last_errno >= 0 ? last_errno : EIO; }; protected: /* Sets non block */ virtual bool set_non_block(int fd) { auto flags = fcntl(fd, F_GETFL, 0); flags = (flags == -1) ? 0 : flags; if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) last_errno = errno; return (last_errno == 0); } /* Reads block of bytes from device. */ std::pair<size_t, int> read_block(char* buff, size_t block_size) { auto size = ::read(fd(), buff, block_size); if (size > 0) return std::make_pair(size, 0); else if (size == 0) return std::make_pair(0, ECONNRESET); else if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) return std::make_pair(0, 0); else return std::make_pair(0, errno); } /* Write block of bytes to device. */ std::pair<size_t, int> write_block(const char* buff, size_t block_size) { auto size = ::write(fd(), buff, block_size); if (size >= 0) return std::make_pair(size, 0); else if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) return std::make_pair(0, 0); else return std::make_pair(0, errno); } #endif private: OnEvent on_event; int last_errno = 0; std::vector<char> in; std::vector<char> out; int pending_event = 0; std::vector<char> delimiter; size_t block_size, buffer_size, threshold; using watcher::setup; int setup_buffer(int pending_event_, size_t threshold_, const std::vector<char>& delimiter_) { cancel(); if (pending_event_ == Event::Read) threshold = threshold_ < buffer_size ? threshold_ : buffer_size; else if (pending_event_ == Event::Write) threshold = threshold_ < (buffer_size - block_size) ? threshold_ : (buffer_size - block_size); else { return 0; } delimiter = delimiter_; if (!delimiter.empty() && (threshold == 0)) threshold = buffer_size; pending_event = pending_event_; threshold = threshold > 0 ? threshold : 0; auto early_events = check_buffer_task(); if (early_events == 0) { watcher::setup(fd(), mode() | pending_event); return -1; } else return early_events; } int check_buffer_task() { int result = 0; if (pending_event == Event::Read) { if (delimiter.size() > 0) { auto found = std::search(in.begin(), in.end(), delimiter.begin(), delimiter.end()); if (found == in.end()) { if (threshold <= incomingSize()) // delimiter not found but max_size result = Event::Error; } else // delimiter found; move threshold threshold = std::distance(in.begin(), found) + delimiter.size(); } if (threshold <= incomingSize()) result |= Event::Read; } else if (pending_event == Event::Write) { if (out.size() <= threshold) result = Event::Write; } if ((result==0)&&(last_errno != 0)) result = Event::Error; return result; } void adjust_buffer_size() { block_size = (block_size > 1024) ? block_size : 1024; block_size += (block_size % 1024) ? 1024 : 0; block_size = (block_size / 1024) * 1024; buffer_size = (buffer_size > 1024 * 4) ? buffer_size : 1024 * 4; buffer_size = (buffer_size / block_size) * block_size; threshold = 0; } void event_handler(int revents) { if (revents & Event::Error) last_errno = -1; else { size_t from = 0; size_t size = 0; last_errno = 0; if (revents & Event::Read) { size = buffer_size - in.size(); size = (size < block_size) ? size : block_size; if (size > 0) { from = in.size(); in.resize(in.size() + size); auto result = read_block(&(*(in.begin() + from)), size); if (result.first > 0) { if (result.first != size) in.resize(in.size() - size + result.first); } else last_errno = result.second; // read error } } if ((last_errno == 0) && (revents & Event::Write)) { size = out.size() < block_size ? out.size() : block_size; if (size > 0) { auto result = write_block(&(*out.begin()), size); if (result.first > 0) out.erase(out.begin(), out.begin() + result.first); else last_errno = result.second; // write error } } } // update I/O buffer mode if (last_errno == 0) { if ((revents & Event::Read) && (in.size() >= buffer_size)) watcher::setup(fd(), mode() & Event::Write); if ((revents & Event::Write) && out.empty()) watcher::setup(fd(), mode() & Event::Read); } else watcher::setup(fd(), 0); // generate buffer events if (pending_event) { auto buffer_events = check_buffer_task(); if (buffer_events) on_event(buffer_events); } } }; } #endif // SQUALL__EVENT_BUFFER_HXX<|endoftext|>
<commit_before>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL #ifndef TAO_PEGTL_DEMANGLE_HPP #define TAO_PEGTL_DEMANGLE_HPP #include <ciso646> #include <string_view> #include "config.hpp" #include "internal/dependent_true.hpp" namespace TAO_PEGTL_NAMESPACE { #if defined( __clang__ ) #if defined( _LIBCPP_VERSION ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) ); return sv.substr( begin + 2, sv.size() - begin - 3 ); } #else // When using libstdc++ with clang, std::string_view::find is not constexpr :( template< char C > constexpr const char* find( const char* p, std::size_t n ) noexcept { while( n ) { if( *p == C ) { return p; } ++p; --n; } return nullptr; } template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = find< '=' >( sv.data(), sv.size() ); static_assert( internal::dependent_true< T > && ( begin != nullptr ) ); return { begin + 2, sv.data() + sv.size() - begin - 3 }; } #endif #elif defined( __GNUC__ ) #if( __GNUC__ == 7 ) // GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions, // therefore we drop the 'constexpr' and hope for the best. template< typename T > [[nodiscard]] std::string_view demangle() noexcept { const std::string_view sv = __PRETTY_FUNCTION__; const auto begin = sv.find( '=' ); const auto tmp = sv.substr( begin + 2 ); const auto end = tmp.rfind( ';' ); return tmp.substr( 0, end ); } #elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 ) // GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names, // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155 template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) ); constexpr auto tmp = sv.substr( begin + 2 ); constexpr auto end = tmp.rfind( ';' ); static_assert( internal::dependen_true< T > && ( end != std::string_view::npos ) ); return tmp.substr( 0, end ); } #endif #elif defined( _MSC_VER ) #if( _MSC_VER < 1920 ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { const std::string_view sv = __FUNCSIG__; const auto begin = sv.find( "demangle<" ); const auto tmp = sv.substr( begin + 9 ); const auto end = tmp.rfind( '>' ); return tmp.substr( 0, end ); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __FUNCSIG__; constexpr auto begin = sv.find( "demangle<" ); static_assert( internal::dependen_true< T > && ( begin != std::string_view::npos ) ); constexpr auto tmp = sv.substr( begin + 9 ); constexpr auto end = tmp.rfind( '>' ); static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) ); return tmp.substr( 0, end ); } #endif #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #endif } // namespace TAO_PEGTL_NAMESPACE #endif <commit_msg>Fix typo.<commit_after>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL #ifndef TAO_PEGTL_DEMANGLE_HPP #define TAO_PEGTL_DEMANGLE_HPP #include <ciso646> #include <string_view> #include "config.hpp" #include "internal/dependent_true.hpp" namespace TAO_PEGTL_NAMESPACE { #if defined( __clang__ ) #if defined( _LIBCPP_VERSION ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) ); return sv.substr( begin + 2, sv.size() - begin - 3 ); } #else // When using libstdc++ with clang, std::string_view::find is not constexpr :( template< char C > constexpr const char* find( const char* p, std::size_t n ) noexcept { while( n ) { if( *p == C ) { return p; } ++p; --n; } return nullptr; } template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = find< '=' >( sv.data(), sv.size() ); static_assert( internal::dependent_true< T > && ( begin != nullptr ) ); return { begin + 2, sv.data() + sv.size() - begin - 3 }; } #endif #elif defined( __GNUC__ ) #if( __GNUC__ == 7 ) // GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions, // therefore we drop the 'constexpr' and hope for the best. template< typename T > [[nodiscard]] std::string_view demangle() noexcept { const std::string_view sv = __PRETTY_FUNCTION__; const auto begin = sv.find( '=' ); const auto tmp = sv.substr( begin + 2 ); const auto end = tmp.rfind( ';' ); return tmp.substr( 0, end ); } #elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 ) // GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names, // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155 template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) ); constexpr auto tmp = sv.substr( begin + 2 ); constexpr auto end = tmp.rfind( ';' ); static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) ); return tmp.substr( 0, end ); } #endif #elif defined( _MSC_VER ) #if( _MSC_VER < 1920 ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { const std::string_view sv = __FUNCSIG__; const auto begin = sv.find( "demangle<" ); const auto tmp = sv.substr( begin + 9 ); const auto end = tmp.rfind( '>' ); return tmp.substr( 0, end ); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __FUNCSIG__; constexpr auto begin = sv.find( "demangle<" ); static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) ); constexpr auto tmp = sv.substr( begin + 9 ); constexpr auto end = tmp.rfind( '>' ); static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) ); return tmp.substr( 0, end ); } #endif #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #endif } // namespace TAO_PEGTL_NAMESPACE #endif <|endoftext|>
<commit_before>// Copyright (c) 2013, Cloudera, inc. #include "util/net/socket.h" #include <errno.h> #include <glog/logging.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <string> #include "util/errno.h" #include "util/net/sockaddr.h" namespace kudu { Socket::Socket() : fd_(-1) { } Socket::Socket(int fd) : fd_(fd) { } void Socket::Reset(int fd) { Close(); fd_ = fd; } int Socket::Release() { int fd = fd_; fd_ = -1; return fd; } Socket::~Socket() { Close(); } Status Socket::Close() { if (fd_ < 0) return Status::OK(); int err, fd = fd_; fd_ = -1; if (::close(fd) < 0) { err = errno; return Status::NetworkError(std::string("close error: ") + ErrnoToString(err), Slice(), err); } fd = -1; return Status::OK(); } Status Socket::Shutdown(bool shut_read, bool shut_write) { DCHECK_GE(fd_, 0); int flags = 0; if (shut_read && shut_write) { flags |= SHUT_RDWR; } else if (shut_read) { flags |= SHUT_RD; } else if (shut_write) { flags |= SHUT_WR; } if (::shutdown(fd_, flags) < 0) { int err = errno; return Status::NetworkError(std::string("shutdown error: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } int Socket::GetFd() const { return fd_; } bool Socket::IsTemporarySocketError(int err) { return ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)); } #ifdef __linux Status Socket::Init(int flags) { int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? SOCK_NONBLOCK : 0; Reset(::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | nonblocking_flag, 0)); if (fd_ < 0) { int err = errno; return Status::NetworkError(std::string("error opening socket: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } #else #error This code has never been tested. Best of luck! Status Socket::Init(int flags) { Reset(::socket(AF_INET, SOCK_STREAM, 0)); if (fd_ < 0) { int err = errno; return Status::NetworkError(std::string("error opening socket: ") + ErrnoToString(err), Slice(), err); } int curflags = fcntl(fd_, F_GETFL, 0); if (curflags == -1) { int err = errno; Reset(-1); return Status::NetworkError(std::string("fcntl(F_GETFL) error: ") + ErrnoToString(err), Slice(), err); } int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? O_NONBLOCK : 0; if (fcntl(fd_, F_SETFL, curflags | nonblocking_flag | FD_CLOEXEC) == -1) { int err = errno; Reset(-1); return Status::NetworkError(std::string("fcntl(F_SETFL) error: ") + ErrnoToString(err), Slice(), err); } // Disable SIGPIPE. RETURN_NOT_OK(DisableSigPipe()); return Status::OK(); } #endif Status Socket::SetNoDelay(bool enabled) { int flag = enabled ? 1 : 0; if (setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == -1) { int err = errno; return Status::NetworkError(std::string("failed to set TCP_NODELAY: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } Status Socket::BindAndListen(const Sockaddr &sockaddr, int listenQueueSize) { int err; struct sockaddr_in addr = sockaddr.addr(); DCHECK_GE(fd_, 0); if (bind(fd_, (struct sockaddr*) &addr, sizeof(addr))) { err = errno; return Status::NetworkError( StringPrintf("error binding socket to %s: %s", sockaddr.ToString().c_str(), ErrnoToString(err).c_str()), Slice(), err); } if (listen(fd_, listenQueueSize)) { err = errno; return Status::NetworkError( StringPrintf("error listening on %s: %s", sockaddr.ToString().c_str(), ErrnoToString(err).c_str()), Slice(), err); } return Status::OK(); } Status Socket::GetSocketAddress(Sockaddr *cur_addr) { struct sockaddr_in sin; socklen_t len = sizeof(sin); DCHECK_GE(fd_, 0); if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) { int err = errno; return Status::NetworkError(string("getsockname error: ") + ErrnoToString(err), Slice(), err); } *cur_addr = sin; return Status::OK(); } Status Socket::Accept(Socket *new_conn, Sockaddr *remote, int flags) { struct sockaddr_in addr; socklen_t olen = sizeof(addr); int accept_flags = SOCK_CLOEXEC; if (flags & FLAG_NONBLOCKING) { accept_flags |= SOCK_NONBLOCK; } DCHECK_GE(fd_, 0); // TODO: add #ifdef accept4, etc. new_conn->Reset(::accept4(fd_, (struct sockaddr*)&addr, &olen, accept_flags)); if (new_conn->GetFd() < 0) { int err = errno; return Status::NetworkError(std::string("accept4(2) error: ") + ErrnoToString(err), Slice(), err); } *remote = addr; return Status::OK(); } Status Socket::Connect(const Sockaddr &remote) { struct sockaddr_in addr; memcpy(&addr, &remote.addr(), sizeof(sockaddr_in)); DCHECK_GE(fd_, 0); if (::connect(fd_, (const struct sockaddr*)&addr, sizeof(addr)) < 0) { int err = errno; return Status::NetworkError(std::string("connect(2) error: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } Status Socket::GetSockError() { int val = 0, ret; socklen_t val_len = sizeof(val); DCHECK_GE(fd_, 0); ret = ::getsockopt(fd_, SOL_SOCKET, SO_ERROR, &val, &val_len); if (ret) { int err = errno; return Status::NetworkError(std::string("getsockopt(SO_ERROR) failed: ") + ErrnoToString(err), Slice(), err); } if (val != 0) { return Status::NetworkError(ErrnoToString(val), Slice(), val); } return Status::OK(); } Status Socket::Write(uint8_t *buf, int32_t amt, int32_t *nwritten) { if (amt <= 0) { return Status::NetworkError( StringPrintf("invalid send of %"PRId32" bytes", amt), Slice(), EINVAL); } DCHECK_GE(fd_, 0); int res = ::write(fd_, buf, amt); if (res < 0) { int err = errno; return Status::NetworkError(std::string("write error: ") + ErrnoToString(err), Slice(), err); } *nwritten = res; return Status::OK(); } Status Socket::Writev(const struct ::iovec *iov, int iov_len, int32_t *nwritten) { if (PREDICT_FALSE(iov_len <= 0)) { return Status::NetworkError( StringPrintf("writev: invalid io vector length of %d", iov_len), Slice(), EINVAL); } DCHECK_GE(fd_, 0); struct msghdr msg; memset(&msg, 0, sizeof(struct msghdr)); msg.msg_iov = const_cast<iovec *>(iov); msg.msg_iovlen = iov_len; int res = sendmsg(fd_, &msg, MSG_NOSIGNAL); if (PREDICT_FALSE(res < 0)) { int err = errno; return Status::NetworkError(std::string("sendmsg error: ") + ErrnoToString(err), Slice(), err); } *nwritten = res; return Status::OK(); } Status Socket::Recv(uint8_t *buf, int32_t amt, int32_t *nread) { if (amt <= 0) { return Status::NetworkError( StringPrintf("invalid recv of %d bytes", amt), Slice(), EINVAL); } DCHECK_GE(fd_, 0); int res = ::recv(fd_, buf, amt, 0); if (res <= 0) { if (res == 0) { return Status::NetworkError("shut down by remote end", Slice(), ESHUTDOWN); } int err = errno; return Status::NetworkError(std::string("recv error: ") + ErrnoToString(err), Slice(), err); } *nread = res; return Status::OK(); } } // namespace kudu <commit_msg>socket: set SO_REUSEADDR when binding sockets<commit_after>// Copyright (c) 2013, Cloudera, inc. #include "util/net/socket.h" #include <errno.h> #include <glog/logging.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <string> #include "util/errno.h" #include "util/net/sockaddr.h" namespace kudu { Socket::Socket() : fd_(-1) { } Socket::Socket(int fd) : fd_(fd) { } void Socket::Reset(int fd) { Close(); fd_ = fd; } int Socket::Release() { int fd = fd_; fd_ = -1; return fd; } Socket::~Socket() { Close(); } Status Socket::Close() { if (fd_ < 0) return Status::OK(); int err, fd = fd_; fd_ = -1; if (::close(fd) < 0) { err = errno; return Status::NetworkError(std::string("close error: ") + ErrnoToString(err), Slice(), err); } fd = -1; return Status::OK(); } Status Socket::Shutdown(bool shut_read, bool shut_write) { DCHECK_GE(fd_, 0); int flags = 0; if (shut_read && shut_write) { flags |= SHUT_RDWR; } else if (shut_read) { flags |= SHUT_RD; } else if (shut_write) { flags |= SHUT_WR; } if (::shutdown(fd_, flags) < 0) { int err = errno; return Status::NetworkError(std::string("shutdown error: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } int Socket::GetFd() const { return fd_; } bool Socket::IsTemporarySocketError(int err) { return ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)); } #ifdef __linux Status Socket::Init(int flags) { int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? SOCK_NONBLOCK : 0; Reset(::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | nonblocking_flag, 0)); if (fd_ < 0) { int err = errno; return Status::NetworkError(std::string("error opening socket: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } #else #error This code has never been tested. Best of luck! Status Socket::Init(int flags) { Reset(::socket(AF_INET, SOCK_STREAM, 0)); if (fd_ < 0) { int err = errno; return Status::NetworkError(std::string("error opening socket: ") + ErrnoToString(err), Slice(), err); } int curflags = fcntl(fd_, F_GETFL, 0); if (curflags == -1) { int err = errno; Reset(-1); return Status::NetworkError(std::string("fcntl(F_GETFL) error: ") + ErrnoToString(err), Slice(), err); } int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? O_NONBLOCK : 0; if (fcntl(fd_, F_SETFL, curflags | nonblocking_flag | FD_CLOEXEC) == -1) { int err = errno; Reset(-1); return Status::NetworkError(std::string("fcntl(F_SETFL) error: ") + ErrnoToString(err), Slice(), err); } // Disable SIGPIPE. RETURN_NOT_OK(DisableSigPipe()); return Status::OK(); } #endif Status Socket::SetNoDelay(bool enabled) { int flag = enabled ? 1 : 0; if (setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == -1) { int err = errno; return Status::NetworkError(std::string("failed to set TCP_NODELAY: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } Status Socket::BindAndListen(const Sockaddr &sockaddr, int listenQueueSize) { int err; struct sockaddr_in addr = sockaddr.addr(); int yes = 1; if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { err = errno; return Status::NetworkError(std::string("failed to set SO_REUSEADDR: ") + ErrnoToString(err), Slice(), err); } DCHECK_GE(fd_, 0); if (bind(fd_, (struct sockaddr*) &addr, sizeof(addr))) { err = errno; return Status::NetworkError( StringPrintf("error binding socket to %s: %s", sockaddr.ToString().c_str(), ErrnoToString(err).c_str()), Slice(), err); } if (listen(fd_, listenQueueSize)) { err = errno; return Status::NetworkError( StringPrintf("error listening on %s: %s", sockaddr.ToString().c_str(), ErrnoToString(err).c_str()), Slice(), err); } return Status::OK(); } Status Socket::GetSocketAddress(Sockaddr *cur_addr) { struct sockaddr_in sin; socklen_t len = sizeof(sin); DCHECK_GE(fd_, 0); if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) { int err = errno; return Status::NetworkError(string("getsockname error: ") + ErrnoToString(err), Slice(), err); } *cur_addr = sin; return Status::OK(); } Status Socket::Accept(Socket *new_conn, Sockaddr *remote, int flags) { struct sockaddr_in addr; socklen_t olen = sizeof(addr); int accept_flags = SOCK_CLOEXEC; if (flags & FLAG_NONBLOCKING) { accept_flags |= SOCK_NONBLOCK; } DCHECK_GE(fd_, 0); // TODO: add #ifdef accept4, etc. new_conn->Reset(::accept4(fd_, (struct sockaddr*)&addr, &olen, accept_flags)); if (new_conn->GetFd() < 0) { int err = errno; return Status::NetworkError(std::string("accept4(2) error: ") + ErrnoToString(err), Slice(), err); } *remote = addr; return Status::OK(); } Status Socket::Connect(const Sockaddr &remote) { struct sockaddr_in addr; memcpy(&addr, &remote.addr(), sizeof(sockaddr_in)); DCHECK_GE(fd_, 0); if (::connect(fd_, (const struct sockaddr*)&addr, sizeof(addr)) < 0) { int err = errno; return Status::NetworkError(std::string("connect(2) error: ") + ErrnoToString(err), Slice(), err); } return Status::OK(); } Status Socket::GetSockError() { int val = 0, ret; socklen_t val_len = sizeof(val); DCHECK_GE(fd_, 0); ret = ::getsockopt(fd_, SOL_SOCKET, SO_ERROR, &val, &val_len); if (ret) { int err = errno; return Status::NetworkError(std::string("getsockopt(SO_ERROR) failed: ") + ErrnoToString(err), Slice(), err); } if (val != 0) { return Status::NetworkError(ErrnoToString(val), Slice(), val); } return Status::OK(); } Status Socket::Write(uint8_t *buf, int32_t amt, int32_t *nwritten) { if (amt <= 0) { return Status::NetworkError( StringPrintf("invalid send of %"PRId32" bytes", amt), Slice(), EINVAL); } DCHECK_GE(fd_, 0); int res = ::write(fd_, buf, amt); if (res < 0) { int err = errno; return Status::NetworkError(std::string("write error: ") + ErrnoToString(err), Slice(), err); } *nwritten = res; return Status::OK(); } Status Socket::Writev(const struct ::iovec *iov, int iov_len, int32_t *nwritten) { if (PREDICT_FALSE(iov_len <= 0)) { return Status::NetworkError( StringPrintf("writev: invalid io vector length of %d", iov_len), Slice(), EINVAL); } DCHECK_GE(fd_, 0); struct msghdr msg; memset(&msg, 0, sizeof(struct msghdr)); msg.msg_iov = const_cast<iovec *>(iov); msg.msg_iovlen = iov_len; int res = sendmsg(fd_, &msg, MSG_NOSIGNAL); if (PREDICT_FALSE(res < 0)) { int err = errno; return Status::NetworkError(std::string("sendmsg error: ") + ErrnoToString(err), Slice(), err); } *nwritten = res; return Status::OK(); } Status Socket::Recv(uint8_t *buf, int32_t amt, int32_t *nread) { if (amt <= 0) { return Status::NetworkError( StringPrintf("invalid recv of %d bytes", amt), Slice(), EINVAL); } DCHECK_GE(fd_, 0); int res = ::recv(fd_, buf, amt, 0); if (res <= 0) { if (res == 0) { return Status::NetworkError("shut down by remote end", Slice(), ESHUTDOWN); } int err = errno; return Status::NetworkError(std::string("recv error: ") + ErrnoToString(err), Slice(), err); } *nread = res; return Status::OK(); } } // namespace kudu <|endoftext|>
<commit_before>#include "stdafx.h" #include "Rule.h" #include "Simulation.h" namespace sim { Rule::Rule(json_spirit::Object &data) { weight = 0.0; for (json_spirit::Pair &pair : data) { std::string &key = pair.name_; if (key == "scores") setupNeededScores(pair.value_.get_array()); else if (key == "parameters") setupParameters(pair.value_.get_obj()); else if (key == "weight") weight = pair.value_.get_real(); else if (key == "function") setCalculationFunction(pair.value_.get_str()); else if (key == "backref") isBackrefRule = pair.value_.get_bool(); else std::cerr << "sim::Rule: invalid property \"" << key << "\"" << std::endl; } if (calculationFunction == &Rule::calc_dummy || calculationFunction == nullptr) std::cerr << "Rule without calculation function." << std::endl; if (calculationFunction == &Rule::calc_custom_binary) { if (ruleParameters.count("normalization_constant")) { customNormalizationConstant = ruleParameters["normalization_constant"]; if (!std::isnormal(customNormalizationConstant)) { std::cerr << "The normalization constant of the custom rating rule must be a non-zero number!" << std::endl; throw "The Simulation was stopped because of invalid rule parameters."; } } else { std::cerr << "Custom Rating rule needs a normalization constant!" << std::endl; throw "The simulation was stopped because of missing rule parameters."; } } } Rule::~Rule() { } void Rule::setupNeededScores(json_spirit::Array &data) { for (json_spirit::Value &val : data) { neededScores.push_back(val.get_str()); } } void Rule::setupParameters(json_spirit::Object &data) { for (json_spirit::Pair &pair : data) { std::string &key = pair.name_; ruleParameters[key] = pair.value_.get_real(); } } double Rule::getRawResults(Team &left, Team &right, double *weight, double *currentWinExpectancy) { assert((isBackrefRule && currentWinExpectancy != nullptr) || (!isBackrefRule && currentWinExpectancy == nullptr)); *weight = 1.0; return (this->*calculationFunction)(left, right, weight, currentWinExpectancy); } void Rule::setCalculationFunction(std::string functionName) { if (functionName == "elo_binary") calculationFunction = &Rule::calc_elo_binary; else if (functionName == "fifa_binary") calculationFunction = &Rule::calc_fifa_binary; else if (functionName == "value_binary") calculationFunction = &Rule::calc_value_binary; else if (functionName == "age_binary") calculationFunction = &Rule::calc_age_binary; else if (functionName == "homeadvantage_binary") calculationFunction = &Rule::calc_homeadvantage_binary; else if (functionName == "spi_binary") calculationFunction = &Rule::calc_spi_binary; else if (functionName == "luck_binary") calculationFunction = &Rule::calc_luck_binary; else if (functionName == "custom_binary") calculationFunction = &Rule::calc_custom_binary; else { std::cerr << "Unknown calculation function: \"" << functionName << "\"" << std::endl; calculationFunction = &Rule::calc_dummy; } } double Rule::calc_elo_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { return 1.0 / (1.0 + std::pow(10.0, (right.scores["ELO"] - left.scores["ELO"]) / 400.0)); } double Rule::calc_fifa_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["FIFA"]; const double &rightScore = right.scores["FIFA"]; const double logScore = std::log(leftScore / rightScore); const double result = 1.0 / (1.0 + std::exp(-logScore / 0.23725)); //std::cerr << "left: " << leftScore << "\tright: " << rightScore << "\tlog: " << logScore << "\tresult: " << result << std::endl; return result; } double Rule::calc_value_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["Value"]; const double &rightScore = right.scores["Value"]; const double logScore = std::log(leftScore / rightScore); const double result = 1.0 / (1.0 + std::exp(-logScore / 1.3026)); return result; } double Rule::calc_age_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["Age"]; const double &rightScore = right.scores["Age"]; const double ageDiff = leftScore - rightScore; const double result = 1.0 / (1.0 + std::exp(-(32.0 * ageDiff - ageDiff * ageDiff * ageDiff) / 131.0)); return result; } double Rule::calc_spi_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { if (probabilityLookupMatrix.empty()) generateExpectancyMatrix(&Rule::calculateSPIWinExpectancy); return probabilityLookupMatrix[left.index][right.index]; } double Rule::calc_homeadvantage_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &homeLeft = left.scores["HA"]; const double &homeRight = right.scores["HA"]; // this rule is only effective if at least one of the teams has a home-advantage assigned *weight = homeLeft / (homeLeft + homeRight); assert(((homeLeft + homeRight) == 0.0) || (*weight >= 0.0 && *weight <= 1.0)); // if not, the weight will be 0 anyway.. if (homeLeft == 0.0) return *currentWinExpectancy; return 2.0 / (1.0 + std::exp(-4.0 * (*currentWinExpectancy))) - 1.0; } double Rule::calc_custom_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { return 1.0 / (1.0 + std::exp((right.scores["Custom"] - left.scores["Custom"]) / customNormalizationConstant)); } void Rule::generateExpectancyMatrix(double (*fun)(Team&, Team&)) { assert(probabilityLookupMatrix.empty()); size_t teamCount = Simulation::singleton->teams.size(); probabilityLookupMatrix.resize(teamCount); for (size_t i = 0; i < teamCount; ++i) probabilityLookupMatrix[i].resize(teamCount); for (Team &left : Simulation::singleton->teams) { for (Team &right : Simulation::singleton->teams) { double prob_left = fun(left, right); double prob_right = fun(right, left); probabilityLookupMatrix[left.index][right.index] = prob_left; probabilityLookupMatrix[right.index][left.index] = prob_right; } } std::cerr << "Matrix is go\nI1\tI2\tP\t" << std::endl; for (size_t i = 0; i < teamCount; ++i) std::cerr << Simulation::singleton->teams[i].id << "\t"; std::cerr << std::endl; for (size_t i = 0; i < teamCount; ++i) { for (size_t c = 0; c < teamCount; ++c) std::cerr << probabilityLookupMatrix[i][c] << "\t"; std::cerr << std::endl; } } double Rule::calculateSPIWinExpectancy(Team &left, Team &right) { const double &off1 = left.scores["SPI Off"]; const double &off2 = right.scores["SPI Off"]; const double &def1 = left.scores["SPI Def"]; const double &def2 = right.scores["SPI Def"]; const double combined_off = (off1 + def2) / 2.0; const double combined_def = (def1 + off2) / 2.0; std::function<int(int)> factorial = [&](int n) { return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; }; auto poisson_probability = [&](double lambda, int times) { return std::exp(-lambda) * std::pow(lambda, (double)times) / (double)factorial(times); }; double prob_off(0.0), prob_def(0.0); for (int i = 0; i < 20; ++i) { const double equal_prob_off = poisson_probability(combined_off, i); const double equal_prob_def = poisson_probability(combined_def, i); double less_prob_off(0.0), less_prob_def(0.0); for (int c = 0; c < i; ++c) { less_prob_off += poisson_probability(combined_off, c); less_prob_def += poisson_probability(combined_def, c); } prob_off += equal_prob_off * less_prob_def; prob_def += equal_prob_def * less_prob_off; } return (prob_off / (prob_off + prob_def)); } } // namespace sim<commit_msg>simulation: made home-advantages of below 1 actually reduce the weight of the rule<commit_after>#include "stdafx.h" #include "Rule.h" #include "Simulation.h" namespace sim { Rule::Rule(json_spirit::Object &data) { weight = 0.0; for (json_spirit::Pair &pair : data) { std::string &key = pair.name_; if (key == "scores") setupNeededScores(pair.value_.get_array()); else if (key == "parameters") setupParameters(pair.value_.get_obj()); else if (key == "weight") weight = pair.value_.get_real(); else if (key == "function") setCalculationFunction(pair.value_.get_str()); else if (key == "backref") isBackrefRule = pair.value_.get_bool(); else std::cerr << "sim::Rule: invalid property \"" << key << "\"" << std::endl; } if (calculationFunction == &Rule::calc_dummy || calculationFunction == nullptr) std::cerr << "Rule without calculation function." << std::endl; if (calculationFunction == &Rule::calc_custom_binary) { if (ruleParameters.count("normalization_constant")) { customNormalizationConstant = ruleParameters["normalization_constant"]; if (!std::isnormal(customNormalizationConstant)) { std::cerr << "The normalization constant of the custom rating rule must be a non-zero number!" << std::endl; throw "The Simulation was stopped because of invalid rule parameters."; } } else { std::cerr << "Custom Rating rule needs a normalization constant!" << std::endl; throw "The simulation was stopped because of missing rule parameters."; } } } Rule::~Rule() { } void Rule::setupNeededScores(json_spirit::Array &data) { for (json_spirit::Value &val : data) { neededScores.push_back(val.get_str()); } } void Rule::setupParameters(json_spirit::Object &data) { for (json_spirit::Pair &pair : data) { std::string &key = pair.name_; ruleParameters[key] = pair.value_.get_real(); } } double Rule::getRawResults(Team &left, Team &right, double *weight, double *currentWinExpectancy) { assert((isBackrefRule && currentWinExpectancy != nullptr) || (!isBackrefRule && currentWinExpectancy == nullptr)); *weight = 1.0; return (this->*calculationFunction)(left, right, weight, currentWinExpectancy); } void Rule::setCalculationFunction(std::string functionName) { if (functionName == "elo_binary") calculationFunction = &Rule::calc_elo_binary; else if (functionName == "fifa_binary") calculationFunction = &Rule::calc_fifa_binary; else if (functionName == "value_binary") calculationFunction = &Rule::calc_value_binary; else if (functionName == "age_binary") calculationFunction = &Rule::calc_age_binary; else if (functionName == "homeadvantage_binary") calculationFunction = &Rule::calc_homeadvantage_binary; else if (functionName == "spi_binary") calculationFunction = &Rule::calc_spi_binary; else if (functionName == "luck_binary") calculationFunction = &Rule::calc_luck_binary; else if (functionName == "custom_binary") calculationFunction = &Rule::calc_custom_binary; else { std::cerr << "Unknown calculation function: \"" << functionName << "\"" << std::endl; calculationFunction = &Rule::calc_dummy; } } double Rule::calc_elo_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { return 1.0 / (1.0 + std::pow(10.0, (right.scores["ELO"] - left.scores["ELO"]) / 400.0)); } double Rule::calc_fifa_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["FIFA"]; const double &rightScore = right.scores["FIFA"]; const double logScore = std::log(leftScore / rightScore); const double result = 1.0 / (1.0 + std::exp(-logScore / 0.23725)); //std::cerr << "left: " << leftScore << "\tright: " << rightScore << "\tlog: " << logScore << "\tresult: " << result << std::endl; return result; } double Rule::calc_value_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["Value"]; const double &rightScore = right.scores["Value"]; const double logScore = std::log(leftScore / rightScore); const double result = 1.0 / (1.0 + std::exp(-logScore / 1.3026)); return result; } double Rule::calc_age_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &leftScore = left.scores["Age"]; const double &rightScore = right.scores["Age"]; const double ageDiff = leftScore - rightScore; const double result = 1.0 / (1.0 + std::exp(-(32.0 * ageDiff - ageDiff * ageDiff * ageDiff) / 131.0)); return result; } double Rule::calc_spi_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { if (probabilityLookupMatrix.empty()) generateExpectancyMatrix(&Rule::calculateSPIWinExpectancy); return probabilityLookupMatrix[left.index][right.index]; } double Rule::calc_homeadvantage_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { const double &homeLeft = left.scores["HA"]; const double &homeRight = right.scores["HA"]; // this rule is only effective if at least one of the teams has a home-advantage assigned *weight = homeLeft / std::max(1.0, homeLeft + homeRight); assert(((homeLeft + homeRight) == 0.0) || (*weight >= 0.0 && *weight <= 1.0)); // if not, the weight will be 0 anyway.. if (homeLeft == 0.0) return *currentWinExpectancy; return 2.0 / (1.0 + std::exp(-4.0 * (*currentWinExpectancy))) - 1.0; } double Rule::calc_custom_binary(Team &left, Team &right, double *weight, double *currentWinExpectancy) { return 1.0 / (1.0 + std::exp((right.scores["Custom"] - left.scores["Custom"]) / customNormalizationConstant)); } void Rule::generateExpectancyMatrix(double (*fun)(Team&, Team&)) { assert(probabilityLookupMatrix.empty()); size_t teamCount = Simulation::singleton->teams.size(); probabilityLookupMatrix.resize(teamCount); for (size_t i = 0; i < teamCount; ++i) probabilityLookupMatrix[i].resize(teamCount); for (Team &left : Simulation::singleton->teams) { for (Team &right : Simulation::singleton->teams) { double prob_left = fun(left, right); double prob_right = fun(right, left); probabilityLookupMatrix[left.index][right.index] = prob_left; probabilityLookupMatrix[right.index][left.index] = prob_right; } } std::cerr << "Matrix is go\nI1\tI2\tP\t" << std::endl; for (size_t i = 0; i < teamCount; ++i) std::cerr << Simulation::singleton->teams[i].id << "\t"; std::cerr << std::endl; for (size_t i = 0; i < teamCount; ++i) { for (size_t c = 0; c < teamCount; ++c) std::cerr << probabilityLookupMatrix[i][c] << "\t"; std::cerr << std::endl; } } double Rule::calculateSPIWinExpectancy(Team &left, Team &right) { const double &off1 = left.scores["SPI Off"]; const double &off2 = right.scores["SPI Off"]; const double &def1 = left.scores["SPI Def"]; const double &def2 = right.scores["SPI Def"]; const double combined_off = (off1 + def2) / 2.0; const double combined_def = (def1 + off2) / 2.0; std::function<int(int)> factorial = [&](int n) { return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; }; auto poisson_probability = [&](double lambda, int times) { return std::exp(-lambda) * std::pow(lambda, (double)times) / (double)factorial(times); }; double prob_off(0.0), prob_def(0.0); for (int i = 0; i < 20; ++i) { const double equal_prob_off = poisson_probability(combined_off, i); const double equal_prob_def = poisson_probability(combined_def, i); double less_prob_off(0.0), less_prob_def(0.0); for (int c = 0; c < i; ++c) { less_prob_off += poisson_probability(combined_off, c); less_prob_def += poisson_probability(combined_def, c); } prob_off += equal_prob_off * less_prob_def; prob_def += equal_prob_def * less_prob_off; } return (prob_off / (prob_off + prob_def)); } } // namespace sim<|endoftext|>
<commit_before>#include "bwbot.h" int main() { BWBOT bwbot; bwbot.init('t'); bwbot.testinit(); bwbot.run(); bwbot.testprint(); return 0; } void BWBOT::run() { int i=0; while(!buildOrder.atEnd()&&i<1000) { update(); i++; } } void BWBOT::update() { ActiveUnit currentUnit = buildHandler.update(); Frame currentFrame = resourceHandler.update(currentUnit); if(currentUnit.action == ActionName::Next_Frame) if(tryToBuild(buildOrder.getUnit())) buildOrder.nextUnit(); if(currentUnit.timer != -1 && currentUnit.action != ActionName::Next_Frame) { currentFrame.miners = buildHandler.getMineralMinerCount(); currentFrame.gasminers = buildHandler.getGasMinerCount(); output.push_back(currentFrame); } } void BWBOT::testinit() { buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); //buildOrder.push_back(UnitName::Terran_SCV); //buildOrder.push_back(UnitName::Terran_SCV); //buildOrder.push_back(UnitName::Terran_Supply_Depot); //buildOrder.push_back(UnitName::Terran_SCV); //buildOrder.push_back(UnitName::Terran_SCV); } void BWBOT::testprint() { for(int i=0; i<(int)output.size(); i++) { Frame f = output[i]; printf("%6d %3d %3d ", f.frame, f.minerals, f.gas); printf("%3d/%3d ", f.supply, f.supplymax); printf("%2d %2d ", f.miners, f.gasminers); string uname = "NULL"; if(f.unit != UnitName::UNIT_NULL) uname = unitData.getUnitFromId(f.unit).name; printf("%2d %s\n", f.action, uname.c_str()); } } void BWBOT::init(char race) { clear(); if(race=='t') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Terran_SCV); buildHandler.spawn(UnitName::Terran_Command_Center); } if(race=='p') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Protoss_Probe); buildHandler.spawn(UnitName::Protoss_Nexus); } if(race=='z') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Zerg_Drone); buildHandler.spawn(UnitName::Zerg_Hatchery); buildHandler.spawn(UnitName::Zerg_Overlord); } } bool BWBOT::tryToBuild(UnitName unitname) { if(resourceHandler.canBuild(unitname)) { if(buildHandler.canBuild(unitname)) { buildHandler.build(unitname); return true; } } return false; } void BWBOT::clear() { buildHandler.clear(); buildOrder.clear(); resourceHandler.clear(); output.clear(); } <commit_msg>more working... larva still has issues, need to figure out how to pass times as well (maybe just fully update frame every time)<commit_after>#include "bwbot.h" int main() { BWBOT bwbot; bwbot.init('t'); bwbot.testinit(); bwbot.run(); bwbot.testprint(); return 0; } void BWBOT::run() { int i=0; while(!buildOrder.atEnd()&&i<10000) { update(); i++; } } void BWBOT::update() { ActiveUnit currentUnit = buildHandler.update(); Frame currentFrame = resourceHandler.update(currentUnit); if(currentUnit.action == ActionName::Next_Frame) if(tryToBuild(buildOrder.getUnit())) buildOrder.nextUnit(); if(currentUnit.action != ActionName::Next_Frame) { currentFrame.miners = buildHandler.getMineralMinerCount(); currentFrame.gasminers = buildHandler.getGasMinerCount(); output.push_back(currentFrame); } } void BWBOT::testinit() { buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_Supply_Depot); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_Barracks); buildOrder.push_back(UnitName::Terran_SCV); buildOrder.push_back(UnitName::Terran_Refinery); buildOrder.push_back(UnitName::Terran_Command_Center); } void BWBOT::testprint() { for(int i=0; i<(int)output.size(); i++) { Frame f = output[i]; printf("%6d %3d %3d ", f.frame, f.minerals, f.gas); printf("%3d/%3d ", f.supply, f.supplymax); printf("%2d %2d ", f.miners, f.gasminers); string uname = "NULL"; if(f.unit != UnitName::UNIT_NULL) uname = unitData.getUnitFromId(f.unit).name; printf("%2d %s\n", f.action, uname.c_str()); } } void BWBOT::init(char race) { clear(); if(race=='t') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Terran_SCV); buildHandler.spawn(UnitName::Terran_Command_Center); } if(race=='p') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Protoss_Probe); buildHandler.spawn(UnitName::Protoss_Nexus); } if(race=='z') { for(int i=0; i<4; i++) buildHandler.spawn(UnitName::Zerg_Drone); buildHandler.spawn(UnitName::Zerg_Hatchery); buildHandler.spawn(UnitName::Zerg_Overlord); } } bool BWBOT::tryToBuild(UnitName unitname) { if(resourceHandler.canBuild(unitname)) { if(buildHandler.canBuild(unitname)) { buildHandler.build(unitname); ActiveUnit abcarg(unitname, ActionName::Start_Build, 150); output.push_back(resourceHandler.update(abcarg)); return true; } } return false; } void BWBOT::clear() { buildHandler.clear(); buildOrder.clear(); resourceHandler.clear(); output.clear(); } <|endoftext|>
<commit_before>#include "Session.hh" #include "../net/HttpConnection.hh" #include "../net/HttpRequest.hh" #include <tr064/trace.hh> #include "../Tr064Exception.hh" #include <pugixml/pugixml.hpp> #include <sstream> #include <iostream> using namespace tr064::soap; //------------------------------------------------------------------------------ pugi::xml_node Session::execute_action( const Service::Ptr& service, const ServiceAction::Ptr& action) { LOG_TRACE("Going to execute Service: " + service->name() + " with action: " + action->name()); HttpConnection http_conn(_host, _port); pugi::xml_document doc; // iterate as long as it is not authenticated do { // reset xml docuemnt. doc.reset(); auto body_str = get_body(service, action); std::stringstream ss; //ss << headers //<< body; std::stringbuf headers_buf; std::ostream headers(&headers_buf); auto header_str = get_headers(service, action, body_str.size()+4); headers << header_str; std::stringbuf body_buf; std::ostream body(&body_buf); body << body_str; LOG_DEBUG("Current request: " << std::endl << header_str << body_str); HttpRequest req(headers, body); auto response = http_conn.sync(&req); //return ""; std::ostringstream r_oss; r_oss << (response->body()); std::string r_s = r_oss.str(); doc.load(r_s.c_str()); // used for debug std::stringstream d_ss; doc.save(d_ss); LOG_DEBUG(d_ss.str()); const auto& envelope_node = doc.child("s:Envelope"); if ( envelope_node.empty() ) { throw tr064::Tr064Exception( "Received response does not contain an envelope_node, " "unable to proceed, received: \n" + r_s); } _auth.handle_auth_response(envelope_node); delete response; } while ( !_auth.is_authenticated() ); // the xml doc should be filled at this point auto body_node = doc.child("s:Envelope").child("s:Body"); if ( body_node.empty() ) { std::cerr << "Received body node is empty." << std::endl; } return body_node; } //------------------------------------------------------------------------------ std::string Session::get_headers( const Service::Ptr& service, const ServiceAction::Ptr& action, const size_t body_length) { std::stringstream ss; ss << "POST " << service->control_url() << " HTTP/1.1\r\n" << "HOST: " << _host << "\r\n" << "CONTENT-LENGTH: " << body_length << "\r\n" << "CONTENT-TYPE: text/xml; charset=\"utf-8\"" << "\r\n" << "SOAPACTION: \"" << service->type() << "#" << action->name() << "\"" << "\r\n" << "CONNECTION: close\r\n" << "USER-AGENT: AVM UPnP/1.0 Client 1.0 - tr064 lib" << "\r\n\r\n"; return ss.str(); } //------------------------------------------------------------------------------ std::string Session::get_body( const Service::Ptr& service, const ServiceAction::Ptr& action) { std::stringstream ss; ss << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl << "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" << std::endl; if (!_no_auth) { ss << " <s:Header>" << std::endl << _auth.get_auth_header_for_request() << " </s:Header>" << std::endl; } ss << " <s:Body>" << std::endl << " <u:" << action->name() << " xmlns:u=\"" << service->type() << "\">" << std::endl; for ( const auto& in_arg : action->args() ) { // skip out args if ( in_arg->direction() == ServiceActionArg::OUT ) continue; // skip empty in args if ( in_arg->value().empty() ) continue; ss << " <" << in_arg->name() << ">" << in_arg->value() << " </" << in_arg->name() << ">" << std::endl; } ss << " </u:" << action->name() << ">" << std::endl << " </s:Body>" << std::endl << "</s:Envelope>" << std::endl; return ss.str(); } <commit_msg>Handle no_auth on HttpRepsonses<commit_after>#include "Session.hh" #include "../net/HttpConnection.hh" #include "../net/HttpRequest.hh" #include <tr064/trace.hh> #include "../Tr064Exception.hh" #include <pugixml/pugixml.hpp> #include <sstream> #include <iostream> using namespace tr064::soap; //------------------------------------------------------------------------------ pugi::xml_node Session::execute_action( const Service::Ptr& service, const ServiceAction::Ptr& action) { LOG_TRACE("Going to execute Service: " + service->name() + " with action: " + action->name()); HttpConnection http_conn(_host, _port); pugi::xml_document doc; // iterate as long as it is not authenticated do { // reset xml docuemnt. doc.reset(); auto body_str = get_body(service, action); std::stringstream ss; //ss << headers //<< body; std::stringbuf headers_buf; std::ostream headers(&headers_buf); auto header_str = get_headers(service, action, body_str.size()+4); headers << header_str; std::stringbuf body_buf; std::ostream body(&body_buf); body << body_str; LOG_DEBUG("Current request: " << std::endl << header_str << body_str); HttpRequest req(headers, body); auto response = http_conn.sync(&req); //return ""; std::ostringstream r_oss; r_oss << (response->body()); std::string r_s = r_oss.str(); doc.load(r_s.c_str()); // used for debug std::stringstream d_ss; doc.save(d_ss); LOG_DEBUG(d_ss.str()); const auto& envelope_node = doc.child("s:Envelope"); if ( envelope_node.empty() ) { throw tr064::Tr064Exception( "Received response does not contain an envelope_node, " "unable to proceed, received: \n" + r_s); } if ( !_no_auth ) _auth.handle_auth_response(envelope_node); delete response; } while ( !_auth.is_authenticated() && !_no_auth ); // the xml doc should be filled at this point auto body_node = doc.child("s:Envelope").child("s:Body"); if ( body_node.empty() ) { std::cerr << "Received body node is empty." << std::endl; } return body_node; } //------------------------------------------------------------------------------ std::string Session::get_headers( const Service::Ptr& service, const ServiceAction::Ptr& action, const size_t body_length) { std::stringstream ss; ss << "POST " << service->control_url() << " HTTP/1.1\r\n" << "HOST: " << _host << "\r\n" << "CONTENT-LENGTH: " << body_length << "\r\n" << "CONTENT-TYPE: text/xml; charset=\"utf-8\"" << "\r\n" << "SOAPACTION: \"" << service->type() << "#" << action->name() << "\"" << "\r\n" << "CONNECTION: close\r\n" << "USER-AGENT: AVM UPnP/1.0 Client 1.0 - tr064 lib" << "\r\n\r\n"; return ss.str(); } //------------------------------------------------------------------------------ std::string Session::get_body( const Service::Ptr& service, const ServiceAction::Ptr& action) { std::stringstream ss; ss << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl << "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" << std::endl; if (!_no_auth) { ss << " <s:Header>" << std::endl << _auth.get_auth_header_for_request() << " </s:Header>" << std::endl; } ss << " <s:Body>" << std::endl << " <u:" << action->name() << " xmlns:u=\"" << service->type() << "\">" << std::endl; for ( const auto& in_arg : action->args() ) { // skip out args if ( in_arg->direction() == ServiceActionArg::OUT ) continue; // skip empty in args if ( in_arg->value().empty() ) continue; ss << " <" << in_arg->name() << ">" << in_arg->value() << " </" << in_arg->name() << ">" << std::endl; } ss << " </u:" << action->name() << ">" << std::endl << " </s:Body>" << std::endl << "</s:Envelope>" << std::endl; return ss.str(); } <|endoftext|>
<commit_before>#ifndef _INCLUDED_DS_TEXTDS_HPP #define _INCLUDED_DS_TEXTDS_HPP #include <sdsl/int_vector.hpp> #include <tudocomp/ds/ITextDSProvider.hpp> #include <tudocomp/ds/SuffixArray.hpp> #include <tudocomp/ds/InverseSuffixArray.hpp> #include <tudocomp/ds/PhiArray.hpp> #include <tudocomp/ds/LCPArray.hpp> #include <tudocomp/io.h> namespace tudocomp { using io::InputView; /// Manages text related data structures. class TextDS : public ITextDSProvider { private: size_t m_size; const uint8_t* m_text; std::shared_ptr<SuffixArray> m_sa; std::shared_ptr<InverseSuffixArray> m_isa; std::shared_ptr<PhiArray> m_phi; std::shared_ptr<LCPArray> m_lcp; public: inline TextDS(const InputView& input) : m_size(input.size()), m_text((const uint8_t*)input.data()) { } /// Requires the Suffix Array to be constructed if not already present. virtual inline const SuffixArray& require_sa() override { if(!m_sa) { m_sa = std::shared_ptr<SuffixArray>(new SuffixArray()); m_sa->construct(*this); } return *m_sa; } /// Requires the Phi Array to be constructed if not already present. virtual inline const PhiArray& require_phi() override { if(!m_phi) { m_phi = std::shared_ptr<PhiArray>(new PhiArray()); m_phi->construct(*this); } return *m_phi; } /// Requires the Inverse Suffix Array to be constructed if not already present. virtual inline const InverseSuffixArray& require_isa() override { if(!m_isa) { m_isa = std::shared_ptr<InverseSuffixArray>(new InverseSuffixArray()); m_isa->construct(*this); } return *m_isa; } /// Requires the LCP Array to be constructed if not already present. virtual inline const LCPArray& require_lcp() override { if(!m_lcp) { m_lcp = std::shared_ptr<LCPArray>(new LCPArray()); m_lcp->construct(*this); } return *m_lcp; } virtual inline uint8_t operator[](size_t i) const override { return m_text[i]; } virtual inline const uint8_t* text() const override { return m_text; } virtual inline size_t size() const override { return m_size; } }; } #endif <commit_msg>Allow release of unneeded data structures<commit_after>#ifndef _INCLUDED_DS_TEXTDS_HPP #define _INCLUDED_DS_TEXTDS_HPP #include <sdsl/int_vector.hpp> #include <tudocomp/ds/ITextDSProvider.hpp> #include <tudocomp/ds/SuffixArray.hpp> #include <tudocomp/ds/InverseSuffixArray.hpp> #include <tudocomp/ds/PhiArray.hpp> #include <tudocomp/ds/LCPArray.hpp> #include <tudocomp/io.h> namespace tudocomp { using io::InputView; /// Manages text related data structures. class TextDS : public ITextDSProvider { public: static const uint64_t SA = 0x01; static const uint64_t ISA = 0x02; static const uint64_t Phi = 0x04; static const uint64_t LCP = 0x08; private: size_t m_size; const uint8_t* m_text; std::shared_ptr<SuffixArray> m_sa; std::shared_ptr<InverseSuffixArray> m_isa; std::shared_ptr<PhiArray> m_phi; std::shared_ptr<LCPArray> m_lcp; public: inline TextDS(const InputView& input) : m_size(input.size()), m_text((const uint8_t*)input.data()) { } /// Constructs the required data structures as denoted by the given flags /// and releases all unwanted ones in a second step. inline void require(uint64_t flags) { //Step 1: construct if(flags & SA) require_sa(); if(flags & ISA) require_isa(); if(flags & Phi) require_phi(); if(flags & LCP) require_lcp(); //Step 2: release unwanted (may have been constructed beforehand) if(!(flags & SA)) release_sa(); if(!(flags & ISA)) release_isa(); if(!(flags & Phi)) release_phi(); if(!(flags & LCP)) release_lcp(); } /// Requires the Suffix Array to be constructed if not already present. virtual inline const SuffixArray& require_sa() override { if(!m_sa) { m_sa = std::shared_ptr<SuffixArray>(new SuffixArray()); m_sa->construct(*this); } return *m_sa; } /// Requires the Phi Array to be constructed if not already present. virtual inline const PhiArray& require_phi() override { if(!m_phi) { m_phi = std::shared_ptr<PhiArray>(new PhiArray()); m_phi->construct(*this); } return *m_phi; } /// Requires the Inverse Suffix Array to be constructed if not already present. virtual inline const InverseSuffixArray& require_isa() override { if(!m_isa) { m_isa = std::shared_ptr<InverseSuffixArray>(new InverseSuffixArray()); m_isa->construct(*this); } return *m_isa; } /// Requires the LCP Array to be constructed if not already present. virtual inline const LCPArray& require_lcp() override { if(!m_lcp) { m_lcp = std::shared_ptr<LCPArray>(new LCPArray()); m_lcp->construct(*this); } return *m_lcp; } /// Releases the suffix array if present. inline void release_sa() { m_sa.reset(); } /// Releases the inverse suffix array array if present. inline void release_isa() { m_isa.reset(); } /// Releases the Phi array if present. inline void release_phi() { m_phi.reset(); } /// Releases the LCP array if present. inline void release_lcp() { m_lcp.reset(); } /// Accesses the input text at position i. virtual inline uint8_t operator[](size_t i) const override { return m_text[i]; } /// Provides access to the input text. virtual inline const uint8_t* text() const override { return m_text; } /// Returns the size of the input text. virtual inline size_t size() const override { return m_size; } }; } #endif <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cache.hxx" #include "event/Loop.hxx" #include "util/djbhash.h" #include <assert.h> #include <string.h> inline size_t CacheItem::KeyHasher(const char *key) noexcept { assert(key != nullptr); return djb_hash_string(key); } bool CacheItem::KeyValueEqual(const char *a, const CacheItem &b) noexcept { assert(a != nullptr); return strcmp(a, b.key) == 0; } void CacheItem::Release() noexcept { if (lock == 0) Destroy(); else /* this item is locked - postpone the Destroy() call */ removed = true; } Cache::Cache(EventLoop &event_loop, unsigned hashtable_capacity, size_t _max_size) noexcept :max_size(_max_size), buckets(new ItemSet::bucket_type[hashtable_capacity]), items(ItemSet::bucket_traits(buckets.get(), hashtable_capacity)), cleanup_timer(event_loop, std::chrono::minutes(1), BIND_THIS_METHOD(ExpireCallback)) {} Cache::~Cache() noexcept { items.clear_and_dispose([this](CacheItem *item){ assert(item->lock == 0); assert(size >= item->size); size -= item->size; #ifndef NDEBUG sorted_items.erase(sorted_items.iterator_to(*item)); #endif item->Destroy(); }); assert(size == 0); assert(sorted_items.empty()); } std::chrono::steady_clock::time_point Cache::SteadyNow() const noexcept { return GetEventLoop().SteadyNow(); } std::chrono::system_clock::time_point Cache::SystemNow() const noexcept { return GetEventLoop().SystemNow(); } void Cache::ItemRemoved(CacheItem *item) noexcept { assert(item != nullptr); assert(item->size > 0); assert(item->lock > 0 || !item->removed); assert(size >= item->size); sorted_items.erase(sorted_items.iterator_to(*item)); size -= item->size; item->Release(); if (size == 0) cleanup_timer.Disable(); } void Cache::Flush() noexcept { items.clear_and_dispose(Cache::ItemRemover(*this)); } void Cache::RefreshItem(CacheItem &item, std::chrono::steady_clock::time_point now) noexcept { item.last_accessed = now; /* move to the front of the linked list */ sorted_items.erase(sorted_items.iterator_to(item)); sorted_items.push_back(item); } void Cache::RemoveItem(CacheItem &item) noexcept { assert(!item.removed); items.erase_and_dispose(items.iterator_to(item), ItemRemover(*this)); } CacheItem * Cache::Get(const char *key) noexcept { auto i = items.find(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); if (i == items.end()) return nullptr; CacheItem *item = &*i; const auto now = SteadyNow(); if (!item->Validate(now)) { RemoveItem(*item); return nullptr; } RefreshItem(*item, now); return item; } CacheItem * Cache::GetMatch(const char *key, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { const auto now = SteadyNow(); const auto r = items.equal_range(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); for (auto i = r.first, end = r.second; i != end;) { CacheItem *item = &*i++; if (!item->Validate(now)) { /* expired cache item: delete it, and re-start the search */ RemoveItem(*item); } else if (match(item, ctx)) { /* this one matches: return it to the caller */ RefreshItem(*item, now); return item; } }; return nullptr; } void Cache::DestroyOldestItem() noexcept { if (sorted_items.empty()) return; CacheItem &item = sorted_items.front(); RemoveItem(item); } bool Cache::NeedRoom(size_t _size) noexcept { if (_size > max_size) return false; while (true) { if (size + _size <= max_size) return true; DestroyOldestItem(); } } bool Cache::Add(const char *key, CacheItem &item) noexcept { /* XXX size constraints */ if (!NeedRoom(item.size)) { item.Destroy(); return false; } item.key = key; items.insert(item); sorted_items.push_back(item); size += item.size; item.last_accessed = SteadyNow(); cleanup_timer.Enable(); return true; } bool Cache::Put(const char *key, CacheItem &item) noexcept { /* XXX size constraints */ assert(item.size > 0); assert(item.lock == 0); assert(!item.removed); if (!NeedRoom(item.size)) { item.Destroy(); return false; } item.key = key; auto i = items.find(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); if (i != items.end()) RemoveItem(*i); size += item.size; item.last_accessed = SteadyNow(); items.insert(item); sorted_items.push_back(item); cleanup_timer.Enable(); return true; } bool Cache::PutMatch(const char *key, CacheItem &item, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { auto *old = GetMatch(key, match, ctx); assert(item.size > 0); assert(item.lock == 0); assert(!item.removed); if (old != nullptr) RemoveItem(*old); return Add(key, item); } void Cache::Remove(const char *key) noexcept { items.erase_and_dispose(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual, [this](CacheItem *item){ ItemRemoved(item); }); } void Cache::RemoveMatch(const char *key, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { const auto r = items.equal_range(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); for (auto i = r.first, end = r.second; i != end;) { CacheItem &item = *i++; if (match(&item, ctx)) RemoveItem(item); } } void Cache::Remove(CacheItem &item) noexcept { if (item.removed) { /* item has already been removed by somebody else */ assert(item.lock > 0); return; } RemoveItem(item); } unsigned Cache::RemoveAllMatch(bool (*match)(const CacheItem *, void *), void *ctx) noexcept { unsigned removed = 0; for (auto i = sorted_items.begin(), end = sorted_items.end(); i != end;) { CacheItem &item = *i++; if (!match(&item, ctx)) continue; items.erase(items.iterator_to(item)); ItemRemoved(&item); ++removed; } return removed; } static std::chrono::steady_clock::time_point ToSteady(std::chrono::steady_clock::time_point steady_now, std::chrono::system_clock::time_point system_now, std::chrono::system_clock::time_point t) noexcept { return t > system_now ? steady_now + (t - system_now) : std::chrono::steady_clock::time_point(); } CacheItem::CacheItem(std::chrono::steady_clock::time_point now, std::chrono::system_clock::time_point system_now, std::chrono::system_clock::time_point _expires, size_t _size) noexcept :CacheItem(ToSteady(now, system_now, _expires), _size) { } CacheItem::CacheItem(std::chrono::steady_clock::time_point now, std::chrono::seconds max_age, size_t _size) noexcept :CacheItem(now + max_age, _size) { } void CacheItem::Unlock() noexcept { assert(lock > 0); if (--lock == 0 && removed) /* postponed destroy */ Destroy(); } /** clean up expired cache items every 60 seconds */ bool Cache::ExpireCallback() noexcept { const auto now = SteadyNow(); for (auto i = sorted_items.begin(), end = sorted_items.end(); i != end;) { CacheItem &item = *i++; if (item.expires > now) /* not yet expired */ continue; RemoveItem(item); } return size > 0; } void Cache::EventAdd() noexcept { if (size > 0) cleanup_timer.Enable(); } void Cache::EventDel() noexcept { cleanup_timer.Disable(); } <commit_msg>cache: add `constexpr`<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cache.hxx" #include "event/Loop.hxx" #include "util/djbhash.h" #include <assert.h> #include <string.h> inline size_t CacheItem::KeyHasher(const char *key) noexcept { assert(key != nullptr); return djb_hash_string(key); } bool CacheItem::KeyValueEqual(const char *a, const CacheItem &b) noexcept { assert(a != nullptr); return strcmp(a, b.key) == 0; } void CacheItem::Release() noexcept { if (lock == 0) Destroy(); else /* this item is locked - postpone the Destroy() call */ removed = true; } Cache::Cache(EventLoop &event_loop, unsigned hashtable_capacity, size_t _max_size) noexcept :max_size(_max_size), buckets(new ItemSet::bucket_type[hashtable_capacity]), items(ItemSet::bucket_traits(buckets.get(), hashtable_capacity)), cleanup_timer(event_loop, std::chrono::minutes(1), BIND_THIS_METHOD(ExpireCallback)) {} Cache::~Cache() noexcept { items.clear_and_dispose([this](CacheItem *item){ assert(item->lock == 0); assert(size >= item->size); size -= item->size; #ifndef NDEBUG sorted_items.erase(sorted_items.iterator_to(*item)); #endif item->Destroy(); }); assert(size == 0); assert(sorted_items.empty()); } std::chrono::steady_clock::time_point Cache::SteadyNow() const noexcept { return GetEventLoop().SteadyNow(); } std::chrono::system_clock::time_point Cache::SystemNow() const noexcept { return GetEventLoop().SystemNow(); } void Cache::ItemRemoved(CacheItem *item) noexcept { assert(item != nullptr); assert(item->size > 0); assert(item->lock > 0 || !item->removed); assert(size >= item->size); sorted_items.erase(sorted_items.iterator_to(*item)); size -= item->size; item->Release(); if (size == 0) cleanup_timer.Disable(); } void Cache::Flush() noexcept { items.clear_and_dispose(Cache::ItemRemover(*this)); } void Cache::RefreshItem(CacheItem &item, std::chrono::steady_clock::time_point now) noexcept { item.last_accessed = now; /* move to the front of the linked list */ sorted_items.erase(sorted_items.iterator_to(item)); sorted_items.push_back(item); } void Cache::RemoveItem(CacheItem &item) noexcept { assert(!item.removed); items.erase_and_dispose(items.iterator_to(item), ItemRemover(*this)); } CacheItem * Cache::Get(const char *key) noexcept { auto i = items.find(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); if (i == items.end()) return nullptr; CacheItem *item = &*i; const auto now = SteadyNow(); if (!item->Validate(now)) { RemoveItem(*item); return nullptr; } RefreshItem(*item, now); return item; } CacheItem * Cache::GetMatch(const char *key, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { const auto now = SteadyNow(); const auto r = items.equal_range(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); for (auto i = r.first, end = r.second; i != end;) { CacheItem *item = &*i++; if (!item->Validate(now)) { /* expired cache item: delete it, and re-start the search */ RemoveItem(*item); } else if (match(item, ctx)) { /* this one matches: return it to the caller */ RefreshItem(*item, now); return item; } }; return nullptr; } void Cache::DestroyOldestItem() noexcept { if (sorted_items.empty()) return; CacheItem &item = sorted_items.front(); RemoveItem(item); } bool Cache::NeedRoom(size_t _size) noexcept { if (_size > max_size) return false; while (true) { if (size + _size <= max_size) return true; DestroyOldestItem(); } } bool Cache::Add(const char *key, CacheItem &item) noexcept { /* XXX size constraints */ if (!NeedRoom(item.size)) { item.Destroy(); return false; } item.key = key; items.insert(item); sorted_items.push_back(item); size += item.size; item.last_accessed = SteadyNow(); cleanup_timer.Enable(); return true; } bool Cache::Put(const char *key, CacheItem &item) noexcept { /* XXX size constraints */ assert(item.size > 0); assert(item.lock == 0); assert(!item.removed); if (!NeedRoom(item.size)) { item.Destroy(); return false; } item.key = key; auto i = items.find(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); if (i != items.end()) RemoveItem(*i); size += item.size; item.last_accessed = SteadyNow(); items.insert(item); sorted_items.push_back(item); cleanup_timer.Enable(); return true; } bool Cache::PutMatch(const char *key, CacheItem &item, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { auto *old = GetMatch(key, match, ctx); assert(item.size > 0); assert(item.lock == 0); assert(!item.removed); if (old != nullptr) RemoveItem(*old); return Add(key, item); } void Cache::Remove(const char *key) noexcept { items.erase_and_dispose(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual, [this](CacheItem *item){ ItemRemoved(item); }); } void Cache::RemoveMatch(const char *key, bool (*match)(const CacheItem *, void *), void *ctx) noexcept { const auto r = items.equal_range(key, CacheItem::KeyHasher, CacheItem::KeyValueEqual); for (auto i = r.first, end = r.second; i != end;) { CacheItem &item = *i++; if (match(&item, ctx)) RemoveItem(item); } } void Cache::Remove(CacheItem &item) noexcept { if (item.removed) { /* item has already been removed by somebody else */ assert(item.lock > 0); return; } RemoveItem(item); } unsigned Cache::RemoveAllMatch(bool (*match)(const CacheItem *, void *), void *ctx) noexcept { unsigned removed = 0; for (auto i = sorted_items.begin(), end = sorted_items.end(); i != end;) { CacheItem &item = *i++; if (!match(&item, ctx)) continue; items.erase(items.iterator_to(item)); ItemRemoved(&item); ++removed; } return removed; } static constexpr std::chrono::steady_clock::time_point ToSteady(std::chrono::steady_clock::time_point steady_now, std::chrono::system_clock::time_point system_now, std::chrono::system_clock::time_point t) noexcept { return t > system_now ? steady_now + (t - system_now) : std::chrono::steady_clock::time_point(); } CacheItem::CacheItem(std::chrono::steady_clock::time_point now, std::chrono::system_clock::time_point system_now, std::chrono::system_clock::time_point _expires, size_t _size) noexcept :CacheItem(ToSteady(now, system_now, _expires), _size) { } CacheItem::CacheItem(std::chrono::steady_clock::time_point now, std::chrono::seconds max_age, size_t _size) noexcept :CacheItem(now + max_age, _size) { } void CacheItem::Unlock() noexcept { assert(lock > 0); if (--lock == 0 && removed) /* postponed destroy */ Destroy(); } /** clean up expired cache items every 60 seconds */ bool Cache::ExpireCallback() noexcept { const auto now = SteadyNow(); for (auto i = sorted_items.begin(), end = sorted_items.end(); i != end;) { CacheItem &item = *i++; if (item.expires > now) /* not yet expired */ continue; RemoveItem(item); } return size > 0; } void Cache::EventAdd() noexcept { if (size > 0) cleanup_timer.Enable(); } void Cache::EventDel() noexcept { cleanup_timer.Disable(); } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "utils.h" #include <e32std.h> QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; _LIT(PanicCategory, "Phonon::MMF"); void MMF::Utils::panic(PanicCode code) { User::Panic(PanicCategory, code); } static const TInt KMimePrefixLength = 6; // either "audio/" or "video/" _LIT(KMimePrefixAudio, "audio/"); _LIT(KMimePrefixVideo, "video/"); MMF::MediaType MMF::Utils::mimeTypeToMediaType(const TDesC& mimeType) { MediaType result = MediaTypeUnknown; if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixAudio) == 0) { result = MediaTypeAudio; } else if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixVideo) == 0) { result = MediaTypeVideo; } return result; } #ifdef _DEBUG #include <hal.h> #include <hal_data.h> #include <gdi.h> #include <eikenv.h> struct TScreenInfo { int width; int height; int bpp; const char* address; int initialOffset; int lineOffset; TDisplayMode displayMode; }; void getScreenInfoL(TScreenInfo& info) { info.displayMode = CEikonEnv::Static()->ScreenDevice()->DisplayMode(); // Then we must set these as the input parameter info.width = info.displayMode; info.height = info.displayMode; info.initialOffset = info.displayMode; info.lineOffset = info.displayMode; info.bpp = info.displayMode; User::LeaveIfError( HAL::Get(HALData::EDisplayXPixels, info.width) ); User::LeaveIfError( HAL::Get(HALData::EDisplayYPixels, info.width) ); int address; User::LeaveIfError( HAL::Get(HALData::EDisplayMemoryAddress, address) ); info.address = reinterpret_cast<const char*>(address); User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetToFirstPixel, info.initialOffset) ); User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetBetweenLines, info.lineOffset) ); User::LeaveIfError( HAL::Get(HALData::EDisplayBitsPerPixel, info.bpp) ); } QColor MMF::Utils::getScreenPixel(const QPoint& pos) { TScreenInfo info; TRAPD(err, getScreenInfoL(info)); QColor pixel; if(err == KErrNone and pos.x() < info.width and pos.y() < info.height) { const int bytesPerPixel = info.bpp / 8; Q_ASSERT(bytesPerPixel >= 3); const int stride = (info.width * bytesPerPixel) + info.lineOffset; const char* ptr = info.address + info.initialOffset + pos.y() * stride + pos.x() * bytesPerPixel; // BGRA pixel.setBlue(*ptr++); pixel.setGreen(*ptr++); pixel.setRed(*ptr++); if(bytesPerPixel == 4) pixel.setAlpha(*ptr++); } return pixel; } // Debugging: for debugging video visibility void MMF::Utils::dumpScreenPixelSample() { for(int i=0; i<20; ++i) { const QPoint pos(i*10, i*10); const QColor pixel = Utils::getScreenPixel(pos); RDebug::Printf( "Phonon::MMF::Utils::dumpScreenPixelSample %d %d = %d %d %d %d", pos.x(), pos.y(), pixel.red(), pixel.green(), pixel.blue(), pixel.alpha() ); } } #endif // _DEBUG QT_END_NAMESPACE <commit_msg>Make local function static.<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "utils.h" #include <e32std.h> QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; _LIT(PanicCategory, "Phonon::MMF"); void MMF::Utils::panic(PanicCode code) { User::Panic(PanicCategory, code); } static const TInt KMimePrefixLength = 6; // either "audio/" or "video/" _LIT(KMimePrefixAudio, "audio/"); _LIT(KMimePrefixVideo, "video/"); MMF::MediaType MMF::Utils::mimeTypeToMediaType(const TDesC& mimeType) { MediaType result = MediaTypeUnknown; if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixAudio) == 0) { result = MediaTypeAudio; } else if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixVideo) == 0) { result = MediaTypeVideo; } return result; } #ifdef _DEBUG #include <hal.h> #include <hal_data.h> #include <gdi.h> #include <eikenv.h> struct TScreenInfo { int width; int height; int bpp; const char* address; int initialOffset; int lineOffset; TDisplayMode displayMode; }; static void getScreenInfoL(TScreenInfo& info) { info.displayMode = CEikonEnv::Static()->ScreenDevice()->DisplayMode(); // Then we must set these as the input parameter info.width = info.displayMode; info.height = info.displayMode; info.initialOffset = info.displayMode; info.lineOffset = info.displayMode; info.bpp = info.displayMode; User::LeaveIfError( HAL::Get(HALData::EDisplayXPixels, info.width) ); User::LeaveIfError( HAL::Get(HALData::EDisplayYPixels, info.width) ); int address; User::LeaveIfError( HAL::Get(HALData::EDisplayMemoryAddress, address) ); info.address = reinterpret_cast<const char*>(address); User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetToFirstPixel, info.initialOffset) ); User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetBetweenLines, info.lineOffset) ); User::LeaveIfError( HAL::Get(HALData::EDisplayBitsPerPixel, info.bpp) ); } QColor MMF::Utils::getScreenPixel(const QPoint& pos) { TScreenInfo info; TRAPD(err, getScreenInfoL(info)); QColor pixel; if(err == KErrNone and pos.x() < info.width and pos.y() < info.height) { const int bytesPerPixel = info.bpp / 8; Q_ASSERT(bytesPerPixel >= 3); const int stride = (info.width * bytesPerPixel) + info.lineOffset; const char* ptr = info.address + info.initialOffset + pos.y() * stride + pos.x() * bytesPerPixel; // BGRA pixel.setBlue(*ptr++); pixel.setGreen(*ptr++); pixel.setRed(*ptr++); if(bytesPerPixel == 4) pixel.setAlpha(*ptr++); } return pixel; } // Debugging: for debugging video visibility void MMF::Utils::dumpScreenPixelSample() { for(int i=0; i<20; ++i) { const QPoint pos(i*10, i*10); const QColor pixel = Utils::getScreenPixel(pos); RDebug::Printf( "Phonon::MMF::Utils::dumpScreenPixelSample %d %d = %d %d %d %d", pos.x(), pos.y(), pixel.red(), pixel.green(), pixel.blue(), pixel.alpha() ); } } #endif // _DEBUG QT_END_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2011 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include <algorithm> class CPerform : public CModule { void Add(const CString& sCommand) { CString sPerf = sCommand.Token(1, true); if (sPerf.empty()) { PutModule("Usage: add <command>"); return; } m_vPerform.push_back(ParsePerform(sPerf)); PutModule("Added!"); Save(); } void Del(const CString& sCommand) { u_int iNum = sCommand.Token(1, true).ToUInt(); if (iNum > m_vPerform.size() || iNum <= 0) { PutModule("Illegal # Requested"); return; } else { m_vPerform.erase(m_vPerform.begin() + iNum - 1); PutModule("Command Erased."); } Save(); } void List(const CString& sCommand) { CTable Table; unsigned int index = 1; CString sExpanded; Table.AddColumn("Id"); Table.AddColumn("Perform"); Table.AddColumn("Expanded"); for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, index++) { Table.AddRow(); Table.SetCell("Id", CString(index)); Table.SetCell("Perform", *it); sExpanded = GetUser()->ExpandString(*it); if (sExpanded != *it) { Table.SetCell("Expanded", sExpanded); } } if (PutModule(Table) == 0) { PutModule("No commands in your perform list."); } } void Execute(const CString& sCommand) { OnIRCConnected(); PutModule("perform commands sent"); } void Swap(const CString& sCommand) { u_int iNumA = sCommand.Token(1).ToUInt(); u_int iNumB = sCommand.Token(2).ToUInt(); if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) { PutModule("Illegal # Requested"); } else { std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1)); PutModule("Commands Swapped."); Save(); } } public: MODCONSTRUCTOR(CPerform) { AddHelpCommand(); AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CPerform::Add), "<command>"); AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CPerform::Del), "<nr>"); AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CPerform::List)); AddCommand("Execute", static_cast<CModCommand::ModCmdFunc>(&CPerform::Execute)); AddCommand("Swap", static_cast<CModCommand::ModCmdFunc>(&CPerform::Swap), "<nr> <nr>"); } virtual ~CPerform() {} CString ParsePerform(const CString& sArg) const { CString sPerf = sArg; if (sPerf.Left(1) == "/") sPerf.LeftChomp(); if (sPerf.Token(0).Equals("MSG")) { sPerf = "PRIVMSG " + sPerf.Token(1, true); } if ((sPerf.Token(0).Equals("PRIVMSG") || sPerf.Token(0).Equals("NOTICE")) && sPerf.Token(2).Left(1) != ":") { sPerf = sPerf.Token(0) + " " + sPerf.Token(1) + " :" + sPerf.Token(2, true); } return sPerf; } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { GetNV("Perform").Split("\n", m_vPerform, false); return true; } virtual void OnIRCConnected() { for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { PutIRC(GetUser()->ExpandString(*it)); } } virtual CString GetWebMenuTitle() { return "Perform"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName != "index") { // only accept requests to /mods/perform/ return false; } if (WebSock.IsPost()) { VCString vsPerf; WebSock.GetRawParam("perform", true).Split("\n", vsPerf, false); m_vPerform.clear(); for (VCString::const_iterator it = vsPerf.begin(); it != vsPerf.end(); ++it) m_vPerform.push_back(ParsePerform(*it)); Save(); } for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { CTemplate& Row = Tmpl.AddRow("PerformLoop"); Row["Perform"] = *it; } return true; } private: void Save() { CString sBuffer = ""; for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { sBuffer += *it + "\n"; } SetNV("Perform", sBuffer); } VCString m_vPerform; }; template<> void TModInfo<CPerform>(CModInfo& Info) { Info.SetWikiPage("perform"); } MODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.") <commit_msg>Perform is now a network module, but could also be loaded as a user module if the user desires<commit_after>/* * Copyright (C) 2004-2011 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include <algorithm> class CPerform : public CModule { void Add(const CString& sCommand) { CString sPerf = sCommand.Token(1, true); if (sPerf.empty()) { PutModule("Usage: add <command>"); return; } m_vPerform.push_back(ParsePerform(sPerf)); PutModule("Added!"); Save(); } void Del(const CString& sCommand) { u_int iNum = sCommand.Token(1, true).ToUInt(); if (iNum > m_vPerform.size() || iNum <= 0) { PutModule("Illegal # Requested"); return; } else { m_vPerform.erase(m_vPerform.begin() + iNum - 1); PutModule("Command Erased."); } Save(); } void List(const CString& sCommand) { CTable Table; unsigned int index = 1; CString sExpanded; Table.AddColumn("Id"); Table.AddColumn("Perform"); Table.AddColumn("Expanded"); for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, index++) { Table.AddRow(); Table.SetCell("Id", CString(index)); Table.SetCell("Perform", *it); sExpanded = GetUser()->ExpandString(*it); if (sExpanded != *it) { Table.SetCell("Expanded", sExpanded); } } if (PutModule(Table) == 0) { PutModule("No commands in your perform list."); } } void Execute(const CString& sCommand) { OnIRCConnected(); PutModule("perform commands sent"); } void Swap(const CString& sCommand) { u_int iNumA = sCommand.Token(1).ToUInt(); u_int iNumB = sCommand.Token(2).ToUInt(); if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) { PutModule("Illegal # Requested"); } else { std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1)); PutModule("Commands Swapped."); Save(); } } public: MODCONSTRUCTOR(CPerform) { AddHelpCommand(); AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CPerform::Add), "<command>"); AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CPerform::Del), "<nr>"); AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CPerform::List)); AddCommand("Execute", static_cast<CModCommand::ModCmdFunc>(&CPerform::Execute)); AddCommand("Swap", static_cast<CModCommand::ModCmdFunc>(&CPerform::Swap), "<nr> <nr>"); } virtual ~CPerform() {} CString ParsePerform(const CString& sArg) const { CString sPerf = sArg; if (sPerf.Left(1) == "/") sPerf.LeftChomp(); if (sPerf.Token(0).Equals("MSG")) { sPerf = "PRIVMSG " + sPerf.Token(1, true); } if ((sPerf.Token(0).Equals("PRIVMSG") || sPerf.Token(0).Equals("NOTICE")) && sPerf.Token(2).Left(1) != ":") { sPerf = sPerf.Token(0) + " " + sPerf.Token(1) + " :" + sPerf.Token(2, true); } return sPerf; } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { GetNV("Perform").Split("\n", m_vPerform, false); return true; } virtual void OnIRCConnected() { for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { PutIRC(GetUser()->ExpandString(*it)); } } virtual CString GetWebMenuTitle() { return "Perform"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName != "index") { // only accept requests to /mods/perform/ return false; } if (WebSock.IsPost()) { VCString vsPerf; WebSock.GetRawParam("perform", true).Split("\n", vsPerf, false); m_vPerform.clear(); for (VCString::const_iterator it = vsPerf.begin(); it != vsPerf.end(); ++it) m_vPerform.push_back(ParsePerform(*it)); Save(); } for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { CTemplate& Row = Tmpl.AddRow("PerformLoop"); Row["Perform"] = *it; } return true; } private: void Save() { CString sBuffer = ""; for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { sBuffer += *it + "\n"; } SetNV("Perform", sBuffer); } VCString m_vPerform; }; template<> void TModInfo<CPerform>(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("perform"); } NETWORKMODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.") <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QDebug> #include "qsysteminfo.h" using namespace QtMobility; #define X(expr) qDebug() << #expr << "->" << (expr); struct symbol_t { const char *key; int val; }; int lookup(const symbol_t *stab, const char *key, int def) { for(;stab->key;++stab) { if(!strcmp(stab->key,key)) return stab->val; } return def; } const char *rlookup(const symbol_t *stab, int val, const char *def) { for(;stab->key; ++stab) { if(stab->val == val) return stab->key; } return def; } #define SYM(x) { #x, x } static const symbol_t Version_lut[] = { SYM(QSystemInfo::Os), SYM(QSystemInfo::QtCore), SYM(QSystemInfo::Firmware), SYM(QSystemInfo::QtMobility), {0,0} }; static const symbol_t Feature_lut[] = { SYM(QSystemInfo::BluetoothFeature), SYM(QSystemInfo::CameraFeature), SYM(QSystemInfo::FmradioFeature), SYM(QSystemInfo::IrFeature), SYM(QSystemInfo::LedFeature), SYM(QSystemInfo::MemcardFeature), SYM(QSystemInfo::UsbFeature), SYM(QSystemInfo::VibFeature), SYM(QSystemInfo::WlanFeature), SYM(QSystemInfo::SimFeature), SYM(QSystemInfo::LocationFeature), SYM(QSystemInfo::VideoOutFeature), SYM(QSystemInfo::HapticsFeature), SYM(QSystemInfo::FmTransmitterFeature), {0,0} }; static const symbol_t NetworkStatus_lut[] = { SYM(QSystemNetworkInfo::UndefinedStatus), SYM(QSystemNetworkInfo::NoNetworkAvailable), SYM(QSystemNetworkInfo::EmergencyOnly), SYM(QSystemNetworkInfo::Searching), SYM(QSystemNetworkInfo::Busy), SYM(QSystemNetworkInfo::Connected), SYM(QSystemNetworkInfo::HomeNetwork), SYM(QSystemNetworkInfo::Denied), SYM(QSystemNetworkInfo::Roaming), {0,0} }; static const symbol_t NetworkMode_lut[] = { SYM(QSystemNetworkInfo::UnknownMode), SYM(QSystemNetworkInfo::GsmMode), SYM(QSystemNetworkInfo::CdmaMode), SYM(QSystemNetworkInfo::WcdmaMode), SYM(QSystemNetworkInfo::WlanMode), SYM(QSystemNetworkInfo::EthernetMode), SYM(QSystemNetworkInfo::BluetoothMode), SYM(QSystemNetworkInfo::WimaxMode), SYM(QSystemNetworkInfo::GprsMode), SYM(QSystemNetworkInfo::EdgeMode), SYM(QSystemNetworkInfo::HspaMode), SYM(QSystemNetworkInfo::LteMode), {0,0} }; /* ------------------------------------------------------------------------- * * test_systeminfo * ------------------------------------------------------------------------- */ static void test_systeminfo(void) { QSystemInfo info; X(info.currentLanguage()); X(info.availableLanguages()); X(info.currentCountryCode()); X(info.version(QSystemInfo::Os)); X(info.version(QSystemInfo::QtCore)); X(info.version(QSystemInfo::Firmware)); X(info.version(QSystemInfo::QtMobility)); X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature)); X(info.hasFeatureSupported(QSystemInfo::CameraFeature)); X(info.hasFeatureSupported(QSystemInfo::FmradioFeature)); X(info.hasFeatureSupported(QSystemInfo::IrFeature)); X(info.hasFeatureSupported(QSystemInfo::LedFeature)); X(info.hasFeatureSupported(QSystemInfo::MemcardFeature)); X(info.hasFeatureSupported(QSystemInfo::UsbFeature)); X(info.hasFeatureSupported(QSystemInfo::VibFeature)); X(info.hasFeatureSupported(QSystemInfo::WlanFeature)); X(info.hasFeatureSupported(QSystemInfo::SimFeature)); X(info.hasFeatureSupported(QSystemInfo::LocationFeature)); X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature)); X(info.hasFeatureSupported(QSystemInfo::HapticsFeature)); X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature)); } /* ------------------------------------------------------------------------- * * test_systemdeviceinfo * ------------------------------------------------------------------------- */ static void test_systemdeviceinfo(void) { QSystemDeviceInfo deviceinfo; X(deviceinfo.batteryLevel()); X(deviceinfo.batteryStatus()); X(deviceinfo.currentBluetoothPowerState()); X(deviceinfo.currentPowerState()); X(deviceinfo.currentProfile()); X(deviceinfo.imei()); X(deviceinfo.imsi()); X(deviceinfo.inputMethodType()); X(deviceinfo.isDeviceLocked()); X(deviceinfo.isKeyboardFlipOpen()); X(deviceinfo.isWirelessKeyboardConnected()); X(deviceinfo.keyboardType()); X(deviceinfo.manufacturer()); X(deviceinfo.model()); X(deviceinfo.productName()); X(deviceinfo.simStatus()); X(deviceinfo.typeOfLock()); } /* ------------------------------------------------------------------------- * * test_systemdisplayinfo * ------------------------------------------------------------------------- */ static void test_systemdisplayinfo(void) { QSystemDisplayInfo displayinfo; for( int display = 0; display < 4; ++display ) { qDebug() << ""; qDebug() << "Display:" << display; int depth = displayinfo.colorDepth(display); qDebug() << " displayinfo.colorDepth() ->" << depth; int value = displayinfo.displayBrightness(display); qDebug() << " displayinfo.displayBrightness() ->" << value; QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display); qDebug() << " displayinfo.getOrientation() ->" << orientation; float contrast = displayinfo.contrast(display); qDebug() << " displayinfo.getContrast() ->" << contrast; int dpiWidth = displayinfo.getDPIWidth(display); qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth; int dpiHeight = displayinfo.getDPIHeight(display); qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight; int physicalHeight = displayinfo.physicalHeight(display); qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight; int physicalWidth = displayinfo.physicalWidth(display); qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth; } } /* ------------------------------------------------------------------------- * * test_systemstorageinfo * ------------------------------------------------------------------------- */ static const char *human_size(qlonglong n) { if(n == 0) return "0B"; static char buf[256]; char *pos = buf; char *end = buf + sizeof buf; int b = n & 1023; n >>= 10; int k = n & 1023; n >>= 10; int m = n & 1023; n >>= 10; int g = n & 1023; n >>= 10; *pos = 0; if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0); return buf; } static void test_systemstorageinfo(void) { QSystemStorageInfo storageinfo; QStringList lst = storageinfo.logicalDrives(); qDebug() << "storageinfo.logicalDrives ->" << lst; for(int i = 0; i < lst.size(); ++i) { const QString &drv = lst.at(i); qDebug() << "Logical drive:" << drv; qlonglong avail = storageinfo.availableDiskSpace(drv); qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail); qlonglong total = storageinfo.totalDiskSpace(drv); qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total); QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv); qDebug() << " storageinfo.typeForDrive() ->" << dtype; QString duri = storageinfo.uriForDrive(drv); qDebug() << " storageinfo.uriForDrive() ->" << duri; QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv); qDebug() << " storageinfo.getStorageState() ->" << dstate; } } /* ------------------------------------------------------------------------- * * test_systemnetworkinfo * ------------------------------------------------------------------------- */ static void test_systemnetworkinfo(void) { QSystemNetworkInfo networkinfo; X(networkinfo.cellId()); X(networkinfo.currentMobileCountryCode()); X(networkinfo.currentMobileNetworkCode()); X(networkinfo.homeMobileCountryCode()); X(networkinfo.homeMobileNetworkCode()); X(networkinfo.locationAreaCode()); for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) { QtMobility::QSystemNetworkInfo::NetworkMode mode = (QtMobility::QSystemNetworkInfo::NetworkMode) sym->val; qDebug() << ""; qDebug() << "NetworkMode:" << sym->key; QNetworkInterface iface = networkinfo.interfaceForMode(mode); qDebug() << " networkinfo.interfaceForMode() ->" << iface; QString macaddr = networkinfo.macAddress(mode); qDebug() << " networkinfo.macAddress() ->" << macaddr; QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode); qDebug() << " networkinfo.networkStatus() ->" << status; QString network = networkinfo.networkName(mode); qDebug() << " networkinfo.networkName() ->" << network; int sigstr = networkinfo.networkSignalStrength(mode); qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr; } } static void test_systemscreensaver(void) { QSystemScreenSaver screensaver; X(screensaver.screenSaverInhibited()); X(screensaver.setScreenSaverInhibit()); } struct dummy_t { const char *name; void (*func)(void); } lut[] = { #define ADD(x) {#x, test_##x } ADD(systeminfo), ADD(systemdeviceinfo), ADD(systemstorageinfo), ADD(systemnetworkinfo), ADD(systemscreensaver), ADD(systemdisplayinfo), #undef ADD {0,0} }; static bool endswith(const char *str, const char *pat) { int slen = strlen(str); int plen = strlen(pat); return (slen >= plen) && !strcmp(str+slen-plen, pat); } int lookup_test(const char *name) { for(int i = 0; lut[i].name; ++i) { if(!strcmp(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(endswith(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(strstr(lut[i].name, name)) return i; } return -1; } int main(int ac, char **av) { if(!getenv("DISPLAY")) { qDebug() << "$DISPLAY not set, assuming :0"; setenv("DISPLAY", ":0", 1); } if(!getenv("DBUS_SESSION_BUS_ADDRESS")) { qDebug() << "session bus not configured"; } QApplication app(ac, av, true); if(ac < 2) { qDebug() << "available tests:"; for(int k = 0; lut[k].name; ++k) { qDebug() << *av << lut[k].name; } exit(0); } for(int i = 1; i < ac; ++i) { const char *name = av[i]; int k = lookup_test(name); if(k != -1) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } else if( !strcmp(name, "all")) { for(int k = 0; lut[k].name; ++k) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } } else { break; } } } // EOF <commit_msg>fix build on windows<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QDebug> #include "qsysteminfo.h" using namespace QtMobility; #define X(expr) qDebug() << #expr << "->" << (expr); struct symbol_t { const char *key; int val; }; int lookup(const symbol_t *stab, const char *key, int def) { for(;stab->key;++stab) { if(!strcmp(stab->key,key)) return stab->val; } return def; } const char *rlookup(const symbol_t *stab, int val, const char *def) { for(;stab->key; ++stab) { if(stab->val == val) return stab->key; } return def; } #define SYM(x) { #x, x } static const symbol_t Version_lut[] = { SYM(QSystemInfo::Os), SYM(QSystemInfo::QtCore), SYM(QSystemInfo::Firmware), SYM(QSystemInfo::QtMobility), {0,0} }; static const symbol_t Feature_lut[] = { SYM(QSystemInfo::BluetoothFeature), SYM(QSystemInfo::CameraFeature), SYM(QSystemInfo::FmradioFeature), SYM(QSystemInfo::IrFeature), SYM(QSystemInfo::LedFeature), SYM(QSystemInfo::MemcardFeature), SYM(QSystemInfo::UsbFeature), SYM(QSystemInfo::VibFeature), SYM(QSystemInfo::WlanFeature), SYM(QSystemInfo::SimFeature), SYM(QSystemInfo::LocationFeature), SYM(QSystemInfo::VideoOutFeature), SYM(QSystemInfo::HapticsFeature), SYM(QSystemInfo::FmTransmitterFeature), {0,0} }; static const symbol_t NetworkStatus_lut[] = { SYM(QSystemNetworkInfo::UndefinedStatus), SYM(QSystemNetworkInfo::NoNetworkAvailable), SYM(QSystemNetworkInfo::EmergencyOnly), SYM(QSystemNetworkInfo::Searching), SYM(QSystemNetworkInfo::Busy), SYM(QSystemNetworkInfo::Connected), SYM(QSystemNetworkInfo::HomeNetwork), SYM(QSystemNetworkInfo::Denied), SYM(QSystemNetworkInfo::Roaming), {0,0} }; static const symbol_t NetworkMode_lut[] = { SYM(QSystemNetworkInfo::UnknownMode), SYM(QSystemNetworkInfo::GsmMode), SYM(QSystemNetworkInfo::CdmaMode), SYM(QSystemNetworkInfo::WcdmaMode), SYM(QSystemNetworkInfo::WlanMode), SYM(QSystemNetworkInfo::EthernetMode), SYM(QSystemNetworkInfo::BluetoothMode), SYM(QSystemNetworkInfo::WimaxMode), SYM(QSystemNetworkInfo::GprsMode), SYM(QSystemNetworkInfo::EdgeMode), SYM(QSystemNetworkInfo::HspaMode), SYM(QSystemNetworkInfo::LteMode), {0,0} }; /* ------------------------------------------------------------------------- * * test_systeminfo * ------------------------------------------------------------------------- */ static void test_systeminfo(void) { QSystemInfo info; X(info.currentLanguage()); X(info.availableLanguages()); X(info.currentCountryCode()); X(info.version(QSystemInfo::Os)); X(info.version(QSystemInfo::QtCore)); X(info.version(QSystemInfo::Firmware)); X(info.version(QSystemInfo::QtMobility)); X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature)); X(info.hasFeatureSupported(QSystemInfo::CameraFeature)); X(info.hasFeatureSupported(QSystemInfo::FmradioFeature)); X(info.hasFeatureSupported(QSystemInfo::IrFeature)); X(info.hasFeatureSupported(QSystemInfo::LedFeature)); X(info.hasFeatureSupported(QSystemInfo::MemcardFeature)); X(info.hasFeatureSupported(QSystemInfo::UsbFeature)); X(info.hasFeatureSupported(QSystemInfo::VibFeature)); X(info.hasFeatureSupported(QSystemInfo::WlanFeature)); X(info.hasFeatureSupported(QSystemInfo::SimFeature)); X(info.hasFeatureSupported(QSystemInfo::LocationFeature)); X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature)); X(info.hasFeatureSupported(QSystemInfo::HapticsFeature)); X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature)); } /* ------------------------------------------------------------------------- * * test_systemdeviceinfo * ------------------------------------------------------------------------- */ static void test_systemdeviceinfo(void) { QSystemDeviceInfo deviceinfo; X(deviceinfo.batteryLevel()); X(deviceinfo.batteryStatus()); X(deviceinfo.currentBluetoothPowerState()); X(deviceinfo.currentPowerState()); X(deviceinfo.currentProfile()); X(deviceinfo.imei()); X(deviceinfo.imsi()); X(deviceinfo.inputMethodType()); X(deviceinfo.isDeviceLocked()); X(deviceinfo.isKeyboardFlipOpen()); X(deviceinfo.isWirelessKeyboardConnected()); X(deviceinfo.keyboardType()); X(deviceinfo.manufacturer()); X(deviceinfo.model()); X(deviceinfo.productName()); X(deviceinfo.simStatus()); X(deviceinfo.typeOfLock()); } /* ------------------------------------------------------------------------- * * test_systemdisplayinfo * ------------------------------------------------------------------------- */ static void test_systemdisplayinfo(void) { QSystemDisplayInfo displayinfo; for( int display = 0; display < 4; ++display ) { qDebug() << ""; qDebug() << "Display:" << display; int depth = displayinfo.colorDepth(display); qDebug() << " displayinfo.colorDepth() ->" << depth; int value = displayinfo.displayBrightness(display); qDebug() << " displayinfo.displayBrightness() ->" << value; QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display); qDebug() << " displayinfo.getOrientation() ->" << orientation; float contrast = displayinfo.contrast(display); qDebug() << " displayinfo.getContrast() ->" << contrast; int dpiWidth = displayinfo.getDPIWidth(display); qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth; int dpiHeight = displayinfo.getDPIHeight(display); qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight; int physicalHeight = displayinfo.physicalHeight(display); qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight; int physicalWidth = displayinfo.physicalWidth(display); qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth; } } /* ------------------------------------------------------------------------- * * test_systemstorageinfo * ------------------------------------------------------------------------- */ static const char *human_size(qlonglong n) { if(n == 0) return "0B"; static char buf[256]; char *pos = buf; char *end = buf + sizeof buf; int b = n & 1023; n >>= 10; int k = n & 1023; n >>= 10; int m = n & 1023; n >>= 10; int g = n & 1023; n >>= 10; *pos = 0; #if defined(Q_WS_WIN) if(g) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #else if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #endif return buf; } static void test_systemstorageinfo(void) { QSystemStorageInfo storageinfo; QStringList lst = storageinfo.logicalDrives(); qDebug() << "storageinfo.logicalDrives ->" << lst; for(int i = 0; i < lst.size(); ++i) { const QString &drv = lst.at(i); qDebug() << "Logical drive:" << drv; qlonglong avail = storageinfo.availableDiskSpace(drv); qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail); qlonglong total = storageinfo.totalDiskSpace(drv); qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total); QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv); qDebug() << " storageinfo.typeForDrive() ->" << dtype; QString duri = storageinfo.uriForDrive(drv); qDebug() << " storageinfo.uriForDrive() ->" << duri; QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv); qDebug() << " storageinfo.getStorageState() ->" << dstate; } } /* ------------------------------------------------------------------------- * * test_systemnetworkinfo * ------------------------------------------------------------------------- */ static void test_systemnetworkinfo(void) { QSystemNetworkInfo networkinfo; X(networkinfo.cellId()); X(networkinfo.currentMobileCountryCode()); X(networkinfo.currentMobileNetworkCode()); X(networkinfo.homeMobileCountryCode()); X(networkinfo.homeMobileNetworkCode()); X(networkinfo.locationAreaCode()); for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) { QtMobility::QSystemNetworkInfo::NetworkMode mode = (QtMobility::QSystemNetworkInfo::NetworkMode) sym->val; qDebug() << ""; qDebug() << "NetworkMode:" << sym->key; QNetworkInterface iface = networkinfo.interfaceForMode(mode); qDebug() << " networkinfo.interfaceForMode() ->" << iface; QString macaddr = networkinfo.macAddress(mode); qDebug() << " networkinfo.macAddress() ->" << macaddr; QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode); qDebug() << " networkinfo.networkStatus() ->" << status; QString network = networkinfo.networkName(mode); qDebug() << " networkinfo.networkName() ->" << network; int sigstr = networkinfo.networkSignalStrength(mode); qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr; } } static void test_systemscreensaver(void) { QSystemScreenSaver screensaver; X(screensaver.screenSaverInhibited()); X(screensaver.setScreenSaverInhibit()); } struct dummy_t { const char *name; void (*func)(void); } lut[] = { #define ADD(x) {#x, test_##x } ADD(systeminfo), ADD(systemdeviceinfo), ADD(systemstorageinfo), ADD(systemnetworkinfo), ADD(systemscreensaver), ADD(systemdisplayinfo), #undef ADD {0,0} }; static bool endswith(const char *str, const char *pat) { int slen = strlen(str); int plen = strlen(pat); return (slen >= plen) && !strcmp(str+slen-plen, pat); } int lookup_test(const char *name) { for(int i = 0; lut[i].name; ++i) { if(!strcmp(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(endswith(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(strstr(lut[i].name, name)) return i; } return -1; } int main(int ac, char **av) { #if !defined(Q_WS_WIN) if(!getenv("DISPLAY")) { qDebug() << "$DISPLAY not set, assuming :0"; setenv("DISPLAY", ":0", 1); } if(!getenv("DBUS_SESSION_BUS_ADDRESS")) { qDebug() << "session bus not configured"; } #endif QApplication app(ac, av, true); if(ac < 2) { qDebug() << "available tests:"; for(int k = 0; lut[k].name; ++k) { qDebug() << *av << lut[k].name; } exit(0); } for(int i = 1; i < ac; ++i) { const char *name = av[i]; int k = lookup_test(name); if(k != -1) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } else if( !strcmp(name, "all")) { for(int k = 0; lut[k].name; ++k) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } } else { break; } } } // EOF <|endoftext|>
<commit_before>/** * 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. */ #ifndef __STOUT_WINDOWS_HPP__ #define __STOUT_WINDOWS_HPP__ #include <direct.h> // For `_mkdir`. #include <fcntl.h> // For file access flags like `_O_CREAT`. #include <io.h> // For `_read`, `_write`. #include <BaseTsd.h> // For `SSIZE_T`. // We include `Winsock2.h` before `Windows.h` explicitly to avoid symbold // re-definitions. This is a known pattern in the windows community. #include <Winsock2.h> #include <Windows.h> // Definitions and constants used for Windows compat. // // Gathers most of the Windows-compatibility definitions. This makes it // possible for files throughout the codebase to remain relatively free of all // the #if's we'd need to make them work. // // Roughly, the things that should go in this file are definitions and // declarations that one would not mind being: // * in global scope. // * globally available throughout both the Stout codebase, and any code // that uses it (such as Mesos). // Define constants used for Windows compat. Allows a lot of code on // Windows and POSIX systems to be the same, because we can pass the // same constants to functions we call to do things like file I/O. #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #define R_OK 0x4 #define W_OK 0x2 #define X_OK 0x0 // No such permission on Windows. #define F_OK 0x0 #define O_RDONLY _O_RDONLY #define O_WRONLY _O_WRONLY #define O_RDWR _O_RDWR #define O_CREAT _O_CREAT #define O_TRUNC _O_TRUNC #define O_APPEND _O_APPEND #define O_CLOEXEC _O_NOINHERIT // TODO(hausdorff): (MESOS-3398) Not defined on Windows. This value is // temporary. #define MAXHOSTNAMELEN 64 #define PATH_MAX _MAX_PATH // Corresponds to `mode_t` defined in sys/types.h of the POSIX spec. // See large "permissions API" comment below for an explanation of // why this is an int instead of unsigned short (as is common on // POSIX). typedef int mode_t; // `DWORD` is expected to be the type holding PIDs throughout the Windows API, // including functions like `OpenProcess`. typedef DWORD pid_t; typedef SSIZE_T ssize_t; // File I/O function aliases. // // NOTE: The use of `auto` and the trailing return type in the following // functions are meant to make it easier for Linux developers to use and // maintain the code. It is an explicit marker that we are using the compiler // to guarantee that the return type is identical to whatever is in the Windows // implementation of the standard. inline auto write(int fd, const void* buffer, size_t count) -> decltype(_write(fd, buffer, count)) { return _write(fd, buffer, count); } inline auto open(const char* path, int flags) -> decltype(_open(path, flags)) { return _open(path, flags); } inline auto close(int fd) -> decltype(_close(fd)) { return _close(fd); } // Filesystem function aliases. inline auto mkdir(const char* path, mode_t mode) -> decltype(_mkdir(path)) { return _mkdir(path); } inline auto mkstemp(char* path) -> decltype(_mktemp_s(path, strlen(path) + 1)) { return _mktemp_s(path, strlen(path) + 1); } inline auto realpath(const char* path, char* resolved) -> decltype(_fullpath(resolved, path, PATH_MAX)) { return _fullpath(resolved, path, PATH_MAX); } inline auto access(const char* fileName, int accessMode) -> decltype(_access(fileName, accessMode)) { return _access(fileName, accessMode); } // Permissions API. (cf. MESOS-3176 to track ongoing permissions work.) // // We are currently able to emulate a subset of the POSIX permissions model // with the Windows model: // [x] User write permissions. // [x] User read permissions. // [ ] User execute permissions. // [ ] Group permissions of any sort. // [ ] Other permissions of any sort. // [x] Flags to control "fallback" behavior (e.g., we might choose // to fall back to user readability when the user passes the // group readability flag in, since we currently do not support // group readability). // // // Rationale: // Windows currently implements two permissions models: (1) an extremely // primitive permission model it largely inherited from DOS, and (2) the Access // Control List (ACL) API. Because there is no trivial way to map the classic // POSIX model into the ACL model, we have implemented POSIX-style permissions // in terms of the DOS model. The result is the permissions limitations above. // // // Flag implementation: // Flags fall into the following two categories. // (1) Flags which exist in both permission models, but which have // different names (e.g., `S_IRUSR` in POSIX is called `_S_IREAD` on // Windows). In this case, we define the POSIX name to be the Windows // value (e.g., we define `S_IRUSR` to have the same value as `_S_IREAD`), // so that we can pass the POSIX name into Windows functions like // `_open`. // (2) Flags which exist only on POSIX (e.g., `S_IXUSR`). Here we // define the POSIX name to be the value given in the glibc // documentation[1], shifted left by 16 bits (since `mode_t` // is unsigned short on POSIX and `int` on Windows). We give these // flags glibc values to stay consistent, and so that existing // calls to functions like `open` do not break when they try to // use a flag that doesn't exist on Windows. But, of course, // these flags do not affect the execution of these functions. // // // Flag strictness: // Because the current implementation does not directly support setting or // getting group or other permission bits on the Windows platform, there is a // question of what we should fall back to when these flags are passed in to // Stout methods. // // TODO(hausdorff): Investigate permissions mappings. // We force "strictness" of the permission flag semantics: // * The group permissions flags will not fall back to anything, and will be // completely ignored. // * Other permissions: Same as above, but with other permissions. // // // Execute permissions: // Because DOS has no notion of "execute permissions", we define execute // permissions to be read permissions. This is not ideal, but it is closest to // being accurate. // // // [1] http://www.delorie.com/gnu/docs/glibc/libc_288.html // User permission flags. const mode_t S_IRUSR = mode_t(_S_IREAD); // Readable by user. const mode_t S_IWUSR = mode_t(_S_IWRITE); // Writeable by user. const mode_t S_IXUSR = S_IRUSR; // Fallback to user read. const mode_t S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR; // Group permission flags. Lossy mapping to Windows permissions. See // note above about flag strictness for explanation. const mode_t S_IRGRP = 0x00200000; // No-op. const mode_t S_IWGRP = 0x00100000; // No-op. const mode_t S_IXGRP = 0x00080000; // No-op. const mode_t S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP; // Other permission flags. Lossy mapping to Windows permissions. See // note above about flag stictness for explanation. const mode_t S_IROTH = 0x00040000; // No-op. const mode_t S_IWOTH = 0x00020000; // No-op. const mode_t S_IXOTH = 0x00010000; // No-op. const mode_t S_IRWXO = S_IROTH | S_IWOTH | S_IXOTH; // Flags for set-ID-on-exec. const mode_t S_ISUID = 0x08000000; // No-op. const mode_t S_ISGID = 0x04000000; // No-op. const mode_t S_ISVTX = 0x02000000; // No-op. #endif // __STOUT_WINDOWS_HPP__ <commit_msg>Windows: Introduced socket flag interop.<commit_after>/** * 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. */ #ifndef __STOUT_WINDOWS_HPP__ #define __STOUT_WINDOWS_HPP__ #include <direct.h> // For `_mkdir`. #include <fcntl.h> // For file access flags like `_O_CREAT`. #include <io.h> // For `_read`, `_write`. #include <BaseTsd.h> // For `SSIZE_T`. // We include `Winsock2.h` before `Windows.h` explicitly to avoid symbold // re-definitions. This is a known pattern in the windows community. #include <Winsock2.h> #include <Windows.h> // Definitions and constants used for Windows compat. // // Gathers most of the Windows-compatibility definitions. This makes it // possible for files throughout the codebase to remain relatively free of all // the #if's we'd need to make them work. // // Roughly, the things that should go in this file are definitions and // declarations that one would not mind being: // * in global scope. // * globally available throughout both the Stout codebase, and any code // that uses it (such as Mesos). // Define constants used for Windows compat. Allows a lot of code on // Windows and POSIX systems to be the same, because we can pass the // same constants to functions we call to do things like file I/O. #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #define R_OK 0x4 #define W_OK 0x2 #define X_OK 0x0 // No such permission on Windows. #define F_OK 0x0 #define O_RDONLY _O_RDONLY #define O_WRONLY _O_WRONLY #define O_RDWR _O_RDWR #define O_CREAT _O_CREAT #define O_TRUNC _O_TRUNC #define O_APPEND _O_APPEND #define O_CLOEXEC _O_NOINHERIT // TODO(hausdorff): (MESOS-3398) Not defined on Windows. This value is // temporary. #define MAXHOSTNAMELEN 64 #define PATH_MAX _MAX_PATH // Corresponds to `mode_t` defined in sys/types.h of the POSIX spec. // See large "permissions API" comment below for an explanation of // why this is an int instead of unsigned short (as is common on // POSIX). typedef int mode_t; // `DWORD` is expected to be the type holding PIDs throughout the Windows API, // including functions like `OpenProcess`. typedef DWORD pid_t; typedef SSIZE_T ssize_t; // Socket flags. Define behavior of a socket when it (e.g.) shuts down. We map // the Windows versions of these flags to their POSIX equivalents so we don't // have to change any socket code. constexpr int SHUT_RD = SD_RECEIVE; // File I/O function aliases. // // NOTE: The use of `auto` and the trailing return type in the following // functions are meant to make it easier for Linux developers to use and // maintain the code. It is an explicit marker that we are using the compiler // to guarantee that the return type is identical to whatever is in the Windows // implementation of the standard. inline auto write(int fd, const void* buffer, size_t count) -> decltype(_write(fd, buffer, count)) { return _write(fd, buffer, count); } inline auto open(const char* path, int flags) -> decltype(_open(path, flags)) { return _open(path, flags); } inline auto close(int fd) -> decltype(_close(fd)) { return _close(fd); } // Filesystem function aliases. inline auto mkdir(const char* path, mode_t mode) -> decltype(_mkdir(path)) { return _mkdir(path); } inline auto mkstemp(char* path) -> decltype(_mktemp_s(path, strlen(path) + 1)) { return _mktemp_s(path, strlen(path) + 1); } inline auto realpath(const char* path, char* resolved) -> decltype(_fullpath(resolved, path, PATH_MAX)) { return _fullpath(resolved, path, PATH_MAX); } inline auto access(const char* fileName, int accessMode) -> decltype(_access(fileName, accessMode)) { return _access(fileName, accessMode); } // Permissions API. (cf. MESOS-3176 to track ongoing permissions work.) // // We are currently able to emulate a subset of the POSIX permissions model // with the Windows model: // [x] User write permissions. // [x] User read permissions. // [ ] User execute permissions. // [ ] Group permissions of any sort. // [ ] Other permissions of any sort. // [x] Flags to control "fallback" behavior (e.g., we might choose // to fall back to user readability when the user passes the // group readability flag in, since we currently do not support // group readability). // // // Rationale: // Windows currently implements two permissions models: (1) an extremely // primitive permission model it largely inherited from DOS, and (2) the Access // Control List (ACL) API. Because there is no trivial way to map the classic // POSIX model into the ACL model, we have implemented POSIX-style permissions // in terms of the DOS model. The result is the permissions limitations above. // // // Flag implementation: // Flags fall into the following two categories. // (1) Flags which exist in both permission models, but which have // different names (e.g., `S_IRUSR` in POSIX is called `_S_IREAD` on // Windows). In this case, we define the POSIX name to be the Windows // value (e.g., we define `S_IRUSR` to have the same value as `_S_IREAD`), // so that we can pass the POSIX name into Windows functions like // `_open`. // (2) Flags which exist only on POSIX (e.g., `S_IXUSR`). Here we // define the POSIX name to be the value given in the glibc // documentation[1], shifted left by 16 bits (since `mode_t` // is unsigned short on POSIX and `int` on Windows). We give these // flags glibc values to stay consistent, and so that existing // calls to functions like `open` do not break when they try to // use a flag that doesn't exist on Windows. But, of course, // these flags do not affect the execution of these functions. // // // Flag strictness: // Because the current implementation does not directly support setting or // getting group or other permission bits on the Windows platform, there is a // question of what we should fall back to when these flags are passed in to // Stout methods. // // TODO(hausdorff): Investigate permissions mappings. // We force "strictness" of the permission flag semantics: // * The group permissions flags will not fall back to anything, and will be // completely ignored. // * Other permissions: Same as above, but with other permissions. // // // Execute permissions: // Because DOS has no notion of "execute permissions", we define execute // permissions to be read permissions. This is not ideal, but it is closest to // being accurate. // // // [1] http://www.delorie.com/gnu/docs/glibc/libc_288.html // User permission flags. const mode_t S_IRUSR = mode_t(_S_IREAD); // Readable by user. const mode_t S_IWUSR = mode_t(_S_IWRITE); // Writeable by user. const mode_t S_IXUSR = S_IRUSR; // Fallback to user read. const mode_t S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR; // Group permission flags. Lossy mapping to Windows permissions. See // note above about flag strictness for explanation. const mode_t S_IRGRP = 0x00200000; // No-op. const mode_t S_IWGRP = 0x00100000; // No-op. const mode_t S_IXGRP = 0x00080000; // No-op. const mode_t S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP; // Other permission flags. Lossy mapping to Windows permissions. See // note above about flag stictness for explanation. const mode_t S_IROTH = 0x00040000; // No-op. const mode_t S_IWOTH = 0x00020000; // No-op. const mode_t S_IXOTH = 0x00010000; // No-op. const mode_t S_IRWXO = S_IROTH | S_IWOTH | S_IXOTH; // Flags for set-ID-on-exec. const mode_t S_ISUID = 0x08000000; // No-op. const mode_t S_ISGID = 0x04000000; // No-op. const mode_t S_ISVTX = 0x02000000; // No-op. #endif // __STOUT_WINDOWS_HPP__ <|endoftext|>
<commit_before>#include "LoadingScreen.h" #include "World.h" #include "SFML/Graphics/Color.hpp" #include <iostream> namespace TT { LoadingScreen *LoadingScreen::_instance = NULL; LoadingScreen *LoadingScreen::GetInstance() { if (!_instance) _instance = new LoadingScreen(500.0f); return _instance; } LoadingScreen::~LoadingScreen() { _instance = NULL; } LoadingScreen::LoadingScreen(float speed) { _speed = speed; rectangle.setFillColor(sf::Color(0, 0, 0, 255)); _alpha = 255; fadingin = false; fadingout = false; isfinished = false; } void LoadingScreen::OnGUI(sf::RenderWindow *window) { sf::Vector2f size(((float)World::GetInstance()->GetWindow()->getSize().x), ((float)World::GetInstance()->GetWindow()->getSize().y)); rectangle.setSize(size); rectangle.setOrigin((float)0.5*size.x, 0.5*size.y); Draw(window); } void LoadingScreen::Update(float timeStep) { if (_alpha <= 255.0 && fadingin) { _alpha += _speed *timeStep; rectangle.setFillColor(sf::Color(0, 0, 0, _alpha)); } if (_alpha >= 0.0 && fadingout) { _alpha -= _speed *timeStep; rectangle.setFillColor(sf::Color(0, 0, 0, _alpha)); } if (_alpha < 0.0 && fadingout) { fadingout = false; rectangle.setFillColor(sf::Color(0, 0, 0, 0)); } if (_alpha > 255.0 && fadingin) { fadingin = false; isfinished = true; } } void LoadingScreen::Draw(sf::RenderWindow *window) { rectangle.setPosition(window->getView().getCenter()); window->draw(rectangle); } bool LoadingScreen::Fadein() { if (fadingin == false && isfinished == false) { isfinished = false; _alpha = 0; rectangle.setFillColor(sf::Color(0, 0, 0, 0)); fadingin = true; } return isfinished; } void LoadingScreen::Fadeout() { _alpha = 255; rectangle.setFillColor(sf::Color(0, 0, 0, 255)); fadingout = true; } bool LoadingScreen::isLoading() { return (fadingin || fadingout); } bool LoadingScreen::isFinished() { return isfinished; } } <commit_msg>Fixed fading transition getting stuck.<commit_after>#include "LoadingScreen.h" #include "World.h" #include "SFML/Graphics/Color.hpp" #include <iostream> namespace TT { LoadingScreen *LoadingScreen::_instance = NULL; LoadingScreen *LoadingScreen::GetInstance() { if (!_instance) _instance = new LoadingScreen(500.0f); return _instance; } LoadingScreen::~LoadingScreen() { _instance = NULL; } LoadingScreen::LoadingScreen(float speed) { _speed = speed; rectangle.setFillColor(sf::Color(0, 0, 0, 255)); _alpha = 255; fadingin = false; fadingout = false; isfinished = false; } void LoadingScreen::OnGUI(sf::RenderWindow *window) { sf::Vector2f size(((float)World::GetInstance()->GetWindow()->getSize().x), ((float)World::GetInstance()->GetWindow()->getSize().y)); rectangle.setSize(size); rectangle.setOrigin((float)0.5*size.x, 0.5*size.y); Draw(window); } void LoadingScreen::Update(float timeStep) { if (_alpha <= 255.0 && fadingin) { _alpha += _speed *timeStep; rectangle.setFillColor(sf::Color(0, 0, 0, _alpha)); } if (_alpha >= 0.0 && fadingout) { _alpha -= _speed *timeStep; rectangle.setFillColor(sf::Color(0, 0, 0, _alpha)); } if (_alpha < 0.0 && fadingout) { fadingout = false; rectangle.setFillColor(sf::Color(0, 0, 0, 0)); } if (_alpha > 255.0 && fadingin) { fadingin = false; isfinished = true; } } void LoadingScreen::Draw(sf::RenderWindow *window) { rectangle.setPosition(window->getView().getCenter()); window->draw(rectangle); } bool LoadingScreen::Fadein() { if(fadingin == false && isfinished == false && fadingout == false) { isfinished = false; _alpha = 0; rectangle.setFillColor(sf::Color(0, 0, 0, 0)); fadingin = true; } return isfinished; } void LoadingScreen::Fadeout() { if(fadingin == false && isfinished == false && fadingout == false) { _alpha = 255; rectangle.setFillColor(sf::Color(0, 0, 0, 255)); fadingout = true; } } bool LoadingScreen::isLoading() { return (fadingin || fadingout); } bool LoadingScreen::isFinished() { return isfinished; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cpplocatorfilter.h" #include "cppmodelmanager.h" #include <QStringMatcher> using namespace CppTools::Internal; static const int MaxPendingDocuments = 10; CppLocatorFilter::CppLocatorFilter(CppLocatorData *locatorData) : m_data(locatorData) { setId("Classes and Methods"); setDisplayName(tr("C++ Classes and Methods")); setShortcutString(QString(QLatin1Char(':'))); setIncludedByDefault(false); } CppLocatorFilter::~CppLocatorFilter() { } Locator::FilterEntry CppLocatorFilter::filterEntryFromModelItemInfo(const CppTools::ModelItemInfo &info) { const QVariant id = qVariantFromValue(info); Locator::FilterEntry filterEntry(this, info.symbolName, id, info.icon); filterEntry.extraInfo = info.type == ModelItemInfo::Class || info.type == ModelItemInfo::Enum ? info.shortNativeFilePath() : info.symbolType; return filterEntry; } void CppLocatorFilter::refresh(QFutureInterface<void> &future) { Q_UNUSED(future) } QList<QList<CppTools::ModelItemInfo> > CppLocatorFilter::itemsToMatchUserInputAgainst() const { return QList<QList<CppTools::ModelItemInfo> >() << m_data->classes() << m_data->functions() << m_data->enums(); } static bool compareLexigraphically(const Locator::FilterEntry &a, const Locator::FilterEntry &b) { return a.displayName < b.displayName; } QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry) { QString entry = trimWildcards(origEntry); QList<Locator::FilterEntry> goodEntries; QList<Locator::FilterEntry> betterEntries; const QChar asterisk = QLatin1Char('*'); QStringMatcher matcher(entry, Qt::CaseInsensitive); QRegExp regexp(asterisk + entry+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard); if (!regexp.isValid()) return goodEntries; bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?'))); bool hasColonColon = entry.contains(QLatin1String("::")); const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry); const QList<QList<CppTools::ModelItemInfo> > itemLists = itemsToMatchUserInputAgainst(); foreach (const QList<CppTools::ModelItemInfo> &items, itemLists) { foreach (const ModelItemInfo &info, items) { if (future.isCanceled()) break; const QString matchString = hasColonColon ? info.scopedSymbolName() : info.symbolName; if ((hasWildcard && regexp.exactMatch(matchString)) || (!hasWildcard && matcher.indexIn(matchString) != -1)) { const Locator::FilterEntry filterEntry = filterEntryFromModelItemInfo(info); if (matchString.startsWith(entry, caseSensitivityForPrefix)) betterEntries.append(filterEntry); else goodEntries.append(filterEntry); } } } if (goodEntries.size() < 1000) qStableSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically); if (betterEntries.size() < 1000) qStableSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically); betterEntries += goodEntries; return betterEntries; } void CppLocatorFilter::accept(Locator::FilterEntry selection) const { ModelItemInfo info = qvariant_cast<CppTools::ModelItemInfo>(selection.internalData); Core::EditorManager::openEditorAt(info.fileName, info.line, info.column); } <commit_msg>CppTools: Remove dead code<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cpplocatorfilter.h" #include "cppmodelmanager.h" #include <QStringMatcher> using namespace CppTools::Internal; CppLocatorFilter::CppLocatorFilter(CppLocatorData *locatorData) : m_data(locatorData) { setId("Classes and Methods"); setDisplayName(tr("C++ Classes and Methods")); setShortcutString(QString(QLatin1Char(':'))); setIncludedByDefault(false); } CppLocatorFilter::~CppLocatorFilter() { } Locator::FilterEntry CppLocatorFilter::filterEntryFromModelItemInfo(const CppTools::ModelItemInfo &info) { const QVariant id = qVariantFromValue(info); Locator::FilterEntry filterEntry(this, info.symbolName, id, info.icon); filterEntry.extraInfo = info.type == ModelItemInfo::Class || info.type == ModelItemInfo::Enum ? info.shortNativeFilePath() : info.symbolType; return filterEntry; } void CppLocatorFilter::refresh(QFutureInterface<void> &future) { Q_UNUSED(future) } QList<QList<CppTools::ModelItemInfo> > CppLocatorFilter::itemsToMatchUserInputAgainst() const { return QList<QList<CppTools::ModelItemInfo> >() << m_data->classes() << m_data->functions() << m_data->enums(); } static bool compareLexigraphically(const Locator::FilterEntry &a, const Locator::FilterEntry &b) { return a.displayName < b.displayName; } QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry) { QString entry = trimWildcards(origEntry); QList<Locator::FilterEntry> goodEntries; QList<Locator::FilterEntry> betterEntries; const QChar asterisk = QLatin1Char('*'); QStringMatcher matcher(entry, Qt::CaseInsensitive); QRegExp regexp(asterisk + entry+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard); if (!regexp.isValid()) return goodEntries; bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?'))); bool hasColonColon = entry.contains(QLatin1String("::")); const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry); const QList<QList<CppTools::ModelItemInfo> > itemLists = itemsToMatchUserInputAgainst(); foreach (const QList<CppTools::ModelItemInfo> &items, itemLists) { foreach (const ModelItemInfo &info, items) { if (future.isCanceled()) break; const QString matchString = hasColonColon ? info.scopedSymbolName() : info.symbolName; if ((hasWildcard && regexp.exactMatch(matchString)) || (!hasWildcard && matcher.indexIn(matchString) != -1)) { const Locator::FilterEntry filterEntry = filterEntryFromModelItemInfo(info); if (matchString.startsWith(entry, caseSensitivityForPrefix)) betterEntries.append(filterEntry); else goodEntries.append(filterEntry); } } } if (goodEntries.size() < 1000) qStableSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically); if (betterEntries.size() < 1000) qStableSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically); betterEntries += goodEntries; return betterEntries; } void CppLocatorFilter::accept(Locator::FilterEntry selection) const { ModelItemInfo info = qvariant_cast<CppTools::ModelItemInfo>(selection.internalData); Core::EditorManager::openEditorAt(info.fileName, info.line, info.column); } <|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include <mysql/mysql.h> using namespace node; using namespace v8; static Persistent<FunctionTemplate> Client_constructor; static Persistent<String> emit_symbol; const int STATE_CONNECT = 0, STATE_CONNECTING = 1, STATE_CONNECTED = 2, STATE_QUERY = 3, STATE_QUERYING = 4, STATE_QUERIED = 5, STATE_ROWSTREAM = 6, STATE_ROWSTREAMING = 7, STATE_ROWSTREAMED = 8, STATE_CLOSE = 9, STATE_CLOSING = 10, STATE_CLOSED = 11; struct sql_config { char* user; char* password; char* ip; char* db; unsigned int port; bool compress; }; #include <stdio.h> #define DEBUG(s) fprintf(stderr, "BINDING: " s "\n") class Client : public ObjectWrap { public: uv_poll_t poll_handle; MYSQL mysql, *mysql_ret; MYSQL_RES *mysql_res; MYSQL_ROW mysql_row; int mysql_qerr; char* cur_query; sql_config config; bool hadError; int state; Client() { state = STATE_CLOSED; } ~Client() { close(); } void init() { config.user = NULL; config.password = NULL; config.ip = NULL; config.db = NULL; cur_query = NULL; hadError = false; poll_handle.type = UV_UNKNOWN_HANDLE; mysql_init(&mysql); mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0); } void connect() { if (state == STATE_CLOSED) { state = STATE_CONNECT; doWork(); } } void close() { if (state != STATE_CLOSED) { if (config.user) free(config.user); if (config.password) free(config.password); if (config.ip) free(config.ip); if (config.db) free(config.db); if (cur_query) free(cur_query); state = STATE_CLOSE; doWork(); } } void query(const char* qry) { if (state == STATE_CONNECTED) { cur_query = strdup(qry); state = STATE_QUERY; doWork(); } } void doWork(int event = 0) { int status = 0, new_events = 0; bool done = false; while (!done) { switch (state) { case STATE_CONNECT: DEBUG("STATE_CONNECT"); status = mysql_real_connect_start(&mysql_ret, &mysql, config.ip, config.user, config.password, config.db, config.port, NULL, 0); uv_poll_init_socket(uv_default_loop(), &poll_handle, mysql_get_socket(&mysql)); poll_handle.data = this; if (status) { state = STATE_CONNECTING; done = true; } else { state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTING: DEBUG("STATE_CONNECTING"); status = mysql_real_connect_cont(&mysql_ret, &mysql, event); if (status) done = true; else { if (!mysql_ret) return emitError("conn"); state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTED: DEBUG("STATE_CONNECTED"); done = true; break; case STATE_QUERY: DEBUG("STATE_QUERY"); status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query, strlen(cur_query)); if (status) { state = STATE_QUERYING; done = true; } else state = STATE_QUERIED; break; case STATE_QUERYING: DEBUG("STATE_QUERYING"); status = mysql_real_query_cont(&mysql_qerr, &mysql, mysql_status(event)); if (status) done = true; else { free(cur_query); if (mysql_qerr) return emitError("query"); state = STATE_QUERIED; } break; case STATE_QUERIED: DEBUG("STATE_QUERIED"); mysql_res = mysql_use_result(&mysql); if (!mysql_res) return emitError("query"); state = STATE_ROWSTREAM; break; case STATE_ROWSTREAM: DEBUG("STATE_ROWSTREAM"); status = mysql_fetch_row_start(&mysql_row, mysql_res); if (status) { done = true; state = STATE_ROWSTREAMING; } else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMING: DEBUG("STATE_ROWSTREAMING"); status = mysql_fetch_row_cont(&mysql_row, mysql_res, mysql_status(event)); if (status) done = true; else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMED: DEBUG("STATE_ROWSTREAMED"); if (mysql_row) { state = STATE_ROWSTREAM; emitRow(); } else { if (mysql_errno(&mysql)) { mysql_free_result(mysql_res); return emitError("result"); } else { // no more rows mysql_free_result(mysql_res); state = STATE_CONNECTED; emit("done"); } } break; case STATE_CLOSE: DEBUG("STATE_CLOSE"); mysql_close(&mysql); state = STATE_CLOSED; uv_close((uv_handle_t*) &poll_handle, cbClose); return; /* status = mysql_close_start(&mysql); if (status) { done = true; state = STATE_CLOSING; } else { state = STATE_CLOSED; DEBUG("STATE_CLOSED"); uv_close((uv_handle_t*) &poll_handle, cbClose); return; }*/ break; case STATE_CLOSING: DEBUG("STATE_CLOSING"); status = mysql_close_cont(&mysql, mysql_status(event)); if (status) done = true; else { state = STATE_CLOSED; DEBUG("STATE_CLOSED"); uv_close((uv_handle_t*) &poll_handle, cbClose); return; } break; case STATE_CLOSED: return; } } if (status & MYSQL_WAIT_READ) new_events |= UV_READABLE; if (status & MYSQL_WAIT_WRITE) new_events |= UV_WRITABLE; uv_poll_start(&poll_handle, new_events, cbPoll); } void emitError(const char* when) { HandleScope scope; hadError = true; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> err = Exception::Error(String::New(mysql_error(&mysql))); Local<Object> err_obj = err->ToObject(); err_obj->Set(String::New("code"), Integer::NewFromUnsigned(mysql_errno(&mysql))); err_obj->Set(String::New("when"), String::New(when)); Local<Value> emit_argv[2] = { String::New("error"), err }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); close(); } void emit(const char* eventName) { HandleScope scope; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> emit_argv[1] = { String::New(eventName) }; TryCatch try_catch; Emit->Call(handle_, 1, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } void emitRow() { HandleScope scope; unsigned int i = 0, len = mysql_num_fields(mysql_res); char* field; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Object> row = Object::New(); for (; i<len; ++i) { field = mysql_fetch_field_direct(mysql_res, i)->name; row->Set(String::New(field), (mysql_row[i] ? String::New(mysql_row[i]) : Null())); } Local<Value> emit_argv[2] = { String::New("result"), row }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static void cbPoll(uv_poll_t* handle, int status, int events) { HandleScope scope; Client* obj = (Client*) handle->data; assert(status == 0); int mysql_status = 0; if (events & UV_READABLE) mysql_status |= MYSQL_WAIT_READ; if (events & UV_WRITABLE) mysql_status |= MYSQL_WAIT_WRITE; /*if (events & UV_TIMEOUT) mysql_status |= MYSQL_WAIT_TIMEOUT;*/ obj->doWork(mysql_status); } static void cbClose(uv_handle_t* handle) { HandleScope scope; Client* obj = (Client*) handle->data; Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol)); TryCatch try_catch; Local<Value> emit_argv[2] = { String::New("close"), Local<Boolean>::New(Boolean::New(obj->hadError)) }; Emit->Call(obj->handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static Handle<Value> New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } Client* obj = new Client(); obj->Wrap(args.This()); return args.This(); } static Handle<Value> Connect(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Not ready to connect")) ); } obj->init(); Local<Object> cfg = args[0]->ToObject(); Local<Value> user_v = cfg->Get(String::New("user")); Local<Value> password_v = cfg->Get(String::New("password")); Local<Value> ip_v = cfg->Get(String::New("host")); Local<Value> port_v = cfg->Get(String::New("port")); Local<Value> db_v = cfg->Get(String::New("db")); Local<Value> compress_v = cfg->Get(String::New("compress")); Local<Value> ssl_v = cfg->Get(String::New("secure")); if (!user_v->IsString() || user_v->ToString()->Length() == 0) { obj->close(); return ThrowException(Exception::Error( String::New("`user` must be a non-empty string")) ); } else { String::Utf8Value user_s(user_v); obj->config.user = strdup(*user_s); } if (!password_v->IsString() || password_v->ToString()->Length() == 0) obj->config.password = NULL; else { String::Utf8Value password_s(password_v); obj->config.password = strdup(*password_s); } if (!ip_v->IsString() || ip_v->ToString()->Length() == 0) obj->config.ip = NULL; else { String::Utf8Value ip_s(ip_v); obj->config.ip = strdup(*ip_s); } if (!port_v->IsUint32() || port_v->Uint32Value() == 0) obj->config.port = 3306; else obj->config.port = port_v->Uint32Value(); if (db_v->IsString() && db_v->ToString()->Length() > 0) { String::Utf8Value db_s(db_v); obj->config.db = strdup(*db_s); } obj->connect(); return Undefined(); } static Handle<Value> Query(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not ready to query")) ); } if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Query expected")) ); } String::Utf8Value query(args[0]->ToString()); obj->query(*query); return Undefined(); } static Handle<Value> Close(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state == STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Already closed")) ); } obj->close(); return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Client"); Client_constructor = Persistent<FunctionTemplate>::New(tpl); Client_constructor->InstanceTemplate()->SetInternalFieldCount(1); Client_constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "connect", Connect); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "query", Query); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "end", Close); emit_symbol = NODE_PSYMBOL("emit"); target->Set(name, Client_constructor->GetFunction()); } }; static Handle<Value> Version(const Arguments& args) { HandleScope scope; unsigned long client_ver = mysql_get_client_version(); char major = (client_ver >> 16) & 0xFF, release = (client_ver >> 8) & 0xFF, rel_ver = client_ver & 0xFF; int slen = (major < 10 ? 1 : 2) + (release < 10 ? 1 : 2) + (rel_ver < 10 ? 1 : 2); char* ver = (char*) malloc(slen + 3); sprintf(ver, "%u.%u.%u", major, release, rel_ver); Local<String> ver_str = String::New(ver); free(ver); return scope.Close(ver_str); } extern "C" { void init(Handle<Object> target) { HandleScope scope; Client::Initialize(target); target->Set(String::NewSymbol("version"), FunctionTemplate::New(Version)->GetFunction()); } NODE_MODULE(sqlclient, init); }<commit_msg>Remove commented code and disable debug output<commit_after>#include <node.h> #include <node_buffer.h> #include <mysql/mysql.h> using namespace node; using namespace v8; static Persistent<FunctionTemplate> Client_constructor; static Persistent<String> emit_symbol; const int STATE_CONNECT = 0, STATE_CONNECTING = 1, STATE_CONNECTED = 2, STATE_QUERY = 3, STATE_QUERYING = 4, STATE_QUERIED = 5, STATE_ROWSTREAM = 6, STATE_ROWSTREAMING = 7, STATE_ROWSTREAMED = 8, STATE_CLOSE = 9, STATE_CLOSING = 10, STATE_CLOSED = 11; struct sql_config { char* user; char* password; char* ip; char* db; unsigned int port; bool compress; }; #include <stdio.h> #define DEBUG(s) fprintf(stderr, "BINDING: " s "\n") class Client : public ObjectWrap { public: uv_poll_t poll_handle; MYSQL mysql, *mysql_ret; MYSQL_RES *mysql_res; MYSQL_ROW mysql_row; int mysql_qerr; char* cur_query; sql_config config; bool hadError; int state; Client() { state = STATE_CLOSED; } ~Client() { close(); } void init() { config.user = NULL; config.password = NULL; config.ip = NULL; config.db = NULL; cur_query = NULL; hadError = false; poll_handle.type = UV_UNKNOWN_HANDLE; mysql_init(&mysql); mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0); } void connect() { if (state == STATE_CLOSED) { state = STATE_CONNECT; doWork(); } } void close() { if (state != STATE_CLOSED) { if (config.user) free(config.user); if (config.password) free(config.password); if (config.ip) free(config.ip); if (config.db) free(config.db); if (cur_query) free(cur_query); state = STATE_CLOSE; doWork(); } } void query(const char* qry) { if (state == STATE_CONNECTED) { cur_query = strdup(qry); state = STATE_QUERY; doWork(); } } void doWork(int event = 0) { int status = 0, new_events = 0; bool done = false; while (!done) { switch (state) { case STATE_CONNECT: //DEBUG("STATE_CONNECT"); status = mysql_real_connect_start(&mysql_ret, &mysql, config.ip, config.user, config.password, config.db, config.port, NULL, 0); uv_poll_init_socket(uv_default_loop(), &poll_handle, mysql_get_socket(&mysql)); poll_handle.data = this; if (status) { state = STATE_CONNECTING; done = true; } else { state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTING: //DEBUG("STATE_CONNECTING"); status = mysql_real_connect_cont(&mysql_ret, &mysql, event); if (status) done = true; else { if (!mysql_ret) return emitError("conn"); state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTED: //DEBUG("STATE_CONNECTED"); done = true; break; case STATE_QUERY: //DEBUG("STATE_QUERY"); status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query, strlen(cur_query)); if (status) { state = STATE_QUERYING; done = true; } else state = STATE_QUERIED; break; case STATE_QUERYING: //DEBUG("STATE_QUERYING"); status = mysql_real_query_cont(&mysql_qerr, &mysql, mysql_status(event)); if (status) done = true; else { free(cur_query); if (mysql_qerr) return emitError("query"); state = STATE_QUERIED; } break; case STATE_QUERIED: //DEBUG("STATE_QUERIED"); mysql_res = mysql_use_result(&mysql); if (!mysql_res) return emitError("query"); state = STATE_ROWSTREAM; break; case STATE_ROWSTREAM: //DEBUG("STATE_ROWSTREAM"); status = mysql_fetch_row_start(&mysql_row, mysql_res); if (status) { done = true; state = STATE_ROWSTREAMING; } else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMING: //DEBUG("STATE_ROWSTREAMING"); status = mysql_fetch_row_cont(&mysql_row, mysql_res, mysql_status(event)); if (status) done = true; else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMED: //DEBUG("STATE_ROWSTREAMED"); if (mysql_row) { state = STATE_ROWSTREAM; emitRow(); } else { if (mysql_errno(&mysql)) { mysql_free_result(mysql_res); return emitError("result"); } else { // no more rows mysql_free_result(mysql_res); state = STATE_CONNECTED; emit("done"); } } break; case STATE_CLOSE: //DEBUG("STATE_CLOSE"); mysql_close(&mysql); state = STATE_CLOSED; uv_close((uv_handle_t*) &poll_handle, cbClose); return; case STATE_CLOSED: return; } } if (status & MYSQL_WAIT_READ) new_events |= UV_READABLE; if (status & MYSQL_WAIT_WRITE) new_events |= UV_WRITABLE; uv_poll_start(&poll_handle, new_events, cbPoll); } void emitError(const char* when) { HandleScope scope; hadError = true; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> err = Exception::Error(String::New(mysql_error(&mysql))); Local<Object> err_obj = err->ToObject(); err_obj->Set(String::New("code"), Integer::NewFromUnsigned(mysql_errno(&mysql))); err_obj->Set(String::New("when"), String::New(when)); Local<Value> emit_argv[2] = { String::New("error"), err }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); close(); } void emit(const char* eventName) { HandleScope scope; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> emit_argv[1] = { String::New(eventName) }; TryCatch try_catch; Emit->Call(handle_, 1, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } void emitRow() { HandleScope scope; unsigned int i = 0, len = mysql_num_fields(mysql_res); char* field; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Object> row = Object::New(); for (; i<len; ++i) { field = mysql_fetch_field_direct(mysql_res, i)->name; row->Set(String::New(field), (mysql_row[i] ? String::New(mysql_row[i]) : Null())); } Local<Value> emit_argv[2] = { String::New("result"), row }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static void cbPoll(uv_poll_t* handle, int status, int events) { HandleScope scope; Client* obj = (Client*) handle->data; assert(status == 0); int mysql_status = 0; if (events & UV_READABLE) mysql_status |= MYSQL_WAIT_READ; if (events & UV_WRITABLE) mysql_status |= MYSQL_WAIT_WRITE; /*if (events & UV_TIMEOUT) mysql_status |= MYSQL_WAIT_TIMEOUT;*/ obj->doWork(mysql_status); } static void cbClose(uv_handle_t* handle) { HandleScope scope; Client* obj = (Client*) handle->data; Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol)); TryCatch try_catch; Local<Value> emit_argv[2] = { String::New("close"), Local<Boolean>::New(Boolean::New(obj->hadError)) }; Emit->Call(obj->handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static Handle<Value> New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } Client* obj = new Client(); obj->Wrap(args.This()); return args.This(); } static Handle<Value> Connect(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Not ready to connect")) ); } obj->init(); Local<Object> cfg = args[0]->ToObject(); Local<Value> user_v = cfg->Get(String::New("user")); Local<Value> password_v = cfg->Get(String::New("password")); Local<Value> ip_v = cfg->Get(String::New("host")); Local<Value> port_v = cfg->Get(String::New("port")); Local<Value> db_v = cfg->Get(String::New("db")); Local<Value> compress_v = cfg->Get(String::New("compress")); Local<Value> ssl_v = cfg->Get(String::New("secure")); if (!user_v->IsString() || user_v->ToString()->Length() == 0) { obj->close(); return ThrowException(Exception::Error( String::New("`user` must be a non-empty string")) ); } else { String::Utf8Value user_s(user_v); obj->config.user = strdup(*user_s); } if (!password_v->IsString() || password_v->ToString()->Length() == 0) obj->config.password = NULL; else { String::Utf8Value password_s(password_v); obj->config.password = strdup(*password_s); } if (!ip_v->IsString() || ip_v->ToString()->Length() == 0) obj->config.ip = NULL; else { String::Utf8Value ip_s(ip_v); obj->config.ip = strdup(*ip_s); } if (!port_v->IsUint32() || port_v->Uint32Value() == 0) obj->config.port = 3306; else obj->config.port = port_v->Uint32Value(); if (db_v->IsString() && db_v->ToString()->Length() > 0) { String::Utf8Value db_s(db_v); obj->config.db = strdup(*db_s); } obj->connect(); return Undefined(); } static Handle<Value> Query(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not ready to query")) ); } if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Query expected")) ); } String::Utf8Value query(args[0]->ToString()); obj->query(*query); return Undefined(); } static Handle<Value> Close(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state == STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Already closed")) ); } obj->close(); return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Client"); Client_constructor = Persistent<FunctionTemplate>::New(tpl); Client_constructor->InstanceTemplate()->SetInternalFieldCount(1); Client_constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "connect", Connect); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "query", Query); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "end", Close); emit_symbol = NODE_PSYMBOL("emit"); target->Set(name, Client_constructor->GetFunction()); } }; static Handle<Value> Version(const Arguments& args) { HandleScope scope; unsigned long client_ver = mysql_get_client_version(); char major = (client_ver >> 16) & 0xFF, release = (client_ver >> 8) & 0xFF, rel_ver = client_ver & 0xFF; int slen = (major < 10 ? 1 : 2) + (release < 10 ? 1 : 2) + (rel_ver < 10 ? 1 : 2); char* ver = (char*) malloc(slen + 3); sprintf(ver, "%u.%u.%u", major, release, rel_ver); Local<String> ver_str = String::New(ver); free(ver); return scope.Close(ver_str); } extern "C" { void init(Handle<Object> target) { HandleScope scope; Client::Initialize(target); target->Set(String::NewSymbol("version"), FunctionTemplate::New(Version)->GetFunction()); } NODE_MODULE(sqlclient, init); }<|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2015-2019, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <fg/font.h> #include <fg/chart.h> #include <fg/exception.h> #include <common.hpp> #include <err_common.hpp> #include <math.h> #include <string> #include <sstream> #include <iomanip> #include <mutex> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std; typedef std::vector<std::string>::const_iterator StringIter; std::string toString(float pVal, const int n = 2) { std::ostringstream out; out << std::fixed << std::setprecision(n) << pVal; return out.str(); } const char *gChartVertexShaderSrc = "#version 330\n" "in vec2 point;\n" "uniform mat4 transform;\n" "void main(void) {\n" " gl_Position = transform * vec4(point.xy, 0, 1);\n" "}"; const char *gChartFragmentShaderSrc = "#version 330\n" "uniform vec4 color;\n" "out vec4 outputColor;\n" "void main(void) {\n" " outputColor = color;\n" "}"; const char *gChartSpriteFragmentShaderSrc = "#version 330\n" "uniform bool isYAxis;\n" "uniform vec4 tick_color;\n" "out vec4 outputColor;\n" "void main(void) {\n" " bool y_axis = isYAxis && abs(gl_PointCoord.y)>0.2;\n" " bool x_axis = !isYAxis && abs(gl_PointCoord.x)>0.2;\n" " if(y_axis || x_axis)\n" " discard;\n" " else\n" " outputColor = tick_color;\n" "}"; fg::Font& getChartFont() { static fg::Font mChartFont; static std::once_flag flag; std::call_once(flag, []() { mChartFont.loadSystemFont("Vera", 32); }); return mChartFont; } namespace fg { void Chart::bindBorderProgram() const { glUseProgram(mBorderProgram); } void Chart::unbindBorderProgram() const { glUseProgram(0); } GLuint Chart::rectangleVBO() const { return mDecorVBO; } GLuint Chart::borderProgramPointIndex() const { return mBorderPointIndex; } GLuint Chart::borderColorIndex() const { return mBorderColorIndex; } GLuint Chart::borderMatIndex() const { return mBorderMatIndex; } int Chart::tickSize() const { return mTickSize; } int Chart::leftMargin() const { return mLeftMargin; } int Chart::rightMargin() const { return mRightMargin; } int Chart::bottomMargin() const { return mBottomMargin; } int Chart::topMargin() const { return mTopMargin; } void Chart::setTickCount(int pTickCount) { static const float border[8] = { -1, -1, 1, -1, 1, 1, -1, 1 }; static const int nValues = sizeof(border)/sizeof(float); mTickCount = pTickCount; std::vector<float> decorData; std::copy(border, border+nValues, std::back_inserter(decorData)); float step = 2.0f/(mTickCount+1); float yRange = mYMax-mYMin; float xRange = mXMax-mXMin; /* push tick points for y axis */ for (int i = 1; i <= mTickCount; i++) { float temp = -1.0f+i*step; /* (-1,-1) to (-1, 1)*/ decorData.push_back(-1.0f); decorData.push_back(temp); /* push tick text marker coordinates and the display text */ mTickTextX.push_back(-1.0f); mTickTextY.push_back(temp); mTickText.push_back(toString(mYMin+i*step*yRange/2)); } /* push tick points for x axis */ for (int i = 1; i <= mTickCount; i++) { float temp = -1.0f+i*step; /* (-1,-1) to (1, -1)*/ decorData.push_back(-1.0f+i*step); decorData.push_back(-1); /* push tick text marker coordinates and the display text */ mTickTextX.push_back(temp); mTickTextY.push_back(-1.0f); mTickText.push_back(toString(mXMin+i*step*xRange/2)); } /* check if decoration VBO has been already used(case where * tick marks are being changed from default(21) */ if (mDecorVBO != 0) glDeleteBuffers(1, &mDecorVBO); /* create vbo that has the border and axis data */ mDecorVBO = createBuffer<float>(decorData.size(), &(decorData.front()), GL_STATIC_DRAW); glBindVertexArray(mDecorVAO); glBindBuffer(GL_ARRAY_BUFFER, mDecorVBO); glVertexAttribPointer(mBorderPointIndex, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(mBorderPointIndex); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } Chart::Chart() : mTickCount(13), mTickSize(10), mLeftMargin(50), mRightMargin(10), mTopMargin(10), mBottomMargin(20), mXMax(1), mXMin(0), mYMax(1), mYMin(0), mDecorVAO(0), mDecorVBO(0), mBorderProgram(0), mSpriteProgram(0) { /* load font Vera font for chart text * renderings, below function actually returns a constant * reference to font object used by Chart objects, we are * calling it here just to make sure required font glyphs * are loaded into the shared Font object */ getChartFont(); mBorderProgram = initShaders(gChartVertexShaderSrc, gChartFragmentShaderSrc); mSpriteProgram = initShaders(gChartVertexShaderSrc, gChartSpriteFragmentShaderSrc); mBorderPointIndex = glGetAttribLocation (mBorderProgram, "point"); mBorderColorIndex = glGetUniformLocation(mBorderProgram, "color"); mBorderMatIndex = glGetUniformLocation(mBorderProgram, "transform"); mSpriteTickcolorIndex = glGetUniformLocation(mSpriteProgram, "tick_color"); mSpriteMatIndex = glGetUniformLocation(mSpriteProgram, "transform"); mSpriteTickaxisIndex = glGetUniformLocation(mSpriteProgram, "isYAxis"); glGenVertexArrays(1, &mDecorVAO); /* the following function sets the member variable * mTickCount and creates VBO to hold tick marks and the corresponding * text markers for those ticks on the axes */ setTickCount(mTickCount); } Chart::~Chart() { CheckGL("Begin Chart::~Chart"); glDeleteBuffers(1, &mDecorVBO); glDeleteVertexArrays(1, &mDecorVAO); glDeleteProgram(mBorderProgram); glDeleteProgram(mSpriteProgram); CheckGL("End Chart::~Chart"); } double Chart::xmax() const { return mXMax; } double Chart::xmin() const { return mXMin; } double Chart::ymax() const { return mYMax; } double Chart::ymin() const { return mYMin; } void Chart::setAxesLimits(double pXmax, double pXmin, double pYmax, double pYmin) { mXMax = pXmax; mXMin = pXmin; mYMax = pYmax; mYMin = pYmin; /* based on maximum value on Y, set vertical axis margin * so that the text tick markers don't go beyond the * axis line */ std::string max_val_str = toString(mYMax); /* assuming each numeric literal occupies 10 pixels */ mLeftMargin = 10.0f * max_val_str.length(); /* remove all the tick text markers that were generated * by default during the base class(chart) creation and * update the text markers based on the new axes limits*/ mTickText.clear(); float step = 2.0f/(mTickCount+1); float yRange = mYMax-mYMin; float xRange = mXMax-mXMin; /* push tick points for y axis */ for (int i = 1; i <= mTickCount; i++) { float temp = (i*step)/2; mTickText.push_back(toString(mYMin+temp*yRange)); } /* push tick points for x axis */ for (int i = 1; i <= mTickCount; i++) { float temp = (i*step)/2; mTickText.push_back(toString(mXMin+temp*xRange)); } } void Chart::renderChart(int pVPW, int pVPH) const { float w = pVPW - (mLeftMargin + mRightMargin + mTickSize); float h = pVPH - (mTopMargin + mBottomMargin + mTickSize); float offset_x = (2.0f * (mLeftMargin+mTickSize) + (w - pVPW)) / pVPW; float offset_y = (2.0f * (mBottomMargin+mTickSize) + (h - pVPH)) / pVPH; float scale_x = w / pVPW; float scale_y = h / pVPH; CheckGL("Begin Chart::render"); /* bind the plotting shader program */ glUseProgram(mBorderProgram); /* set uniform attributes of shader * for drawing the plot borders */ glm::mat4 trans = glm::scale(glm::translate(glm::mat4(1), glm::vec3(offset_x, offset_y, 0)), glm::vec3(scale_x, scale_y, 1)); glUniformMatrix4fv(mBorderMatIndex, 1, GL_FALSE, glm::value_ptr(trans)); glUniform4fv(mBorderColorIndex, 1, WHITE); /* Draw borders */ glBindVertexArray(mDecorVAO); glDrawArrays(GL_LINE_LOOP, 0, 4); glBindVertexArray(0); /* reset shader program binding */ glUseProgram(0); /* bind the sprite shader program to * draw ticks on x and y axes */ glUseProgram(mSpriteProgram); glPointSize(mTickSize); glUniform4fv(mSpriteTickcolorIndex, 1, WHITE); glUniformMatrix4fv(mSpriteMatIndex, 1, GL_FALSE, glm::value_ptr(trans)); /* Draw tick marks on y axis */ glUniform1i(mSpriteTickaxisIndex, 1); glBindVertexArray(mDecorVAO); glDrawArrays(GL_POINTS, 4, mTickCount); glBindVertexArray(0); /* Draw tick marks on x axis */ glUniform1i(mSpriteTickaxisIndex, 0); glBindVertexArray(mDecorVAO); glDrawArrays(GL_POINTS, 4+mTickCount, mTickCount); glBindVertexArray(0); /* restoring point size to default */ glPointSize(1); /* reset shader program binding */ glUseProgram(0); fg::Font& fonter = getChartFont(); fonter.setOthro2D(pVPW, pVPH); for (StringIter it = mTickText.begin(); it!=mTickText.end(); ++it) { int idx = it - mTickText.begin(); float pos[2] = { pVPW*(mTickTextX[idx]+1)/2, pVPH*(mTickTextY[idx]+1)/2 }; fonter.render(pos, WHITE, *it, 14); } CheckGL("End Chart::render"); } } <commit_msg>Corrected chart tick marks projection matrix<commit_after>/******************************************************* * Copyright (c) 2015-2019, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <fg/font.h> #include <fg/chart.h> #include <fg/exception.h> #include <common.hpp> #include <err_common.hpp> #include <math.h> #include <string> #include <sstream> #include <iomanip> #include <mutex> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std; typedef std::vector<std::string>::const_iterator StringIter; std::string toString(float pVal, const int n = 2) { std::ostringstream out; out << std::fixed << std::setprecision(n) << pVal; return out.str(); } const char *gChartVertexShaderSrc = "#version 330\n" "in vec2 point;\n" "uniform mat4 transform;\n" "void main(void) {\n" " gl_Position = transform * vec4(point.xy, 0, 1);\n" "}"; const char *gChartFragmentShaderSrc = "#version 330\n" "uniform vec4 color;\n" "out vec4 outputColor;\n" "void main(void) {\n" " outputColor = color;\n" "}"; const char *gChartSpriteFragmentShaderSrc = "#version 330\n" "uniform bool isYAxis;\n" "uniform vec4 tick_color;\n" "out vec4 outputColor;\n" "void main(void) {\n" " bool y_axis = isYAxis && abs(gl_PointCoord.y)>0.2;\n" " bool x_axis = !isYAxis && abs(gl_PointCoord.x)>0.2;\n" " if(y_axis || x_axis)\n" " discard;\n" " else\n" " outputColor = tick_color;\n" "}"; fg::Font& getChartFont() { static fg::Font mChartFont; static std::once_flag flag; std::call_once(flag, []() { mChartFont.loadSystemFont("Vera", 32); }); return mChartFont; } namespace fg { void Chart::bindBorderProgram() const { glUseProgram(mBorderProgram); } void Chart::unbindBorderProgram() const { glUseProgram(0); } GLuint Chart::rectangleVBO() const { return mDecorVBO; } GLuint Chart::borderProgramPointIndex() const { return mBorderPointIndex; } GLuint Chart::borderColorIndex() const { return mBorderColorIndex; } GLuint Chart::borderMatIndex() const { return mBorderMatIndex; } int Chart::tickSize() const { return mTickSize; } int Chart::leftMargin() const { return mLeftMargin; } int Chart::rightMargin() const { return mRightMargin; } int Chart::bottomMargin() const { return mBottomMargin; } int Chart::topMargin() const { return mTopMargin; } void Chart::setTickCount(int pTickCount) { static const float border[8] = { -1, -1, 1, -1, 1, 1, -1, 1 }; static const int nValues = sizeof(border)/sizeof(float); mTickCount = pTickCount; std::vector<float> decorData; std::copy(border, border+nValues, std::back_inserter(decorData)); float step = 2.0f/(mTickCount+1); float yRange = mYMax-mYMin; float xRange = mXMax-mXMin; /* push tick points for y axis */ for (int i = 1; i <= mTickCount; i++) { float temp = -1.0f+i*step; /* (-1,-1) to (-1, 1)*/ decorData.push_back(-1.0f); decorData.push_back(temp); /* push tick text marker coordinates and the display text */ mTickTextX.push_back(-1.0f); mTickTextY.push_back(temp); mTickText.push_back(toString(mYMin+i*step*yRange/2)); } /* push tick points for x axis */ for (int i = 1; i <= mTickCount; i++) { float temp = -1.0f+i*step; /* (-1,-1) to (1, -1)*/ decorData.push_back(-1.0f+i*step); decorData.push_back(-1); /* push tick text marker coordinates and the display text */ mTickTextX.push_back(temp); mTickTextY.push_back(-1.0f); mTickText.push_back(toString(mXMin+i*step*xRange/2)); } /* check if decoration VBO has been already used(case where * tick marks are being changed from default(21) */ if (mDecorVBO != 0) glDeleteBuffers(1, &mDecorVBO); /* create vbo that has the border and axis data */ mDecorVBO = createBuffer<float>(decorData.size(), &(decorData.front()), GL_STATIC_DRAW); glBindVertexArray(mDecorVAO); glBindBuffer(GL_ARRAY_BUFFER, mDecorVBO); glVertexAttribPointer(mBorderPointIndex, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(mBorderPointIndex); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } Chart::Chart() : mTickCount(8), mTickSize(10), mLeftMargin(50), mRightMargin(10), mTopMargin(10), mBottomMargin(20), mXMax(1), mXMin(0), mYMax(1), mYMin(0), mDecorVAO(0), mDecorVBO(0), mBorderProgram(0), mSpriteProgram(0) { /* load font Vera font for chart text * renderings, below function actually returns a constant * reference to font object used by Chart objects, we are * calling it here just to make sure required font glyphs * are loaded into the shared Font object */ getChartFont(); mBorderProgram = initShaders(gChartVertexShaderSrc, gChartFragmentShaderSrc); mSpriteProgram = initShaders(gChartVertexShaderSrc, gChartSpriteFragmentShaderSrc); mBorderPointIndex = glGetAttribLocation (mBorderProgram, "point"); mBorderColorIndex = glGetUniformLocation(mBorderProgram, "color"); mBorderMatIndex = glGetUniformLocation(mBorderProgram, "transform"); mSpriteTickcolorIndex = glGetUniformLocation(mSpriteProgram, "tick_color"); mSpriteMatIndex = glGetUniformLocation(mSpriteProgram, "transform"); mSpriteTickaxisIndex = glGetUniformLocation(mSpriteProgram, "isYAxis"); glGenVertexArrays(1, &mDecorVAO); /* the following function sets the member variable * mTickCount and creates VBO to hold tick marks and the corresponding * text markers for those ticks on the axes */ setTickCount(mTickCount); } Chart::~Chart() { CheckGL("Begin Chart::~Chart"); glDeleteBuffers(1, &mDecorVBO); glDeleteVertexArrays(1, &mDecorVAO); glDeleteProgram(mBorderProgram); glDeleteProgram(mSpriteProgram); CheckGL("End Chart::~Chart"); } double Chart::xmax() const { return mXMax; } double Chart::xmin() const { return mXMin; } double Chart::ymax() const { return mYMax; } double Chart::ymin() const { return mYMin; } void Chart::setAxesLimits(double pXmax, double pXmin, double pYmax, double pYmin) { mXMax = pXmax; mXMin = pXmin; mYMax = pYmax; mYMin = pYmin; /* based on maximum value on Y, set vertical axis margin * so that the text tick markers don't go beyond the * axis line */ std::string max_val_str = toString(mYMax); /* assuming each numeric literal occupies 10 pixels */ mLeftMargin = 10.0f * max_val_str.length(); /* remove all the tick text markers that were generated * by default during the base class(chart) creation and * update the text markers based on the new axes limits*/ mTickText.clear(); float step = 2.0f/(mTickCount+1); float yRange = mYMax-mYMin; float xRange = mXMax-mXMin; /* push tick points for y axis */ for (int i = 1; i <= mTickCount; i++) { float temp = (i*step)/2; mTickText.push_back(toString(mYMin+temp*yRange)); } /* push tick points for x axis */ for (int i = 1; i <= mTickCount; i++) { float temp = (i*step)/2; mTickText.push_back(toString(mXMin+temp*xRange)); } } void Chart::renderChart(int pVPW, int pVPH) const { float w = pVPW - (mLeftMargin + mRightMargin + mTickSize); float h = pVPH - (mTopMargin + mBottomMargin + mTickSize); float offset_x = (2.0f * (mLeftMargin+mTickSize) + (w - pVPW)) / pVPW; float offset_y = (2.0f * (mBottomMargin+mTickSize) + (h - pVPH)) / pVPH; float scale_x = w / pVPW; float scale_y = h / pVPH; CheckGL("Begin Chart::render"); /* bind the plotting shader program */ glUseProgram(mBorderProgram); /* set uniform attributes of shader * for drawing the plot borders */ glm::mat4 trans = glm::scale(glm::translate(glm::mat4(1), glm::vec3(offset_x, offset_y, 0)), glm::vec3(scale_x, scale_y, 1)); glUniformMatrix4fv(mBorderMatIndex, 1, GL_FALSE, glm::value_ptr(trans)); glUniform4fv(mBorderColorIndex, 1, WHITE); /* Draw borders */ glBindVertexArray(mDecorVAO); glDrawArrays(GL_LINE_LOOP, 0, 4); glBindVertexArray(0); /* reset shader program binding */ glUseProgram(0); /* bind the sprite shader program to * draw ticks on x and y axes */ glUseProgram(mSpriteProgram); glPointSize(mTickSize); glUniform4fv(mSpriteTickcolorIndex, 1, WHITE); glUniformMatrix4fv(mSpriteMatIndex, 1, GL_FALSE, glm::value_ptr(trans)); /* Draw tick marks on y axis */ glUniform1i(mSpriteTickaxisIndex, 1); glBindVertexArray(mDecorVAO); glDrawArrays(GL_POINTS, 4, mTickCount); glBindVertexArray(0); /* Draw tick marks on x axis */ glUniform1i(mSpriteTickaxisIndex, 0); glBindVertexArray(mDecorVAO); glDrawArrays(GL_POINTS, 4+mTickCount, mTickCount); glBindVertexArray(0); /* restoring point size to default */ glPointSize(1); /* reset shader program binding */ glUseProgram(0); fg::Font& fonter = getChartFont(); fonter.setOthro2D(w, h); for (StringIter it = mTickText.begin(); it!=mTickText.end(); ++it) { int idx = it - mTickText.begin(); float pos[2] = { w*(mTickTextX[idx]+1)/2, h*(mTickTextY[idx]+1)/2 }; fonter.render(pos, WHITE, *it, 15); } CheckGL("End Chart::render"); } } <|endoftext|>
<commit_before>/* * This file is part of the chess-at-nite project [chess-at-nite.googlecode.com] * * Copyright (c) 2009-2010 by * Franziskus Domig * Panayiotis Lipiridis * Radoslav Petrik * Thai Gia Tuong * * For the full copyright and license information, please visit: * http://chess-at-nite.googlecode.com/svn/trunk/doc/LICENSE */ #include "common/globals.h" #include <iostream> #include <string> #include <vector> #include <stdlib.h> #ifdef WIN32 #include <conio.h> #else #include "common/unixio.c" #endif #include "common/define.h" #include "model/MoveGenerator.h" #include "model/Game.h" #include "player/Player.h" #include "player/HumanPlayer.h" #include "player/ComputerPlayer.h" #include "control/CLI.h" #include "common/extra_utils.h" #include "control/PGN.h" #include "control/XBoard.h" void test(); int main(int argc, char **argv) { #ifdef DEBUG cerr << "!!!!!!!!!!!!!!!!!!!!!!!!\n"; cerr << "!!! DEBUG MODE IS ON !!!\n"; cerr << "!!!!!!!!!!!!!!!!!!!!!!!!\n"; #endif srand(time(NULL)); init_globals(); bool xboard_mode = false; int user_option = 0; if (argc > 1) { string tmp(argv[1]); if (tmp == "xboard") { xboard_mode = true; } else { user_option = atoi(argv[1]); } } else { //check cin for "xboard" message string inp; int check_time = get_ms() + 5000; //check for 500 msecs while(get_ms() < check_time) { #ifdef WIN32 if(kbhit()) { char ch = getch(); #else int chi; if(kbdhit(&chi)) { char ch = char(chi); #endif inp += ch; if(inp == "xboard") { xboard_mode = true; break; } } } } #ifdef COMMAND_LINE if (xboard_mode) { XBoard xboard; xboard.start(); } else if (user_option > 0) { CLI cli(user_option); } else { CLI cli; } #else // for testing test(); #endif return 0; } /* * For testing purposes during developing. */ void test() { string default_board = DEFAULT_FEN; default_board = "5q2/k113PP/2Q5/8/2K4r/3P4/4P3/8 w - - 0 20"; default_board = "8/4p3/k3p3/4P3/8/K7/8/8 w - - 0 100"; default_board = "bn6/8/k3p3/4P3/8/K7/8/BN6 w - - 0 100"; //Bishop and knight checkmate (wikipedia) //white to move will checkmate black! default_board = "7k/8/5K2/4N3/8/3B4/8/8 w - - 0 1"; //Deletang's second triangle default_board = "3k4/8/4K3/1B1N4/8/8/8/8 w - - 0 1"; //two Queens vs a Queen.. default_board = "6k1/5qq1/8/8/8/8/Q7/4K3 w - - 0 1"; default_board = DEFAULT_FEN; Board board = Board(default_board); Player* white_player = new HumanPlayer(); Player* black_player = new ComputerPlayer(); Game game = Game(&board, white_player, black_player); game.start_game(); delete white_player; delete black_player; } <commit_msg>commented out some Unix specific code (additional dependancies to other library)<commit_after>/* * This file is part of the chess-at-nite project [chess-at-nite.googlecode.com] * * Copyright (c) 2009-2010 by * Franziskus Domig * Panayiotis Lipiridis * Radoslav Petrik * Thai Gia Tuong * * For the full copyright and license information, please visit: * http://chess-at-nite.googlecode.com/svn/trunk/doc/LICENSE */ #include "common/globals.h" #include <iostream> #include <string> #include <vector> #include <stdlib.h> #ifdef WIN32 #include <conio.h> #else //#include "common/unixio.h" //for future use #endif #include "common/define.h" #include "model/MoveGenerator.h" #include "model/Game.h" #include "player/Player.h" #include "player/HumanPlayer.h" #include "player/ComputerPlayer.h" #include "control/CLI.h" #include "common/extra_utils.h" #include "control/PGN.h" #include "control/XBoard.h" void test(); int main(int argc, char **argv) { #ifdef DEBUG cerr << "!!!!!!!!!!!!!!!!!!!!!!!!\n"; cerr << "!!! DEBUG MODE IS ON !!!\n"; cerr << "!!!!!!!!!!!!!!!!!!!!!!!!\n"; #endif srand(time(NULL)); init_globals(); bool xboard_mode = false; int user_option = 0; if (argc > 1) { string tmp(argv[1]); if (tmp == "xboard") { xboard_mode = true; } else { user_option = atoi(argv[1]); } } else { //check cin for "xboard" message string inp; int check_time = get_ms() + 500; //check for 500 msecs while(get_ms() < check_time) { #ifdef WIN32 if(kbhit()) { char ch = getch(); #else int chi; if(false) //kbdhit(&chi)) //for future usage { char ch = char(chi); #endif inp += ch; if(inp == "xboard") { xboard_mode = true; break; } } } } #ifdef COMMAND_LINE if (xboard_mode) { XBoard xboard; xboard.start(); } else if (user_option > 0) { CLI cli(user_option); } else { CLI cli; } #else // for testing test(); #endif return 0; } /* * For testing purposes during developing. */ void test() { string default_board = DEFAULT_FEN; default_board = "5q2/k113PP/2Q5/8/2K4r/3P4/4P3/8 w - - 0 20"; default_board = "8/4p3/k3p3/4P3/8/K7/8/8 w - - 0 100"; default_board = "bn6/8/k3p3/4P3/8/K7/8/BN6 w - - 0 100"; //Bishop and knight checkmate (wikipedia) //white to move will checkmate black! default_board = "7k/8/5K2/4N3/8/3B4/8/8 w - - 0 1"; //Deletang's second triangle default_board = "3k4/8/4K3/1B1N4/8/8/8/8 w - - 0 1"; //two Queens vs a Queen.. default_board = "6k1/5qq1/8/8/8/8/Q7/4K3 w - - 0 1"; default_board = DEFAULT_FEN; Board board = Board(default_board); Player* white_player = new HumanPlayer(); Player* black_player = new ComputerPlayer(); Game game = Game(&board, white_player, black_player); game.start_game(); delete white_player; delete black_player; } <|endoftext|>
<commit_before>#include "client.hh" #include "face_registry.hh" #include "context.hh" #include "buffer_manager.hh" #include "buffer_utils.hh" #include "file.hh" #include "remote.hh" #include "option.hh" #include "client_manager.hh" #include "command_manager.hh" #include "event_manager.hh" #include "user_interface.hh" #include "window.hh" #include "hash_map.hh" #include <csignal> #include <unistd.h> #include <utility> namespace Kakoune { Client::Client(std::unique_ptr<UserInterface>&& ui, std::unique_ptr<Window>&& window, SelectionList selections, int pid, EnvVarMap env_vars, String name, OnExitCallback on_exit) : m_ui{std::move(ui)}, m_window{std::move(window)}, m_pid{pid}, m_on_exit{std::move(on_exit)}, m_input_handler{std::move(selections), Context::Flags::None, std::move(name)}, m_env_vars(std::move(env_vars)) { m_window->set_client(this); context().set_client(*this); context().set_window(*m_window); m_window->set_dimensions(m_ui->dimensions()); m_window->options().register_watcher(*this); m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); m_ui->set_on_key([this](Key key) { if (key == ctrl('c')) killpg(getpgrp(), SIGINT); else m_pending_keys.push_back(key); }); m_window->hooks().run_hook("WinDisplay", m_window->buffer().name(), context()); force_redraw(); } Client::~Client() { m_window->options().unregister_watcher(*this); m_window->set_client(nullptr); // Do not move the selections here, as we need them to be valid // in order to correctly destroy the input handler ClientManager::instance().add_free_window(std::move(m_window), context().selections()); } bool Client::process_pending_inputs() { const bool debug_keys = (bool)(context().options()["debug"].get<DebugFlags>() & DebugFlags::Keys); // steal keys as we might receive new keys while handling them. Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys); for (auto& key : keys) { try { if (debug_keys) write_to_debug_buffer(format("Client '{}' got key '{}'", context().name(), key_to_str(key))); if (key == Key::FocusIn) context().hooks().run_hook("FocusIn", context().name(), context()); else if (key == Key::FocusOut) context().hooks().run_hook("FocusOut", context().name(), context()); else if (key.modifiers == Key::Modifiers::Resize) { m_window->set_dimensions(m_ui->dimensions()); force_redraw(); } else m_input_handler.handle_key(key); context().hooks().run_hook("RawKey", key_to_str(key), context()); } catch (Kakoune::runtime_error& error) { write_to_debug_buffer(format("Error: {}", error.what())); context().print_status({ fix_atom_text(error.what().str()), get_face("Error") }); context().hooks().run_hook("RuntimeError", error.what(), context()); } } return not keys.empty(); } void Client::print_status(DisplayLine status_line, bool immediate) { m_status_line = std::move(status_line); if (immediate) { m_ui->draw_status(m_status_line, m_mode_line, get_face("StatusLine")); m_ui->refresh(true); } else { m_ui_pending |= StatusLine; } } DisplayCoord Client::dimensions() const { return m_ui->dimensions(); } String generate_context_info(const Context& context) { String s = ""; if (context.buffer().is_modified()) s += "[+]"; if (context.client().input_handler().is_recording()) s += format("[recording ({})]", context.client().input_handler().recording_reg()); if (context.buffer().flags() & Buffer::Flags::New) s += "[new file]"; if (context.hooks_disabled()) s += "[no-hooks]"; if (context.buffer().flags() & Buffer::Flags::Fifo) s += "[fifo]"; return s; } DisplayLine Client::generate_mode_line() const { DisplayLine modeline; try { const String& modelinefmt = context().options()["modelinefmt"].get<String>(); HashMap<String, DisplayLine> atoms{{ "mode_info", context().client().input_handler().mode_line() }, { "context_info", {generate_context_info(context()), get_face("Information")}}}; auto expanded = expand(modelinefmt, context(), ShellContext{}, [](String s) { return escape(s, '{', '\\'); }); modeline = parse_display_line(expanded, atoms); } catch (runtime_error& err) { write_to_debug_buffer(format("Error while parsing modelinefmt: {}", err.what())); modeline.push_back({ "modelinefmt error, see *debug* buffer", get_face("Error") }); } return modeline; } void Client::change_buffer(Buffer& buffer) { if (m_buffer_reload_dialog_opened) close_buffer_reload_dialog(); auto* current = &m_window->buffer(); m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr; auto& client_manager = ClientManager::instance(); m_window->options().unregister_watcher(*this); m_window->set_client(nullptr); client_manager.add_free_window(std::move(m_window), std::move(context().selections())); WindowAndSelections ws = client_manager.get_free_window(buffer); m_window = std::move(ws.window); m_window->set_client(this); m_window->options().register_watcher(*this); m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); context().selections_write_only() = std::move(ws.selections); context().set_window(*m_window); m_window->set_dimensions(m_ui->dimensions()); m_window->hooks().run_hook("WinDisplay", buffer.name(), context()); force_redraw(); } static bool is_inline(InfoStyle style) { return style == InfoStyle::Inline or style == InfoStyle::InlineAbove or style == InfoStyle::InlineBelow; } void Client::redraw_ifn() { Window& window = context().window(); if (window.needs_redraw(context())) m_ui_pending |= Draw; DisplayLine mode_line = generate_mode_line(); if (mode_line.atoms() != m_mode_line.atoms()) { m_ui_pending |= StatusLine; m_mode_line = std::move(mode_line); } if (m_ui_pending == 0) return; if (m_ui_pending & Draw) m_ui->draw(window.update_display_buffer(context()), get_face("Default"), get_face("BufferPadding")); const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and not m_menu.items.empty() and m_menu.style == MenuStyle::Inline; if ((m_ui_pending & MenuShow) or update_menu_anchor) { auto anchor = m_menu.style == MenuStyle::Inline ? window.display_position(m_menu.anchor) : DisplayCoord{}; if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor) m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide; m_menu.ui_anchor = anchor; } if (m_ui_pending & MenuShow and m_menu.ui_anchor) m_ui->menu_show(m_menu.items, *m_menu.ui_anchor, get_face("MenuForeground"), get_face("MenuBackground"), m_menu.style); if (m_ui_pending & MenuSelect and m_menu.ui_anchor) m_ui->menu_select(m_menu.selected); if (m_ui_pending & MenuHide) m_ui->menu_hide(); const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and not m_info.content.empty() and is_inline(m_info.style); if ((m_ui_pending & InfoShow) or update_info_anchor) { auto anchor = is_inline(m_info.style) ? window.display_position(m_info.anchor) : DisplayCoord{}; if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor) m_ui_pending |= anchor ? InfoShow : InfoHide; m_info.ui_anchor = anchor; } if (m_ui_pending & InfoShow and m_info.ui_anchor) m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor, get_face("Information"), m_info.style); if (m_ui_pending & InfoHide) m_ui->info_hide(); if (m_ui_pending & StatusLine) m_ui->draw_status(m_status_line, m_mode_line, get_face("StatusLine")); auto cursor = m_input_handler.get_cursor_info(); m_ui->set_cursor(cursor.first, cursor.second); m_ui->refresh(m_ui_pending | Refresh); m_ui_pending = 0; } void Client::force_redraw() { m_ui_pending |= Refresh | Draw | StatusLine | (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) | (m_info.content.empty() ? InfoHide : InfoShow); } void Client::reload_buffer() { Buffer& buffer = context().buffer(); reload_file_buffer(buffer); context().print_status({ format("'{}' reloaded", buffer.display_name()), get_face("Information") }); } void Client::on_buffer_reload_key(Key key) { auto& buffer = context().buffer(); if (key == 'y' or key == Key::Return) reload_buffer(); else if (key == 'n' or key == Key::Escape) { // reread timestamp in case the file was modified again buffer.set_fs_timestamp(get_fs_timestamp(buffer.name())); print_status({ format("'{}' kept", buffer.display_name()), get_face("Information") }); } else { print_status({ format("'{}' is not a valid choice", key_to_str(key)), get_face("Error") }); m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); return; } for (auto& client : ClientManager::instance()) { if (&client->context().buffer() == &buffer and client->m_buffer_reload_dialog_opened) client->close_buffer_reload_dialog(); } } void Client::close_buffer_reload_dialog() { kak_assert(m_buffer_reload_dialog_opened); m_buffer_reload_dialog_opened = false; info_hide(true); m_input_handler.reset_normal_mode(); } void Client::check_if_buffer_needs_reloading() { if (m_buffer_reload_dialog_opened) return; Buffer& buffer = context().buffer(); auto reload = context().options()["autoreload"].get<Autoreload>(); if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No) return; const String& filename = buffer.name(); timespec ts = get_fs_timestamp(filename); if (ts == InvalidTime or ts == buffer.fs_timestamp()) return; if (reload == Autoreload::Ask) { StringView bufname = buffer.display_name(); info_show(format("reload '{}' ?", bufname), format("'{}' was modified externally\n" "press <ret> or y to reload, <esc> or n to keep", bufname), {}, InfoStyle::Modal); m_buffer_reload_dialog_opened = true; m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); } else reload_buffer(); } StringView Client::get_env_var(StringView name) const { auto it = m_env_vars.find(name); if (it == m_env_vars.end()) return {}; return it->value; } void Client::on_option_changed(const Option& option) { if (option.name() == "ui_options") { m_ui->set_ui_options(option.get<UserInterface::Options>()); m_ui_pending |= Draw; } } void Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style) { m_menu = Menu{ std::move(choices), anchor, {}, style, -1 }; m_ui_pending |= MenuShow; m_ui_pending &= ~MenuHide; } void Client::menu_select(int selected) { m_menu.selected = selected; m_ui_pending |= MenuSelect; m_ui_pending &= ~MenuHide; } void Client::menu_hide() { m_menu = Menu{}; m_ui_pending |= MenuHide; m_ui_pending &= ~(MenuShow | MenuSelect); } void Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style) { if (m_info.style == InfoStyle::Modal) // We already have a modal info opened, do not touch it. return; m_info = Info{ std::move(title), std::move(content), anchor, {}, style }; m_ui_pending |= InfoShow; m_ui_pending &= ~InfoHide; } void Client::info_hide(bool even_modal) { if (not even_modal and m_info.style == InfoStyle::Modal) return; m_info = Info{}; m_ui_pending |= InfoHide; m_ui_pending &= ~InfoShow; } } <commit_msg>Add '[debug]' context_info for debug buffers<commit_after>#include "client.hh" #include "face_registry.hh" #include "context.hh" #include "buffer_manager.hh" #include "buffer_utils.hh" #include "file.hh" #include "remote.hh" #include "option.hh" #include "client_manager.hh" #include "command_manager.hh" #include "event_manager.hh" #include "user_interface.hh" #include "window.hh" #include "hash_map.hh" #include <csignal> #include <unistd.h> #include <utility> namespace Kakoune { Client::Client(std::unique_ptr<UserInterface>&& ui, std::unique_ptr<Window>&& window, SelectionList selections, int pid, EnvVarMap env_vars, String name, OnExitCallback on_exit) : m_ui{std::move(ui)}, m_window{std::move(window)}, m_pid{pid}, m_on_exit{std::move(on_exit)}, m_input_handler{std::move(selections), Context::Flags::None, std::move(name)}, m_env_vars(std::move(env_vars)) { m_window->set_client(this); context().set_client(*this); context().set_window(*m_window); m_window->set_dimensions(m_ui->dimensions()); m_window->options().register_watcher(*this); m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); m_ui->set_on_key([this](Key key) { if (key == ctrl('c')) killpg(getpgrp(), SIGINT); else m_pending_keys.push_back(key); }); m_window->hooks().run_hook("WinDisplay", m_window->buffer().name(), context()); force_redraw(); } Client::~Client() { m_window->options().unregister_watcher(*this); m_window->set_client(nullptr); // Do not move the selections here, as we need them to be valid // in order to correctly destroy the input handler ClientManager::instance().add_free_window(std::move(m_window), context().selections()); } bool Client::process_pending_inputs() { const bool debug_keys = (bool)(context().options()["debug"].get<DebugFlags>() & DebugFlags::Keys); // steal keys as we might receive new keys while handling them. Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys); for (auto& key : keys) { try { if (debug_keys) write_to_debug_buffer(format("Client '{}' got key '{}'", context().name(), key_to_str(key))); if (key == Key::FocusIn) context().hooks().run_hook("FocusIn", context().name(), context()); else if (key == Key::FocusOut) context().hooks().run_hook("FocusOut", context().name(), context()); else if (key.modifiers == Key::Modifiers::Resize) { m_window->set_dimensions(m_ui->dimensions()); force_redraw(); } else m_input_handler.handle_key(key); context().hooks().run_hook("RawKey", key_to_str(key), context()); } catch (Kakoune::runtime_error& error) { write_to_debug_buffer(format("Error: {}", error.what())); context().print_status({ fix_atom_text(error.what().str()), get_face("Error") }); context().hooks().run_hook("RuntimeError", error.what(), context()); } } return not keys.empty(); } void Client::print_status(DisplayLine status_line, bool immediate) { m_status_line = std::move(status_line); if (immediate) { m_ui->draw_status(m_status_line, m_mode_line, get_face("StatusLine")); m_ui->refresh(true); } else { m_ui_pending |= StatusLine; } } DisplayCoord Client::dimensions() const { return m_ui->dimensions(); } String generate_context_info(const Context& context) { String s = ""; if (context.buffer().is_modified()) s += "[+]"; if (context.client().input_handler().is_recording()) s += format("[recording ({})]", context.client().input_handler().recording_reg()); if (context.buffer().flags() & Buffer::Flags::New) s += "[new file]"; if (context.hooks_disabled()) s += "[no-hooks]"; if (context.buffer().flags() & Buffer::Flags::Fifo) s += "[fifo]"; if (context.buffer().flags() & Buffer::Flags::Debug) s += "[debug]"; return s; } DisplayLine Client::generate_mode_line() const { DisplayLine modeline; try { const String& modelinefmt = context().options()["modelinefmt"].get<String>(); HashMap<String, DisplayLine> atoms{{ "mode_info", context().client().input_handler().mode_line() }, { "context_info", {generate_context_info(context()), get_face("Information")}}}; auto expanded = expand(modelinefmt, context(), ShellContext{}, [](String s) { return escape(s, '{', '\\'); }); modeline = parse_display_line(expanded, atoms); } catch (runtime_error& err) { write_to_debug_buffer(format("Error while parsing modelinefmt: {}", err.what())); modeline.push_back({ "modelinefmt error, see *debug* buffer", get_face("Error") }); } return modeline; } void Client::change_buffer(Buffer& buffer) { if (m_buffer_reload_dialog_opened) close_buffer_reload_dialog(); auto* current = &m_window->buffer(); m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr; auto& client_manager = ClientManager::instance(); m_window->options().unregister_watcher(*this); m_window->set_client(nullptr); client_manager.add_free_window(std::move(m_window), std::move(context().selections())); WindowAndSelections ws = client_manager.get_free_window(buffer); m_window = std::move(ws.window); m_window->set_client(this); m_window->options().register_watcher(*this); m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); context().selections_write_only() = std::move(ws.selections); context().set_window(*m_window); m_window->set_dimensions(m_ui->dimensions()); m_window->hooks().run_hook("WinDisplay", buffer.name(), context()); force_redraw(); } static bool is_inline(InfoStyle style) { return style == InfoStyle::Inline or style == InfoStyle::InlineAbove or style == InfoStyle::InlineBelow; } void Client::redraw_ifn() { Window& window = context().window(); if (window.needs_redraw(context())) m_ui_pending |= Draw; DisplayLine mode_line = generate_mode_line(); if (mode_line.atoms() != m_mode_line.atoms()) { m_ui_pending |= StatusLine; m_mode_line = std::move(mode_line); } if (m_ui_pending == 0) return; if (m_ui_pending & Draw) m_ui->draw(window.update_display_buffer(context()), get_face("Default"), get_face("BufferPadding")); const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and not m_menu.items.empty() and m_menu.style == MenuStyle::Inline; if ((m_ui_pending & MenuShow) or update_menu_anchor) { auto anchor = m_menu.style == MenuStyle::Inline ? window.display_position(m_menu.anchor) : DisplayCoord{}; if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor) m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide; m_menu.ui_anchor = anchor; } if (m_ui_pending & MenuShow and m_menu.ui_anchor) m_ui->menu_show(m_menu.items, *m_menu.ui_anchor, get_face("MenuForeground"), get_face("MenuBackground"), m_menu.style); if (m_ui_pending & MenuSelect and m_menu.ui_anchor) m_ui->menu_select(m_menu.selected); if (m_ui_pending & MenuHide) m_ui->menu_hide(); const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and not m_info.content.empty() and is_inline(m_info.style); if ((m_ui_pending & InfoShow) or update_info_anchor) { auto anchor = is_inline(m_info.style) ? window.display_position(m_info.anchor) : DisplayCoord{}; if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor) m_ui_pending |= anchor ? InfoShow : InfoHide; m_info.ui_anchor = anchor; } if (m_ui_pending & InfoShow and m_info.ui_anchor) m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor, get_face("Information"), m_info.style); if (m_ui_pending & InfoHide) m_ui->info_hide(); if (m_ui_pending & StatusLine) m_ui->draw_status(m_status_line, m_mode_line, get_face("StatusLine")); auto cursor = m_input_handler.get_cursor_info(); m_ui->set_cursor(cursor.first, cursor.second); m_ui->refresh(m_ui_pending | Refresh); m_ui_pending = 0; } void Client::force_redraw() { m_ui_pending |= Refresh | Draw | StatusLine | (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) | (m_info.content.empty() ? InfoHide : InfoShow); } void Client::reload_buffer() { Buffer& buffer = context().buffer(); reload_file_buffer(buffer); context().print_status({ format("'{}' reloaded", buffer.display_name()), get_face("Information") }); } void Client::on_buffer_reload_key(Key key) { auto& buffer = context().buffer(); if (key == 'y' or key == Key::Return) reload_buffer(); else if (key == 'n' or key == Key::Escape) { // reread timestamp in case the file was modified again buffer.set_fs_timestamp(get_fs_timestamp(buffer.name())); print_status({ format("'{}' kept", buffer.display_name()), get_face("Information") }); } else { print_status({ format("'{}' is not a valid choice", key_to_str(key)), get_face("Error") }); m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); return; } for (auto& client : ClientManager::instance()) { if (&client->context().buffer() == &buffer and client->m_buffer_reload_dialog_opened) client->close_buffer_reload_dialog(); } } void Client::close_buffer_reload_dialog() { kak_assert(m_buffer_reload_dialog_opened); m_buffer_reload_dialog_opened = false; info_hide(true); m_input_handler.reset_normal_mode(); } void Client::check_if_buffer_needs_reloading() { if (m_buffer_reload_dialog_opened) return; Buffer& buffer = context().buffer(); auto reload = context().options()["autoreload"].get<Autoreload>(); if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No) return; const String& filename = buffer.name(); timespec ts = get_fs_timestamp(filename); if (ts == InvalidTime or ts == buffer.fs_timestamp()) return; if (reload == Autoreload::Ask) { StringView bufname = buffer.display_name(); info_show(format("reload '{}' ?", bufname), format("'{}' was modified externally\n" "press <ret> or y to reload, <esc> or n to keep", bufname), {}, InfoStyle::Modal); m_buffer_reload_dialog_opened = true; m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); } else reload_buffer(); } StringView Client::get_env_var(StringView name) const { auto it = m_env_vars.find(name); if (it == m_env_vars.end()) return {}; return it->value; } void Client::on_option_changed(const Option& option) { if (option.name() == "ui_options") { m_ui->set_ui_options(option.get<UserInterface::Options>()); m_ui_pending |= Draw; } } void Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style) { m_menu = Menu{ std::move(choices), anchor, {}, style, -1 }; m_ui_pending |= MenuShow; m_ui_pending &= ~MenuHide; } void Client::menu_select(int selected) { m_menu.selected = selected; m_ui_pending |= MenuSelect; m_ui_pending &= ~MenuHide; } void Client::menu_hide() { m_menu = Menu{}; m_ui_pending |= MenuHide; m_ui_pending &= ~(MenuShow | MenuSelect); } void Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style) { if (m_info.style == InfoStyle::Modal) // We already have a modal info opened, do not touch it. return; m_info = Info{ std::move(title), std::move(content), anchor, {}, style }; m_ui_pending |= InfoShow; m_ui_pending &= ~InfoHide; } void Client::info_hide(bool even_modal) { if (not even_modal and m_info.style == InfoStyle::Modal) return; m_info = Info{}; m_ui_pending |= InfoHide; m_ui_pending &= ~InfoShow; } } <|endoftext|>
<commit_before>#include <coffee/core/CUnitTesting> #include <coffee/core/CFiles> using namespace Coffee; using namespace CResources; const constexpr sbyte_t probe_text[25] = "I'M THE TRASHMAN! Hello."; bool resource_exist_test() { { Resource rsc("the-one-that-works", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests limitations in implementation for names */ if(!FileExists(rsc)) return false; } { Resource rsc("filled-dir/subdir/we-need-to-go-deeper/odd-file-with-long-extension.txt.zip.exe", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests limitations in implementation for names */ if(!FileExists(rsc)) return false; } { Resource rsc("filled-dir/subdir/we-need-to-go-deeper/Spaced filename.txt", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests errors in scripts regarding spaces */ if(!FileExists(rsc)) return false; } return true; } const constexpr cstring filename_odd = "Oddball: æøå, カケ"; bool resource_exists_odd_characters_test() { Resource rsc(filename_odd, ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests what happens to unexpected characters. We want these to work. */ /* If existence passes, we assume the rest works too for these cases. */ return FileExists(rsc); } const constexpr cstring filename_testable = "filled-dir/subdir/we-need-to-go-deeper/odd-file-with-long-extension.txt.zip.exe"; bool resource_read_test() { Resource rsc(filename_testable, ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FilePull(rsc)) return false; if(sizeof(probe_text)-1 != rsc.size || !MemCmp(rsc.data,probe_text,rsc.size)) { cDebug("Sizes: {0} ?= {1}",sizeof(probe_text),rsc.size); cDebug("Data:\n" "Internal: {0}\n" "Resource: {1}\n", StrUtil::hexdump(probe_text,sizeof(probe_text)), StrUtil::hexdump(rsc.data,rsc.size)); return false; } FileFree(rsc); return true; } bool resource_map_test() { Resource rsc("Oddball: æøå, カケ", ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FileMap(rsc,ResourceAccess::ReadOnly)) return false; if(!FileUnmap(rsc)) return false; return true; } bool resource_write_test() { Resource rsc("Oddball: æøå, カケ", ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FileMap(rsc,ResourceAccess::ReadWrite)) return false; if(!FileUnmap(rsc)) return false; return true; } const constexpr CoffeeTest::Test _tests[10] = { {resource_exist_test, "Resource existence", "Test whether the resources are there"}, {resource_read_test, "Resource reading", "Opening and reading a resource, uses an odd filename"}, /* The ones below only test feature sets */ {resource_exists_odd_characters_test, "Gettin weird with filenames", "Test what happens with multibyte characters",true}, {resource_map_test, "Resource mapping", "If the resources are mappable",true}, {resource_write_test, "Resource writing", "If the resources are writable",true}, }; COFFEE_RUN_TESTS(_tests); <commit_msg> - Make packaging-api/test01 more friendly to Win32 by dumbing it down<commit_after>#include <coffee/core/CUnitTesting> #include <coffee/core/CFiles> using namespace Coffee; using namespace CResources; const constexpr sbyte_t probe_text[25] = "I'M THE TRASHMAN! Hello."; bool resource_exist_test() { { Resource rsc("the-one-that-works", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests limitations in implementation for names */ if(!FileExists(rsc)) return false; } { Resource rsc("filled-dir/subdir/we-need-to-go-deeper/odd-file-with-long-extension.txt.zip.exe", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests limitations in implementation for names */ if(!FileExists(rsc)) return false; } { Resource rsc("filled-dir/subdir/we-need-to-go-deeper/Spaced filename.txt", ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests errors in scripts regarding spaces */ if(!FileExists(rsc)) return false; } return true; } const constexpr cstring filename_odd = "Oddball: æøå, カケ"; bool resource_exists_odd_characters_test() { Resource rsc(filename_odd, ResourceAccess::SpecifyStorage|ResourceAccess::AssetFile); /* Tests what happens to unexpected characters. We want these to work. */ /* If existence passes, we assume the rest works too for these cases. */ /* It is known that it does not work with Win32's resource system. */ return FileExists(rsc); } const constexpr cstring filename_testable = "filled-dir/subdir/we-need-to-go-deeper/odd-file-with-long-extension.txt.zip.exe"; bool resource_read_test() { Resource rsc(filename_testable, ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FilePull(rsc)) return false; if(sizeof(probe_text)-1 != rsc.size || !MemCmp(rsc.data,probe_text,rsc.size)) { cDebug("Sizes: {0} ?= {1}", sizeof(probe_text) - 1,rsc.size); cDebug("Data:\n" "Internal: {0}\n" "Resource: {1}\n", StrUtil::hexdump(probe_text, sizeof(probe_text) - 1), StrUtil::hexdump(rsc.data,rsc.size)); return false; } FileFree(rsc); return true; } bool resource_map_test() { Resource rsc(filename_testable, ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FileMap(rsc,ResourceAccess::ReadOnly)) return false; if(!FileUnmap(rsc)) return false; return true; } bool resource_write_test() { Resource rsc(filename_testable, ResourceAccess::SpecifyStorage |ResourceAccess::AssetFile); if(!FileMap(rsc,ResourceAccess::ReadWrite)) return false; if(!FileUnmap(rsc)) return false; return true; } const constexpr CoffeeTest::Test _tests[10] = { {resource_exist_test, "Resource existence", "Test whether the resources are there"}, {resource_read_test, "Resource reading", "Opening and reading a resource, uses an odd filename"}, /* The ones below only test feature sets */ {resource_exists_odd_characters_test, "Gettin weird with filenames", "Test what happens with multibyte characters",true}, {resource_map_test, "Resource mapping", "If the resources are mappable",true}, {resource_write_test, "Resource writing", "If the resources are writable",true}, }; COFFEE_RUN_TESTS(_tests); <|endoftext|>
<commit_before>#include <iostream> #include "parser.h" int main(int argc, char * argv[]) { if (argc != 2) { std::cout << "Try ./calc expr" << std::endl; return 0; } try { std::cout << calc(argv[1]) << std::endl; } catch(const char *msg) { std::cout << msg << std::endl; return 1; } return 0; } <commit_msg>added non-zero exit code<commit_after>#include <iostream> #include "parser.h" int main(int argc, char * argv[]) { if (argc != 2) { std::cout << "Try ./calc expr" << std::endl; return 0; } try { std::cout << calc(argv[1]) << std::endl; } catch(const char *msg) { std::cout << msg << std::endl; //code 1 return 1; } return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferSceneUI/SceneGadget.h" #include "GafferUI/ViewportGadget.h" #include "Gaffer/BackgroundTask.h" #include "Gaffer/Node.h" #include "Gaffer/StringPlug.h" #include "IECoreGL/CachedConverter.h" #include "IECoreGL/CurvesPrimitive.h" #include "IECoreGL/PointsPrimitive.h" #include "IECoreGL/Primitive.h" #include "IECoreGL/Renderable.h" #include "IECoreGL/Selector.h" #include "IECoreScene/CurvesPrimitive.h" #include "IECore/MessageHandler.h" #include "boost/algorithm/string/predicate.hpp" #include "boost/bind.hpp" #include "tbb/concurrent_unordered_set.h" #include "tbb/task.h" using namespace std; using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; using namespace GafferScene; using namespace GafferSceneUI; ////////////////////////////////////////////////////////////////////////// // SceneGadget implementation ////////////////////////////////////////////////////////////////////////// SceneGadget::SceneGadget() : Gadget( defaultName<SceneGadget>() ), m_paused( false ), m_renderer( IECoreScenePreview::Renderer::create( "OpenGL", IECoreScenePreview::Renderer::Interactive ) ), m_controller( nullptr, nullptr, m_renderer ), m_updateErrored( false ), m_renderRequestPending( false ) { typedef CompoundObject::ObjectMap::value_type Option; CompoundObjectPtr openGLOptions = new CompoundObject; openGLOptions->members().insert( { Option( "gl:primitive:wireframeColor", new Color4fData( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) ), Option( "gl:primitive:pointColor", new Color4fData( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) ), Option( "gl:primitive:pointWidth", new FloatData( 2.0f ) ) } ); setOpenGLOptions( openGLOptions.get() ); m_controller.updateRequiredSignal().connect( boost::bind( &SceneGadget::requestRender, this ) ); visibilityChangedSignal().connect( boost::bind( &SceneGadget::visibilityChanged, this ) ); setContext( new Context ); } SceneGadget::~SceneGadget() { // Make sure background task completes before anything // it relies on is destroyed. m_updateTask.reset(); } void SceneGadget::setScene( GafferScene::ConstScenePlugPtr scene ) { m_controller.setScene( scene ); } const GafferScene::ScenePlug *SceneGadget::getScene() const { return m_controller.getScene(); } void SceneGadget::setContext( Gaffer::ConstContextPtr context ) { m_controller.setContext( context ); } const Gaffer::Context *SceneGadget::getContext() const { return m_controller.getContext(); } void SceneGadget::setExpandedPaths( const IECore::PathMatcher &expandedPaths ) { m_controller.setExpandedPaths( expandedPaths ); } const IECore::PathMatcher &SceneGadget::getExpandedPaths() const { return m_controller.getExpandedPaths(); } void SceneGadget::setMinimumExpansionDepth( size_t depth ) { m_controller.setMinimumExpansionDepth( depth ); } size_t SceneGadget::getMinimumExpansionDepth() const { return m_controller.getMinimumExpansionDepth(); } void SceneGadget::setPaused( bool paused ) { if( paused == m_paused ) { return; } m_paused = paused; if( m_paused ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } stateChangedSignal()( this ); } else if( m_controller.updateRequired() ) { requestRender(); } } bool SceneGadget::getPaused() const { return m_paused; } void SceneGadget::setBlockingPaths( const IECore::PathMatcher &blockingPaths ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } m_blockingPaths = blockingPaths; requestRender(); } const IECore::PathMatcher &SceneGadget::getBlockingPaths() const { return m_blockingPaths; } void SceneGadget::setPriorityPaths( const IECore::PathMatcher &priorityPaths ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } m_priorityPaths = priorityPaths; requestRender(); } const IECore::PathMatcher &SceneGadget::getPriorityPaths() const { return m_priorityPaths; } SceneGadget::State SceneGadget::state() const { if( m_paused ) { return Paused; } return m_controller.updateRequired() ? Running : Complete; } SceneGadget::SceneGadgetSignal &SceneGadget::stateChangedSignal() { return m_stateChangedSignal; } void SceneGadget::waitForCompletion() { updateRenderer(); if( m_updateTask ) { m_updateTask->wait(); } } void SceneGadget::setOpenGLOptions( const IECore::CompoundObject *options ) { if( m_openGLOptions && *m_openGLOptions == *options ) { return; } // Output anything that has changed or was added for( const auto &option : options->members() ) { bool changedOrAdded = true; if( m_openGLOptions ) { if( const Object *previousOption = m_openGLOptions->member<Object>( option.first ) ) { changedOrAdded = *previousOption != *option.second; } } if( changedOrAdded ) { m_renderer->option( option.first, option.second.get() ); } } // Remove anything that was removed if( m_openGLOptions ) { for( const auto &oldOption : m_openGLOptions->members() ) { if( !options->member<Object>( oldOption.first ) ) { m_renderer->option( oldOption.first, nullptr ); } } } m_openGLOptions = options->copy(); requestRender(); } const IECore::CompoundObject *SceneGadget::getOpenGLOptions() const { return m_openGLOptions.get(); } void SceneGadget::setSelectionMask( const IECore::StringVectorData *typeNames ) { m_selectionMask = typeNames ? typeNames->copy() : nullptr; } const IECore::StringVectorData *SceneGadget::getSelectionMask() const { return m_selectionMask.get(); } bool SceneGadget::objectAt( const IECore::LineSegment3f &lineInGadgetSpace, GafferScene::ScenePlug::ScenePath &path ) const { std::vector<IECoreGL::HitRecord> selection; { ViewportGadget::SelectionScope selectionScope( lineInGadgetSpace, this, selection, IECoreGL::Selector::IDRender ); renderScene(); } if( !selection.size() ) { return false; } float depthMin = selection[0].depthMin; unsigned int name = selection[0].name; for( const auto &i : selection ) { if( i.depthMin < depthMin ) { depthMin = i.depthMin; name = i.name; } } PathMatcher paths = convertSelection( new UIntVectorData( { name } ) ); if( paths.isEmpty() ) { return false; } path = *PathMatcher::Iterator( paths.begin() ); return true; } size_t SceneGadget::objectsAt( const Imath::V3f &corner0InGadgetSpace, const Imath::V3f &corner1InGadgetSpace, IECore::PathMatcher &paths ) const { vector<IECoreGL::HitRecord> selection; { ViewportGadget::SelectionScope selectionScope( corner0InGadgetSpace, corner1InGadgetSpace, this, selection, IECoreGL::Selector::OcclusionQuery ); renderScene(); } UIntVectorDataPtr ids = new UIntVectorData; std::transform( selection.begin(), selection.end(), std::back_inserter( ids->writable() ), []( const IECoreGL::HitRecord &h ) { return h.name; } ); PathMatcher selectedPaths = convertSelection( ids ); paths.addPaths( selectedPaths ); return selectedPaths.size(); } IECore::PathMatcher SceneGadget::convertSelection( IECore::UIntVectorDataPtr ids ) const { CompoundDataMap parameters = { { "selection", ids } }; if( m_selectionMask ) { parameters["mask"] = m_selectionMask; } auto pathsData = static_pointer_cast<PathMatcherData>( m_renderer->command( "gl:querySelection", parameters ) ); PathMatcher result = pathsData->readable(); // Unexpanded locations are represented with // objects named __unexpandedChildren__ to allow // locations to have an object _and_ children. // We want to replace any such locations with their // parent location. const InternedString unexpandedChildren = "__unexpandedChildren__"; vector<InternedString> parent; PathMatcher toAdd; PathMatcher toRemove; for( PathMatcher::Iterator it = result.begin(), eIt = result.end(); it != eIt; ++it ) { if( it->size() && it->back() == unexpandedChildren ) { toRemove.addPath( *it ); parent.assign( it->begin(), it->end() - 1 ); toAdd.addPath( parent ); } } result.addPaths( toAdd ); result.removePaths( toRemove ); return result; } const IECore::PathMatcher &SceneGadget::getSelection() const { return m_selection; } void SceneGadget::setSelection( const IECore::PathMatcher &selection ) { m_selection = selection; ConstDataPtr d = new IECore::PathMatcherData( selection ); m_renderer->option( "gl:selection", d.get() ); requestRender(); } Imath::Box3f SceneGadget::selectionBound() const { DataPtr d = m_renderer->command( "gl:queryBound", { { "selection", new BoolData( true ) } } ); return static_cast<Box3fData *>( d.get() )->readable(); } std::string SceneGadget::getToolTip( const IECore::LineSegment3f &line ) const { std::string result = Gadget::getToolTip( line ); if( result.size() ) { return result; } ScenePlug::ScenePath path; if( objectAt( line, path ) ) { ScenePlug::pathToString( path, result ); } return result; } Imath::Box3f SceneGadget::bound() const { if( m_updateErrored ) { return Box3f(); } DataPtr d = m_renderer->command( "gl:queryBound" ); return static_cast<Box3fData *>( d.get() )->readable(); } void SceneGadget::doRenderLayer( Layer layer, const GafferUI::Style *style ) const { if( layer != Layer::Main ) { return; } if( IECoreGL::Selector::currentSelector() ) { return; } const_cast<SceneGadget *>( this )->updateRenderer(); renderScene(); } void SceneGadget::updateRenderer() { if( m_paused ) { return; } if( m_updateTask ) { if( m_updateTask->status() == BackgroundTask::Running ) { return; } m_updateTask.reset(); } if( !m_controller.updateRequired() ) { return; } auto progressCallback = [this] ( BackgroundTask::Status progress ) { if( !refCount() ) { return; } bool shouldRequestRender = !m_renderRequestPending.exchange( true ); bool shouldEmitStateChange = progress == BackgroundTask::Completed || progress == BackgroundTask::Errored ; if( shouldRequestRender || shouldEmitStateChange ) { // Must hold a reference to stop us dying before our UI thread call is scheduled. SceneGadgetPtr thisRef = this; ParallelAlgo::callOnUIThread( [thisRef, shouldRequestRender, shouldEmitStateChange, progress] { if( progress == BackgroundTask::Errored ) { thisRef->m_updateErrored = true; } if( shouldEmitStateChange ) { thisRef->stateChangedSignal()( thisRef.get() ); } if( shouldRequestRender ) { thisRef->m_renderRequestPending = false; thisRef->requestRender(); } } ); } }; if( !m_blockingPaths.isEmpty() ) { try { m_controller.updateMatchingPaths( m_blockingPaths ); } catch( std::exception &e ) { // Leave it to the rest of the UI to report the error. m_updateErrored = true; } } m_updateErrored = false; m_updateTask = m_controller.updateInBackground( progressCallback, m_priorityPaths ); stateChangedSignal()( this ); // Give ourselves a 0.1s grace period in which we block // the UI while our updates occur. This means that for reasonably // interactive animation or manipulation, we only show the final // result, rathen than a series of partial intermediate results. // It also prevents a "cancellation storm" where new UI events // cancel our background updates faster than we can show them. m_updateTask->waitFor( 0.1 ); } void SceneGadget::renderScene() const { if( m_updateErrored ) { return; } m_renderer->render(); } void SceneGadget::visibilityChanged() { if( !visible() && m_updateTask ) { m_updateTask->cancelAndWait(); } } <commit_msg>SceneGadget : Remove unused includes<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferSceneUI/SceneGadget.h" #include "GafferUI/ViewportGadget.h" #include "Gaffer/BackgroundTask.h" #include "boost/bind.hpp" using namespace std; using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; using namespace GafferScene; using namespace GafferSceneUI; ////////////////////////////////////////////////////////////////////////// // SceneGadget implementation ////////////////////////////////////////////////////////////////////////// SceneGadget::SceneGadget() : Gadget( defaultName<SceneGadget>() ), m_paused( false ), m_renderer( IECoreScenePreview::Renderer::create( "OpenGL", IECoreScenePreview::Renderer::Interactive ) ), m_controller( nullptr, nullptr, m_renderer ), m_updateErrored( false ), m_renderRequestPending( false ) { typedef CompoundObject::ObjectMap::value_type Option; CompoundObjectPtr openGLOptions = new CompoundObject; openGLOptions->members().insert( { Option( "gl:primitive:wireframeColor", new Color4fData( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) ), Option( "gl:primitive:pointColor", new Color4fData( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) ), Option( "gl:primitive:pointWidth", new FloatData( 2.0f ) ) } ); setOpenGLOptions( openGLOptions.get() ); m_controller.updateRequiredSignal().connect( boost::bind( &SceneGadget::requestRender, this ) ); visibilityChangedSignal().connect( boost::bind( &SceneGadget::visibilityChanged, this ) ); setContext( new Context ); } SceneGadget::~SceneGadget() { // Make sure background task completes before anything // it relies on is destroyed. m_updateTask.reset(); } void SceneGadget::setScene( GafferScene::ConstScenePlugPtr scene ) { m_controller.setScene( scene ); } const GafferScene::ScenePlug *SceneGadget::getScene() const { return m_controller.getScene(); } void SceneGadget::setContext( Gaffer::ConstContextPtr context ) { m_controller.setContext( context ); } const Gaffer::Context *SceneGadget::getContext() const { return m_controller.getContext(); } void SceneGadget::setExpandedPaths( const IECore::PathMatcher &expandedPaths ) { m_controller.setExpandedPaths( expandedPaths ); } const IECore::PathMatcher &SceneGadget::getExpandedPaths() const { return m_controller.getExpandedPaths(); } void SceneGadget::setMinimumExpansionDepth( size_t depth ) { m_controller.setMinimumExpansionDepth( depth ); } size_t SceneGadget::getMinimumExpansionDepth() const { return m_controller.getMinimumExpansionDepth(); } void SceneGadget::setPaused( bool paused ) { if( paused == m_paused ) { return; } m_paused = paused; if( m_paused ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } stateChangedSignal()( this ); } else if( m_controller.updateRequired() ) { requestRender(); } } bool SceneGadget::getPaused() const { return m_paused; } void SceneGadget::setBlockingPaths( const IECore::PathMatcher &blockingPaths ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } m_blockingPaths = blockingPaths; requestRender(); } const IECore::PathMatcher &SceneGadget::getBlockingPaths() const { return m_blockingPaths; } void SceneGadget::setPriorityPaths( const IECore::PathMatcher &priorityPaths ) { if( m_updateTask ) { m_updateTask->cancelAndWait(); m_updateTask.reset(); } m_priorityPaths = priorityPaths; requestRender(); } const IECore::PathMatcher &SceneGadget::getPriorityPaths() const { return m_priorityPaths; } SceneGadget::State SceneGadget::state() const { if( m_paused ) { return Paused; } return m_controller.updateRequired() ? Running : Complete; } SceneGadget::SceneGadgetSignal &SceneGadget::stateChangedSignal() { return m_stateChangedSignal; } void SceneGadget::waitForCompletion() { updateRenderer(); if( m_updateTask ) { m_updateTask->wait(); } } void SceneGadget::setOpenGLOptions( const IECore::CompoundObject *options ) { if( m_openGLOptions && *m_openGLOptions == *options ) { return; } // Output anything that has changed or was added for( const auto &option : options->members() ) { bool changedOrAdded = true; if( m_openGLOptions ) { if( const Object *previousOption = m_openGLOptions->member<Object>( option.first ) ) { changedOrAdded = *previousOption != *option.second; } } if( changedOrAdded ) { m_renderer->option( option.first, option.second.get() ); } } // Remove anything that was removed if( m_openGLOptions ) { for( const auto &oldOption : m_openGLOptions->members() ) { if( !options->member<Object>( oldOption.first ) ) { m_renderer->option( oldOption.first, nullptr ); } } } m_openGLOptions = options->copy(); requestRender(); } const IECore::CompoundObject *SceneGadget::getOpenGLOptions() const { return m_openGLOptions.get(); } void SceneGadget::setSelectionMask( const IECore::StringVectorData *typeNames ) { m_selectionMask = typeNames ? typeNames->copy() : nullptr; } const IECore::StringVectorData *SceneGadget::getSelectionMask() const { return m_selectionMask.get(); } bool SceneGadget::objectAt( const IECore::LineSegment3f &lineInGadgetSpace, GafferScene::ScenePlug::ScenePath &path ) const { std::vector<IECoreGL::HitRecord> selection; { ViewportGadget::SelectionScope selectionScope( lineInGadgetSpace, this, selection, IECoreGL::Selector::IDRender ); renderScene(); } if( !selection.size() ) { return false; } float depthMin = selection[0].depthMin; unsigned int name = selection[0].name; for( const auto &i : selection ) { if( i.depthMin < depthMin ) { depthMin = i.depthMin; name = i.name; } } PathMatcher paths = convertSelection( new UIntVectorData( { name } ) ); if( paths.isEmpty() ) { return false; } path = *PathMatcher::Iterator( paths.begin() ); return true; } size_t SceneGadget::objectsAt( const Imath::V3f &corner0InGadgetSpace, const Imath::V3f &corner1InGadgetSpace, IECore::PathMatcher &paths ) const { vector<IECoreGL::HitRecord> selection; { ViewportGadget::SelectionScope selectionScope( corner0InGadgetSpace, corner1InGadgetSpace, this, selection, IECoreGL::Selector::OcclusionQuery ); renderScene(); } UIntVectorDataPtr ids = new UIntVectorData; std::transform( selection.begin(), selection.end(), std::back_inserter( ids->writable() ), []( const IECoreGL::HitRecord &h ) { return h.name; } ); PathMatcher selectedPaths = convertSelection( ids ); paths.addPaths( selectedPaths ); return selectedPaths.size(); } IECore::PathMatcher SceneGadget::convertSelection( IECore::UIntVectorDataPtr ids ) const { CompoundDataMap parameters = { { "selection", ids } }; if( m_selectionMask ) { parameters["mask"] = m_selectionMask; } auto pathsData = static_pointer_cast<PathMatcherData>( m_renderer->command( "gl:querySelection", parameters ) ); PathMatcher result = pathsData->readable(); // Unexpanded locations are represented with // objects named __unexpandedChildren__ to allow // locations to have an object _and_ children. // We want to replace any such locations with their // parent location. const InternedString unexpandedChildren = "__unexpandedChildren__"; vector<InternedString> parent; PathMatcher toAdd; PathMatcher toRemove; for( PathMatcher::Iterator it = result.begin(), eIt = result.end(); it != eIt; ++it ) { if( it->size() && it->back() == unexpandedChildren ) { toRemove.addPath( *it ); parent.assign( it->begin(), it->end() - 1 ); toAdd.addPath( parent ); } } result.addPaths( toAdd ); result.removePaths( toRemove ); return result; } const IECore::PathMatcher &SceneGadget::getSelection() const { return m_selection; } void SceneGadget::setSelection( const IECore::PathMatcher &selection ) { m_selection = selection; ConstDataPtr d = new IECore::PathMatcherData( selection ); m_renderer->option( "gl:selection", d.get() ); requestRender(); } Imath::Box3f SceneGadget::selectionBound() const { DataPtr d = m_renderer->command( "gl:queryBound", { { "selection", new BoolData( true ) } } ); return static_cast<Box3fData *>( d.get() )->readable(); } std::string SceneGadget::getToolTip( const IECore::LineSegment3f &line ) const { std::string result = Gadget::getToolTip( line ); if( result.size() ) { return result; } ScenePlug::ScenePath path; if( objectAt( line, path ) ) { ScenePlug::pathToString( path, result ); } return result; } Imath::Box3f SceneGadget::bound() const { if( m_updateErrored ) { return Box3f(); } DataPtr d = m_renderer->command( "gl:queryBound" ); return static_cast<Box3fData *>( d.get() )->readable(); } void SceneGadget::doRenderLayer( Layer layer, const GafferUI::Style *style ) const { if( layer != Layer::Main ) { return; } if( IECoreGL::Selector::currentSelector() ) { return; } const_cast<SceneGadget *>( this )->updateRenderer(); renderScene(); } void SceneGadget::updateRenderer() { if( m_paused ) { return; } if( m_updateTask ) { if( m_updateTask->status() == BackgroundTask::Running ) { return; } m_updateTask.reset(); } if( !m_controller.updateRequired() ) { return; } auto progressCallback = [this] ( BackgroundTask::Status progress ) { if( !refCount() ) { return; } bool shouldRequestRender = !m_renderRequestPending.exchange( true ); bool shouldEmitStateChange = progress == BackgroundTask::Completed || progress == BackgroundTask::Errored ; if( shouldRequestRender || shouldEmitStateChange ) { // Must hold a reference to stop us dying before our UI thread call is scheduled. SceneGadgetPtr thisRef = this; ParallelAlgo::callOnUIThread( [thisRef, shouldRequestRender, shouldEmitStateChange, progress] { if( progress == BackgroundTask::Errored ) { thisRef->m_updateErrored = true; } if( shouldEmitStateChange ) { thisRef->stateChangedSignal()( thisRef.get() ); } if( shouldRequestRender ) { thisRef->m_renderRequestPending = false; thisRef->requestRender(); } } ); } }; if( !m_blockingPaths.isEmpty() ) { try { m_controller.updateMatchingPaths( m_blockingPaths ); } catch( std::exception &e ) { // Leave it to the rest of the UI to report the error. m_updateErrored = true; } } m_updateErrored = false; m_updateTask = m_controller.updateInBackground( progressCallback, m_priorityPaths ); stateChangedSignal()( this ); // Give ourselves a 0.1s grace period in which we block // the UI while our updates occur. This means that for reasonably // interactive animation or manipulation, we only show the final // result, rathen than a series of partial intermediate results. // It also prevents a "cancellation storm" where new UI events // cancel our background updates faster than we can show them. m_updateTask->waitFor( 0.1 ); } void SceneGadget::renderScene() const { if( m_updateErrored ) { return; } m_renderer->render(); } void SceneGadget::visibilityChanged() { if( !visible() && m_updateTask ) { m_updateTask->cancelAndWait(); } } <|endoftext|>
<commit_before>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "core/Setup.h" #include <iostream> #include <string> #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <sys/syslog.h> #endif #if OUZEL_PLATFORM_WINDOWS #include <windows.h> #include <strsafe.h> #endif #if OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #if OUZEL_PLATFORM_EMSCRIPTEN #include <emscripten.h> #endif #include "Log.hpp" namespace ouzel { #ifdef DEBUG Log::Level Log::threshold = Log::Level::ALL; #else Log::Level Log::threshold = Log::Level::INFO; #endif Log::~Log() { if (!s.empty()) { #if OUZEL_PLATFORM_MACOS || OUZEL_PLATFORM_LINUX || OUZEL_PLATFORM_RASPBIAN switch (level) { case Level::ERR: case Level::WARN: std::cerr << s << std::endl; break; case Level::INFO: case Level::ALL: std::cout << s << std::endl; break; default: break; } #elif OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS int priority = 0; switch (level) { case Level::ERR: priority = LOG_ERR; break; case Level::WARN: priority = LOG_WARNING; break; case Level::INFO: priority = LOG_INFO; break; case Level::ALL: priority = LOG_DEBUG; break; default: break; } syslog(priority, "%s", s.c_str()); #elif OUZEL_PLATFORM_WINDOWS std::vector<wchar_t> szBuffer(s.length() + 1); if (MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, szBuffer.data(), static_cast<int>(szBuffer.size())) == 0) { Log(Log::Level::ERR) << "Failed to convert UTF-8 to wide char"; return; } StringCchCatW(szBuffer.data(), szBuffer.size(), L"\n"); OutputDebugStringW(szBuffer.data()); #if DEBUG HANDLE handle = 0; switch (level) { case Level::ERR: case Level::WARN: handle = GetStdHandle(STD_ERROR_HANDLE); break; case Level::INFO: case Level::ALL: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; default: break; } if (handle) { DWORD bytesWritten; WriteConsoleW(handle, szBuffer.data(), static_cast<DWORD>(wcslen(szBuffer.data())), &bytesWritten, nullptr); } #endif #elif OUZEL_PLATFORM_ANDROID int priority = 0; switch (level) { case Level::ERR: priority = ANDROID_LOG_ERROR; break; case Level::WARN: priority = ANDROID_LOG_WARN; break; case Level::INFO: priority = ANDROID_LOG_INFO; break; case Level::ALL: priority = ANDROID_LOG_DEBUG; break; default: break; } __android_log_print(priority, "Ouzel", "%s", s.c_str()); #elif OUZEL_PLATFORM_EMSCRIPTEN int flags = EM_LOG_CONSOLE; if (level == Level::ERR) flags |= EM_LOG_ERROR; else if (level == Level::WARN) flags |= EM_LOG_WARN; emscripten_log(flags, "%s", s.c_str()); #endif s.clear(); } } } <commit_msg>Readd the +1<commit_after>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "core/Setup.h" #include <iostream> #include <string> #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <sys/syslog.h> #endif #if OUZEL_PLATFORM_WINDOWS #include <windows.h> #include <strsafe.h> #endif #if OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #if OUZEL_PLATFORM_EMSCRIPTEN #include <emscripten.h> #endif #include "Log.hpp" namespace ouzel { #ifdef DEBUG Log::Level Log::threshold = Log::Level::ALL; #else Log::Level Log::threshold = Log::Level::INFO; #endif Log::~Log() { if (!s.empty()) { #if OUZEL_PLATFORM_MACOS || OUZEL_PLATFORM_LINUX || OUZEL_PLATFORM_RASPBIAN switch (level) { case Level::ERR: case Level::WARN: std::cerr << s << std::endl; break; case Level::INFO: case Level::ALL: std::cout << s << std::endl; break; default: break; } #elif OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS int priority = 0; switch (level) { case Level::ERR: priority = LOG_ERR; break; case Level::WARN: priority = LOG_WARNING; break; case Level::INFO: priority = LOG_INFO; break; case Level::ALL: priority = LOG_DEBUG; break; default: break; } syslog(priority, "%s", s.c_str()); #elif OUZEL_PLATFORM_WINDOWS std::vector<wchar_t> szBuffer(s.length() + 1 + 1); // for the newline and the terminating char if (MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, szBuffer.data(), static_cast<int>(szBuffer.size())) == 0) { Log(Log::Level::ERR) << "Failed to convert UTF-8 to wide char"; return; } StringCchCatW(szBuffer.data(), szBuffer.size(), L"\n"); OutputDebugStringW(szBuffer.data()); #if DEBUG HANDLE handle = 0; switch (level) { case Level::ERR: case Level::WARN: handle = GetStdHandle(STD_ERROR_HANDLE); break; case Level::INFO: case Level::ALL: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; default: break; } if (handle) { DWORD bytesWritten; WriteConsoleW(handle, szBuffer.data(), static_cast<DWORD>(wcslen(szBuffer.data())), &bytesWritten, nullptr); } #endif #elif OUZEL_PLATFORM_ANDROID int priority = 0; switch (level) { case Level::ERR: priority = ANDROID_LOG_ERROR; break; case Level::WARN: priority = ANDROID_LOG_WARN; break; case Level::INFO: priority = ANDROID_LOG_INFO; break; case Level::ALL: priority = ANDROID_LOG_DEBUG; break; default: break; } __android_log_print(priority, "Ouzel", "%s", s.c_str()); #elif OUZEL_PLATFORM_EMSCRIPTEN int flags = EM_LOG_CONSOLE; if (level == Level::ERR) flags |= EM_LOG_ERROR; else if (level == Level::WARN) flags |= EM_LOG_WARN; emscripten_log(flags, "%s", s.c_str()); #endif s.clear(); } } } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_AES_INV_SBOX_HPP_ #define _SNARKFRONT_AES_INV_SBOX_HPP_ #include <array> #include <cstdint> #include "DSL_utility.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // FIPS PUB 197, NIST November 2001 // // Algorithm Key Length Block Size Number of Rounds // (Nk words) (Nb words) (Nr) // // AES-128 4 4 10 // AES-192 6 4 12 // AES-256 8 4 14 // //////////////////////////////////////////////////////////////////////////////// // Inverse S-Box // template <typename T, typename U, typename BITWISE> class AES_InvSBox { public: AES_InvSBox() : m_lut(std::array<std::uint8_t, 256>{ // 00 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, // 10 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, // 20 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, // 30 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, // 40 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, // 50 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, // 60 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, // 70 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, // 80 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, // 90 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, // a0 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, // b0 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, // c0 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, // d0 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, // e0 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, // f0 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }) {} U operator() (const T& x) const { return m_lut[x]; } private: const BitwiseLUT<T, U, std::uint8_t, BITWISE> m_lut; }; } // namespace snarkfront #endif <commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_INV_SBOX_HPP_ #define _SNARKFRONT_AES_INV_SBOX_HPP_ #include <array> #include <cstdint> #include <snarkfront/DSL_utility.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // FIPS PUB 197, NIST November 2001 // // Algorithm Key Length Block Size Number of Rounds // (Nk words) (Nb words) (Nr) // // AES-128 4 4 10 // AES-192 6 4 12 // AES-256 8 4 14 // //////////////////////////////////////////////////////////////////////////////// // Inverse S-Box // template <typename T, typename U, typename BITWISE> class AES_InvSBox { public: AES_InvSBox() : m_lut(std::array<std::uint8_t, 256>{ // 00 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, // 10 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, // 20 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, // 30 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, // 40 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, // 50 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, // 60 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, // 70 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, // 80 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, // 90 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, // a0 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, // b0 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, // c0 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, // d0 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, // e0 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, // f0 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }) {} U operator() (const T& x) const { return m_lut[x]; } private: const BitwiseLUT<T, U, std::uint8_t, BITWISE> m_lut; }; } // namespace snarkfront #endif <|endoftext|>
<commit_before> <commit_msg>Delete 1.cpp<commit_after><|endoftext|>
<commit_before>#include "imageviewer.h" #include "ui_imageviewer.h" ImageViewer::ImageViewer(QWidget *parent) : QMainWindow(parent), ui(new Ui::ImageViewer) { ui->setupUi(this); actionOpen = ui->actionOpen; actionZoomIn = ui->actionZoomIn; actionZoomOut = ui->actionZoomOut; actionRotateLeft = ui->actionRotateLeft; actionRotateRight = ui->actionRotateRight; actionCrop = ui->actionCrop; updateActions(false); imageLabel = new QLabel; imageLabel->setBackgroundRole(QPalette::Base); imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); imageLabel->setScaledContents(true); imageLabel->installEventFilter(this); scrollArea = new QScrollArea; scrollArea->setBackgroundRole(QPalette::Dark); scrollArea->setWidget(imageLabel); setCentralWidget(scrollArea); setWindowTitle(tr("Image Viewer")); } ImageViewer::~ImageViewer() { delete ui; } void ImageViewer::updateActions(bool updateTo) { actionZoomIn->setEnabled(updateTo); actionZoomOut->setEnabled(updateTo); actionRotateLeft->setEnabled(updateTo); actionRotateRight->setEnabled(updateTo); actionCrop->setEnabled(updateTo); } void ImageViewer::scaleImage(double factor) { Q_ASSERT(imageLabel->pixmap()); scaleFactor *= factor; imageLabel->resize(scaleFactor * imageLabel->pixmap()->size()); adjustScrollBar(scrollArea->horizontalScrollBar(), factor); adjustScrollBar(scrollArea->verticalScrollBar(), factor); actionZoomIn->setEnabled(scaleFactor < 3.0); actionZoomOut->setEnabled(scaleFactor > 0.333); } void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor) { int newValue = factor * scrollBar->value() + (factor - 1) * scrollBar->pageStep() / 2; scrollBar->setValue(newValue); } void ImageViewer::on_actionOpen_triggered() { QString lastFileName = fileName.isEmpty() ? QDir::currentPath() : fileName; fileName = QFileDialog::getOpenFileName(this, tr("Open File"), lastFileName); if (!fileName.isEmpty()) { image = QImage(fileName); if (image.isNull()) { QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(fileName)); return; } imageLabel->setPixmap(QPixmap::fromImage(image)); scaleFactor = 1.0; croppingImage = false; updateActions(true); imageLabel->adjustSize(); } } void ImageViewer::on_actionZoomIn_triggered() { scaleImage(1.25); } void ImageViewer::on_actionZoomOut_triggered() { scaleImage(0.80); } void ImageViewer::rotateImage(int angle) { QPixmap pixmap(*imageLabel->pixmap()); QMatrix rm; rm.rotate(angle); pixmap = pixmap.transformed(rm); imageLabel->setPixmap(pixmap); } void ImageViewer::on_actionRotateLeft_triggered() { rotateImage(-90); } void ImageViewer::on_actionRotateRight_triggered() { rotateImage(90); } void ImageViewer::on_actionCrop_triggered() { changeCroppingImage(true); } void ImageViewer::changeCroppingImage(bool changeTo) { croppingImage = changeTo; actionCrop->setDisabled(changeTo); } bool ImageViewer::eventFilter(QObject* watched, QEvent* event) { if (watched != imageLabel || !croppingImage) return false; switch (event->type()) { case QEvent::MouseButtonPress: { const QMouseEvent* const me = static_cast<const QMouseEvent*>(event); croppingStart = me->pos() / scaleFactor; break; } case QEvent::MouseButtonRelease: { const QMouseEvent* const me = static_cast<const QMouseEvent*>(event); croppingEnd = me->pos() / scaleFactor; QRect rect(croppingStart, croppingEnd); image = image.copy(rect); imageLabel->setPixmap(QPixmap::fromImage(image)); imageLabel->adjustSize(); scaleImage(1.0); changeCroppingImage(false); break; } default: break; } return false; } <commit_msg>Allow for cropping of rotated image<commit_after>#include "imageviewer.h" #include "ui_imageviewer.h" ImageViewer::ImageViewer(QWidget *parent) : QMainWindow(parent), ui(new Ui::ImageViewer) { ui->setupUi(this); actionOpen = ui->actionOpen; actionZoomIn = ui->actionZoomIn; actionZoomOut = ui->actionZoomOut; actionRotateLeft = ui->actionRotateLeft; actionRotateRight = ui->actionRotateRight; actionCrop = ui->actionCrop; updateActions(false); imageLabel = new QLabel; imageLabel->setBackgroundRole(QPalette::Base); imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); imageLabel->setScaledContents(true); imageLabel->installEventFilter(this); scrollArea = new QScrollArea; scrollArea->setBackgroundRole(QPalette::Dark); scrollArea->setWidget(imageLabel); setCentralWidget(scrollArea); setWindowTitle(tr("Image Viewer")); } ImageViewer::~ImageViewer() { delete ui; } void ImageViewer::updateActions(bool updateTo) { actionZoomIn->setEnabled(updateTo); actionZoomOut->setEnabled(updateTo); actionRotateLeft->setEnabled(updateTo); actionRotateRight->setEnabled(updateTo); actionCrop->setEnabled(updateTo); } void ImageViewer::scaleImage(double factor) { Q_ASSERT(imageLabel->pixmap()); scaleFactor *= factor; imageLabel->resize(scaleFactor * imageLabel->pixmap()->size()); adjustScrollBar(scrollArea->horizontalScrollBar(), factor); adjustScrollBar(scrollArea->verticalScrollBar(), factor); actionZoomIn->setEnabled(scaleFactor < 3.0); actionZoomOut->setEnabled(scaleFactor > 0.333); } void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor) { int newValue = factor * scrollBar->value() + (factor - 1) * scrollBar->pageStep() / 2; scrollBar->setValue(newValue); } void ImageViewer::on_actionOpen_triggered() { QString lastFileName = fileName.isEmpty() ? QDir::currentPath() : fileName; fileName = QFileDialog::getOpenFileName(this, tr("Open File"), lastFileName); if (!fileName.isEmpty()) { image = QImage(fileName); if (image.isNull()) { QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(fileName)); return; } imageLabel->setPixmap(QPixmap::fromImage(image)); scaleFactor = 1.0; croppingImage = false; updateActions(true); imageLabel->adjustSize(); } } void ImageViewer::on_actionZoomIn_triggered() { scaleImage(1.25); } void ImageViewer::on_actionZoomOut_triggered() { scaleImage(0.80); } void ImageViewer::rotateImage(int angle) { QPixmap pixmap(*imageLabel->pixmap()); QMatrix rm; rm.rotate(angle); pixmap = pixmap.transformed(rm); image = pixmap.toImage(); imageLabel->setPixmap(pixmap); } void ImageViewer::on_actionRotateLeft_triggered() { rotateImage(-90); } void ImageViewer::on_actionRotateRight_triggered() { rotateImage(90); } void ImageViewer::on_actionCrop_triggered() { changeCroppingImage(true); } void ImageViewer::changeCroppingImage(bool changeTo) { croppingImage = changeTo; actionCrop->setDisabled(changeTo); } bool ImageViewer::eventFilter(QObject* watched, QEvent* event) { if (watched != imageLabel || !croppingImage) return false; switch (event->type()) { case QEvent::MouseButtonPress: { const QMouseEvent* const me = static_cast<const QMouseEvent*>(event); croppingStart = me->pos() / scaleFactor; break; } case QEvent::MouseButtonRelease: { const QMouseEvent* const me = static_cast<const QMouseEvent*>(event); croppingEnd = me->pos() / scaleFactor; QRect rect(croppingStart, croppingEnd); image = image.copy(rect); imageLabel->setPixmap(QPixmap::fromImage(image)); imageLabel->adjustSize(); scaleImage(1.0); changeCroppingImage(false); break; } default: break; } return false; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/Op.h" #include "IECore/Parameter.h" #include "IECore/CompoundParameter.h" #include "IECore/Object.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/RunTimeTypedBinding.h" #include "IECore/bindings/Wrapper.h" using namespace boost; using namespace boost::python; namespace IECore { class OpWrap : public Op, public Wrapper<Op> { public : OpWrap( PyObject *self, const std::string &description, ParameterPtr resultParameter ) : Op( description, resultParameter ), Wrapper<Op>( self, this ) {}; OpWrap( PyObject *self, const std::string &description, CompoundParameterPtr compoundParameter, ParameterPtr resultParameter ) : Op( description, compoundParameter, resultParameter ), Wrapper<Op>( self, this ) {}; virtual ObjectPtr doOperation( ConstCompoundObjectPtr operands ) { override o = this->get_override( "doOperation" ); if( o ) { ObjectPtr r = o( const_pointer_cast<CompoundObject>( operands ) ); if( !r ) { throw Exception( "doOperation() python method didn't return an Object." ); } return r; } else { throw Exception( "doOperation() python method not defined" ); } }; }; IE_CORE_DECLAREPTR( OpWrap ); static ParameterPtr resultParameter( const Op &o ) { return const_pointer_cast<Parameter>( o.resultParameter() ); } void bindOp() { using boost::python::arg; RunTimeTypedClass<Op, OpWrapPtr>() .def( init< const std::string &, ParameterPtr >( ( arg( "name" ), arg( "description" ), arg( "resultParameter") ) ) ) .def( init< const std::string &, CompoundParameterPtr, ParameterPtr >( ( arg( "name" ), arg( "description" ), arg( "compoundParameter" ), arg( "resultParameter") ) ) ) .def( "resultParameter", &resultParameter ) .def( "operate", &Op::operate ) .def( "__call__", &Op::operate ) ; } } // namespace IECore <commit_msg>Fixing argument description for OpBinding.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/Op.h" #include "IECore/Parameter.h" #include "IECore/CompoundParameter.h" #include "IECore/Object.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/RunTimeTypedBinding.h" #include "IECore/bindings/Wrapper.h" using namespace boost; using namespace boost::python; namespace IECore { class OpWrap : public Op, public Wrapper<Op> { public : OpWrap( PyObject *self, const std::string &description, ParameterPtr resultParameter ) : Op( description, resultParameter ), Wrapper<Op>( self, this ) {}; OpWrap( PyObject *self, const std::string &description, CompoundParameterPtr compoundParameter, ParameterPtr resultParameter ) : Op( description, compoundParameter, resultParameter ), Wrapper<Op>( self, this ) {}; virtual ObjectPtr doOperation( ConstCompoundObjectPtr operands ) { override o = this->get_override( "doOperation" ); if( o ) { ObjectPtr r = o( const_pointer_cast<CompoundObject>( operands ) ); if( !r ) { throw Exception( "doOperation() python method didn't return an Object." ); } return r; } else { throw Exception( "doOperation() python method not defined" ); } }; }; IE_CORE_DECLAREPTR( OpWrap ); static ParameterPtr resultParameter( const Op &o ) { return const_pointer_cast<Parameter>( o.resultParameter() ); } void bindOp() { using boost::python::arg; RunTimeTypedClass<Op, OpWrapPtr>() .def( init< const std::string &, ParameterPtr >( ( arg( "description" ), arg( "resultParameter") ) ) ) .def( init< const std::string &, CompoundParameterPtr, ParameterPtr >( ( arg( "description" ), arg( "compoundParameter" ), arg( "resultParameter") ) ) ) .def( "resultParameter", &resultParameter ) .def( "operate", &Op::operate ) .def( "__call__", &Op::operate ) ; } } // namespace IECore <|endoftext|>
<commit_before>#include <ghost.h> #include <ghost_util.h> #include <ghost_mat.h> #include <crs.h> #include "ghost_complex.h" #include <iostream> #include <omp.h> // TODO shift, scale als templateparameter template<typename m_t, typename v_t> void CRS_kernel_plain_tmpl(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { //#pragma omp parallel // { // if (omp_get_thread_num() == (omp_get_num_threads()-1)) { // WARNING_LOG("Thread %d/%d running @ core %d",omp_get_thread_num(),omp_get_num_threads()-1,ghost_getCore()); // } // } CR_TYPE *cr = CR(mat); v_t *rhsv = (v_t *)(rhs->val); v_t *lhsv = (v_t *)(lhs->val); m_t *mval = (m_t *)(cr->val); ghost_midx_t i, j; v_t hlp1 = 0.; v_t shift, scale; if (options & GHOST_SPMVM_APPLY_SHIFT) shift = *((v_t *)(mat->traits->shift)); if (options & GHOST_SPMVM_APPLY_SCALE) scale = *((v_t *)(mat->traits->scale)); #pragma omp parallel for schedule(runtime) private (hlp1, j) for (i=0; i<cr->nrows; i++){ hlp1 = (v_t)0.0; for (j=cr->rpt[i]; j<cr->rpt[i+1]; j++){ hlp1 += ((v_t)(mval[j])) * rhsv[cr->col[j]]; } if (options & GHOST_SPMVM_APPLY_SHIFT) { if (options & GHOST_SPMVM_APPLY_SCALE) { if (options & GHOST_SPMVM_AXPY) { lhsv[i] += scale*(hlp1+shift*rhsv[i]); } else { lhsv[i] = scale*(hlp1+shift*rhsv[i]); } } else { if (options & GHOST_SPMVM_AXPY) { lhsv[i] += (hlp1+shift*rhsv[i]); } else { lhsv[i] = (hlp1+shift*rhsv[i]); } } } else { if (options & GHOST_SPMVM_APPLY_SCALE) { if (options & GHOST_SPMVM_AXPY) { lhsv[i] += scale*(hlp1); } else { lhsv[i] = scale*(hlp1); } } else { if (options & GHOST_SPMVM_AXPY) { lhsv[i] += (hlp1); } else { lhsv[i] = (hlp1); } } } } } template<typename m_t, typename f_t> void CRS_castData_tmpl(void *matrixData, void *fileData, int nEnts) { ghost_mnnz_t i; m_t *md = (m_t *)matrixData; f_t *fd = (f_t *)fileData; for (i = 0; i<nEnts; i++) { md[i] = (m_t)(fd[i]); } } template<typename m_t> void CRS_valToStr_tmpl(void *val, char *str, int n) { if (val == NULL) { UNUSED(str); //str = "0."; } else { UNUSED(str); UNUSED(n); // TODO //snprintf(str,n,"%g",*((m_t *)(val))); } } extern "C" void dd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,double >(mat,lhs,rhs,options); } extern "C" void ds_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,float >(mat,lhs,rhs,options); } extern "C" void dc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void dz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void sd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,double >(mat,lhs,rhs,options); } extern "C" void ss_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,float >(mat,lhs,rhs,options); } extern "C" void sc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void sz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void cd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,double >(mat,lhs,rhs,options); } extern "C" void cs_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,float >(mat,lhs,rhs,options); } extern "C" void cc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void cz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void zd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,double >(mat,lhs,rhs,options); } extern "C" void zs_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,float >(mat,lhs,rhs,options); } extern "C" void zc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void zz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void dd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,double >(matrixData, fileData, nEnts); } extern "C" void ds_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,float >(matrixData, fileData, nEnts); } extern "C" void dc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void dz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void sd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,double >(matrixData, fileData, nEnts); } extern "C" void ss_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,float >(matrixData, fileData, nEnts); } extern "C" void sc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void sz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void cd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,double >(matrixData, fileData, nEnts); } extern "C" void cs_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,float >(matrixData, fileData, nEnts); } extern "C" void cc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void cz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void zd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,double >(matrixData, fileData, nEnts); } extern "C" void zs_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,float >(matrixData, fileData, nEnts); } extern "C" void zc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void zz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void d_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< double >(val,str,n); } extern "C" void s_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< float >(val,str,n); } extern "C" void c_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< ghost_complex<float> >(val,str,n); } extern "C" void z_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< ghost_complex<double> >(val,str,n); } <commit_msg>CRS spMVM kernel now multi-vector aware (untested)<commit_after>#include <ghost.h> #include <ghost_util.h> #include <ghost_mat.h> #include <crs.h> #include "ghost_complex.h" #include <iostream> #include <omp.h> // TODO shift, scale als templateparameter template<typename m_t, typename v_t> void CRS_kernel_plain_tmpl(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { CR_TYPE *cr = CR(mat); v_t *rhsv = (v_t *)(rhs->val); v_t *lhsv = (v_t *)(lhs->val); m_t *mval = (m_t *)(cr->val); ghost_midx_t i, j; ghost_vidx_t v; v_t hlp1 = 0.; v_t shift, scale; if (options & GHOST_SPMVM_APPLY_SHIFT) shift = *((v_t *)(mat->traits->shift)); if (options & GHOST_SPMVM_APPLY_SCALE) scale = *((v_t *)(mat->traits->scale)); for (v=0; v<MIN(lhs->traits->nvecs,rhs->traits->nvecs); v++) { #pragma omp parallel for schedule(runtime) private (hlp1, j) for (i=0; i<cr->nrows; i++){ hlp1 = (v_t)0.0; for (j=cr->rpt[i]; j<cr->rpt[i+1]; j++){ hlp1 += ((v_t)(mval[j])) * rhsv[v*rhs->traits->nrowspadded+cr->col[j]]; } if (options & GHOST_SPMVM_APPLY_SHIFT) { if (options & GHOST_SPMVM_APPLY_SCALE) { if (options & GHOST_SPMVM_AXPY) { lhsv[v*lhs->traits->nrowspadded+i] += scale*(hlp1+shift*rhsv[v*rhs->traits->nrowspadded+i]); } else { lhsv[v*lhs->traits->nrowspadded+i] = scale*(hlp1+shift*rhsv[v*rhs->traits->nrowspadded+i]); } } else { if (options & GHOST_SPMVM_AXPY) { lhsv[v*lhs->traits->nrowspadded+i] += (hlp1+shift*rhsv[v*rhs->traits->nrowspadded+i]); } else { lhsv[v*lhs->traits->nrowspadded+i] = (hlp1+shift*rhsv[v*rhs->traits->nrowspadded+i]); } } } else { if (options & GHOST_SPMVM_APPLY_SCALE) { if (options & GHOST_SPMVM_AXPY) { lhsv[v*lhs->traits->nrowspadded+i] += scale*(hlp1); } else { lhsv[v*lhs->traits->nrowspadded+i] = scale*(hlp1); } } else { if (options & GHOST_SPMVM_AXPY) { lhsv[v*lhs->traits->nrowspadded+i] += (hlp1); } else { lhsv[v*lhs->traits->nrowspadded+i] = (hlp1); } } } } } } template<typename m_t, typename f_t> void CRS_castData_tmpl(void *matrixData, void *fileData, int nEnts) { ghost_mnnz_t i; m_t *md = (m_t *)matrixData; f_t *fd = (f_t *)fileData; for (i = 0; i<nEnts; i++) { md[i] = (m_t)(fd[i]); } } template<typename m_t> void CRS_valToStr_tmpl(void *val, char *str, int n) { if (val == NULL) { UNUSED(str); //str = "0."; } else { UNUSED(str); UNUSED(n); // TODO //snprintf(str,n,"%g",*((m_t *)(val))); } } extern "C" void dd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,double >(mat,lhs,rhs,options); } extern "C" void ds_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,float >(mat,lhs,rhs,options); } extern "C" void dc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void dz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< double,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void sd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,double >(mat,lhs,rhs,options); } extern "C" void ss_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,float >(mat,lhs,rhs,options); } extern "C" void sc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void sz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< float,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void cd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,double >(mat,lhs,rhs,options); } extern "C" void cs_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,float >(mat,lhs,rhs,options); } extern "C" void cc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void cz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<float>,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void zd_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,double >(mat,lhs,rhs,options); } extern "C" void zs_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,float >(mat,lhs,rhs,options); } extern "C" void zc_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,ghost_complex<float> >(mat,lhs,rhs,options); } extern "C" void zz_CRS_kernel_plain(ghost_mat_t *mat, ghost_vec_t *lhs, ghost_vec_t *rhs, int options) { return CRS_kernel_plain_tmpl< ghost_complex<double>,ghost_complex<double> >(mat,lhs,rhs,options); } extern "C" void dd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,double >(matrixData, fileData, nEnts); } extern "C" void ds_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,float >(matrixData, fileData, nEnts); } extern "C" void dc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void dz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< double,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void sd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,double >(matrixData, fileData, nEnts); } extern "C" void ss_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,float >(matrixData, fileData, nEnts); } extern "C" void sc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void sz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< float,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void cd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,double >(matrixData, fileData, nEnts); } extern "C" void cs_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,float >(matrixData, fileData, nEnts); } extern "C" void cc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void cz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<float>,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void zd_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,double >(matrixData, fileData, nEnts); } extern "C" void zs_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,float >(matrixData, fileData, nEnts); } extern "C" void zc_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,ghost_complex<float> >(matrixData, fileData, nEnts); } extern "C" void zz_CRS_castData(void *matrixData, void *fileData, int nEnts) { return CRS_castData_tmpl< ghost_complex<double>,ghost_complex<double> >(matrixData, fileData, nEnts); } extern "C" void d_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< double >(val,str,n); } extern "C" void s_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< float >(val,str,n); } extern "C" void c_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< ghost_complex<float> >(val,str,n); } extern "C" void z_CRS_valToStr(void *val, char *str, int n) { return CRS_valToStr_tmpl< ghost_complex<double> >(val,str,n); } <|endoftext|>
<commit_before>// Copyright 2015-2018 Kuzzle // // 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 "kuzzle.hpp" #include "auth.hpp" namespace kuzzleio { Auth::Auth(Kuzzle *kuzzle) { _auth = new auth(); _kuzzle = kuzzle; kuzzle_new_auth(_auth, kuzzle->_kuzzle); } Auth::Auth(Kuzzle *kuzzle, auth *auth) { _auth = auth; _kuzzle = kuzzle; kuzzle_new_auth(_auth, kuzzle->_kuzzle); } Auth::~Auth() { unregisterAuth(_auth); delete(_auth); } token_validity* Auth::checkToken(const std::string& token) { return kuzzle_check_token(_auth, const_cast<char*>(token.c_str())); } std::string Auth::createMyCredentials(const std::string& strategy, const std::string& credentials, query_options* options) { string_result* r = kuzzle_create_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error) throwExceptionFromStatus(r); std::string ret = r->result; delete(r); return ret; } bool Auth::credentialsExist(const std::string& strategy, query_options *options) { bool_result* r = kuzzle_credentials_exist(_auth, const_cast<char*>(strategy.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); bool ret = r->result; delete(r); return ret; } void Auth::deleteMyCredentials(const std::string& strategy, query_options *options) { error_result *r = kuzzle_delete_my_credentials(_auth, const_cast<char*>(strategy.c_str()), options); if (r != nullptr) throwExceptionFromStatus(r); delete(r); } kuzzle_user* Auth::getCurrentUser() { user_result *r = kuzzle_get_current_user(_auth); if (r->error != nullptr) throwExceptionFromStatus(r); kuzzle_user *u = r->result; kuzzle_free_user_result(r); return u; } std::string Auth::getMyCredentials(const std::string& strategy, query_options *options) { string_result *r = kuzzle_get_my_credentials(_auth, const_cast<char*>(strategy.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } user_right* Auth::getMyRights(query_options* options) { user_rights_result *r = kuzzle_get_my_rights(_auth, options); if (r->error != nullptr) throwExceptionFromStatus(r); user_right *ret = r->result; kuzzle_free_user_rights_result(r); return ret; } std::vector<std::string> Auth::getStrategies(query_options *options) { string_array_result *r = kuzzle_get_strategies(_auth, options); if (r->error != nullptr) throwExceptionFromStatus(r); std::vector<std::string> v; for (int i = 0; r->result[i]; i++) v.push_back(r->result[i]); kuzzle_free_string_array_result(r); return v; } std::string Auth::login(const std::string& strategy, const std::string& credentials) { string_result* r = kuzzle_login(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), nullptr); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } std::string Auth::login(const std::string& strategy, const std::string& credentials, int expires_in) { string_result* r = kuzzle_login(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), &expires_in); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } void Auth::logout() noexcept { kuzzle_logout(_auth); } void Auth::setJwt(const std::string& jwt) { kuzzle_set_jwt(_kuzzle->_kuzzle, const_cast<char*>(jwt.c_str())); } std::string Auth::updateMyCredentials(const std::string& strategy, const std::string& credentials, query_options *options) { string_result *r = kuzzle_update_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } kuzzle_user* Auth::updateSelf(const std::string& content, query_options* options) { user_result *r = kuzzle_update_self(_auth, const_cast<char*>(content.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); kuzzle_user *ret = r->result; kuzzle_free_user_result(r); return ret; } bool Auth::validateMyCredentials(const std::string& strategy, const std::string& credentials, query_options* options) { bool_result *r = kuzzle_validate_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); bool ret = r->result; kuzzle_free_bool_result(r); return ret; } } <commit_msg>fix signatures<commit_after>// Copyright 2015-2018 Kuzzle // // 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 "kuzzle.hpp" #include "auth.hpp" namespace kuzzleio { Auth::Auth(Kuzzle *kuzzle) { _auth = new auth(); _kuzzle = kuzzle; kuzzle_new_auth(_auth, kuzzle->_kuzzle); } Auth::Auth(Kuzzle *kuzzle, auth *auth) { _auth = auth; _kuzzle = kuzzle; kuzzle_new_auth(_auth, kuzzle->_kuzzle); } Auth::~Auth() { unregisterAuth(_auth); delete(_auth); } token_validity* Auth::checkToken(const std::string& token) { return kuzzle_check_token(_auth, const_cast<char*>(token.c_str())); } std::string Auth::createMyCredentials(const std::string& strategy, const std::string& credentials, query_options* options) { string_result* r = kuzzle_create_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error) throwExceptionFromStatus(r); std::string ret = r->result; delete(r); return ret; } bool Auth::credentialsExist(const std::string& strategy, query_options *options) { bool_result* r = kuzzle_credentials_exist(_auth, const_cast<char*>(strategy.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); bool ret = r->result; delete(r); return ret; } void Auth::deleteMyCredentials(const std::string& strategy, query_options *options) { error_result *r = kuzzle_delete_my_credentials(_auth, const_cast<char*>(strategy.c_str()), options); if (r != nullptr) throwExceptionFromStatus(r); delete(r); } kuzzle_user* Auth::getCurrentUser() { user_result *r = kuzzle_get_current_user(_auth); if (r->error != nullptr) throwExceptionFromStatus(r); kuzzle_user *u = r->result; kuzzle_free_user_result(r); return u; } std::string Auth::getMyCredentials(const std::string& strategy, query_options *options) { string_result *r = kuzzle_get_my_credentials(_auth, const_cast<char*>(strategy.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } user_right* Auth::getMyRights(query_options* options) { user_rights_result *r = kuzzle_get_my_rights(_auth, options); if (r->error != nullptr) throwExceptionFromStatus(r); user_right *ret = r->result; kuzzle_free_user_rights_result(r); return ret; } std::vector<std::string> Auth::getStrategies(query_options *options) { string_array_result *r = kuzzle_get_strategies(_auth, options); if (r->error != nullptr) throwExceptionFromStatus(r); std::vector<std::string> v; for (int i = 0; r->result[i]; i++) v.push_back(r->result[i]); kuzzle_free_string_array_result(r); return v; } std::string Auth::login(const std::string& strategy, const std::string& credentials) { string_result* r = kuzzle_login(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), nullptr); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } std::string Auth::login(const std::string& strategy, const std::string& credentials, int expires_in) { string_result* r = kuzzle_login(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), &expires_in); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } void Auth::logout() noexcept { kuzzle_logout(_auth); } void Auth::setJwt(const std::string& jwt) noexcept { kuzzle_set_jwt(_kuzzle->_kuzzle, const_cast<char*>(jwt.c_str())); } std::string Auth::updateMyCredentials(const std::string& strategy, const std::string& credentials, query_options *options) { string_result *r = kuzzle_update_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); std::string ret = r->result; kuzzle_free_string_result(r); return ret; } kuzzle_user* Auth::updateSelf(const std::string& content, query_options* options) { user_result *r = kuzzle_update_self(_auth, const_cast<char*>(content.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); kuzzle_user *ret = r->result; kuzzle_free_user_result(r); return ret; } bool Auth::validateMyCredentials(const std::string& strategy, const std::string& credentials, query_options* options) { bool_result *r = kuzzle_validate_my_credentials(_auth, const_cast<char*>(strategy.c_str()), const_cast<char*>(credentials.c_str()), options); if (r->error != nullptr) throwExceptionFromStatus(r); bool ret = r->result; kuzzle_free_bool_result(r); return ret; } } <|endoftext|>
<commit_before>// // 16bitBinaryLoader.cpp // Phantasma // // Created by Thomas Harte on 17/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "16bitBinaryLoader.h" #include "Parser.h" #include "16bitDetokeniser.h" #include "Object.h" #include "Area.h" #include <map> class StreamLoader { private: vector<uint8_t>::size_type bytePointer; vector <uint8_t> binary; uint8_t readMaskByte1; uint8_t readMaskByte2; public: StreamLoader(vector <uint8_t> &_binary) { binary = _binary; bytePointer = 0; readMaskByte1 = 0; readMaskByte2 = 0; } uint8_t get8() { if(!eof()) { uint8_t sourceByte = binary[bytePointer]; if(bytePointer&1) sourceByte ^= readMaskByte2; else sourceByte ^= readMaskByte1; bytePointer++; return sourceByte; } return 0; } uint16_t get16() { uint16_t result = (uint16_t)(get8() << 8); result |= get8(); return result; } uint32_t get32() { uint32_t result = (uint32_t)(get16() << 16); result |= get16(); return result; } bool eof() { return bytePointer >= binary.size(); } void alignPointer() { if(bytePointer&1) bytePointer++; } void skipBytes(vector<uint8_t>::size_type numberOfBytes) { bytePointer += numberOfBytes; } shared_ptr<vector<uint8_t>> nextBytes(vector<uint8_t>::size_type numberOfBytes) { shared_ptr<vector<uint8_t>> returnBuffer(new vector<uint8_t>); while(numberOfBytes--) returnBuffer->push_back(get8()); return returnBuffer; } vector<uint8_t>::size_type getFileOffset() { return bytePointer; } void setFileOffset(vector<uint8_t>::size_type newOffset) { bytePointer = newOffset; } void setReadMask(uint8_t byte1, uint8_t byte2) { readMaskByte1 = byte1; readMaskByte2 = byte2; } }; static Object *loadObject(StreamLoader &stream) { // get object flags and type uint8_t objectFlags = stream.get8(); Object::Type objectType = (Object::Type)stream.get8(); // get unknown value uint16_t skippedShort = stream.get16(); // grab location, size Vector3d position, size; position.x = stream.get16(); position.y = stream.get16(); position.z = stream.get16(); size.x = stream.get16(); size.y = stream.get16(); size.z = stream.get16(); // object ID uint16_t objectID = stream.get16(); // size of object on disk; we've accounted for 20 bytes // already so we can subtract that to get the remaining // length beyond here uint32_t byteSizeOfObject = (uint32_t)(stream.get16() << 1) - 20; std::cout << "Object " << objectID << "; type " << (int)objectType << std::endl; switch(objectType) { default: { // read the appropriate number of colours int numberOfColours = GeometricObject::numberOfColoursForObjectOfType(objectType); std::vector<uint8_t> *colours = new std::vector<uint8_t>; for(uint8_t colour = 0; colour < numberOfColours; colour++) { colours->push_back(stream.get8()); byteSizeOfObject--; } // read extra vertices if required... int numberOfOrdinates = GeometricObject::numberOfOrdinatesForType(objectType); std::vector<uint16_t> *ordinates = nullptr; if(numberOfOrdinates) { ordinates = new std::vector<uint16_t>; for(int ordinate = 0; ordinate < numberOfOrdinates; ordinate++) { ordinates->push_back(stream.get16()); byteSizeOfObject -= 2; } } // grab the object condition, if there is one FCLInstructionVector instructions; if(byteSizeOfObject) { shared_ptr<vector<uint8_t>> conditionData = stream.nextBytes(byteSizeOfObject); shared_ptr<string> conditionSource = detokenise16bitCondition(*conditionData); instructions = getInstructions(conditionSource.get()); } byteSizeOfObject = 0; // create an object return new GeometricObject( objectType, objectID, position, size, colours, ordinates, instructions); } break; case Object::Entrance: case Object::Sensor: case Object::Group: break; } // skip whatever we didn't understand stream.skipBytes(byteSizeOfObject); return nullptr; } static shared_ptr<Area> loadArea(StreamLoader &stream) { // the lowest bit of this value seems to indicate // horizon on or off; this is as much as I currently know uint16_t skippedValue = stream.get16(); uint16_t numberOfObjects = stream.get16(); uint16_t areaNumber = stream.get16(); cout << "Area " << areaNumber << endl; cout << "Skipped value " << skippedValue << endl; cout << "Objects: " << numberOfObjects << endl; // I've yet to decipher this fully uint16_t horizonColour = stream.get16(); cout << "Horizon colour " << hex << (int)horizonColour << dec << endl; // this is just a complete guess for(int paletteEntry = 0; paletteEntry < 22; paletteEntry++) { uint8_t paletteColour = stream.get8(); cout << "Palette colour (?) " << hex << (int)paletteColour << dec << endl; } // we'll need to collate all objects and entrances; it's likely a // plain C array would do but maps are safer and the total application // cost is going to be negligible regardless ObjectMap *objectsByID = new ObjectMap; ObjectMap *entrancesByID = new ObjectMap; // get the objects or whatever; entrances use a unique numbering // system and have the high bit of their IDs set in the original file for(uint16_t object = 0; object < numberOfObjects; object++) { Object *newObject = loadObject(stream); if(newObject) { if(newObject->getType() == Object::Entrance) { (*entrancesByID)[newObject->getObjectID() & 0x7fff] = newObject; } else { (*objectsByID)[newObject->getObjectID()] = newObject; } } } return shared_ptr<Area>(new Area(areaNumber, objectsByID, entrancesByID)); } Game *load16bitBinary(vector <uint8_t> &binary) { StreamLoader streamLoader(binary); vector<uint8_t>::size_type baseOffset = 0; // check whether this looks like an Amiga game; if so it'll start with AM // XOR'd with the repeating byte pattern 0x71, 0xc1 or with the pattern // 0x88 0x2c if it's on the ST (though the signature will still be AM) uint16_t platformID = streamLoader.get16(); if( (platformID == 12428) || (platformID == 51553) ) { // TODO: record original platform type, so we can decode the palette // and possibly the border properly streamLoader.setReadMask((platformID >> 8) ^ 'A', (platformID & 0xff) ^ 'M'); } else { // find DOS end of file and consume it while(!streamLoader.eof() && streamLoader.get8() != 0x1a); streamLoader.get8(); // advance to the next two-byte boundary if necessary streamLoader.alignPointer(); // skip bytes with meaning unknown streamLoader.get16(); // this brings us to the beginning of the embedded // .KIT file, so we'll grab the base offset for // finding areas later baseOffset = streamLoader.getFileOffset(); // check that the next two bytes are "PC", then // skip the number that comes after if(streamLoader.get8() != 'C' || streamLoader.get8() != 'P') return nullptr; } // skip an unknown meaning streamLoader.get16(); // start grabbing some of the basics... uint16_t numberOfAreas = streamLoader.get16(); streamLoader.get16(); // meaning unknown cout << numberOfAreas << " Areas" << endl; uint16_t windowCentreX = streamLoader.get16(); uint16_t windowCentreY = streamLoader.get16(); uint16_t windowWidth = streamLoader.get16(); uint16_t windowHeight = streamLoader.get16(); cout << "Window centre: (" << windowCentreX << ", " << windowCentreY << ")" << endl; cout << "Window size: (" << windowWidth << ", " << windowHeight << ")" << endl; uint16_t scaleX = streamLoader.get16(); uint16_t scaleY = streamLoader.get16(); uint16_t scaleZ = streamLoader.get16(); cout << "Scale: " << scaleX << ", " << scaleY << ", " << scaleZ << endl; uint16_t timerReload = streamLoader.get16(); cout << "Timer: every " << timerReload << " 50Hz frames"; uint16_t maximumActivationDistance = streamLoader.get16(); uint16_t maximumFallDistance = streamLoader.get16(); uint16_t maximumClimbDistance = streamLoader.get16(); cout << "Maximum activation distance: " << maximumActivationDistance << endl; cout << "Maximum fall distance: " << maximumFallDistance << endl; cout << "Maximum climb distance: " << maximumClimbDistance << endl; uint16_t startArea = streamLoader.get16(); uint16_t startEntrance = streamLoader.get16(); cout << "Start at entrance " << startEntrance << " in area " << startArea << endl; uint16_t playerHeight = streamLoader.get16(); uint16_t playerStep = streamLoader.get16(); uint16_t playerAngle = streamLoader.get16(); cout << "Height " << playerHeight << ", stap " << playerStep << ", angle " << playerAngle << endl; uint16_t startVehicle = streamLoader.get16(); uint16_t executeGlobalCondition = streamLoader.get16(); cout << "Start vehicle " << startVehicle << ", execute global condition " << executeGlobalCondition << endl; // I haven't figured out what the next 106 // bytes mean, so we'll skip them — global objects // maybe? Likely not 106 bytes in every file. // // ADDED: having rediscovered my source for the 8bit // file format, could this be shading information by // analogy with that? streamLoader.skipBytes(106); // at this point I should properly load the border/key/mouse // bindings, but I'm not worried about it for now. // // Format is: // (left x, top y, right x, bottom y) - all 16 bit // keyboard key as an ASCII character (or zero for none) // mouse button masl; 00 = both, 01 = left, 02 = right // // So, 10 bytes per binding. Bindings are listed in the order: // // move forwards, move backwards, move right, move left, rise, // fall, turn left, turn right, look up, look down, tilt left, // tilt right, face forward, u-turn, change vehicle type, // select this vehicle, quit game, fire, activate object, // centre cursor on/off, save game position, load game position // // So 35 total. Which means this area takes up 350 bytes. streamLoader.skipBytes(350); // there are then file pointers for every area — these are // the number of shorts from the 'PC' tag, so multiply by // two for bytes. Each is four bytes uint32_t *fileOffsetForArea = new uint32_t[numberOfAreas]; for(uint16_t area = 0; area < numberOfAreas; area++) fileOffsetForArea[area] = (uint32_t)streamLoader.get32() << 1; // now come the global conditions uint16_t numberOfGlobalConditions = streamLoader.get16(); for(uint16_t globalCondition = 0; globalCondition < numberOfGlobalConditions; globalCondition++) { // 12 bytes for the name of the condition; // we don't care streamLoader.skipBytes(12); // get the length and the data itself, converting from // shorts to bytes uint32_t lengthOfCondition = (uint32_t)streamLoader.get16() << 1; // get the condition shared_ptr<vector<uint8_t>> conditionData = streamLoader.nextBytes(lengthOfCondition); cout << "Global condition " << globalCondition+1 << endl; cout << *detokenise16bitCondition(*conditionData) << endl; } // grab the areas AreaMap *areaMap = new AreaMap; for(uint16_t area = 0; area < numberOfAreas; area++) { // cout << "Area " << area+1 << endl; streamLoader.setFileOffset(fileOffsetForArea[area] + baseOffset); shared_ptr<Area> newArea = loadArea(streamLoader); if(newArea.get()) { (*areaMap)[newArea->getAreaID()] = newArea; } cout << endl; } delete[] fileOffsetForArea; return new Game(areaMap); } <commit_msg>Either the encryptions are more random than I thought or I’ve stumbled upon an Amiga 3d Construction Kit 2 file. I’m not sure yet.<commit_after>// // 16bitBinaryLoader.cpp // Phantasma // // Created by Thomas Harte on 17/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "16bitBinaryLoader.h" #include "Parser.h" #include "16bitDetokeniser.h" #include "Object.h" #include "Area.h" #include <map> class StreamLoader { private: vector<uint8_t>::size_type bytePointer; vector <uint8_t> binary; uint8_t readMaskByte1; uint8_t readMaskByte2; public: StreamLoader(vector <uint8_t> &_binary) { binary = _binary; bytePointer = 0; readMaskByte1 = 0; readMaskByte2 = 0; } uint8_t get8() { if(!eof()) { uint8_t sourceByte = binary[bytePointer]; if(bytePointer&1) sourceByte ^= readMaskByte2; else sourceByte ^= readMaskByte1; bytePointer++; return sourceByte; } return 0; } uint16_t get16() { uint16_t result = (uint16_t)(get8() << 8); result |= get8(); return result; } uint32_t get32() { uint32_t result = (uint32_t)(get16() << 16); result |= get16(); return result; } bool eof() { return bytePointer >= binary.size(); } void alignPointer() { if(bytePointer&1) bytePointer++; } void skipBytes(vector<uint8_t>::size_type numberOfBytes) { bytePointer += numberOfBytes; } shared_ptr<vector<uint8_t>> nextBytes(vector<uint8_t>::size_type numberOfBytes) { shared_ptr<vector<uint8_t>> returnBuffer(new vector<uint8_t>); while(numberOfBytes--) returnBuffer->push_back(get8()); return returnBuffer; } vector<uint8_t>::size_type getFileOffset() { return bytePointer; } void setFileOffset(vector<uint8_t>::size_type newOffset) { bytePointer = newOffset; } void setReadMask(uint8_t byte1, uint8_t byte2) { readMaskByte1 = byte1; readMaskByte2 = byte2; } }; static Object *loadObject(StreamLoader &stream) { // get object flags and type uint8_t objectFlags = stream.get8(); Object::Type objectType = (Object::Type)stream.get8(); // get unknown value uint16_t skippedShort = stream.get16(); // grab location, size Vector3d position, size; position.x = stream.get16(); position.y = stream.get16(); position.z = stream.get16(); size.x = stream.get16(); size.y = stream.get16(); size.z = stream.get16(); // object ID uint16_t objectID = stream.get16(); // size of object on disk; we've accounted for 20 bytes // already so we can subtract that to get the remaining // length beyond here uint32_t byteSizeOfObject = (uint32_t)(stream.get16() << 1) - 20; std::cout << "Object " << objectID << "; type " << (int)objectType << std::endl; switch(objectType) { default: { // read the appropriate number of colours int numberOfColours = GeometricObject::numberOfColoursForObjectOfType(objectType); std::vector<uint8_t> *colours = new std::vector<uint8_t>; for(uint8_t colour = 0; colour < numberOfColours; colour++) { colours->push_back(stream.get8()); byteSizeOfObject--; } // read extra vertices if required... int numberOfOrdinates = GeometricObject::numberOfOrdinatesForType(objectType); std::vector<uint16_t> *ordinates = nullptr; if(numberOfOrdinates) { ordinates = new std::vector<uint16_t>; for(int ordinate = 0; ordinate < numberOfOrdinates; ordinate++) { ordinates->push_back(stream.get16()); byteSizeOfObject -= 2; } } // grab the object condition, if there is one FCLInstructionVector instructions; if(byteSizeOfObject) { shared_ptr<vector<uint8_t>> conditionData = stream.nextBytes(byteSizeOfObject); shared_ptr<string> conditionSource = detokenise16bitCondition(*conditionData); instructions = getInstructions(conditionSource.get()); } byteSizeOfObject = 0; // create an object return new GeometricObject( objectType, objectID, position, size, colours, ordinates, instructions); } break; case Object::Entrance: case Object::Sensor: case Object::Group: break; } // skip whatever we didn't understand stream.skipBytes(byteSizeOfObject); return nullptr; } static shared_ptr<Area> loadArea(StreamLoader &stream) { // the lowest bit of this value seems to indicate // horizon on or off; this is as much as I currently know uint16_t skippedValue = stream.get16(); uint16_t numberOfObjects = stream.get16(); uint16_t areaNumber = stream.get16(); cout << "Area " << areaNumber << endl; cout << "Skipped value " << skippedValue << endl; cout << "Objects: " << numberOfObjects << endl; // I've yet to decipher this fully uint16_t horizonColour = stream.get16(); cout << "Horizon colour " << hex << (int)horizonColour << dec << endl; // this is just a complete guess for(int paletteEntry = 0; paletteEntry < 22; paletteEntry++) { uint8_t paletteColour = stream.get8(); cout << "Palette colour (?) " << hex << (int)paletteColour << dec << endl; } // we'll need to collate all objects and entrances; it's likely a // plain C array would do but maps are safer and the total application // cost is going to be negligible regardless ObjectMap *objectsByID = new ObjectMap; ObjectMap *entrancesByID = new ObjectMap; // get the objects or whatever; entrances use a unique numbering // system and have the high bit of their IDs set in the original file for(uint16_t object = 0; object < numberOfObjects; object++) { Object *newObject = loadObject(stream); if(newObject) { if(newObject->getType() == Object::Entrance) { (*entrancesByID)[newObject->getObjectID() & 0x7fff] = newObject; } else { (*objectsByID)[newObject->getObjectID()] = newObject; } } } return shared_ptr<Area>(new Area(areaNumber, objectsByID, entrancesByID)); } Game *load16bitBinary(vector <uint8_t> &binary) { StreamLoader streamLoader(binary); vector<uint8_t>::size_type baseOffset = 0; // check whether this looks like an Amiga game; if so it'll start with AM // XOR'd with the repeating byte pattern 0x71, 0xc1 or with the pattern // 0x88 0x2c if it's on the ST (though the signature will still be AM) uint16_t platformID = streamLoader.get16(); if( (platformID != 0x4120) // (platformID == 12428) || (platformID == 51553) ) { // TODO: record original platform type, so we can decode the palette // and possibly the border properly streamLoader.setReadMask((platformID >> 8) ^ 'A', (platformID & 0xff) ^ 'M'); } else { // find DOS end of file and consume it while(!streamLoader.eof() && streamLoader.get8() != 0x1a); streamLoader.get8(); // advance to the next two-byte boundary if necessary streamLoader.alignPointer(); // skip bytes with meaning unknown streamLoader.get16(); // this brings us to the beginning of the embedded // .KIT file, so we'll grab the base offset for // finding areas later baseOffset = streamLoader.getFileOffset(); // check that the next two bytes are "PC", then // skip the number that comes after if(streamLoader.get8() != 'C' || streamLoader.get8() != 'P') return nullptr; } // skip an unknown meaning streamLoader.get16(); // start grabbing some of the basics... uint16_t numberOfAreas = streamLoader.get16(); streamLoader.get16(); // meaning unknown cout << numberOfAreas << " Areas" << endl; uint16_t windowCentreX = streamLoader.get16(); uint16_t windowCentreY = streamLoader.get16(); uint16_t windowWidth = streamLoader.get16(); uint16_t windowHeight = streamLoader.get16(); cout << "Window centre: (" << windowCentreX << ", " << windowCentreY << ")" << endl; cout << "Window size: (" << windowWidth << ", " << windowHeight << ")" << endl; uint16_t scaleX = streamLoader.get16(); uint16_t scaleY = streamLoader.get16(); uint16_t scaleZ = streamLoader.get16(); cout << "Scale: " << scaleX << ", " << scaleY << ", " << scaleZ << endl; uint16_t timerReload = streamLoader.get16(); cout << "Timer: every " << timerReload << " 50Hz frames"; uint16_t maximumActivationDistance = streamLoader.get16(); uint16_t maximumFallDistance = streamLoader.get16(); uint16_t maximumClimbDistance = streamLoader.get16(); cout << "Maximum activation distance: " << maximumActivationDistance << endl; cout << "Maximum fall distance: " << maximumFallDistance << endl; cout << "Maximum climb distance: " << maximumClimbDistance << endl; uint16_t startArea = streamLoader.get16(); uint16_t startEntrance = streamLoader.get16(); cout << "Start at entrance " << startEntrance << " in area " << startArea << endl; uint16_t playerHeight = streamLoader.get16(); uint16_t playerStep = streamLoader.get16(); uint16_t playerAngle = streamLoader.get16(); cout << "Height " << playerHeight << ", stap " << playerStep << ", angle " << playerAngle << endl; uint16_t startVehicle = streamLoader.get16(); uint16_t executeGlobalCondition = streamLoader.get16(); cout << "Start vehicle " << startVehicle << ", execute global condition " << executeGlobalCondition << endl; // I haven't figured out what the next 106 // bytes mean, so we'll skip them — global objects // maybe? Likely not 106 bytes in every file. // // ADDED: having rediscovered my source for the 8bit // file format, could this be shading information by // analogy with that? streamLoader.skipBytes(106); // at this point I should properly load the border/key/mouse // bindings, but I'm not worried about it for now. // // Format is: // (left x, top y, right x, bottom y) - all 16 bit // keyboard key as an ASCII character (or zero for none) // mouse button masl; 00 = both, 01 = left, 02 = right // // So, 10 bytes per binding. Bindings are listed in the order: // // move forwards, move backwards, move right, move left, rise, // fall, turn left, turn right, look up, look down, tilt left, // tilt right, face forward, u-turn, change vehicle type, // select this vehicle, quit game, fire, activate object, // centre cursor on/off, save game position, load game position // // So 35 total. Which means this area takes up 350 bytes. streamLoader.skipBytes(350); // there are then file pointers for every area — these are // the number of shorts from the 'PC' tag, so multiply by // two for bytes. Each is four bytes uint32_t *fileOffsetForArea = new uint32_t[numberOfAreas]; for(uint16_t area = 0; area < numberOfAreas; area++) fileOffsetForArea[area] = (uint32_t)streamLoader.get32() << 1; // now come the global conditions uint16_t numberOfGlobalConditions = streamLoader.get16(); for(uint16_t globalCondition = 0; globalCondition < numberOfGlobalConditions; globalCondition++) { // 12 bytes for the name of the condition; // we don't care streamLoader.skipBytes(12); // get the length and the data itself, converting from // shorts to bytes uint32_t lengthOfCondition = (uint32_t)streamLoader.get16() << 1; // get the condition shared_ptr<vector<uint8_t>> conditionData = streamLoader.nextBytes(lengthOfCondition); cout << "Global condition " << globalCondition+1 << endl; cout << *detokenise16bitCondition(*conditionData) << endl; } // grab the areas AreaMap *areaMap = new AreaMap; for(uint16_t area = 0; area < numberOfAreas; area++) { // cout << "Area " << area+1 << endl; streamLoader.setFileOffset(fileOffsetForArea[area] + baseOffset); shared_ptr<Area> newArea = loadArea(streamLoader); if(newArea.get()) { (*areaMap)[newArea->getAreaID()] = newArea; } cout << endl; } delete[] fileOffsetForArea; return new Game(areaMap); } <|endoftext|>
<commit_before>#include "singletons.h" #include "config.h" #include "logging.h" #include <exception> #include "files.h" #include "sourcefile.h" MainConfig::MainConfig() { find_or_create_config_files(); boost::property_tree::json_parser::read_json(Singleton::config_dir() + "config.json", cfg); Singleton::Config::window()->keybindings = cfg.get_child("keybindings"); GenerateSource(); GenerateDirectoryFilter(); Singleton::Config::window()->theme_name=cfg.get<std::string>("gtk_theme.name"); Singleton::Config::window()->theme_variant=cfg.get<std::string>("gtk_theme.variant"); Singleton::Config::terminal()->make_command=cfg.get<std::string>("project.make_command"); Singleton::Config::terminal()->cmake_command=cfg.get<std::string>("project.cmake_command"); } void MainConfig::find_or_create_config_files() { std::vector<std::string> files = {"config.json", "menu.xml", "plugins.py"}; boost::filesystem::create_directories(boost::filesystem::path(Singleton::config_dir())); for (auto &file : files) { auto path = boost::filesystem::path(Singleton::config_dir() + file); if (!boost::filesystem::is_regular_file(path)) { if (file == "config.json") juci::filesystem::write(path, configjson); if (file == "plugins.py") juci::filesystem::write(path, pluginspy); if (file == "menu.xml") juci::filesystem::write(path, menuxml); } } boost::filesystem::create_directories(boost::filesystem::path(Singleton::style_dir())); boost::filesystem::path juci_style_path=Singleton::style_dir(); juci_style_path+="juci-light.xml"; if(!boost::filesystem::exists(juci_style_path)) juci::filesystem::write(juci_style_path, juci_light_style); juci_style_path=Singleton::style_dir(); juci_style_path+="juci-dark.xml"; if(!boost::filesystem::exists(juci_style_path)) juci::filesystem::write(juci_style_path, juci_dark_style); } void MainConfig::GenerateSource() { auto source_cfg = Singleton::Config::source(); auto source_json = cfg.get_child("source"); source_cfg->spellcheck_language = source_json.get<std::string>("spellcheck_language"); source_cfg->default_tab_char = source_json.get<char>("default_tab_char"); source_cfg->default_tab_size = source_json.get<unsigned>("default_tab_size"); source_cfg->auto_tab_char_and_size = source_json.get<bool>("auto_tab_char_and_size"); source_cfg->wrap_lines = source_json.get_value<bool>("wrap_lines"); source_cfg->highlight_current_line = source_json.get_value<bool>("highlight_current_line"); source_cfg->show_line_numbers = source_json.get_value<bool>("show_line_numbers"); for (auto &i : source_json.get_child("clang_types")) source_cfg->clang_types[i.first] = i.second.get_value<std::string>(); Singleton::Config::source()->style=source_json.get<std::string>("style"); source_cfg->font=source_json.get<std::string>("font"); } void MainConfig::GenerateDirectoryFilter() { auto dir_cfg=Singleton::Config::directories(); DEBUG("Fetching directory filter"); boost::property_tree::ptree dir_json = cfg.get_child("directoryfilter"); boost::property_tree::ptree ignore_json = dir_json.get_child("ignore"); boost::property_tree::ptree except_json = dir_json.get_child("exceptions"); for ( auto &i : except_json ) dir_cfg->exceptions.emplace_back(i.second.get_value<std::string>()); for ( auto &i : ignore_json ) dir_cfg->ignored.emplace_back(i.second.get_value<std::string>()); DEBUG("Directory filter fetched"); } <commit_msg>Fixed bug when reading config.json.<commit_after>#include "singletons.h" #include "config.h" #include "logging.h" #include <exception> #include "files.h" #include "sourcefile.h" MainConfig::MainConfig() { find_or_create_config_files(); boost::property_tree::json_parser::read_json(Singleton::config_dir() + "config.json", cfg); Singleton::Config::window()->keybindings = cfg.get_child("keybindings"); GenerateSource(); GenerateDirectoryFilter(); Singleton::Config::window()->theme_name=cfg.get<std::string>("gtk_theme.name"); Singleton::Config::window()->theme_variant=cfg.get<std::string>("gtk_theme.variant"); Singleton::Config::terminal()->make_command=cfg.get<std::string>("project.make_command"); Singleton::Config::terminal()->cmake_command=cfg.get<std::string>("project.cmake_command"); } void MainConfig::find_or_create_config_files() { std::vector<std::string> files = {"config.json", "menu.xml", "plugins.py"}; boost::filesystem::create_directories(boost::filesystem::path(Singleton::config_dir())); for (auto &file : files) { auto path = boost::filesystem::path(Singleton::config_dir() + file); if (!boost::filesystem::is_regular_file(path)) { if (file == "config.json") juci::filesystem::write(path, configjson); if (file == "plugins.py") juci::filesystem::write(path, pluginspy); if (file == "menu.xml") juci::filesystem::write(path, menuxml); } } boost::filesystem::create_directories(boost::filesystem::path(Singleton::style_dir())); boost::filesystem::path juci_style_path=Singleton::style_dir(); juci_style_path+="juci-light.xml"; if(!boost::filesystem::exists(juci_style_path)) juci::filesystem::write(juci_style_path, juci_light_style); juci_style_path=Singleton::style_dir(); juci_style_path+="juci-dark.xml"; if(!boost::filesystem::exists(juci_style_path)) juci::filesystem::write(juci_style_path, juci_dark_style); } void MainConfig::GenerateSource() { auto source_cfg = Singleton::Config::source(); auto source_json = cfg.get_child("source"); source_cfg->spellcheck_language = source_json.get<std::string>("spellcheck_language"); source_cfg->default_tab_char = source_json.get<char>("default_tab_char"); source_cfg->default_tab_size = source_json.get<unsigned>("default_tab_size"); source_cfg->auto_tab_char_and_size = source_json.get<bool>("auto_tab_char_and_size"); source_cfg->wrap_lines = source_json.get<bool>("wrap_lines"); source_cfg->highlight_current_line = source_json.get<bool>("highlight_current_line"); source_cfg->show_line_numbers = source_json.get<bool>("show_line_numbers"); for (auto &i : source_json.get_child("clang_types")) source_cfg->clang_types[i.first] = i.second.get_value<std::string>(); Singleton::Config::source()->style=source_json.get<std::string>("style"); source_cfg->font=source_json.get<std::string>("font"); } void MainConfig::GenerateDirectoryFilter() { auto dir_cfg=Singleton::Config::directories(); DEBUG("Fetching directory filter"); boost::property_tree::ptree dir_json = cfg.get_child("directoryfilter"); boost::property_tree::ptree ignore_json = dir_json.get_child("ignore"); boost::property_tree::ptree except_json = dir_json.get_child("exceptions"); for ( auto &i : except_json ) dir_cfg->exceptions.emplace_back(i.second.get_value<std::string>()); for ( auto &i : ignore_json ) dir_cfg->ignored.emplace_back(i.second.get_value<std::string>()); DEBUG("Directory filter fetched"); } <|endoftext|>
<commit_before><commit_msg>FEM: [skip ci] support Line and Plane objects in Constraint::getDirection()<commit_after><|endoftext|>
<commit_before>/********************************************************************* ** Author: Zach Colbert ** Date: 1 November 2017 ** Description: *********************************************************************/ // Pre-processing includes pre-requisite libraries for the functions below #include <string> // Make sure to include the header file where we declare the player and team classes! #include "Player.hpp" #include "Team.hpp" /********************************************************************* ** Description: The default constructor for the Player class takes no arguments, and sets the player's name and stats to default values. Default name: "" Default stats: -1 *********************************************************************/ Player::Player() { // Set player name to empty string setName(""); // Set player stats to -1 setPoints(-1); setRebounds(-1); setAssists(-1); } // This class doesn't get a default constructor, because there's no "I" in "Team" // REPLACE THIS COMMEMTN!!!!!!! Team::Team(Player::Player point_Guard, Player::Player shooting_Guard, Player::Player small_Forward, Player::Player power_Forward, Player::Player center_In) { // Set each of the positions using mutator functions setPointGuard(point_Guard); setShootingGuard(shooting_Guard); setSmallForward(small_Forward); setPowerForward(power_Forward); setCenter(center_In); } // Mutator for pointGuard void setPointGuard(Player::Player p) { pointGuard = p; } // Accessor for pointGuard Player::Player getPointGuard() { return pointGuard; } // Mutator for shootingGuard void setShootingGuard(Player::Player p) { shootingGuard = p; } // Accessor for shootingGuard Player::Player getShootingGuard() { return shootingGuard; } // Mutator for smallForward void setSmallForward(Player::Player p) { smallForward = p; } // Accessor for smallForward Player::Player getSmallForward() { return smallForward; } // Mutator for powerForward void setPowerForward(Player::Player p) { powerForward = p; } // Accessor for powerForward Player::Player getPowerForward() { return powerForward; } // Mutator for center void setCenter(Player::Player p) { center = p; } // Accessor for center Player::Player getCenter() { return center; } // totalPoints gets the points attribute from each of the member variables, and returns the total // REPLACE THIS COMMENT!!!!!!!! int totalPoints() { return pointGuard.getPoints() + shootingGuard.getPoints() + smallForward.getPoints() + powerForward.getPoints() + center.getPoints(); }<commit_msg>Comments finished<commit_after>/********************************************************************* ** Author: Zach Colbert ** Date: 1 November 2017 ** Description: *********************************************************************/ // Pre-processing includes pre-requisite libraries for the functions below #include <string> // Make sure to include the header file where we declare the player and team classes! #include "Player.hpp" #include "Team.hpp" /********************************************************************* ** Description: The constructor for the Team class takes five objects of the Player type as arguments, and sets them as positions on the team. Those positions are, in this order: ** Point Guard ** Shooting Guard ** Small Forward ** Power Forward ** Center This class does not have a default constructor because there is no "I" in "Team." ** Example: Team::Team myTeam(pointGuard, shootingGuard, smallForward, powerForward, center); *********************************************************************/ Team::Team(Player::Player point_Guard, Player::Player shooting_Guard, Player::Player small_Forward, Player::Player power_Forward, Player::Player center_In) { // Set each of the positions using mutator functions setPointGuard(point_Guard); setShootingGuard(shooting_Guard); setSmallForward(small_Forward); setPowerForward(power_Forward); setCenter(center_In); } // Mutator for pointGuard void setPointGuard(Player::Player p) { pointGuard = p; } // Accessor for pointGuard Player::Player getPointGuard() { return pointGuard; } // Mutator for shootingGuard void setShootingGuard(Player::Player p) { shootingGuard = p; } // Accessor for shootingGuard Player::Player getShootingGuard() { return shootingGuard; } // Mutator for smallForward void setSmallForward(Player::Player p) { smallForward = p; } // Accessor for smallForward Player::Player getSmallForward() { return smallForward; } // Mutator for powerForward void setPowerForward(Player::Player p) { powerForward = p; } // Accessor for powerForward Player::Player getPowerForward() { return powerForward; } // Mutator for center void setCenter(Player::Player p) { center = p; } // Accessor for center Player::Player getCenter() { return center; } /********************************************************************* ** Description: The totalPoints function of the Team class gets the points attribute from each Player object in the team, sums them, and returns the total value of points of all players on the team. ** Example: myTeam.totalPoints(); ** Example Output: 12; *********************************************************************/ int totalPoints() { return pointGuard.getPoints() + shootingGuard.getPoints() + smallForward.getPoints() + powerForward.getPoints() + center.getPoints(); }<|endoftext|>
<commit_before>#include "MicroBit.h" char MICROBIT_BLE_DEVICE_NAME[] = "BBC MicroBit [xxxxx]"; #if CONFIG_ENABLED(MICROBIT_BLE_ENABLED) && CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) const char MICROBIT_BLE_MANUFACTURER[] = "The Cast of W1A"; const char MICROBIT_BLE_MODEL[] = "Microbit SB2"; const char MICROBIT_BLE_SERIAL[] = "SN1"; const char MICROBIT_BLE_HARDWARE_VERSION[] = "0.2"; const char MICROBIT_BLE_FIRMWARE_VERSION[] = "1.1"; const char MICROBIT_BLE_SOFTWARE_VERSION[] = "1.0"; #endif /** * custom function for panic for malloc & new due to scoping issue. */ void panic(int statusCode) { uBit.panic(statusCode); } /** * Callback when a BLE GATT disconnect occurs. */ void bleDisconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason) { uBit.ble->startAdvertising(); } /** * Constructor. * Create a representation of a MicroBit device as a global singleton. * @param messageBus callback function to receive MicroBitMessageBus events. * * Exposed objects: * @code * uBit.systemTicker; //the Ticker callback that performs routines like updating the display. * uBit.MessageBus; //The message bus where events are fired. * uBit.display; //The display object for the LED matrix. * uBit.buttonA; //The buttonA object for button a. * uBit.buttonB; //The buttonB object for button b. * uBit.buttonAB; //The buttonAB object for button a+b multi press. * uBit.resetButton; //The resetButton used for soft resets. * uBit.accelerometer; //The object that represents the inbuilt accelerometer * uBit.compass; //The object that represents the inbuilt compass(magnetometer) * uBit.io.P*; //Where P* is P0 to P16, P19 & P20 on the edge connector * @endcode */ MicroBit::MicroBit() : flags(0x00), i2c(MICROBIT_PIN_SDA, MICROBIT_PIN_SCL), #if CONFIG_DISABLED(MICROBIT_DBG) serial(USBTX, USBRX), #endif MessageBus(), display(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_WIDTH, MICROBIT_DISPLAY_HEIGHT), buttonA(MICROBIT_ID_BUTTON_A,MICROBIT_PIN_BUTTON_A), buttonB(MICROBIT_ID_BUTTON_B,MICROBIT_PIN_BUTTON_B), buttonAB(MICROBIT_ID_BUTTON_AB,MICROBIT_ID_BUTTON_A,MICROBIT_ID_BUTTON_B), accelerometer(MICROBIT_ID_ACCELEROMETER, MMA8653_DEFAULT_ADDR), compass(MICROBIT_ID_COMPASS, MAG3110_DEFAULT_ADDR), thermometer(MICROBIT_ID_THERMOMETER), io(MICROBIT_ID_IO_P0,MICROBIT_ID_IO_P1,MICROBIT_ID_IO_P2, MICROBIT_ID_IO_P3,MICROBIT_ID_IO_P4,MICROBIT_ID_IO_P5, MICROBIT_ID_IO_P6,MICROBIT_ID_IO_P7,MICROBIT_ID_IO_P8, MICROBIT_ID_IO_P9,MICROBIT_ID_IO_P10,MICROBIT_ID_IO_P11, MICROBIT_ID_IO_P12,MICROBIT_ID_IO_P13,MICROBIT_ID_IO_P14, MICROBIT_ID_IO_P15,MICROBIT_ID_IO_P16,MICROBIT_ID_IO_P19, MICROBIT_ID_IO_P20) { } /** * Post constructor initialisation method. * After *MUCH* pain, it's noted that the BLE stack can't be brought up in a * static context, so we bring it up here rather than in the constructor. * n.b. This method *must* be called in main() or later, not before. * * Example: * @code * uBit.init(); * @endcode */ void MicroBit::init() { //add the display to the systemComponent array addSystemComponent(&uBit.display); //add the compass and accelerometer to the idle array addIdleComponent(&uBit.accelerometer); addIdleComponent(&uBit.compass); addIdleComponent(&uBit.MessageBus); // Seed our random number generator seedRandom(); #if CONFIG_ENABLED(MICROBIT_BLE_ENABLED) // Start the BLE stack. ble = new BLEDevice(); ble->init(); ble->onDisconnection(bleDisconnectionCallback); // Bring up any configured auxiliary services. #if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE) ble_firmware_update_service = new MicroBitDFUService(*ble); // Compute our auto-generated MicroBit device name. ble_firmware_update_service->getName(MICROBIT_BLE_DEVICE_NAME+14); #endif #if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) DeviceInformationService ble_device_information_service (*ble, MICROBIT_BLE_MANUFACTURER, MICROBIT_BLE_MODEL, MICROBIT_BLE_SERIAL, MICROBIT_BLE_HARDWARE_VERSION, MICROBIT_BLE_FIRMWARE_VERSION, MICROBIT_BLE_SOFTWARE_VERSION); #endif #if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE) ble_event_service = new MicroBitEventService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_LED_SERVICE) ble_led_service = new MicroBitLEDService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_ACCELEROMETER_SERVICE) ble_accelerometer_service = new MicroBitAccelerometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_MAGNETOMETER_SERVICE) ble_magnetometer_service = new MicroBitMagnetometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_BUTTON_SERVICE) ble_button_service = new MicroBitButtonService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_IO_PIN_SERVICE) ble_io_pin_service = new MicroBitIOPinService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_TEMPERATURE_SERVICE) ble_temperature_service = new MicroBitTemperatureService(*ble); #endif // Setup advertising. ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)MICROBIT_BLE_DEVICE_NAME, sizeof(MICROBIT_BLE_DEVICE_NAME)); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000)); ble->startAdvertising(); #endif // Start refreshing the Matrix Display systemTicker.attach(this, &MicroBit::systemTick, MICROBIT_DISPLAY_REFRESH_PERIOD); } /** * Will reset the micro:bit when called. * * Example: * @code * uBit.reset(); * @endcode */ void MicroBit::reset() { reset(); } /** * Delay for the given amount of time. * If the scheduler is running, this will deschedule the current fiber and perform * a power efficent, concurrent sleep operation. * If the scheduler is disabled or we're running in an interrupt context, this * will revert to a busy wait. * * @note Values of 6 and below tend to lose resolution - do you really need to sleep for this short amount of time? * * @param milliseconds the amount of time, in ms, to wait for. This number cannot be negative. * * Example: * @code * uBit.sleep(20); //sleep for 20ms * @endcode */ void MicroBit::sleep(int milliseconds) { //sanity check, we can't time travel... (yet?) if(milliseconds < 0) return; if (flags & MICROBIT_FLAG_SCHEDULER_RUNNING) fiber_sleep(milliseconds); else wait_ms(milliseconds); } /** * Generate a random number in the given range. * We use a simple Galois LFSR random number generator here, * as a Galois LFSR is sufficient for our applications, and much more lightweight * than the hardware random number generator built int the processor, which takes * a long time and uses a lot of energy. * * KIDS: You shouldn't use this is the real world to generte cryptographic keys though... * have a think why not. :-) * * @param max the upper range to generate a number for. This number cannot be negative * @return A random, natural number between 0 and the max-1. Or MICROBIT_INVALID_VALUE (defined in ErrorNo.h) if max is <= 0. * * Example: * @code * uBit.random(200); //a number between 0 and 199 * @endcode */ int MicroBit::random(int max) { //return MICROBIT_INVALID_VALUE if max is <= 0... if(max <= 0) return MICROBIT_INVALID_VALUE; // Cycle the LFSR (Linear Feedback Shift Register). // We use an optimal sequence with a period of 2^32-1, as defined by Bruce Schneider here (a true legend in the field!), // For those interested, it's documented in his paper: // "Pseudo-Random Sequence Generator for 32-Bit CPUs: A fast, machine-independent generator for 32-bit Microprocessors" randomValue = ((((randomValue >> 31) ^ (randomValue >> 6) ^ (randomValue >> 4) ^ (randomValue >> 2) ^ (randomValue >> 1) ^ randomValue) & 0x0000001) << 31 ) | (randomValue >> 1); return randomValue % max; } /** * Seed our a random number generator (RNG). * We use the NRF51822 in built cryptographic random number generator to seed a Galois LFSR. * We do this as the hardware RNG is relatively high power, and use the the BLE stack internally, * with a less than optimal application interface. A Galois LFSR is sufficient for our * applications, and much more lightweight. */ void MicroBit::seedRandom() { randomValue = 0; // Start the Random number generator. No need to leave it running... I hope. :-) NRF_RNG->TASKS_START = 1; for(int i = 0; i < 4 ;i++) { // Clear the VALRDY EVENT NRF_RNG->EVENTS_VALRDY = 0; // Wait for a number ot be generated. while ( NRF_RNG->EVENTS_VALRDY == 0); randomValue = (randomValue << 8) | ((int) NRF_RNG->VALUE); } // Disable the generator to save power. NRF_RNG->TASKS_STOP = 1; } /** * Periodic callback. Used by MicroBitDisplay, FiberScheduler and buttons. */ void MicroBit::systemTick() { // Scheduler callback. We do this here just as a single timer is more efficient. :-) if (uBit.flags & MICROBIT_FLAG_SCHEDULER_RUNNING) scheduler_tick(); //work out if any idle components need processing, if so prioritise the idle thread for(int i = 0; i < MICROBIT_IDLE_COMPONENTS; i++) if(idleThreadComponents[i] != NULL && idleThreadComponents[i]->isIdleCallbackNeeded()) { fiber_flags |= MICROBIT_FLAG_DATA_READY; break; } //update any components in the systemComponents array for(int i = 0; i < MICROBIT_SYSTEM_COMPONENTS; i++) if(systemTickComponents[i] != NULL) systemTickComponents[i]->systemTick(); } /** * System tasks to be executed by the idle thread when the Micro:Bit isn't busy or when data needs to be read. */ void MicroBit::systemTasks() { //call the idleTick member function indiscriminately for(int i = 0; i < MICROBIT_IDLE_COMPONENTS; i++) if(idleThreadComponents[i] != NULL) idleThreadComponents[i]->idleTick(); fiber_flags &= ~MICROBIT_FLAG_DATA_READY; } /** * add a component to the array of components which invocate the systemTick member function during a systemTick * @note this will be converted into a dynamic list of components */ void MicroBit::addSystemComponent(MicroBitComponent *component) { int i = 0; while(systemTickComponents[i] != NULL && i < MICROBIT_SYSTEM_COMPONENTS) i++; if(i == MICROBIT_SYSTEM_COMPONENTS) return; systemTickComponents[i] = component; } /** * remove a component from the array of components * @note this will be converted into a dynamic list of components */ void MicroBit::removeSystemComponent(MicroBitComponent *component) { int i = 0; while(systemTickComponents[i] != component && i < MICROBIT_SYSTEM_COMPONENTS) i++; if(i == MICROBIT_SYSTEM_COMPONENTS) return; systemTickComponents[i] = NULL; } /** * add a component to the array of components which invocate the systemTick member function during a systemTick * @note this will be converted into a dynamic list of components */ void MicroBit::addIdleComponent(MicroBitComponent *component) { int i = 0; while(idleThreadComponents[i] != NULL && i < MICROBIT_IDLE_COMPONENTS) i++; if(i == MICROBIT_IDLE_COMPONENTS) return; idleThreadComponents[i] = component; } /** * remove a component from the array of components * @note this will be converted into a dynamic list of components */ void MicroBit::removeIdleComponent(MicroBitComponent *component) { int i = 0; while(idleThreadComponents[i] != component && i < MICROBIT_IDLE_COMPONENTS) i++; if(i == MICROBIT_IDLE_COMPONENTS) return; idleThreadComponents[i] = NULL; } /** * Determine the time since this MicroBit was last reset. * * @return The time since the last reset, in milliseconds. This will result in overflow after 1.6 months. * TODO: handle overflow case. */ unsigned long MicroBit::systemTime() { return ticks; } /** * Triggers a microbit panic where an infinite loop will occur swapping between the panicFace and statusCode if provided. * * @param statusCode the status code of the associated error. Status codes must be in the range 0-255. */ void MicroBit::panic(int statusCode) { //show error and enter infinite while uBit.display.error(statusCode); } <commit_msg>microbit: Updated Bluetooth device name from MicroBit to micro:bit to match brand guidelines<commit_after>#include "MicroBit.h" char MICROBIT_BLE_DEVICE_NAME[] = "BBC micro:bit [xxxxx]"; #if CONFIG_ENABLED(MICROBIT_BLE_ENABLED) && CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) const char MICROBIT_BLE_MANUFACTURER[] = "The Cast of W1A"; const char MICROBIT_BLE_MODEL[] = "micro:bit"; const char MICROBIT_BLE_SERIAL[] = "SN1"; const char MICROBIT_BLE_HARDWARE_VERSION[] = "0.2"; const char MICROBIT_BLE_FIRMWARE_VERSION[] = "1.1"; const char MICROBIT_BLE_SOFTWARE_VERSION[] = "1.0"; #endif /** * custom function for panic for malloc & new due to scoping issue. */ void panic(int statusCode) { uBit.panic(statusCode); } /** * Callback when a BLE GATT disconnect occurs. */ void bleDisconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason) { uBit.ble->startAdvertising(); } /** * Constructor. * Create a representation of a MicroBit device as a global singleton. * @param messageBus callback function to receive MicroBitMessageBus events. * * Exposed objects: * @code * uBit.systemTicker; //the Ticker callback that performs routines like updating the display. * uBit.MessageBus; //The message bus where events are fired. * uBit.display; //The display object for the LED matrix. * uBit.buttonA; //The buttonA object for button a. * uBit.buttonB; //The buttonB object for button b. * uBit.buttonAB; //The buttonAB object for button a+b multi press. * uBit.resetButton; //The resetButton used for soft resets. * uBit.accelerometer; //The object that represents the inbuilt accelerometer * uBit.compass; //The object that represents the inbuilt compass(magnetometer) * uBit.io.P*; //Where P* is P0 to P16, P19 & P20 on the edge connector * @endcode */ MicroBit::MicroBit() : flags(0x00), i2c(MICROBIT_PIN_SDA, MICROBIT_PIN_SCL), #if CONFIG_DISABLED(MICROBIT_DBG) serial(USBTX, USBRX), #endif MessageBus(), display(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_WIDTH, MICROBIT_DISPLAY_HEIGHT), buttonA(MICROBIT_ID_BUTTON_A,MICROBIT_PIN_BUTTON_A), buttonB(MICROBIT_ID_BUTTON_B,MICROBIT_PIN_BUTTON_B), buttonAB(MICROBIT_ID_BUTTON_AB,MICROBIT_ID_BUTTON_A,MICROBIT_ID_BUTTON_B), accelerometer(MICROBIT_ID_ACCELEROMETER, MMA8653_DEFAULT_ADDR), compass(MICROBIT_ID_COMPASS, MAG3110_DEFAULT_ADDR), thermometer(MICROBIT_ID_THERMOMETER), io(MICROBIT_ID_IO_P0,MICROBIT_ID_IO_P1,MICROBIT_ID_IO_P2, MICROBIT_ID_IO_P3,MICROBIT_ID_IO_P4,MICROBIT_ID_IO_P5, MICROBIT_ID_IO_P6,MICROBIT_ID_IO_P7,MICROBIT_ID_IO_P8, MICROBIT_ID_IO_P9,MICROBIT_ID_IO_P10,MICROBIT_ID_IO_P11, MICROBIT_ID_IO_P12,MICROBIT_ID_IO_P13,MICROBIT_ID_IO_P14, MICROBIT_ID_IO_P15,MICROBIT_ID_IO_P16,MICROBIT_ID_IO_P19, MICROBIT_ID_IO_P20) { } /** * Post constructor initialisation method. * After *MUCH* pain, it's noted that the BLE stack can't be brought up in a * static context, so we bring it up here rather than in the constructor. * n.b. This method *must* be called in main() or later, not before. * * Example: * @code * uBit.init(); * @endcode */ void MicroBit::init() { //add the display to the systemComponent array addSystemComponent(&uBit.display); //add the compass and accelerometer to the idle array addIdleComponent(&uBit.accelerometer); addIdleComponent(&uBit.compass); addIdleComponent(&uBit.MessageBus); // Seed our random number generator seedRandom(); #if CONFIG_ENABLED(MICROBIT_BLE_ENABLED) // Start the BLE stack. ble = new BLEDevice(); ble->init(); ble->onDisconnection(bleDisconnectionCallback); // Bring up any configured auxiliary services. #if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE) ble_firmware_update_service = new MicroBitDFUService(*ble); // Compute our auto-generated MicroBit device name. ble_firmware_update_service->getName(MICROBIT_BLE_DEVICE_NAME+15); #endif #if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) DeviceInformationService ble_device_information_service (*ble, MICROBIT_BLE_MANUFACTURER, MICROBIT_BLE_MODEL, MICROBIT_BLE_SERIAL, MICROBIT_BLE_HARDWARE_VERSION, MICROBIT_BLE_FIRMWARE_VERSION, MICROBIT_BLE_SOFTWARE_VERSION); #endif #if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE) ble_event_service = new MicroBitEventService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_LED_SERVICE) ble_led_service = new MicroBitLEDService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_ACCELEROMETER_SERVICE) ble_accelerometer_service = new MicroBitAccelerometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_MAGNETOMETER_SERVICE) ble_magnetometer_service = new MicroBitMagnetometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_BUTTON_SERVICE) ble_button_service = new MicroBitButtonService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_IO_PIN_SERVICE) ble_io_pin_service = new MicroBitIOPinService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_TEMPERATURE_SERVICE) ble_temperature_service = new MicroBitTemperatureService(*ble); #endif // Setup advertising. ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)MICROBIT_BLE_DEVICE_NAME, sizeof(MICROBIT_BLE_DEVICE_NAME)); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000)); ble->startAdvertising(); #endif // Start refreshing the Matrix Display systemTicker.attach(this, &MicroBit::systemTick, MICROBIT_DISPLAY_REFRESH_PERIOD); } /** * Will reset the micro:bit when called. * * Example: * @code * uBit.reset(); * @endcode */ void MicroBit::reset() { reset(); } /** * Delay for the given amount of time. * If the scheduler is running, this will deschedule the current fiber and perform * a power efficent, concurrent sleep operation. * If the scheduler is disabled or we're running in an interrupt context, this * will revert to a busy wait. * * @note Values of 6 and below tend to lose resolution - do you really need to sleep for this short amount of time? * * @param milliseconds the amount of time, in ms, to wait for. This number cannot be negative. * * Example: * @code * uBit.sleep(20); //sleep for 20ms * @endcode */ void MicroBit::sleep(int milliseconds) { //sanity check, we can't time travel... (yet?) if(milliseconds < 0) return; if (flags & MICROBIT_FLAG_SCHEDULER_RUNNING) fiber_sleep(milliseconds); else wait_ms(milliseconds); } /** * Generate a random number in the given range. * We use a simple Galois LFSR random number generator here, * as a Galois LFSR is sufficient for our applications, and much more lightweight * than the hardware random number generator built int the processor, which takes * a long time and uses a lot of energy. * * KIDS: You shouldn't use this is the real world to generte cryptographic keys though... * have a think why not. :-) * * @param max the upper range to generate a number for. This number cannot be negative * @return A random, natural number between 0 and the max-1. Or MICROBIT_INVALID_VALUE (defined in ErrorNo.h) if max is <= 0. * * Example: * @code * uBit.random(200); //a number between 0 and 199 * @endcode */ int MicroBit::random(int max) { //return MICROBIT_INVALID_VALUE if max is <= 0... if(max <= 0) return MICROBIT_INVALID_VALUE; // Cycle the LFSR (Linear Feedback Shift Register). // We use an optimal sequence with a period of 2^32-1, as defined by Bruce Schneider here (a true legend in the field!), // For those interested, it's documented in his paper: // "Pseudo-Random Sequence Generator for 32-Bit CPUs: A fast, machine-independent generator for 32-bit Microprocessors" randomValue = ((((randomValue >> 31) ^ (randomValue >> 6) ^ (randomValue >> 4) ^ (randomValue >> 2) ^ (randomValue >> 1) ^ randomValue) & 0x0000001) << 31 ) | (randomValue >> 1); return randomValue % max; } /** * Seed our a random number generator (RNG). * We use the NRF51822 in built cryptographic random number generator to seed a Galois LFSR. * We do this as the hardware RNG is relatively high power, and use the the BLE stack internally, * with a less than optimal application interface. A Galois LFSR is sufficient for our * applications, and much more lightweight. */ void MicroBit::seedRandom() { randomValue = 0; // Start the Random number generator. No need to leave it running... I hope. :-) NRF_RNG->TASKS_START = 1; for(int i = 0; i < 4 ;i++) { // Clear the VALRDY EVENT NRF_RNG->EVENTS_VALRDY = 0; // Wait for a number ot be generated. while ( NRF_RNG->EVENTS_VALRDY == 0); randomValue = (randomValue << 8) | ((int) NRF_RNG->VALUE); } // Disable the generator to save power. NRF_RNG->TASKS_STOP = 1; } /** * Periodic callback. Used by MicroBitDisplay, FiberScheduler and buttons. */ void MicroBit::systemTick() { // Scheduler callback. We do this here just as a single timer is more efficient. :-) if (uBit.flags & MICROBIT_FLAG_SCHEDULER_RUNNING) scheduler_tick(); //work out if any idle components need processing, if so prioritise the idle thread for(int i = 0; i < MICROBIT_IDLE_COMPONENTS; i++) if(idleThreadComponents[i] != NULL && idleThreadComponents[i]->isIdleCallbackNeeded()) { fiber_flags |= MICROBIT_FLAG_DATA_READY; break; } //update any components in the systemComponents array for(int i = 0; i < MICROBIT_SYSTEM_COMPONENTS; i++) if(systemTickComponents[i] != NULL) systemTickComponents[i]->systemTick(); } /** * System tasks to be executed by the idle thread when the Micro:Bit isn't busy or when data needs to be read. */ void MicroBit::systemTasks() { //call the idleTick member function indiscriminately for(int i = 0; i < MICROBIT_IDLE_COMPONENTS; i++) if(idleThreadComponents[i] != NULL) idleThreadComponents[i]->idleTick(); fiber_flags &= ~MICROBIT_FLAG_DATA_READY; } /** * add a component to the array of components which invocate the systemTick member function during a systemTick * @note this will be converted into a dynamic list of components */ void MicroBit::addSystemComponent(MicroBitComponent *component) { int i = 0; while(systemTickComponents[i] != NULL && i < MICROBIT_SYSTEM_COMPONENTS) i++; if(i == MICROBIT_SYSTEM_COMPONENTS) return; systemTickComponents[i] = component; } /** * remove a component from the array of components * @note this will be converted into a dynamic list of components */ void MicroBit::removeSystemComponent(MicroBitComponent *component) { int i = 0; while(systemTickComponents[i] != component && i < MICROBIT_SYSTEM_COMPONENTS) i++; if(i == MICROBIT_SYSTEM_COMPONENTS) return; systemTickComponents[i] = NULL; } /** * add a component to the array of components which invocate the systemTick member function during a systemTick * @note this will be converted into a dynamic list of components */ void MicroBit::addIdleComponent(MicroBitComponent *component) { int i = 0; while(idleThreadComponents[i] != NULL && i < MICROBIT_IDLE_COMPONENTS) i++; if(i == MICROBIT_IDLE_COMPONENTS) return; idleThreadComponents[i] = component; } /** * remove a component from the array of components * @note this will be converted into a dynamic list of components */ void MicroBit::removeIdleComponent(MicroBitComponent *component) { int i = 0; while(idleThreadComponents[i] != component && i < MICROBIT_IDLE_COMPONENTS) i++; if(i == MICROBIT_IDLE_COMPONENTS) return; idleThreadComponents[i] = NULL; } /** * Determine the time since this MicroBit was last reset. * * @return The time since the last reset, in milliseconds. This will result in overflow after 1.6 months. * TODO: handle overflow case. */ unsigned long MicroBit::systemTime() { return ticks; } /** * Triggers a microbit panic where an infinite loop will occur swapping between the panicFace and statusCode if provided. * * @param statusCode the status code of the associated error. Status codes must be in the range 0-255. */ void MicroBit::panic(int statusCode) { //show error and enter infinite while uBit.display.error(statusCode); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkDicomSeriesReader.h" #include "mitkTestingMacros.h" #include "mitkImageStatisticsCalculator.h" #include "mitkPlanarPolygon.h" #include "mitkDicomSeriesReader.h" #include <itkGDCMSeriesFileNames.h> //#include <QtCore> /** * \brief Test class for mitkImageStatisticsCalculator * * This test covers: * - instantiation of an ImageStatisticsCalculator class * - correctness of statistics when using PlanarFigures for masking */ class mitkImageStatisticsCalculatorTestClass { public: struct testCase { int id; mitk::PlanarFigure::Pointer figure; double mean; double sd; }; // calculate statistics for the given image and planarpolygon static const mitk::ImageStatisticsCalculator::Statistics TestStatistics( mitk::Image::Pointer image, mitk::PlanarFigure::Pointer polygon ) { mitk::ImageStatisticsCalculator::Pointer statisticsCalculator = mitk::ImageStatisticsCalculator::New(); statisticsCalculator->SetImage( image ); statisticsCalculator->SetMaskingModeToPlanarFigure(); statisticsCalculator->SetPlanarFigure( polygon ); statisticsCalculator->ComputeStatistics(); return statisticsCalculator->GetStatistics(); } // returns a vector of defined test-cases static std::vector<testCase> InitializeTestCases( mitk::Geometry2D::Pointer geom ) { std::vector<testCase> testCases; { /***************************** * one whole white pixel * -> mean of 255 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 10.5 ; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 10.5; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 255.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * half pixel in x-direction (white) * -> mean of 255 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 10.0 ; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 10.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 255.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * whole pixel (white) + half pixel (gray) in x-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * quarter pixel (black) + whole pixel (white) + half pixel (gray) in x-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.25; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.25; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * half pixel (black) + whole pixel (white) + half pixel (gray) in x-direction * -> mean of 127.67 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.0; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.0; pnt3[1] = 4.0; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.0; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 127.67; test.sd = 127.5; testCases.push_back( test ); } { /***************************** * whole pixel (gray) * -> mean of 128 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 11.5; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 11.5; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 128.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * whole pixel (gray) + half pixel (white) in y-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 12.0; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 12.0; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * whole pixel (gray) + whole pixel (white) + whole pixel (black) in y-direction * -> mean of 127.67 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 13.5; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 13.5; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 127.67; test.sd = 127.5; testCases.push_back( test ); } return testCases; } // loads the test image static mitk::Image::Pointer GetTestImage() { mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); const std::string filename = locator->FindFile("testimage.dcm", "Modules\\MitkExt\\Testing\\Data"); if (filename.empty()) { MITK_ERROR << "Could not find test file"; return NULL; } else { MITK_INFO << "Found testimage.dcm"; } itk::FilenamesContainer file; file.push_back( filename ); mitk::DicomSeriesReader* reader = new mitk::DicomSeriesReader; mitk::DataNode::Pointer node = reader->LoadDicomSeries( file, false, false ); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() ); return image; } }; int mitkImageStatisticsCalculatorTest(int argc, char* argv[]) { // always start with this! MITK_TEST_BEGIN("mitkImageStatisticsCalculatorTest") //QCoreApplication app(argc, argv); mitk::Image::Pointer image = mitkImageStatisticsCalculatorTestClass::GetTestImage(); MITK_TEST_CONDITION_REQUIRED( image.IsNotNull(), "Loading test image" ); mitk::Geometry2D::Pointer geom = image->GetSlicedGeometry()->GetGeometry2D(0); std::vector<mitkImageStatisticsCalculatorTestClass::testCase> allTestCases = mitkImageStatisticsCalculatorTestClass::InitializeTestCases( geom ); for ( int i=0; i<allTestCases.size(); i++ ) { mitkImageStatisticsCalculatorTestClass::testCase test = allTestCases[i]; const mitk::ImageStatisticsCalculator::Statistics stats = mitkImageStatisticsCalculatorTestClass::TestStatistics( image, test.figure ); MITK_TEST_CONDITION( int(stats.Mean) == int(test.mean), "Calculated mean grayvalue '"<< stats.Mean <<"' is equal to the desired value '" << test.mean <<"' for testcase #" << test.id ); MITK_TEST_CONDITION( int(stats.Sigma) == int(test.sd), "Calculated grayvalue sd '"<< stats.Sigma <<"' is equal to the desired value '" << test.sd <<"' for testcase #" << test.id ); //MITK_TEST_CONDITION( int(stats.Sigma) == int(test.sd), // qPrintable( QString("Calculated grayvalue sd '%1' is equal to the desired value '%2' for testcase #%3") // .arg(stats.Sigma).arg( test.sd ).arg( test.id ) ) ); } MITK_TEST_END() } <commit_msg>fixing failing test, seems like path was falsely formatted for linux<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkDicomSeriesReader.h" #include "mitkTestingMacros.h" #include "mitkImageStatisticsCalculator.h" #include "mitkPlanarPolygon.h" #include "mitkDicomSeriesReader.h" #include <itkGDCMSeriesFileNames.h> //#include <QtCore> /** * \brief Test class for mitkImageStatisticsCalculator * * This test covers: * - instantiation of an ImageStatisticsCalculator class * - correctness of statistics when using PlanarFigures for masking */ class mitkImageStatisticsCalculatorTestClass { public: struct testCase { int id; mitk::PlanarFigure::Pointer figure; double mean; double sd; }; // calculate statistics for the given image and planarpolygon static const mitk::ImageStatisticsCalculator::Statistics TestStatistics( mitk::Image::Pointer image, mitk::PlanarFigure::Pointer polygon ) { mitk::ImageStatisticsCalculator::Pointer statisticsCalculator = mitk::ImageStatisticsCalculator::New(); statisticsCalculator->SetImage( image ); statisticsCalculator->SetMaskingModeToPlanarFigure(); statisticsCalculator->SetPlanarFigure( polygon ); statisticsCalculator->ComputeStatistics(); return statisticsCalculator->GetStatistics(); } // returns a vector of defined test-cases static std::vector<testCase> InitializeTestCases( mitk::Geometry2D::Pointer geom ) { std::vector<testCase> testCases; { /***************************** * one whole white pixel * -> mean of 255 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 10.5 ; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 10.5; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 255.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * half pixel in x-direction (white) * -> mean of 255 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 10.0 ; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 10.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 255.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * whole pixel (white) + half pixel (gray) in x-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.5; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.5; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * quarter pixel (black) + whole pixel (white) + half pixel (gray) in x-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.25; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.25; pnt3[1] = 4.5; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.5; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * half pixel (black) + whole pixel (white) + half pixel (gray) in x-direction * -> mean of 127.67 expected ******************************/ mitk::PlanarPolygon::Pointer figure1 = mitk::PlanarPolygon::New(); figure1->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.0; pnt1[1] = 3.5; figure1->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 9.0; pnt2[1] = 3.5; figure1->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 9.0; pnt3[1] = 4.0; figure1->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 11.0; pnt4[1] = 4.0; figure1->SetControlPoint( 3, pnt4, true ); figure1->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure1; test.mean = 127.67; test.sd = 127.5; testCases.push_back( test ); } { /***************************** * whole pixel (gray) * -> mean of 128 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 11.5; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 11.5; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 128.0; test.sd = 0.0; testCases.push_back( test ); } { /***************************** * whole pixel (gray) + half pixel (white) in y-direction * -> mean of 191.5 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 12.0; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 12.0; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 191.5; test.sd = 89.8025; testCases.push_back( test ); } { /***************************** * whole pixel (gray) + whole pixel (white) + whole pixel (black) in y-direction * -> mean of 127.67 expected ******************************/ mitk::PlanarPolygon::Pointer figure2 = mitk::PlanarPolygon::New(); figure2->SetGeometry2D( geom ); mitk::Point2D pnt1; pnt1[0] = 11.5; pnt1[1] = 10.5; figure2->PlaceFigure( pnt1 ); mitk::Point2D pnt2; pnt2[0] = 11.5; pnt2[1] = 13.5; figure2->SetControlPoint( 1, pnt2, true ); mitk::Point2D pnt3; pnt3[0] = 12.5; pnt3[1] = 13.5; figure2->SetControlPoint( 2, pnt3, true ); mitk::Point2D pnt4; pnt4[0] = 12.5; pnt4[1] = 10.5; figure2->SetControlPoint( 3, pnt4, true ); figure2->GetPolyLine(0); testCase test; test.id = testCases.size(); test.figure = figure2; test.mean = 127.67; test.sd = 127.5; testCases.push_back( test ); } return testCases; } // loads the test image static mitk::Image::Pointer GetTestImage() { mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); const std::string filename = locator->FindFile("testimage.dcm", "Modules/MitkExt/Testing/Data"); if (filename.empty()) { MITK_ERROR << "Could not find test file"; return NULL; } else { MITK_INFO << "Found testimage.dcm"; } itk::FilenamesContainer file; file.push_back( filename ); mitk::DicomSeriesReader* reader = new mitk::DicomSeriesReader; mitk::DataNode::Pointer node = reader->LoadDicomSeries( file, false, false ); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() ); return image; } }; int mitkImageStatisticsCalculatorTest(int argc, char* argv[]) { // always start with this! MITK_TEST_BEGIN("mitkImageStatisticsCalculatorTest") //QCoreApplication app(argc, argv); mitk::Image::Pointer image = mitkImageStatisticsCalculatorTestClass::GetTestImage(); MITK_TEST_CONDITION_REQUIRED( image.IsNotNull(), "Loading test image" ); mitk::Geometry2D::Pointer geom = image->GetSlicedGeometry()->GetGeometry2D(0); std::vector<mitkImageStatisticsCalculatorTestClass::testCase> allTestCases = mitkImageStatisticsCalculatorTestClass::InitializeTestCases( geom ); for ( int i=0; i<allTestCases.size(); i++ ) { mitkImageStatisticsCalculatorTestClass::testCase test = allTestCases[i]; const mitk::ImageStatisticsCalculator::Statistics stats = mitkImageStatisticsCalculatorTestClass::TestStatistics( image, test.figure ); MITK_TEST_CONDITION( int(stats.Mean) == int(test.mean), "Calculated mean grayvalue '"<< stats.Mean <<"' is equal to the desired value '" << test.mean <<"' for testcase #" << test.id ); MITK_TEST_CONDITION( int(stats.Sigma) == int(test.sd), "Calculated grayvalue sd '"<< stats.Sigma <<"' is equal to the desired value '" << test.sd <<"' for testcase #" << test.id ); //MITK_TEST_CONDITION( int(stats.Sigma) == int(test.sd), // qPrintable( QString("Calculated grayvalue sd '%1' is equal to the desired value '%2' for testcase #%3") // .arg(stats.Sigma).arg( test.sd ).arg( test.id ) ) ); } MITK_TEST_END() } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2010 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRepAdaptor_Surface.hxx> # include <BRepAlgoAPI_Common.hxx> # include <BRepAlgoAPI_Cut.hxx> # include <BRepAlgoAPI_Section.hxx> # include <BRepBuilderAPI_MakeFace.hxx> # include <BRepBuilderAPI_MakeWire.hxx> # include <BRepGProp_Face.hxx> # include <BRepPrimAPI_MakeHalfSpace.hxx> # include <gp_Pln.hxx> # include <Precision.hxx> # include <ShapeFix_Wire.hxx> # include <ShapeAnalysis_FreeBounds.hxx> # include <TopExp.hxx> # include <TopExp_Explorer.hxx> # include <TopTools_IndexedMapOfShape.hxx> # include <TopTools_HSequenceOfShape.hxx> # include <TopoDS.hxx> # include <TopoDS_Edge.hxx> # include <TopoDS_Wire.hxx> #endif #include "CrossSection.h" using namespace Part; CrossSection::CrossSection(double a, double b, double c, const TopoDS_Shape& s) : a(a), b(b), c(c), s(s) { } std::list<TopoDS_Wire> CrossSection::slice(double d) const { std::list<TopoDS_Wire> wires; // Fixes: 0001228: Cross section of Torus in Part Workbench fails or give wrong results // Fixes: 0001137: Incomplete slices when using Part.slice on a torus TopExp_Explorer xp; for (xp.Init(s, TopAbs_SOLID); xp.More(); xp.Next()) { sliceSolid(d, xp.Current(), wires); } for (xp.Init(s, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next()) { sliceNonSolid(d, xp.Current(), wires); } for (xp.Init(s, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next()) { sliceNonSolid(d, xp.Current(), wires); } return wires; } void CrossSection::sliceNonSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const { BRepAlgoAPI_Section cs(shape, gp_Pln(a,b,c,-d)); if (cs.IsDone()) { std::list<TopoDS_Edge> edges; TopExp_Explorer xp; for (xp.Init(cs.Shape(), TopAbs_EDGE); xp.More(); xp.Next()) edges.push_back(TopoDS::Edge(xp.Current())); connectEdges(edges, wires); } } void CrossSection::sliceSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const { #if 0 gp_Pln slicePlane(a,b,c,-d); BRepBuilderAPI_MakeFace mkFace(slicePlane); TopoDS_Face face = mkFace.Face(); BRepAlgoAPI_Common mkInt(shape, face); if (mkInt.IsDone()) { // sort and repair the wires TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(mkInt.Shape(), TopAbs_WIRE, mapOfWires); connectWires(mapOfWires, wires); } #else gp_Pln slicePlane(a,b,c,-d); BRepBuilderAPI_MakeFace mkFace(slicePlane); TopoDS_Face face = mkFace.Face(); BRepPrimAPI_MakeHalfSpace mkSolid(face, gp_Pnt(0,0,d-1)); TopoDS_Solid solid = mkSolid.Solid(); BRepAlgoAPI_Cut mkCut(shape, solid); if (mkCut.IsDone()) { TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(mkCut.Shape(), TopAbs_FACE, mapOfFaces); for (int i=1; i<=mapOfFaces.Extent(); i++) { const TopoDS_Face& face = TopoDS::Face(mapOfFaces.FindKey(i)); BRepAdaptor_Surface adapt(face); if (adapt.GetType() == GeomAbs_Plane) { gp_Pln plane = adapt.Plane(); if (plane.Axis().IsParallel(slicePlane.Axis(), Precision::Confusion()) && plane.Distance(slicePlane.Location()) < Precision::Confusion()) { // sort and repair the wires TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(face, TopAbs_WIRE, mapOfWires); connectWires(mapOfWires, wires); } } } } #endif } void CrossSection::connectEdges (const std::list<TopoDS_Edge>& edges, std::list<TopoDS_Wire>& wires) const { // FIXME: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative std::list<TopoDS_Edge> edge_list = edges; while (edge_list.size() > 0) { BRepBuilderAPI_MakeWire mkWire; // add and erase first edge mkWire.Add(edge_list.front()); edge_list.erase(edge_list.begin()); TopoDS_Wire new_wire = mkWire.Wire(); // current new wire // try to connect each edge to the wire, the wire is complete if no more egdes are connectible bool found = false; do { found = false; for (std::list<TopoDS_Edge>::iterator pE = edge_list.begin(); pE != edge_list.end();++pE) { mkWire.Add(*pE); if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) { // edge added ==> remove it from list found = true; edge_list.erase(pE); new_wire = mkWire.Wire(); break; } } } while (found); // Fix any topological issues of the wire ShapeFix_Wire aFix; aFix.SetPrecision(Precision::Confusion()); aFix.Load(new_wire); aFix.FixReorder(); aFix.FixConnected(); aFix.FixClosed(); wires.push_back(aFix.Wire()); } } void CrossSection::connectWires (const TopTools_IndexedMapOfShape& wireMap, std::list<TopoDS_Wire>& wires) const { Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); for (int i=1; i<=wireMap.Extent(); i++) { const TopoDS_Shape& wire = wireMap.FindKey(i); hWires->Append(wire); } Handle(TopTools_HSequenceOfShape) hSorted = new TopTools_HSequenceOfShape(); ShapeAnalysis_FreeBounds::ConnectWiresToWires(hWires, Precision::Confusion(), false, hSorted); for (int i=1; i<=hSorted->Length(); i++) { const TopoDS_Wire& new_wire = TopoDS::Wire(hSorted->Value(i)); // Fix any topological issues of the wire ShapeFix_Wire aFix; aFix.SetPrecision(Precision::Confusion()); aFix.Load(new_wire); aFix.FixReorder(); aFix.FixConnected(); aFix.FixClosed(); wires.push_back(aFix.Wire()); } } <commit_msg>0001228: Cross section of Torus in Part Workbench fails or give wrong results<commit_after>/*************************************************************************** * Copyright (c) 2010 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRepAdaptor_Surface.hxx> # include <BRepAlgoAPI_Common.hxx> # include <BRepAlgoAPI_Cut.hxx> # include <BRepAlgoAPI_Section.hxx> # include <BRepBuilderAPI_MakeFace.hxx> # include <BRepBuilderAPI_MakeWire.hxx> # include <BRepGProp_Face.hxx> # include <BRepPrimAPI_MakeHalfSpace.hxx> # include <gp_Pln.hxx> # include <Precision.hxx> # include <ShapeFix_Wire.hxx> # include <ShapeAnalysis_FreeBounds.hxx> # include <TopExp.hxx> # include <TopExp_Explorer.hxx> # include <TopTools_IndexedMapOfShape.hxx> # include <TopTools_HSequenceOfShape.hxx> # include <TopoDS.hxx> # include <TopoDS_Edge.hxx> # include <TopoDS_Wire.hxx> #endif #include "CrossSection.h" using namespace Part; CrossSection::CrossSection(double a, double b, double c, const TopoDS_Shape& s) : a(a), b(b), c(c), s(s) { } std::list<TopoDS_Wire> CrossSection::slice(double d) const { std::list<TopoDS_Wire> wires; // Fixes: 0001228: Cross section of Torus in Part Workbench fails or give wrong results // Fixes: 0001137: Incomplete slices when using Part.slice on a torus TopExp_Explorer xp; for (xp.Init(s, TopAbs_SOLID); xp.More(); xp.Next()) { sliceSolid(d, xp.Current(), wires); } for (xp.Init(s, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next()) { sliceNonSolid(d, xp.Current(), wires); } for (xp.Init(s, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next()) { sliceNonSolid(d, xp.Current(), wires); } return wires; } void CrossSection::sliceNonSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const { BRepAlgoAPI_Section cs(shape, gp_Pln(a,b,c,-d)); if (cs.IsDone()) { std::list<TopoDS_Edge> edges; TopExp_Explorer xp; for (xp.Init(cs.Shape(), TopAbs_EDGE); xp.More(); xp.Next()) edges.push_back(TopoDS::Edge(xp.Current())); connectEdges(edges, wires); } } void CrossSection::sliceSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const { #if 0 gp_Pln slicePlane(a,b,c,-d); BRepBuilderAPI_MakeFace mkFace(slicePlane); TopoDS_Face face = mkFace.Face(); BRepAlgoAPI_Common mkInt(shape, face); if (mkInt.IsDone()) { // sort and repair the wires TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(mkInt.Shape(), TopAbs_WIRE, mapOfWires); connectWires(mapOfWires, wires); } #else gp_Pln slicePlane(a,b,c,-d); BRepBuilderAPI_MakeFace mkFace(slicePlane); TopoDS_Face face = mkFace.Face(); // Make sure to choose a point that does not lie on the plane (fixes #0001228) gp_Vec tempVector(a,b,c); tempVector.Normalize();//just in case. tempVector *= (d+1.0); gp_Pnt refPoint(0.0d, 0.0d, 0.0d); refPoint.Translate(tempVector); BRepPrimAPI_MakeHalfSpace mkSolid(face, refPoint); TopoDS_Solid solid = mkSolid.Solid(); BRepAlgoAPI_Cut mkCut(shape, solid); if (mkCut.IsDone()) { TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(mkCut.Shape(), TopAbs_FACE, mapOfFaces); for (int i=1; i<=mapOfFaces.Extent(); i++) { const TopoDS_Face& face = TopoDS::Face(mapOfFaces.FindKey(i)); BRepAdaptor_Surface adapt(face); if (adapt.GetType() == GeomAbs_Plane) { gp_Pln plane = adapt.Plane(); if (plane.Axis().IsParallel(slicePlane.Axis(), Precision::Confusion()) && plane.Distance(slicePlane.Location()) < Precision::Confusion()) { // sort and repair the wires TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(face, TopAbs_WIRE, mapOfWires); connectWires(mapOfWires, wires); } } } } #endif } void CrossSection::connectEdges (const std::list<TopoDS_Edge>& edges, std::list<TopoDS_Wire>& wires) const { // FIXME: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative std::list<TopoDS_Edge> edge_list = edges; while (edge_list.size() > 0) { BRepBuilderAPI_MakeWire mkWire; // add and erase first edge mkWire.Add(edge_list.front()); edge_list.erase(edge_list.begin()); TopoDS_Wire new_wire = mkWire.Wire(); // current new wire // try to connect each edge to the wire, the wire is complete if no more egdes are connectible bool found = false; do { found = false; for (std::list<TopoDS_Edge>::iterator pE = edge_list.begin(); pE != edge_list.end();++pE) { mkWire.Add(*pE); if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) { // edge added ==> remove it from list found = true; edge_list.erase(pE); new_wire = mkWire.Wire(); break; } } } while (found); // Fix any topological issues of the wire ShapeFix_Wire aFix; aFix.SetPrecision(Precision::Confusion()); aFix.Load(new_wire); aFix.FixReorder(); aFix.FixConnected(); aFix.FixClosed(); wires.push_back(aFix.Wire()); } } void CrossSection::connectWires (const TopTools_IndexedMapOfShape& wireMap, std::list<TopoDS_Wire>& wires) const { Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); for (int i=1; i<=wireMap.Extent(); i++) { const TopoDS_Shape& wire = wireMap.FindKey(i); hWires->Append(wire); } Handle(TopTools_HSequenceOfShape) hSorted = new TopTools_HSequenceOfShape(); ShapeAnalysis_FreeBounds::ConnectWiresToWires(hWires, Precision::Confusion(), false, hSorted); for (int i=1; i<=hSorted->Length(); i++) { const TopoDS_Wire& new_wire = TopoDS::Wire(hSorted->Value(i)); // Fix any topological issues of the wire ShapeFix_Wire aFix; aFix.SetPrecision(Precision::Confusion()); aFix.Load(new_wire); aFix.FixReorder(); aFix.FixConnected(); aFix.FixClosed(); wires.push_back(aFix.Wire()); } } <|endoftext|>
<commit_before> #include "odrive_main.h" Encoder::Encoder(const EncoderHardwareConfig_t& hw_config, Config_t& config) : hw_config_(hw_config), config_(config) { // Calculate encoder pll gains // This calculation is currently identical to the PLL in SensorlessEstimator float pll_bandwidth = 1000.0f; // [rad/s] pll_kp_ = 2.0f * pll_bandwidth; // Critically damped pll_ki_ = 0.25f * (pll_kp_ * pll_kp_); if (config.pre_calibrated && (config.mode == Encoder::MODE_HALL)) { offset_ = config.offset; is_ready_ = true; } } static void enc_index_cb_wrapper(void* ctx) { reinterpret_cast<Encoder*>(ctx)->enc_index_cb(); } void Encoder::setup() { HAL_TIM_Encoder_Start(hw_config_.timer, TIM_CHANNEL_ALL); GPIO_subscribe(hw_config_.index_port, hw_config_.index_pin, GPIO_NOPULL, enc_index_cb_wrapper, this); } void Encoder::set_error(Encoder::Error_t error) { error_ |= error; axis_->error_ |= Axis::ERROR_MOTOR_FAILED; } bool Encoder::do_checks(){ return error_ == ERROR_NONE; } //-------------------- // Hardware Dependent //-------------------- // Triggered when an encoder passes over the "Index" pin // TODO: only arm index edge interrupt when we know encoder has powered up // TODO: disable interrupt once we found the index void Encoder::enc_index_cb() { if (config_.use_index && !index_found_) { set_circular_count(0); if (config_.pre_calibrated) { offset_ = config_.offset; is_ready_ = true; } index_found_ = true; } } // Function that sets the current encoder count to a desired 32-bit value. void Encoder::set_linear_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Update states shadow_count_ = count; pos_estimate_ = (float)count; //Write hardware last hw_config_.timer->Instance->CNT = count; __set_PRIMASK(prim); } // Function that sets the CPR circular tracking encoder count to a desired 32-bit value. // Note that this will get mod'ed down to [0, cpr) void Encoder::set_circular_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Offset and state must be shifted by the same amount offset_ += count - count_in_cpr_; offset_ = mod(offset_, config_.cpr); // Update states count_in_cpr_ = mod(count, config_.cpr); pos_cpr_ = (float)count_in_cpr_; __set_PRIMASK(prim); } // @brief Slowly turns the motor in one direction until the // encoder index is found. // TODO: Do the scan with current, not voltage! bool Encoder::run_index_search() { float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; float omega = (float)(axis_->motor_.config_.direction) * config_.idx_search_speed; index_found_ = false; float phase = 0.0f; axis_->run_control_loop([&](){ phase = wrap_pm_pi(phase + omega * current_meas_period); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_IDX_SEARCH); // continue until the index is found return !index_found_; }); return true; } // @brief Turns the motor in one direction for a bit and then in the other // direction in order to find the offset between the electrical phase 0 // and the encoder state 0. // TODO: Do the scan with current, not voltage! bool Encoder::run_offset_calibration() { static const float start_lock_duration = 1.0f; static const float scan_omega = 4.0f * M_PI; static const float scan_distance = 16.0f * M_PI; static const int num_steps = scan_distance / scan_omega * current_meas_hz; // Temporarily disable index search so it doesn't mess // with the offset calibration bool old_use_index = config_.use_index; config_.use_index = false; float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; // go to motor zero phase for start_lock_duration to get ready to scan int i = 0; axis_->run_control_loop([&](){ if (!axis_->motor_.enqueue_voltage_timings(voltage_magnitude, 0.0f)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); return ++i < start_lock_duration * current_meas_hz; }); if (axis_->error_ != Axis::ERROR_NONE) return false; int32_t init_enc_val = shadow_count_; int64_t encvaluesum = 0; // scan forward i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(scan_distance * (float)i / (float)num_steps - scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float expected_encoder_delta = scan_distance / elec_rad_per_enc; float actual_encoder_delta_abs = fabsf(shadow_count_-init_enc_val); if(fabsf(actual_encoder_delta_abs - expected_encoder_delta)/expected_encoder_delta > config_.calib_range) { set_error(ERROR_CPR_OUT_OF_RANGE); return false; } // check direction if (shadow_count_ > init_enc_val + 8) { // motor same dir as encoder axis_->motor_.config_.direction = 1; } else if (shadow_count_ < init_enc_val - 8) { // motor opposite dir as encoder axis_->motor_.config_.direction = -1; } else { // Encoder response error set_error(ERROR_RESPONSE); return false; } // scan backwards i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(-scan_distance * (float)i / (float)num_steps + scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; offset_ = encvaluesum / (num_steps * 2); config_.offset = offset_; int32_t residual = encvaluesum - ((int64_t)offset_ * (int64_t)(num_steps * 2)); config_.offset_float = (float)residual / (float)(num_steps * 2); is_ready_ = true; config_.use_index = old_use_index; return true; } static bool decode_hall(uint8_t hall_state, int32_t* hall_cnt) { switch (hall_state) { case 0b001: *hall_cnt = 0; return true; case 0b011: *hall_cnt = 1; return true; case 0b010: *hall_cnt = 2; return true; case 0b110: *hall_cnt = 3; return true; case 0b100: *hall_cnt = 4; return true; case 0b101: *hall_cnt = 5; return true; default: return false; } } bool Encoder::update() { // Check that we don't get problems with discrete time approximation if (!(current_meas_period * pll_kp_ < 1.0f)) { set_error(ERROR_UNSTABLE_GAIN); return false; } // update internal encoder state. int32_t delta_enc = 0; switch (config_.mode) { case MODE_INCREMENTAL: { //TODO: use count_in_cpr_ instead as shadow_count_ can overflow //or use 64 bit int16_t delta_enc_16 = (int16_t)hw_config_.timer->Instance->CNT - (int16_t)shadow_count_; delta_enc = (int32_t)delta_enc_16; //sign extend } break; case MODE_HALL: { int32_t hall_cnt; if (decode_hall(hall_state_, &hall_cnt)) { delta_enc = hall_cnt - count_in_cpr_; delta_enc = mod(delta_enc, 6); if (delta_enc > 3) delta_enc -= 6; } else { set_error(ERROR_ILLEGAL_HALL_STATE); return false; } } break; default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); return false; } break; } shadow_count_ += delta_enc; count_in_cpr_ += delta_enc; count_in_cpr_ = mod(count_in_cpr_, config_.cpr); //// run encoder count interpolation int32_t corrected_enc = count_in_cpr_ - offset_; // reset interpolation if encoder edge comes if (delta_enc > 0) { interpolation_ = 0.0f; } else if (delta_enc < 0) { interpolation_ = 1.0f; } else { // Interpolate (predict) between encoder counts using pll_vel, interpolation_ += current_meas_period * pll_vel_; // don't allow interpolation indicated position outside of [enc, enc+1) if (interpolation_ > 1.0f) interpolation_ = 1.0f; if (interpolation_ < 0.0f) interpolation_ = 0.0f; } float interpolated_enc = corrected_enc + interpolation_; //// compute electrical phase //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float ph = elec_rad_per_enc * (interpolated_enc - config_.offset_float); // ph = fmodf(ph, 2*M_PI); phase_ = wrap_pm_pi(ph); //// run pll (for now pll is in units of encoder counts) // Predict current pos pos_estimate_ += current_meas_period * pll_vel_; pos_cpr_ += current_meas_period * pll_vel_; // discrete phase detector float delta_pos = (float)(shadow_count_ - (int32_t)floorf(pos_estimate_)); float delta_pos_cpr = (float)(count_in_cpr_ - (int32_t)floorf(pos_cpr_)); delta_pos_cpr = wrap_pm(delta_pos_cpr, 0.5f * (float)(config_.cpr)); // pll feedback pos_estimate_ += current_meas_period * pll_kp_ * delta_pos; pos_cpr_ += current_meas_period * pll_kp_ * delta_pos_cpr; pos_cpr_ = fmodf_pos(pos_cpr_, (float)(config_.cpr)); pll_vel_ += current_meas_period * pll_ki_ * delta_pos_cpr; if (fabsf(pll_vel_) < 0.5f * current_meas_period * pll_ki_) pll_vel_ = 0.0f; //align delta-sigma on zero to prevent jitter return true; } <commit_msg>center-align hall interpolation float offset<commit_after> #include "odrive_main.h" Encoder::Encoder(const EncoderHardwareConfig_t& hw_config, Config_t& config) : hw_config_(hw_config), config_(config) { // Calculate encoder pll gains // This calculation is currently identical to the PLL in SensorlessEstimator float pll_bandwidth = 1000.0f; // [rad/s] pll_kp_ = 2.0f * pll_bandwidth; // Critically damped pll_ki_ = 0.25f * (pll_kp_ * pll_kp_); if (config.pre_calibrated && (config.mode == Encoder::MODE_HALL)) { offset_ = config.offset; is_ready_ = true; } } static void enc_index_cb_wrapper(void* ctx) { reinterpret_cast<Encoder*>(ctx)->enc_index_cb(); } void Encoder::setup() { HAL_TIM_Encoder_Start(hw_config_.timer, TIM_CHANNEL_ALL); GPIO_subscribe(hw_config_.index_port, hw_config_.index_pin, GPIO_NOPULL, enc_index_cb_wrapper, this); } void Encoder::set_error(Encoder::Error_t error) { error_ |= error; axis_->error_ |= Axis::ERROR_MOTOR_FAILED; } bool Encoder::do_checks(){ return error_ == ERROR_NONE; } //-------------------- // Hardware Dependent //-------------------- // Triggered when an encoder passes over the "Index" pin // TODO: only arm index edge interrupt when we know encoder has powered up // TODO: disable interrupt once we found the index void Encoder::enc_index_cb() { if (config_.use_index && !index_found_) { set_circular_count(0); if (config_.pre_calibrated) { offset_ = config_.offset; is_ready_ = true; } index_found_ = true; } } // Function that sets the current encoder count to a desired 32-bit value. void Encoder::set_linear_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Update states shadow_count_ = count; pos_estimate_ = (float)count; //Write hardware last hw_config_.timer->Instance->CNT = count; __set_PRIMASK(prim); } // Function that sets the CPR circular tracking encoder count to a desired 32-bit value. // Note that this will get mod'ed down to [0, cpr) void Encoder::set_circular_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Offset and state must be shifted by the same amount offset_ += count - count_in_cpr_; offset_ = mod(offset_, config_.cpr); // Update states count_in_cpr_ = mod(count, config_.cpr); pos_cpr_ = (float)count_in_cpr_; __set_PRIMASK(prim); } // @brief Slowly turns the motor in one direction until the // encoder index is found. // TODO: Do the scan with current, not voltage! bool Encoder::run_index_search() { float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; float omega = (float)(axis_->motor_.config_.direction) * config_.idx_search_speed; index_found_ = false; float phase = 0.0f; axis_->run_control_loop([&](){ phase = wrap_pm_pi(phase + omega * current_meas_period); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_IDX_SEARCH); // continue until the index is found return !index_found_; }); return true; } // @brief Turns the motor in one direction for a bit and then in the other // direction in order to find the offset between the electrical phase 0 // and the encoder state 0. // TODO: Do the scan with current, not voltage! bool Encoder::run_offset_calibration() { static const float start_lock_duration = 1.0f; static const float scan_omega = 4.0f * M_PI; static const float scan_distance = 16.0f * M_PI; static const int num_steps = scan_distance / scan_omega * current_meas_hz; // Temporarily disable index search so it doesn't mess // with the offset calibration bool old_use_index = config_.use_index; config_.use_index = false; float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; // go to motor zero phase for start_lock_duration to get ready to scan int i = 0; axis_->run_control_loop([&](){ if (!axis_->motor_.enqueue_voltage_timings(voltage_magnitude, 0.0f)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); return ++i < start_lock_duration * current_meas_hz; }); if (axis_->error_ != Axis::ERROR_NONE) return false; int32_t init_enc_val = shadow_count_; int64_t encvaluesum = 0; // scan forward i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(scan_distance * (float)i / (float)num_steps - scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float expected_encoder_delta = scan_distance / elec_rad_per_enc; float actual_encoder_delta_abs = fabsf(shadow_count_-init_enc_val); if(fabsf(actual_encoder_delta_abs - expected_encoder_delta)/expected_encoder_delta > config_.calib_range) { set_error(ERROR_CPR_OUT_OF_RANGE); return false; } // check direction if (shadow_count_ > init_enc_val + 8) { // motor same dir as encoder axis_->motor_.config_.direction = 1; } else if (shadow_count_ < init_enc_val - 8) { // motor opposite dir as encoder axis_->motor_.config_.direction = -1; } else { // Encoder response error set_error(ERROR_RESPONSE); return false; } // scan backwards i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(-scan_distance * (float)i / (float)num_steps + scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; offset_ = encvaluesum / (num_steps * 2); config_.offset = offset_; int32_t residual = encvaluesum - ((int64_t)offset_ * (int64_t)(num_steps * 2)); config_.offset_float = (float)residual / (float)(num_steps * 2) + 0.5f; // add 0.5 to center-align state to phase is_ready_ = true; config_.use_index = old_use_index; return true; } static bool decode_hall(uint8_t hall_state, int32_t* hall_cnt) { switch (hall_state) { case 0b001: *hall_cnt = 0; return true; case 0b011: *hall_cnt = 1; return true; case 0b010: *hall_cnt = 2; return true; case 0b110: *hall_cnt = 3; return true; case 0b100: *hall_cnt = 4; return true; case 0b101: *hall_cnt = 5; return true; default: return false; } } bool Encoder::update() { // Check that we don't get problems with discrete time approximation if (!(current_meas_period * pll_kp_ < 1.0f)) { set_error(ERROR_UNSTABLE_GAIN); return false; } // update internal encoder state. int32_t delta_enc = 0; switch (config_.mode) { case MODE_INCREMENTAL: { //TODO: use count_in_cpr_ instead as shadow_count_ can overflow //or use 64 bit int16_t delta_enc_16 = (int16_t)hw_config_.timer->Instance->CNT - (int16_t)shadow_count_; delta_enc = (int32_t)delta_enc_16; //sign extend } break; case MODE_HALL: { int32_t hall_cnt; if (decode_hall(hall_state_, &hall_cnt)) { delta_enc = hall_cnt - count_in_cpr_; delta_enc = mod(delta_enc, 6); if (delta_enc > 3) delta_enc -= 6; } else { set_error(ERROR_ILLEGAL_HALL_STATE); return false; } } break; default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); return false; } break; } shadow_count_ += delta_enc; count_in_cpr_ += delta_enc; count_in_cpr_ = mod(count_in_cpr_, config_.cpr); //// run pll (for now pll is in units of encoder counts) // Predict current pos pos_estimate_ += current_meas_period * pll_vel_; pos_cpr_ += current_meas_period * pll_vel_; // discrete phase detector float delta_pos = (float)(shadow_count_ - (int32_t)floorf(pos_estimate_)); float delta_pos_cpr = (float)(count_in_cpr_ - (int32_t)floorf(pos_cpr_)); delta_pos_cpr = wrap_pm(delta_pos_cpr, 0.5f * (float)(config_.cpr)); // pll feedback pos_estimate_ += current_meas_period * pll_kp_ * delta_pos; pos_cpr_ += current_meas_period * pll_kp_ * delta_pos_cpr; pos_cpr_ = fmodf_pos(pos_cpr_, (float)(config_.cpr)); pll_vel_ += current_meas_period * pll_ki_ * delta_pos_cpr; bool snap_to_zero_vel = false; if (fabsf(pll_vel_) < 0.5f * current_meas_period * pll_ki_) { pll_vel_ = 0.0f; //align delta-sigma on zero to prevent jitter snap_to_zero_vel = true; } //// run encoder count interpolation int32_t corrected_enc = count_in_cpr_ - offset_; // if we are stopped, make sure we don't randomly drift if (snap_to_zero_vel) { interpolation_ = 0.5f; // reset interpolation if encoder edge comes } else if (delta_enc > 0) { interpolation_ = 0.0f; } else if (delta_enc < 0) { interpolation_ = 1.0f; } else { // Interpolate (predict) between encoder counts using pll_vel, interpolation_ += current_meas_period * pll_vel_; // don't allow interpolation indicated position outside of [enc, enc+1) if (interpolation_ > 1.0f) interpolation_ = 1.0f; if (interpolation_ < 0.0f) interpolation_ = 0.0f; } float interpolated_enc = corrected_enc + interpolation_; //// compute electrical phase //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float ph = elec_rad_per_enc * (interpolated_enc - config_.offset_float); // ph = fmodf(ph, 2*M_PI); phase_ = wrap_pm_pi(ph); return true; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/network/NetworkObjectBase.hpp> #include <swift2d/utils/Logger.hpp> #include <raknet/RakPeerInterface.h> #include <raknet/GetTime.h> namespace swift { //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::WriteAllocationID(RakNet::Connection_RM3 *con, RakNet::BitStream* stream) const { stream->Write(get_type()); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3ConstructionState NetworkObjectBase::QueryConstruction(RakNet::Connection_RM3 *con, RakNet::ReplicaManager3 *replicaManager3) { return QueryConstruction_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::QueryRemoteConstruction(RakNet::Connection_RM3 *con) { return QueryRemoteConstruction_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::SerializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { vd_serializer_.AddRemoteSystemVariableHistory(con->GetRakNetGUID()); for (auto& member: distributed_members_) { member.serialize(stream); } } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::DeserializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { for (auto& member: distributed_members_) { member.deserialize(stream); } return true; } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::SerializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { vd_serializer_.RemoveRemoteSystemVariableHistory(con->GetRakNetGUID()); for (auto& member: distributed_members_) { member.serialize(stream); } } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::DeserializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { for (auto& member: distributed_members_) { member.deserialize(stream); } return true; } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3ActionOnPopConnection NetworkObjectBase::QueryActionOnPopConnection(RakNet::Connection_RM3 *con) const { return QueryActionOnPopConnection_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::DeallocReplica(RakNet::Connection_RM3 *con) { on_remote_delete(); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3QuerySerializationResult NetworkObjectBase::QuerySerialization(RakNet::Connection_RM3 *con) { return QuerySerialization_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3SerializationResult NetworkObjectBase::Serialize(RakNet::SerializeParameters *serializeParameters) { RakNet::VariableDeltaSerializer::SerializationContext ctx; serializeParameters->pro[0].reliability=RELIABLE_ORDERED; vd_serializer_.BeginIdenticalSerialize( &ctx, serializeParameters->whenLastSerialized==0, &serializeParameters->outputBitstream[0] ); for (auto& member: distributed_members_) { member.serialize(&ctx, &vd_serializer_); } vd_serializer_.EndSerialize(&ctx); return RakNet::RM3SR_SERIALIZED_ALWAYS_IDENTICALLY; } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::Deserialize(RakNet::DeserializeParameters *deserializeParameters) { RakNet::VariableDeltaSerializer::DeserializationContext ctx; vd_serializer_.BeginDeserialize(&ctx, &deserializeParameters->serializationBitstream[0]); for (auto& member: distributed_members_) { member.deserialize(&ctx, &vd_serializer_); } vd_serializer_.EndDeserialize(&ctx); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::OnUserReplicaPreSerializeTick(void) { vd_serializer_.OnPreSerializeTick(); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::distribute_member(SerializableReference const& value) { distributed_members_.push_back(value); } //////////////////////////////////////////////////////////////////////////////// } <commit_msg>added some output<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/network/NetworkObjectBase.hpp> #include <swift2d/utils/Logger.hpp> #include <raknet/RakPeerInterface.h> #include <raknet/GetTime.h> namespace swift { //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::WriteAllocationID(RakNet::Connection_RM3 *con, RakNet::BitStream* stream) const { stream->Write(get_type()); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3ConstructionState NetworkObjectBase::QueryConstruction(RakNet::Connection_RM3 *con, RakNet::ReplicaManager3 *replicaManager3) { return QueryConstruction_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::QueryRemoteConstruction(RakNet::Connection_RM3 *con) { return QueryRemoteConstruction_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::SerializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { vd_serializer_.AddRemoteSystemVariableHistory(con->GetRakNetGUID()); std::cout << "SerializeConstruction Begin" << std::endl; for (auto& member: distributed_members_) { std::cout << "membaa" << std::endl; member.serialize(stream); } std::cout << "SerializeConstruction End" << std::endl; } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::DeserializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { std::cout << "DeserializeConstruction Begin" << std::endl; for (auto& member: distributed_members_) { std::cout << "membaa" << std::endl; member.deserialize(stream); } std::cout << "DeserializeConstruction End" << std::endl; return true; } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::SerializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { vd_serializer_.RemoveRemoteSystemVariableHistory(con->GetRakNetGUID()); for (auto& member: distributed_members_) { member.serialize(stream); } } //////////////////////////////////////////////////////////////////////////////// bool NetworkObjectBase::DeserializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) { for (auto& member: distributed_members_) { member.deserialize(stream); } return true; } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3ActionOnPopConnection NetworkObjectBase::QueryActionOnPopConnection(RakNet::Connection_RM3 *con) const { return QueryActionOnPopConnection_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::DeallocReplica(RakNet::Connection_RM3 *con) { on_remote_delete(); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3QuerySerializationResult NetworkObjectBase::QuerySerialization(RakNet::Connection_RM3 *con) { return QuerySerialization_PeerToPeer(con); } //////////////////////////////////////////////////////////////////////////////// RakNet::RM3SerializationResult NetworkObjectBase::Serialize(RakNet::SerializeParameters *serializeParameters) { RakNet::VariableDeltaSerializer::SerializationContext ctx; serializeParameters->pro[0].reliability=RELIABLE_ORDERED; vd_serializer_.BeginIdenticalSerialize( &ctx, serializeParameters->whenLastSerialized==0, &serializeParameters->outputBitstream[0] ); for (auto& member: distributed_members_) { member.serialize(&ctx, &vd_serializer_); } vd_serializer_.EndSerialize(&ctx); return RakNet::RM3SR_SERIALIZED_ALWAYS_IDENTICALLY; } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::Deserialize(RakNet::DeserializeParameters *deserializeParameters) { RakNet::VariableDeltaSerializer::DeserializationContext ctx; vd_serializer_.BeginDeserialize(&ctx, &deserializeParameters->serializationBitstream[0]); for (auto& member: distributed_members_) { member.deserialize(&ctx, &vd_serializer_); } vd_serializer_.EndDeserialize(&ctx); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::OnUserReplicaPreSerializeTick(void) { vd_serializer_.OnPreSerializeTick(); } //////////////////////////////////////////////////////////////////////////////// void NetworkObjectBase::distribute_member(SerializableReference const& value) { distributed_members_.push_back(value); } //////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>#ifndef __NETWORKMESSAGEJOINACCEPT_H #define __NETWORKMESSAGEJOINACCEPT_H #include <string> #include <sstream> #include <deque> #include "NetworkMessage.hpp" #include "../Player.hpp" #include "../PlayerList.hpp" #include "../Map.hpp" namespace NetworkMessage{ class JoinAccept : public NetworkMessage{ public: //methods JoinAccept( PlayerList *playerList, unsigned int mapHeight, unsigned int mapWidth, time_t seed ); ~JoinAccept(); PlayerList *getPlayerList(); unsigned int getMapHeight(); unsigned int getMapWidth(); time_t getSeed(); private: //methods //arguments PlayerList mPlayerList; unsigned int mMapHeight; unsigned int mMapWidth; time_t mSeed; }; }; #endif //__NETWORKMESSAGEJOINACCEPT_H <commit_msg>removed unnecessary 'Player.hpp' include<commit_after>#ifndef __NETWORKMESSAGEJOINACCEPT_H #define __NETWORKMESSAGEJOINACCEPT_H #include <string> #include <sstream> #include <deque> #include "NetworkMessage.hpp" #include "../PlayerList.hpp" #include "../Map.hpp" namespace NetworkMessage{ class JoinAccept : public NetworkMessage{ public: //methods JoinAccept( PlayerList *playerList, unsigned int mapHeight, unsigned int mapWidth, time_t seed ); ~JoinAccept(); PlayerList *getPlayerList(); unsigned int getMapHeight(); unsigned int getMapWidth(); time_t getSeed(); private: //methods //arguments PlayerList mPlayerList; unsigned int mMapHeight; unsigned int mMapWidth; time_t mSeed; }; }; #endif //__NETWORKMESSAGEJOINACCEPT_H <|endoftext|>
<commit_before>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfileLoader class * * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfileLoader.h" #include "TTUnitTest.h" /* #define TESTFILE "/Users/nathanwolek/Desktop/geese_clip.aif" #define TESTNUMCHANNELS 2 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 88202 #define TESTDURATIONINSECONDS 2.00004535 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfileLoader Basics..."); TTSoundfileLoaderPtr soundfile_loader = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile.loader", (TTObjectBasePtr*)&soundfile_loader, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>adding test of setTargetMatrix()<commit_after>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfileLoader class * * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfileLoader.h" #include "TTUnitTest.h" /* #define TESTFILE "/Users/nathanwolek/Desktop/geese_clip.aif" #define TESTNUMCHANNELS 2 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 88202 #define TESTDURATIONINSECONDS 2.00004535 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfileLoader Basics..."); TTSoundfileLoaderPtr testSoundfileLoader = NULL; TTMatrixPtr testTargetMatrix = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile.loader", (TTObjectBasePtr*)&testSoundfileLoader, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); // TEST 2: instantiate a TTSampleMatrix and set is as the target TTBoolean result2 = { TTObjectBaseInstantiate("samplematrix", (TTObjectBasePtr*)&testTargetMatrix, kTTValNONE) == kTTErrNone}; TTBoolean result2b = { testSoundfileLoader->setTargetMatrix(testTargetMatrix) == kTTErrNone }; TTTestAssertion("sets target matrix successfully", result0, testAssertionCount, errorCount); } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>// @(#) $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * * for The ALICE HLT Project. * * * * 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. * **************************************************************************/ /** @file AliHLTAgentUtil.cxx @author Matthias Richter @date @brief Agent of the libAliHLTUtil library */ #include <cassert> #include "AliHLTAgentUtil.h" #include "AliHLTConfiguration.h" #include "AliHLTOUTHandlerChain.h" // header files of library components #include "AliHLTDataGenerator.h" #include "AliHLTRawReaderPublisherComponent.h" #include "AliHLTLoaderPublisherComponent.h" #include "AliHLTRootFileStreamerComponent.h" #include "AliHLTRootFileWriterComponent.h" #include "AliHLTRootFilePublisherComponent.h" #include "AliHLTRootSchemaEvolutionComponent.h" //#include "AliHLTMCGeneratorComponent.h" #include "AliHLTESDMCEventPublisherComponent.h" #include "AliHLTFileWriter.h" #include "AliHLTFilePublisher.h" #include "AliHLTBlockFilterComponent.h" #include "AliHLTMonitoringRelay.h" #include "AliHLTEsdCollectorComponent.h" #include "AliHLTReadoutListDumpComponent.h" #include "AliHLTOUTPublisherComponent.h" #include "AliHLTCompStatCollector.h" /** global instance for agent registration */ AliHLTAgentUtil gAliHLTAgentUtil; /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTAgentUtil) AliHLTAgentUtil::AliHLTAgentUtil() : AliHLTModuleAgent("Util") , fCompStatDataHandler(NULL) , fStreamerInfoDataHandler(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTAgentUtil::~AliHLTAgentUtil() { // see header file for class documentation } int AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler, AliRawReader* /*rawReader*/, AliRunLoader* /*runloader*/) const { // see header file for class documentation if (!handler) return 0; ///////////////////////////////////////////////////////////////////////////////////// // // a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks // produces a TTree object of the component statistics and writes it to disc // publisher component handler->CreateConfiguration("UTIL-hltout-compstat-publisher", "AliHLTOUTPublisher" , NULL, "-disable-component-stat"); // collector configuration handler->CreateConfiguration("UTIL-compstat-converter", "StatisticsCollector", "UTIL-hltout-compstat-publisher", "-disable-component-stat -arraysize 10000"); // writer configuration handler->CreateConfiguration("UTIL-compstat-writer", "ROOTFileWriter", "UTIL-compstat-converter", "-datafile HLT.statistics.root -concatenate-events -overwrite"); return 0; } const char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* /*rawReader*/, AliRunLoader* /*runloader*/) const { // see header file for class documentation return NULL; } const char* AliHLTAgentUtil::GetRequiredComponentLibraries() const { // see header file for class documentation return NULL; } int AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const { // see header file for class documentation assert(pHandler); if (!pHandler) return -EINVAL; pHandler->AddComponent(new AliHLTDataGenerator); pHandler->AddComponent(new AliHLTRawReaderPublisherComponent); pHandler->AddComponent(new AliHLTLoaderPublisherComponent); pHandler->AddComponent(new AliHLTRootFileStreamerComponent); pHandler->AddComponent(new AliHLTRootFileWriterComponent); pHandler->AddComponent(new AliHLTRootFilePublisherComponent); pHandler->AddComponent(new AliHLTRootSchemaEvolutionComponent); // pHandler->AddComponent(new AliHLTMCGeneratorComponent); pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent); pHandler->AddComponent(new AliHLTFileWriter); pHandler->AddComponent(new AliHLTFilePublisher); pHandler->AddComponent(new AliHLTBlockFilterComponent); pHandler->AddComponent(new AliHLTMonitoringRelay); pHandler->AddComponent(new AliHLTEsdCollectorComponent); pHandler->AddComponent(new AliHLTReadoutListDumpComponent); pHandler->AddComponent(new AliHLTOUTPublisherComponent); pHandler->AddComponent(new AliHLTCompStatCollector); return 0; } int AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt, AliHLTUInt32_t /*spec*/, AliHLTOUTHandlerDesc& desc) const { // see header file for class documentation // handler for the component statistics data blocks {'COMPSTAT':'PRIV'} if (dt==kAliHLTDataTypeComponentStatistics || dt==kAliHLTDataTypeComponentTable) { desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId()); return 1; } // handler for the component statistics data blocks {'ROOTSTRI':'HLT '} if (dt==kAliHLTDataTypeStreamerInfo) { desc=AliHLTOUTHandlerDesc(kProprietary, dt, GetModuleId()); return 1; } return 0; } AliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt, AliHLTUInt32_t /*spec*/) { // see header file for class documentation // handler for the component statistics data blocks {'COMPSTAT':'PRIV'} if (dt==kAliHLTDataTypeComponentStatistics || dt==kAliHLTDataTypeComponentTable) { if (fCompStatDataHandler==NULL) fCompStatDataHandler=new AliHLTOUTHandlerChain("chains=UTIL-compstat-writer"); return fCompStatDataHandler; } // handler for the component statistics data blocks {'ROOTSTRI':'HLT '} if (dt==kAliHLTDataTypeStreamerInfo) { if (fStreamerInfoDataHandler==NULL) fStreamerInfoDataHandler=new AliHLTStreamerInfoHandler; return fStreamerInfoDataHandler; } return NULL; } int AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance) { // see header file for class documentation if (pInstance==NULL) return -EINVAL; if (pInstance==fCompStatDataHandler) { delete fCompStatDataHandler; fCompStatDataHandler=NULL; } if (pInstance==fStreamerInfoDataHandler) { delete fStreamerInfoDataHandler; fStreamerInfoDataHandler=NULL; } return 0; } <commit_msg>removing unnecessary include file<commit_after>// $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * * for The ALICE HLT Project. * * * * 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. * **************************************************************************/ /** @file AliHLTAgentUtil.cxx @author Matthias Richter @date @brief Agent of the libAliHLTUtil library */ #include <cassert> #include "AliHLTAgentUtil.h" #include "AliHLTOUTHandlerChain.h" // header files of library components #include "AliHLTDataGenerator.h" #include "AliHLTRawReaderPublisherComponent.h" #include "AliHLTLoaderPublisherComponent.h" #include "AliHLTRootFileStreamerComponent.h" #include "AliHLTRootFileWriterComponent.h" #include "AliHLTRootFilePublisherComponent.h" #include "AliHLTRootSchemaEvolutionComponent.h" //#include "AliHLTMCGeneratorComponent.h" #include "AliHLTESDMCEventPublisherComponent.h" #include "AliHLTFileWriter.h" #include "AliHLTFilePublisher.h" #include "AliHLTBlockFilterComponent.h" #include "AliHLTMonitoringRelay.h" #include "AliHLTEsdCollectorComponent.h" #include "AliHLTReadoutListDumpComponent.h" #include "AliHLTOUTPublisherComponent.h" #include "AliHLTCompStatCollector.h" /** global instance for agent registration */ AliHLTAgentUtil gAliHLTAgentUtil; /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTAgentUtil) AliHLTAgentUtil::AliHLTAgentUtil() : AliHLTModuleAgent("Util") , fCompStatDataHandler(NULL) , fStreamerInfoDataHandler(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTAgentUtil::~AliHLTAgentUtil() { // see header file for class documentation } int AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler, AliRawReader* /*rawReader*/, AliRunLoader* /*runloader*/) const { // see header file for class documentation if (!handler) return 0; ///////////////////////////////////////////////////////////////////////////////////// // // a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks // produces a TTree object of the component statistics and writes it to disc // publisher component handler->CreateConfiguration("UTIL-hltout-compstat-publisher", "AliHLTOUTPublisher" , NULL, "-disable-component-stat"); // collector configuration handler->CreateConfiguration("UTIL-compstat-converter", "StatisticsCollector", "UTIL-hltout-compstat-publisher", "-disable-component-stat -arraysize 10000"); // writer configuration handler->CreateConfiguration("UTIL-compstat-writer", "ROOTFileWriter", "UTIL-compstat-converter", "-datafile HLT.statistics.root -concatenate-events -overwrite"); return 0; } const char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* /*rawReader*/, AliRunLoader* /*runloader*/) const { // see header file for class documentation return NULL; } const char* AliHLTAgentUtil::GetRequiredComponentLibraries() const { // see header file for class documentation return NULL; } int AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const { // see header file for class documentation assert(pHandler); if (!pHandler) return -EINVAL; pHandler->AddComponent(new AliHLTDataGenerator); pHandler->AddComponent(new AliHLTRawReaderPublisherComponent); pHandler->AddComponent(new AliHLTLoaderPublisherComponent); pHandler->AddComponent(new AliHLTRootFileStreamerComponent); pHandler->AddComponent(new AliHLTRootFileWriterComponent); pHandler->AddComponent(new AliHLTRootFilePublisherComponent); pHandler->AddComponent(new AliHLTRootSchemaEvolutionComponent); // pHandler->AddComponent(new AliHLTMCGeneratorComponent); pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent); pHandler->AddComponent(new AliHLTFileWriter); pHandler->AddComponent(new AliHLTFilePublisher); pHandler->AddComponent(new AliHLTBlockFilterComponent); pHandler->AddComponent(new AliHLTMonitoringRelay); pHandler->AddComponent(new AliHLTEsdCollectorComponent); pHandler->AddComponent(new AliHLTReadoutListDumpComponent); pHandler->AddComponent(new AliHLTOUTPublisherComponent); pHandler->AddComponent(new AliHLTCompStatCollector); return 0; } int AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt, AliHLTUInt32_t /*spec*/, AliHLTOUTHandlerDesc& desc) const { // see header file for class documentation // handler for the component statistics data blocks {'COMPSTAT':'PRIV'} if (dt==kAliHLTDataTypeComponentStatistics || dt==kAliHLTDataTypeComponentTable) { desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId()); return 1; } // handler for the component statistics data blocks {'ROOTSTRI':'HLT '} if (dt==kAliHLTDataTypeStreamerInfo) { desc=AliHLTOUTHandlerDesc(kProprietary, dt, GetModuleId()); return 1; } return 0; } AliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt, AliHLTUInt32_t /*spec*/) { // see header file for class documentation // handler for the component statistics data blocks {'COMPSTAT':'PRIV'} if (dt==kAliHLTDataTypeComponentStatistics || dt==kAliHLTDataTypeComponentTable) { if (fCompStatDataHandler==NULL) fCompStatDataHandler=new AliHLTOUTHandlerChain("chains=UTIL-compstat-writer"); return fCompStatDataHandler; } // handler for the component statistics data blocks {'ROOTSTRI':'HLT '} if (dt==kAliHLTDataTypeStreamerInfo) { if (fStreamerInfoDataHandler==NULL) fStreamerInfoDataHandler=new AliHLTStreamerInfoHandler; return fStreamerInfoDataHandler; } return NULL; } int AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance) { // see header file for class documentation if (pInstance==NULL) return -EINVAL; if (pInstance==fCompStatDataHandler) { delete fCompStatDataHandler; fCompStatDataHandler=NULL; } if (pInstance==fStreamerInfoDataHandler) { delete fStreamerInfoDataHandler; fStreamerInfoDataHandler=NULL; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/bluetooth/bluetooth_event_router.h" #include <map> #include <string> #include "base/json/json_writer.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_vector.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/api/bluetooth/bluetooth_api_utils.h" #include "chrome/browser/extensions/event_names.h" #include "chrome/browser/extensions/event_router.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/common/extensions/api/bluetooth.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_socket.h" namespace extensions { ExtensionBluetoothEventRouter::ExtensionBluetoothEventRouter(Profile* profile) : send_discovery_events_(false), responsible_for_discovery_(false), profile_(profile), adapter_(NULL), num_event_listeners_(0), next_socket_id_(1), ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { DCHECK(profile_); } ExtensionBluetoothEventRouter::~ExtensionBluetoothEventRouter() { CHECK(socket_map_.size() == 0); if (adapter_) { adapter_->RemoveObserver(this); adapter_ = NULL; } } bool ExtensionBluetoothEventRouter::IsBluetoothSupported() const { return adapter_ || device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable(); } void ExtensionBluetoothEventRouter::GetAdapter( const device::BluetoothAdapterFactory::AdapterCallback& callback) { if (adapter_) { callback.Run(scoped_refptr<device::BluetoothAdapter>(adapter_)); return; } device::BluetoothAdapterFactory::GetAdapter(callback); } void ExtensionBluetoothEventRouter::OnListenerAdded() { num_event_listeners_++; InitializeAdapterIfNeeded(); } void ExtensionBluetoothEventRouter::OnListenerRemoved() { if (num_event_listeners_ > 0) num_event_listeners_--; MaybeReleaseAdapter(); } int ExtensionBluetoothEventRouter::RegisterSocket( scoped_refptr<device::BluetoothSocket> socket) { // If there is a socket registered with the same fd, just return it's id for (SocketMap::const_iterator i = socket_map_.begin(); i != socket_map_.end(); ++i) { if (i->second.get() == socket.get()) return i->first; } int return_id = next_socket_id_++; socket_map_[return_id] = socket; return return_id; } bool ExtensionBluetoothEventRouter::ReleaseSocket(int id) { SocketMap::iterator socket_entry = socket_map_.find(id); if (socket_entry == socket_map_.end()) return false; socket_map_.erase(socket_entry); return true; } scoped_refptr<device::BluetoothSocket> ExtensionBluetoothEventRouter::GetSocket(int id) { SocketMap::iterator socket_entry = socket_map_.find(id); if (socket_entry == socket_map_.end()) return NULL; return socket_entry->second; } void ExtensionBluetoothEventRouter::SetResponsibleForDiscovery( bool responsible) { responsible_for_discovery_ = responsible; } bool ExtensionBluetoothEventRouter::IsResponsibleForDiscovery() const { return responsible_for_discovery_; } void ExtensionBluetoothEventRouter::SetSendDiscoveryEvents(bool should_send) { // At the transition into sending devices, also send past devices that // were discovered as they will not be discovered again. if (should_send && !send_discovery_events_) { for (DeviceList::const_iterator i = discovered_devices_.begin(); i != discovered_devices_.end(); ++i) { DispatchDeviceEvent(extensions::event_names::kBluetoothOnDeviceDiscovered, **i); } } send_discovery_events_ = should_send; } void ExtensionBluetoothEventRouter::DispatchDeviceEvent( const char* event_name, const extensions::api::bluetooth::Device& device) { scoped_ptr<ListValue> args(new ListValue()); args->Append(device.ToValue().release()); scoped_ptr<Event> event(new Event(event_name, args.Pass())); ExtensionSystem::Get(profile_)->event_router()->BroadcastEvent(event.Pass()); } void ExtensionBluetoothEventRouter::AdapterPresentChanged( device::BluetoothAdapter* adapter, bool present) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::AdapterPoweredChanged( device::BluetoothAdapter* adapter, bool has_power) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::AdapterDiscoveringChanged( device::BluetoothAdapter* adapter, bool discovering) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } if (!discovering) { send_discovery_events_ = false; responsible_for_discovery_ = false; discovered_devices_.clear(); } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::DeviceAdded( device::BluetoothAdapter* adapter, device::BluetoothDevice* device) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } extensions::api::bluetooth::Device* extension_device = new extensions::api::bluetooth::Device(); extensions::api::bluetooth::BluetoothDeviceToApiDevice( *device, extension_device); discovered_devices_.push_back(extension_device); if (!send_discovery_events_) return; DispatchDeviceEvent(extensions::event_names::kBluetoothOnDeviceDiscovered, *extension_device); } void ExtensionBluetoothEventRouter::InitializeAdapterIfNeeded() { if (!adapter_) { GetAdapter(base::Bind(&ExtensionBluetoothEventRouter::InitializeAdapter, weak_ptr_factory_.GetWeakPtr())); } } void ExtensionBluetoothEventRouter::InitializeAdapter( scoped_refptr<device::BluetoothAdapter> adapter) { if (!adapter_) { adapter_ = adapter; adapter_->AddObserver(this); } } void ExtensionBluetoothEventRouter::MaybeReleaseAdapter() { if (adapter_ && num_event_listeners_ == 0) { adapter_->RemoveObserver(this); adapter_ = NULL; } } void ExtensionBluetoothEventRouter::DispatchAdapterStateEvent() { api::bluetooth::AdapterState state; PopulateAdapterState(*adapter_, &state); scoped_ptr<ListValue> args(new ListValue()); args->Append(state.ToValue().release()); scoped_ptr<Event> event(new Event( extensions::event_names::kBluetoothOnAdapterStateChanged, args.Pass())); ExtensionSystem::Get(profile_)->event_router()->BroadcastEvent(event.Pass()); } } // namespace extensions <commit_msg>Remove socket_map_.size() == 0 CHECK.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/bluetooth/bluetooth_event_router.h" #include <map> #include <string> #include "base/json/json_writer.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_vector.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/api/bluetooth/bluetooth_api_utils.h" #include "chrome/browser/extensions/event_names.h" #include "chrome/browser/extensions/event_router.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/common/extensions/api/bluetooth.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_socket.h" namespace extensions { ExtensionBluetoothEventRouter::ExtensionBluetoothEventRouter(Profile* profile) : send_discovery_events_(false), responsible_for_discovery_(false), profile_(profile), adapter_(NULL), num_event_listeners_(0), next_socket_id_(1), ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { DCHECK(profile_); } ExtensionBluetoothEventRouter::~ExtensionBluetoothEventRouter() { if (adapter_) { adapter_->RemoveObserver(this); adapter_ = NULL; } DLOG_IF(WARNING, socket_map_.size() != 0) << "Bluetooth sockets are still open."; socket_map_.clear(); } bool ExtensionBluetoothEventRouter::IsBluetoothSupported() const { return adapter_ || device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable(); } void ExtensionBluetoothEventRouter::GetAdapter( const device::BluetoothAdapterFactory::AdapterCallback& callback) { if (adapter_) { callback.Run(scoped_refptr<device::BluetoothAdapter>(adapter_)); return; } device::BluetoothAdapterFactory::GetAdapter(callback); } void ExtensionBluetoothEventRouter::OnListenerAdded() { num_event_listeners_++; InitializeAdapterIfNeeded(); } void ExtensionBluetoothEventRouter::OnListenerRemoved() { if (num_event_listeners_ > 0) num_event_listeners_--; MaybeReleaseAdapter(); } int ExtensionBluetoothEventRouter::RegisterSocket( scoped_refptr<device::BluetoothSocket> socket) { // If there is a socket registered with the same fd, just return it's id for (SocketMap::const_iterator i = socket_map_.begin(); i != socket_map_.end(); ++i) { if (i->second.get() == socket.get()) return i->first; } int return_id = next_socket_id_++; socket_map_[return_id] = socket; return return_id; } bool ExtensionBluetoothEventRouter::ReleaseSocket(int id) { SocketMap::iterator socket_entry = socket_map_.find(id); if (socket_entry == socket_map_.end()) return false; socket_map_.erase(socket_entry); return true; } scoped_refptr<device::BluetoothSocket> ExtensionBluetoothEventRouter::GetSocket(int id) { SocketMap::iterator socket_entry = socket_map_.find(id); if (socket_entry == socket_map_.end()) return NULL; return socket_entry->second; } void ExtensionBluetoothEventRouter::SetResponsibleForDiscovery( bool responsible) { responsible_for_discovery_ = responsible; } bool ExtensionBluetoothEventRouter::IsResponsibleForDiscovery() const { return responsible_for_discovery_; } void ExtensionBluetoothEventRouter::SetSendDiscoveryEvents(bool should_send) { // At the transition into sending devices, also send past devices that // were discovered as they will not be discovered again. if (should_send && !send_discovery_events_) { for (DeviceList::const_iterator i = discovered_devices_.begin(); i != discovered_devices_.end(); ++i) { DispatchDeviceEvent(extensions::event_names::kBluetoothOnDeviceDiscovered, **i); } } send_discovery_events_ = should_send; } void ExtensionBluetoothEventRouter::DispatchDeviceEvent( const char* event_name, const extensions::api::bluetooth::Device& device) { scoped_ptr<ListValue> args(new ListValue()); args->Append(device.ToValue().release()); scoped_ptr<Event> event(new Event(event_name, args.Pass())); ExtensionSystem::Get(profile_)->event_router()->BroadcastEvent(event.Pass()); } void ExtensionBluetoothEventRouter::AdapterPresentChanged( device::BluetoothAdapter* adapter, bool present) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::AdapterPoweredChanged( device::BluetoothAdapter* adapter, bool has_power) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::AdapterDiscoveringChanged( device::BluetoothAdapter* adapter, bool discovering) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } if (!discovering) { send_discovery_events_ = false; responsible_for_discovery_ = false; discovered_devices_.clear(); } DispatchAdapterStateEvent(); } void ExtensionBluetoothEventRouter::DeviceAdded( device::BluetoothAdapter* adapter, device::BluetoothDevice* device) { if (adapter != adapter_) { DVLOG(1) << "Ignoring event for adapter " << adapter->address(); return; } extensions::api::bluetooth::Device* extension_device = new extensions::api::bluetooth::Device(); extensions::api::bluetooth::BluetoothDeviceToApiDevice( *device, extension_device); discovered_devices_.push_back(extension_device); if (!send_discovery_events_) return; DispatchDeviceEvent(extensions::event_names::kBluetoothOnDeviceDiscovered, *extension_device); } void ExtensionBluetoothEventRouter::InitializeAdapterIfNeeded() { if (!adapter_) { GetAdapter(base::Bind(&ExtensionBluetoothEventRouter::InitializeAdapter, weak_ptr_factory_.GetWeakPtr())); } } void ExtensionBluetoothEventRouter::InitializeAdapter( scoped_refptr<device::BluetoothAdapter> adapter) { if (!adapter_) { adapter_ = adapter; adapter_->AddObserver(this); } } void ExtensionBluetoothEventRouter::MaybeReleaseAdapter() { if (adapter_ && num_event_listeners_ == 0) { adapter_->RemoveObserver(this); adapter_ = NULL; } } void ExtensionBluetoothEventRouter::DispatchAdapterStateEvent() { api::bluetooth::AdapterState state; PopulateAdapterState(*adapter_, &state); scoped_ptr<ListValue> args(new ListValue()); args->Append(state.ToValue().release()); scoped_ptr<Event> event(new Event( extensions::event_names::kBluetoothOnAdapterStateChanged, args.Pass())); ExtensionSystem::Get(profile_)->event_router()->BroadcastEvent(event.Pass()); } } // namespace extensions <|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/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; TEST_F(GtkKeyBindingsHandlerTest, MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <commit_msg>Mark the GtkKeyBindingsHandlerTest tests as flaky since they don't work in a chroot.<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/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <|endoftext|>
<commit_before>#include "SalomeApp_Study.h" #include "SalomeApp_Module.h" #include "SalomeApp_DataModel.h" #include "SalomeApp_RootObject.h" #include "SalomeApp_DataObject.h" #include "SalomeApp_Application.h" #include <OB_Browser.h> #include <SUIT_ResourceMgr.h> #include "utilities.h" SalomeApp_Study::SalomeApp_Study( SUIT_Application* app ) : CAM_Study( app ) { } SalomeApp_Study::~SalomeApp_Study() { } int SalomeApp_Study::id() const { int id = -1; if ( myStudyDS ) id = studyDS()->StudyId(); return id; } _PTR(Study) SalomeApp_Study::studyDS() const { return myStudyDS; } void SalomeApp_Study::createDocument() { MESSAGE( "openDocument" ); // initialize myStudyDS, read HDF file _PTR(Study) study ( SalomeApp_Application::studyMgr()->NewStudy( newStudyName().latin1() ) ); if ( !study ) return; setStudyDS( study ); // create myRoot setRoot( new SalomeApp_RootObject( this ) ); CAM_Study::createDocument(); emit created( this ); } //======================================================================= // name : openDocument // Purpose : Open document //======================================================================= bool SalomeApp_Study::openDocument( const QString& theFileName ) { MESSAGE( "openDocument" ); // initialize myStudyDS, read HDF file _PTR(Study) study ( SalomeApp_Application::studyMgr()->Open( (char*) theFileName.latin1() ) ); if ( !study ) return false; setStudyDS( study ); // build a SUIT_DataObject-s tree under myRoot member field // 1. create myRoot setRoot( new SalomeApp_RootObject( this ) ); // 2. iterate through all components and create corresponding sub-trees under them _PTR(SComponentIterator) it ( studyDS()->NewComponentIterator() ); for ( ; it->More(); it->Next() ) { // don't use shared_ptr here, for Data Object will take // ownership of this pointer _PTR(SComponent) aComponent ( it->Value() ); if ( aComponent->ComponentDataType() == "Interface Applicative" ) continue; // skip the magic "Interface Applicative" component SalomeApp_DataModel::BuildTree( aComponent, root(), this ); } bool res = CAM_Study::openDocument( theFileName ); emit opened( this ); return res; } //======================================================================= // name : loadDocument // Purpose : Connects GUI study to SALOMEDS one already loaded into StudyManager //======================================================================= bool SalomeApp_Study::loadDocument( const QString& theStudyName ) { MESSAGE( "loadDocument" ); // obtain myStudyDS from StudyManager _PTR(Study) study ( SalomeApp_Application::studyMgr()->GetStudyByName( (char*) theStudyName.latin1() ) ); if ( !study ) return false; setStudyDS( study ); // build a SUIT_DataObject-s tree under myRoot member field // 1. create myRoot setRoot( new SalomeApp_RootObject( this ) ); // 2. iterate through all components and create corresponding sub-trees under them _PTR(SComponentIterator) it ( studyDS()->NewComponentIterator() ); for ( ; it->More(); it->Next() ) { // don't use shared_ptr here, for Data Object will take // ownership of this pointer _PTR(SComponent) aComponent ( it->Value() ); if ( aComponent->ComponentDataType() == "Interface Applicative" ) continue; // skip the magic "Interface Applicative" component SalomeApp_DataModel::BuildTree( aComponent, root(), this ); } // TODO: potentially unsafe call, since base study's openDocument() might try to access the file directly - to be improved bool res = CAM_Study::openDocument( theStudyName ); emit opened( this ); return res; } //======================================================================= // name : saveDocumentAs // Purpose : Save document //======================================================================= bool SalomeApp_Study::saveDocumentAs( const QString& theFileName ) { ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) aModel->saveAs( theFileName, this ); bool res = CAM_Study::saveDocumentAs( theFileName ); // save SALOMEDS document bool isMultiFile = false, isAscii = false;// TODO: This information should be taken from preferences afterwards! isAscii ? SalomeApp_Application::studyMgr()->SaveAsASCII( theFileName.latin1(), studyDS(), isMultiFile ) : SalomeApp_Application::studyMgr()->SaveAs ( theFileName.latin1(), studyDS(), isMultiFile ); emit saved( this ); return res; } //======================================================================= // name : saveDocument // Purpose : Save document //======================================================================= void SalomeApp_Study::saveDocument() { ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) aModel->save(); CAM_Study::saveDocument(); // save SALOMEDS document bool isMultiFile = false, isAscii = false;// TODO: This information should be taken from preferences afterwards! isAscii ? SalomeApp_Application::studyMgr()->SaveASCII( studyDS(), isMultiFile ) : SalomeApp_Application::studyMgr()->Save ( studyDS(), isMultiFile ); emit saved( this ); } //================================================================ // Function : closeDocument // Purpose : //================================================================ void SalomeApp_Study::closeDocument() { // Inform everybody that this study is going to close when it's most safe to, // i.e. in the very beginning emit closed( this ); // close SALOMEDS document _PTR(Study) studyPtr = studyDS(); if ( studyPtr.get() ) { SalomeApp_Application::studyMgr()->Close( studyPtr ); SALOMEDSClient_Study* aStudy = 0; setStudyDS( _PTR(Study)(aStudy) ); } CAM_Study::closeDocument(); } //================================================================ // Function : isModified // Purpose : //================================================================ bool SalomeApp_Study::isModified() const { bool isAnyChanged = studyDS() && studyDS()->IsModified(); ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = 0; for ( QPtrListIterator<CAM_DataModel> it( list ); it.current() && !isAnyChanged; ++it ){ aModel = dynamic_cast<SalomeApp_DataModel*>( it.current() ); if ( aModel ) isAnyChanged = aModel->isModified(); } return isAnyChanged; } //================================================================ // Function : isSaved // Purpose : //================================================================ bool SalomeApp_Study::isSaved() const { bool isAllSaved = studyDS() && studyDS()->GetPersistentReference().size(); ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = 0; for ( QPtrListIterator<CAM_DataModel> it( list ); it.current() && isAllSaved; ++it ){ aModel = dynamic_cast<SalomeApp_DataModel*>( it.current() ); if ( aModel ) isAllSaved = aModel->isSaved(); } return isAllSaved; } void SalomeApp_Study::setStudyDS( const _PTR(Study)& s ) { myStudyDS = s; } void SalomeApp_Study::dataModelInserted (const CAM_DataModel* dm) { MESSAGE("SalomeApp_Study::dataModelInserted() : module name() = " << dm->module()->name()); CAM_Study::dataModelInserted(dm); // Create SComponent for module, using default engine (CORBAless) SalomeApp_Module* aModule = (SalomeApp_Module*)(dm->module()); if (aModule) { QString anEngineIOR = aModule->engineIOR(); if (anEngineIOR.isEmpty()) { // CORBAless module // Check SComponent existance _PTR(SComponent) aComp = studyDS()->FindComponent(dm->module()->name()); if (!aComp) { // Create SComponent _PTR(StudyBuilder) aBuilder = studyDS()->NewBuilder(); aComp = aBuilder->NewComponent(dm->module()->name()); // Set default engine IOR aBuilder->DefineComponentInstance(aComp, SalomeApp_Application::defaultEngineIOR().latin1()); } } } } bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm ) { if (!dm) return false; SalomeApp_DataModel* aDM = (SalomeApp_DataModel*)(dm); if (aDM && aDM->open(studyName, this)) { // Something has been read -> create data model tree aDM->update(NULL, this); return true; } return false; } void SalomeApp_Study::updateModelRoot( const CAM_DataModel* dm ) { CAM_Study::updateModelRoot( dm ); ((SalomeApp_Application*)application())->objectBrowser()->updateTree(); } QString SalomeApp_Study::newStudyName() const { std::vector<std::string> studies = SalomeApp_Application::studyMgr()->GetOpenStudies(); QString prefix( "Study%1" ), newName, curName; int i = 1, j, n = studies.size(); while ( newName.isEmpty() ){ curName = prefix.arg( i ); for ( j = 0 ; j < n; j++ ){ if ( !strcmp( studies[j].c_str(), curName.latin1() ) ) break; } if ( j == n ) newName = curName; else i++; } return newName; } <commit_msg>setStudyName() called from createDocument() to avoid creating unnamed documents<commit_after>#include "SalomeApp_Study.h" #include "SalomeApp_Module.h" #include "SalomeApp_DataModel.h" #include "SalomeApp_RootObject.h" #include "SalomeApp_DataObject.h" #include "SalomeApp_Application.h" #include <OB_Browser.h> #include <SUIT_ResourceMgr.h> #include "utilities.h" SalomeApp_Study::SalomeApp_Study( SUIT_Application* app ) : CAM_Study( app ) { } SalomeApp_Study::~SalomeApp_Study() { } int SalomeApp_Study::id() const { int id = -1; if ( myStudyDS ) id = studyDS()->StudyId(); return id; } _PTR(Study) SalomeApp_Study::studyDS() const { return myStudyDS; } void SalomeApp_Study::createDocument() { MESSAGE( "openDocument" ); // initialize myStudyDS, read HDF file QString aName = newStudyName(); _PTR(Study) study ( SalomeApp_Application::studyMgr()->NewStudy( aName.latin1() ) ); if ( !study ) return; setStudyDS( study ); setStudyName( aName ); // create myRoot setRoot( new SalomeApp_RootObject( this ) ); CAM_Study::createDocument(); emit created( this ); } //======================================================================= // name : openDocument // Purpose : Open document //======================================================================= bool SalomeApp_Study::openDocument( const QString& theFileName ) { MESSAGE( "openDocument" ); // initialize myStudyDS, read HDF file _PTR(Study) study ( SalomeApp_Application::studyMgr()->Open( (char*) theFileName.latin1() ) ); if ( !study ) return false; setStudyDS( study ); // build a SUIT_DataObject-s tree under myRoot member field // 1. create myRoot setRoot( new SalomeApp_RootObject( this ) ); // 2. iterate through all components and create corresponding sub-trees under them _PTR(SComponentIterator) it ( studyDS()->NewComponentIterator() ); for ( ; it->More(); it->Next() ) { // don't use shared_ptr here, for Data Object will take // ownership of this pointer _PTR(SComponent) aComponent ( it->Value() ); if ( aComponent->ComponentDataType() == "Interface Applicative" ) continue; // skip the magic "Interface Applicative" component SalomeApp_DataModel::BuildTree( aComponent, root(), this ); } bool res = CAM_Study::openDocument( theFileName ); emit opened( this ); return res; } //======================================================================= // name : loadDocument // Purpose : Connects GUI study to SALOMEDS one already loaded into StudyManager //======================================================================= bool SalomeApp_Study::loadDocument( const QString& theStudyName ) { MESSAGE( "loadDocument" ); // obtain myStudyDS from StudyManager _PTR(Study) study ( SalomeApp_Application::studyMgr()->GetStudyByName( (char*) theStudyName.latin1() ) ); if ( !study ) return false; setStudyDS( study ); // build a SUIT_DataObject-s tree under myRoot member field // 1. create myRoot setRoot( new SalomeApp_RootObject( this ) ); // 2. iterate through all components and create corresponding sub-trees under them _PTR(SComponentIterator) it ( studyDS()->NewComponentIterator() ); for ( ; it->More(); it->Next() ) { // don't use shared_ptr here, for Data Object will take // ownership of this pointer _PTR(SComponent) aComponent ( it->Value() ); if ( aComponent->ComponentDataType() == "Interface Applicative" ) continue; // skip the magic "Interface Applicative" component SalomeApp_DataModel::BuildTree( aComponent, root(), this ); } // TODO: potentially unsafe call, since base study's openDocument() might try to access the file directly - to be improved bool res = CAM_Study::openDocument( theStudyName ); emit opened( this ); return res; } //======================================================================= // name : saveDocumentAs // Purpose : Save document //======================================================================= bool SalomeApp_Study::saveDocumentAs( const QString& theFileName ) { ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) aModel->saveAs( theFileName, this ); bool res = CAM_Study::saveDocumentAs( theFileName ); // save SALOMEDS document bool isMultiFile = false, isAscii = false;// TODO: This information should be taken from preferences afterwards! isAscii ? SalomeApp_Application::studyMgr()->SaveAsASCII( theFileName.latin1(), studyDS(), isMultiFile ) : SalomeApp_Application::studyMgr()->SaveAs ( theFileName.latin1(), studyDS(), isMultiFile ); emit saved( this ); return res; } //======================================================================= // name : saveDocument // Purpose : Save document //======================================================================= void SalomeApp_Study::saveDocument() { ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) aModel->save(); CAM_Study::saveDocument(); // save SALOMEDS document bool isMultiFile = false, isAscii = false;// TODO: This information should be taken from preferences afterwards! isAscii ? SalomeApp_Application::studyMgr()->SaveASCII( studyDS(), isMultiFile ) : SalomeApp_Application::studyMgr()->Save ( studyDS(), isMultiFile ); emit saved( this ); } //================================================================ // Function : closeDocument // Purpose : //================================================================ void SalomeApp_Study::closeDocument() { // Inform everybody that this study is going to close when it's most safe to, // i.e. in the very beginning emit closed( this ); // close SALOMEDS document _PTR(Study) studyPtr = studyDS(); if ( studyPtr ) { SalomeApp_Application::studyMgr()->Close( studyPtr ); SALOMEDSClient_Study* aStudy = 0; setStudyDS( _PTR(Study)(aStudy) ); } CAM_Study::closeDocument(); } //================================================================ // Function : isModified // Purpose : //================================================================ bool SalomeApp_Study::isModified() const { bool isAnyChanged = studyDS() && studyDS()->IsModified(); ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = 0; for ( QPtrListIterator<CAM_DataModel> it( list ); it.current() && !isAnyChanged; ++it ){ aModel = dynamic_cast<SalomeApp_DataModel*>( it.current() ); if ( aModel ) isAnyChanged = aModel->isModified(); } return isAnyChanged; } //================================================================ // Function : isSaved // Purpose : //================================================================ bool SalomeApp_Study::isSaved() const { bool isAllSaved = studyDS() && studyDS()->GetPersistentReference().size(); ModelList list; dataModels( list ); SalomeApp_DataModel* aModel = 0; for ( QPtrListIterator<CAM_DataModel> it( list ); it.current() && isAllSaved; ++it ){ aModel = dynamic_cast<SalomeApp_DataModel*>( it.current() ); if ( aModel ) isAllSaved = aModel->isSaved(); } return isAllSaved; } void SalomeApp_Study::setStudyDS( const _PTR(Study)& s ) { myStudyDS = s; } void SalomeApp_Study::dataModelInserted (const CAM_DataModel* dm) { MESSAGE("SalomeApp_Study::dataModelInserted() : module name() = " << dm->module()->name()); CAM_Study::dataModelInserted(dm); // Create SComponent for module, using default engine (CORBAless) SalomeApp_Module* aModule = (SalomeApp_Module*)(dm->module()); if (aModule) { QString anEngineIOR = aModule->engineIOR(); if (anEngineIOR.isEmpty()) { // CORBAless module // Check SComponent existance _PTR(SComponent) aComp = studyDS()->FindComponent(dm->module()->name()); if (!aComp) { // Create SComponent _PTR(StudyBuilder) aBuilder = studyDS()->NewBuilder(); aComp = aBuilder->NewComponent(dm->module()->name()); // Set default engine IOR aBuilder->DefineComponentInstance(aComp, SalomeApp_Application::defaultEngineIOR().latin1()); } } } } bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm ) { if (!dm) return false; SalomeApp_DataModel* aDM = (SalomeApp_DataModel*)(dm); if (aDM && aDM->open(studyName, this)) { // Something has been read -> create data model tree aDM->update(NULL, this); return true; } return false; } void SalomeApp_Study::updateModelRoot( const CAM_DataModel* dm ) { CAM_Study::updateModelRoot( dm ); ((SalomeApp_Application*)application())->objectBrowser()->updateTree(); } QString SalomeApp_Study::newStudyName() const { std::vector<std::string> studies = SalomeApp_Application::studyMgr()->GetOpenStudies(); QString prefix( "Study%1" ), newName, curName; int i = 1, j, n = studies.size(); while ( newName.isEmpty() ){ curName = prefix.arg( i ); for ( j = 0 ; j < n; j++ ){ if ( !strcmp( studies[j].c_str(), curName.latin1() ) ) break; } if ( j == n ) newName = curName; else i++; } return newName; } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_WebSocketHandshakeParser.h" namespace jnc { namespace io { //.............................................................................. bool findInCsvStringIgnoreCase( const sl::StringRef& string0, const sl::StringRef& value, char c = ',' ) { sl::StringRef string = string0; for (size_t i = 0;; i++) { size_t delim = string.find(c); if (delim == -1) return string.cmpIgnoreCase(value) == 0 ? i : -1; if (string.getLeftSubString(delim).getRightTimmedString().cmpIgnoreCase(value) == 0) return i; string = string.getSubString(i + 1).getLeftTrimmedString(); } } //.............................................................................. WebSocketHandshakeParser::WebSocketHandshakeParser( WebSocketHandshake* handshake, const sl::StringRef& key ) { handshake->clear(); m_handshake = handshake; m_key = key; m_state = key.isEmpty() ? State_RequestLine : State_ResponseLine; } size_t WebSocketHandshakeParser::bufferLine( const char* p, size_t size ) { char* lf = (char*)memchr(p, '\n', size); if (lf) size = lf - p + 1; if (m_line.getLength() + size > MaxLineLength) return err::fail<size_t>(-1, "HTTP request line length limit exceeded"); m_line.append(p, size); return size; } size_t WebSocketHandshakeParser::parse( const void* p0, size_t size ) { const char* p = (char*)p0; const char* end = p + size; while (p < end && m_state != State_Completed) { size_t result = bufferLine(p, end - p); if (result == -1) return -1; p += result; if (!m_line.isSuffix('\n')) // incomplete line break; m_line.trim(); switch (m_state) { case State_RequestLine: result = parseRequestLine(); break; case State_ResponseLine: result = parseResponseLine(); break; case State_HeaderLine: result = parseHeaderLine(); break; default: ASSERT(false); } if (!result) return -1; m_line.clear(); } size_t length = p - (char*)p0; m_handshake->m_rawData = m_handshake->m_rawData.m_string + sl::StringRef((char*)p0, length); return length; } bool WebSocketHandshakeParser::parseRequestLine() { size_t delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP request line: missing resource"); sl::StringRef verb = m_line.getLeftSubString(delim); if (verb != "GET") return err::fail("invalid HTTP request: unexpected verb"); m_line.remove(0, delim + 1); m_line.trimLeft(); delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP request line: missing version"); m_handshake->m_resource = m_line.getLeftSubString(delim); m_line.remove(0, delim + 1); m_line.trimLeft(); if (!m_line.isPrefix("HTTP/")) return err::fail("invalid HTTP request line: unexpected version prefix"); m_line.remove(0, lengthof("HTTP/")); m_handshake->m_httpVersion = strtoul(m_line, NULL, 10) << 8; delim = m_line.find('.'); if (delim != -1) { m_line.remove(0, delim + 1); m_handshake->m_httpVersion |= strtoul(m_line, NULL, 10); } m_state = State_HeaderLine; return true; } bool WebSocketHandshakeParser::parseResponseLine() { if (!m_line.isPrefix("HTTP/")) return err::fail("invalid HTTP response line: unexpected version prefix"); m_line.remove(0, lengthof("HTTP/")); m_handshake->m_httpVersion = strtoul(m_line, NULL, 10) << 8; size_t delim = m_line.find('.'); if (delim != -1) { m_line.remove(0, delim + 1); m_handshake->m_httpVersion |= strtoul(m_line, NULL, 10); } delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP response line: missing status code"); m_line.remove(0, delim + 1); m_line.trimLeft(); m_handshake->m_statusCode = strtoul(m_line, NULL, 10); delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP response line: missing reason phrase"); m_line.remove(0, delim + 1); m_line.trimLeft(); m_handshake->m_reasonPhrase = m_line; m_state = State_HeaderLine; return true; } bool WebSocketHandshakeParser::parseHeaderLine() { if (m_line.isEmpty()) return finalize(); size_t delim = m_line.find(':'); if (delim == -1) return err::fail("invalid HTTP header line"); sl::StringRef key = m_line.getLeftSubString(delim).getRightTimmedString(); sl::StringRef value = m_line.getSubString(delim + 1).getLeftTrimmedString(); m_handshake->m_headers->addImpl(key, value); return true; } bool WebSocketHandshakeParser::finalize() { if (m_handshake->m_httpVersion < 0x0101) // HTTP/1.1 return err::fail("unsupported HTTP version"); const WebSocketHandshakeHeader* const* stdHeaderTable = m_handshake->m_headers->getStdHeaderTable(); bool hasMissingFields = !m_key.isEmpty() ? !stdHeaderTable[WebSocketHandshakeStdHeader_Connection] || !stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketAccept] : !stdHeaderTable[WebSocketHandshakeStdHeader_Host] || !stdHeaderTable[WebSocketHandshakeStdHeader_Connection] || !stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketVersion] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketKey]; if (hasMissingFields) return err::fail("invalid handshake: missing one or more required HTTP headers"); size_t i = findInCsvStringIgnoreCase(stdHeaderTable[WebSocketHandshakeStdHeader_Connection]->m_firstValue, "upgrade"); if (i == -1) return err::fail("invalid handshake: missing 'Upgrade' in HTTP 'Connection' header"); if (stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade]->m_firstValue.m_string.cmpIgnoreCase("websocket") != 0) return err::fail("invalid handshake: unexpected value of HTTP 'Upgrade' header"); if (!m_key.isEmpty() && !verifyAccept()) return false; m_state = State_Completed; return true; } bool WebSocketHandshakeParser::verifyAccept() { const WebSocketHandshakeHeader* accept = m_handshake->m_headers->getStdHeader(WebSocketHandshakeStdHeader_WebSocketAccept); ASSERT(!m_key.isEmpty() && accept); if (m_handshake->m_statusCode != 101) { err::setFormatStringError( "failure to switch HTTP protocol: %d %s", m_handshake->m_statusCode, m_handshake->m_reasonPhrase.sz() ); return false; } char buffer[256]; sl::Array<char> acceptHash(rc::BufKind_Stack, buffer, sizeof(buffer)); enc::Base64Encoding::decode(&acceptHash, accept->m_firstValue); if (acceptHash.getCount() != SHA_DIGEST_LENGTH) return err::fail("invalid handshake: bad 'Sec-WebSocket-Accept' format"); uchar_t keyHash[SHA_DIGEST_LENGTH]; calcWebSocketHandshakeKeyHash(keyHash, m_key); if (memcmp(acceptHash, keyHash, SHA_DIGEST_LENGTH) != 0) return err::fail("invalid handshake: 'Sec-WebSocket-Accept' doesn't match 'Sec-WebSocket-Key'"); return true; } //.............................................................................. } // namespace io } // namespace jnc <commit_msg>[jnc_io_websocket] typo fix: bool -> size_t; potential errors during handshake header parsing (non-critical)<commit_after>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_WebSocketHandshakeParser.h" namespace jnc { namespace io { //.............................................................................. size_t findInCsvStringIgnoreCase( const sl::StringRef& string0, const sl::StringRef& value, char c = ',' ) { sl::StringRef string = string0; for (size_t i = 0;; i++) { size_t delim = string.find(c); if (delim == -1) return string.cmpIgnoreCase(value) == 0 ? i : -1; if (string.getLeftSubString(delim).getRightTimmedString().cmpIgnoreCase(value) == 0) return i; string = string.getSubString(i + 1).getLeftTrimmedString(); } } //.............................................................................. WebSocketHandshakeParser::WebSocketHandshakeParser( WebSocketHandshake* handshake, const sl::StringRef& key ) { handshake->clear(); m_handshake = handshake; m_key = key; m_state = key.isEmpty() ? State_RequestLine : State_ResponseLine; } size_t WebSocketHandshakeParser::bufferLine( const char* p, size_t size ) { char* lf = (char*)memchr(p, '\n', size); if (lf) size = lf - p + 1; if (m_line.getLength() + size > MaxLineLength) return err::fail<size_t>(-1, "HTTP request line length limit exceeded"); m_line.append(p, size); return size; } size_t WebSocketHandshakeParser::parse( const void* p0, size_t size ) { const char* p = (char*)p0; const char* end = p + size; while (p < end && m_state != State_Completed) { size_t result = bufferLine(p, end - p); if (result == -1) return -1; p += result; if (!m_line.isSuffix('\n')) // incomplete line break; m_line.trim(); switch (m_state) { case State_RequestLine: result = parseRequestLine(); break; case State_ResponseLine: result = parseResponseLine(); break; case State_HeaderLine: result = parseHeaderLine(); break; default: ASSERT(false); } if (!result) return -1; m_line.clear(); } size_t length = p - (char*)p0; m_handshake->m_rawData = m_handshake->m_rawData.m_string + sl::StringRef((char*)p0, length); return length; } bool WebSocketHandshakeParser::parseRequestLine() { size_t delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP request line: missing resource"); sl::StringRef verb = m_line.getLeftSubString(delim); if (verb != "GET") return err::fail("invalid HTTP request: unexpected verb"); m_line.remove(0, delim + 1); m_line.trimLeft(); delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP request line: missing version"); m_handshake->m_resource = m_line.getLeftSubString(delim); m_line.remove(0, delim + 1); m_line.trimLeft(); if (!m_line.isPrefix("HTTP/")) return err::fail("invalid HTTP request line: unexpected version prefix"); m_line.remove(0, lengthof("HTTP/")); m_handshake->m_httpVersion = strtoul(m_line, NULL, 10) << 8; delim = m_line.find('.'); if (delim != -1) { m_line.remove(0, delim + 1); m_handshake->m_httpVersion |= strtoul(m_line, NULL, 10); } m_state = State_HeaderLine; return true; } bool WebSocketHandshakeParser::parseResponseLine() { if (!m_line.isPrefix("HTTP/")) return err::fail("invalid HTTP response line: unexpected version prefix"); m_line.remove(0, lengthof("HTTP/")); m_handshake->m_httpVersion = strtoul(m_line, NULL, 10) << 8; size_t delim = m_line.find('.'); if (delim != -1) { m_line.remove(0, delim + 1); m_handshake->m_httpVersion |= strtoul(m_line, NULL, 10); } delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP response line: missing status code"); m_line.remove(0, delim + 1); m_line.trimLeft(); m_handshake->m_statusCode = strtoul(m_line, NULL, 10); delim = m_line.find(' '); if (delim == -1) return err::fail("invalid HTTP response line: missing reason phrase"); m_line.remove(0, delim + 1); m_line.trimLeft(); m_handshake->m_reasonPhrase = m_line; m_state = State_HeaderLine; return true; } bool WebSocketHandshakeParser::parseHeaderLine() { if (m_line.isEmpty()) return finalize(); size_t delim = m_line.find(':'); if (delim == -1) return err::fail("invalid HTTP header line"); sl::StringRef key = m_line.getLeftSubString(delim).getRightTimmedString(); sl::StringRef value = m_line.getSubString(delim + 1).getLeftTrimmedString(); m_handshake->m_headers->addImpl(key, value); return true; } bool WebSocketHandshakeParser::finalize() { if (m_handshake->m_httpVersion < 0x0101) // HTTP/1.1 return err::fail("unsupported HTTP version"); const WebSocketHandshakeHeader* const* stdHeaderTable = m_handshake->m_headers->getStdHeaderTable(); bool hasMissingFields = !m_key.isEmpty() ? !stdHeaderTable[WebSocketHandshakeStdHeader_Connection] || !stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketAccept] : !stdHeaderTable[WebSocketHandshakeStdHeader_Host] || !stdHeaderTable[WebSocketHandshakeStdHeader_Connection] || !stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketVersion] || !stdHeaderTable[WebSocketHandshakeStdHeader_WebSocketKey]; if (hasMissingFields) return err::fail("invalid handshake: missing one or more required HTTP headers"); size_t i = findInCsvStringIgnoreCase(stdHeaderTable[WebSocketHandshakeStdHeader_Connection]->m_firstValue, "upgrade"); if (i == -1) return err::fail("invalid handshake: missing 'Upgrade' in HTTP 'Connection' header"); if (stdHeaderTable[WebSocketHandshakeStdHeader_Upgrade]->m_firstValue.m_string.cmpIgnoreCase("websocket") != 0) return err::fail("invalid handshake: unexpected value of HTTP 'Upgrade' header"); if (!m_key.isEmpty() && !verifyAccept()) return false; m_state = State_Completed; return true; } bool WebSocketHandshakeParser::verifyAccept() { const WebSocketHandshakeHeader* accept = m_handshake->m_headers->getStdHeader(WebSocketHandshakeStdHeader_WebSocketAccept); ASSERT(!m_key.isEmpty() && accept); if (m_handshake->m_statusCode != 101) { err::setFormatStringError( "failure to switch HTTP protocol: %d %s", m_handshake->m_statusCode, m_handshake->m_reasonPhrase.sz() ); return false; } char buffer[256]; sl::Array<char> acceptHash(rc::BufKind_Stack, buffer, sizeof(buffer)); enc::Base64Encoding::decode(&acceptHash, accept->m_firstValue); if (acceptHash.getCount() != SHA_DIGEST_LENGTH) return err::fail("invalid handshake: bad 'Sec-WebSocket-Accept' format"); uchar_t keyHash[SHA_DIGEST_LENGTH]; calcWebSocketHandshakeKeyHash(keyHash, m_key); if (memcmp(acceptHash, keyHash, SHA_DIGEST_LENGTH) != 0) return err::fail("invalid handshake: 'Sec-WebSocket-Accept' doesn't match 'Sec-WebSocket-Key'"); return true; } //.............................................................................. } // namespace io } // namespace jnc <|endoftext|>
<commit_before>#ifdef __APPLE__ // We can't set _POSIX_C_SOURCE on OS X because it hides the non-POSIX dladdr() with no way to get it back. // But we do need level 200809L features generally (for example, for EOWNERDEAD and ENOTRECOVERABLE on OS X). // So we do it the Apple Way. #define __DARWIN_C_LEVEL __DARWIN_C_FULL #else // Needed for siginfo_t to be defined. #define _POSIX_C_SOURCE 200809L #endif // We need this for ucontext.h to give us useful context stuff... #define _XOPEN_SOURCE 1 #include "crash.hpp" // iostream wants this on Travis on Mac #include <pthread.h> #include <errno.h> // Needed for automatic name demangling, but not all that portable #include <cxxabi.h> #include <execinfo.h> // Needed to hack contexts for signal traces #include <ucontext.h> // Needed to generate stacktraces ourselves #include <dlfcn.h> // We need strcmp #include <cstring> #include <cstdlib> #include <unistd.h> #include <string> #include <iostream> #include <fstream> #include <signal.h> #ifndef __APPLE__ // Pull in backward-cpp and use libdw from elfutils. // In theory backward-cpp can build and even backtrace on mac // In practice the mac port doesn't work on my machine and breaks the build on Travis. #define BACKWARD_HAS_DW 1 #include <backward.hpp> #endif namespace vg { // env var for getting full stack trace on cerr instead of a file path const char* var = "VG_FULL_TRACEBACK"; // fullTrace = true means env var was set // fullTrace = false means env var was not set bool fullTrace = false; /// Emit a stack trace when something bad happens. Add as a signal handler with sigaction. void emit_stacktrace(int signalNumber, siginfo_t *signalInfo, void *signalContext) { ofstream tempStream; string dirName; ostream* out; if (fullTrace == true) { out = &cerr; } else { char temp[] = "/tmp/vg_crash_XXXXXX"; char* tempDir = mkdtemp(temp); dirName = tempDir; tempStream.open(dirName+ "/stacktrace.txt"); out = &tempStream; } static backward::StackTrace stack_trace; stack_trace.load_here(32); static backward::Printer p; p.color_mode = backward::ColorMode::automatic; p.address = true; p.object = true; p.print(stack_trace, *out); if (fullTrace == false) { cerr << "ERROR: Signal "<< signalNumber << " occurred. VG has crashed. Run 'vg bugs --new' to report a bug." << endl; // Print path for stack trace file cerr << "Stack trace path: "<< dirName << "/stacktrace.txt" << endl; } // Make sure to exit with the right code exit(signalNumber + 128); } void enable_crash_handling() { // Set up stack trace support if (getenv(var) != nullptr) { if (strcmp(getenv(var), "1") == 0) { // if VG_FULL_TRACEBACK env var is set fullTrace = true; } } else { // if VG_FULL_TRACEBACK env var is not set fullTrace = false; } // backtrace() doesn't work in our Mac builds, and backward-cpp uses backtrace(). // Do this the old-fashioned way. // We do it the cleverer sigaction way to try and make OS X backtrace not just tell us that the signal handler is being called. struct sigaction sig_config; sig_config.sa_flags = SA_SIGINFO; // Use the new API and not the old signal() API for the handler. sig_config.sa_sigaction = emit_stacktrace; sigemptyset(&sig_config.sa_mask); sigaction(SIGABRT, &sig_config, nullptr); sigaction(SIGSEGV, &sig_config, nullptr); sigaction(SIGBUS, &sig_config, nullptr); sigaction(SIGILL, &sig_config, nullptr); // We don't set_terminate for aborts because we still want the standard // library's message about what the exception was. } } <commit_msg>Added stacktrace functionality to Mac and Linux systems<commit_after>#ifdef __APPLE__ // We can't set _POSIX_C_SOURCE on OS X because it hides the non-POSIX dladdr() with no way to get it back. // But we do need level 200809L features generally (for example, for EOWNERDEAD and ENOTRECOVERABLE on OS X). // So we do it the Apple Way. #define __DARWIN_C_LEVEL __DARWIN_C_FULL #else // Needed for siginfo_t to be defined. #define _POSIX_C_SOURCE 200809L #endif // We need this for ucontext.h to give us useful context stuff... #define _XOPEN_SOURCE 1 #include "crash.hpp" // iostream wants this on Travis on Mac #include <pthread.h> #include <errno.h> // Needed for automatic name demangling, but not all that portable #include <cxxabi.h> #include <execinfo.h> // Needed to hack contexts for signal traces #include <ucontext.h> // Needed to generate stacktraces ourselves #include <dlfcn.h> // We need strcmp #include <cstring> #include <cstdlib> #include <unistd.h> #include <string> #include <iostream> #include <fstream> #include <signal.h> #ifndef __APPLE__ // Pull in backward-cpp and use libdw from elfutils. // In theory backward-cpp can build and even backtrace on mac // In practice the mac port doesn't work on my machine and breaks the build on Travis. #define BACKWARD_HAS_DW 1 #include <backward.hpp> #endif namespace vg { // env var for getting full stack trace on cerr instead of a file path const char* var = "VG_FULL_TRACEBACK"; // fullTrace = true means env var was set // fullTrace = false means env var was not set bool fullTrace = false; void stacktrace_manually(ostream& out, int signalNumber, void* ip, void** bp) { // Now we compute our own stack trace, because backtrace() isn't so good on OS X. // We operate on the same principles as <https://stackoverflow.com/a/5426269> // Unfortunately this *only* seems to work even a little well on OS X; on Linux we get ip // wandering off relatively quickly. // Allocate a place to keep the dynamic library info for the address the stack is executing at Dl_info address_library; out << endl; out << "Next ip: " << ip << " Next bp: " << bp << endl; while (true) { // Work out where the ip is. if (!dladdr(ip, &address_library)) { // This address doesn't belong to anything! out << "Stack leaves code at ip=" << ip << endl; break; } if (address_library.dli_sname != nullptr) { // Make a place for the demangling function to save its status int status; // Do the demangling char* demangledName = abi::__cxa_demangle(address_library.dli_sname, NULL, NULL, &status); if(status == 0) { // Successfully demangled out << "Address " << ip << " in demangled symbol " << demangledName << " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr)) << ", in library " << address_library.dli_fname << " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl; free(demangledName); } else { // Leave mangled out << "Address " << ip << " in mangled symbol " << address_library.dli_sname << " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr)) << ", in library " << address_library.dli_fname << " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl; } #ifdef __APPLE__ #ifdef VG_DO_ATOS // Try running atos to print a line number. This can be slow so we don't do it by default. stringstream command; command << "atos -o " << address_library.dli_fname << " -l " << address_library.dli_fbase << " " << ip; out << "Running " << command.str() << "..." << endl; system(command.str().c_str()); #endif #endif } else { out << "Address " << ip << " out of symbol in library " << address_library.dli_fname << endl; } if(address_library.dli_sname != nullptr && !strcmp(address_library.dli_sname, "main")) { out << "Stack hit main" << endl; break; } if (bp != nullptr) { // Simulate a return ip = bp[1]; bp = (void**) bp[0]; } else { break; } out << endl; out << "Next ip: " << ip << " Next bp: " << bp << endl; } out << "Stack trace complete" << endl; out << endl; } /// Emit a stack trace when something bad happens. Add as a signal handler with sigaction. void emit_stacktrace(int signalNumber, siginfo_t *signalInfo, void *signalContext) { ofstream tempStream; string dirName; ostream* out; if (fullTrace == true) { out = &cerr; } else { char temp[] = "/tmp/vg_crash_XXXXXX"; char* tempDir = mkdtemp(temp); dirName = tempDir; tempStream.open(dirName+ "/stacktrace.txt"); out = &tempStream; } #ifdef __APPLE__ // OS X 64 bit does it this way // This holds the context that the signal came from, including registers and stuff ucontext_t* context = (ucontext_t*) signalContext; // TODO: This assumes x86 // Fetch out the registers // We model IP as a pointer to void (i.e. into code) void* ip; // We model BP as an array of two things: previous BP, and previous IP. void** bp; ip = (void*)context->uc_mcontext->__ss.__rip; bp = (void**)context->uc_mcontext->__ss.__rbp; *out << "Caught signal " << signalNumber << " raised at address " << ip << endl; // Do our own tracing because backtrace doesn't really work on all platforms. stacktrace_manually(*out,signalNumber, ip, bp); #else // Linux 64 bit does it this way static backward::StackTrace stack_trace; stack_trace.load_here(32); static backward::Printer p; p.color_mode = backward::ColorMode::automatic; p.address = true; p.object = true; p.print(stack_trace, *out); tempStream.close(); #endif if (fullTrace == false) { cerr << "ERROR: Signal "<< signalNumber << " occurred. VG has crashed. Run 'vg bugs --new' to report a bug." << endl; // Print path for stack trace file cerr << "Stack trace path: "<< dirName << "/stacktrace.txt" << endl; } // Make sure to exit with the right code exit(signalNumber + 128); } void enable_crash_handling() { // Set up stack trace support if (getenv(var) != nullptr) { if (strcmp(getenv(var), "1") == 0) { // if VG_FULL_TRACEBACK env var is set fullTrace = true; } } else { // if VG_FULL_TRACEBACK env var is not set fullTrace = false; } // backtrace() doesn't work in our Mac builds, and backward-cpp uses backtrace(). // Do this the old-fashioned way. // We do it the cleverer sigaction way to try and make OS X backtrace not just tell us that the signal handler is being called. struct sigaction sig_config; sig_config.sa_flags = SA_SIGINFO; // Use the new API and not the old signal() API for the handler. sig_config.sa_sigaction = emit_stacktrace; sigemptyset(&sig_config.sa_mask); sigaction(SIGABRT, &sig_config, nullptr); sigaction(SIGSEGV, &sig_config, nullptr); sigaction(SIGBUS, &sig_config, nullptr); sigaction(SIGILL, &sig_config, nullptr); // We don't set_terminate for aborts because we still want the standard // library's message about what the exception was. } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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 * *****************************************************************************/ // mapnik #include <mapnik/color.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/config_error.hpp> // agg #include "agg_color_rgba.h" // boost #include <boost/spirit/include/karma.hpp> // stl #include <sstream> namespace mapnik { color::color(std::string const& str) { *this = parse_color(str); } std::string color::to_string() const { std::stringstream ss; if (alpha_ == 255) { ss << "rgb(" << static_cast<unsigned>(red()) << "," << static_cast<unsigned>(green()) << "," << static_cast<unsigned>(blue()) << ")"; } else { ss << "rgba(" << static_cast<unsigned>(red()) << "," << static_cast<unsigned>(green()) << "," << static_cast<unsigned>(blue()) << "," << alpha() / 255.0 << ")"; } return ss.str(); } std::string color::to_hex_string() const { namespace karma = boost::spirit::karma; using boost::spirit::karma::_1; using boost::spirit::karma::hex; using boost::spirit::karma::eps; using boost::spirit::karma::right_align; std::string str; std::back_insert_iterator<std::string> sink(str); karma::generate(sink, // begin grammar '#' << right_align(2,'0')[hex[_1 = red()]] << right_align(2,'0')[hex[_1 = green()]] << right_align(2,'0')[hex[_1 = blue()]] << eps(alpha() < 255) << right_align(2,'0')[hex [_1 = alpha()]] // end grammar ); return str; } void color::premultiply() { agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_); pre_c.premultiply(); red_ = pre_c.r; green_ = pre_c.g; blue_ = pre_c.b; } void color::demultiply() { // note: this darkens too much: https://github.com/mapnik/mapnik/issues/1519 agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_); pre_c.demultiply(); red_ = pre_c.r; green_ = pre_c.g; blue_ = pre_c.b; } } <commit_msg>+ to_string based on spirit::karma for completeness.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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 * *****************************************************************************/ // mapnik #include <mapnik/color.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/config_error.hpp> // agg #include "agg_color_rgba.h" // boost #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_statement.hpp> // stl #include <sstream> namespace mapnik { color::color(std::string const& str) { *this = parse_color(str); } std::string color::to_string() const { namespace karma = boost::spirit::karma; using boost::spirit::karma::_1; using boost::spirit::karma::eps; using boost::spirit::karma::double_; using boost::spirit::karma::string; boost::spirit::karma::uint_generator<uint8_t,10> color_generator; std::string str; std::back_insert_iterator<std::string> sink(str); karma::generate(sink, // begin grammar string[ phoenix::if_(alpha()==255) [_1="rgb("].else_[_1="rgba("]] << color_generator[_1 = red()] << ',' << color_generator[_1 = green()] << ',' << color_generator[_1 = blue()] << string[ phoenix::if_(alpha()==255) [_1 = ')'].else_[_1 =',']] << eps(alpha()<255) << ',' << double_ [_1 = alpha()/255.0] << ')' // end grammar ); return str; } std::string color::to_hex_string() const { namespace karma = boost::spirit::karma; using boost::spirit::karma::_1; using boost::spirit::karma::hex; using boost::spirit::karma::eps; using boost::spirit::karma::right_align; std::string str; std::back_insert_iterator<std::string> sink(str); karma::generate(sink, // begin grammar '#' << right_align(2,'0')[hex[_1 = red()]] << right_align(2,'0')[hex[_1 = green()]] << right_align(2,'0')[hex[_1 = blue()]] << eps(alpha() < 255) << right_align(2,'0')[hex [_1 = alpha()]] // end grammar ); return str; } void color::premultiply() { agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_); pre_c.premultiply(); red_ = pre_c.r; green_ = pre_c.g; blue_ = pre_c.b; } void color::demultiply() { // note: this darkens too much: https://github.com/mapnik/mapnik/issues/1519 agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_); pre_c.demultiply(); red_ = pre_c.r; green_ = pre_c.g; blue_ = pre_c.b; } } <|endoftext|>
<commit_before>/** @file crema.cpp @brief Main cremacc file and main() function @copyright 2014 Assured Information Security, Inc. @author Jacob Torrey <torreyj@ainfosec.com> A main function to read in an input. It will parse and perform semantic analysis on the input and either exit(0) if it passes both, -1 otherwise. */ #include <iostream> #include "ast.h" #include "codegen.h" extern NBlock *rootBlock; extern int yyparse(); int main(int argc, char **argv) { yyparse(); if (rootBlock) { std::cout << *rootBlock << std::endl; if (rootBlock->semanticAnalysis(&rootCtx)) { std::cout << "Passed semantic analysis!" << std::endl; } else { std::cout << "Failed semantic analysis!" << std::endl; return -1; } } std::cout << "Generating LLVM IR bytecode" << std::endl; rootCodeGenCtx.codeGen(rootBlock); std::cout << "Dumping generated LLVM bytecode" << std::endl; rootCodeGenCtx.dump(); /* std::cout << "Running program:" << std::endl; rootCodeGenCtx.runProgram(); std::cout << "Program run successfully!" << std::endl; */ return 0; } <commit_msg>cremacc now executes the IR if it was successfully generated<commit_after>/** @file crema.cpp @brief Main cremacc file and main() function @copyright 2014 Assured Information Security, Inc. @author Jacob Torrey <torreyj@ainfosec.com> A main function to read in an input. It will parse and perform semantic analysis on the input and either exit(0) if it passes both, -1 otherwise. */ #include <iostream> #include "ast.h" #include "codegen.h" extern NBlock *rootBlock; extern int yyparse(); int main(int argc, char **argv) { yyparse(); if (rootBlock) { std::cout << *rootBlock << std::endl; if (rootBlock->semanticAnalysis(&rootCtx)) { std::cout << "Passed semantic analysis!" << std::endl; } else { std::cout << "Failed semantic analysis!" << std::endl; return -1; } } std::cout << "Generating LLVM IR bytecode" << std::endl; rootCodeGenCtx.codeGen(rootBlock); std::cout << "Dumping generated LLVM bytecode" << std::endl; rootCodeGenCtx.dump(); std::cout << "Running program:" << std::endl; std::cout << "Return value: " << rootCodeGenCtx.runProgram().IntVal.toString(10, true) << std::endl; std::cout << "Program run successfully!" << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008 by Jeff Weisberg Author: Jeff Weisberg <jaw @ tcp4me.com> Created: 2008-Dec-28 11:05 (EST) Function: daemonize $Id$ */ #define CURRENT_SUBSYSTEM 'd' #include "defs.h" #include "diag.h" #include "hrtime.h" #include "runmode.h" #include <stdlib.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <errno.h> static int i_am_parent = 1; static int childpid = 0; static char pidfile[64]; static void finish(void){ int status; int i; DEBUG("finishing"); if( childpid > 1 ){ DEBUG("killing child"); kill(childpid, 15); while(1){ i = wait(&status); if( i == -1 && errno == EINTR ) continue; break; } } if( i_am_parent ){ unlink(pidfile); } } static void sigexit(int sig){ VERBOSE("caught signal %d - exiting", sig); if( !i_am_parent && sig == 15 ){ // in child. exit runmode.shutdown(); return; } exit(EXIT_NORMAL_EXIT); // NB - parent will kill child in finish() } static void sigrestart(int sig){ int status; if( i_am_parent ){ if( childpid > 1 ){ VERBOSE("caught sig hup - restarting child"); kill(childpid, 1); } }else{ // in child. exit gracefully VERBOSE("caught sig hup - restarting"); runmode.winddown_and_restart(); return; } } void install_handler(int sig, void(*func)(int)){ struct sigaction sigi; sigi.sa_handler = func; sigi.sa_flags = 0; sigemptyset( & sigi.sa_mask ); sigaction(sig, &sigi, 0); } void daemon_siginit(void){ // sig handlers install_handler(SIGHUP, sigrestart); install_handler(SIGINT, sigexit); install_handler(SIGQUIT, sigexit); install_handler(SIGTERM, sigexit); install_handler(SIGPIPE, SIG_IGN); } int daemonize(int to, const char *name, int argc, char **argv){ int status = 0; FILE *pf; int i; // background if( fork() ) exit(0); // close fd close(0); open("/dev/null", O_RDWR); close(1); open("/dev/null", O_RDWR); #ifndef DEBUGING close(2); open("/dev/null", O_RDWR); #endif setsid(); daemon_siginit(); // pidfile snprintf(pidfile, sizeof(pidfile), "/var/run/%s.pid", name); pf = fopen(pidfile, "w"); if( !pf ){ FATAL("cannot open pid file"); } fprintf(pf, "%d\n", getpid()); fprintf(pf, "#"); for(i=1;i<argc;i++){ fprintf(pf, " %s", argv[i]); } fprintf(pf, "\n"); fclose(pf); atexit(finish); // watcher proc while(1){ DEBUG("forking"); childpid = fork(); if( childpid == -1 ){ FATAL("cannot fork"); } if( childpid ){ // parent while(1){ i = wait(&status); if( i == -1 && errno == EINTR ) continue; break; } childpid = 0; DEBUG("child exited with %d", status); if( !status ){ VERBOSE("exiting"); exit(EXIT_NORMAL_EXIT); } // otherwise, pause + restart sleep(to); }else{ // child i_am_parent = 0; return status; } } } <commit_msg>always close<commit_after>/* Copyright (c) 2008 by Jeff Weisberg Author: Jeff Weisberg <jaw @ tcp4me.com> Created: 2008-Dec-28 11:05 (EST) Function: daemonize $Id$ */ #define CURRENT_SUBSYSTEM 'd' #include "defs.h" #include "diag.h" #include "hrtime.h" #include "runmode.h" #include <stdlib.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <errno.h> static int i_am_parent = 1; static int childpid = 0; static char pidfile[64]; static void finish(void){ int status; int i; DEBUG("finishing"); if( childpid > 1 ){ DEBUG("killing child"); kill(childpid, 15); while(1){ i = wait(&status); if( i == -1 && errno == EINTR ) continue; break; } } if( i_am_parent ){ unlink(pidfile); } } static void sigexit(int sig){ VERBOSE("caught signal %d - exiting", sig); if( !i_am_parent && sig == 15 ){ // in child. exit runmode.shutdown(); return; } exit(EXIT_NORMAL_EXIT); // NB - parent will kill child in finish() } static void sigrestart(int sig){ int status; if( i_am_parent ){ if( childpid > 1 ){ VERBOSE("caught sig hup - restarting child"); kill(childpid, 1); } }else{ // in child. exit gracefully VERBOSE("caught sig hup - restarting"); runmode.winddown_and_restart(); return; } } void install_handler(int sig, void(*func)(int)){ struct sigaction sigi; sigi.sa_handler = func; sigi.sa_flags = 0; sigemptyset( & sigi.sa_mask ); sigaction(sig, &sigi, 0); } void daemon_siginit(void){ // sig handlers install_handler(SIGHUP, sigrestart); install_handler(SIGINT, sigexit); install_handler(SIGQUIT, sigexit); install_handler(SIGTERM, sigexit); install_handler(SIGPIPE, SIG_IGN); } int daemonize(int to, const char *name, int argc, char **argv){ int status = 0; FILE *pf; int i; // background if( fork() ) exit(0); // close fd close(0); open("/dev/null", O_RDWR); close(1); open("/dev/null", O_RDWR); close(2); open("/dev/null", O_RDWR); setsid(); daemon_siginit(); // pidfile snprintf(pidfile, sizeof(pidfile), "/var/run/%s.pid", name); pf = fopen(pidfile, "w"); if( !pf ){ FATAL("cannot open pid file"); } fprintf(pf, "%d\n", getpid()); fprintf(pf, "#"); for(i=1;i<argc;i++){ fprintf(pf, " %s", argv[i]); } fprintf(pf, "\n"); fclose(pf); atexit(finish); // watcher proc while(1){ DEBUG("forking"); childpid = fork(); if( childpid == -1 ){ FATAL("cannot fork"); } if( childpid ){ // parent while(1){ i = wait(&status); if( i == -1 && errno == EINTR ) continue; break; } childpid = 0; DEBUG("child exited with %d", status); if( !status ){ VERBOSE("exiting"); exit(EXIT_NORMAL_EXIT); } // otherwise, pause + restart sleep(to); }else{ // child i_am_parent = 0; return status; } } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkImageToHistogramFilter_hxx #define itkImageToHistogramFilter_hxx #include "itkImageToHistogramFilter.h" #include "itkImageRegionConstIterator.h" namespace itk { namespace Statistics { template <typename TImage> ImageToHistogramFilter<TImage>::ImageToHistogramFilter() { this->SetNumberOfRequiredInputs(1); this->SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput(0, this->MakeOutput(0)); // same default values as in the HistogramGenerator this->Self::SetMarginalScale(100); if (typeid(ValueType) == typeid(signed char) || typeid(ValueType) == typeid(unsigned char)) { this->Self::SetAutoMinimumMaximum(false); } else { this->Self::SetAutoMinimumMaximum(true); } } template <typename TImage> DataObject::Pointer ImageToHistogramFilter<TImage>::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)) { return HistogramType::New().GetPointer(); } template <typename TImage> const typename ImageToHistogramFilter<TImage>::HistogramType * ImageToHistogramFilter<TImage>::GetOutput() const { auto * output = itkDynamicCastInDebugMode<const HistogramType *>(this->ProcessObject::GetPrimaryOutput()); return output; } template <typename TImage> typename ImageToHistogramFilter<TImage>::HistogramType * ImageToHistogramFilter<TImage>::GetOutput() { auto * output = itkDynamicCastInDebugMode<HistogramType *>(this->ProcessObject::GetPrimaryOutput()); return output; } template <typename TImage> void ImageToHistogramFilter<TImage>::GraftOutput(DataObject * graft) { DataObject * output = const_cast<HistogramType *>(this->GetOutput()); // Call Histogram to copy meta-information, and the container output->Graft(graft); } template <typename TImage> unsigned int ImageToHistogramFilter<TImage>::GetNumberOfInputRequestedRegions() { // If we need to compute the minimum and maximum we don't stream if (this->GetAutoMinimumMaximumInput() && this->GetAutoMinimumMaximum()) { return 1; } return Superclass::GetNumberOfInputRequestedRegions(); } template <typename TImage> void ImageToHistogramFilter<TImage>::StreamedGenerateData(unsigned int inputRequestedRegionNumber) { if (inputRequestedRegionNumber == 0) { this->InitializeOutputHistogram(); } Superclass::StreamedGenerateData(inputRequestedRegionNumber); } template <typename TImage> void ImageToHistogramFilter<TImage>::InitializeOutputHistogram() { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); m_Minimum = HistogramMeasurementVectorType(nbOfComponents); m_Maximum = HistogramMeasurementVectorType(nbOfComponents); m_Minimum.Fill(NumericTraits<ValueType>::max()); m_Maximum.Fill(NumericTraits<ValueType>::NonpositiveMin()); m_MergeHistogram = nullptr; HistogramType * outputHistogram = this->GetOutput(); outputHistogram->SetClipBinsAtEnds(true); // the parameter needed to initialize the histogram HistogramSizeType size(nbOfComponents); if (this->GetHistogramSizeInput()) { // user provided value size = this->GetHistogramSize(); } else { // use a default value, which must be computed at run time for the VectorImage size.Fill(256); } if (this->GetAutoMinimumMaximumInput() && this->GetAutoMinimumMaximum()) { if (this->GetInput()->GetBufferedRegion() != this->GetInput()->GetLargestPossibleRegion()) { itkExceptionMacro(<< "AutoMinimumMaximumInput is not supported with streaming.") } // we have to compute the minimum and maximum values this->GetMultiThreader()->template ParallelizeImageRegion<ImageType::ImageDimension>( this->GetInput()->GetBufferedRegion(), [this](const RegionType & inputRegionForThread) { this->ThreadedComputeMinimumAndMaximum(inputRegionForThread); }, this); this->ApplyMarginalScale(m_Minimum, m_Maximum, size); } else { if (this->GetHistogramBinMinimumInput()) { m_Minimum = this->GetHistogramBinMinimum(); } else { m_Minimum.Fill(NumericTraits<ValueType>::NonpositiveMin() - 0.5); } if (this->GetHistogramBinMaximumInput()) { m_Maximum = this->GetHistogramBinMaximum(); } else { m_Maximum.Fill(NumericTraits<ValueType>::max() + 0.5); } // No marginal scaling is applied in this case } outputHistogram->SetMeasurementVectorSize(nbOfComponents); outputHistogram->Initialize(size, m_Minimum, m_Maximum); } template <typename TImage> void ImageToHistogramFilter<TImage>::AfterStreamedGenerateData() { Superclass::AfterStreamedGenerateData(); HistogramType * outputHistogram = this->GetOutput(); outputHistogram->Graft(m_MergeHistogram); m_MergeHistogram = nullptr; } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedComputeMinimumAndMaximum(const RegionType & inputRegionForThread) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); HistogramMeasurementVectorType min(nbOfComponents); HistogramMeasurementVectorType max(nbOfComponents); ImageRegionConstIterator<TImage> inputIt(this->GetInput(), inputRegionForThread); inputIt.GoToBegin(); HistogramMeasurementVectorType m(nbOfComponents); min.Fill(NumericTraits<ValueType>::max()); max.Fill(NumericTraits<ValueType>::NonpositiveMin()); while (!inputIt.IsAtEnd()) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray(p, m); for (unsigned int i = 0; i < nbOfComponents; i++) { min[i] = std::min(m[i], min[i]); max[i] = std::max(m[i], max[i]); } ++inputIt; } std::lock_guard<std::mutex> mutexHolder(m_Mutex); for (unsigned int i = 0; i < nbOfComponents; i++) { m_Minimum[i] = std::min(m_Minimum[i], min[i]); m_Maximum[i] = std::max(m_Maximum[i], max[i]); } } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedStreamedGenerateData(const RegionType & inputRegionForThread) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); const HistogramType * outputHistogram = this->GetOutput(); HistogramPointer histogram = HistogramType::New(); histogram->SetClipBinsAtEnds(outputHistogram->GetClipBinsAtEnds()); histogram->SetMeasurementVectorSize(nbOfComponents); histogram->Initialize(outputHistogram->GetSize(), m_Minimum, m_Maximum); ImageRegionConstIterator<TImage> inputIt(this->GetInput(), inputRegionForThread); inputIt.GoToBegin(); HistogramMeasurementVectorType m(nbOfComponents); typename HistogramType::IndexType index; while (!inputIt.IsAtEnd()) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray(p, m); histogram->GetIndex(m, index); histogram->IncreaseFrequencyOfIndex(index, 1); ++inputIt; } this->ThreadedMergeHistogram(std::move(histogram)); } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedMergeHistogram(HistogramPointer && histogram) { while (true) { std::unique_lock<std::mutex> lock(m_Mutex); if (m_MergeHistogram.IsNull()) { m_MergeHistogram = std::move(histogram); return; } else { // merge/reduce the local results with current values in m_MergeHistogram // take ownership locally HistogramPointer tomergeHistogram; swap(m_MergeHistogram, tomergeHistogram); // allow other threads to merge data lock.unlock(); using HistogramIterator = typename HistogramType::ConstIterator; HistogramIterator hit = tomergeHistogram->Begin(); HistogramIterator end = tomergeHistogram->End(); typename HistogramType::IndexType index; while (hit != end) { histogram->GetIndex(hit.GetMeasurementVector(), index); histogram->IncreaseFrequencyOfIndex(index, hit.GetFrequency()); ++hit; } } } } template <typename TImage> void ImageToHistogramFilter<TImage>::ApplyMarginalScale(HistogramMeasurementVectorType & min, HistogramMeasurementVectorType & max, HistogramSizeType & size) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); bool clipHistograms = true; for (unsigned int i = 0; i < nbOfComponents; i++) { if (!NumericTraits<HistogramMeasurementType>::is_integer) { HistogramMeasurementType marginalScale = this->GetMarginalScale(); const double margin = (static_cast<HistogramMeasurementType>(max[i] - min[i]) / static_cast<HistogramMeasurementType>(size[i])) / static_cast<HistogramMeasurementType>(marginalScale); // Now we check if the max[i] value can be increased by // the margin value without saturating the capacity of the // HistogramMeasurementType if ((NumericTraits<HistogramMeasurementType>::max() - max[i]) > margin) { max[i] = static_cast<HistogramMeasurementType>(max[i] + margin); } else { // an overflow would occur if we add 'margin' to the max // therefore we just compromise in setting max = max. // Histogram measurement type would force the clipping the max // value. // Therefore we must call the following to include the max value: clipHistograms = false; // The above function is okay since here we are within the // autoMinMax // computation and clearly the user intended to include min and max. } } else { // max[i] = SafeAssign(max[i] + NumericTraits<MeasurementType>::OneValue()); // if ( max[i] <= max[i] ) if (max[i] < (static_cast<ValueType>(NumericTraits<HistogramMeasurementType>::max()) - NumericTraits<ValueType>::OneValue())) { max[i] = static_cast<HistogramMeasurementType>(max[i] + NumericTraits<ValueType>::OneValue()); } else { // an overflow would have occurred, therefore set max to max // Histogram measurement type would force the clipping the max // value. // Therefore we must call the following to include the max value: clipHistograms = false; // The above function is okay since here we are within the // autoMinMax // computation and clearly the user intended to include min and max. } } } if (clipHistograms == false) { this->GetOutput()->SetClipBinsAtEnds(false); } } template <typename TImage> void ImageToHistogramFilter<TImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); // m_HistogramBinMinimum os << indent << "HistogramBinMinimum: " << this->GetHistogramBinMinimum() << std::endl; // m_HistogramBinMaximum os << indent << "HistogramBinMaximum: " << this->GetHistogramBinMaximum() << std::endl; // m_MarginalScale os << indent << "MarginalScale: " << this->GetMarginalScale() << std::endl; // m_AutoMinimumMaximum os << indent << "AutoMinimumMaximum: " << this->GetAutoMinimumMaximum() << std::endl; // m_HistogramSize os << indent << "HistogramSize: " << this->GetHistogramSize() << std::endl; } } // end of namespace Statistics } // end of namespace itk #endif <commit_msg>BUG: Fix ImageHistogram printing null inputs<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkImageToHistogramFilter_hxx #define itkImageToHistogramFilter_hxx #include "itkImageToHistogramFilter.h" #include "itkImageRegionConstIterator.h" namespace itk { namespace Statistics { template <typename TImage> ImageToHistogramFilter<TImage>::ImageToHistogramFilter() { this->SetNumberOfRequiredInputs(1); this->SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput(0, this->MakeOutput(0)); // same default values as in the HistogramGenerator this->Self::SetMarginalScale(100); if (typeid(ValueType) == typeid(signed char) || typeid(ValueType) == typeid(unsigned char)) { this->Self::SetAutoMinimumMaximum(false); } else { this->Self::SetAutoMinimumMaximum(true); } } template <typename TImage> DataObject::Pointer ImageToHistogramFilter<TImage>::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)) { return HistogramType::New().GetPointer(); } template <typename TImage> const typename ImageToHistogramFilter<TImage>::HistogramType * ImageToHistogramFilter<TImage>::GetOutput() const { auto * output = itkDynamicCastInDebugMode<const HistogramType *>(this->ProcessObject::GetPrimaryOutput()); return output; } template <typename TImage> typename ImageToHistogramFilter<TImage>::HistogramType * ImageToHistogramFilter<TImage>::GetOutput() { auto * output = itkDynamicCastInDebugMode<HistogramType *>(this->ProcessObject::GetPrimaryOutput()); return output; } template <typename TImage> void ImageToHistogramFilter<TImage>::GraftOutput(DataObject * graft) { DataObject * output = const_cast<HistogramType *>(this->GetOutput()); // Call Histogram to copy meta-information, and the container output->Graft(graft); } template <typename TImage> unsigned int ImageToHistogramFilter<TImage>::GetNumberOfInputRequestedRegions() { // If we need to compute the minimum and maximum we don't stream if (this->GetAutoMinimumMaximumInput() && this->GetAutoMinimumMaximum()) { return 1; } return Superclass::GetNumberOfInputRequestedRegions(); } template <typename TImage> void ImageToHistogramFilter<TImage>::StreamedGenerateData(unsigned int inputRequestedRegionNumber) { if (inputRequestedRegionNumber == 0) { this->InitializeOutputHistogram(); } Superclass::StreamedGenerateData(inputRequestedRegionNumber); } template <typename TImage> void ImageToHistogramFilter<TImage>::InitializeOutputHistogram() { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); m_Minimum = HistogramMeasurementVectorType(nbOfComponents); m_Maximum = HistogramMeasurementVectorType(nbOfComponents); m_Minimum.Fill(NumericTraits<ValueType>::max()); m_Maximum.Fill(NumericTraits<ValueType>::NonpositiveMin()); m_MergeHistogram = nullptr; HistogramType * outputHistogram = this->GetOutput(); outputHistogram->SetClipBinsAtEnds(true); // the parameter needed to initialize the histogram HistogramSizeType size(nbOfComponents); if (this->GetHistogramSizeInput()) { // user provided value size = this->GetHistogramSize(); } else { // use a default value, which must be computed at run time for the VectorImage size.Fill(256); } if (this->GetAutoMinimumMaximumInput() && this->GetAutoMinimumMaximum()) { if (this->GetInput()->GetBufferedRegion() != this->GetInput()->GetLargestPossibleRegion()) { itkExceptionMacro(<< "AutoMinimumMaximumInput is not supported with streaming.") } // we have to compute the minimum and maximum values this->GetMultiThreader()->template ParallelizeImageRegion<ImageType::ImageDimension>( this->GetInput()->GetBufferedRegion(), [this](const RegionType & inputRegionForThread) { this->ThreadedComputeMinimumAndMaximum(inputRegionForThread); }, this); this->ApplyMarginalScale(m_Minimum, m_Maximum, size); } else { if (this->GetHistogramBinMinimumInput()) { m_Minimum = this->GetHistogramBinMinimum(); } else { m_Minimum.Fill(NumericTraits<ValueType>::NonpositiveMin() - 0.5); } if (this->GetHistogramBinMaximumInput()) { m_Maximum = this->GetHistogramBinMaximum(); } else { m_Maximum.Fill(NumericTraits<ValueType>::max() + 0.5); } // No marginal scaling is applied in this case } outputHistogram->SetMeasurementVectorSize(nbOfComponents); outputHistogram->Initialize(size, m_Minimum, m_Maximum); } template <typename TImage> void ImageToHistogramFilter<TImage>::AfterStreamedGenerateData() { Superclass::AfterStreamedGenerateData(); HistogramType * outputHistogram = this->GetOutput(); outputHistogram->Graft(m_MergeHistogram); m_MergeHistogram = nullptr; } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedComputeMinimumAndMaximum(const RegionType & inputRegionForThread) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); HistogramMeasurementVectorType min(nbOfComponents); HistogramMeasurementVectorType max(nbOfComponents); ImageRegionConstIterator<TImage> inputIt(this->GetInput(), inputRegionForThread); inputIt.GoToBegin(); HistogramMeasurementVectorType m(nbOfComponents); min.Fill(NumericTraits<ValueType>::max()); max.Fill(NumericTraits<ValueType>::NonpositiveMin()); while (!inputIt.IsAtEnd()) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray(p, m); for (unsigned int i = 0; i < nbOfComponents; i++) { min[i] = std::min(m[i], min[i]); max[i] = std::max(m[i], max[i]); } ++inputIt; } std::lock_guard<std::mutex> mutexHolder(m_Mutex); for (unsigned int i = 0; i < nbOfComponents; i++) { m_Minimum[i] = std::min(m_Minimum[i], min[i]); m_Maximum[i] = std::max(m_Maximum[i], max[i]); } } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedStreamedGenerateData(const RegionType & inputRegionForThread) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); const HistogramType * outputHistogram = this->GetOutput(); HistogramPointer histogram = HistogramType::New(); histogram->SetClipBinsAtEnds(outputHistogram->GetClipBinsAtEnds()); histogram->SetMeasurementVectorSize(nbOfComponents); histogram->Initialize(outputHistogram->GetSize(), m_Minimum, m_Maximum); ImageRegionConstIterator<TImage> inputIt(this->GetInput(), inputRegionForThread); inputIt.GoToBegin(); HistogramMeasurementVectorType m(nbOfComponents); typename HistogramType::IndexType index; while (!inputIt.IsAtEnd()) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray(p, m); histogram->GetIndex(m, index); histogram->IncreaseFrequencyOfIndex(index, 1); ++inputIt; } this->ThreadedMergeHistogram(std::move(histogram)); } template <typename TImage> void ImageToHistogramFilter<TImage>::ThreadedMergeHistogram(HistogramPointer && histogram) { while (true) { std::unique_lock<std::mutex> lock(m_Mutex); if (m_MergeHistogram.IsNull()) { m_MergeHistogram = std::move(histogram); return; } else { // merge/reduce the local results with current values in m_MergeHistogram // take ownership locally HistogramPointer tomergeHistogram; swap(m_MergeHistogram, tomergeHistogram); // allow other threads to merge data lock.unlock(); using HistogramIterator = typename HistogramType::ConstIterator; HistogramIterator hit = tomergeHistogram->Begin(); HistogramIterator end = tomergeHistogram->End(); typename HistogramType::IndexType index; while (hit != end) { histogram->GetIndex(hit.GetMeasurementVector(), index); histogram->IncreaseFrequencyOfIndex(index, hit.GetFrequency()); ++hit; } } } } template <typename TImage> void ImageToHistogramFilter<TImage>::ApplyMarginalScale(HistogramMeasurementVectorType & min, HistogramMeasurementVectorType & max, HistogramSizeType & size) { const unsigned int nbOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); bool clipHistograms = true; for (unsigned int i = 0; i < nbOfComponents; i++) { if (!NumericTraits<HistogramMeasurementType>::is_integer) { HistogramMeasurementType marginalScale = this->GetMarginalScale(); const double margin = (static_cast<HistogramMeasurementType>(max[i] - min[i]) / static_cast<HistogramMeasurementType>(size[i])) / static_cast<HistogramMeasurementType>(marginalScale); // Now we check if the max[i] value can be increased by // the margin value without saturating the capacity of the // HistogramMeasurementType if ((NumericTraits<HistogramMeasurementType>::max() - max[i]) > margin) { max[i] = static_cast<HistogramMeasurementType>(max[i] + margin); } else { // an overflow would occur if we add 'margin' to the max // therefore we just compromise in setting max = max. // Histogram measurement type would force the clipping the max // value. // Therefore we must call the following to include the max value: clipHistograms = false; // The above function is okay since here we are within the // autoMinMax // computation and clearly the user intended to include min and max. } } else { // max[i] = SafeAssign(max[i] + NumericTraits<MeasurementType>::OneValue()); // if ( max[i] <= max[i] ) if (max[i] < (static_cast<ValueType>(NumericTraits<HistogramMeasurementType>::max()) - NumericTraits<ValueType>::OneValue())) { max[i] = static_cast<HistogramMeasurementType>(max[i] + NumericTraits<ValueType>::OneValue()); } else { // an overflow would have occurred, therefore set max to max // Histogram measurement type would force the clipping the max // value. // Therefore we must call the following to include the max value: clipHistograms = false; // The above function is okay since here we are within the // autoMinMax // computation and clearly the user intended to include min and max. } } } if (clipHistograms == false) { this->GetOutput()->SetClipBinsAtEnds(false); } } template <typename TImage> void ImageToHistogramFilter<TImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); if (this->GetHistogramBinMinimumInput()) { os << indent << "HistogramBinMinimum: " << this->GetHistogramBinMinimum() << std::endl; } if (this->GetHistogramBinMaximumInput()) { os << indent << "HistogramBinMaximum: " << this->GetHistogramBinMaximum() << std::endl; } os << indent << "MarginalScale: " << this->GetMarginalScale() << std::endl; os << indent << "AutoMinimumMaximum: " << this->GetAutoMinimumMaximum() << std::endl; if (this->GetHistogramSizeInput()) { os << indent << "HistogramSize: " << this->GetHistogramSize() << std::endl; } } } // end of namespace Statistics } // end of namespace itk #endif <|endoftext|>
<commit_before>/* * Game: Pong Game. * Author: Rafael Campos Nunes. * License: Apache v2. * * Fell free to contact me on * Email: rafaelnunes737@hotmail.com * Github: https://github.com/rafaelcn * * Also you can contact me on IRC(freenode.net server) my nickname is: ranu. */ #ifndef DEBUG_HPP #define DEBUG_HPP #include <iostream> /** * @brief The Debug class is where debug functions are defined. */ class Debug { public: /** * @brief logf * @param filename * @param message * @return */ static bool logf(const std::string& filename, const std::string& message); template<typename... Ts> static void log(const Ts&... args) { std::cout << "Debug::log: "; int expanded[] = { (std::cout << args << "", 0)... }; (void)expanded; std::cout << std::endl; } template<typename... Ts> static void logerr(const Ts&... args) { std::cout << "Debug::logerr: "; int expanded[] = { (std::cout << args, 0)... }; (void)expanded; std::cout << std::endl; } }; #endif // DEBUG_H <commit_msg>Added a warning debug option.<commit_after>/* * Game: Pong Game. * Author: Rafael Campos Nunes. * License: Apache v2. * * Fell free to contact me on * Email: rafaelnunes737@hotmail.com * Github: https://github.com/rafaelcn * * Also you can contact me on IRC(freenode.net server) my nickname is: ranu. */ #ifndef DEBUG_HPP #define DEBUG_HPP #include <iostream> /** * @brief The Debug class is where debug functions are defined. */ class Debug { public: /** * @brief logf * @param filename * @param message * @return */ static bool logf(const std::string& filename, const std::string& message); template<typename... Ts> static void log(const Ts&... args) { std::cout << "Debug::log: "; int expanded[] = { (std::cout << args << "", 0)... }; (void)expanded; std::cout << std::endl; } template<typename... Ts> static void logwarn(const Ts&... args) { std::cout << "Debug::logwarn: "; int expanded[] = { (std::cout << args, 0)... }; (void)expanded; std::cout << std::endl; } template<typename... Ts> static void logerr(const Ts&... args) { std::cout << "Debug::logerr: "; int expanded[] = { (std::cout << args, 0)... }; (void)expanded; std::cout << std::endl; } }; #endif // DEBUG_H <|endoftext|>
<commit_before>/* Copyright: Copyright (C) 2003-2018 SIL International. Authors: mcdurdin */ #include "pch.h" #include <stdarg.h> inline BOOL ShouldDebug() { return g_debug_KeymanLog; } #define TAB "\t" #define NL "\n" #include <chrono> #define _USE_WINDOWS #ifdef _USE_WINDOWS #define DECLSPEC_IMPORT __declspec(dllimport) #define WINBASEAPI DECLSPEC_IMPORT #define VOID void #define WINAPI __stdcall extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( char *lpOutputString ); #else #include <syslog.h> #endif // simulation of Windows GetTickCount() unsigned long GetTickCount() { using namespace std::chrono; return (unsigned long) duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count(); } int DebugLog_1(const char *file, int line, const char *function, const char *fmt, ...) { char fmtbuf[256]; va_list vars; va_start(vars, fmt); vsnprintf_s(fmtbuf, sizeof(fmtbuf) / sizeof(fmtbuf[0]), _TRUNCATE, fmt, vars); // I2248 // I3547 fmtbuf[255] = 0; va_end(vars); if(g_debug_KeymanLog) { if(g_debug_ToConsole) { // I3951 char windowinfo[1024]; sprintf(windowinfo, "%d" TAB //"TickCount" TAB "%s:%d" TAB //"SourceFile" TAB "%s" TAB //"Function" "%s" NL, //"Message" GetTickCount(), //"TickCount" TAB file, line, //"SourceFile" TAB function, //"Function" TAB fmtbuf); //"Message" #ifdef _USE_WINDOWS OutputDebugStringA(windowinfo); #else syslog(LOG_DEBUG, "%s", windowinfo); #endif } } return 0; } struct Debug_ModifierNames { char *name; UINT flag; }; extern const char *VKeyNames[256]; const struct Debug_ModifierNames s_modifierNames[14] = { {" LCTRL", 0x0001}, // Left Control flag {" RCTRL", 0x0002}, // Right Control flag {" LALT", 0x0004}, // Left Alt flag {" RALT", 0x0008}, // Right Alt flag {" SHIFT", 0x0010}, // Either shift flag {" CTRL", 0x0020}, // Either ctrl flag -- don't use this for inputs {" ALT", 0x0040}, // Either alt flag -- don't use this for inputs {" CAPS", 0x0100}, // Caps lock on {" NCAPS", 0x0200}, // Caps lock NOT on {" NUMLOCK", 0x0400}, // Num lock on {" NNUMLOCK", 0x0800}, // Num lock NOT on {" SCROLL", 0x1000}, // Scroll lock on {" NSCROLL", 0x2000}, // Scroll lock NOT on {NULL, 0} }; char *Debug_ModifierName(UINT modifiers) { __declspec(thread) static char buf[256]; buf[0] = 0; for(int i = 0; s_modifierNames[i].name; i++) if (modifiers & s_modifierNames[i].flag) { strcat(buf, s_modifierNames[i].name); } if (*buf) return buf + 1; return "Unmodified"; } char *Debug_VirtualKey(WORD vk) { __declspec(thread) static char buf[256]; if (!ShouldDebug()) { return ""; } if (vk < 256) { sprintf(buf, "['%s' 0x%x]", VKeyNames[vk], vk); } else { sprintf(buf, "[0x%x]", vk); } return buf; } char *Debug_UnicodeString(PWSTR s, int x) { if (!ShouldDebug()) { return ""; } __declspec(thread) static char bufout[2][128 * 7]; WCHAR *p; char *q; bufout[x][0] = 0; for (p = s, q = bufout[x]; *p && (p - s < 128); p++) { sprintf(q, "U+%4.4X ", *p); q = strchr(q, 0); } //WideCharToMultiByte(CP_ACP, 0, buf, -1, bufout, 128, NULL, NULL); return bufout[x]; } char *Debug_UnicodeString(std::u16string s, int x) { if (!ShouldDebug()) { return ""; } __declspec(thread) static char bufout[2][128 * 7]; auto p = s.begin(); char *q; bufout[x][0] = 0; for (p, q = bufout[x]; p != s.end(); p++) { sprintf(q, "U+%4.4X ", *p); q = strchr(q, 0); } //WideCharToMultiByte(CP_ACP, 0, buf, -1, bufout, 128, NULL, NULL); return bufout[x]; } void write_console(BOOL error, const wchar_t *fmt, ...) { if (!g_silent || error) { va_list vars; va_start(vars, fmt); vwprintf(fmt, vars); va_end(vars); } } <commit_msg>[Common] debug functions thread safety removal for cross-platform<commit_after>/* Copyright: Copyright (C) 2003-2018 SIL International. Authors: mcdurdin */ #include "pch.h" #include <stdarg.h> inline BOOL ShouldDebug() { return g_debug_KeymanLog; } #define TAB "\t" #define NL "\n" #include <chrono> #ifdef _MSC_VER #define _USE_WINDOWS #endif #ifdef _USE_WINDOWS #define DECLSPEC_IMPORT __declspec(dllimport) #define WINBASEAPI DECLSPEC_IMPORT #define VOID void #define WINAPI __stdcall extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( char *lpOutputString ); #else #include <syslog.h> #endif // simulation of Windows GetTickCount() unsigned long GetTickCount() { using namespace std::chrono; return (unsigned long) duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count(); } int DebugLog_1(const char *file, int line, const char *function, const char *fmt, ...) { char fmtbuf[256]; va_list vars; va_start(vars, fmt); vsnprintf_s(fmtbuf, sizeof(fmtbuf) / sizeof(fmtbuf[0]), _TRUNCATE, fmt, vars); // I2248 // I3547 fmtbuf[255] = 0; va_end(vars); if(g_debug_KeymanLog) { if(g_debug_ToConsole) { // I3951 char windowinfo[1024]; sprintf(windowinfo, "%d" TAB //"TickCount" TAB "%s:%d" TAB //"SourceFile" TAB "%s" TAB //"Function" "%s" NL, //"Message" GetTickCount(), //"TickCount" TAB file, line, //"SourceFile" TAB function, //"Function" TAB fmtbuf); //"Message" #ifdef _USE_WINDOWS OutputDebugStringA(windowinfo); #else syslog(LOG_DEBUG, "%s", windowinfo); #endif } } return 0; } struct Debug_ModifierNames { char *name; UINT flag; }; extern const char *VKeyNames[256]; const struct Debug_ModifierNames s_modifierNames[14] = { {" LCTRL", 0x0001}, // Left Control flag {" RCTRL", 0x0002}, // Right Control flag {" LALT", 0x0004}, // Left Alt flag {" RALT", 0x0008}, // Right Alt flag {" SHIFT", 0x0010}, // Either shift flag {" CTRL", 0x0020}, // Either ctrl flag -- don't use this for inputs {" ALT", 0x0040}, // Either alt flag -- don't use this for inputs {" CAPS", 0x0100}, // Caps lock on {" NCAPS", 0x0200}, // Caps lock NOT on {" NUMLOCK", 0x0400}, // Num lock on {" NNUMLOCK", 0x0800}, // Num lock NOT on {" SCROLL", 0x1000}, // Scroll lock on {" NSCROLL", 0x2000}, // Scroll lock NOT on {NULL, 0} }; char *Debug_ModifierName(UINT modifiers) { #ifdef _MSC_VER __declspec(thread) #endif static char buf[256]; buf[0] = 0; for(int i = 0; s_modifierNames[i].name; i++) if (modifiers & s_modifierNames[i].flag) { strcat(buf, s_modifierNames[i].name); } if (*buf) return buf + 1; return "Unmodified"; } char *Debug_VirtualKey(WORD vk) { #ifdef _MSC_VER __declspec(thread) #endif static char buf[256]; if (!ShouldDebug()) { return ""; } if (vk < 256) { sprintf(buf, "['%s' 0x%x]", VKeyNames[vk], vk); } else { sprintf(buf, "[0x%x]", vk); } return buf; } char *Debug_UnicodeString(PWSTR s, int x) { if (!ShouldDebug()) { return ""; } #ifdef _MSC_VER __declspec(thread) #endif static char bufout[2][128 * 7]; WCHAR *p; char *q; bufout[x][0] = 0; for (p = s, q = bufout[x]; *p && (p - s < 128); p++) { sprintf(q, "U+%4.4X ", *p); q = strchr(q, 0); } //WideCharToMultiByte(CP_ACP, 0, buf, -1, bufout, 128, NULL, NULL); return bufout[x]; } char *Debug_UnicodeString(std::u16string s, int x) { if (!ShouldDebug()) { return ""; } #ifdef _MSC_VER __declspec(thread) #endif static char bufout[2][128 * 7]; auto p = s.begin(); char *q; bufout[x][0] = 0; for (p, q = bufout[x]; p != s.end(); p++) { sprintf(q, "U+%4.4X ", *p); q = strchr(q, 0); } //WideCharToMultiByte(CP_ACP, 0, buf, -1, bufout, 128, NULL, NULL); return bufout[x]; } void write_console(BOOL error, const wchar_t *fmt, ...) { if (!g_silent || error) { va_list vars; va_start(vars, fmt); vwprintf(fmt, vars); va_end(vars); } } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/basegl/processors/imageprocessing/imagechannelcombine.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> namespace inviwo { const ProcessorInfo ImageChannelCombine::processorInfo_{ "org.inviwo.ImageChannelCombine", // Class identifier "Image Channel Combine", // Display name "Image Operation", // Category CodeState::Experimental, // Code state Tags::GL, // Tags }; const ProcessorInfo ImageChannelCombine::getProcessorInfo() const { return processorInfo_; } ImageChannelCombine::ImageChannelCombine() : Processor() , inport0_("inport0", true) , inport1_("inport1", true) , inport2_("inport2", true) , inport3_("inport3", true) , outport_("outport", false) , rChannelSrc_("redChannel", "Red Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , gChannelSrc_("greenChannel", "Green Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , bChannelSrc_("blueChannel", "Blue Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , aChannelSrc_("alphaChannel", "Alpha Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , alpha_("alpha", "Alpha", 1.0f, 0.0f, 1.0f, 0.001f) , shader_("img_channel_combine.frag") { shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); addPort(inport0_); addPort(inport1_); addPort(inport2_); inport3_.setOptional(true); addPort(inport3_); addPort(outport_); addProperties(rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_, alpha_); } void ImageChannelCombine::process() { auto isSame = [](auto a, auto b, auto c) { if (a != b) return false; if (a != c) return false; if (b != c) return false; return true; }; auto img0 = inport0_.getData(); auto img1 = inport1_.getData(); auto img2 = inport2_.getData(); auto img3 = inport3_.getData(); if (isSame(img0->getDimensions(), img1->getDimensions(), img2->getDimensions()) && (inport3_.isConnected() && img3 && img3->getDimensions() != img0->getDimensions())) { throw Exception("The image dimensions of all inports needs to be the same", IVW_CONTEXT); } if (inport0_.isChanged() || inport1_.isChanged() || inport2_.isChanged()) { const auto dimensions = inport0_.getData()->getDimensions(); auto t1 = inport0_.getData()->getDataFormat()->getNumericType(); auto t2 = inport1_.getData()->getDataFormat()->getNumericType(); auto t3 = inport2_.getData()->getDataFormat()->getNumericType(); NumericType type; if (t1 == t2 && t1 == t3) { // All have the same numType type = t1; } else if (t1 == NumericType::Float || t2 == NumericType::Float || t2 == NumericType::Float) { // At least one is a float type type = NumericType::Float; } else { // At least one are signed, and at least one are unsigned type = NumericType::Float; } auto p0 = inport0_.getData()->getDataFormat()->getPrecision(); auto p1 = inport1_.getData()->getDataFormat()->getPrecision(); auto p2 = inport2_.getData()->getDataFormat()->getPrecision(); DataFormatBase::get(type, 4, std::max({p0, p1, p2})); auto img = std::make_shared<Image>(dimensions, DataVec4UInt8::get()); outport_.setData(img); } utilgl::activateAndClearTarget(outport_); shader_.activate(); TextureUnitContainer units; utilgl::bindAndSetUniforms(shader_, units, inport0_, ImageType::ColorOnly); utilgl::bindAndSetUniforms(shader_, units, inport1_, ImageType::ColorOnly); utilgl::bindAndSetUniforms(shader_, units, inport2_, ImageType::ColorOnly); if (inport3_.hasData()) { utilgl::bindAndSetUniforms(shader_, units, inport3_, ImageType::ColorOnly); } utilgl::setUniforms(shader_, outport_, rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_, alpha_); shader_.setUniform("use_alpha_texture", inport3_.hasData()); utilgl::setUniforms(shader_, outport_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } } // namespace inviwo <commit_msg>BaseGL: minor optimization<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/basegl/processors/imageprocessing/imagechannelcombine.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> namespace inviwo { const ProcessorInfo ImageChannelCombine::processorInfo_{ "org.inviwo.ImageChannelCombine", // Class identifier "Image Channel Combine", // Display name "Image Operation", // Category CodeState::Experimental, // Code state Tags::GL, // Tags }; const ProcessorInfo ImageChannelCombine::getProcessorInfo() const { return processorInfo_; } ImageChannelCombine::ImageChannelCombine() : Processor() , inport0_("inport0", true) , inport1_("inport1", true) , inport2_("inport2", true) , inport3_("inport3", true) , outport_("outport", false) , rChannelSrc_("redChannel", "Red Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , gChannelSrc_("greenChannel", "Green Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , bChannelSrc_("blueChannel", "Blue Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , aChannelSrc_("alphaChannel", "Alpha Channel", {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}}) , alpha_("alpha", "Alpha", 1.0f, 0.0f, 1.0f, 0.001f) , shader_("img_channel_combine.frag") { shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); addPort(inport0_); addPort(inport1_); addPort(inport2_); inport3_.setOptional(true); addPort(inport3_); addPort(outport_); addProperties(rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_, alpha_); } void ImageChannelCombine::process() { auto isSame = [](auto a, auto b, auto c) { if (a != b) return false; if (a != c) return false; return true; }; auto img0 = inport0_.getData(); auto img1 = inport1_.getData(); auto img2 = inport2_.getData(); auto img3 = inport3_.getData(); if (isSame(img0->getDimensions(), img1->getDimensions(), img2->getDimensions()) && (inport3_.isConnected() && img3 && img3->getDimensions() != img0->getDimensions())) { throw Exception("The image dimensions of all inports needs to be the same", IVW_CONTEXT); } if (inport0_.isChanged() || inport1_.isChanged() || inport2_.isChanged()) { const auto dimensions = inport0_.getData()->getDimensions(); auto t1 = inport0_.getData()->getDataFormat()->getNumericType(); auto t2 = inport1_.getData()->getDataFormat()->getNumericType(); auto t3 = inport2_.getData()->getDataFormat()->getNumericType(); NumericType type; if (t1 == t2 && t1 == t3) { // All have the same numType type = t1; } else if (t1 == NumericType::Float || t2 == NumericType::Float || t2 == NumericType::Float) { // At least one is a float type type = NumericType::Float; } else { // At least one are signed, and at least one are unsigned type = NumericType::Float; } auto p0 = inport0_.getData()->getDataFormat()->getPrecision(); auto p1 = inport1_.getData()->getDataFormat()->getPrecision(); auto p2 = inport2_.getData()->getDataFormat()->getPrecision(); DataFormatBase::get(type, 4, std::max({p0, p1, p2})); auto img = std::make_shared<Image>(dimensions, DataVec4UInt8::get()); outport_.setData(img); } utilgl::activateAndClearTarget(outport_); shader_.activate(); TextureUnitContainer units; utilgl::bindAndSetUniforms(shader_, units, inport0_, ImageType::ColorOnly); utilgl::bindAndSetUniforms(shader_, units, inport1_, ImageType::ColorOnly); utilgl::bindAndSetUniforms(shader_, units, inport2_, ImageType::ColorOnly); if (inport3_.hasData()) { utilgl::bindAndSetUniforms(shader_, units, inport3_, ImageType::ColorOnly); } utilgl::setUniforms(shader_, outport_, rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_, alpha_); shader_.setUniform("use_alpha_texture", inport3_.hasData()); utilgl::setUniforms(shader_, outport_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } } // namespace inviwo <|endoftext|>
<commit_before>/* This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Its purpose is to analyse the persistent homology of connectivity matrices. The tool bears some semblance to the *network analysis* tools, but focuses specifically on data sets whose weights are an interpretable correlation measure. */ #include <aleph/persistenceDiagrams/Entropy.hh> #include <aleph/persistenceDiagrams/Norms.hh> #include <aleph/persistenceDiagrams/io/JSON.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/io/AdjacencyMatrix.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/utilities/Filesystem.hh> #include <iostream> #include <map> #include <string> #include <vector> #include <getopt.h> void usage() { std::cerr << "Usage: connectivity_matrix_analysis [--dimension DIMENSION] FILENAMES\n" << "\n" << "Analyses a set of connectivity matrices. The matrices are optionally\n" << "expanded to a pre-defined dimension. By default, only information of\n" << "the zeroth persistent homology group will be shown.\n" << "\n" << "Flags:\n" << " -k: keep & report unpaired simplices (infinite values)\n" << "\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "dimension" , required_argument, nullptr, 'd' }, { "keep-unpaired" , no_argument , nullptr, 'k' }, { nullptr , 0 , nullptr, 0 } }; unsigned dimension = 0; bool keepUnpaired = false; { int option = 0; while( ( option = getopt_long( argc, argv, "d:k", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'd': dimension = static_cast<unsigned>( std::stoul(optarg) ); break; case 'k': keepUnpaired = false; break; } } } if( (argc - optind) < 1 ) { usage(); return -1; } bool verbose = false; using DataType = double; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; std::vector<std::string> filenames; for( int i = optind; i < argc; i++ ) filenames.push_back( argv[i] ); aleph::topology::io::AdjacencyMatrixReader reader; reader.setIgnoreNaNs(); reader.setIgnoreZeroWeights(); // Whew, is there *really* no better way of specifying this strategy // here as a qualified name? reader.setVertexWeightAssignmentStrategy( aleph::topology::io::AdjacencyMatrixReader::VertexWeightAssignmentStrategy::AssignZero ); std::cout << "{\n" << "\"diagrams\": [\n"; for( auto&& filename : filenames ) { if( verbose ) std::cerr << "* Processing " << filename << "..."; SimplicialComplex K; reader( filename, K ); K.sort(); bool dualize = true; bool includeAllUnpairedCreators = keepUnpaired; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); if( verbose ) std::cerr << "finished\n"; auto basename = aleph::utilities::basename( filename ); for( auto&& diagram : diagrams ) { // Stores additional data about each persistence diagram in order // to make it easier to keep track of information. std::map<std::string, std::string> kvs; kvs["total_persistence_1"] = std::to_string( aleph::totalPersistence( diagram, 1.0 ) ); kvs["total_persistence_2"] = std::to_string( aleph::totalPersistence( diagram, 2.0 ) ); kvs["persistent_entropy"] = std::to_string( aleph::persistentEntropy( diagram ) ); aleph::io::writeJSON( std::cout, diagram, basename, kvs ); } } std::cout << "\n" << "]\n" << "}\n"; } <commit_msg>Added option to replace infinite values in the persistence diagram<commit_after>/* This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Its purpose is to analyse the persistent homology of connectivity matrices. The tool bears some semblance to the *network analysis* tools, but focuses specifically on data sets whose weights are an interpretable correlation measure. */ #include <aleph/persistenceDiagrams/Entropy.hh> #include <aleph/persistenceDiagrams/Norms.hh> #include <aleph/persistenceDiagrams/io/JSON.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/io/AdjacencyMatrix.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/utilities/Filesystem.hh> #include <cmath> #include <algorithm> #include <iostream> #include <limits> #include <map> #include <string> #include <vector> #include <getopt.h> void usage() { std::cerr << "Usage: connectivity_matrix_analysis [--dimension DIMENSION] [--infinity INF] FILENAMES\n" << "\n" << "Analyses a set of connectivity matrices. The matrices are optionally\n" << "expanded to a pre-defined dimension. By default, only information of\n" << "the zeroth persistent homology group will be shown.\n" << "\n" << "The value INF will be used to replace infinite values in the diagram\n" << "in order to facilitate the subsequent analysis.\n" << "\n" << "Flags:\n" << " -k: keep & report unpaired simplices (infinite values)\n" << " -v: verbose output\n" << "\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "dimension" , required_argument, nullptr, 'd' }, { "infinity" , required_argument, nullptr, 'i' }, { "keep-unpaired" , no_argument , nullptr, 'k' }, { "verbose" , no_argument , nullptr, 'v' }, { nullptr , 0 , nullptr, 0 } }; unsigned dimension = 0; double infinity = std::numeric_limits<double>::infinity(); bool keepUnpaired = false; bool verbose = false; { int option = 0; while( ( option = getopt_long( argc, argv, "d:i:kv", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'd': dimension = static_cast<unsigned>( std::stoul(optarg) ); break; case 'i': infinity = static_cast<double>( std::stod(optarg) ); break; case 'k': keepUnpaired = false; break; } } } if( (argc - optind) < 1 ) { usage(); return -1; } using DataType = double; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using Point = typename PersistenceDiagram::Point; std::vector<std::string> filenames; for( int i = optind; i < argc; i++ ) filenames.push_back( argv[i] ); aleph::topology::io::AdjacencyMatrixReader reader; reader.setIgnoreNaNs(); reader.setIgnoreZeroWeights(); // Whew, is there *really* no better way of specifying this strategy // here as a qualified name? reader.setVertexWeightAssignmentStrategy( aleph::topology::io::AdjacencyMatrixReader::VertexWeightAssignmentStrategy::AssignZero ); std::cout << "{\n" << "\"diagrams\": [\n"; for( auto&& filename : filenames ) { if( verbose ) std::cerr << "* Processing " << filename << "..."; SimplicialComplex K; reader( filename, K ); K.sort(); bool dualize = true; bool includeAllUnpairedCreators = keepUnpaired; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); if( verbose ) std::cerr << "finished\n"; auto basename = aleph::utilities::basename( filename ); for( auto&& diagram : diagrams ) { if( std::isfinite( infinity ) ) { std::transform( diagram.begin(), diagram.end(), diagram.begin(), [&infinity] ( const Point& p ) { if( p.isUnpaired() ) return Point( p.x(), infinity ); else return Point( p.x(), p.y() ); } ); } // Stores additional data about each persistence diagram in order // to make it easier to keep track of information. std::map<std::string, std::string> kvs; kvs["total_persistence_1"] = std::to_string( aleph::totalPersistence( diagram, 1.0 ) ); kvs["total_persistence_2"] = std::to_string( aleph::totalPersistence( diagram, 2.0 ) ); kvs["persistent_entropy"] = std::to_string( aleph::persistentEntropy( diagram ) ); aleph::io::writeJSON( std::cout, diagram, basename, kvs ); } } std::cout << "\n" << "]\n" << "}\n"; } <|endoftext|>
<commit_before>#include "drawer.hh" #include <cmath> #include <cstring> #include <deque> #include <iostream> #include <fstream> #include <stdexcept> namespace { const std::string svg_preambule( "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" ); struct svg_shape { svg_shape() = default; svg_shape(const svg_shape &) = delete; svg_shape & operator=(const svg_shape &) = delete; virtual void flush(std::ostream & out) = 0; virtual ~svg_shape() { } }; struct svg_circle : public svg_shape { OutputCoord pos; double radius; std::string fill; double stroke_width; std::string stroke; svg_circle(const OutputCoord & pos, double radius, const std::string & fill, double stroke_width, const std::string & stroke) : pos(pos), radius(radius), fill(fill), stroke_width(stroke_width), stroke(stroke) { } virtual void flush(std::ostream & out) { out << "<circle cx='" << pos.x << "' cy='" << pos.y << "' r='" << radius << "' fill='" << fill << "' " "stroke='" << stroke << "' stroke-width='" << stroke_width << "' />\n"; } }; struct svg_rect : public svg_shape { OutputCoord start, size; std::string fill; svg_rect(const OutputCoord & start, const OutputCoord & size, const std::string & fill) : start(start), size(size), fill(fill) { } virtual void flush(std::ostream & out) { out << "<rect x='" << start.x << "' y='" << start.y << "' " "width='" << size.x << "' height='" << size.y << "' fill='" << fill << "' />\n"; } }; struct svg_cbezier : public svg_shape { std::vector<OutputCoord> path; std::string stroke; double width; svg_cbezier(std::vector<OutputCoord> && path, const std::string & stroke, double width) : path(std::move(path)), stroke(stroke), width(width) { } virtual void flush(std::ostream & out) { if (! path.empty()) { out << "<path fill='none' stroke='" << stroke << "' stroke-width='" << width << "' " "d='M"; auto i(path.begin()), i_end(path.end()); out << i->x << ',' << i->y << ' '; ++i; while (i != i_end) { out << "L" << i->x << ',' << i->y << ' '; ++i; } out << "' />\n"; } } }; struct svg_text : public svg_shape { std::string body; OutputCoord pos; double size; svg_text(const std::string & body, const OutputCoord & pos, double size) : body(body), pos(pos), size(size) { } virtual void flush(std::ostream & out) { out << "<text x='" << pos.x << "' y='" << pos.y << "' font-size='" << size << "' font-family='sans-serif'>\n" << body << "\n</text>\n"; } }; } struct Drawer::Impl { std::shared_ptr<Projection> projection_; const OutputCoord canvas_; std::deque<std::shared_ptr<svg_shape>> shapes_; Impl(const OutputCoord & canvas) : canvas_(canvas) { } }; Drawer::Drawer(const OutputCoord & canvas) : imp_(new Impl(canvas)) { std::string background_color("white"); double hx(imp_->canvas_.x / 2.), hy(imp_->canvas_.y / 2.); imp_->shapes_.push_back( std::make_shared<svg_rect>(OutputCoord(-hx, -hy), OutputCoord(imp_->canvas_.x, imp_->canvas_.y), background_color)); } Drawer::~Drawer() { delete imp_; } void Drawer::set_projection(const std::shared_ptr<Projection> & projection) { imp_->projection_ = projection; } void Drawer::store(const char * file) const { std::ofstream of(file); if (! of) throw std::runtime_error("Can't open file '" + std::string(file) + "' for writing " + std::strerror(errno)); of << svg_preambule; double hx(imp_->canvas_.x / 2.), hy(imp_->canvas_.y / 2.); of << "<svg width='" << imp_->canvas_.x << "mm' height='" << imp_->canvas_.y << "mm' " "viewBox='" << -hx << ' ' << -hy << ' ' << imp_->canvas_.x << ' ' << imp_->canvas_.y << "' " "xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"; for (auto shape(imp_->shapes_.begin()), shape_end(imp_->shapes_.end()); shape != shape_end; ++shape) (*shape)->flush(of); of << "</svg>\n"; } void Drawer::draw(const Star & star) { static std::string black("black"); static std::string white("white"); static const double e(exp(1)); double s(2. * exp(-star.vmag_ / e)); OutputCoord coord(imp_->projection_->project(star.pos_)); auto c(std::make_shared<svg_circle>(coord, s, black, .5 * s, white)); imp_->shapes_.push_back(c); // if (star.vmag_ < 4. && ! star.common_name_.empty()) // imp_->board << Lb::Text(-star.pos_.ra + s, star.pos_.dec, star.common_name_, Lb::Fonts::Helvetica, 3.); } void Drawer::draw(const std::vector<ln_equ_posn> & path) { std::vector<OutputCoord> ret; double min(0), max(0); for (auto i(path.begin()), i_end(path.end()); i != i_end; ++i) { auto p(imp_->projection_->project(*i)); if (p.y > max) max = p.y; else if (p.y < min) min = p.y; ret.push_back(p); } std::cout << max << ' ' << min << '\n'; imp_->shapes_.push_back(std::make_shared<svg_cbezier>(std::move(ret), "#888888", 0.1)); } void Drawer::draw(const std::string & body, const ln_equ_posn & pos) { imp_->shapes_.push_back(std::make_shared<svg_text>(body, imp_->projection_->project(pos), 4.)); } <commit_msg>clean up junk<commit_after>#include "drawer.hh" #include <cmath> #include <cstring> #include <deque> #include <fstream> #include <stdexcept> namespace { const std::string svg_preambule( "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" ); struct svg_shape { svg_shape() = default; svg_shape(const svg_shape &) = delete; svg_shape & operator=(const svg_shape &) = delete; virtual void flush(std::ostream & out) = 0; virtual ~svg_shape() { } }; struct svg_circle : public svg_shape { OutputCoord pos; double radius; std::string fill; double stroke_width; std::string stroke; svg_circle(const OutputCoord & pos, double radius, const std::string & fill, double stroke_width, const std::string & stroke) : pos(pos), radius(radius), fill(fill), stroke_width(stroke_width), stroke(stroke) { } virtual void flush(std::ostream & out) { out << "<circle cx='" << pos.x << "' cy='" << pos.y << "' r='" << radius << "' fill='" << fill << "' " "stroke='" << stroke << "' stroke-width='" << stroke_width << "' />\n"; } }; struct svg_rect : public svg_shape { OutputCoord start, size; std::string fill; svg_rect(const OutputCoord & start, const OutputCoord & size, const std::string & fill) : start(start), size(size), fill(fill) { } virtual void flush(std::ostream & out) { out << "<rect x='" << start.x << "' y='" << start.y << "' " "width='" << size.x << "' height='" << size.y << "' fill='" << fill << "' />\n"; } }; struct svg_cbezier : public svg_shape { std::vector<OutputCoord> path; std::string stroke; double width; svg_cbezier(std::vector<OutputCoord> && path, const std::string & stroke, double width) : path(std::move(path)), stroke(stroke), width(width) { } virtual void flush(std::ostream & out) { if (! path.empty()) { out << "<path fill='none' stroke='" << stroke << "' stroke-width='" << width << "' " "d='M"; auto i(path.begin()), i_end(path.end()); out << i->x << ',' << i->y << ' '; ++i; while (i != i_end) { out << "L" << i->x << ',' << i->y << ' '; ++i; } out << "' />\n"; } } }; struct svg_text : public svg_shape { std::string body; OutputCoord pos; double size; svg_text(const std::string & body, const OutputCoord & pos, double size) : body(body), pos(pos), size(size) { } virtual void flush(std::ostream & out) { out << "<text x='" << pos.x << "' y='" << pos.y << "' font-size='" << size << "' font-family='sans-serif'>\n" << body << "\n</text>\n"; } }; } struct Drawer::Impl { std::shared_ptr<Projection> projection_; const OutputCoord canvas_; std::deque<std::shared_ptr<svg_shape>> shapes_; Impl(const OutputCoord & canvas) : canvas_(canvas) { } }; Drawer::Drawer(const OutputCoord & canvas) : imp_(new Impl(canvas)) { std::string background_color("white"); double hx(imp_->canvas_.x / 2.), hy(imp_->canvas_.y / 2.); imp_->shapes_.push_back( std::make_shared<svg_rect>(OutputCoord(-hx, -hy), OutputCoord(imp_->canvas_.x, imp_->canvas_.y), background_color)); } Drawer::~Drawer() { delete imp_; } void Drawer::set_projection(const std::shared_ptr<Projection> & projection) { imp_->projection_ = projection; } void Drawer::store(const char * file) const { std::ofstream of(file); if (! of) throw std::runtime_error("Can't open file '" + std::string(file) + "' for writing " + std::strerror(errno)); of << svg_preambule; double hx(imp_->canvas_.x / 2.), hy(imp_->canvas_.y / 2.); of << "<svg width='" << imp_->canvas_.x << "mm' height='" << imp_->canvas_.y << "mm' " "viewBox='" << -hx << ' ' << -hy << ' ' << imp_->canvas_.x << ' ' << imp_->canvas_.y << "' " "xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"; for (auto shape(imp_->shapes_.begin()), shape_end(imp_->shapes_.end()); shape != shape_end; ++shape) (*shape)->flush(of); of << "</svg>\n"; } void Drawer::draw(const Star & star) { static std::string black("black"); static std::string white("white"); static const double e(exp(1)); double s(2. * exp(-star.vmag_ / e)); OutputCoord coord(imp_->projection_->project(star.pos_)); auto c(std::make_shared<svg_circle>(coord, s, black, .5 * s, white)); imp_->shapes_.push_back(c); // if (star.vmag_ < 4. && ! star.common_name_.empty()) // imp_->board << Lb::Text(-star.pos_.ra + s, star.pos_.dec, star.common_name_, Lb::Fonts::Helvetica, 3.); } void Drawer::draw(const std::vector<ln_equ_posn> & path) { std::vector<OutputCoord> ret; for (auto i(path.begin()), i_end(path.end()); i != i_end; ++i) ret.push_back(imp_->projection_->project(*i)); imp_->shapes_.push_back(std::make_shared<svg_cbezier>(std::move(ret), "#888888", 0.1)); } void Drawer::draw(const std::string & body, const ln_equ_posn & pos) { imp_->shapes_.push_back(std::make_shared<svg_text>(body, imp_->projection_->project(pos), 4.)); } <|endoftext|>
<commit_before>/* Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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 <sstream> #include <algorithm> #include <fstream> #include <sys/stat.h> #include <dirent.h> #include <cstring> #include "Utils.h" using std::stringstream; using std::ifstream; void CWMetric::updateMetrics(string metric, string value) { //Plugin to Plot Cloudwatch Metrics from the EC2 Instance so that as you cans see the training Progress /* static const string executable = "/usr/bin/cw_monitoring.py"; ifstream f(executable.c_str()); if ( f.good()) { stringstream command ; command <<"python "<< executable << " --metric "<< metric << " --value "<< value; std::cout << "Executing "<< command.str()<< std::endl; system(command.str().c_str()); } */ } void CWMetric::updateMetrics(string metric, int value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, unsigned int value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, double value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, size_t value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return find(begin, end, option) != end; } /** * Helper function to return the value of a given argument. If it isn't supplied, errors out. */ string getRequiredArgValue(int argc, char** argv, string flag, string message, void (*usage)()) { if(!cmdOptionExists(argv, argv+argc, flag)) { std::cout << "Error: Missing required argument: " << flag << ": " << message << std::endl; usage(); exit(1); } else { return string(getCmdOption(argv, argv + argc, flag)); } } /** * Helper function to return the value of a given argument. If it isn't supplied, return the defaultValue. */ string getOptionalArgValue(int argc, char** argv, string flag, string defaultValue) { if(!cmdOptionExists(argv, argv+argc, flag)) { return defaultValue; } else { return string(getCmdOption(argv, argv + argc, flag)); } } /** * Returns true if the argument flag is defined/set. */ bool isArgSet(int argc, char** argv, string flag) { return cmdOptionExists(argv, argv+argc, flag); } /* This is an utility function which checks the file actually exist */ bool fileExists(const std::string& fileName) { ifstream stream(fileName); if(stream.good()) { return true; } else { return false; } } /** * Currently we simply use the file extension. Ideally we should use something like the unix * file command to determine specific file type. */ bool isNetCDFfile(const string &filename) { size_t extIndex = filename.find_last_of("."); if (extIndex == string::npos) { return false; } string ext = filename.substr(extIndex); return (ext.compare(NETCDF_FILE_EXTENTION) == 0); } /* This is the splitter which is used to split a string which is used majorly for splitting our data sets */ std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } void forceClearVector(vector<unsigned int> &vectorToClear) { vectorToClear.clear(); vector<unsigned int>(vectorToClear).swap(vectorToClear); } void forceClearVector(vector<float> &vectorToClear) { vectorToClear.clear(); vector<float>(vectorToClear).swap(vectorToClear); } double elapsed_time(timeval x, timeval y) { const int uSecondsInSeconds = 1000000; timeval result; /* Perform the carry for the later subtraction by updating y. */ if (x.tv_usec < y.tv_usec) { int nsec = (y.tv_usec - x.tv_usec) / uSecondsInSeconds + 1; y.tv_usec -= uSecondsInSeconds * nsec; y.tv_sec += nsec; } if (x.tv_usec - y.tv_usec > uSecondsInSeconds) { int nsec = (x.tv_usec - y.tv_usec) / uSecondsInSeconds; y.tv_usec += uSecondsInSeconds * nsec; y.tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result.tv_sec = x.tv_sec - y.tv_sec; result.tv_usec = x.tv_usec - y.tv_usec; return (double) result.tv_sec + ((double) result.tv_usec / (double) uSecondsInSeconds); } bool isDirectory(const string &dirname) { struct stat buf; stat(dirname.c_str(), &buf); return S_ISDIR(buf.st_mode); } bool isFile(const string &filename) { struct stat buf; stat(filename.c_str(), &buf); return S_ISREG(buf.st_mode); } int listFiles(const string &dirname, const bool recursive, vector<string> &files) { if (isFile(dirname)) { files.push_back(dirname); } else if (isDirectory(dirname)) { DIR *dp; struct dirent *dirp; if ((dp = opendir(dirname.data())) != NULL) { string normalizedDirname = (dirname[dirname.length() - 1] != '/') ? dirname + "/" : dirname; while ((dirp = readdir(dp)) != NULL) { char *relativeChildFilePath = dirp->d_name; if (strcmp(relativeChildFilePath, ".") == 0 || strcmp(relativeChildFilePath, "..") == 0) { continue; } string absoluteChildFilePath = normalizedDirname + relativeChildFilePath; if (recursive && isDirectory(absoluteChildFilePath)) { listFiles(absoluteChildFilePath, recursive, files); } else { files.push_back(absoluteChildFilePath); } } } else { std::cerr << "Error(" << errno << ") opening " << dirname << std::endl; return errno; } } else { return 1; } std::sort(files.begin(), files.end()); return 0; } <commit_msg>Fixed resource leak in listFiles(). There was a missing closedir() call.<commit_after>/* Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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 <sstream> #include <algorithm> #include <fstream> #include <sys/stat.h> #include <dirent.h> #include <cstring> #include "Utils.h" using std::stringstream; using std::ifstream; void CWMetric::updateMetrics(string metric, string value) { //Plugin to Plot Cloudwatch Metrics from the EC2 Instance so that as you cans see the training Progress /* static const string executable = "/usr/bin/cw_monitoring.py"; ifstream f(executable.c_str()); if ( f.good()) { stringstream command ; command <<"python "<< executable << " --metric "<< metric << " --value "<< value; std::cout << "Executing "<< command.str()<< std::endl; system(command.str().c_str()); } */ } void CWMetric::updateMetrics(string metric, int value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, unsigned int value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, double value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } void CWMetric::updateMetrics(string metric, size_t value) { stringstream sValue; sValue << value; return CWMetric::updateMetrics(metric, sValue.str()); } char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return find(begin, end, option) != end; } /** * Helper function to return the value of a given argument. If it isn't supplied, errors out. */ string getRequiredArgValue(int argc, char** argv, string flag, string message, void (*usage)()) { if(!cmdOptionExists(argv, argv+argc, flag)) { std::cout << "Error: Missing required argument: " << flag << ": " << message << std::endl; usage(); exit(1); } else { return string(getCmdOption(argv, argv + argc, flag)); } } /** * Helper function to return the value of a given argument. If it isn't supplied, return the defaultValue. */ string getOptionalArgValue(int argc, char** argv, string flag, string defaultValue) { if(!cmdOptionExists(argv, argv+argc, flag)) { return defaultValue; } else { return string(getCmdOption(argv, argv + argc, flag)); } } /** * Returns true if the argument flag is defined/set. */ bool isArgSet(int argc, char** argv, string flag) { return cmdOptionExists(argv, argv+argc, flag); } /* This is an utility function which checks the file actually exist */ bool fileExists(const std::string& fileName) { ifstream stream(fileName); if(stream.good()) { return true; } else { return false; } } /** * Currently we simply use the file extension. Ideally we should use something like the unix * file command to determine specific file type. */ bool isNetCDFfile(const string &filename) { size_t extIndex = filename.find_last_of("."); if (extIndex == string::npos) { return false; } string ext = filename.substr(extIndex); return (ext.compare(NETCDF_FILE_EXTENTION) == 0); } /* This is the splitter which is used to split a string which is used majorly for splitting our data sets */ std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } void forceClearVector(vector<unsigned int> &vectorToClear) { vectorToClear.clear(); vector<unsigned int>(vectorToClear).swap(vectorToClear); } void forceClearVector(vector<float> &vectorToClear) { vectorToClear.clear(); vector<float>(vectorToClear).swap(vectorToClear); } double elapsed_time(timeval x, timeval y) { const int uSecondsInSeconds = 1000000; timeval result; /* Perform the carry for the later subtraction by updating y. */ if (x.tv_usec < y.tv_usec) { int nsec = (y.tv_usec - x.tv_usec) / uSecondsInSeconds + 1; y.tv_usec -= uSecondsInSeconds * nsec; y.tv_sec += nsec; } if (x.tv_usec - y.tv_usec > uSecondsInSeconds) { int nsec = (x.tv_usec - y.tv_usec) / uSecondsInSeconds; y.tv_usec += uSecondsInSeconds * nsec; y.tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result.tv_sec = x.tv_sec - y.tv_sec; result.tv_usec = x.tv_usec - y.tv_usec; return (double) result.tv_sec + ((double) result.tv_usec / (double) uSecondsInSeconds); } bool isDirectory(const string &dirname) { struct stat buf; stat(dirname.c_str(), &buf); return S_ISDIR(buf.st_mode); } bool isFile(const string &filename) { struct stat buf; stat(filename.c_str(), &buf); return S_ISREG(buf.st_mode); } int listFiles(const string &dirname, const bool recursive, vector<string> &files) { if (isFile(dirname)) { files.push_back(dirname); } else if (isDirectory(dirname)) { DIR *dp; struct dirent *dirp; if ((dp = opendir(dirname.data())) != NULL) { string normalizedDirname = (dirname[dirname.length() - 1] != '/') ? dirname + "/" : dirname; while ((dirp = readdir(dp)) != NULL) { char *relativeChildFilePath = dirp->d_name; if (strcmp(relativeChildFilePath, ".") == 0 || strcmp(relativeChildFilePath, "..") == 0) { continue; } string absoluteChildFilePath = normalizedDirname + relativeChildFilePath; if (recursive && isDirectory(absoluteChildFilePath)) { listFiles(absoluteChildFilePath, recursive, files); } else { files.push_back(absoluteChildFilePath); } } closedir(dp); } else { std::cerr << "Error(" << errno << ") opening " << dirname << std::endl; return errno; } } else { return 1; } std::sort(files.begin(), files.end()); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "src/tracing/core/service_impl.h" #include <string.h> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "perfetto/tracing/core/consumer.h" #include "perfetto/tracing/core/data_source_config.h" #include "perfetto/tracing/core/data_source_descriptor.h" #include "perfetto/tracing/core/producer.h" #include "perfetto/tracing/core/shared_memory.h" #include "perfetto/tracing/core/trace_packet.h" #include "src/base/test/test_task_runner.h" #include "src/tracing/test/test_shared_memory.h" namespace perfetto { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Mock; namespace { class MockProducer : public Producer { public: ~MockProducer() override {} // Producer implementation. MOCK_METHOD0(OnConnect, void()); MOCK_METHOD0(OnDisconnect, void()); MOCK_METHOD2(CreateDataSourceInstance, void(DataSourceInstanceID, const DataSourceConfig&)); MOCK_METHOD1(TearDownDataSourceInstance, void(DataSourceInstanceID)); MOCK_METHOD0(OnTracingStart, void()); MOCK_METHOD0(OnTracingStop, void()); }; class MockConsumer : public Consumer { public: ~MockConsumer() override {} // Consumer implementation. MOCK_METHOD0(OnConnect, void()); MOCK_METHOD0(OnDisconnect, void()); void OnTraceData(std::vector<TracePacket> packets, bool has_more) override {} }; } // namespace class ServiceImplTest : public testing::Test { public: ServiceImplTest() { auto shm_factory = std::unique_ptr<SharedMemory::Factory>(new TestSharedMemory::Factory()); svc.reset(static_cast<ServiceImpl*>( Service::CreateInstance(std::move(shm_factory), &task_runner) .release())); } base::TestTaskRunner task_runner; std::unique_ptr<ServiceImpl> svc; }; TEST_F(ServiceImplTest, RegisterAndUnregister) { MockProducer mock_producer_1; MockProducer mock_producer_2; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_1 = svc->ConnectProducer(&mock_producer_1, 123u /* uid */); std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_2 = svc->ConnectProducer(&mock_producer_2, 456u /* uid */); ASSERT_TRUE(producer_endpoint_1); ASSERT_TRUE(producer_endpoint_2); InSequence seq; EXPECT_CALL(mock_producer_1, OnConnect()); EXPECT_CALL(mock_producer_2, OnConnect()); task_runner.RunUntilIdle(); ASSERT_EQ(2u, svc->num_producers()); ASSERT_EQ(producer_endpoint_1.get(), svc->GetProducer(1)); ASSERT_EQ(producer_endpoint_2.get(), svc->GetProducer(2)); ASSERT_EQ(123u, svc->GetProducer(1)->uid_); ASSERT_EQ(456u, svc->GetProducer(2)->uid_); DataSourceDescriptor ds_desc1; ds_desc1.set_name("foo"); producer_endpoint_1->RegisterDataSource( ds_desc1, [this, &producer_endpoint_1](DataSourceID id) { EXPECT_EQ(1u, id); task_runner.PostTask( std::bind(&Service::ProducerEndpoint::UnregisterDataSource, producer_endpoint_1.get(), id)); }); DataSourceDescriptor ds_desc2; ds_desc2.set_name("bar"); producer_endpoint_2->RegisterDataSource( ds_desc2, [this, &producer_endpoint_2](DataSourceID id) { EXPECT_EQ(1u, id); task_runner.PostTask( std::bind(&Service::ProducerEndpoint::UnregisterDataSource, producer_endpoint_2.get(), id)); }); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer_1, OnDisconnect()); producer_endpoint_1.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer_1); ASSERT_EQ(1u, svc->num_producers()); ASSERT_EQ(nullptr, svc->GetProducer(1)); EXPECT_CALL(mock_producer_2, OnDisconnect()); producer_endpoint_2.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer_2); ASSERT_EQ(0u, svc->num_producers()); } TEST_F(ServiceImplTest, EnableAndDisableTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint->DisableTracing(); producer_endpoint.reset(); consumer_endpoint.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, LockdownMode) { MockConsumer mock_consumer; EXPECT_CALL(mock_consumer, OnConnect()); std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); TraceConfig trace_config; trace_config.set_lockdown_mode( TraceConfig::LockdownModeOperation::LOCKDOWN_SET); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); InSequence seq; MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, geteuid() + 1 /* uid */); MockProducer mock_producer_sameuid; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_sameuid = svc->ConnectProducer(&mock_producer_sameuid, geteuid() /* uid */); EXPECT_CALL(mock_producer, OnConnect()).Times(0); EXPECT_CALL(mock_producer_sameuid, OnConnect()); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer); consumer_endpoint->DisableTracing(); task_runner.RunUntilIdle(); trace_config.set_lockdown_mode( TraceConfig::LockdownModeOperation::LOCKDOWN_CLEAR); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnConnect()); producer_endpoint_sameuid = svc->ConnectProducer(&mock_producer, geteuid() + 1); task_runner.RunUntilIdle(); } TEST_F(ServiceImplTest, DisconnectConsumerWhileTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); // Disconnecting the consumer while tracing should trigger data source // teardown. EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint.reset(); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); producer_endpoint.reset(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, ReconnectProducerWhileTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); // Disconnecting the producer while tracing should trigger data source // teardown. EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); EXPECT_CALL(mock_producer, OnDisconnect()); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); producer_endpoint.reset(); task_runner.RunUntilIdle(); // Reconnecting a producer with a matching data source should see that data // source getting enabled. EXPECT_CALL(mock_producer, OnConnect()); producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint->DisableTracing(); consumer_endpoint.reset(); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); producer_endpoint.reset(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, ProducerIDWrapping) { base::TestTaskRunner task_runner; auto shm_factory = std::unique_ptr<SharedMemory::Factory>(new TestSharedMemory::Factory()); std::unique_ptr<ServiceImpl> svc(static_cast<ServiceImpl*>( Service::CreateInstance(std::move(shm_factory), &task_runner).release())); std::map<ProducerID, std::pair<std::unique_ptr<MockProducer>, std::unique_ptr<Service::ProducerEndpoint>>> producers; auto ConnectProducerAndWait = [&task_runner, &svc, &producers]() { char checkpoint_name[32]; static int checkpoint_num = 0; sprintf(checkpoint_name, "on_connect_%d", checkpoint_num++); auto on_connect = task_runner.CreateCheckpoint(checkpoint_name); std::unique_ptr<MockProducer> producer(new MockProducer()); std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(producer.get(), 123u /* uid */); EXPECT_CALL(*producer, OnConnect()).WillOnce(Invoke(on_connect)); task_runner.RunUntilCheckpoint(checkpoint_name); EXPECT_EQ(&*producer_endpoint, svc->GetProducer(svc->last_producer_id_)); const ProducerID pr_id = svc->last_producer_id_; producers.emplace(pr_id, std::make_pair(std::move(producer), std::move(producer_endpoint))); return pr_id; }; auto DisconnectProducerAndWait = [&task_runner, &producers](ProducerID pr_id) { char checkpoint_name[32]; static int checkpoint_num = 0; sprintf(checkpoint_name, "on_disconnect_%d", checkpoint_num++); auto on_disconnect = task_runner.CreateCheckpoint(checkpoint_name); auto it = producers.find(pr_id); PERFETTO_CHECK(it != producers.end()); EXPECT_CALL(*it->second.first, OnDisconnect()) .WillOnce(Invoke(on_disconnect)); producers.erase(pr_id); task_runner.RunUntilCheckpoint(checkpoint_name); }; // Connect producers 1-4. for (ProducerID i = 1; i <= 4; i++) ASSERT_EQ(i, ConnectProducerAndWait()); // Disconnect producers 1,3. DisconnectProducerAndWait(1); DisconnectProducerAndWait(3); svc->last_producer_id_ = kMaxProducerID - 1; ASSERT_EQ(kMaxProducerID, ConnectProducerAndWait()); ASSERT_EQ(1u, ConnectProducerAndWait()); ASSERT_EQ(3u, ConnectProducerAndWait()); ASSERT_EQ(5u, ConnectProducerAndWait()); ASSERT_EQ(6u, ConnectProducerAndWait()); // Disconnect all producers to mute spurious callbacks. DisconnectProducerAndWait(kMaxProducerID); for (ProducerID i = 1; i <= 6; i++) DisconnectProducerAndWait(i); } } // namespace perfetto <commit_msg>perfetto: Silence test logs am: 5afe501b22 am: f44a5629e9<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "src/tracing/core/service_impl.h" #include <string.h> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "perfetto/tracing/core/consumer.h" #include "perfetto/tracing/core/data_source_config.h" #include "perfetto/tracing/core/data_source_descriptor.h" #include "perfetto/tracing/core/producer.h" #include "perfetto/tracing/core/shared_memory.h" #include "perfetto/tracing/core/trace_packet.h" #include "src/base/test/test_task_runner.h" #include "src/tracing/test/test_shared_memory.h" namespace perfetto { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Mock; namespace { class MockProducer : public Producer { public: ~MockProducer() override {} // Producer implementation. MOCK_METHOD0(OnConnect, void()); MOCK_METHOD0(OnDisconnect, void()); MOCK_METHOD2(CreateDataSourceInstance, void(DataSourceInstanceID, const DataSourceConfig&)); MOCK_METHOD1(TearDownDataSourceInstance, void(DataSourceInstanceID)); MOCK_METHOD0(OnTracingStart, void()); MOCK_METHOD0(OnTracingStop, void()); }; class MockConsumer : public Consumer { public: ~MockConsumer() override {} // Consumer implementation. MOCK_METHOD0(OnConnect, void()); MOCK_METHOD0(OnDisconnect, void()); void OnTraceData(std::vector<TracePacket> packets, bool has_more) override {} }; } // namespace class ServiceImplTest : public testing::Test { public: ServiceImplTest() { auto shm_factory = std::unique_ptr<SharedMemory::Factory>(new TestSharedMemory::Factory()); svc.reset(static_cast<ServiceImpl*>( Service::CreateInstance(std::move(shm_factory), &task_runner) .release())); } base::TestTaskRunner task_runner; std::unique_ptr<ServiceImpl> svc; }; TEST_F(ServiceImplTest, RegisterAndUnregister) { MockProducer mock_producer_1; MockProducer mock_producer_2; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_1 = svc->ConnectProducer(&mock_producer_1, 123u /* uid */); std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_2 = svc->ConnectProducer(&mock_producer_2, 456u /* uid */); ASSERT_TRUE(producer_endpoint_1); ASSERT_TRUE(producer_endpoint_2); InSequence seq; EXPECT_CALL(mock_producer_1, OnConnect()); EXPECT_CALL(mock_producer_2, OnConnect()); task_runner.RunUntilIdle(); ASSERT_EQ(2u, svc->num_producers()); ASSERT_EQ(producer_endpoint_1.get(), svc->GetProducer(1)); ASSERT_EQ(producer_endpoint_2.get(), svc->GetProducer(2)); ASSERT_EQ(123u, svc->GetProducer(1)->uid_); ASSERT_EQ(456u, svc->GetProducer(2)->uid_); DataSourceDescriptor ds_desc1; ds_desc1.set_name("foo"); producer_endpoint_1->RegisterDataSource( ds_desc1, [this, &producer_endpoint_1](DataSourceID id) { EXPECT_EQ(1u, id); task_runner.PostTask( std::bind(&Service::ProducerEndpoint::UnregisterDataSource, producer_endpoint_1.get(), id)); }); DataSourceDescriptor ds_desc2; ds_desc2.set_name("bar"); producer_endpoint_2->RegisterDataSource( ds_desc2, [this, &producer_endpoint_2](DataSourceID id) { EXPECT_EQ(1u, id); task_runner.PostTask( std::bind(&Service::ProducerEndpoint::UnregisterDataSource, producer_endpoint_2.get(), id)); }); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer_1, OnDisconnect()); producer_endpoint_1.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer_1); ASSERT_EQ(1u, svc->num_producers()); ASSERT_EQ(nullptr, svc->GetProducer(1)); EXPECT_CALL(mock_producer_2, OnDisconnect()); producer_endpoint_2.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer_2); ASSERT_EQ(0u, svc->num_producers()); } TEST_F(ServiceImplTest, EnableAndDisableTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint->DisableTracing(); producer_endpoint.reset(); consumer_endpoint.reset(); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, LockdownMode) { MockConsumer mock_consumer; EXPECT_CALL(mock_consumer, OnConnect()); std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); TraceConfig trace_config; trace_config.set_lockdown_mode( TraceConfig::LockdownModeOperation::LOCKDOWN_SET); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); InSequence seq; MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, geteuid() + 1 /* uid */); MockProducer mock_producer_sameuid; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint_sameuid = svc->ConnectProducer(&mock_producer_sameuid, geteuid() /* uid */); EXPECT_CALL(mock_producer, OnConnect()).Times(0); EXPECT_CALL(mock_producer_sameuid, OnConnect()); task_runner.RunUntilIdle(); Mock::VerifyAndClearExpectations(&mock_producer); consumer_endpoint->DisableTracing(); task_runner.RunUntilIdle(); trace_config.set_lockdown_mode( TraceConfig::LockdownModeOperation::LOCKDOWN_CLEAR); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer_sameuid, OnDisconnect()); EXPECT_CALL(mock_producer, OnConnect()); producer_endpoint_sameuid = svc->ConnectProducer(&mock_producer, geteuid() + 1); EXPECT_CALL(mock_producer, OnDisconnect()); task_runner.RunUntilIdle(); } TEST_F(ServiceImplTest, DisconnectConsumerWhileTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); // Disconnecting the consumer while tracing should trigger data source // teardown. EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); task_runner.RunUntilIdle(); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint.reset(); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); producer_endpoint.reset(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, ReconnectProducerWhileTracing) { MockProducer mock_producer; std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); MockConsumer mock_consumer; std::unique_ptr<Service::ConsumerEndpoint> consumer_endpoint = svc->ConnectConsumer(&mock_consumer); InSequence seq; EXPECT_CALL(mock_producer, OnConnect()); EXPECT_CALL(mock_consumer, OnConnect()); task_runner.RunUntilIdle(); DataSourceDescriptor ds_desc; ds_desc.set_name("foo"); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); // Disconnecting the producer while tracing should trigger data source // teardown. EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); EXPECT_CALL(mock_producer, OnDisconnect()); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(4096 * 10); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("foo"); ds_config->set_target_buffer(0); consumer_endpoint->EnableTracing(trace_config); producer_endpoint.reset(); task_runner.RunUntilIdle(); // Reconnecting a producer with a matching data source should see that data // source getting enabled. EXPECT_CALL(mock_producer, OnConnect()); producer_endpoint = svc->ConnectProducer(&mock_producer, 123u /* uid */); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, CreateDataSourceInstance(_, _)); EXPECT_CALL(mock_producer, TearDownDataSourceInstance(_)); producer_endpoint->RegisterDataSource(ds_desc, [](DataSourceID) {}); task_runner.RunUntilIdle(); EXPECT_CALL(mock_consumer, OnDisconnect()); consumer_endpoint->DisableTracing(); consumer_endpoint.reset(); task_runner.RunUntilIdle(); EXPECT_CALL(mock_producer, OnDisconnect()); producer_endpoint.reset(); Mock::VerifyAndClearExpectations(&mock_producer); Mock::VerifyAndClearExpectations(&mock_consumer); } TEST_F(ServiceImplTest, ProducerIDWrapping) { base::TestTaskRunner task_runner; auto shm_factory = std::unique_ptr<SharedMemory::Factory>(new TestSharedMemory::Factory()); std::unique_ptr<ServiceImpl> svc(static_cast<ServiceImpl*>( Service::CreateInstance(std::move(shm_factory), &task_runner).release())); std::map<ProducerID, std::pair<std::unique_ptr<MockProducer>, std::unique_ptr<Service::ProducerEndpoint>>> producers; auto ConnectProducerAndWait = [&task_runner, &svc, &producers]() { char checkpoint_name[32]; static int checkpoint_num = 0; sprintf(checkpoint_name, "on_connect_%d", checkpoint_num++); auto on_connect = task_runner.CreateCheckpoint(checkpoint_name); std::unique_ptr<MockProducer> producer(new MockProducer()); std::unique_ptr<Service::ProducerEndpoint> producer_endpoint = svc->ConnectProducer(producer.get(), 123u /* uid */); EXPECT_CALL(*producer, OnConnect()).WillOnce(Invoke(on_connect)); task_runner.RunUntilCheckpoint(checkpoint_name); EXPECT_EQ(&*producer_endpoint, svc->GetProducer(svc->last_producer_id_)); const ProducerID pr_id = svc->last_producer_id_; producers.emplace(pr_id, std::make_pair(std::move(producer), std::move(producer_endpoint))); return pr_id; }; auto DisconnectProducerAndWait = [&task_runner, &producers](ProducerID pr_id) { char checkpoint_name[32]; static int checkpoint_num = 0; sprintf(checkpoint_name, "on_disconnect_%d", checkpoint_num++); auto on_disconnect = task_runner.CreateCheckpoint(checkpoint_name); auto it = producers.find(pr_id); PERFETTO_CHECK(it != producers.end()); EXPECT_CALL(*it->second.first, OnDisconnect()) .WillOnce(Invoke(on_disconnect)); producers.erase(pr_id); task_runner.RunUntilCheckpoint(checkpoint_name); }; // Connect producers 1-4. for (ProducerID i = 1; i <= 4; i++) ASSERT_EQ(i, ConnectProducerAndWait()); // Disconnect producers 1,3. DisconnectProducerAndWait(1); DisconnectProducerAndWait(3); svc->last_producer_id_ = kMaxProducerID - 1; ASSERT_EQ(kMaxProducerID, ConnectProducerAndWait()); ASSERT_EQ(1u, ConnectProducerAndWait()); ASSERT_EQ(3u, ConnectProducerAndWait()); ASSERT_EQ(5u, ConnectProducerAndWait()); ASSERT_EQ(6u, ConnectProducerAndWait()); // Disconnect all producers to mute spurious callbacks. DisconnectProducerAndWait(kMaxProducerID); for (ProducerID i = 1; i <= 6; i++) DisconnectProducerAndWait(i); } } // namespace perfetto <|endoftext|>
<commit_before>//===-- llvm-diff.cpp - Module comparator command-line driver ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the command-line driver for the difference engine. // //===----------------------------------------------------------------------===// #include "DifferenceEngine.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SourceMgr.h" #include <string> #include <utility> using namespace llvm; /// Reads a module from a file. If the filename ends in .ll, it is /// interpreted as an assembly file; otherwise, it is interpreted as /// bitcode. On error, messages are written to stderr and null is /// returned. static Module *ReadModule(LLVMContext &Context, StringRef Name) { // LLVM assembly path. if (Name.endswith(".ll")) { SMDiagnostic Diag; Module *M = ParseAssemblyFile(Name, Diag, Context); if (M) return M; Diag.Print("llvmdiff", errs()); return 0; } // Bitcode path. MemoryBuffer *Buffer = MemoryBuffer::getFile(Name); // ParseBitcodeFile takes ownership of the buffer if it succeeds. std::string Error; Module *M = ParseBitcodeFile(Buffer, Context, &Error); if (M) return M; errs() << "error parsing " << Name << ": " << Error; delete Buffer; return 0; } namespace { struct DiffContext { DiffContext(Value *L, Value *R) : L(L), R(R), Differences(false), IsFunction(isa<Function>(L)) {} Value *L; Value *R; bool Differences; bool IsFunction; DenseMap<Value*,unsigned> LNumbering; DenseMap<Value*,unsigned> RNumbering; }; void ComputeNumbering(Function *F, DenseMap<Value*,unsigned> &Numbering) { unsigned BBN = 0; unsigned IN = 0; // Arguments get the first numbers. for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end(); AI != AE; ++AI) if (!AI->hasName()) Numbering[&*AI] = IN++; // Walk the basic blocks in order. for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) { // Basic blocks have their own 'namespace'. if (!FI->hasName()) Numbering[&*FI] = BBN++; // Walk the instructions in order. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) // void instructions don't get numbers. if (!BI->hasName() && !BI->getType()->isVoidTy()) Numbering[&*BI] = IN++; } assert(!Numbering.empty() && "asked for numbering but numbering was no-op"); } class DiffConsumer : public DifferenceEngine::Consumer { private: raw_ostream &out; Module *LModule; Module *RModule; SmallVector<DiffContext, 5> contexts; bool Differences; unsigned Indent; void printValue(Value *V, bool isL) { if (V->hasName()) { out << (isa<GlobalValue>(V) ? '@' : '%') << V->getName(); return; } if (V->getType()->isVoidTy()) { if (isa<StoreInst>(V)) { out << "store to "; printValue(cast<StoreInst>(V)->getPointerOperand(), isL); } else if (isa<CallInst>(V)) { out << "call to "; printValue(cast<CallInst>(V)->getCalledValue(), isL); } else if (isa<InvokeInst>(V)) { out << "invoke to "; printValue(cast<InvokeInst>(V)->getCalledValue(), isL); } else { out << *V; } return; } unsigned N = contexts.size(); while (N > 0) { --N; DiffContext &ctxt = contexts[N]; if (!ctxt.IsFunction) continue; if (isL) { if (ctxt.LNumbering.empty()) ComputeNumbering(cast<Function>(ctxt.L), ctxt.LNumbering); out << '%' << ctxt.LNumbering[V]; return; } else { if (ctxt.RNumbering.empty()) ComputeNumbering(cast<Function>(ctxt.R), ctxt.RNumbering); out << '%' << ctxt.RNumbering[V]; return; } } out << "<anonymous>"; } void header() { if (contexts.empty()) return; for (SmallVectorImpl<DiffContext>::iterator I = contexts.begin(), E = contexts.end(); I != E; ++I) { if (I->Differences) continue; if (isa<Function>(I->L)) { // Extra newline between functions. if (Differences) out << "\n"; Function *L = cast<Function>(I->L); Function *R = cast<Function>(I->R); if (L->getName() != R->getName()) out << "in function " << L->getName() << " / " << R->getName() << ":\n"; else out << "in function " << L->getName() << ":\n"; } else if (isa<BasicBlock>(I->L)) { BasicBlock *L = cast<BasicBlock>(I->L); BasicBlock *R = cast<BasicBlock>(I->R); out << " in block "; printValue(L, true); out << " / "; printValue(R, false); out << ":\n"; } else if (isa<Instruction>(I->L)) { out << " in instruction "; printValue(I->L, true); out << " / "; printValue(I->R, false); out << ":\n"; } I->Differences = true; } } void indent() { unsigned N = Indent; while (N--) out << ' '; } public: DiffConsumer(Module *L, Module *R) : out(errs()), LModule(L), RModule(R), Differences(false), Indent(0) {} bool hadDifferences() const { return Differences; } void enterContext(Value *L, Value *R) { contexts.push_back(DiffContext(L, R)); Indent += 2; } void exitContext() { Differences |= contexts.back().Differences; contexts.pop_back(); Indent -= 2; } void log(StringRef text) { header(); indent(); out << text << '\n'; } void logf(const DifferenceEngine::LogBuilder &Log) { header(); indent(); unsigned arg = 0; StringRef format = Log.getFormat(); while (true) { size_t percent = format.find('%'); if (percent == StringRef::npos) { out << format; break; } assert(format[percent] == '%'); if (percent > 0) out << format.substr(0, percent); switch (format[percent+1]) { case '%': out << '%'; break; case 'l': printValue(Log.getArgument(arg++), true); break; case 'r': printValue(Log.getArgument(arg++), false); break; default: llvm_unreachable("unknown format character"); } format = format.substr(percent+2); } out << '\n'; } void logd(const DifferenceEngine::DiffLogBuilder &Log) { header(); for (unsigned I = 0, E = Log.getNumLines(); I != E; ++I) { indent(); switch (Log.getLineKind(I)) { case DifferenceEngine::DC_match: out << " "; Log.getLeft(I)->dump(); //printValue(Log.getLeft(I), true); break; case DifferenceEngine::DC_left: out << "< "; Log.getLeft(I)->dump(); //printValue(Log.getLeft(I), true); break; case DifferenceEngine::DC_right: out << "> "; Log.getRight(I)->dump(); //printValue(Log.getRight(I), false); break; } //out << "\n"; } } }; } static void diffGlobal(DifferenceEngine &Engine, Module *L, Module *R, StringRef Name) { // Drop leading sigils from the global name. if (Name.startswith("@")) Name = Name.substr(1); Function *LFn = L->getFunction(Name); Function *RFn = R->getFunction(Name); if (LFn && RFn) Engine.diff(LFn, RFn); else if (!LFn && !RFn) errs() << "No function named @" << Name << " in either module\n"; else if (!LFn) errs() << "No function named @" << Name << " in left module\n"; else errs() << "No function named @" << Name << " in right module\n"; } cl::opt<std::string> LeftFilename(cl::Positional, cl::desc("<first file>"), cl::Required); cl::opt<std::string> RightFilename(cl::Positional, cl::desc("<second file>"), cl::Required); cl::list<std::string> GlobalsToCompare(cl::Positional, cl::desc("<globals to compare>")); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); LLVMContext Context; // Load both modules. Die if that fails. Module *LModule = ReadModule(Context, LeftFilename); Module *RModule = ReadModule(Context, RightFilename); if (!LModule || !RModule) return 1; DiffConsumer Consumer(LModule, RModule); DifferenceEngine Engine(Context, Consumer); // If any global names were given, just diff those. if (!GlobalsToCompare.empty()) { for (unsigned I = 0, E = GlobalsToCompare.size(); I != E; ++I) diffGlobal(Engine, LModule, RModule, GlobalsToCompare[I]); // Otherwise, diff everything in the module. } else { Engine.diff(LModule, RModule); } delete LModule; delete RModule; return Consumer.hadDifferences(); } <commit_msg>Transcribe IRC to svn. Also don't print basic block names twice if they match.<commit_after>//===-- llvm-diff.cpp - Module comparator command-line driver ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the command-line driver for the difference engine. // //===----------------------------------------------------------------------===// #include "DifferenceEngine.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SourceMgr.h" #include <string> #include <utility> using namespace llvm; /// Reads a module from a file. If the filename ends in .ll, it is /// interpreted as an assembly file; otherwise, it is interpreted as /// bitcode. On error, messages are written to stderr and null is /// returned. static Module *ReadModule(LLVMContext &Context, StringRef Name) { // LLVM assembly path. if (Name.endswith(".ll")) { SMDiagnostic Diag; Module *M = ParseAssemblyFile(Name, Diag, Context); if (M) return M; Diag.Print("llvmdiff", errs()); return 0; } // Bitcode path. MemoryBuffer *Buffer = MemoryBuffer::getFile(Name); // ParseBitcodeFile takes ownership of the buffer if it succeeds. std::string Error; Module *M = ParseBitcodeFile(Buffer, Context, &Error); if (M) return M; errs() << "error parsing " << Name << ": " << Error; delete Buffer; return 0; } namespace { struct DiffContext { DiffContext(Value *L, Value *R) : L(L), R(R), Differences(false), IsFunction(isa<Function>(L)) {} Value *L; Value *R; bool Differences; bool IsFunction; DenseMap<Value*,unsigned> LNumbering; DenseMap<Value*,unsigned> RNumbering; }; void ComputeNumbering(Function *F, DenseMap<Value*,unsigned> &Numbering) { unsigned BBN = 0; unsigned IN = 0; // Arguments get the first numbers. for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end(); AI != AE; ++AI) if (!AI->hasName()) Numbering[&*AI] = IN++; // Walk the basic blocks in order. for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) { // Basic blocks have their own 'namespace'. if (!FI->hasName()) Numbering[&*FI] = BBN++; // Walk the instructions in order. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) // void instructions don't get numbers. if (!BI->hasName() && !BI->getType()->isVoidTy()) Numbering[&*BI] = IN++; } assert(!Numbering.empty() && "asked for numbering but numbering was no-op"); } class DiffConsumer : public DifferenceEngine::Consumer { private: raw_ostream &out; Module *LModule; Module *RModule; SmallVector<DiffContext, 5> contexts; bool Differences; unsigned Indent; void printValue(Value *V, bool isL) { if (V->hasName()) { out << (isa<GlobalValue>(V) ? '@' : '%') << V->getName(); return; } if (V->getType()->isVoidTy()) { if (isa<StoreInst>(V)) { out << "store to "; printValue(cast<StoreInst>(V)->getPointerOperand(), isL); } else if (isa<CallInst>(V)) { out << "call to "; printValue(cast<CallInst>(V)->getCalledValue(), isL); } else if (isa<InvokeInst>(V)) { out << "invoke to "; printValue(cast<InvokeInst>(V)->getCalledValue(), isL); } else { out << *V; } return; } unsigned N = contexts.size(); while (N > 0) { --N; DiffContext &ctxt = contexts[N]; if (!ctxt.IsFunction) continue; if (isL) { if (ctxt.LNumbering.empty()) ComputeNumbering(cast<Function>(ctxt.L), ctxt.LNumbering); out << '%' << ctxt.LNumbering[V]; return; } else { if (ctxt.RNumbering.empty()) ComputeNumbering(cast<Function>(ctxt.R), ctxt.RNumbering); out << '%' << ctxt.RNumbering[V]; return; } } out << "<anonymous>"; } void header() { if (contexts.empty()) return; for (SmallVectorImpl<DiffContext>::iterator I = contexts.begin(), E = contexts.end(); I != E; ++I) { if (I->Differences) continue; if (isa<Function>(I->L)) { // Extra newline between functions. if (Differences) out << "\n"; Function *L = cast<Function>(I->L); Function *R = cast<Function>(I->R); if (L->getName() != R->getName()) out << "in function " << L->getName() << " / " << R->getName() << ":\n"; else out << "in function " << L->getName() << ":\n"; } else if (isa<BasicBlock>(I->L)) { BasicBlock *L = cast<BasicBlock>(I->L); BasicBlock *R = cast<BasicBlock>(I->R); if (L->hasName() && R->hasName() && L->getName() == R->getName()) out << " in block %" << L->getName() << ":\n"; else { out << " in block "; printValue(L, true); out << " / "; printValue(R, false); out << ":\n"; } } else if (isa<Instruction>(I->L)) { out << " in instruction "; printValue(I->L, true); out << " / "; printValue(I->R, false); out << ":\n"; } I->Differences = true; } } void indent() { unsigned N = Indent; while (N--) out << ' '; } public: DiffConsumer(Module *L, Module *R) : out(errs()), LModule(L), RModule(R), Differences(false), Indent(0) {} bool hadDifferences() const { return Differences; } void enterContext(Value *L, Value *R) { contexts.push_back(DiffContext(L, R)); Indent += 2; } void exitContext() { Differences |= contexts.back().Differences; contexts.pop_back(); Indent -= 2; } void log(StringRef text) { header(); indent(); out << text << '\n'; } void logf(const DifferenceEngine::LogBuilder &Log) { header(); indent(); unsigned arg = 0; StringRef format = Log.getFormat(); while (true) { size_t percent = format.find('%'); if (percent == StringRef::npos) { out << format; break; } assert(format[percent] == '%'); if (percent > 0) out << format.substr(0, percent); switch (format[percent+1]) { case '%': out << '%'; break; case 'l': printValue(Log.getArgument(arg++), true); break; case 'r': printValue(Log.getArgument(arg++), false); break; default: llvm_unreachable("unknown format character"); } format = format.substr(percent+2); } out << '\n'; } void logd(const DifferenceEngine::DiffLogBuilder &Log) { header(); for (unsigned I = 0, E = Log.getNumLines(); I != E; ++I) { indent(); switch (Log.getLineKind(I)) { case DifferenceEngine::DC_match: out << " "; Log.getLeft(I)->dump(); //printValue(Log.getLeft(I), true); break; case DifferenceEngine::DC_left: out << "< "; Log.getLeft(I)->dump(); //printValue(Log.getLeft(I), true); break; case DifferenceEngine::DC_right: out << "> "; Log.getRight(I)->dump(); //printValue(Log.getRight(I), false); break; } //out << "\n"; } } }; } static void diffGlobal(DifferenceEngine &Engine, Module *L, Module *R, StringRef Name) { // Drop leading sigils from the global name. if (Name.startswith("@")) Name = Name.substr(1); Function *LFn = L->getFunction(Name); Function *RFn = R->getFunction(Name); if (LFn && RFn) Engine.diff(LFn, RFn); else if (!LFn && !RFn) errs() << "No function named @" << Name << " in either module\n"; else if (!LFn) errs() << "No function named @" << Name << " in left module\n"; else errs() << "No function named @" << Name << " in right module\n"; } cl::opt<std::string> LeftFilename(cl::Positional, cl::desc("<first file>"), cl::Required); cl::opt<std::string> RightFilename(cl::Positional, cl::desc("<second file>"), cl::Required); cl::list<std::string> GlobalsToCompare(cl::Positional, cl::desc("<globals to compare>")); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); LLVMContext Context; // Load both modules. Die if that fails. Module *LModule = ReadModule(Context, LeftFilename); Module *RModule = ReadModule(Context, RightFilename); if (!LModule || !RModule) return 1; DiffConsumer Consumer(LModule, RModule); DifferenceEngine Engine(Context, Consumer); // If any global names were given, just diff those. if (!GlobalsToCompare.empty()) { for (unsigned I = 0, E = GlobalsToCompare.size(); I != E; ++I) diffGlobal(Engine, LModule, RModule, GlobalsToCompare[I]); // Otherwise, diff everything in the module. } else { Engine.diff(LModule, RModule); } delete LModule; delete RModule; return Consumer.hadDifferences(); } <|endoftext|>
<commit_before>//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes in a list of bitcode files, links them and performs // link-time optimization according to the provided symbol resolutions using the // resolution-based LTO interface, and outputs one or more object files. // // This program is intended to eventually replace llvm-lto which uses the legacy // LTO interface. // //===----------------------------------------------------------------------===// #include "llvm/LTO/Caching.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/LTO/LTO.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Threading.h" using namespace llvm; using namespace lto; using namespace object; static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init('2')); static cl::opt<char> CGOptLevel( "cg-opt-level", cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"), cl::init('2')); static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::Required, cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"), cl::value_desc("directory")); static cl::opt<std::string> OptPipeline("opt-pipeline", cl::desc("Optimizer Pipeline"), cl::value_desc("pipeline")); static cl::opt<std::string> AAPipeline("aa-pipeline", cl::desc("Alias Analysis Pipeline"), cl::value_desc("aapipeline")); static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files")); static cl::opt<bool> ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false), cl::desc("Write out individual index and " "import files for the " "distributed backend case")); static cl::opt<int> Threads("-thinlto-threads", cl::init(llvm::heavyweight_hardware_concurrency())); static cl::list<std::string> SymbolResolutions( "r", cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n" "where \"resolution\" is a sequence (which may be empty) of the\n" "following characters:\n" " p - prevailing: the linker has chosen this definition of the\n" " symbol\n" " l - local: the definition of this symbol is unpreemptable at\n" " runtime and is known to be in this linkage unit\n" " x - externally visible: the definition of this symbol is\n" " visible outside of the LTO unit\n" "A resolution for each symbol must be specified."), cl::ZeroOrMore); static cl::opt<std::string> OverrideTriple( "override-triple", cl::desc("Replace target triples in input files with this triple")); static cl::opt<std::string> DefaultTriple( "default-triple", cl::desc( "Replace unspecified target triples in input files with this triple")); static void check(Error E, std::string Msg) { if (!E) return; handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n'; }); exit(1); } template <typename T> static T check(Expected<T> E, std::string Msg) { if (E) return std::move(*E); check(E.takeError(), Msg); return T(); } static void check(std::error_code EC, std::string Msg) { check(errorCodeToError(EC), Msg); } template <typename T> static T check(ErrorOr<T> E, std::string Msg) { if (E) return std::move(*E); check(E.getError(), Msg); return T(); } int main(int argc, char **argv) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness"); // FIXME: Workaround PR30396 which means that a symbol can appear // more than once if it is defined in module-level assembly and // has a GV declaration. We allow (file, symbol) pairs to have multiple // resolutions and apply them in the order observed. std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>> CommandLineResolutions; for (std::string R : SymbolResolutions) { StringRef Rest = R; StringRef FileName, SymbolName; std::tie(FileName, Rest) = Rest.split(','); if (Rest.empty()) { llvm::errs() << "invalid resolution: " << R << '\n'; return 1; } std::tie(SymbolName, Rest) = Rest.split(','); SymbolResolution Res; for (char C : Rest) { if (C == 'p') Res.Prevailing = true; else if (C == 'l') Res.FinalDefinitionInLinkageUnit = true; else if (C == 'x') Res.VisibleToRegularObj = true; else llvm::errs() << "invalid character " << C << " in resolution: " << R << '\n'; } CommandLineResolutions[{FileName, SymbolName}].push_back(Res); } std::vector<std::unique_ptr<MemoryBuffer>> MBs; Config Conf; Conf.DiagHandler = [](const DiagnosticInfo &) { exit(1); }; Conf.CPU = MCPU; Conf.Options = InitTargetOptionsFromCodeGenFlags(); Conf.MAttrs = MAttrs; if (auto RM = getRelocModel()) Conf.RelocModel = *RM; Conf.CodeModel = CMModel; if (SaveTemps) check(Conf.addSaveTemps(OutputFilename + "."), "Config::addSaveTemps failed"); // Run a custom pipeline, if asked for. Conf.OptPipeline = OptPipeline; Conf.AAPipeline = AAPipeline; Conf.OptLevel = OptLevel - '0'; switch (CGOptLevel) { case '0': Conf.CGOptLevel = CodeGenOpt::None; break; case '1': Conf.CGOptLevel = CodeGenOpt::Less; break; case '2': Conf.CGOptLevel = CodeGenOpt::Default; break; case '3': Conf.CGOptLevel = CodeGenOpt::Aggressive; break; default: llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n'; return 1; } Conf.OverrideTriple = OverrideTriple; Conf.DefaultTriple = DefaultTriple; ThinBackend Backend; if (ThinLTODistributedIndexes) Backend = createWriteIndexesThinBackend("", "", true, ""); else Backend = createInProcessThinBackend(Threads); LTO Lto(std::move(Conf), std::move(Backend)); bool HasErrors = false; for (std::string F : InputFilenames) { std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); std::unique_ptr<InputFile> Input = check(InputFile::create(MB->getMemBufferRef()), F); std::vector<SymbolResolution> Res; for (const InputFile::Symbol &Sym : Input->symbols()) { auto I = CommandLineResolutions.find({F, Sym.getName()}); if (I == CommandLineResolutions.end()) { llvm::errs() << argv[0] << ": missing symbol resolution for " << F << ',' << Sym.getName() << '\n'; HasErrors = true; } else { Res.push_back(I->second.front()); I->second.pop_front(); if (I->second.empty()) CommandLineResolutions.erase(I); } } if (HasErrors) continue; MBs.push_back(std::move(MB)); check(Lto.add(std::move(Input), Res), F); } if (!CommandLineResolutions.empty()) { HasErrors = true; for (auto UnusedRes : CommandLineResolutions) llvm::errs() << argv[0] << ": unused symbol resolution for " << UnusedRes.first.first << ',' << UnusedRes.first.second << '\n'; } if (HasErrors) return 1; auto AddStream = [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> { std::string Path = OutputFilename + "." + utostr(Task); std::error_code EC; auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None); check(EC, Path); return llvm::make_unique<lto::NativeObjectStream>(std::move(S)); }; auto AddFile = [&](size_t Task, StringRef Path) { auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path); if (auto EC = ReloadedBufferOrErr.getError()) report_fatal_error(Twine("Can't reload cached file '") + Path + "': " + EC.message() + "\n"); *AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer(); }; NativeObjectCache Cache; if (!CacheDir.empty()) Cache = localCache(CacheDir, AddFile); check(Lto.run(AddStream, Cache), "LTO::run failed"); } <commit_msg>llvm-lto2: Print diagnostics before exiting (NFC)<commit_after>//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes in a list of bitcode files, links them and performs // link-time optimization according to the provided symbol resolutions using the // resolution-based LTO interface, and outputs one or more object files. // // This program is intended to eventually replace llvm-lto which uses the legacy // LTO interface. // //===----------------------------------------------------------------------===// #include "llvm/LTO/Caching.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/LTO/LTO.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Threading.h" using namespace llvm; using namespace lto; using namespace object; static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init('2')); static cl::opt<char> CGOptLevel( "cg-opt-level", cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"), cl::init('2')); static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::Required, cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"), cl::value_desc("directory")); static cl::opt<std::string> OptPipeline("opt-pipeline", cl::desc("Optimizer Pipeline"), cl::value_desc("pipeline")); static cl::opt<std::string> AAPipeline("aa-pipeline", cl::desc("Alias Analysis Pipeline"), cl::value_desc("aapipeline")); static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files")); static cl::opt<bool> ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false), cl::desc("Write out individual index and " "import files for the " "distributed backend case")); static cl::opt<int> Threads("-thinlto-threads", cl::init(llvm::heavyweight_hardware_concurrency())); static cl::list<std::string> SymbolResolutions( "r", cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n" "where \"resolution\" is a sequence (which may be empty) of the\n" "following characters:\n" " p - prevailing: the linker has chosen this definition of the\n" " symbol\n" " l - local: the definition of this symbol is unpreemptable at\n" " runtime and is known to be in this linkage unit\n" " x - externally visible: the definition of this symbol is\n" " visible outside of the LTO unit\n" "A resolution for each symbol must be specified."), cl::ZeroOrMore); static cl::opt<std::string> OverrideTriple( "override-triple", cl::desc("Replace target triples in input files with this triple")); static cl::opt<std::string> DefaultTriple( "default-triple", cl::desc( "Replace unspecified target triples in input files with this triple")); static void check(Error E, std::string Msg) { if (!E) return; handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n'; }); exit(1); } template <typename T> static T check(Expected<T> E, std::string Msg) { if (E) return std::move(*E); check(E.takeError(), Msg); return T(); } static void check(std::error_code EC, std::string Msg) { check(errorCodeToError(EC), Msg); } template <typename T> static T check(ErrorOr<T> E, std::string Msg) { if (E) return std::move(*E); check(E.getError(), Msg); return T(); } int main(int argc, char **argv) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness"); // FIXME: Workaround PR30396 which means that a symbol can appear // more than once if it is defined in module-level assembly and // has a GV declaration. We allow (file, symbol) pairs to have multiple // resolutions and apply them in the order observed. std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>> CommandLineResolutions; for (std::string R : SymbolResolutions) { StringRef Rest = R; StringRef FileName, SymbolName; std::tie(FileName, Rest) = Rest.split(','); if (Rest.empty()) { llvm::errs() << "invalid resolution: " << R << '\n'; return 1; } std::tie(SymbolName, Rest) = Rest.split(','); SymbolResolution Res; for (char C : Rest) { if (C == 'p') Res.Prevailing = true; else if (C == 'l') Res.FinalDefinitionInLinkageUnit = true; else if (C == 'x') Res.VisibleToRegularObj = true; else llvm::errs() << "invalid character " << C << " in resolution: " << R << '\n'; } CommandLineResolutions[{FileName, SymbolName}].push_back(Res); } std::vector<std::unique_ptr<MemoryBuffer>> MBs; Config Conf; Conf.DiagHandler = [](const DiagnosticInfo &DI) { DiagnosticPrinterRawOStream DP(errs()); DI.print(DP); errs() << '\n'; exit(1); }; Conf.CPU = MCPU; Conf.Options = InitTargetOptionsFromCodeGenFlags(); Conf.MAttrs = MAttrs; if (auto RM = getRelocModel()) Conf.RelocModel = *RM; Conf.CodeModel = CMModel; if (SaveTemps) check(Conf.addSaveTemps(OutputFilename + "."), "Config::addSaveTemps failed"); // Run a custom pipeline, if asked for. Conf.OptPipeline = OptPipeline; Conf.AAPipeline = AAPipeline; Conf.OptLevel = OptLevel - '0'; switch (CGOptLevel) { case '0': Conf.CGOptLevel = CodeGenOpt::None; break; case '1': Conf.CGOptLevel = CodeGenOpt::Less; break; case '2': Conf.CGOptLevel = CodeGenOpt::Default; break; case '3': Conf.CGOptLevel = CodeGenOpt::Aggressive; break; default: llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n'; return 1; } Conf.OverrideTriple = OverrideTriple; Conf.DefaultTriple = DefaultTriple; ThinBackend Backend; if (ThinLTODistributedIndexes) Backend = createWriteIndexesThinBackend("", "", true, ""); else Backend = createInProcessThinBackend(Threads); LTO Lto(std::move(Conf), std::move(Backend)); bool HasErrors = false; for (std::string F : InputFilenames) { std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); std::unique_ptr<InputFile> Input = check(InputFile::create(MB->getMemBufferRef()), F); std::vector<SymbolResolution> Res; for (const InputFile::Symbol &Sym : Input->symbols()) { auto I = CommandLineResolutions.find({F, Sym.getName()}); if (I == CommandLineResolutions.end()) { llvm::errs() << argv[0] << ": missing symbol resolution for " << F << ',' << Sym.getName() << '\n'; HasErrors = true; } else { Res.push_back(I->second.front()); I->second.pop_front(); if (I->second.empty()) CommandLineResolutions.erase(I); } } if (HasErrors) continue; MBs.push_back(std::move(MB)); check(Lto.add(std::move(Input), Res), F); } if (!CommandLineResolutions.empty()) { HasErrors = true; for (auto UnusedRes : CommandLineResolutions) llvm::errs() << argv[0] << ": unused symbol resolution for " << UnusedRes.first.first << ',' << UnusedRes.first.second << '\n'; } if (HasErrors) return 1; auto AddStream = [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> { std::string Path = OutputFilename + "." + utostr(Task); std::error_code EC; auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None); check(EC, Path); return llvm::make_unique<lto::NativeObjectStream>(std::move(S)); }; auto AddFile = [&](size_t Task, StringRef Path) { auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path); if (auto EC = ReloadedBufferOrErr.getError()) report_fatal_error(Twine("Can't reload cached file '") + Path + "': " + EC.message() + "\n"); *AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer(); }; NativeObjectCache Cache; if (!CacheDir.empty()) Cache = localCache(CacheDir, AddFile); check(Lto.run(AddStream, Cache), "LTO::run failed"); } <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2019, Jan Koester jan.koester@gmx.net 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 <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <iostream> #include <config.h> #include "connections.h" #include "eventapi.h" #include "threadpool.h" #include "exception.h" #include "event.h" bool libhttppp::Event::_Run=true; bool libhttppp::Event::_Restart=false; libhttppp::Event::Event(libhttppp::ServerSocket* serversocket) : EVENT(serversocket){ libhttppp::CtrlHandler::initCtrlHandler(); } libhttppp::Event::~Event(){ } libhttppp::EventApi::~EventApi(){ } void libhttppp::CtrlHandler::CTRLCloseEvent() { libhttppp::Event::_Run = false; } void libhttppp::CtrlHandler::CTRLBreakEvent() { libhttppp::Event::_Restart = true; libhttppp::Event::_Run=false; libhttppp::Event::_Run=true; } void libhttppp::CtrlHandler::CTRLTermEvent() { libhttppp::Event::_Run = false; } void libhttppp::CtrlHandler::SIGPIPEEvent() { return; } void libhttppp::Event::runEventloop(){ CpuInfo cpuinfo; size_t thrs = cpuinfo.getCores(); initEventHandler(); MAINWORKERLOOP: ThreadPool thpool; for (size_t i = 0; i < thrs; i++) { Thread *cthread=thpool.addThread(); cthread->Create(WorkerThread, (void*)this); } for (Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread()) { curth->Join(); } if(libhttppp::Event::_Restart){ libhttppp::Event::_Restart=false; goto MAINWORKERLOOP; } } void * libhttppp::Event::WorkerThread(void* wrkevent){ Event *eventptr=((Event*)wrkevent); int lstate=LockState::NOLOCK; while (libhttppp::Event::_Run) { try { for (int i = 0; i < eventptr->waitEventHandler(); ++i) { if((lstate=eventptr->LockConnection(i))!=LockState::ERRLOCK){ try{ switch(eventptr->StatusEventHandler(i)){ case EventApi::EventHandlerStatus::EVNOTREADY: eventptr->ConnectEventHandler(i); break; case EventApi::EventHandlerStatus::EVIN: eventptr->ReadEventHandler(i); break; case EventApi::EventHandlerStatus::EVOUT: eventptr->WriteEventHandler(i); break; default: eventptr->CloseEventHandler(i); break; } eventptr->UnlockConnection(i); }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; case HTTPException::Error: try{ eventptr->CloseEventHandler(i); }catch(HTTPException &e){ eventptr->UnlockConnection(i); throw e; } break; } } } } }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; default: Console con; con << e.what() << con.endl; } } } return NULL; } <commit_msg>fixed deadlocks<commit_after>/******************************************************************************* Copyright (c) 2019, Jan Koester jan.koester@gmx.net 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 <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <iostream> #include <config.h> #include "connections.h" #include "eventapi.h" #include "threadpool.h" #include "exception.h" #include "event.h" bool libhttppp::Event::_Run=true; bool libhttppp::Event::_Restart=false; libhttppp::Event::Event(libhttppp::ServerSocket* serversocket) : EVENT(serversocket){ libhttppp::CtrlHandler::initCtrlHandler(); } libhttppp::Event::~Event(){ } libhttppp::EventApi::~EventApi(){ } void libhttppp::CtrlHandler::CTRLCloseEvent() { libhttppp::Event::_Run = false; } void libhttppp::CtrlHandler::CTRLBreakEvent() { libhttppp::Event::_Restart = true; libhttppp::Event::_Run=false; libhttppp::Event::_Run=true; } void libhttppp::CtrlHandler::CTRLTermEvent() { libhttppp::Event::_Run = false; } void libhttppp::CtrlHandler::SIGPIPEEvent() { return; } void libhttppp::Event::runEventloop(){ CpuInfo cpuinfo; size_t thrs = cpuinfo.getCores(); initEventHandler(); MAINWORKERLOOP: ThreadPool thpool; for (size_t i = 0; i < thrs; i++) { Thread *cthread=thpool.addThread(); cthread->Create(WorkerThread, (void*)this); } for (Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread()) { curth->Join(); } if(libhttppp::Event::_Restart){ libhttppp::Event::_Restart=false; goto MAINWORKERLOOP; } } void * libhttppp::Event::WorkerThread(void* wrkevent){ Event *eventptr=((Event*)wrkevent); int lstate=LockState::NOLOCK; while (libhttppp::Event::_Run) { try { for (int i = 0; i < eventptr->waitEventHandler(); ++i) { if((lstate=eventptr->LockConnection(i))!=LockState::ERRLOCK){ try{ switch(eventptr->StatusEventHandler(i)){ case EventApi::EventHandlerStatus::EVNOTREADY: eventptr->ConnectEventHandler(i); break; case EventApi::EventHandlerStatus::EVIN: eventptr->ReadEventHandler(i); break; case EventApi::EventHandlerStatus::EVOUT: eventptr->WriteEventHandler(i); break; default: eventptr->CloseEventHandler(i); break; } eventptr->UnlockConnection(i); }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; case HTTPException::Error: try{ eventptr->CloseEventHandler(i); }catch(HTTPException &e){ if(e.getErrorType()==HTTPException::Critical){ eventptr->UnlockConnection(i); throw e; } } break; } eventptr->UnlockConnection(i); } } } }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; default: Console con; con << e.what() << con.endl; } } } return NULL; } <|endoftext|>
<commit_before>#include "aerial_autonomy/types/spiral_reference_trajectory.h" #include <glog/logging.h> constexpr double SpiralReferenceTrajectory::epsilon; constexpr double SpiralReferenceTrajectory::gravity_magnitude_; SpiralReferenceTrajectory::SpiralReferenceTrajectory( SpiralReferenceTrajectoryConfig config, ArmSineControllerConfig arm_config, Eigen::Vector3d current_position, double current_yaw) : ReferenceTrajectory(), config_(config), arm_config_(arm_config), current_position_(current_position), current_yaw_(current_yaw) { const auto &joint_config_vec = arm_config_.joint_config(); CHECK(joint_config_vec.size() == 2) << "There should be two joints"; CHECK(config.frequency_z() > 0) << "Z frequency cannot be 0 which implies z amplitude is infinity"; } void SpiralReferenceTrajectory::getRP( double &roll, double &pitch, double yaw, Eigen::Vector3d acceleration_vector) const { Eigen::Vector3d unit_vec = acceleration_vector.normalized(); double s_yaw = sin(yaw); double c_yaw = cos(yaw); double temp1 = unit_vec[0] * s_yaw - unit_vec[1] * c_yaw; if (std::abs(temp1) > 1.0) { LOG(WARNING) << "sin(roll) > 1"; temp1 = std::copysign(1.0, temp1); } roll = std::asin(temp1); double temp2 = unit_vec[0] * c_yaw + unit_vec[1] * s_yaw; if (std::abs(temp2) < epsilon && std::abs(unit_vec[2]) < epsilon) { LOG(WARNING) << "Roll is +/-90degrees which is a singularity"; pitch = 0; } else { double cos_inv = 1.0 / cos(roll); pitch = std::atan2(temp2 * cos_inv, unit_vec[2] * cos_inv); } } Eigen::Vector3d SpiralReferenceTrajectory::getAcceleration(double angle, double omega_squared, double rx, double ry) const { // Counter gravity in addition to trajectory acceleration return Eigen::Vector3d(-rx * omega_squared * sin(angle), -ry * omega_squared * cos(angle), gravity_magnitude_); } std::pair<Eigen::VectorXd, Eigen::VectorXd> SpiralReferenceTrajectory::atTime(double t) const { // State: position, rpy, velocity, rpydot, rpyd, ja, jv, jad // Controls: thrust, rpyd_dot, jad_dot; Eigen::VectorXd x(21); Eigen::VectorXd u(6); const double rx = config_.radiusx(); const double ry = config_.radiusy(); const double omega = 2 * M_PI * config_.frequency(); const double phase = config_.phase(); const double velocity_z = config_.velocity_z(); const double frequency_z = config_.frequency_z(); const double frequency_yaw = config_.frequency_yaw(); const double amplitude_yaw = config_.amplitude_yaw(); double amplitude_z = velocity_z / frequency_z; double z_rem = std::fmod(t * frequency_z, 2.0); double sign = z_rem < 1.0 ? 1.0 : -1.0; double dist_z = z_rem < 1.0 ? z_rem : (2.0 - z_rem); double angle = omega * t + phase; double omega_yaw = 2 * M_PI * frequency_yaw; double angle_yaw = omega_yaw * t; double omega_squared = omega * omega; double signed_velocity_z = sign * velocity_z; double yaw = current_yaw_ + amplitude_yaw * sin(angle_yaw); // Position x[0] = current_position_[0] + rx * sin(angle); x[1] = current_position_[1] + ry * cos(angle); x[2] = current_position_[2] + amplitude_z * dist_z; // Rpy Eigen::Vector3d acceleration_vector = getAcceleration(angle, omega_squared, rx, ry); getRP(x[3], x[4], yaw, acceleration_vector); x[5] = yaw; // Velocities x[6] = rx * omega * cos(angle); x[7] = -ry * omega * sin(angle); x[8] = signed_velocity_z; // Finite difference to get rpydot double dt = 1e-6; double angle_delta = angle + omega * dt; Eigen::Vector3d acceleration_vector_dt = getAcceleration(angle_delta, omega_squared, rx, ry); double yaw_dt = yaw + amplitude_yaw * sin(angle_yaw + omega_yaw * dt); double roll_dt, pitch_dt; getRP(roll_dt, pitch_dt, yaw_dt, acceleration_vector_dt); x[9] = (roll_dt - x[3]) / dt; x[10] = (pitch_dt - x[4]) / dt; x[11] = amplitude_yaw * omega_yaw * cos(angle_yaw); // Commanded angles x[12] = x[3]; x[13] = x[4]; x[14] = x[5]; // Joint state const auto &joint_config_vec = arm_config_.joint_config(); int start = 15; // Assuming 2 joints for (int i = 0; i < 2; ++i) { const auto &joint_config = joint_config_vec.Get(i); const double &amp = joint_config.amplitude(); const double &phi = joint_config.phase(); const double &offset = joint_config.offset(); double omega = 2 * M_PI * joint_config.frequency(); double angle = omega * t + phi; x[start + i] = offset + amp * sin(angle); x[start + i + 2] = amp * omega * cos(angle); x[start + i + 4] = x[start + i]; } // Controls u[0] = acceleration_vector.norm() / gravity_magnitude_; // rpyd_dot = rpy_dot u[1] = x[9]; u[2] = x[10]; u[3] = x[11]; // jad_dot = ja_dot u[4] = x[17]; u[5] = x[18]; return std::make_pair(x, u); } <commit_msg>Start spiral from the current position<commit_after>#include "aerial_autonomy/types/spiral_reference_trajectory.h" #include <glog/logging.h> constexpr double SpiralReferenceTrajectory::epsilon; constexpr double SpiralReferenceTrajectory::gravity_magnitude_; SpiralReferenceTrajectory::SpiralReferenceTrajectory( SpiralReferenceTrajectoryConfig config, ArmSineControllerConfig arm_config, Eigen::Vector3d current_position, double current_yaw) : ReferenceTrajectory(), config_(config), arm_config_(arm_config), current_position_(current_position), current_yaw_(current_yaw) { const auto &joint_config_vec = arm_config_.joint_config(); CHECK(joint_config_vec.size() == 2) << "There should be two joints"; CHECK(config.frequency_z() > 0) << "Z frequency cannot be 0 which implies z amplitude is infinity"; } void SpiralReferenceTrajectory::getRP( double &roll, double &pitch, double yaw, Eigen::Vector3d acceleration_vector) const { Eigen::Vector3d unit_vec = acceleration_vector.normalized(); double s_yaw = sin(yaw); double c_yaw = cos(yaw); double temp1 = unit_vec[0] * s_yaw - unit_vec[1] * c_yaw; if (std::abs(temp1) > 1.0) { LOG(WARNING) << "sin(roll) > 1"; temp1 = std::copysign(1.0, temp1); } roll = std::asin(temp1); double temp2 = unit_vec[0] * c_yaw + unit_vec[1] * s_yaw; if (std::abs(temp2) < epsilon && std::abs(unit_vec[2]) < epsilon) { LOG(WARNING) << "Roll is +/-90degrees which is a singularity"; pitch = 0; } else { double cos_inv = 1.0 / cos(roll); pitch = std::atan2(temp2 * cos_inv, unit_vec[2] * cos_inv); } } Eigen::Vector3d SpiralReferenceTrajectory::getAcceleration(double angle, double omega_squared, double rx, double ry) const { // Counter gravity in addition to trajectory acceleration return Eigen::Vector3d(-rx * omega_squared * sin(angle), -ry * omega_squared * cos(angle), gravity_magnitude_); } std::pair<Eigen::VectorXd, Eigen::VectorXd> SpiralReferenceTrajectory::atTime(double t) const { // State: position, rpy, velocity, rpydot, rpyd, ja, jv, jad // Controls: thrust, rpyd_dot, jad_dot; Eigen::VectorXd x(21); Eigen::VectorXd u(6); const double rx = config_.radiusx(); const double ry = config_.radiusy(); const double omega = 2 * M_PI * config_.frequency(); const double phase = config_.phase(); const double velocity_z = config_.velocity_z(); const double frequency_z = config_.frequency_z(); const double frequency_yaw = config_.frequency_yaw(); const double amplitude_yaw = config_.amplitude_yaw(); double amplitude_z = velocity_z / frequency_z; double z_rem = std::fmod(t * frequency_z, 2.0); double sign = z_rem < 1.0 ? 1.0 : -1.0; double dist_z = z_rem < 1.0 ? z_rem : (2.0 - z_rem); double angle = omega * t + phase; double omega_yaw = 2 * M_PI * frequency_yaw; double angle_yaw = omega_yaw * t; double omega_squared = omega * omega; double signed_velocity_z = sign * velocity_z; double yaw = current_yaw_ + amplitude_yaw * sin(angle_yaw); // Position x[0] = current_position_[0] - rx * sin(phase) + rx * sin(angle); x[1] = current_position_[1] - ry * cos(phase) + ry * cos(angle); x[2] = current_position_[2] + amplitude_z * dist_z; // Rpy Eigen::Vector3d acceleration_vector = getAcceleration(angle, omega_squared, rx, ry); getRP(x[3], x[4], yaw, acceleration_vector); x[5] = yaw; // Velocities x[6] = rx * omega * cos(angle); x[7] = -ry * omega * sin(angle); x[8] = signed_velocity_z; // Finite difference to get rpydot double dt = 1e-6; double angle_delta = angle + omega * dt; Eigen::Vector3d acceleration_vector_dt = getAcceleration(angle_delta, omega_squared, rx, ry); double yaw_dt = yaw + amplitude_yaw * sin(angle_yaw + omega_yaw * dt); double roll_dt, pitch_dt; getRP(roll_dt, pitch_dt, yaw_dt, acceleration_vector_dt); x[9] = (roll_dt - x[3]) / dt; x[10] = (pitch_dt - x[4]) / dt; x[11] = amplitude_yaw * omega_yaw * cos(angle_yaw); // Commanded angles x[12] = x[3]; x[13] = x[4]; x[14] = x[5]; // Joint state const auto &joint_config_vec = arm_config_.joint_config(); int start = 15; // Assuming 2 joints for (int i = 0; i < 2; ++i) { const auto &joint_config = joint_config_vec.Get(i); const double &amp = joint_config.amplitude(); const double &phi = joint_config.phase(); const double &offset = joint_config.offset(); double omega = 2 * M_PI * joint_config.frequency(); double angle = omega * t + phi; x[start + i] = offset + amp * sin(angle); x[start + i + 2] = amp * omega * cos(angle); x[start + i + 4] = x[start + i]; } // Controls u[0] = acceleration_vector.norm() / gravity_magnitude_; // rpyd_dot = rpy_dot u[1] = x[9]; u[2] = x[10]; u[3] = x[11]; // jad_dot = ja_dot u[4] = x[17]; u[5] = x[18]; return std::make_pair(x, u); } <|endoftext|>
<commit_before>/** * This file is part of the "tsdb" project * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <zbase/core/LogPartitionReplication.h> #include <zbase/core/LogPartitionReader.h> #include <zbase/core/ReplicationScheme.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/protobuf/msg.h> using namespace stx; namespace zbase { const size_t LogPartitionReplication::kMaxBatchSizeRows = 8192; const size_t LogPartitionReplication::kMaxBatchSizeBytes = 1024 * 1024 * 50; // 50 MB LogPartitionReplication::LogPartitionReplication( RefPtr<Partition> partition, RefPtr<ReplicationScheme> repl_scheme, http::HTTPConnectionPool* http) : PartitionReplication(partition, repl_scheme, http) {} bool LogPartitionReplication::needsReplication() const { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return false; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { return true; } } return false; } size_t LogPartitionReplication::numFullRemoteCopies() const { size_t ncopies = 0; auto replicas = repl_scheme_->replicasFor(snap_->key); auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset >= head_offset) { ncopies += 1; } } return ncopies; } void LogPartitionReplication::replicateTo( const ReplicaRef& replica, uint64_t replicated_offset) { if (replica.is_local) { RAISE(kIllegalStateError, "can't replicate to myself"); } LogPartitionReader reader(partition_->getTable(), snap_); size_t batch_size = 0; RecordEnvelopeList batch; reader.fetchRecords( replicated_offset, size_t(-1), [this, &batch, &replica, &replicated_offset, &batch_size] ( const SHA1Hash& record_id, const void* record_data, size_t record_size) { auto rec = batch.add_records(); rec->set_tsdb_namespace(snap_->state.tsdb_namespace()); rec->set_table_name(snap_->state.table_key()); rec->set_partition_sha1(snap_->key.toString()); rec->set_record_id(record_id.toString()); rec->set_record_data(record_data, record_size); batch_size += record_size; if (batch_size > kMaxBatchSizeBytes || batch.records().size() > kMaxBatchSizeRows) { uploadBatchTo(replica, batch); batch.mutable_records()->Clear(); batch_size = 0; } }); if (batch.records().size() > 0) { uploadBatchTo(replica, batch); } } void LogPartitionReplication::uploadBatchTo( const ReplicaRef& replica, const RecordEnvelopeList& batch) { auto body = msg::encode(batch); URI uri(StringUtil::format("http://$0/tsdb/insert", replica.addr.hostAndPort())); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); req.addBody(body->data(), body->size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } bool LogPartitionReplication::replicate() { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return true; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; bool dirty = false; bool success = true; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { logTrace( "tsdb", "Replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr.hostAndPort()); try { replicateTo(r, replica_offset); setReplicatedOffsetFor(&repl_state, r.unique_id, head_offset); dirty = true; } catch (const std::exception& e) { success = false; stx::logError( "tsdb", e, "Error while replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr.hostAndPort()); } } } if (dirty) { commitReplicationState(repl_state); } return success; } } // namespace tdsb <commit_msg>add assert in LogPartitionReplication<commit_after>/** * This file is part of the "tsdb" project * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <zbase/core/LogPartitionReplication.h> #include <zbase/core/LogPartitionReader.h> #include <zbase/core/ReplicationScheme.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/protobuf/msg.h> using namespace stx; namespace zbase { const size_t LogPartitionReplication::kMaxBatchSizeRows = 8192; const size_t LogPartitionReplication::kMaxBatchSizeBytes = 1024 * 1024 * 50; // 50 MB LogPartitionReplication::LogPartitionReplication( RefPtr<Partition> partition, RefPtr<ReplicationScheme> repl_scheme, http::HTTPConnectionPool* http) : PartitionReplication(partition, repl_scheme, http) {} bool LogPartitionReplication::needsReplication() const { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return false; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { return true; } } return false; } size_t LogPartitionReplication::numFullRemoteCopies() const { size_t ncopies = 0; auto replicas = repl_scheme_->replicasFor(snap_->key); auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset >= head_offset) { ncopies += 1; } } return ncopies; } void LogPartitionReplication::replicateTo( const ReplicaRef& replica, uint64_t replicated_offset) { if (replica.is_local) { RAISE(kIllegalStateError, "can't replicate to myself"); } LogPartitionReader reader(partition_->getTable(), snap_); size_t batch_size = 0; size_t num_replicated = 0; RecordEnvelopeList batch; reader.fetchRecords( replicated_offset, size_t(-1), [this, &batch, &replica, &replicated_offset, &batch_size, &num_replicated] ( const SHA1Hash& record_id, const void* record_data, size_t record_size) { auto rec = batch.add_records(); rec->set_tsdb_namespace(snap_->state.tsdb_namespace()); rec->set_table_name(snap_->state.table_key()); rec->set_partition_sha1(snap_->key.toString()); rec->set_record_id(record_id.toString()); rec->set_record_data(record_data, record_size); batch_size += record_size; ++num_replicated; if (batch_size > kMaxBatchSizeBytes || batch.records().size() > kMaxBatchSizeRows) { uploadBatchTo(replica, batch); batch.mutable_records()->Clear(); batch_size = 0; } }); if (batch.records().size() > 0) { uploadBatchTo(replica, batch); } if (num_replicated != snap_->nrecs - replicated_offset) { RAISEF( kIllegalStateError, "expected to replicate $0 records, but only saw $1", snap_->nrecs - replicated_offset, num_replicated); } } void LogPartitionReplication::uploadBatchTo( const ReplicaRef& replica, const RecordEnvelopeList& batch) { auto body = msg::encode(batch); URI uri(StringUtil::format("http://$0/tsdb/insert", replica.addr.hostAndPort())); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); req.addBody(body->data(), body->size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } bool LogPartitionReplication::replicate() { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return true; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; bool dirty = false; bool success = true; for (const auto& r : replicas) { if (r.is_local) { continue; } const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { logTrace( "tsdb", "Replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr.hostAndPort()); try { replicateTo(r, replica_offset); setReplicatedOffsetFor(&repl_state, r.unique_id, head_offset); dirty = true; } catch (const std::exception& e) { success = false; stx::logError( "tsdb", e, "Error while replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr.hostAndPort()); } } } if (dirty) { commitReplicationState(repl_state); } return success; } } // namespace tdsb <|endoftext|>
<commit_before>#include <qpiekey.h> #include <QSizePolicy> #include <QPainter> #include <QPaintEvent> #include <math.h> #include <stdio.h> #include <unistd.h> #include "term_logging.h" using namespace std; QPieKey::QPieKey(QWidget *parent) : QWidget(parent) { sections = 0; size = 0; hide(); } QPieKey::~QPieKey() { } QChar QPieKey::toChar(Qt::Key key) { if( key >= Qt::Key_A && key <= Qt::Key_Z ) { return key - Qt::Key_A + 'a'; } } void QPieKey::paintEvent(QPaintEvent *event) { int inSelection = 0, selectedChar; int i, j,k; double charangle; QPainter painter(this); Qt::Key character; painter.setBrush(QColor(128, 128, 128)); painter.drawRect(event->rect()); if( sections ) { painter.setBrush(QColor(180, 180, 180)); if( highlighted_section != -1 ) { painter.drawPie(0, 0, size*2, size*2, (90-(angle*(highlighted_section+0.5))*180/M_PI)*16, angle*180/M_PI*16); } painter.setBrush(QColor(0, 0, 0)); for( i = 0; i < sections; i ++ ) { for( j = 0; j < letters_per_section; j ++ ) { // The angle of the section extends from angle*(i-0.5) to // angle*(i+0.5). We want to center 'sections' characters // with equal angular spacing in this area. Add a full width // on each side to separate a section from its neighbour character = keylist[i][j]; charangle = angle*((j+1.0)/(sections+1.0)+i-0.5); selectedChar = (highlighted_section == -1 || highlighted_section == i); if( selectedChar ) { for(map<int, const vector<Qt::Key> *>::const_iterator k = selections.begin(); k != selections.end(); k ++ ) { if( k->second == NULL ) continue; if( std::find(k->second->begin(), k->second->end(), selectedChar) == k->second->end() ) { selectedChar = false; break; } } } if( selectedChar != inSelection ) { QFont font; inSelection = selectedChar; font.setBold(inSelection); if( inSelection ) { if( font.pixelSize() != -1 ) { font.setPixelSize(font.pixelSize() + 3); } if( font.pointSize() != -1 ) { font.setPointSize(font.pointSize() + 3); } } painter.setFont(font); } switch( character ) { case Qt::Key_Tab: { QPixmap img("app/native/tab.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; case Qt::Key_Escape: { QPixmap img("app/native/escape.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; case Qt::Key_Up: { QPixmap img("app/native/up.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; case Qt::Key_Down: { QPixmap img("app/native/down.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; case Qt::Key_Right: { QPixmap img("app/native/right.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; case Qt::Key_Left: { QPixmap img("app/native/left.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4+img.height()/2, img); } break; default: painter.drawText(size+size*sin(charangle)*3/4-painter.fontMetrics().width(character)/2, size-size*cos(charangle)*3/4+painter.fontMetrics().height()/2, toChar(character)); break; } } } for( i = 0; i < sections; i ++ ) { if( highlighted_section == -1 || (i != highlighted_section && i != (highlighted_section + 1) % sections)) { painter.drawLine(size, size, size+size*sin(angle*(i-0.5)), size-size*cos(angle*(i-0.5))); } } } } void QPieKey::mouseMoveEvent(QMouseEvent *event) { moveTouch(event->x(), event->y()); } void QPieKey::moveTouch(int x, int y) { int section; double distance; double mouseangle; // Find whether we are in the wheel distance = sqrt((x-size)*(x-size)+(y-size)*(y-size)); if( distance * 2 < size ) { section = -1; } else { mouseangle = atan2(((double)size - x), ((double)y - size)) + M_PI; section = ((int)((mouseangle + 0.5) / angle)) % sections; } if( section != highlighted_section ) { if( section == -1 ) { // We're losing our selection, send the signal now for(int i = 0; i < letters_per_section; i ++ ) { std::map<int, const std::vector<Qt::Key> *>::const_iterator j; for(j = selections.begin(); j != selections.end(); j ++ ) { if( std::find(j->second->begin(), j->second->end(), keylist[highlighted_section][i]) == j->second->end() ) { break; } } if( j == selections.end() ) { emit(keypress(keylist[highlighted_section][i])); } } emit selectionChanged(NULL); } else { // We're gaining a selection, notify our parent emit selectionChanged(&keylist[ section ]); } highlighted_section = section; update(0,0, size*2, size*2); } } void QPieKey::mouseReleaseEvent(QMouseEvent *event) { releaseMouse(); emit released(); } void QPieKey::initialize(int sections, const vector<Qt::Key> &keylist) { int i, j; this->selections.clear(); letters_per_section = keylist.size() / sections; this->sections = sections; this->keylist.clear(); for( i = 0; i < sections; i ++ ) { this->keylist.push_back(vector<Qt::Key>()); for( j = 0; j < letters_per_section; j ++ ) { this->keylist.back().push_back(keylist[i*letters_per_section+j]); } } angle = 2*M_PI / sections; highlighted_section = -1; size_ring(); } void QPieKey::activate(int x, int y) { // Center the widget on the mouse coordinates highlighted_section = -1; selections.clear(); setGeometry(x - width() / 2, y - height() / 2, width(), height()); show(); grabMouse(); } void QPieKey::select(int key, const vector<Qt::Key> *selection) { this->selections[key] = selection; update(0,0, size*2, size*2); } void QPieKey::size_ring() { // TODO Figure out how big the largest section has to be so letters don't overlap size = 200; // Update the mask of the widget appropriately bitmap = new QBitmap(size*2,size*2); QPainter painter(bitmap); setFixedSize(size*2, size*2); bitmap->clear(); painter.setBrush(Qt::color1); painter.drawEllipse(1, 1, size*2-2, size*2-2); painter.setBrush(Qt::color0); painter.drawEllipse(size/2, size/2, size, size); setMask(*bitmap); } <commit_msg>Fix centering of letters/images in piekey<commit_after>#include <qpiekey.h> #include <QSizePolicy> #include <QPainter> #include <QPaintEvent> #include <math.h> #include <stdio.h> #include <unistd.h> #include "term_logging.h" using namespace std; QPieKey::QPieKey(QWidget *parent) : QWidget(parent) { sections = 0; size = 0; hide(); } QPieKey::~QPieKey() { } QChar QPieKey::toChar(Qt::Key key) { if( key >= Qt::Key_A && key <= Qt::Key_Z ) { return key - Qt::Key_A + 'a'; } } void QPieKey::paintEvent(QPaintEvent *event) { int inSelection = 0, selectedChar; int i, j,k; double charangle; QPainter painter(this); Qt::Key character; painter.setBrush(QColor(128, 128, 128)); painter.drawRect(event->rect()); if( sections ) { painter.setBrush(QColor(180, 180, 180)); if( highlighted_section != -1 ) { painter.drawPie(0, 0, size*2, size*2, (90-(angle*(highlighted_section+0.5))*180/M_PI)*16, angle*180/M_PI*16); } painter.setBrush(QColor(0, 0, 0)); for( i = 0; i < sections; i ++ ) { for( j = 0; j < letters_per_section; j ++ ) { // The angle of the section extends from angle*(i-0.5) to // angle*(i+0.5). We want to center 'sections' characters // with equal angular spacing in this area. Add a full width // on each side to separate a section from its neighbour character = keylist[i][j]; charangle = angle*(j/letters_per_section + i); selectedChar = (highlighted_section == -1 || highlighted_section == i); if( selectedChar ) { for(map<int, const vector<Qt::Key> *>::const_iterator k = selections.begin(); k != selections.end(); k ++ ) { if( k->second == NULL ) continue; if( std::find(k->second->begin(), k->second->end(), selectedChar) == k->second->end() ) { selectedChar = false; break; } } } if( selectedChar != inSelection ) { QFont font; inSelection = selectedChar; font.setBold(inSelection); if( inSelection ) { if( font.pixelSize() != -1 ) { font.setPixelSize(font.pixelSize() + 3); } if( font.pointSize() != -1 ) { font.setPointSize(font.pointSize() + 3); } } painter.setFont(font); } switch( character ) { case Qt::Key_Tab: { QPixmap img("app/native/tab.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; case Qt::Key_Escape: { QPixmap img("app/native/escape.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; case Qt::Key_Up: { QPixmap img("app/native/up.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; case Qt::Key_Down: { QPixmap img("app/native/down.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; case Qt::Key_Right: { QPixmap img("app/native/right.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; case Qt::Key_Left: { QPixmap img("app/native/left.png"); painter.drawPixmap(size+size*sin(charangle)*3/4-img.width()/2, size-size*cos(charangle)*3/4-img.height()/2, img); } break; default: painter.drawText(size+size*sin(charangle)*3/4-painter.fontMetrics().width(character)/2, size-size*cos(charangle)*3/4+painter.fontMetrics().height()/2, toChar(character)); break; } } } for( i = 0; i < sections; i ++ ) { if( highlighted_section == -1 || (i != highlighted_section && i != (highlighted_section + 1) % sections)) { painter.drawLine(size, size, size+size*sin(angle*(i-0.5)), size-size*cos(angle*(i-0.5))); } } } } void QPieKey::mouseMoveEvent(QMouseEvent *event) { moveTouch(event->x(), event->y()); } void QPieKey::moveTouch(int x, int y) { int section; double distance; double mouseangle; // Find whether we are in the wheel distance = sqrt((x-size)*(x-size)+(y-size)*(y-size)); if( distance * 2 < size ) { section = -1; } else { mouseangle = atan2(((double)size - x), ((double)y - size)) + M_PI; section = ((int)((mouseangle + 0.5) / angle)) % sections; } if( section != highlighted_section ) { if( section == -1 ) { // We're losing our selection, send the signal now for(int i = 0; i < letters_per_section; i ++ ) { std::map<int, const std::vector<Qt::Key> *>::const_iterator j; for(j = selections.begin(); j != selections.end(); j ++ ) { if( std::find(j->second->begin(), j->second->end(), keylist[highlighted_section][i]) == j->second->end() ) { break; } } if( j == selections.end() ) { emit(keypress(keylist[highlighted_section][i])); } } emit selectionChanged(NULL); } else { // We're gaining a selection, notify our parent emit selectionChanged(&keylist[ section ]); } highlighted_section = section; update(0,0, size*2, size*2); } } void QPieKey::mouseReleaseEvent(QMouseEvent *event) { releaseMouse(); emit released(); } void QPieKey::initialize(int sections, const vector<Qt::Key> &keylist) { int i, j; this->selections.clear(); letters_per_section = keylist.size() / sections; this->sections = sections; this->keylist.clear(); for( i = 0; i < sections; i ++ ) { this->keylist.push_back(vector<Qt::Key>()); for( j = 0; j < letters_per_section; j ++ ) { this->keylist.back().push_back(keylist[i*letters_per_section+j]); } } angle = 2*M_PI / sections; highlighted_section = -1; size_ring(); } void QPieKey::activate(int x, int y) { // Center the widget on the mouse coordinates highlighted_section = -1; selections.clear(); setGeometry(x - width() / 2, y - height() / 2, width(), height()); show(); grabMouse(); } void QPieKey::select(int key, const vector<Qt::Key> *selection) { this->selections[key] = selection; update(0,0, size*2, size*2); } void QPieKey::size_ring() { // TODO Figure out how big the largest section has to be so letters don't overlap size = 200; // Update the mask of the widget appropriately bitmap = new QBitmap(size*2,size*2); QPainter painter(bitmap); setFixedSize(size*2, size*2); bitmap->clear(); painter.setBrush(Qt::color1); painter.drawEllipse(1, 1, size*2-2, size*2-2); painter.setBrush(Qt::color0); painter.drawEllipse(size/2, size/2, size, size); setMask(*bitmap); } <|endoftext|>
<commit_before> #include <memory> #include <string> #include <map> #include <algorithm> #pragma warning (disable : 4005) #include "Effekseer.h" #include "EffekseerRendererDX9.h" #include "EffekseerRendererDX11.h" #include "../common/IUnityGraphics.h" #include "../common/EffekseerPluginLoader.h" using namespace Effekseer; extern UnityGfxRenderer g_RendererType; extern IDirect3DDevice9* g_D3d9Device; extern ID3D11Device* g_D3d11Device; extern ID3D11DeviceContext* g_D3d11Context; extern EffekseerRenderer::Renderer* g_EffekseerRenderer; namespace EffekseerPlugin { class TextureLoaderWin : public TextureLoader { struct TextureResource { int referenceCount = 1; void* texture = nullptr; }; std::map<std::u16string, TextureResource> resources; public: TextureLoaderWin( TextureLoaderLoad load, TextureLoaderUnload unload) : TextureLoader(load, unload) {} virtual ~TextureLoaderWin() {} virtual void* Load( const EFK_CHAR* path, Effekseer::TextureType textureType ){ auto it = resources.find((const char16_t*)path); if (it != resources.end()) { it->second.referenceCount++; return it->second.texture; } else { TextureResource res; res.texture = load( (const char16_t*)path ); if (g_RendererType == kUnityGfxRendererD3D11) { // Unity[ĥID3D11Texture2DȂ̂ŁA // ID3D11ShaderResourceViewɕϊ HRESULT hr; ID3D11Texture2D* textureDX11 = (ID3D11Texture2D*)res.texture; D3D11_TEXTURE2D_DESC texDesc; textureDX11->GetDesc(&texDesc); ID3D11ShaderResourceView* resView = nullptr; D3D11_SHADER_RESOURCE_VIEW_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Format = texDesc.Format; desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.MipLevels = texDesc.MipLevels; hr = g_D3d11Device->CreateShaderResourceView(textureDX11, &desc, &resView); if (FAILED(hr)) { return nullptr; } res.texture = resView; } resources.insert( std::make_pair( (const char16_t*)path, res ) ); return res.texture; } return nullptr; } virtual void Unload( void* source ){ for (auto it = resources.begin(); it != resources.end(); it++) { if (it->second.texture == source) { it->second.referenceCount--; if (it->second.referenceCount <= 0) { if (g_RendererType == kUnityGfxRendererD3D11) { // ID3D11Texture2Dɖ߂UnityɃA[hĂ炤 ID3D11Resource* resourceDX11 = nullptr; ID3D11ShaderResourceView* resView = (ID3D11ShaderResourceView*)source; resView->GetResource(&resourceDX11); resView->Release(); } unload( it->first.c_str() ); resources.erase(it); } } } } }; TextureLoader* TextureLoader::Create( TextureLoaderLoad load, TextureLoaderUnload unload) { return new TextureLoaderWin( load, unload ); } class ModelLoaderWin : public ModelLoader { ModelLoaderLoad load; ModelLoaderUnload unload; struct ModelResource { int referenceCount = 1; void* internalData; }; std::map<std::u16string, ModelResource> resources; class MemoryFileReader : public Effekseer::FileReader { uint8_t* data; size_t length; int position; public: MemoryFileReader(uint8_t* data, size_t length): data(data), length(length) {} size_t Read( void* buffer, size_t size ) { if (size >= length - position) { size = length - position; } memcpy(buffer, &data[position], size); position += size; return size; } void Seek(int position) { this->position = position; } int GetPosition() { return position; } size_t GetLength() { return length; } }; class MemoryFile : public Effekseer::FileInterface { public: std::vector<uint8_t> loadbuffer; size_t loadsize; FileReader* OpenRead( const EFK_CHAR* path ) { return new MemoryFileReader(&loadbuffer[0], loadsize); } FileWriter* OpenWrite( const EFK_CHAR* path ) { return nullptr; } }; MemoryFile memoryFile; std::unique_ptr<Effekseer::ModelLoader> internalLoader; public: ModelLoaderWin( ModelLoaderLoad load, ModelLoaderUnload unload ) : ModelLoader( load, unload ) , internalLoader( g_EffekseerRenderer->CreateModelLoader( &memoryFile ) ) {} virtual ~ModelLoaderWin() {} virtual void* Load( const EFK_CHAR* path ){ auto it = resources.find((const char16_t*)path); if (it != resources.end()) { it->second.referenceCount++; return it->second.internalData; } else { ModelResource res; int size = load( (const char16_t*)path, &memoryFile.loadbuffer[0], (int)memoryFile.loadbuffer.size() ); if (size <= 0) { return nullptr; } memoryFile.loadsize = (size_t)size; res.internalData = internalLoader->Load( path ); resources.insert( std::make_pair( (const char16_t*)path, res ) ); return res.internalData; } return nullptr; } virtual void Unload( void* source ){ for (auto it = resources.begin(); it != resources.end(); it++) { if (it->second.internalData == source) { it->second.referenceCount--; if (it->second.referenceCount <= 0) { unload( it->first.c_str() ); resources.erase(it); } } } } }; ModelLoader* ModelLoader::Create( ModelLoaderLoad load, ModelLoaderUnload unload) { return new ModelLoaderWin( load, unload ); } };<commit_msg>[UnityPlugin] テクスチャロード時のnullチェックを追加<commit_after> #include <memory> #include <string> #include <map> #include <algorithm> #pragma warning (disable : 4005) #include "Effekseer.h" #include "EffekseerRendererDX9.h" #include "EffekseerRendererDX11.h" #include "../common/IUnityGraphics.h" #include "../common/EffekseerPluginLoader.h" using namespace Effekseer; extern UnityGfxRenderer g_RendererType; extern IDirect3DDevice9* g_D3d9Device; extern ID3D11Device* g_D3d11Device; extern ID3D11DeviceContext* g_D3d11Context; extern EffekseerRenderer::Renderer* g_EffekseerRenderer; namespace EffekseerPlugin { class TextureLoaderWin : public TextureLoader { struct TextureResource { int referenceCount = 1; void* texture = nullptr; }; std::map<std::u16string, TextureResource> resources; public: TextureLoaderWin( TextureLoaderLoad load, TextureLoaderUnload unload) : TextureLoader(load, unload) {} virtual ~TextureLoaderWin() {} virtual void* Load( const EFK_CHAR* path, Effekseer::TextureType textureType ){ auto it = resources.find((const char16_t*)path); if (it != resources.end()) { it->second.referenceCount++; return it->second.texture; } else { TextureResource res; res.texture = load( (const char16_t*)path ); if (res.texture == nullptr) { return nullptr; } if (g_RendererType == kUnityGfxRendererD3D11) { // Unity[ĥID3D11Texture2DȂ̂ŁA // ID3D11ShaderResourceViewɕϊ HRESULT hr; ID3D11Texture2D* textureDX11 = (ID3D11Texture2D*)res.texture; D3D11_TEXTURE2D_DESC texDesc; textureDX11->GetDesc(&texDesc); ID3D11ShaderResourceView* resView = nullptr; D3D11_SHADER_RESOURCE_VIEW_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Format = texDesc.Format; desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.MipLevels = texDesc.MipLevels; hr = g_D3d11Device->CreateShaderResourceView(textureDX11, &desc, &resView); if (FAILED(hr)) { return nullptr; } res.texture = resView; } resources.insert( std::make_pair( (const char16_t*)path, res ) ); return res.texture; } return nullptr; } virtual void Unload( void* source ){ for (auto it = resources.begin(); it != resources.end(); it++) { if (it->second.texture == source) { it->second.referenceCount--; if (it->second.referenceCount <= 0) { if (g_RendererType == kUnityGfxRendererD3D11) { // ID3D11Texture2Dɖ߂UnityɃA[hĂ炤 ID3D11Resource* resourceDX11 = nullptr; ID3D11ShaderResourceView* resView = (ID3D11ShaderResourceView*)source; resView->GetResource(&resourceDX11); resView->Release(); } unload( it->first.c_str() ); resources.erase(it); } } } } }; TextureLoader* TextureLoader::Create( TextureLoaderLoad load, TextureLoaderUnload unload) { return new TextureLoaderWin( load, unload ); } class ModelLoaderWin : public ModelLoader { ModelLoaderLoad load; ModelLoaderUnload unload; struct ModelResource { int referenceCount = 1; void* internalData; }; std::map<std::u16string, ModelResource> resources; class MemoryFileReader : public Effekseer::FileReader { uint8_t* data; size_t length; int position; public: MemoryFileReader(uint8_t* data, size_t length): data(data), length(length) {} size_t Read( void* buffer, size_t size ) { if (size >= length - position) { size = length - position; } memcpy(buffer, &data[position], size); position += (int)size; return size; } void Seek(int position) { this->position = position; } int GetPosition() { return position; } size_t GetLength() { return length; } }; class MemoryFile : public Effekseer::FileInterface { public: std::vector<uint8_t> loadbuffer; size_t loadsize; FileReader* OpenRead( const EFK_CHAR* path ) { return new MemoryFileReader(&loadbuffer[0], loadsize); } FileWriter* OpenWrite( const EFK_CHAR* path ) { return nullptr; } }; MemoryFile memoryFile; std::unique_ptr<Effekseer::ModelLoader> internalLoader; public: ModelLoaderWin( ModelLoaderLoad load, ModelLoaderUnload unload ) : ModelLoader( load, unload ) , internalLoader( g_EffekseerRenderer->CreateModelLoader( &memoryFile ) ) {} virtual ~ModelLoaderWin() {} virtual void* Load( const EFK_CHAR* path ){ auto it = resources.find((const char16_t*)path); if (it != resources.end()) { it->second.referenceCount++; return it->second.internalData; } else { ModelResource res; int size = load( (const char16_t*)path, &memoryFile.loadbuffer[0], (int)memoryFile.loadbuffer.size() ); if (size <= 0) { return nullptr; } memoryFile.loadsize = (size_t)size; res.internalData = internalLoader->Load( path ); resources.insert( std::make_pair( (const char16_t*)path, res ) ); return res.internalData; } return nullptr; } virtual void Unload( void* source ){ for (auto it = resources.begin(); it != resources.end(); it++) { if (it->second.internalData == source) { it->second.referenceCount--; if (it->second.referenceCount <= 0) { unload( it->first.c_str() ); resources.erase(it); } } } } }; ModelLoader* ModelLoader::Create( ModelLoaderLoad load, ModelLoaderUnload unload) { return new ModelLoaderWin( load, unload ); } };<|endoftext|>
<commit_before>#include <string> #include <vector> #include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/robot_trajectory/robot_trajectory.h> #include <moveit/trajectory_processing/iterative_time_parameterization.h> #include <tf2_ros/transform_listener.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/TransformStamped.h> #include <moveit_msgs/RobotTrajectory.h> class MoveGroupInterface { moveit::planning_interface::MoveGroup move_group_; tf2_ros::Buffer buffer_; tf2_ros::TransformListener listener_; geometry_msgs::Pose tomapo_; std::vector<geometry_msgs::Pose> waypoints_; static constexpr double eef_length_ {0.3}; // TODO static constexpr double eef_step_ {0.10}; static constexpr double abs_rail_length_ {5.0}; double sign_; public: MoveGroupInterface(const std::string& group_name, const double& joint_tolerance) : move_group_ {group_name}, buffer_ {}, listener_ {buffer_}, tomapo_ {}, waypoints_ {}, sign_ {1.0} { move_group_.allowReplanning(true); move_group_.setGoalJointTolerance(joint_tolerance); move_group_.setPlanningTime(5.0); } bool queryTargetExistence() { try { geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform("rail", "tomato", ros::Time(0), ros::Duration(1.0))}; tomapo_.position.x = transform_stamped_.transform.translation.x; tomapo_.position.y = transform_stamped_.transform.translation.y; tomapo_.position.z = transform_stamped_.transform.translation.z; tomapo_.orientation.x = 0; tomapo_.orientation.y = 0; tomapo_.orientation.z = 0; tomapo_.orientation.w = 1.0; return true; } catch (const tf2::TransformException& ex) { ROS_INFO_STREAM(ex.what()); return false; } } bool startSequence() { waypoints_.clear(); geometry_msgs::Pose pose1 {tomapo_}; pose1.position.x -= eef_length_; // waypoints_.push_back(pose1); move_group_.setPoseTarget(pose1); moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); if (!move_group_.execute(plan)) return false; geometry_msgs::Pose pose2 {tomapo_}; waypoints_.push_back(pose2); geometry_msgs::Pose pose3 {tomapo_}; pose3.orientation = tf::createQuaternionMsgFromRollPitchYaw(1.0, 0, 0); waypoints_.push_back(pose3); geometry_msgs::Pose pose4 {tomapo_}; pose4.position.x -= eef_length_; waypoints_.push_back(pose4); moveit_msgs::RobotTrajectory trajectory_msgs_; move_group_.computeCartesianPath(waypoints_, eef_step_, 0.0, trajectory_msgs_); robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()}; robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_); trajectory_processing::IterativeParabolicTimeParameterization iptp; iptp.computeTimeStamps(robot_trajectory_); robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_); moveit::planning_interface::MoveGroup::Plan motion_plan_; motion_plan_.trajectory_ = trajectory_msgs_; return move_group_.execute(motion_plan_); } bool baseShift() { double tmp; try { geometry_msgs::TransformStamped transform_stamped {buffer_.lookupTransform("rail", "shaft", ros::Time(0), ros::Duration(1.0))}; tmp = transform_stamped.transform.translation.y; if (tmp > (abs_rail_length_ - 1.0)) sign_ = -1.0; else if (tmp < -(abs_rail_length_ - 1.0)) sign_ = 1.0; } catch (const tf2::TransformException& ex) { ROS_INFO_STREAM(ex.what()); return false; } // auto named_target_values = move_group_.getNamedTargetValues("init"); // named_target_values["rail_to_shaft_joint"] += (sign_ * 1.0); // move_group_.setJointValueTarget(named_target_values); move_group_.setNamedTarget("init"); std::vector<double> joint_values; auto joint_model_group = move_group_.getCurrentState()->getRobotModel()->getJointModelGroup(move_group_.getName()); move_group_.getCurrentState()->copyJointGroupPositions(joint_model_group, joint_values); // joint_values[0] += sign_ * 1.0; // joint_values[1] = -0.3927; joint_values[1] = 0; joint_values[2] = -0.7854; joint_values[3] = 1.5707; joint_values[4] = -0.7854; joint_values[5] = 0; move_group_.setJointValueTarget(joint_values); moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); move_group_.execute(plan); joint_values[0] += sign_ * 1.0; // joint_values[1] = -0.3927; joint_values[1] = 0; joint_values[2] = -0.7854; joint_values[3] = 1.5707; joint_values[4] = -0.7854; joint_values[5] = 0; move_group_.setJointValueTarget(joint_values); // moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); return move_group_.execute(plan); } }; int main(int argc, char** argv) { ros::init(argc, argv, "arcsys2_move_group_interface_node"); ros::NodeHandle node_handle {"~"}; ros::AsyncSpinner spinner {1}; spinner.start(); MoveGroupInterface interface {"arcsys2", node_handle.param("joint_tolerance", 0.1)}; while (ros::ok()) { while (!interface.queryTargetExistence()) interface.baseShift(); interface.startSequence(); } spinner.stop(); return 0; } <commit_msg>Change to getCurrentJointValues()<commit_after>#include <string> #include <vector> #include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/robot_trajectory/robot_trajectory.h> #include <moveit/trajectory_processing/iterative_time_parameterization.h> #include <tf2_ros/transform_listener.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/TransformStamped.h> #include <moveit_msgs/RobotTrajectory.h> class MoveGroupInterface { moveit::planning_interface::MoveGroup move_group_; tf2_ros::Buffer buffer_; tf2_ros::TransformListener listener_; geometry_msgs::Pose tomapo_; std::vector<geometry_msgs::Pose> waypoints_; static constexpr double eef_length_ {0.3}; // TODO static constexpr double eef_step_ {0.10}; static constexpr double abs_rail_length_ {5.0}; double sign_; public: MoveGroupInterface(const std::string& group_name, const double& joint_tolerance) : move_group_ {group_name}, buffer_ {}, listener_ {buffer_}, tomapo_ {}, waypoints_ {}, sign_ {1.0} { move_group_.allowReplanning(true); move_group_.setGoalJointTolerance(joint_tolerance); move_group_.setPlanningTime(5.0); } bool queryTargetExistence() { try { geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform("rail", "tomato", ros::Time(0), ros::Duration(1.0))}; tomapo_.position.x = transform_stamped_.transform.translation.x; tomapo_.position.y = transform_stamped_.transform.translation.y; tomapo_.position.z = transform_stamped_.transform.translation.z; tomapo_.orientation.x = 0; tomapo_.orientation.y = 0; tomapo_.orientation.z = 0; tomapo_.orientation.w = 1.0; return true; } catch (const tf2::TransformException& ex) { ROS_INFO_STREAM(ex.what()); return false; } } bool startSequence() { waypoints_.clear(); geometry_msgs::Pose pose1 {tomapo_}; pose1.position.x -= eef_length_; // waypoints_.push_back(pose1); move_group_.setPoseTarget(pose1); moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); if (!move_group_.execute(plan)) return false; geometry_msgs::Pose pose2 {tomapo_}; waypoints_.push_back(pose2); geometry_msgs::Pose pose3 {tomapo_}; pose3.orientation = tf::createQuaternionMsgFromRollPitchYaw(1.0, 0, 0); waypoints_.push_back(pose3); geometry_msgs::Pose pose4 {tomapo_}; pose4.position.x -= eef_length_; waypoints_.push_back(pose4); moveit_msgs::RobotTrajectory trajectory_msgs_; move_group_.computeCartesianPath(waypoints_, eef_step_, 0.0, trajectory_msgs_); robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()}; robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_); trajectory_processing::IterativeParabolicTimeParameterization iptp; iptp.computeTimeStamps(robot_trajectory_); robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_); moveit::planning_interface::MoveGroup::Plan motion_plan_; motion_plan_.trajectory_ = trajectory_msgs_; return move_group_.execute(motion_plan_); } bool baseShift() { double tmp; try { geometry_msgs::TransformStamped transform_stamped {buffer_.lookupTransform("rail", "shaft", ros::Time(0), ros::Duration(1.0))}; tmp = transform_stamped.transform.translation.y; if (tmp > (abs_rail_length_ - 1.0)) sign_ = -1.0; else if (tmp < -(abs_rail_length_ - 1.0)) sign_ = 1.0; } catch (const tf2::TransformException& ex) { ROS_INFO_STREAM(ex.what()); return false; } // auto named_target_values = move_group_.getNamedTargetValues("init"); // named_target_values["rail_to_shaft_joint"] += (sign_ * 1.0); // move_group_.setJointValueTarget(named_target_values); // move_group_.setNamedTarget("init"); std::vector<double> joint_values = move_group_.getCurrentJointValues(); // auto joint_model_group = move_group_.getCurrentState()->getRobotModel()->getJointModelGroup(move_group_.getName()); // move_group_.getCurrentState()->copyJointGroupPositions(joint_model_group, joint_values); // joint_values[0] += sign_ * 1.0; // joint_values[1] = -0.3927; joint_values[1] = 0; joint_values[2] = -0.7854; joint_values[3] = 1.5707; joint_values[4] = -0.7854; joint_values[5] = 0; move_group_.setJointValueTarget(joint_values); moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); move_group_.execute(plan); joint_values[0] += sign_ * 1.0; // joint_values[1] = -0.3927; joint_values[1] = 0; joint_values[2] = -0.7854; joint_values[3] = 1.5707; joint_values[4] = -0.7854; joint_values[5] = 0; move_group_.setJointValueTarget(joint_values); // moveit::planning_interface::MoveGroup::Plan plan; move_group_.plan(plan); return move_group_.execute(plan); } }; int main(int argc, char** argv) { ros::init(argc, argv, "arcsys2_move_group_interface_node"); ros::NodeHandle node_handle {"~"}; ros::AsyncSpinner spinner {1}; spinner.start(); MoveGroupInterface interface {"arcsys2", node_handle.param("joint_tolerance", 0.1)}; while (ros::ok()) { while (!interface.queryTargetExistence()) interface.baseShift(); interface.startSequence(); } spinner.stop(); return 0; } <|endoftext|>
<commit_before>/* * * Copyright (c) 2019 Nest Labs, Inc. * 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. */ /** * @file * Contains non-inline method definitions for the * GenericThreadStackManagerImpl_FreeRTOS<> template. */ #ifndef GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP #define GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP #include <Weave/DeviceLayer/internal/WeaveDeviceLayerInternal.h> #include <Weave/DeviceLayer/ThreadStackManager.h> #include <Weave/DeviceLayer/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h> namespace nl { namespace Weave { namespace DeviceLayer { namespace Internal { // Fully instantiate the generic implementation class in whatever compilation unit includes this file. template class GenericThreadStackManagerImpl_FreeRTOS<ThreadStackManagerImpl>; template<class ImplClass> WEAVE_ERROR GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::DoInit(void) { WEAVE_ERROR err = WEAVE_NO_ERROR; mThreadStackLock = xSemaphoreCreateMutex(); if (mThreadStackLock == NULL) { WeaveLogError(DeviceLayer, "Failed to create Thread stack lock"); ExitNow(err = WEAVE_ERROR_NO_MEMORY); } mThreadTask = NULL; exit: return err; } template<class ImplClass> WEAVE_ERROR GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_StartThreadTask(void) { WEAVE_ERROR err = WEAVE_NO_ERROR; BaseType_t res; VerifyOrExit(mThreadTask == NULL, err = WEAVE_ERROR_INCORRECT_STATE); res = xTaskCreate(ThreadTaskMain, WEAVE_DEVICE_CONFIG_THREAD_TASK_NAME, WEAVE_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE / sizeof(StackType_t), this, WEAVE_DEVICE_CONFIG_THREAD_TASK_PRIORITY, NULL); VerifyOrExit(res == pdPASS, err = WEAVE_ERROR_NO_MEMORY); exit: return err; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_LockThreadStack(void) { xSemaphoreTake(mThreadStackLock, portMAX_DELAY); } template<class ImplClass> bool GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_TryLockThreadStack(void) { return xSemaphoreTake(mThreadStackLock, 0) == pdTRUE; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_UnlockThreadStack(void) { xSemaphoreGive(mThreadStackLock); } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::SignalThreadActivityPending() { if (mThreadTask != NULL) { xTaskNotifyGive(mThreadTask); } } template<class ImplClass> BaseType_t GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::SignalThreadActivityPendingFromISR() { BaseType_t yieldRequired = pdFALSE; if (mThreadTask != NULL) { vTaskNotifyGiveFromISR(mThreadTask, &yieldRequired); } return yieldRequired; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::ThreadTaskMain(void * arg) { GenericThreadStackManagerImpl_FreeRTOS<ImplClass> * self = static_cast<GenericThreadStackManagerImpl_FreeRTOS<ImplClass>*>(arg); VerifyOrDie(self->mThreadTask == NULL); WeaveLogDetail(DeviceLayer, "Thread task running"); // Capture the Thread task handle. self->mThreadTask = xTaskGetCurrentTaskHandle(); while (true) { // Lock the Thread stack. self->Impl()->LockThreadStack(); // Process any pending Thread activity. self->Impl()->ProcessThreadActivity(); // Unlock the Thread stack. self->Impl()->UnlockThreadStack(); // Wait for a signal that more activity is pending. ulTaskNotifyTake(pdTRUE, portMAX_DELAY); } } } // namespace Internal } // namespace DeviceLayer } // namespace Weave } // namespace nl #endif // GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP <commit_msg>Update GenericThreadStackManagerImpl_FreeRTOS<commit_after>/* * * Copyright (c) 2019 Nest Labs, Inc. * 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. */ /** * @file * Contains non-inline method definitions for the * GenericThreadStackManagerImpl_FreeRTOS<> template. */ #ifndef GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP #define GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP #include <Weave/DeviceLayer/internal/WeaveDeviceLayerInternal.h> #include <Weave/DeviceLayer/ThreadStackManager.h> #include <Weave/DeviceLayer/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h> namespace nl { namespace Weave { namespace DeviceLayer { namespace Internal { // Fully instantiate the generic implementation class in whatever compilation unit includes this file. template class GenericThreadStackManagerImpl_FreeRTOS<ThreadStackManagerImpl>; template<class ImplClass> WEAVE_ERROR GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::DoInit(void) { WEAVE_ERROR err = WEAVE_NO_ERROR; mThreadStackLock = xSemaphoreCreateRecursiveMutex(); if (mThreadStackLock == NULL) { WeaveLogError(DeviceLayer, "Failed to create Thread stack lock"); ExitNow(err = WEAVE_ERROR_NO_MEMORY); } mThreadTask = NULL; exit: return err; } template<class ImplClass> WEAVE_ERROR GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_StartThreadTask(void) { WEAVE_ERROR err = WEAVE_NO_ERROR; BaseType_t res; VerifyOrExit(mThreadTask == NULL, err = WEAVE_ERROR_INCORRECT_STATE); res = xTaskCreate(ThreadTaskMain, WEAVE_DEVICE_CONFIG_THREAD_TASK_NAME, WEAVE_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE / sizeof(StackType_t), this, WEAVE_DEVICE_CONFIG_THREAD_TASK_PRIORITY, NULL); VerifyOrExit(res == pdPASS, err = WEAVE_ERROR_NO_MEMORY); exit: return err; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_LockThreadStack(void) { xSemaphoreTakeRecursive(mThreadStackLock, portMAX_DELAY); } template<class ImplClass> bool GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_TryLockThreadStack(void) { return xSemaphoreTakeRecursive(mThreadStackLock, 0) == pdTRUE; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::_UnlockThreadStack(void) { xSemaphoreGiveRecursive(mThreadStackLock); } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::SignalThreadActivityPending() { if (mThreadTask != NULL) { xTaskNotifyGive(mThreadTask); } } template<class ImplClass> BaseType_t GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::SignalThreadActivityPendingFromISR() { BaseType_t yieldRequired = pdFALSE; if (mThreadTask != NULL) { vTaskNotifyGiveFromISR(mThreadTask, &yieldRequired); } return yieldRequired; } template<class ImplClass> void GenericThreadStackManagerImpl_FreeRTOS<ImplClass>::ThreadTaskMain(void * arg) { GenericThreadStackManagerImpl_FreeRTOS<ImplClass> * self = static_cast<GenericThreadStackManagerImpl_FreeRTOS<ImplClass>*>(arg); VerifyOrDie(self->mThreadTask == NULL); WeaveLogDetail(DeviceLayer, "Thread task running"); // Capture the Thread task handle. self->mThreadTask = xTaskGetCurrentTaskHandle(); while (true) { // Lock the Thread stack. self->Impl()->LockThreadStack(); // Process any pending Thread activity. self->Impl()->ProcessThreadActivity(); // Unlock the Thread stack. self->Impl()->UnlockThreadStack(); // Wait for a signal that more activity is pending. ulTaskNotifyTake(pdTRUE, portMAX_DELAY); } } } // namespace Internal } // namespace DeviceLayer } // namespace Weave } // namespace nl #endif // GENERIC_THREAD_STACK_MANAGER_IMPL_FREERTOS_IPP <|endoftext|>
<commit_before>/************************************************************************* * * 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: kill.cxx,v $ * $Revision: 1.7 $ * * 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_sal.hxx" #include <tchar.h> #ifdef _MSC_VER #pragma warning(push,1) // disable warnings within system headers #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <tlhelp32.h> #include <psapi.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <signal.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #ifndef SIGNULL #define SIGNULL 0 #endif #ifndef SIGKILL #define SIGKILL 9 #endif #include <signal.h> #define MAX_MODULES 1024 ///////////////////////////////////////////////////////////////////////////// // Determines if a returned handle value is valid ///////////////////////////////////////////////////////////////////////////// static inline bool IsValidHandle( HANDLE handle ) { return INVALID_HANDLE_VALUE != handle && NULL != handle; } #define elementsof( a ) (sizeof(a) / sizeof( (a)[0] )) ///////////////////////////////////////////////////////////////////////////// // Retrieves function adress in another process ///////////////////////////////////////////////////////////////////////////// #if 1 #define GetProcAddressEx( hProcess, hModule, lpProcName ) GetProcAddress( hModule, lpProcName ) #else FARPROC WINAPI GetProcAddressEx( HANDLE hProcess, HMODULE hModule, LPCSTR lpProcName ) { FARPROC lpfnProcAddress = GetProcAddress( hModule, lpProcName ); if ( lpfnProcAddress ) { DWORD dwProcessId = GetProcessId( hProcess ); if ( GetCurrentProcessId() != dwProcessId ) { FARPROC lpfnRemoteProcAddress = NULL; TCHAR szBaseName[MAX_PATH]; if ( GetModuleBaseName( GetCurrentProcess(), hModule, szBaseName, elementsof(szBaseName) ) ) { HMODULE ahModules[MAX_MODULES]; DWORD cbNeeded = 0; if ( EnumProcessModules( hProcess, ahModules, sizeof(ahModules), &cbNeeded ) ) { ULONG nModules = cbNeeded / sizeof(ahModules[0]); for ( ULONG n = 0; n < nModules; n++ ) { TCHAR szRemoteBaseName[MAX_PATH]; if ( GetModuleBaseName( hProcess, ahModules[n], szRemoteBaseName, elementsof(szRemoteBaseName) ) && 0 == lstrcmpi( szRemoteBaseName, szBaseName ) ) { lpfnRemoteProcAddress = lpfnProcAddress; if ( ahModules[n] != hModule ) *(LPBYTE*)&lpfnRemoteProcAddress += (LPBYTE)ahModules[n] - (LPBYTE)hModule; break; } } } } lpfnProcAddress = lpfnRemoteProcAddress; } } return lpfnProcAddress; } #endif ///////////////////////////////////////////////////////////////////////////// // Raises a signal in an other process ///////////////////////////////////////////////////////////////////////////// static DWORD SignalToExceptionCode( int signal ) { switch ( signal ) { case SIGSEGV: return EXCEPTION_ACCESS_VIOLATION; case SIGFPE: return EXCEPTION_FLT_INVALID_OPERATION; case SIGILL: return EXCEPTION_ILLEGAL_INSTRUCTION; case SIGINT: return CONTROL_C_EXIT; case SIGBREAK: return CONTROL_C_EXIT; default: return 0; } } static void RaiseSignalEx( HANDLE hProcess, int sig ) { DWORD dwProcessId = GetProcessId( hProcess ); HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); HANDLE hThread = 0; if ( IsValidHandle(hSnapshot) ) { THREADENTRY32 te; te.dwSize = sizeof(te); BOOL fSuccess = Thread32First( hSnapshot, &te ); while ( fSuccess ) { if ( te.th32OwnerProcessID == dwProcessId ) { hThread = OpenThread( THREAD_ALL_ACCESS, FALSE, te.th32ThreadID ); break; } fSuccess = Thread32Next( hSnapshot, &te ); } CloseHandle( hSnapshot ); } CONTEXT aContext; SuspendThread( hThread ); ZeroMemory( &aContext, sizeof(aContext) ); aContext.ContextFlags = CONTEXT_FULL; GetThreadContext( hThread, &aContext ); if ( sig ) { DWORD dwStackBuffer[] = { aContext.Eip, SignalToExceptionCode( sig ), EXCEPTION_NONCONTINUABLE, 0, 0 }; aContext.Esp -= sizeof(dwStackBuffer); WriteProcessMemory( hProcess, (LPVOID)aContext.Esp, dwStackBuffer, sizeof(dwStackBuffer), NULL ); aContext.Eip = (DWORD)GetProcAddressEx( hProcess, GetModuleHandleA("KERNEL32"), "RaiseException" ); } else { aContext.Ecx = aContext.Eax = aContext.Ebx = aContext.Edx = aContext.Esi = aContext.Edi = 0; } SetThreadContext( hThread, &aContext ); ResumeThread( hThread ); } ///////////////////////////////////////////////////////////////////////////// // Command line parameter parsing ///////////////////////////////////////////////////////////////////////////// static void ParseCommandArgs( LPDWORD lpProcesses, LPDWORD lpdwNumProcesses, int *pSig ) { typedef struct _SignalEntry { LPCTSTR lpSignalName; int iSignalValue; } SignalEntry; #define SIG_ENTRY( signal ) { TEXT(#signal), SIG##signal } static SignalEntry SupportedSignals[] = { SIG_ENTRY( NULL ), SIG_ENTRY( SEGV ), SIG_ENTRY( ILL ), SIG_ENTRY( FPE ), SIG_ENTRY( INT ), SIG_ENTRY( BREAK ), SIG_ENTRY( TERM ), SIG_ENTRY( ABRT ), SIG_ENTRY( KILL ) }; const int NumSupportedSignals = elementsof(SupportedSignals); DWORD dwMaxProcesses = *lpdwNumProcesses; int argc = __argc; TCHAR **argv = __targv; *lpdwNumProcesses = 0; for ( int argn = 1; argn < argc; argn++ ) { if ( 0 == lstrcmpi( argv[argn], TEXT("-l") ) || 0 == lstrcmpi( argv[argn], TEXT("/l") ) ) { for ( int n = 0; n < NumSupportedSignals; n++ ) { _tprintf( _T("%s "), SupportedSignals[n] ); } _tprintf( _T("\n") ); ExitProcess( 0 ); } else if ( 0 == lstrcmpi( argv[argn], TEXT("-?") ) || 0 == lstrcmpi( argv[argn], TEXT("/?") ) || 0 == lstrcmpi( argv[argn], TEXT("-h") ) || 0 == lstrcmpi( argv[argn], TEXT("/h") ) || 0 == lstrcmpi( argv[argn], TEXT("--help") ) ) { _tprintf( _T("Terminates a process by sending a signal.\n\n") _T("Usage: kill [ -l ] [ -signal ] pid ...\n\n") _T("-l Lists supported signals\n") _T("-signal Sends the specified signal to the given processes.\n") _T(" signal can be a numeric value specifying the signal number\n") _T(" or a string listed by the -l parameter. If no signal is\n") _T(" given SIGTERM (-TERM) is used.\n") _T("pid Process id(s) or executables names(s) of processes to \n") _T(" signal or terminate.\n\n") ); ExitProcess( 0 ); } else if ( argv[argn] && ( *argv[argn] == '-' || *argv[argn] == '/' ) ) { LPCTSTR argsig = CharNext( argv[argn] ); int n; for ( n = 0; n < NumSupportedSignals; n++ ) { _TCHAR *endptr = NULL; if ( 0 == lstrcmpi( SupportedSignals[n].lpSignalName, argsig ) || _tcstoul( argsig, &endptr, 0 ) == static_cast< unsigned >(SupportedSignals[n].iSignalValue) && (!endptr || !*endptr) ) { *pSig = SupportedSignals[n].iSignalValue; break; } } if ( n >= NumSupportedSignals ) { _ftprintf( stderr, _T("kill: Illegal argument %s\n") _T("Type 'kill --help' to show allowed syntax.\n") _T("Type 'kill -l' to show supported signals.\n"), argv[argn] ); ExitProcess( 0 ); } } else { unsigned long value = 0; _TCHAR *endptr = NULL; value = _tcstoul( argv[argn], &endptr, 0 ); if ( !endptr || !*endptr ) { if ( *lpdwNumProcesses < dwMaxProcesses ) { *(lpProcesses++) = value; (*lpdwNumProcesses)++; } } else { HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if ( IsValidHandle( hSnapshot ) ) { PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); BOOL fSuccess = Process32First( hSnapshot, &pe ); while ( fSuccess ) { if ( 0 == lstrcmpi( argv[argn], pe.szExeFile ) ) { if ( *lpdwNumProcesses < dwMaxProcesses ) { *(lpProcesses++) = pe.th32ProcessID; (*lpdwNumProcesses)++; } } fSuccess = Process32Next( hSnapshot, &pe ); } CloseHandle( hSnapshot ); } } } } if ( !*lpdwNumProcesses ) { _ftprintf( stderr, _T("kill: No process specified.\n") _T("Use kill --help to show allowed syntax.\n") ); ExitProcess( 0 ); } } int _tmain() { DWORD dwProcessIds[1024]; DWORD nProcesses = elementsof(dwProcessIds); int sig = SIGTERM; ParseCommandArgs( dwProcessIds, &nProcesses, &sig ); for ( ULONG n = 0; n < nProcesses; n++ ) { HANDLE hProcess; _tprintf( _T("Sending signal to process id %d..."), dwProcessIds[n] ); hProcess = OpenProcess( PROCESS_TERMINATE | PROCESS_CREATE_THREAD | SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessIds[n] ); if ( IsValidHandle( hProcess ) ) { RaiseSignalEx( hProcess, sig ); _tprintf( _T("Done\n") ); CloseHandle( hProcess ); } else _ftprintf( stderr, _T("No such process\n") ); } return 0; } <commit_msg>INTEGRATION: CWS qadev32 (1.7.2); FILE MERGED 2008/04/18 14:11:32 hro 1.7.2.1: #i86802# Support kill -9<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: kill.cxx,v $ * $Revision: 1.8 $ * * 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_sal.hxx" #include <tchar.h> #ifdef _MSC_VER #pragma warning(push,1) // disable warnings within system headers #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <tlhelp32.h> #include <psapi.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <signal.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #ifndef SIGNULL #define SIGNULL 0 #endif #ifndef SIGKILL #define SIGKILL 9 #endif #include <signal.h> #define MAX_MODULES 1024 ///////////////////////////////////////////////////////////////////////////// // Determines if a returned handle value is valid ///////////////////////////////////////////////////////////////////////////// static inline bool IsValidHandle( HANDLE handle ) { return INVALID_HANDLE_VALUE != handle && NULL != handle; } #define elementsof( a ) (sizeof(a) / sizeof( (a)[0] )) ///////////////////////////////////////////////////////////////////////////// // Retrieves function adress in another process ///////////////////////////////////////////////////////////////////////////// #if 1 #define GetProcAddressEx( hProcess, hModule, lpProcName ) GetProcAddress( hModule, lpProcName ) #else FARPROC WINAPI GetProcAddressEx( HANDLE hProcess, HMODULE hModule, LPCSTR lpProcName ) { FARPROC lpfnProcAddress = GetProcAddress( hModule, lpProcName ); if ( lpfnProcAddress ) { DWORD dwProcessId = GetProcessId( hProcess ); if ( GetCurrentProcessId() != dwProcessId ) { FARPROC lpfnRemoteProcAddress = NULL; TCHAR szBaseName[MAX_PATH]; if ( GetModuleBaseName( GetCurrentProcess(), hModule, szBaseName, elementsof(szBaseName) ) ) { HMODULE ahModules[MAX_MODULES]; DWORD cbNeeded = 0; if ( EnumProcessModules( hProcess, ahModules, sizeof(ahModules), &cbNeeded ) ) { ULONG nModules = cbNeeded / sizeof(ahModules[0]); for ( ULONG n = 0; n < nModules; n++ ) { TCHAR szRemoteBaseName[MAX_PATH]; if ( GetModuleBaseName( hProcess, ahModules[n], szRemoteBaseName, elementsof(szRemoteBaseName) ) && 0 == lstrcmpi( szRemoteBaseName, szBaseName ) ) { lpfnRemoteProcAddress = lpfnProcAddress; if ( ahModules[n] != hModule ) *(LPBYTE*)&lpfnRemoteProcAddress += (LPBYTE)ahModules[n] - (LPBYTE)hModule; break; } } } } lpfnProcAddress = lpfnRemoteProcAddress; } } return lpfnProcAddress; } #endif ///////////////////////////////////////////////////////////////////////////// // Raises a signal in an other process ///////////////////////////////////////////////////////////////////////////// static DWORD SignalToExceptionCode( int signal ) { switch ( signal ) { case SIGSEGV: return EXCEPTION_ACCESS_VIOLATION; case SIGFPE: return EXCEPTION_FLT_INVALID_OPERATION; case SIGILL: return EXCEPTION_ILLEGAL_INSTRUCTION; case SIGINT: return CONTROL_C_EXIT; case SIGBREAK: return CONTROL_C_EXIT; default: return 0; } } static void RaiseSignalEx( HANDLE hProcess, int sig ) { DWORD dwProcessId = GetProcessId( hProcess ); HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); HANDLE hThread = 0; if ( IsValidHandle(hSnapshot) ) { THREADENTRY32 te; te.dwSize = sizeof(te); BOOL fSuccess = Thread32First( hSnapshot, &te ); while ( fSuccess ) { if ( te.th32OwnerProcessID == dwProcessId ) { hThread = OpenThread( THREAD_ALL_ACCESS, FALSE, te.th32ThreadID ); break; } fSuccess = Thread32Next( hSnapshot, &te ); } CloseHandle( hSnapshot ); } CONTEXT aContext; SuspendThread( hThread ); ZeroMemory( &aContext, sizeof(aContext) ); aContext.ContextFlags = CONTEXT_FULL; GetThreadContext( hThread, &aContext ); if ( sig ) { DWORD dwStackBuffer[] = { aContext.Eip, SignalToExceptionCode( sig ), EXCEPTION_NONCONTINUABLE, 0, 0 }; aContext.Esp -= sizeof(dwStackBuffer); WriteProcessMemory( hProcess, (LPVOID)aContext.Esp, dwStackBuffer, sizeof(dwStackBuffer), NULL ); aContext.Eip = (DWORD)GetProcAddressEx( hProcess, GetModuleHandleA("KERNEL32"), "RaiseException" ); } else { aContext.Ecx = aContext.Eax = aContext.Ebx = aContext.Edx = aContext.Esi = aContext.Edi = 0; } SetThreadContext( hThread, &aContext ); ResumeThread( hThread ); } ///////////////////////////////////////////////////////////////////////////// // Command line parameter parsing ///////////////////////////////////////////////////////////////////////////// static void ParseCommandArgs( LPDWORD lpProcesses, LPDWORD lpdwNumProcesses, int *pSig ) { typedef struct _SignalEntry { LPCTSTR lpSignalName; int iSignalValue; } SignalEntry; #define SIG_ENTRY( signal ) { TEXT(#signal), SIG##signal } static SignalEntry SupportedSignals[] = { SIG_ENTRY( NULL ), SIG_ENTRY( SEGV ), SIG_ENTRY( ILL ), SIG_ENTRY( FPE ), SIG_ENTRY( INT ), SIG_ENTRY( BREAK ), SIG_ENTRY( TERM ), SIG_ENTRY( ABRT ), SIG_ENTRY( KILL ) }; const int NumSupportedSignals = elementsof(SupportedSignals); DWORD dwMaxProcesses = *lpdwNumProcesses; int argc = __argc; TCHAR **argv = __targv; *lpdwNumProcesses = 0; for ( int argn = 1; argn < argc; argn++ ) { if ( 0 == lstrcmpi( argv[argn], TEXT("-l") ) || 0 == lstrcmpi( argv[argn], TEXT("/l") ) ) { for ( int n = 0; n < NumSupportedSignals; n++ ) { _tprintf( _T("%s "), SupportedSignals[n] ); } _tprintf( _T("\n") ); ExitProcess( 0 ); } else if ( 0 == lstrcmpi( argv[argn], TEXT("-?") ) || 0 == lstrcmpi( argv[argn], TEXT("/?") ) || 0 == lstrcmpi( argv[argn], TEXT("-h") ) || 0 == lstrcmpi( argv[argn], TEXT("/h") ) || 0 == lstrcmpi( argv[argn], TEXT("--help") ) ) { _tprintf( _T("Terminates a process by sending a signal.\n\n") _T("Usage: kill [ -l ] [ -signal ] pid ...\n\n") _T("-l Lists supported signals\n") _T("-signal Sends the specified signal to the given processes.\n") _T(" signal can be a numeric value specifying the signal number\n") _T(" or a string listed by the -l parameter. If no signal is\n") _T(" given SIGTERM (-TERM) is used.\n") _T("pid Process id(s) or executables names(s) of processes to \n") _T(" signal or terminate.\n\n") ); ExitProcess( 0 ); } else if ( argv[argn] && ( *argv[argn] == '-' || *argv[argn] == '/' ) ) { LPCTSTR argsig = CharNext( argv[argn] ); int n; for ( n = 0; n < NumSupportedSignals; n++ ) { _TCHAR *endptr = NULL; if ( 0 == lstrcmpi( SupportedSignals[n].lpSignalName, argsig ) || _tcstoul( argsig, &endptr, 0 ) == static_cast< unsigned >(SupportedSignals[n].iSignalValue) && (!endptr || !*endptr) ) { *pSig = SupportedSignals[n].iSignalValue; break; } } if ( n >= NumSupportedSignals ) { _ftprintf( stderr, _T("kill: Illegal argument %s\n") _T("Type 'kill --help' to show allowed syntax.\n") _T("Type 'kill -l' to show supported signals.\n"), argv[argn] ); ExitProcess( 0 ); } } else { unsigned long value = 0; _TCHAR *endptr = NULL; value = _tcstoul( argv[argn], &endptr, 0 ); if ( !endptr || !*endptr ) { if ( *lpdwNumProcesses < dwMaxProcesses ) { *(lpProcesses++) = value; (*lpdwNumProcesses)++; } } else { HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if ( IsValidHandle( hSnapshot ) ) { PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); BOOL fSuccess = Process32First( hSnapshot, &pe ); while ( fSuccess ) { if ( 0 == lstrcmpi( argv[argn], pe.szExeFile ) ) { if ( *lpdwNumProcesses < dwMaxProcesses ) { *(lpProcesses++) = pe.th32ProcessID; (*lpdwNumProcesses)++; } } fSuccess = Process32Next( hSnapshot, &pe ); } CloseHandle( hSnapshot ); } } } } if ( !*lpdwNumProcesses ) { _ftprintf( stderr, _T("kill: No process specified.\n") _T("Use kill --help to show allowed syntax.\n") ); ExitProcess( 0 ); } } int _tmain() { DWORD dwProcessIds[1024]; DWORD nProcesses = elementsof(dwProcessIds); int sig = SIGTERM; ParseCommandArgs( dwProcessIds, &nProcesses, &sig ); for ( ULONG n = 0; n < nProcesses; n++ ) { HANDLE hProcess; _tprintf( _T("Sending signal to process id %d..."), dwProcessIds[n] ); hProcess = OpenProcess( PROCESS_TERMINATE | PROCESS_CREATE_THREAD | SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessIds[n] ); if ( IsValidHandle( hProcess ) ) { if ( SIGKILL == sig ) TerminateProcess( hProcess, 255 ); else RaiseSignalEx( hProcess, sig ); _tprintf( _T("Done\n") ); CloseHandle( hProcess ); } else _ftprintf( stderr, _T("No such process\n") ); } return 0; } <|endoftext|>
<commit_before>/* * matching_test.cpp * * Created on: Oct 17, 2010 * Author: ethan */ #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <vector> #include <iostream> using namespace cv; using std::cout; using std::cerr; using std::endl; using std::vector; void help(char **av) { cerr << "usage: " << av[0] << " im1.jpg im2.jpg" << "\n" << "This program shows how to use BRIEF descriptor to match points in features2d\n" << "It takes in two images, finds keypoints and matches them displaying matches and final homography warped results\n" << endl; } //Copy (x,y) location of descriptor matches found from KeyPoint data structures into Point2f vectors void matches2points(const vector<DMatch>& matches, const vector<KeyPoint>& kpts_train, const vector<KeyPoint>& kpts_query, vector<Point2f>& pts_train, vector<Point2f>& pts_query) { pts_train.clear(); pts_query.clear(); pts_train.reserve(matches.size()); pts_query.reserve(matches.size()); for (size_t i = 0; i < matches.size(); i++) { const DMatch& match = matches[i]; pts_query.push_back(kpts_query[match.queryIdx].pt); pts_train.push_back(kpts_train[match.trainIdx].pt); } } double match(const vector<KeyPoint>& /*kpts_train*/, const vector<KeyPoint>& /*kpts_query*/, DescriptorMatcher& matcher, const Mat& train, const Mat& query, vector<DMatch>& matches) { double t = (double)getTickCount(); matcher.match(query, train, matches); //Using features2d return ((double)getTickCount() - t) / getTickFrequency(); } int main(int ac, char ** av) { if (ac != 3) { help(av); return 1; } string im1_name, im2_name; im1_name = av[1]; im2_name = av[2]; Mat im1 = imread(im1_name, CV_LOAD_IMAGE_GRAYSCALE); Mat im2 = imread(im2_name, CV_LOAD_IMAGE_GRAYSCALE); if (im1.empty() || im2.empty()) { cerr << "could not open one of the images..." << endl; return 1; } double t = (double)getTickCount(); FastFeatureDetector detector(50); BriefDescriptorExtractor extractor(32); //this is really 32 x 8 matches since they are binary matches packed into bytes vector<KeyPoint> kpts_1, kpts_2; detector.detect(im1, kpts_1); detector.detect(im2, kpts_2); t = ((double)getTickCount() - t) / getTickFrequency(); cout << "found " << kpts_1.size() << " keypoints in " << im1_name << endl << "fount " << kpts_2.size() << " keypoints in " << im2_name << endl << "took " << t << " seconds." << endl; Mat desc_1, desc_2; cout << "computing descriptors..." << endl; t = (double)getTickCount(); extractor.compute(im1, kpts_1, desc_1); extractor.compute(im2, kpts_2, desc_2); t = ((double)getTickCount() - t) / getTickFrequency(); cout << "done computing descriptors... took " << t << " seconds" << endl; //Do matching with 2 methods using features2d cout << "matching with BruteForceMatcher<HammingLUT>" << endl; BruteForceMatcher<HammingLUT> matcher; vector<DMatch> matches_lut; float lut_time = (float)match(kpts_1, kpts_2, matcher, desc_1, desc_2, matches_lut); cout << "done BruteForceMatcher<HammingLUT> matching. took " << lut_time << " seconds" << endl; cout << "matching with BruteForceMatcher<Hamming>" << endl; BruteForceMatcher<Hamming> matcher_popcount; vector<DMatch> matches_popcount; double pop_time = match(kpts_1, kpts_2, matcher_popcount, desc_1, desc_2, matches_popcount); cout << "done BruteForceMatcher<Hamming> matching. took " << pop_time << " seconds" << endl; vector<Point2f> mpts_1, mpts_2; matches2points(matches_popcount, kpts_1, kpts_2, mpts_1, mpts_2); //Extract a list of the (x,y) location of the matches vector<uchar> outlier_mask; Mat H = findHomography(mpts_2, mpts_1, RANSAC, 1, outlier_mask); Mat outimg; drawMatches(im2, kpts_2, im1, kpts_1, matches_popcount, outimg, Scalar::all(-1), Scalar::all(-1), reinterpret_cast<const vector<char>&> (outlier_mask)); imshow("matches - popcount - outliers removed", outimg); Mat warped; warpPerspective(im2, warped, H, im1.size()); imshow("warped", warped); imshow("diff", im1 - warped); waitKey(); return 0; } <commit_msg>Fix a litte bug on matrix subtraction<commit_after>/* * matching_test.cpp * * Created on: Oct 17, 2010 * Author: ethan */ #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <vector> #include <iostream> using namespace cv; using std::cout; using std::cerr; using std::endl; using std::vector; void help(char **av) { cerr << "usage: " << av[0] << " im1.jpg im2.jpg" << "\n" << "This program shows how to use BRIEF descriptor to match points in features2d\n" << "It takes in two images, finds keypoints and matches them displaying matches and final homography warped results\n" << endl; } //Copy (x,y) location of descriptor matches found from KeyPoint data structures into Point2f vectors void matches2points(const vector<DMatch>& matches, const vector<KeyPoint>& kpts_train, const vector<KeyPoint>& kpts_query, vector<Point2f>& pts_train, vector<Point2f>& pts_query) { pts_train.clear(); pts_query.clear(); pts_train.reserve(matches.size()); pts_query.reserve(matches.size()); for (size_t i = 0; i < matches.size(); i++) { const DMatch& match = matches[i]; pts_query.push_back(kpts_query[match.queryIdx].pt); pts_train.push_back(kpts_train[match.trainIdx].pt); } } double match(const vector<KeyPoint>& /*kpts_train*/, const vector<KeyPoint>& /*kpts_query*/, DescriptorMatcher& matcher, const Mat& train, const Mat& query, vector<DMatch>& matches) { double t = (double)getTickCount(); matcher.match(query, train, matches); //Using features2d return ((double)getTickCount() - t) / getTickFrequency(); } int main(int ac, char ** av) { if (ac != 3) { help(av); return 1; } string im1_name, im2_name; im1_name = av[1]; im2_name = av[2]; Mat im1 = imread(im1_name, CV_LOAD_IMAGE_GRAYSCALE); Mat im2 = imread(im2_name, CV_LOAD_IMAGE_GRAYSCALE); if (im1.empty() || im2.empty()) { cerr << "could not open one of the images..." << endl; return 1; } double t = (double)getTickCount(); FastFeatureDetector detector(50); BriefDescriptorExtractor extractor(32); //this is really 32 x 8 matches since they are binary matches packed into bytes vector<KeyPoint> kpts_1, kpts_2; detector.detect(im1, kpts_1); detector.detect(im2, kpts_2); t = ((double)getTickCount() - t) / getTickFrequency(); cout << "found " << kpts_1.size() << " keypoints in " << im1_name << endl << "fount " << kpts_2.size() << " keypoints in " << im2_name << endl << "took " << t << " seconds." << endl; Mat desc_1, desc_2; cout << "computing descriptors..." << endl; t = (double)getTickCount(); extractor.compute(im1, kpts_1, desc_1); extractor.compute(im2, kpts_2, desc_2); t = ((double)getTickCount() - t) / getTickFrequency(); cout << "done computing descriptors... took " << t << " seconds" << endl; //Do matching with 2 methods using features2d cout << "matching with BruteForceMatcher<HammingLUT>" << endl; BruteForceMatcher<HammingLUT> matcher; vector<DMatch> matches_lut; float lut_time = (float)match(kpts_1, kpts_2, matcher, desc_1, desc_2, matches_lut); cout << "done BruteForceMatcher<HammingLUT> matching. took " << lut_time << " seconds" << endl; cout << "matching with BruteForceMatcher<Hamming>" << endl; BruteForceMatcher<Hamming> matcher_popcount; vector<DMatch> matches_popcount; double pop_time = match(kpts_1, kpts_2, matcher_popcount, desc_1, desc_2, matches_popcount); cout << "done BruteForceMatcher<Hamming> matching. took " << pop_time << " seconds" << endl; vector<Point2f> mpts_1, mpts_2; matches2points(matches_popcount, kpts_1, kpts_2, mpts_1, mpts_2); //Extract a list of the (x,y) location of the matches vector<uchar> outlier_mask; Mat H = findHomography(mpts_2, mpts_1, RANSAC, 1, outlier_mask); Mat outimg; drawMatches(im2, kpts_2, im1, kpts_1, matches_popcount, outimg, Scalar::all(-1), Scalar::all(-1), reinterpret_cast<const vector<char>&> (outlier_mask)); imshow("matches - popcount - outliers removed", outimg); Mat warped; Mat diff; warpPerspective(im2, warped, H, im1.size()); imshow("warped", warped); absdiff(im1,warped,diff); imshow("diff", diff); waitKey(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lotus.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2006-07-21 12:28:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "lotimpop.hxx" #include <sfx2/docfile.hxx> #include <tools/urlobj.hxx> #include "scerrors.hxx" #include "root.hxx" #include "filtopt.hxx" //------------------------------------------------------------------------ extern FltError ScImportLotus123old( SvStream&, ScDocument*, CharSet eSrc ); // alter Krempel in filter.cxx! FltError ScImportLotus123( SfxMedium& rMedium, ScDocument* pDocument, CharSet eSrc ) { ScFilterOptions aFilterOpt; BOOL bWithWK3 = aFilterOpt.GetWK3Flag(); SvStream* pStream = rMedium.GetInStream(); if( !pStream ) return eERR_OPEN; FltError eRet; pStream->Seek( 0UL ); pStream->SetBufferSize( 32768 ); ImportLotus aLotusImport( *pStream, pDocument, eSrc ); if( bWithWK3 ) eRet = aLotusImport.Read(); else eRet = 0xFFFFFFFF; // WK1 /WKS erzwingen // ACHTUNG: QUICK-HACK fuer WK1 / WKS <-> WK3 / WK4 if( eRet == 0xFFFFFFFF ) { SvStream* pStream = rMedium.GetInStream(); if( !pStream ) return eERR_OPEN; pStream->Seek( 0UL ); pStream->SetBufferSize( 32768 ); eRet = ScImportLotus123old( *pStream, pDocument, eSrc ); pStream->SetBufferSize( 0 ); return eRet; } if( eRet != eERR_OK ) return eRet; if( pLotusRoot->eFirstType == Lotus_WK3 ) {// versuchen *.FM3-File zu laden INetURLObject aURL( rMedium.GetURLObject() ); aURL.setExtension( CREATE_STRING( "FM3" ) ); SfxMedium aMedium( aURL.GetMainURL(INetURLObject::NO_DECODE), STREAM_STD_READ, TRUE ); SvStream* pStream = aMedium.GetInStream(); if ( pStream ) { if( aLotusImport.Read( *pStream ) != eERR_OK ) eRet = SCWARN_IMPORT_WRONG_FM3; } else eRet = SCWARN_IMPORT_OPEN_FM3; } return eRet; } <commit_msg>INTEGRATION: CWS calcwarnings (1.8.110); FILE MERGED 2006/12/12 16:42:51 dr 1.8.110.1: #i69284# remove compiler warnings for unxlngi6<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lotus.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:39:05 $ * * 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_sc.hxx" #include "lotimpop.hxx" #include <sfx2/docfile.hxx> #include <tools/urlobj.hxx> #include "scerrors.hxx" #include "root.hxx" #include "filtopt.hxx" //------------------------------------------------------------------------ extern FltError ScImportLotus123old( SvStream&, ScDocument*, CharSet eSrc ); // alter Krempel in filter.cxx! FltError ScImportLotus123( SfxMedium& rMedium, ScDocument* pDocument, CharSet eSrc ) { ScFilterOptions aFilterOpt; BOOL bWithWK3 = aFilterOpt.GetWK3Flag(); SvStream* pStream = rMedium.GetInStream(); if( !pStream ) return eERR_OPEN; FltError eRet; pStream->Seek( 0UL ); pStream->SetBufferSize( 32768 ); ImportLotus aLotusImport( *pStream, pDocument, eSrc ); if( bWithWK3 ) eRet = aLotusImport.Read(); else eRet = 0xFFFFFFFF; // WK1 /WKS erzwingen // ACHTUNG: QUICK-HACK fuer WK1 / WKS <-> WK3 / WK4 if( eRet == 0xFFFFFFFF ) { pStream->Seek( 0UL ); pStream->SetBufferSize( 32768 ); eRet = ScImportLotus123old( *pStream, pDocument, eSrc ); pStream->SetBufferSize( 0 ); return eRet; } if( eRet != eERR_OK ) return eRet; if( pLotusRoot->eFirstType == Lotus_WK3 ) {// versuchen *.FM3-File zu laden INetURLObject aURL( rMedium.GetURLObject() ); aURL.setExtension( CREATE_STRING( "FM3" ) ); SfxMedium aMedium( aURL.GetMainURL(INetURLObject::NO_DECODE), STREAM_STD_READ, TRUE ); pStream = aMedium.GetInStream(); if ( pStream ) { if( aLotusImport.Read( *pStream ) != eERR_OK ) eRet = SCWARN_IMPORT_WRONG_FM3; } else eRet = SCWARN_IMPORT_OPEN_FM3; } return eRet; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docsh7.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:47:22 $ * * 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 * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------- #include "docsh.hxx" //------------------------------------------------------------------ void ScDocShell::GetDrawObjState( SfxItemSet &rSet ) { // SID_SC_ACTIVEOBJECT (SelectedObject) - removed (old Basic) } <commit_msg>INTEGRATION: CWS pchfix01 (1.2.216); FILE MERGED 2006/07/12 10:02:33 kaib 1.2.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docsh7.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-07-21 13:41:31 $ * * 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_sc.hxx" // INCLUDE --------------------------------------------------------- #include "docsh.hxx" //------------------------------------------------------------------ void ScDocShell::GetDrawObjState( SfxItemSet &rSet ) { // SID_SC_ACTIVEOBJECT (SelectedObject) - removed (old Basic) } <|endoftext|>
<commit_before>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <tuple> namespace gnr { namespace detail::invoke { constexpr bool is_nothrow_invocable(auto&& f, auto&& t) noexcept { return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::make_tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( noexcept( detail::invoke::is_nothrow_invocable( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ) ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept( noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N> constexpr bool is_nothrow_split_invocable(auto f, auto&& ...a) noexcept { return noexcept( ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ) ); } } template <std::size_t N> constexpr void invoke_split(auto f, auto&& ...a) noexcept( noexcept( detail::invoke::is_nothrow_split_invocable<N>( f, std::forward<decltype(a)>(a)... ) ) ) { ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <functional> #include <tuple> namespace gnr { namespace detail::invoke { constexpr bool is_nothrow_invocable(auto&& f, auto&& t) noexcept { return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( noexcept( detail::invoke::is_nothrow_invocable( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ) ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept( noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N> constexpr bool is_nothrow_split_invocable(auto f, auto&& ...a) noexcept { return noexcept( ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ) ); } } template <std::size_t N> constexpr void invoke_split(auto f, auto&& ...a) noexcept( noexcept( detail::invoke::is_nothrow_split_invocable<N>( f, std::forward<decltype(a)>(a)... ) ) ) { ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unovwcrs.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-01-20 12:36:52 $ * * 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 _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_ #include <com/sun/star/text/XTextViewCursor.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_ #include <com/sun/star/view/XScreenCursor.hpp> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SVX_LIGHT #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_FU_SLIDE_SHOW_HXX #include "fuslshow.hxx" #endif #include <cppuhelper/implbase2.hxx> using namespace ::vos; using namespace ::rtl; using namespace ::com::sun::star; class SdXTextViewCursor : public ::cppu::WeakImplHelper2< text::XTextViewCursor, view::XScreenCursor > { public: SdXTextViewCursor(::sd::View* pVw) throw(); virtual ~SdXTextViewCursor() throw(); //XTextViewCursor virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException ); virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException ); virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException ); //XTextCursor virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException ); virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException); //XTextRange virtual uno::Reference< text::XText > SAL_CALL getText(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getStart(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getEnd(void) throw( uno::RuntimeException ); virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException ); virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException ); //XScreenCursor virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException ); void Invalidate() { mpView = 0; } private: ::sd::View* mpView; }; text::XTextViewCursor* CreateSdXTextViewCursor(::sd::View* mpView ) { return new SdXTextViewCursor( mpView ); } SdXTextViewCursor::SdXTextViewCursor(::sd::View* pSdView ) throw() : mpView(pSdView) { } SdXTextViewCursor::~SdXTextViewCursor() throw() { } sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return awt::Point(); } void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) ); return sal_True; } } } return sal_False; } sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) ); return sal_True; } } } return sal_False; } uno::Reference< text::XText > SdXTextViewCursor::getText(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XText > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return OUString(); } void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } <commit_msg>INTEGRATION: CWS presentationengine01 (1.4.10); FILE MERGED 2004/08/25 16:32:23 cl 1.4.10.1: replaced old FuSlideShow with new SlideShow<commit_after>/************************************************************************* * * $RCSfile: unovwcrs.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-11-26 20:29:42 $ * * 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 _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_ #include <com/sun/star/text/XTextViewCursor.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_ #include <com/sun/star/view/XScreenCursor.hpp> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SVX_LIGHT #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef _SD_SLIDESHOW_HXX #include "slideshow.hxx" #endif #include <cppuhelper/implbase2.hxx> using namespace ::vos; using namespace ::rtl; using namespace ::com::sun::star; class SdXTextViewCursor : public ::cppu::WeakImplHelper2< text::XTextViewCursor, view::XScreenCursor > { public: SdXTextViewCursor(::sd::View* pVw) throw(); virtual ~SdXTextViewCursor() throw(); //XTextViewCursor virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException ); virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException ); virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException ); //XTextCursor virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException ); virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException); //XTextRange virtual uno::Reference< text::XText > SAL_CALL getText(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getStart(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getEnd(void) throw( uno::RuntimeException ); virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException ); virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException ); //XScreenCursor virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException ); void Invalidate() { mpView = 0; } private: ::sd::View* mpView; }; text::XTextViewCursor* CreateSdXTextViewCursor(::sd::View* mpView ) { return new SdXTextViewCursor( mpView ); } SdXTextViewCursor::SdXTextViewCursor(::sd::View* pSdView ) throw() : mpView(pSdView) { } SdXTextViewCursor::~SdXTextViewCursor() throw() { } sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return awt::Point(); } void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; /* if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) ); return sal_True; } } } */ return sal_False; } sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); /* sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) ); return sal_True; } } } */ return sal_False; } uno::Reference< text::XText > SdXTextViewCursor::getText(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XText > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return OUString(); } void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } <|endoftext|>
<commit_before>#include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QLabel> #include <QPushButton> #include <QStackedWidget> #include <QTimer> #include <QVBoxLayout> #include "QrCode.hpp" #include "api.hpp" #include "common/params.h" #include "setup.hpp" using qrcodegen::QrCode; PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { qrCode = new QLabel; qrCode->setScaledContents(true); QVBoxLayout* v = new QVBoxLayout; v->addWidget(qrCode, 0, Qt::AlignCenter); setLayout(v); QTimer* timer = new QTimer(this); timer->start(30 * 1000); connect(timer, SIGNAL(timeout()), this, SLOT(refresh())); refresh(); // don't wait for the first refresh } void PairingQRWidget::refresh(){ QString IMEI = QString::fromStdString(Params().get("IMEI")); QString serial = QString::fromStdString(Params().get("HardwareSerial")); if (std::min(IMEI.length(), serial.length()) <= 5) { qrCode->setText("Error getting serial: contact support"); qrCode->setWordWrap(true); qrCode->setStyleSheet(R"(font-size: 60px;)"); return; } QString pairToken = CommaApi::create_jwt({{"pair", true}}); QString qrString = IMEI + "--" + serial + "--" + pairToken; this->updateQrCode(qrString); } void PairingQRWidget::updateQrCode(QString text) { QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); qint32 sz = qr.getSize(); // make the image larger so we can have a white border QImage im(sz + 2, sz + 2, QImage::Format_RGB32); QRgb black = qRgb(0, 0, 0); QRgb white = qRgb(255, 255, 255); for (int y = 0; y < sz + 2; y++) { for (int x = 0; x < sz + 2; x++) { im.setPixel(x, y, white); } } for (int y = 0; y < sz; y++) { for (int x = 0; x < sz; x++) { im.setPixel(x + 1, y + 1, qr.getModule(x, y) ? black : white); } } // Integer division to prevent anti-aliasing int approx500 = (500 / (sz + 2)) * (sz + 2); qrCode->setPixmap(QPixmap::fromImage(im.scaled(approx500, approx500, Qt::KeepAspectRatio, Qt::FastTransformation), Qt::MonoOnly)); qrCode->setFixedSize(approx500, approx500); } PrimeUserWidget::PrimeUserWidget(QWidget* parent) : QWidget(parent) { mainLayout = new QVBoxLayout; mainLayout->setMargin(30); QLabel* commaPrime = new QLabel("COMMA PRIME"); mainLayout->addWidget(commaPrime, 0, Qt::AlignTop); username = new QLabel(); username->setStyleSheet("font-size: 55px;"); // TODO: fit width mainLayout->addWidget(username, 0, Qt::AlignTop); mainLayout->addSpacing(100); QLabel* commaPoints = new QLabel("COMMA POINTS"); commaPoints->setStyleSheet(R"( color: #b8b8b8; )"); mainLayout->addWidget(commaPoints, 0, Qt::AlignTop); points = new QLabel(); mainLayout->addWidget(points, 0, Qt::AlignTop); setLayout(mainLayout); setStyleSheet(R"( QLabel { font-size: 70px; font-weight: 500; } )"); // set up API requests QString dongleId = QString::fromStdString(Params().get("DongleId")); if (!dongleId.length()) { return; } // TODO: only send the request when widget is shown QString url = "https://api.commadotai.com/v1/devices/" + dongleId + "/owner"; RequestRepeater* repeater = new RequestRepeater(this, url, 6, "ApiCache_Owner"); QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); } void PrimeUserWidget::replyFinished(QString response) { QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); if (doc.isNull()) { qDebug() << "JSON Parse failed on getting username and points"; return; } QJsonObject json = doc.object(); QString points_str = QString::number(json["points"].toInt()); QString username_str = json["username"].toString(); if (username_str.length()) { username_str = "@" + username_str; } username->setText(username_str); points->setText(points_str); } PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QWidget(parent) { QVBoxLayout* vlayout = new QVBoxLayout; vlayout->setMargin(30); vlayout->setSpacing(15); vlayout->addWidget(new QLabel("Upgrade now"), 1, Qt::AlignTop); QLabel* description = new QLabel("Become a comma prime member in the comma connect app and get premium features!"); description->setStyleSheet(R"( font-size: 50px; color: #b8b8b8; )"); description->setWordWrap(true); vlayout->addWidget(description, 2, Qt::AlignTop); QVector<QString> features = {"✓ REMOTE ACCESS", "✓ 14 DAYS OF STORAGE", "✓ DEVELOPER PERKS"}; for (auto &f: features) { QLabel* feature = new QLabel(f); feature->setStyleSheet(R"(font-size: 40px;)"); vlayout->addWidget(feature, 0, Qt::AlignBottom); } setLayout(vlayout); } SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { mainLayout = new QStackedWidget; // Unpaired, registration prompt layout QVBoxLayout* finishRegistationLayout = new QVBoxLayout; finishRegistationLayout->setMargin(30); QLabel* registrationDescription = new QLabel("Pair your device with the comma connect app"); registrationDescription->setWordWrap(true); registrationDescription->setAlignment(Qt::AlignCenter); registrationDescription->setStyleSheet(R"( font-size: 55px; font-weight: 400; )"); finishRegistationLayout->addWidget(registrationDescription); QPushButton* finishButton = new QPushButton("Finish setup"); finishButton->setFixedHeight(200); finishButton->setStyleSheet(R"( border-radius: 30px; font-size: 55px; font-weight: 500; background: #585858; )"); finishRegistationLayout->addWidget(finishButton); QObject::connect(finishButton, SIGNAL(released()), this, SLOT(showQrCode())); QWidget* finishRegistration = new QWidget; finishRegistration->setLayout(finishRegistationLayout); mainLayout->addWidget(finishRegistration); // Pairing QR code layout QVBoxLayout* qrLayout = new QVBoxLayout; qrLayout->addSpacing(40); QLabel* qrLabel = new QLabel("Scan with comma connect!"); qrLabel->setWordWrap(true); qrLabel->setAlignment(Qt::AlignHCenter); qrLabel->setStyleSheet(R"( font-size: 55px; font-weight: 400; )"); qrLayout->addWidget(qrLabel, 0, Qt::AlignTop); qrLayout->addWidget(new PairingQRWidget, 1); QWidget* q = new QWidget; q->setLayout(qrLayout); mainLayout->addWidget(q); primeAd = new PrimeAdWidget; mainLayout->addWidget(primeAd); primeUser = new PrimeUserWidget; mainLayout->addWidget(primeUser); mainLayout->setCurrentWidget(primeAd); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(mainLayout); setLayout(layout); setStyleSheet(R"( SetupWidget { background-color: #292929; } * { font-size: 90px; font-weight: 500; border-radius: 40px; } )"); // Retain size while hidden QSizePolicy sp_retain = sizePolicy(); sp_retain.setRetainSizeWhenHidden(true); setSizePolicy(sp_retain); // set up API requests QString dongleId = QString::fromStdString(Params().get("DongleId")); QString url = "https://api.commadotai.com/v1.1/devices/" + dongleId + "/"; RequestRepeater* repeater = new RequestRepeater(this, url, 5, "ApiCache_Device"); QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); QObject::connect(repeater, SIGNAL(failedResponse(QString)), this, SLOT(parseError(QString))); hide(); // Only show when first request comes back } void SetupWidget::parseError(QString response) { show(); showQr = false; mainLayout->setCurrentIndex(0); } void SetupWidget::showQrCode(){ showQr = true; mainLayout->setCurrentIndex(1); } void SetupWidget::replyFinished(QString response) { show(); QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); if (doc.isNull()) { qDebug() << "JSON Parse failed on getting pairing and prime status"; return; } QJsonObject json = doc.object(); bool is_paired = json["is_paired"].toBool(); bool is_prime = json["prime"].toBool(); if (!is_paired) { mainLayout->setCurrentIndex(showQr); } else if (!is_prime) { showQr = false; mainLayout->setCurrentWidget(primeAd); } else { showQr = false; mainLayout->setCurrentWidget(primeUser); } } <commit_msg>fix cut off qr code<commit_after>#include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QLabel> #include <QPushButton> #include <QStackedWidget> #include <QTimer> #include <QVBoxLayout> #include "QrCode.hpp" #include "api.hpp" #include "common/params.h" #include "setup.hpp" using qrcodegen::QrCode; PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { qrCode = new QLabel; qrCode->setScaledContents(true); QVBoxLayout* v = new QVBoxLayout; v->addWidget(qrCode, 0, Qt::AlignCenter); setLayout(v); QTimer* timer = new QTimer(this); timer->start(30 * 1000); connect(timer, SIGNAL(timeout()), this, SLOT(refresh())); refresh(); // don't wait for the first refresh } void PairingQRWidget::refresh(){ QString IMEI = QString::fromStdString(Params().get("IMEI")); QString serial = QString::fromStdString(Params().get("HardwareSerial")); if (std::min(IMEI.length(), serial.length()) <= 5) { qrCode->setText("Error getting serial: contact support"); qrCode->setWordWrap(true); qrCode->setStyleSheet(R"(font-size: 60px;)"); return; } QString pairToken = CommaApi::create_jwt({{"pair", true}}); QString qrString = IMEI + "--" + serial + "--" + pairToken; this->updateQrCode(qrString); } void PairingQRWidget::updateQrCode(QString text) { QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); qint32 sz = qr.getSize(); // make the image larger so we can have a white border QImage im(sz + 2, sz + 2, QImage::Format_RGB32); QRgb black = qRgb(0, 0, 0); QRgb white = qRgb(255, 255, 255); for (int y = 0; y < sz + 2; y++) { for (int x = 0; x < sz + 2; x++) { im.setPixel(x, y, white); } } for (int y = 0; y < sz; y++) { for (int x = 0; x < sz; x++) { im.setPixel(x + 1, y + 1, qr.getModule(x, y) ? black : white); } } // Integer division to prevent anti-aliasing int approx500 = (500 / (sz + 2)) * (sz + 2); qrCode->setPixmap(QPixmap::fromImage(im.scaled(approx500, approx500, Qt::KeepAspectRatio, Qt::FastTransformation), Qt::MonoOnly)); qrCode->setFixedSize(approx500, approx500); } PrimeUserWidget::PrimeUserWidget(QWidget* parent) : QWidget(parent) { mainLayout = new QVBoxLayout; mainLayout->setMargin(30); QLabel* commaPrime = new QLabel("COMMA PRIME"); mainLayout->addWidget(commaPrime, 0, Qt::AlignTop); username = new QLabel(); username->setStyleSheet("font-size: 55px;"); // TODO: fit width mainLayout->addWidget(username, 0, Qt::AlignTop); mainLayout->addSpacing(100); QLabel* commaPoints = new QLabel("COMMA POINTS"); commaPoints->setStyleSheet(R"( color: #b8b8b8; )"); mainLayout->addWidget(commaPoints, 0, Qt::AlignTop); points = new QLabel(); mainLayout->addWidget(points, 0, Qt::AlignTop); setLayout(mainLayout); setStyleSheet(R"( QLabel { font-size: 70px; font-weight: 500; } )"); // set up API requests QString dongleId = QString::fromStdString(Params().get("DongleId")); if (!dongleId.length()) { return; } QString url = "https://api.commadotai.com/v1/devices/" + dongleId + "/owner"; RequestRepeater* repeater = new RequestRepeater(this, url, 6, "ApiCache_Owner"); QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); } void PrimeUserWidget::replyFinished(QString response) { QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); if (doc.isNull()) { qDebug() << "JSON Parse failed on getting username and points"; return; } QJsonObject json = doc.object(); QString points_str = QString::number(json["points"].toInt()); QString username_str = json["username"].toString(); if (username_str.length()) { username_str = "@" + username_str; } username->setText(username_str); points->setText(points_str); } PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QWidget(parent) { QVBoxLayout* vlayout = new QVBoxLayout; vlayout->setMargin(30); vlayout->setSpacing(15); vlayout->addWidget(new QLabel("Upgrade now"), 1, Qt::AlignTop); QLabel* description = new QLabel("Become a comma prime member in the comma connect app and get premium features!"); description->setStyleSheet(R"( font-size: 50px; color: #b8b8b8; )"); description->setWordWrap(true); vlayout->addWidget(description, 2, Qt::AlignTop); QVector<QString> features = {"✓ REMOTE ACCESS", "✓ 14 DAYS OF STORAGE", "✓ DEVELOPER PERKS"}; for (auto &f: features) { QLabel* feature = new QLabel(f); feature->setStyleSheet(R"(font-size: 40px;)"); vlayout->addWidget(feature, 0, Qt::AlignBottom); } setLayout(vlayout); } SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { mainLayout = new QStackedWidget; // Unpaired, registration prompt layout QVBoxLayout* finishRegistationLayout = new QVBoxLayout; finishRegistationLayout->setMargin(30); QLabel* registrationDescription = new QLabel("Pair your device with the comma connect app"); registrationDescription->setWordWrap(true); registrationDescription->setAlignment(Qt::AlignCenter); registrationDescription->setStyleSheet(R"( font-size: 55px; font-weight: 400; )"); finishRegistationLayout->addWidget(registrationDescription); QPushButton* finishButton = new QPushButton("Finish setup"); finishButton->setFixedHeight(200); finishButton->setStyleSheet(R"( border-radius: 30px; font-size: 55px; font-weight: 500; background: #585858; )"); finishRegistationLayout->addWidget(finishButton); QObject::connect(finishButton, SIGNAL(released()), this, SLOT(showQrCode())); QWidget* finishRegistration = new QWidget; finishRegistration->setLayout(finishRegistationLayout); mainLayout->addWidget(finishRegistration); // Pairing QR code layout QVBoxLayout* qrLayout = new QVBoxLayout; qrLayout->addSpacing(30); QLabel* qrLabel = new QLabel("Scan with comma connect!"); qrLabel->setWordWrap(true); qrLabel->setAlignment(Qt::AlignHCenter); qrLabel->setStyleSheet(R"( font-size: 55px; font-weight: 400; )"); qrLayout->addWidget(qrLabel, 0, Qt::AlignTop); qrLayout->addWidget(new PairingQRWidget, 1); QWidget* q = new QWidget; q->setLayout(qrLayout); mainLayout->addWidget(q); primeAd = new PrimeAdWidget; mainLayout->addWidget(primeAd); primeUser = new PrimeUserWidget; mainLayout->addWidget(primeUser); mainLayout->setCurrentWidget(primeAd); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(mainLayout); setLayout(layout); setStyleSheet(R"( SetupWidget { background-color: #292929; } * { font-size: 90px; font-weight: 500; border-radius: 40px; } )"); // Retain size while hidden QSizePolicy sp_retain = sizePolicy(); sp_retain.setRetainSizeWhenHidden(true); setSizePolicy(sp_retain); // set up API requests QString dongleId = QString::fromStdString(Params().get("DongleId")); QString url = "https://api.commadotai.com/v1.1/devices/" + dongleId + "/"; RequestRepeater* repeater = new RequestRepeater(this, url, 5, "ApiCache_Device"); QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); QObject::connect(repeater, SIGNAL(failedResponse(QString)), this, SLOT(parseError(QString))); hide(); // Only show when first request comes back } void SetupWidget::parseError(QString response) { show(); showQr = false; mainLayout->setCurrentIndex(0); } void SetupWidget::showQrCode(){ showQr = true; mainLayout->setCurrentIndex(1); } void SetupWidget::replyFinished(QString response) { show(); QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); if (doc.isNull()) { qDebug() << "JSON Parse failed on getting pairing and prime status"; return; } QJsonObject json = doc.object(); bool is_paired = json["is_paired"].toBool(); bool is_prime = json["prime"].toBool(); if (!is_paired) { mainLayout->setCurrentIndex(showQr); } else if (!is_prime) { showQr = false; mainLayout->setCurrentWidget(primeAd); } else { showQr = false; mainLayout->setCurrentWidget(primeUser); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "derive.h" #include "xact.h" #include "post.h" #include "account.h" #include "journal.h" #include "session.h" #include "report.h" #include "output.h" namespace ledger { namespace { struct xact_template_t { optional<date_t> date; optional<string> code; optional<string> note; mask_t payee_mask; struct post_template_t { bool from; optional<mask_t> account_mask; optional<amount_t> amount; post_template_t() : from(false) {} }; std::list<post_template_t> posts; xact_template_t() {} void dump(std::ostream& out) const { if (date) out << _("Date: ") << *date << std::endl; else out << _("Date: <today>") << std::endl; if (code) out << _("Code: ") << *code << std::endl; if (note) out << _("Note: ") << *note << std::endl; if (payee_mask.empty()) out << _("Payee mask: INVALID (template expression will cause an error)") << std::endl; else out << _("Payee mask: ") << payee_mask << std::endl; if (posts.empty()) { out << std::endl << _("<Posting copied from last related transaction>") << std::endl; } else { bool has_only_from = true; bool has_only_to = true; foreach (const post_template_t& post, posts) { if (post.from) has_only_to = false; else has_only_from = false; } foreach (const post_template_t& post, posts) { straccstream accum; out << std::endl << ACCUM(accum << _("[Posting \"%1\"]_") << (post.from ? _("from") : _("to"))) << std::endl; if (post.account_mask) out << _(" Account mask: ") << *post.account_mask << std::endl; else if (post.from) out << _(" Account mask: <use last of last related accounts>") << std::endl; else out << _(" Account mask: <use first of last related accounts>") << std::endl; if (post.amount) out << _(" Amount: ") << *post.amount << std::endl; } } } }; xact_template_t args_to_xact_template(value_t::sequence_t::const_iterator begin, value_t::sequence_t::const_iterator end) { regex date_mask(_("([0-9]+(?:[-/.][0-9]+)?(?:[-/.][0-9]+))?")); smatch what; xact_template_t tmpl; bool check_for_date = true; optional<date_time::weekdays> weekday; xact_template_t::post_template_t * post = NULL; for (; begin != end; begin++) { if (check_for_date && regex_match((*begin).to_string(), what, date_mask)) { tmpl.date = parse_date(what[0]); check_for_date = false; } else if (check_for_date && bool(weekday = string_to_day_of_week(what[0]))) { short dow = static_cast<short>(*weekday); date_t date = CURRENT_DATE() - date_duration(1); while (date.day_of_week() != dow) date -= date_duration(1); tmpl.date = date; check_for_date = false; } else { string arg = (*begin).to_string(); if (arg == "at") { tmpl.payee_mask = (*++begin).to_string(); } else if (arg == "to" || arg == "from") { if (! post || post->account_mask) { tmpl.posts.push_back(xact_template_t::post_template_t()); post = &tmpl.posts.back(); } post->account_mask = mask_t((*++begin).to_string()); post->from = arg == "from"; } else if (arg == "on") { tmpl.date = parse_date((*++begin).to_string()); check_for_date = false; } else if (arg == "code") { tmpl.code = (*++begin).to_string(); } else if (arg == "note") { tmpl.note = (*++begin).to_string(); } else if (arg == "rest") { ; // just ignore this argument } else { // Without a preposition, it is either: // // A payee, if we have not seen one // An account or an amount, if we have // An account if an amount has just been seen // An amount if an account has just been seen if (tmpl.payee_mask.empty()) { tmpl.payee_mask = arg; } else { amount_t amt; optional<mask_t> account; if (! amt.parse(arg, amount_t::PARSE_SOFT_FAIL | amount_t::PARSE_NO_MIGRATE)) account = mask_t(arg); if (! post || (account && post->account_mask) || (! account && post->amount)) { tmpl.posts.push_back(xact_template_t::post_template_t()); post = &tmpl.posts.back(); } if (account) { post->from = false; post->account_mask = account; } else { post->amount = amt; } } } } } if (! tmpl.posts.empty()) { bool has_only_from = true; bool has_only_to = true; // A single account at the end of the line is the "from" account if (tmpl.posts.size() > 1 && tmpl.posts.back().account_mask && ! tmpl.posts.back().amount) tmpl.posts.back().from = true; foreach (xact_template_t::post_template_t& post, tmpl.posts) { if (post.from) has_only_to = false; else has_only_from = false; } if (has_only_from) { tmpl.posts.push_front(xact_template_t::post_template_t()); } else if (has_only_to) { tmpl.posts.push_back(xact_template_t::post_template_t()); tmpl.posts.back().from = true; } } return tmpl; } xact_t * derive_xact_from_template(xact_template_t& tmpl, report_t& report) { if (tmpl.payee_mask.empty()) throw std::runtime_error(_("'xact' command requires at least a payee")); xact_t * matching = NULL; journal_t& journal(*report.session.journal.get()); std::auto_ptr<xact_t> added(new xact_t); xacts_list::reverse_iterator j; for (j = journal.xacts.rbegin(); j != journal.xacts.rend(); j++) { if (tmpl.payee_mask.match((*j)->payee)) { matching = *j; break; } } if (! tmpl.date) added->_date = CURRENT_DATE(); else added->_date = tmpl.date; added->set_state(item_t::UNCLEARED); if (matching) { added->payee = matching->payee; added->code = matching->code; added->note = matching->note; } else { added->payee = tmpl.payee_mask.expr.str(); } if (tmpl.code) added->code = tmpl.code; if (tmpl.note) added->note = tmpl.note; if (tmpl.posts.empty()) { if (matching) { foreach (post_t * post, matching->posts) { added->add_post(new post_t(*post)); added->posts.back()->set_state(item_t::UNCLEARED); } } else { throw_(std::runtime_error, _("No accounts, and no past transaction matching '%1'") << tmpl.payee_mask); } } else { bool any_post_has_amount = false; foreach (xact_template_t::post_template_t& post, tmpl.posts) { if (post.amount) { any_post_has_amount = true; break; } } foreach (xact_template_t::post_template_t& post, tmpl.posts) { std::auto_ptr<post_t> new_post; commodity_t * found_commodity = NULL; if (matching) { if (post.account_mask) { foreach (post_t * x, matching->posts) { if (post.account_mask->match(x->account->fullname())) { new_post.reset(new post_t(*x)); break; } } } else { if (post.from) new_post.reset(new post_t(*matching->posts.back())); else new_post.reset(new post_t(*matching->posts.front())); } } if (! new_post.get()) new_post.reset(new post_t); if (! new_post->account) { if (post.account_mask) { account_t * acct = NULL; if (! acct) acct = journal.find_account_re(post.account_mask->expr.str()); if (! acct) acct = journal.find_account(post.account_mask->expr.str()); // Find out the default commodity to use by looking at the last // commodity used in that account xacts_list::reverse_iterator j; for (j = journal.xacts.rbegin(); j != journal.xacts.rend(); j++) { foreach (post_t * x, (*j)->posts) { if (x->account == acct && ! x->amount.is_null()) { new_post.reset(new post_t(*x)); break; } } } if (! new_post.get()) new_post.reset(new post_t); new_post->account = acct; } else { if (post.from) new_post->account = journal.find_account(_("Liabilities:Unknown")); else new_post->account = journal.find_account(_("Expenses:Unknown")); } } if (new_post.get() && ! new_post->amount.is_null()) { found_commodity = &new_post->amount.commodity(); if (any_post_has_amount) new_post->amount = amount_t(); else any_post_has_amount = true; } if (post.amount) { new_post->amount = *post.amount; if (post.from) new_post->amount.in_place_negate(); } if (found_commodity && ! new_post->amount.is_null() && ! new_post->amount.has_commodity()) { new_post->amount.set_commodity(*found_commodity); new_post->amount = new_post->amount.rounded(); } added->add_post(new_post.release()); added->posts.back()->set_state(item_t::UNCLEARED); } } if (! journal.xact_finalize_hooks.run_hooks(*added.get(), false) || ! added->finalize() || ! journal.xact_finalize_hooks.run_hooks(*added.get(), true)) throw_(std::runtime_error, _("Failed to finalize derived transaction (check commodities)")); return added.release(); } } value_t template_command(call_scope_t& args) { report_t& report(find_scope<report_t>(args)); std::ostream& out(report.output_stream); value_t::sequence_t::const_iterator begin = args.value().begin(); value_t::sequence_t::const_iterator end = args.value().end(); out << _("--- Input arguments ---") << std::endl; args.value().dump(out); out << std::endl << std::endl; xact_template_t tmpl = args_to_xact_template(begin, end); out << _("--- Transaction template ---") << std::endl; tmpl.dump(out); return true; } value_t xact_command(call_scope_t& args) { value_t::sequence_t::const_iterator begin = args.value().begin(); value_t::sequence_t::const_iterator end = args.value().end(); report_t& report(find_scope<report_t>(args)); xact_template_t tmpl = args_to_xact_template(begin, end); std::auto_ptr<xact_t> new_xact(derive_xact_from_template(tmpl, report)); // jww (2009-02-27): make this more general report.HANDLER(limit_).on(string("#xact"), "actual"); report.xact_report(post_handler_ptr (new format_posts(report, report.HANDLER(print_format_).str())), *new_xact.get()); return true; } } // namespace ledger <commit_msg>Corrected a minor typo<commit_after>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "derive.h" #include "xact.h" #include "post.h" #include "account.h" #include "journal.h" #include "session.h" #include "report.h" #include "output.h" namespace ledger { namespace { struct xact_template_t { optional<date_t> date; optional<string> code; optional<string> note; mask_t payee_mask; struct post_template_t { bool from; optional<mask_t> account_mask; optional<amount_t> amount; post_template_t() : from(false) {} }; std::list<post_template_t> posts; xact_template_t() {} void dump(std::ostream& out) const { if (date) out << _("Date: ") << *date << std::endl; else out << _("Date: <today>") << std::endl; if (code) out << _("Code: ") << *code << std::endl; if (note) out << _("Note: ") << *note << std::endl; if (payee_mask.empty()) out << _("Payee mask: INVALID (template expression will cause an error)") << std::endl; else out << _("Payee mask: ") << payee_mask << std::endl; if (posts.empty()) { out << std::endl << _("<Posting copied from last related transaction>") << std::endl; } else { bool has_only_from = true; bool has_only_to = true; foreach (const post_template_t& post, posts) { if (post.from) has_only_to = false; else has_only_from = false; } foreach (const post_template_t& post, posts) { straccstream accum; out << std::endl << ACCUM(accum << _("[Posting \"%1\"]") << (post.from ? _("from") : _("to"))) << std::endl; if (post.account_mask) out << _(" Account mask: ") << *post.account_mask << std::endl; else if (post.from) out << _(" Account mask: <use last of last related accounts>") << std::endl; else out << _(" Account mask: <use first of last related accounts>") << std::endl; if (post.amount) out << _(" Amount: ") << *post.amount << std::endl; } } } }; xact_template_t args_to_xact_template(value_t::sequence_t::const_iterator begin, value_t::sequence_t::const_iterator end) { regex date_mask(_("([0-9]+(?:[-/.][0-9]+)?(?:[-/.][0-9]+))?")); smatch what; xact_template_t tmpl; bool check_for_date = true; optional<date_time::weekdays> weekday; xact_template_t::post_template_t * post = NULL; for (; begin != end; begin++) { if (check_for_date && regex_match((*begin).to_string(), what, date_mask)) { tmpl.date = parse_date(what[0]); check_for_date = false; } else if (check_for_date && bool(weekday = string_to_day_of_week(what[0]))) { short dow = static_cast<short>(*weekday); date_t date = CURRENT_DATE() - date_duration(1); while (date.day_of_week() != dow) date -= date_duration(1); tmpl.date = date; check_for_date = false; } else { string arg = (*begin).to_string(); if (arg == "at") { tmpl.payee_mask = (*++begin).to_string(); } else if (arg == "to" || arg == "from") { if (! post || post->account_mask) { tmpl.posts.push_back(xact_template_t::post_template_t()); post = &tmpl.posts.back(); } post->account_mask = mask_t((*++begin).to_string()); post->from = arg == "from"; } else if (arg == "on") { tmpl.date = parse_date((*++begin).to_string()); check_for_date = false; } else if (arg == "code") { tmpl.code = (*++begin).to_string(); } else if (arg == "note") { tmpl.note = (*++begin).to_string(); } else if (arg == "rest") { ; // just ignore this argument } else { // Without a preposition, it is either: // // A payee, if we have not seen one // An account or an amount, if we have // An account if an amount has just been seen // An amount if an account has just been seen if (tmpl.payee_mask.empty()) { tmpl.payee_mask = arg; } else { amount_t amt; optional<mask_t> account; if (! amt.parse(arg, amount_t::PARSE_SOFT_FAIL | amount_t::PARSE_NO_MIGRATE)) account = mask_t(arg); if (! post || (account && post->account_mask) || (! account && post->amount)) { tmpl.posts.push_back(xact_template_t::post_template_t()); post = &tmpl.posts.back(); } if (account) { post->from = false; post->account_mask = account; } else { post->amount = amt; } } } } } if (! tmpl.posts.empty()) { bool has_only_from = true; bool has_only_to = true; // A single account at the end of the line is the "from" account if (tmpl.posts.size() > 1 && tmpl.posts.back().account_mask && ! tmpl.posts.back().amount) tmpl.posts.back().from = true; foreach (xact_template_t::post_template_t& post, tmpl.posts) { if (post.from) has_only_to = false; else has_only_from = false; } if (has_only_from) { tmpl.posts.push_front(xact_template_t::post_template_t()); } else if (has_only_to) { tmpl.posts.push_back(xact_template_t::post_template_t()); tmpl.posts.back().from = true; } } return tmpl; } xact_t * derive_xact_from_template(xact_template_t& tmpl, report_t& report) { if (tmpl.payee_mask.empty()) throw std::runtime_error(_("'xact' command requires at least a payee")); xact_t * matching = NULL; journal_t& journal(*report.session.journal.get()); std::auto_ptr<xact_t> added(new xact_t); xacts_list::reverse_iterator j; for (j = journal.xacts.rbegin(); j != journal.xacts.rend(); j++) { if (tmpl.payee_mask.match((*j)->payee)) { matching = *j; break; } } if (! tmpl.date) added->_date = CURRENT_DATE(); else added->_date = tmpl.date; added->set_state(item_t::UNCLEARED); if (matching) { added->payee = matching->payee; added->code = matching->code; added->note = matching->note; } else { added->payee = tmpl.payee_mask.expr.str(); } if (tmpl.code) added->code = tmpl.code; if (tmpl.note) added->note = tmpl.note; if (tmpl.posts.empty()) { if (matching) { foreach (post_t * post, matching->posts) { added->add_post(new post_t(*post)); added->posts.back()->set_state(item_t::UNCLEARED); } } else { throw_(std::runtime_error, _("No accounts, and no past transaction matching '%1'") << tmpl.payee_mask); } } else { bool any_post_has_amount = false; foreach (xact_template_t::post_template_t& post, tmpl.posts) { if (post.amount) { any_post_has_amount = true; break; } } foreach (xact_template_t::post_template_t& post, tmpl.posts) { std::auto_ptr<post_t> new_post; commodity_t * found_commodity = NULL; if (matching) { if (post.account_mask) { foreach (post_t * x, matching->posts) { if (post.account_mask->match(x->account->fullname())) { new_post.reset(new post_t(*x)); break; } } } else { if (post.from) new_post.reset(new post_t(*matching->posts.back())); else new_post.reset(new post_t(*matching->posts.front())); } } if (! new_post.get()) new_post.reset(new post_t); if (! new_post->account) { if (post.account_mask) { account_t * acct = NULL; if (! acct) acct = journal.find_account_re(post.account_mask->expr.str()); if (! acct) acct = journal.find_account(post.account_mask->expr.str()); // Find out the default commodity to use by looking at the last // commodity used in that account xacts_list::reverse_iterator j; for (j = journal.xacts.rbegin(); j != journal.xacts.rend(); j++) { foreach (post_t * x, (*j)->posts) { if (x->account == acct && ! x->amount.is_null()) { new_post.reset(new post_t(*x)); break; } } } if (! new_post.get()) new_post.reset(new post_t); new_post->account = acct; } else { if (post.from) new_post->account = journal.find_account(_("Liabilities:Unknown")); else new_post->account = journal.find_account(_("Expenses:Unknown")); } } if (new_post.get() && ! new_post->amount.is_null()) { found_commodity = &new_post->amount.commodity(); if (any_post_has_amount) new_post->amount = amount_t(); else any_post_has_amount = true; } if (post.amount) { new_post->amount = *post.amount; if (post.from) new_post->amount.in_place_negate(); } if (found_commodity && ! new_post->amount.is_null() && ! new_post->amount.has_commodity()) { new_post->amount.set_commodity(*found_commodity); new_post->amount = new_post->amount.rounded(); } added->add_post(new_post.release()); added->posts.back()->set_state(item_t::UNCLEARED); } } if (! journal.xact_finalize_hooks.run_hooks(*added.get(), false) || ! added->finalize() || ! journal.xact_finalize_hooks.run_hooks(*added.get(), true)) throw_(std::runtime_error, _("Failed to finalize derived transaction (check commodities)")); return added.release(); } } value_t template_command(call_scope_t& args) { report_t& report(find_scope<report_t>(args)); std::ostream& out(report.output_stream); value_t::sequence_t::const_iterator begin = args.value().begin(); value_t::sequence_t::const_iterator end = args.value().end(); out << _("--- Input arguments ---") << std::endl; args.value().dump(out); out << std::endl << std::endl; xact_template_t tmpl = args_to_xact_template(begin, end); out << _("--- Transaction template ---") << std::endl; tmpl.dump(out); return true; } value_t xact_command(call_scope_t& args) { value_t::sequence_t::const_iterator begin = args.value().begin(); value_t::sequence_t::const_iterator end = args.value().end(); report_t& report(find_scope<report_t>(args)); xact_template_t tmpl = args_to_xact_template(begin, end); std::auto_ptr<xact_t> new_xact(derive_xact_from_template(tmpl, report)); // jww (2009-02-27): make this more general report.HANDLER(limit_).on(string("#xact"), "actual"); report.xact_report(post_handler_ptr (new format_posts(report, report.HANDLER(print_format_).str())), *new_xact.get()); return true; } } // namespace ledger <|endoftext|>
<commit_before>#include "general.hpp" #include "course.hpp" #include "student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses(string filename) { ifstream infile(filename.c_str()); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); // cout << incourse << endl; } // for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c) { // if (c->getProfessor()[1] == ' ') // if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1') // cout << *c << endl; // if (c->getDepartment(0) == NONE) // cout << *c << endl; // } } void readData() { loadCourses("data/2012-13-s2.csv"); loadCourses("data/2012-13-interim.csv"); loadCourses("data/2012-13-s1.csv"); loadCourses("data/2011-12-s2.csv"); loadCourses("data/2011-12-interim.csv"); loadCourses("data/2011-12-s1.csv"); loadCourses("data/2010-11-s2.csv"); loadCourses("data/2010-11-interim.csv"); loadCourses("data/2010-11-s1.csv"); } void welcome() { string name, yearS = "", yearE = "", majors; cout << "Welcome!" << endl; cout << "What is your name? "; getline(cin, name); cout << "What year do you graduate? "; getline(cin, yearE); cout << "What are your majors (ex. CSCI, ASIAN) "; getline(cin, majors); user = Student(name, yearS, yearE, majors); } void requestCourses() { string courses; cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; getline(cin, courses); user.addCourses(courses); } int main(int argc, const char *argv[]) { readData(); // Method 1: Dynamic. // welcome(); // requestCourses(); // Method 2: Hard-coded file path. user = Student("data/example.txt"); // Method 3: File path as an argument. // Student user(argv[1]); user.updateStanding(); user.display(); return 0; } <commit_msg>Add some command-line arguments to the program<commit_after>#include "general.hpp" #include "course.hpp" #include "student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses(string filename) { ifstream infile(filename.c_str()); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); // cout << incourse << endl; } } void readData() { loadCourses("data/2012-13-s2.csv"); loadCourses("data/2012-13-interim.csv"); loadCourses("data/2012-13-s1.csv"); loadCourses("data/2011-12-s2.csv"); loadCourses("data/2011-12-interim.csv"); loadCourses("data/2011-12-s1.csv"); loadCourses("data/2010-11-s2.csv"); loadCourses("data/2010-11-interim.csv"); loadCourses("data/2010-11-s1.csv"); } vector<string> parseArguments(int argc, const char* argv[]) { // cout << argc << endl; vector<string> arguments; for (int i = 1; i < argc; i++) { // cout << argv[i] << endl; arguments.push_back(argv[i]); } return arguments; } int main(int argc, const char *argv[]) { vector<string> arguments = parseArguments(argc, argv); readData(); if (arguments.size() > 0) { string arg0 = arguments.at(0); if (arg0 == "--find" || arg0 == "-f") { if (arguments.size() == 2) { Course c = Course(arguments.at(1)); c.display(); } } else if (arg0 == "--load" || arg0 == "-l") { if (arguments.size() == 2) { user = Student(arguments.at(1)); user.display(); } } else if (arg0 == "--demo") { user = Student("data/example.txt"); user.display(); } else if (arg0 == "--stress") { user = Student("data/stress.txt"); user.display(); } else if (arg0 == "--debug") { for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c) { if (c->getProfessor()[1] == ' ') if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1') cout << *c << endl; if (c->getDepartment(0) == NONE) cout << *c << endl; } } else if (arg0 == "--interactive" || arg0 == "-i") { string name, yearS = "", yearE = "", majors; cout << "Welcome!" << endl; cout << "What is your name? "; getline(cin, name); cout << "What year do you graduate? "; getline(cin, yearE); cout << "What are your majors (ex. CSCI, ASIAN) "; getline(cin, majors); user = Student(name, yearS, yearE, majors); string courses; cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; getline(cin, courses); user.addCourses(courses); user.display(); } } else { cout << "This program works best if you give it some data ;)" << endl; cout << "However, we have some example stuff to show you anyway." << endl; user = Student("data/example.txt"); user.display(); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgstreamermetadataprovider.h" #include "qgstreamerplayersession.h" #include <QDebug> #include <gst/gstversion.h> QT_BEGIN_NAMESPACE struct QGstreamerMetaDataKeyLookup { QString key; const char *token; }; static const QGstreamerMetaDataKeyLookup qt_gstreamerMetaDataKeys[] = { { QtMultimedia::MetaData::Title, GST_TAG_TITLE }, //{ QtMultimedia::MetaData::SubTitle, 0 }, //{ QtMultimedia::MetaData::Author, 0 }, { QtMultimedia::MetaData::Comment, GST_TAG_COMMENT }, { QtMultimedia::MetaData::Description, GST_TAG_DESCRIPTION }, //{ QtMultimedia::MetaData::Category, 0 }, { QtMultimedia::MetaData::Genre, GST_TAG_GENRE }, { QtMultimedia::MetaData::Year, "year" }, //{ QtMultimedia::MetaData::UserRating, 0 }, { QtMultimedia::MetaData::Language, GST_TAG_LANGUAGE_CODE }, { QtMultimedia::MetaData::Publisher, GST_TAG_ORGANIZATION }, { QtMultimedia::MetaData::Copyright, GST_TAG_COPYRIGHT }, //{ QtMultimedia::MetaData::ParentalRating, 0 }, //{ QtMultimedia::MetaData::RatingOrganisation, 0 }, // Media //{ QtMultimedia::MetaData::Size, 0 }, //{ QtMultimedia::MetaData::MediaType, 0 }, { QtMultimedia::MetaData::Duration, GST_TAG_DURATION }, // Audio { QtMultimedia::MetaData::AudioBitRate, GST_TAG_BITRATE }, { QtMultimedia::MetaData::AudioCodec, GST_TAG_AUDIO_CODEC }, //{ QtMultimedia::MetaData::ChannelCount, 0 }, //{ QtMultimedia::MetaData::SampleRate, 0 }, // Music { QtMultimedia::MetaData::AlbumTitle, GST_TAG_ALBUM }, { QtMultimedia::MetaData::AlbumArtist, GST_TAG_ARTIST}, { QtMultimedia::MetaData::ContributingArtist, GST_TAG_PERFORMER }, #if (GST_VERSION_MAJOR >= 0) && (GST_VERSION_MINOR >= 10) && (GST_VERSION_MICRO >= 19) { QtMultimedia::MetaData::Composer, GST_TAG_COMPOSER }, #endif //{ QtMultimedia::MetaData::Conductor, 0 }, //{ QtMultimedia::MetaData::Lyrics, 0 }, //{ QtMultimedia::MetaData::Mood, 0 }, { QtMultimedia::MetaData::TrackNumber, GST_TAG_TRACK_NUMBER }, //{ QtMultimedia::MetaData::CoverArtUrlSmall, 0 }, //{ QtMultimedia::MetaData::CoverArtUrlLarge, 0 }, // Image/Video { QtMultimedia::MetaData::Resolution, "resolution" }, { QtMultimedia::MetaData::PixelAspectRatio, "pixel-aspect-ratio" }, // Video //{ QtMultimedia::MetaData::VideoFrameRate, 0 }, //{ QtMultimedia::MetaData::VideoBitRate, 0 }, { QtMultimedia::MetaData::VideoCodec, GST_TAG_VIDEO_CODEC }, //{ QtMultimedia::MetaData::PosterUrl, 0 }, // Movie //{ QtMultimedia::MetaData::ChapterNumber, 0 }, //{ QtMultimedia::MetaData::Director, 0 }, { QtMultimedia::MetaData::LeadPerformer, GST_TAG_PERFORMER }, //{ QtMultimedia::MetaData::Writer, 0 }, // Photos //{ QtMultimedia::MetaData::CameraManufacturer, 0 }, //{ QtMultimedia::MetaData::CameraModel, 0 }, //{ QtMultimedia::MetaData::Event, 0 }, //{ QtMultimedia::MetaData::Subject, 0 } }; QGstreamerMetaDataProvider::QGstreamerMetaDataProvider(QGstreamerPlayerSession *session, QObject *parent) :QMetaDataReaderControl(parent), m_session(session) { connect(m_session, SIGNAL(tagsChanged()), SLOT(updateTags())); const int count = sizeof(qt_gstreamerMetaDataKeys) / sizeof(QGstreamerMetaDataKeyLookup); for (int i = 0; i < count; ++i) { m_keysMap[QByteArray(qt_gstreamerMetaDataKeys[i].token)] = qt_gstreamerMetaDataKeys[i].key; } } QGstreamerMetaDataProvider::~QGstreamerMetaDataProvider() { } bool QGstreamerMetaDataProvider::isMetaDataAvailable() const { return !m_session->tags().isEmpty(); } bool QGstreamerMetaDataProvider::isWritable() const { return false; } QVariant QGstreamerMetaDataProvider::metaData(const QString &key) const { return m_tags.value(key); } QStringList QGstreamerMetaDataProvider::availableMetaData() const { return m_tags.keys(); } void QGstreamerMetaDataProvider::updateTags() { QVariantMap oldTags = m_tags; m_tags.clear(); QSet<QString> allTags = QSet<QString>::fromList(m_tags.keys()); QMapIterator<QByteArray ,QVariant> i(m_session->tags()); while (i.hasNext()) { i.next(); //use gstreamer native keys for elements not in m_keysMap QString key = m_keysMap.value(i.key(), i.key()); m_tags[key] = i.value(); allTags.insert(i.key()); } bool changed = false; foreach (const QString &key, allTags) { const QVariant value = m_tags.value(key); if (value != oldTags.value(key)) { changed = true; emit metaDataChanged(key, value); } } if (changed) emit metaDataChanged(); } QT_END_NAMESPACE <commit_msg>QGstreamerMetaDataProvider: fix keys not mapped properly.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgstreamermetadataprovider.h" #include "qgstreamerplayersession.h" #include <QDebug> #include <gst/gstversion.h> QT_BEGIN_NAMESPACE struct QGstreamerMetaDataKeyLookup { QString key; const char *token; }; static const QGstreamerMetaDataKeyLookup qt_gstreamerMetaDataKeys[] = { { QtMultimedia::MetaData::Title, GST_TAG_TITLE }, //{ QtMultimedia::MetaData::SubTitle, 0 }, //{ QtMultimedia::MetaData::Author, 0 }, { QtMultimedia::MetaData::Comment, GST_TAG_COMMENT }, { QtMultimedia::MetaData::Description, GST_TAG_DESCRIPTION }, //{ QtMultimedia::MetaData::Category, 0 }, { QtMultimedia::MetaData::Genre, GST_TAG_GENRE }, { QtMultimedia::MetaData::Year, "year" }, //{ QtMultimedia::MetaData::UserRating, 0 }, { QtMultimedia::MetaData::Language, GST_TAG_LANGUAGE_CODE }, { QtMultimedia::MetaData::Publisher, GST_TAG_ORGANIZATION }, { QtMultimedia::MetaData::Copyright, GST_TAG_COPYRIGHT }, //{ QtMultimedia::MetaData::ParentalRating, 0 }, //{ QtMultimedia::MetaData::RatingOrganisation, 0 }, // Media //{ QtMultimedia::MetaData::Size, 0 }, //{ QtMultimedia::MetaData::MediaType, 0 }, { QtMultimedia::MetaData::Duration, GST_TAG_DURATION }, // Audio { QtMultimedia::MetaData::AudioBitRate, GST_TAG_BITRATE }, { QtMultimedia::MetaData::AudioCodec, GST_TAG_AUDIO_CODEC }, //{ QtMultimedia::MetaData::ChannelCount, 0 }, //{ QtMultimedia::MetaData::SampleRate, 0 }, // Music { QtMultimedia::MetaData::AlbumTitle, GST_TAG_ALBUM }, { QtMultimedia::MetaData::AlbumArtist, GST_TAG_ARTIST}, { QtMultimedia::MetaData::ContributingArtist, GST_TAG_PERFORMER }, #if (GST_VERSION_MAJOR >= 0) && (GST_VERSION_MINOR >= 10) && (GST_VERSION_MICRO >= 19) { QtMultimedia::MetaData::Composer, GST_TAG_COMPOSER }, #endif //{ QtMultimedia::MetaData::Conductor, 0 }, //{ QtMultimedia::MetaData::Lyrics, 0 }, //{ QtMultimedia::MetaData::Mood, 0 }, { QtMultimedia::MetaData::TrackNumber, GST_TAG_TRACK_NUMBER }, //{ QtMultimedia::MetaData::CoverArtUrlSmall, 0 }, //{ QtMultimedia::MetaData::CoverArtUrlLarge, 0 }, // Image/Video { QtMultimedia::MetaData::Resolution, "resolution" }, { QtMultimedia::MetaData::PixelAspectRatio, "pixel-aspect-ratio" }, // Video //{ QtMultimedia::MetaData::VideoFrameRate, 0 }, //{ QtMultimedia::MetaData::VideoBitRate, 0 }, { QtMultimedia::MetaData::VideoCodec, GST_TAG_VIDEO_CODEC }, //{ QtMultimedia::MetaData::PosterUrl, 0 }, // Movie //{ QtMultimedia::MetaData::ChapterNumber, 0 }, //{ QtMultimedia::MetaData::Director, 0 }, { QtMultimedia::MetaData::LeadPerformer, GST_TAG_PERFORMER }, //{ QtMultimedia::MetaData::Writer, 0 }, // Photos //{ QtMultimedia::MetaData::CameraManufacturer, 0 }, //{ QtMultimedia::MetaData::CameraModel, 0 }, //{ QtMultimedia::MetaData::Event, 0 }, //{ QtMultimedia::MetaData::Subject, 0 } }; QGstreamerMetaDataProvider::QGstreamerMetaDataProvider(QGstreamerPlayerSession *session, QObject *parent) :QMetaDataReaderControl(parent), m_session(session) { connect(m_session, SIGNAL(tagsChanged()), SLOT(updateTags())); const int count = sizeof(qt_gstreamerMetaDataKeys) / sizeof(QGstreamerMetaDataKeyLookup); for (int i = 0; i < count; ++i) { m_keysMap[QByteArray(qt_gstreamerMetaDataKeys[i].token)] = qt_gstreamerMetaDataKeys[i].key; } } QGstreamerMetaDataProvider::~QGstreamerMetaDataProvider() { } bool QGstreamerMetaDataProvider::isMetaDataAvailable() const { return !m_session->tags().isEmpty(); } bool QGstreamerMetaDataProvider::isWritable() const { return false; } QVariant QGstreamerMetaDataProvider::metaData(const QString &key) const { return m_tags.value(key); } QStringList QGstreamerMetaDataProvider::availableMetaData() const { return m_tags.keys(); } void QGstreamerMetaDataProvider::updateTags() { QVariantMap oldTags = m_tags; m_tags.clear(); QSet<QString> allTags = QSet<QString>::fromList(m_tags.keys()); QMapIterator<QByteArray ,QVariant> i(m_session->tags()); while (i.hasNext()) { i.next(); //use gstreamer native keys for elements not in m_keysMap QString key = m_keysMap.value(i.key(), i.key()); m_tags[key] = i.value(); allTags.insert(key); } bool changed = false; foreach (const QString &key, allTags) { const QVariant value = m_tags.value(key); if (value != oldTags.value(key)) { changed = true; emit metaDataChanged(key, value); } } if (changed) emit metaDataChanged(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "functionhintproposalwidget.h" #include "ifunctionhintproposalmodel.h" #include "codeassistant.h" #include <utils/faketooltip.h> #include <utils/hostosinfo.h> #include <QDebug> #include <QApplication> #include <QLabel> #include <QToolButton> #include <QHBoxLayout> #include <QDesktopWidget> #include <QKeyEvent> namespace TextEditor { // ------------------------- // HintProposalWidgetPrivate // ------------------------- struct FunctionHintProposalWidgetPrivate { FunctionHintProposalWidgetPrivate(); const QWidget *m_underlyingWidget; CodeAssistant *m_assistant; IFunctionHintProposalModel *m_model; Utils::FakeToolTip *m_popupFrame; QLabel *m_numberLabel; QLabel *m_hintLabel; QWidget *m_pager; QRect m_displayRect; int m_currentHint; int m_totalHints; int m_currentArgument; bool m_escapePressed; }; FunctionHintProposalWidgetPrivate::FunctionHintProposalWidgetPrivate() : m_underlyingWidget(0) , m_assistant(0) , m_model(0) , m_popupFrame(new Utils::FakeToolTip) , m_numberLabel(new QLabel) , m_hintLabel(new QLabel) , m_pager(new QWidget) , m_currentHint(-1) , m_totalHints(0) , m_currentArgument(-1) , m_escapePressed(false) { m_hintLabel->setTextFormat(Qt::RichText); } // ------------------ // HintProposalWidget // ------------------ FunctionHintProposalWidget::FunctionHintProposalWidget() : d(new FunctionHintProposalWidgetPrivate) { QToolButton *downArrow = new QToolButton; downArrow->setArrowType(Qt::DownArrow); downArrow->setFixedSize(16, 16); downArrow->setAutoRaise(true); QToolButton *upArrow = new QToolButton; upArrow->setArrowType(Qt::UpArrow); upArrow->setFixedSize(16, 16); upArrow->setAutoRaise(true); QHBoxLayout *pagerLayout = new QHBoxLayout(d->m_pager); pagerLayout->setMargin(0); pagerLayout->setSpacing(0); pagerLayout->addWidget(upArrow); pagerLayout->addWidget(d->m_numberLabel); pagerLayout->addWidget(downArrow); QHBoxLayout *popupLayout = new QHBoxLayout(d->m_popupFrame); popupLayout->setMargin(0); popupLayout->setSpacing(0); popupLayout->addWidget(d->m_pager); popupLayout->addWidget(d->m_hintLabel); connect(upArrow, SIGNAL(clicked()), SLOT(previousPage())); connect(downArrow, SIGNAL(clicked()), SLOT(nextPage())); qApp->installEventFilter(this); setFocusPolicy(Qt::NoFocus); } FunctionHintProposalWidget::~FunctionHintProposalWidget() { delete d->m_model; delete d; } void FunctionHintProposalWidget::setAssistant(CodeAssistant *assistant) { d->m_assistant = assistant; } void FunctionHintProposalWidget::setReason(AssistReason) {} void FunctionHintProposalWidget::setKind(AssistKind) {} void FunctionHintProposalWidget::setUnderlyingWidget(const QWidget *underlyingWidget) { d->m_underlyingWidget = underlyingWidget; } void FunctionHintProposalWidget::setModel(IAssistProposalModel *model) { d->m_model = static_cast<IFunctionHintProposalModel *>(model); } void FunctionHintProposalWidget::setDisplayRect(const QRect &rect) { d->m_displayRect = rect; } void FunctionHintProposalWidget::setIsSynchronized(bool) {} void FunctionHintProposalWidget::showProposal(const QString &prefix) { d->m_totalHints = d->m_model->size(); if (d->m_totalHints == 0) { abort(); return; } d->m_pager->setVisible(d->m_totalHints > 1); d->m_currentHint = 0; if (!updateAndCheck(prefix)) { abort(); return; } d->m_popupFrame->show(); } void FunctionHintProposalWidget::updateProposal(const QString &prefix) { updateAndCheck(prefix); } void FunctionHintProposalWidget::closeProposal() { abort(); } void FunctionHintProposalWidget::abort() { if (d->m_popupFrame->isVisible()) d->m_popupFrame->close(); deleteLater(); } bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { d->m_escapePressed = true; e->accept(); } break; case QEvent::KeyPress: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { d->m_escapePressed = true; e->accept(); } if (d->m_model->size() > 1) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Up) { previousPage(); return true; } else if (ke->key() == Qt::Key_Down) { nextPage(); return true; } return false; } break; case QEvent::KeyRelease: { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape && d->m_escapePressed) { abort(); emit explicitlyAborted(); return false; } else if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { if (d->m_model->size() > 1) return false; } d->m_assistant->notifyChange(); } break; case QEvent::WindowDeactivate: case QEvent::FocusOut: if (obj != d->m_underlyingWidget) break; abort(); break; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::Wheel: { QWidget *widget = qobject_cast<QWidget *>(obj); if (!d->m_popupFrame->isAncestorOf(widget)) { abort(); } else if (e->type() == QEvent::Wheel) { if (static_cast<QWheelEvent*>(e)->delta() > 0) previousPage(); else nextPage(); return true; } } break; default: break; } return false; } void FunctionHintProposalWidget::nextPage() { d->m_currentHint = (d->m_currentHint + 1) % d->m_totalHints; updateContent(); } void FunctionHintProposalWidget::previousPage() { if (d->m_currentHint == 0) d->m_currentHint = d->m_totalHints - 1; else --d->m_currentHint; updateContent(); } bool FunctionHintProposalWidget::updateAndCheck(const QString &prefix) { const int activeArgument = d->m_model->activeArgument(prefix); if (activeArgument == -1) { abort(); return false; } else if (activeArgument != d->m_currentArgument) { d->m_currentArgument = activeArgument; updateContent(); } return true; } void FunctionHintProposalWidget::updateContent() { d->m_hintLabel->setText(d->m_model->text(d->m_currentHint)); d->m_numberLabel->setText(tr("%1 of %2").arg(d->m_currentHint + 1).arg(d->m_totalHints)); updatePosition(); } void FunctionHintProposalWidget::updatePosition() { const QDesktopWidget *desktop = QApplication::desktop(); const QRect &screen = Utils::HostOsInfo::isMacHost() ? desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget)) : desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget)); d->m_pager->setFixedWidth(d->m_pager->minimumSizeHint().width()); d->m_hintLabel->setWordWrap(false); const int maxDesiredWidth = screen.width() - 10; const QSize &minHint = d->m_popupFrame->minimumSizeHint(); if (minHint.width() > maxDesiredWidth) { d->m_hintLabel->setWordWrap(true); d->m_popupFrame->setFixedWidth(maxDesiredWidth); const int extra = d->m_popupFrame->contentsMargins().bottom() + d->m_popupFrame->contentsMargins().top(); d->m_popupFrame->setFixedHeight( d->m_hintLabel->heightForWidth(maxDesiredWidth - d->m_pager->width()) + extra); } else { d->m_popupFrame->setFixedSize(minHint); } const QSize &sz = d->m_popupFrame->size(); QPoint pos = d->m_displayRect.topLeft(); pos.setY(pos.y() - sz.height() - 1); if (pos.x() + sz.width() > screen.right()) pos.setX(screen.right() - sz.width()); d->m_popupFrame->move(pos); } } // TextEditor <commit_msg>Editors/Function hint: Guard against potential crashes<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "functionhintproposalwidget.h" #include "ifunctionhintproposalmodel.h" #include "codeassistant.h" #include <utils/faketooltip.h> #include <utils/hostosinfo.h> #include <utils/qtcassert.h> #include <QDebug> #include <QApplication> #include <QLabel> #include <QToolButton> #include <QHBoxLayout> #include <QDesktopWidget> #include <QKeyEvent> namespace TextEditor { // ------------------------- // HintProposalWidgetPrivate // ------------------------- struct FunctionHintProposalWidgetPrivate { FunctionHintProposalWidgetPrivate(); const QWidget *m_underlyingWidget; CodeAssistant *m_assistant; IFunctionHintProposalModel *m_model; Utils::FakeToolTip *m_popupFrame; QLabel *m_numberLabel; QLabel *m_hintLabel; QWidget *m_pager; QRect m_displayRect; int m_currentHint; int m_totalHints; int m_currentArgument; bool m_escapePressed; }; FunctionHintProposalWidgetPrivate::FunctionHintProposalWidgetPrivate() : m_underlyingWidget(0) , m_assistant(0) , m_model(0) , m_popupFrame(new Utils::FakeToolTip) , m_numberLabel(new QLabel) , m_hintLabel(new QLabel) , m_pager(new QWidget) , m_currentHint(-1) , m_totalHints(0) , m_currentArgument(-1) , m_escapePressed(false) { m_hintLabel->setTextFormat(Qt::RichText); } // ------------------ // HintProposalWidget // ------------------ FunctionHintProposalWidget::FunctionHintProposalWidget() : d(new FunctionHintProposalWidgetPrivate) { QToolButton *downArrow = new QToolButton; downArrow->setArrowType(Qt::DownArrow); downArrow->setFixedSize(16, 16); downArrow->setAutoRaise(true); QToolButton *upArrow = new QToolButton; upArrow->setArrowType(Qt::UpArrow); upArrow->setFixedSize(16, 16); upArrow->setAutoRaise(true); QHBoxLayout *pagerLayout = new QHBoxLayout(d->m_pager); pagerLayout->setMargin(0); pagerLayout->setSpacing(0); pagerLayout->addWidget(upArrow); pagerLayout->addWidget(d->m_numberLabel); pagerLayout->addWidget(downArrow); QHBoxLayout *popupLayout = new QHBoxLayout(d->m_popupFrame); popupLayout->setMargin(0); popupLayout->setSpacing(0); popupLayout->addWidget(d->m_pager); popupLayout->addWidget(d->m_hintLabel); connect(upArrow, SIGNAL(clicked()), SLOT(previousPage())); connect(downArrow, SIGNAL(clicked()), SLOT(nextPage())); qApp->installEventFilter(this); setFocusPolicy(Qt::NoFocus); } FunctionHintProposalWidget::~FunctionHintProposalWidget() { delete d->m_model; delete d; } void FunctionHintProposalWidget::setAssistant(CodeAssistant *assistant) { d->m_assistant = assistant; } void FunctionHintProposalWidget::setReason(AssistReason) {} void FunctionHintProposalWidget::setKind(AssistKind) {} void FunctionHintProposalWidget::setUnderlyingWidget(const QWidget *underlyingWidget) { d->m_underlyingWidget = underlyingWidget; } void FunctionHintProposalWidget::setModel(IAssistProposalModel *model) { d->m_model = static_cast<IFunctionHintProposalModel *>(model); } void FunctionHintProposalWidget::setDisplayRect(const QRect &rect) { d->m_displayRect = rect; } void FunctionHintProposalWidget::setIsSynchronized(bool) {} void FunctionHintProposalWidget::showProposal(const QString &prefix) { d->m_totalHints = d->m_model->size(); if (d->m_totalHints == 0) { abort(); return; } d->m_pager->setVisible(d->m_totalHints > 1); d->m_currentHint = 0; if (!updateAndCheck(prefix)) { abort(); return; } d->m_popupFrame->show(); } void FunctionHintProposalWidget::updateProposal(const QString &prefix) { updateAndCheck(prefix); } void FunctionHintProposalWidget::closeProposal() { abort(); } void FunctionHintProposalWidget::abort() { if (d->m_popupFrame->isVisible()) d->m_popupFrame->close(); deleteLater(); } bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { d->m_escapePressed = true; e->accept(); } break; case QEvent::KeyPress: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { d->m_escapePressed = true; e->accept(); } QTC_CHECK(d->m_model); if (d->m_model && d->m_model->size() > 1) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Up) { previousPage(); return true; } else if (ke->key() == Qt::Key_Down) { nextPage(); return true; } return false; } break; case QEvent::KeyRelease: { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape && d->m_escapePressed) { abort(); emit explicitlyAborted(); return false; } else if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { QTC_CHECK(d->m_model); if (d->m_model && d->m_model->size() > 1) return false; } QTC_CHECK(d->m_assistant); if (d->m_assistant) d->m_assistant->notifyChange(); } break; case QEvent::WindowDeactivate: case QEvent::FocusOut: if (obj != d->m_underlyingWidget) break; abort(); break; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::Wheel: { QWidget *widget = qobject_cast<QWidget *>(obj); if (!d->m_popupFrame->isAncestorOf(widget)) { abort(); } else if (e->type() == QEvent::Wheel) { if (static_cast<QWheelEvent*>(e)->delta() > 0) previousPage(); else nextPage(); return true; } } break; default: break; } return false; } void FunctionHintProposalWidget::nextPage() { d->m_currentHint = (d->m_currentHint + 1) % d->m_totalHints; updateContent(); } void FunctionHintProposalWidget::previousPage() { if (d->m_currentHint == 0) d->m_currentHint = d->m_totalHints - 1; else --d->m_currentHint; updateContent(); } bool FunctionHintProposalWidget::updateAndCheck(const QString &prefix) { const int activeArgument = d->m_model->activeArgument(prefix); if (activeArgument == -1) { abort(); return false; } else if (activeArgument != d->m_currentArgument) { d->m_currentArgument = activeArgument; updateContent(); } return true; } void FunctionHintProposalWidget::updateContent() { d->m_hintLabel->setText(d->m_model->text(d->m_currentHint)); d->m_numberLabel->setText(tr("%1 of %2").arg(d->m_currentHint + 1).arg(d->m_totalHints)); updatePosition(); } void FunctionHintProposalWidget::updatePosition() { const QDesktopWidget *desktop = QApplication::desktop(); const QRect &screen = Utils::HostOsInfo::isMacHost() ? desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget)) : desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget)); d->m_pager->setFixedWidth(d->m_pager->minimumSizeHint().width()); d->m_hintLabel->setWordWrap(false); const int maxDesiredWidth = screen.width() - 10; const QSize &minHint = d->m_popupFrame->minimumSizeHint(); if (minHint.width() > maxDesiredWidth) { d->m_hintLabel->setWordWrap(true); d->m_popupFrame->setFixedWidth(maxDesiredWidth); const int extra = d->m_popupFrame->contentsMargins().bottom() + d->m_popupFrame->contentsMargins().top(); d->m_popupFrame->setFixedHeight( d->m_hintLabel->heightForWidth(maxDesiredWidth - d->m_pager->width()) + extra); } else { d->m_popupFrame->setFixedSize(minHint); } const QSize &sz = d->m_popupFrame->size(); QPoint pos = d->m_displayRect.topLeft(); pos.setY(pos.y() - sz.height() - 1); if (pos.x() + sz.width() > screen.right()) pos.setX(screen.right() - sz.width()); d->m_popupFrame->move(pos); } } // TextEditor <|endoftext|>
<commit_before>#include "triangle.hpp" #include <algorithm> Triangle::Triangle(): Shape(), ecke1_{1.0f,0.0f,-2.0f}, ecke2_{-1.0f,0.0f,-2.0f}, ecke3_{0.0f,1.0f,-2.0f} {} Triangle::Triangle(glm::vec3 const& ecke1, glm::vec3 const& ecke2, glm::vec3 const& ecke3): Shape(), /*ecke1_{ecke1.x,ecke1.y,ecke1.z}, ecke2_{ecke2.x,ecke2.y,ecke2.z}, ecke3_{ecke3.x,ecke3.y,ecke3.z}*/ ecke1_{ecke1}, ecke2_{ecke2}, ecke3_{ecke3} {} Triangle::Triangle(glm::vec3 const& ecke1, glm::vec3 const& ecke2, glm::vec3 const& ecke3, std::string const& name, Material const& mat): Shape(name, mat), /*ecke1_{ecke1.x,ecke1.y,ecke1.z}, ecke2_{ecke2.x,ecke2.y,ecke2.z}, ecke3_{ecke3.x,ecke3.y,ecke3.z}*/ ecke1_{ecke1}, ecke2_{ecke2}, ecke3_{ecke3} {} std::ostream& Triangle::print(std::ostream& os) const{ Shape::print(os); os << "Punkt 1: ("<<ecke1_.x << ", "<<ecke1_.y << ", "<<ecke1_.z << "Punkt 2: ("<< ecke2_.x << ", "<<ecke2_.y << ", "<<ecke2_.z << "Punkt 3: ("<< ecke3_.x << ", "<<ecke3_.y << ", "<<ecke3_.z << "\n"; } /*Hit Triangle::intersect(Ray const& ray) { Hit defaulthit; return defaulthit; }*/ Hit Triangle::intersect(Ray const& ray) { Hit impact; Hit noimpact; glm::vec3 e1,e2; glm::vec3 P,Q,T; float det, inv_det, u, v; float t; float bias = 0.00009; e1 = sub(ecke2_,ecke1_); e2 = sub(ecke3_,ecke1_); P = crossp(ray.direction,e2); det = skalar(e1,P); if(det > -bias && det < bias)return noimpact; inv_det = 1.0f / det; T = ray.origin-ecke1_; u = skalar(T,P) * inv_det; if(u < 0.0f || u > 1.0f)return noimpact; Q = crossp(T,e1); v = skalar(ray.direction,Q) * inv_det; if (v < 0.0 || u + v > 1.0)return noimpact; t = skalar(e2,Q) * inv_det; if (t > bias) { float distance = t; impact.distance_=t; impact.target_ = ray.origin + (distance * glm::normalize(ray.direction)); glm::vec3 norm = crossp(ecke1_-ecke2_,ecke1_-ecke3_); glm::normalize(norm); impact.hit_=true; impact.normal_=norm; impact.sptr_=this; //std::cout << "t: " << t << "\n"; return impact; std::cout << "ende"; //std::cout << norm.x << norm.y << norm.z; //taken from https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm } return noimpact; /* Hit HelloHitty; glm::vec3 norm = crossp(ecke1_-ecke2_,ecke1_-ecke3_); //glm::normalize(norm); float d = skalar(norm , ray.direction); if(d != 0) { float distance = (-(norm.x*(ray.origin.x - ecke1_.x))-(norm.y*(ray.origin.y - ecke1_.y)) -(norm.z*(ray.origin.z - ecke1_.z))) / d; if(distance > 0) { HelloHitty.target_ = ray.origin + (distance * ray.direction); { if(skalar(ecke3_-ecke1_, ecke1_ - HelloHitty.target_) <= skalar(ecke3_ - ecke1_, ecke2_ - ecke1_) and skalar(ecke1_-ecke2_, ecke2_ - HelloHitty.target_) <= skalar(ecke1_ - ecke2_, ecke3_ - ecke2_) and skalar(ecke2_-ecke3_, ecke3_ - HelloHitty.target_) <= skalar(ecke2_ - ecke3_, ecke1_ - ecke3_) ) { HelloHitty.hit_ = true; HelloHitty.normal_ = norm; HelloHitty.sptr_ = this; HelloHitty.distance_= distance; // glm::length(HelloHitty.target_ - ray.origin); } } } } return HelloHitty;*/ /*glm::vec3 sub21{0.0f,0.0f,0.0f}; sub21.x = ecke2_.x - ecke1_.x; sub21.y = ecke2_.y - ecke1_.y; sub21.z = ecke2_.z - ecke1_.z; glm::vec3 sub31{0.0f,0.0f,0.0f}; sub31.x = ecke3_.x - ecke1_.x; sub31.y = ecke3_.y - ecke1_.y; sub31.z = ecke3_.z - ecke1_.z; glm::vec3 N = crossp(sub21,sub31); float A = betrag(N); Hit HelloHitty; float NdotprodwithRaydir = skalar(N, ray.direction); if (fabs(NdotprodwithRaydir) < 0.005)return HelloHitty; float d = skalar(N,ecke1_); float t = (skalar(N,ray.origin)+d) / NdotprodwithRaydir; glm::vec3 p = ray.origin + t * ray.direction; glm::vec3 C{0.0f,0.0f,0.0f}; //ecke 1 glm::vec3 eckeone = ecke2_-ecke1_; glm::vec3 vpone = p - ecke1_; C=crossp(ecke1_,vpone); if(skalar(N,C)<0)return HelloHitty; //ecke 2 glm::vec3 ecketwo = ecke3_-ecke2_; glm::vec3 vptwo = p - ecke2_; C=crossp(ecke2_,vptwo); if(skalar(N,C)<0)return HelloHitty; //ecke 3 glm::vec3 eckethree = ecke1_-ecke3_; glm::vec3 vpthree = p - ecke3_; C=crossp(ecke3_,vpthree); if(skalar(N,C)<0)return HelloHitty; glm::vec3 target= ray.origin + glm::normalize(ray.direction) * t; glm::vec3 normale= glm::normalize(crossp(sub21,sub31)); Hit trifft; trifft.hit_=true; trifft.distance_=t; trifft.target_=target; trifft.normal_=normale; trifft.sptr_=this; return trifft;*/ } /*bool rayTriangleIntersect( const Vec3f &orig, const Vec3f &dir, const Vec3f &v0, const Vec3f &v1, const Vec3f &v2, float &t) { // compute plane's normal Vec3f v0v1 = v1 - v0; Vec3f v0v2 = v2 - v0; // no need to normalize Vec3f N = v0v1.crossProduct(v0v2); // N float area2 = N.length(); // Step 1: finding P // check if ray and plane are parallel ? float NdotRayDirection = N.dotProduct(dir); if (fabs(NdotRayDirection) < kEpsilon) // almost 0 return false; // they are parallel so they don't intersect ! // compute d parameter using equation 2 float d = N.dotProduct(v0); // compute t (equation 3) t = (N.dotProduct(orig) + d) / NdotRayDirection; // check if the triangle is in behind the ray if (t < 0) return false; // the triangle is behind // compute the intersection point using equation 1 Vec3f P = orig + t * dir; // Step 2: inside-outside test Vec3f C; // vector perpendicular to triangle's plane // edge 0 Vec3f edge0 = v1 - v0; Vec3f vp0 = P - v0; C = edge0.crossProduct(vp0); if (N.dotProduct(C) < 0) return false; // P is on the right side // edge 1 Vec3f edge1 = v2 - v1; Vec3f vp1 = P - v1; C = edge1.crossProduct(vp1); if (N.dotProduct(C) < 0) return false; // P is on the right side // edge 2 Vec3f edge2 = v0 - v2; Vec3f vecke2_ = P - v2; C = edge2.crossProduct(vecke2_); if (N.dotProduct(C) < 0) return false; // P is on the right side; return true; // this ray hits the triangle } */<commit_msg>there you go normalized normal vector<commit_after>#include "triangle.hpp" #include <algorithm> Triangle::Triangle(): Shape(), ecke1_{1.0f,0.0f,-2.0f}, ecke2_{-1.0f,0.0f,-2.0f}, ecke3_{0.0f,1.0f,-2.0f} {} Triangle::Triangle(glm::vec3 const& ecke1, glm::vec3 const& ecke2, glm::vec3 const& ecke3): Shape(), /*ecke1_{ecke1.x,ecke1.y,ecke1.z}, ecke2_{ecke2.x,ecke2.y,ecke2.z}, ecke3_{ecke3.x,ecke3.y,ecke3.z}*/ ecke1_{ecke1}, ecke2_{ecke2}, ecke3_{ecke3} {} Triangle::Triangle(glm::vec3 const& ecke1, glm::vec3 const& ecke2, glm::vec3 const& ecke3, std::string const& name, Material const& mat): Shape(name, mat), /*ecke1_{ecke1.x,ecke1.y,ecke1.z}, ecke2_{ecke2.x,ecke2.y,ecke2.z}, ecke3_{ecke3.x,ecke3.y,ecke3.z}*/ ecke1_{ecke1}, ecke2_{ecke2}, ecke3_{ecke3} {} std::ostream& Triangle::print(std::ostream& os) const{ Shape::print(os); os << "Punkt 1: ("<<ecke1_.x << ", "<<ecke1_.y << ", "<<ecke1_.z << "Punkt 2: ("<< ecke2_.x << ", "<<ecke2_.y << ", "<<ecke2_.z << "Punkt 3: ("<< ecke3_.x << ", "<<ecke3_.y << ", "<<ecke3_.z << "\n"; } /*Hit Triangle::intersect(Ray const& ray) { Hit defaulthit; return defaulthit; }*/ Hit Triangle::intersect(Ray const& ray) { Hit impact; Hit noimpact; glm::vec3 e1,e2; glm::vec3 P,Q,T; float det, inv_det, u, v; float t; float bias = 0.00009; e1 = sub(ecke2_,ecke1_); e2 = sub(ecke3_,ecke1_); P = crossp(ray.direction,e2); det = skalar(e1,P); if(det > -bias && det < bias)return noimpact; inv_det = 1.0f / det; T = ray.origin-ecke1_; u = skalar(T,P) * inv_det; if(u < 0.0f || u > 1.0f)return noimpact; Q = crossp(T,e1); v = skalar(ray.direction,Q) * inv_det; if (v < 0.0 || u + v > 1.0)return noimpact; t = skalar(e2,Q) * inv_det; if (t > bias) { float distance = t; impact.distance_=t; impact.target_ = ray.origin + (distance * glm::normalize(ray.direction)); glm::vec3 norm = crossp(ecke1_-ecke2_,ecke1_-ecke3_); norm = glm::normalize(norm); impact.hit_=true; impact.normal_=norm; impact.sptr_=this; //std::cout << "t: " << t << "\n"; return impact; std::cout << "ende"; //std::cout << norm.x << norm.y << norm.z; //taken from https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm } return noimpact; /* Hit HelloHitty; glm::vec3 norm = crossp(ecke1_-ecke2_,ecke1_-ecke3_); //glm::normalize(norm); float d = skalar(norm , ray.direction); if(d != 0) { float distance = (-(norm.x*(ray.origin.x - ecke1_.x))-(norm.y*(ray.origin.y - ecke1_.y)) -(norm.z*(ray.origin.z - ecke1_.z))) / d; if(distance > 0) { HelloHitty.target_ = ray.origin + (distance * ray.direction); { if(skalar(ecke3_-ecke1_, ecke1_ - HelloHitty.target_) <= skalar(ecke3_ - ecke1_, ecke2_ - ecke1_) and skalar(ecke1_-ecke2_, ecke2_ - HelloHitty.target_) <= skalar(ecke1_ - ecke2_, ecke3_ - ecke2_) and skalar(ecke2_-ecke3_, ecke3_ - HelloHitty.target_) <= skalar(ecke2_ - ecke3_, ecke1_ - ecke3_) ) { HelloHitty.hit_ = true; HelloHitty.normal_ = norm; HelloHitty.sptr_ = this; HelloHitty.distance_= distance; // glm::length(HelloHitty.target_ - ray.origin); } } } } return HelloHitty;*/ /*glm::vec3 sub21{0.0f,0.0f,0.0f}; sub21.x = ecke2_.x - ecke1_.x; sub21.y = ecke2_.y - ecke1_.y; sub21.z = ecke2_.z - ecke1_.z; glm::vec3 sub31{0.0f,0.0f,0.0f}; sub31.x = ecke3_.x - ecke1_.x; sub31.y = ecke3_.y - ecke1_.y; sub31.z = ecke3_.z - ecke1_.z; glm::vec3 N = crossp(sub21,sub31); float A = betrag(N); Hit HelloHitty; float NdotprodwithRaydir = skalar(N, ray.direction); if (fabs(NdotprodwithRaydir) < 0.005)return HelloHitty; float d = skalar(N,ecke1_); float t = (skalar(N,ray.origin)+d) / NdotprodwithRaydir; glm::vec3 p = ray.origin + t * ray.direction; glm::vec3 C{0.0f,0.0f,0.0f}; //ecke 1 glm::vec3 eckeone = ecke2_-ecke1_; glm::vec3 vpone = p - ecke1_; C=crossp(ecke1_,vpone); if(skalar(N,C)<0)return HelloHitty; //ecke 2 glm::vec3 ecketwo = ecke3_-ecke2_; glm::vec3 vptwo = p - ecke2_; C=crossp(ecke2_,vptwo); if(skalar(N,C)<0)return HelloHitty; //ecke 3 glm::vec3 eckethree = ecke1_-ecke3_; glm::vec3 vpthree = p - ecke3_; C=crossp(ecke3_,vpthree); if(skalar(N,C)<0)return HelloHitty; glm::vec3 target= ray.origin + glm::normalize(ray.direction) * t; glm::vec3 normale= glm::normalize(crossp(sub21,sub31)); Hit trifft; trifft.hit_=true; trifft.distance_=t; trifft.target_=target; trifft.normal_=normale; trifft.sptr_=this; return trifft;*/ } /*bool rayTriangleIntersect( const Vec3f &orig, const Vec3f &dir, const Vec3f &v0, const Vec3f &v1, const Vec3f &v2, float &t) { // compute plane's normal Vec3f v0v1 = v1 - v0; Vec3f v0v2 = v2 - v0; // no need to normalize Vec3f N = v0v1.crossProduct(v0v2); // N float area2 = N.length(); // Step 1: finding P // check if ray and plane are parallel ? float NdotRayDirection = N.dotProduct(dir); if (fabs(NdotRayDirection) < kEpsilon) // almost 0 return false; // they are parallel so they don't intersect ! // compute d parameter using equation 2 float d = N.dotProduct(v0); // compute t (equation 3) t = (N.dotProduct(orig) + d) / NdotRayDirection; // check if the triangle is in behind the ray if (t < 0) return false; // the triangle is behind // compute the intersection point using equation 1 Vec3f P = orig + t * dir; // Step 2: inside-outside test Vec3f C; // vector perpendicular to triangle's plane // edge 0 Vec3f edge0 = v1 - v0; Vec3f vp0 = P - v0; C = edge0.crossProduct(vp0); if (N.dotProduct(C) < 0) return false; // P is on the right side // edge 1 Vec3f edge1 = v2 - v1; Vec3f vp1 = P - v1; C = edge1.crossProduct(vp1); if (N.dotProduct(C) < 0) return false; // P is on the right side // edge 2 Vec3f edge2 = v0 - v2; Vec3f vecke2_ = P - v2; C = edge2.crossProduct(vecke2_); if (N.dotProduct(C) < 0) return false; // P is on the right side; return true; // this ray hits the triangle } */<|endoftext|>
<commit_before> #include <pgdb2.h> int main (int argc, char *argv[]) { pagedb::Options opts; opts.f_read = true; opts.f_write = true; opts.f_create = true; pagedb::DB db("foo.db", opts); return 0; } <commit_msg>[test] basic: test for constructor failure upon non-existent db<commit_after> #include <pgdb2.h> #include <stdexcept> #include <assert.h> int main (int argc, char *argv[]) { pagedb::Options opts; opts.f_read = true; opts.f_write = false; opts.f_create = false; // TEST: fail, b/c foo.db does not exist bool saw_err = false; try { pagedb::DB db("foo.db", opts); } catch (const std::runtime_error& error) { saw_err = true; } catch (...) { assert(0); } assert(saw_err == true); // TEST: open/close foo.db opts.f_read = true; opts.f_write = true; opts.f_create = true; try { pagedb::DB db("foo.db", opts); } catch (...) { assert(0); } return 0; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 University of Groningen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "VRPNInputPrivatePCH.h" #include "VRPNInputDeviceManager.h" #if PLATFORM_WINDOWS #include "AllowWindowsPlatformTypes.h" #include "vrpn_Tracker.h" #include "vrpn_Button.h" #include "HideWindowsPlatformTypes.h" #elif PLATFORM_LINUX #include "vrpn_Tracker.h" #include "vrpn_Button.h" #endif DEFINE_LOG_CATEGORY(LogVRPNInputDevice); class FVRPNInputPlugin : public IInputDeviceModule { public: /* * We override this so we can init the keys before the blueprints are compiled on editor startup * if we do not do this here we will get warnings in blueprints. */ virtual void StartupModule() override { IModularFeatures::Get().RegisterModularFeature(GetModularFeatureName(), this); UE_LOG(LogVRPNInputDevice, Log, TEXT("Locating VRPN config file.")); FString ConfigFile; if(!FParse::Value(FCommandLine::Get(), TEXT("VRPNConfigFile="), ConfigFile)) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Could not find VRPN configuration file: %s."), *ConfigFile); return; } if(!FPaths::FileExists(ConfigFile)) { return; UE_LOG(LogVRPNInputDevice, Warning, TEXT("Could not find VRPN configuration file: %s."), *ConfigFile); } FString EnabledDevices; TArray<FString> EnabledDevicesArray; FParse::Value(FCommandLine::Get(), TEXT("VRPNEnabledDevices="), EnabledDevices); EnabledDevices.ParseIntoArray(&EnabledDevicesArray, TEXT(","), false); TArray<FString> SectionNames; GConfig->GetSectionNames(ConfigFile,SectionNames); for(FString &SectionNameString : SectionNames) { // Tracker name is the section name itself FConfigSection* TrackerConfig = GConfig->GetSectionPrivate(*SectionNameString, false, true, ConfigFile); FString *TrackerTypeString = TrackerConfig->Find(FName(TEXT("Type"))); if(TrackerTypeString == nullptr) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: expected to find Type of type String in section [%s]. Skipping this section."), *ConfigFile, *SectionNameString); continue; } FString *TrackerAdressString = TrackerConfig->Find(FName(TEXT("Address"))); if(TrackerAdressString == nullptr) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: expected to find Address of type String in section [%s]. Skipping this section."), *ConfigFile, *SectionNameString); continue; } IVRPNInputDevice *InputDevice = nullptr; bool bEnabled = EnabledDevicesArray.Num() == 0 ||EnabledDevicesArray.Contains(SectionNameString); if(TrackerTypeString->Compare("Tracker") == 0) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Creating VRPNTrackerInputDevice %s on adress %s."), *SectionNameString, *(*TrackerAdressString)); InputDevice = new VRPNTrackerInputDevice(*TrackerAdressString, bEnabled); } else if(TrackerTypeString->Compare("Button") == 0) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Creating VRPNButtonInputDevice %s on adress %s."), *SectionNameString, *(*TrackerAdressString)); InputDevice = new VRPNButtonInputDevice(*TrackerAdressString, bEnabled); } else { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: Type should be Tracker or Button but found %s in section %s. Skipping this section."), *ConfigFile, *(*TrackerTypeString), *SectionNameString); continue; } if(!InputDevice->ParseConfig(TrackerConfig)) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: Could not parse config %s.."), *ConfigFile, *SectionNameString); continue; } if(!DeviceManager.IsValid()) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Create VRPN Input Manager.")); DeviceManager = TSharedPtr< FVRPNInputDeviceManager >(new FVRPNInputDeviceManager()); } DeviceManager->AddInputDevice(InputDevice); } } /** IPsudoControllerInterface implementation */ virtual TSharedPtr< class IInputDevice > CreateInputDevice(const TSharedRef< FGenericApplicationMessageHandler >& InMessageHandler) override { if(!DeviceManager.IsValid()) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Create VRPN Input Manager")); DeviceManager = TSharedPtr< FVRPNInputDeviceManager >(new FVRPNInputDeviceManager()); } return DeviceManager; } virtual void ShutdownModule() override { DeviceManager = nullptr; } TSharedPtr< class FVRPNInputDeviceManager > DeviceManager; }; IMPLEMENT_MODULE(FVRPNInputPlugin, VRPNInput) FVRPNInputDeviceManager::FVRPNInputDeviceManager() { } FVRPNInputDeviceManager::~FVRPNInputDeviceManager() { for(IVRPNInputDevice* InputDevice: VRPNInputDevices) { delete InputDevice; } } void FVRPNInputDeviceManager::SendControllerEvents() { for(IVRPNInputDevice* InputDevice: VRPNInputDevices) { InputDevice->Update(); } } <commit_msg>Compile fix against API change in Unreal Engine 4.8 release.<commit_after>/* The MIT License (MIT) Copyright (c) 2015 University of Groningen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "VRPNInputPrivatePCH.h" #include "VRPNInputDeviceManager.h" #if PLATFORM_WINDOWS #include "AllowWindowsPlatformTypes.h" #include "vrpn_Tracker.h" #include "vrpn_Button.h" #include "HideWindowsPlatformTypes.h" #elif PLATFORM_LINUX #include "vrpn_Tracker.h" #include "vrpn_Button.h" #endif DEFINE_LOG_CATEGORY(LogVRPNInputDevice); class FVRPNInputPlugin : public IInputDeviceModule { public: /* * We override this so we can init the keys before the blueprints are compiled on editor startup * if we do not do this here we will get warnings in blueprints. */ virtual void StartupModule() override { IModularFeatures::Get().RegisterModularFeature(GetModularFeatureName(), this); UE_LOG(LogVRPNInputDevice, Log, TEXT("Locating VRPN config file.")); FString ConfigFile; if(!FParse::Value(FCommandLine::Get(), TEXT("VRPNConfigFile="), ConfigFile)) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Could not find VRPN configuration file: %s."), *ConfigFile); return; } if(!FPaths::FileExists(ConfigFile)) { return; UE_LOG(LogVRPNInputDevice, Warning, TEXT("Could not find VRPN configuration file: %s."), *ConfigFile); } FString EnabledDevices; TArray<FString> EnabledDevicesArray; FParse::Value(FCommandLine::Get(), TEXT("VRPNEnabledDevices="), EnabledDevices); EnabledDevices.ParseIntoArray(EnabledDevicesArray, TEXT(","), false); TArray<FString> SectionNames; GConfig->GetSectionNames(ConfigFile,SectionNames); for(FString &SectionNameString : SectionNames) { // Tracker name is the section name itself FConfigSection* TrackerConfig = GConfig->GetSectionPrivate(*SectionNameString, false, true, ConfigFile); FString *TrackerTypeString = TrackerConfig->Find(FName(TEXT("Type"))); if(TrackerTypeString == nullptr) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: expected to find Type of type String in section [%s]. Skipping this section."), *ConfigFile, *SectionNameString); continue; } FString *TrackerAdressString = TrackerConfig->Find(FName(TEXT("Address"))); if(TrackerAdressString == nullptr) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: expected to find Address of type String in section [%s]. Skipping this section."), *ConfigFile, *SectionNameString); continue; } IVRPNInputDevice *InputDevice = nullptr; bool bEnabled = EnabledDevicesArray.Num() == 0 ||EnabledDevicesArray.Contains(SectionNameString); if(TrackerTypeString->Compare("Tracker") == 0) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Creating VRPNTrackerInputDevice %s on adress %s."), *SectionNameString, *(*TrackerAdressString)); InputDevice = new VRPNTrackerInputDevice(*TrackerAdressString, bEnabled); } else if(TrackerTypeString->Compare("Button") == 0) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Creating VRPNButtonInputDevice %s on adress %s."), *SectionNameString, *(*TrackerAdressString)); InputDevice = new VRPNButtonInputDevice(*TrackerAdressString, bEnabled); } else { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: Type should be Tracker or Button but found %s in section %s. Skipping this section."), *ConfigFile, *(*TrackerTypeString), *SectionNameString); continue; } if(!InputDevice->ParseConfig(TrackerConfig)) { UE_LOG(LogVRPNInputDevice, Warning, TEXT("Tracker config file %s: Could not parse config %s.."), *ConfigFile, *SectionNameString); continue; } if(!DeviceManager.IsValid()) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Create VRPN Input Manager.")); DeviceManager = TSharedPtr< FVRPNInputDeviceManager >(new FVRPNInputDeviceManager()); } DeviceManager->AddInputDevice(InputDevice); } } /** IPsudoControllerInterface implementation */ virtual TSharedPtr< class IInputDevice > CreateInputDevice(const TSharedRef< FGenericApplicationMessageHandler >& InMessageHandler) override { if(!DeviceManager.IsValid()) { UE_LOG(LogVRPNInputDevice, Log, TEXT("Create VRPN Input Manager")); DeviceManager = TSharedPtr< FVRPNInputDeviceManager >(new FVRPNInputDeviceManager()); } return DeviceManager; } virtual void ShutdownModule() override { DeviceManager = nullptr; } TSharedPtr< class FVRPNInputDeviceManager > DeviceManager; }; IMPLEMENT_MODULE(FVRPNInputPlugin, VRPNInput) FVRPNInputDeviceManager::FVRPNInputDeviceManager() { } FVRPNInputDeviceManager::~FVRPNInputDeviceManager() { for(IVRPNInputDevice* InputDevice: VRPNInputDevices) { delete InputDevice; } } void FVRPNInputDeviceManager::SendControllerEvents() { for(IVRPNInputDevice* InputDevice: VRPNInputDevices) { InputDevice->Update(); } } <|endoftext|>
<commit_before>//! @file communicator.hpp //! @brief Public interface for Communicator. //! //! @author Peter Georg #ifndef pMR_BACKENDS_MPI_COMMUNICATOR_H #define pMR_BACKENDS_MPI_COMMUNICATOR_H #include <memory> #include <vector> extern "C" { #include <mpi.h> } #include "target.hpp" namespace pMR { //! @brief Backend-agnostic Communicator. class Communicator { public: //! @brief Convert MPI Communicator to backend-agnostic //! Communicator. //! @param communicator MPI Communicator Communicator(MPI_Comm const communicator); //! @brief Creates a cartesian Communicator with topoloy.size() //! dimensions. //! @param communicator MPI Communicator to use as base for new //! cartesian Communicator. //! @param topology Number of processes in each dimension. Special //! value 0 indicates to auto detect a best fit for that //! dimension. //! @param periodic Wether a dimension is periodic or not. Communicator(MPI_Comm const communicator, std::vector<int> const &topology, std::vector<int> const &periodic); ~Communicator() = default; //! @brief Get the number of dimensions of the communicator. //! @return Number of dimensions. int dimensions() const; //! @brief The overall size of the communicator. //! @return Overall size of the communicator. int size() const; //! @brief Number of processes in specified dimension. //! @param dimension Dimension. //! @return Number of processes. int size(int const dimension) const; //! @brief Check if specified dimension is perodic. //! @param dimension Dimension. //! @return true if dimension is periodic, false otherwise. bool isPeriodic(int const dimension) const; //! @brief Get own coordinate of specified dimension. //! @param dimension Dimension. //! @return Own coordinate. int ID() const; //! @brief Get own identification number unique within this //! communicator. //! @return Own ID. int coordinate(int const dimension) const; //! @brief Get the neighbor in specified dimension, direction and //! displacement. //! @param dimension Dimension. //! @param displacement Direction (>0: upwards, <0: downwards) and //! displacement. //! @return Target representing requested neighbor. //! @note In case of a non-circular shift the neighbor might be //! null, check the target for further information. Target getNeighbor(int const dimension, int const displacement) const; //! @brief Get target by ID. //! @param ID ID. //! @return Target with requested ID. //! @note Returns target loop in case ID is own ID. //! @note Returns targel null in case of negative ID. Target getTarget(int const ID) const; MPI_Comm get() const; //! @brief Get the communicator's topology. //! @return Vector of length dimensions containing the number of //! processes in each dimension. std::vector<int> topology() const; //! @brief Get the communicator's topology periodicity. //! @return Vector of length dimensions containing 0 or 1 //! indicating wether dimensions is periodic or not. std::vector<int> periodic() const; private: MPI_Comm mCommunicator; int mID; int mSize; std::vector<int> mCoordinates; std::vector<int> mTopology; std::vector<int> mPeriodic; bool mCartesian = false; }; } #endif // pMR_BACKENDS_MPI_COMMUNICATOR_H <commit_msg>Fix documentation<commit_after>//! @file communicator.hpp //! @brief Public interface for Communicator. //! //! @author Peter Georg #ifndef pMR_BACKENDS_MPI_COMMUNICATOR_H #define pMR_BACKENDS_MPI_COMMUNICATOR_H #include <memory> #include <vector> extern "C" { #include <mpi.h> } #include "target.hpp" namespace pMR { //! @brief Backend-agnostic Communicator. class Communicator { public: //! @brief Convert MPI Communicator to backend-agnostic //! Communicator. //! @param communicator MPI Communicator Communicator(MPI_Comm const communicator); //! @brief Creates a cartesian Communicator with topoloy.size() //! dimensions. //! @param communicator MPI Communicator to use as base for new //! cartesian Communicator. //! @param topology Number of processes in each dimension. Special //! value 0 indicates to auto detect a best fit for that //! dimension. //! @param periodic Wether a dimension is periodic or not. Communicator(MPI_Comm const communicator, std::vector<int> const &topology, std::vector<int> const &periodic); ~Communicator() = default; //! @brief Get the number of dimensions of the communicator. //! @return Number of dimensions. int dimensions() const; //! @brief The overall size of the communicator. //! @return Overall size of the communicator. int size() const; //! @brief Number of processes in specified dimension. //! @param dimension Dimension. //! @return Number of processes. int size(int const dimension) const; //! @brief Check if specified dimension is perodic. //! @param dimension Dimension. //! @return true if dimension is periodic, false otherwise. bool isPeriodic(int const dimension) const; //! @brief Get own identification number unique within this //! communicator. //! @return Own ID. int ID() const; //! @brief Get own coordinate of specified dimension. //! @param dimension Dimension. //! @return Own coordinate. int coordinate(int const dimension) const; //! @brief Get the neighbor in specified dimension, direction and //! displacement. //! @param dimension Dimension. //! @param displacement Direction (>0: upwards, <0: downwards) and //! displacement. //! @return Target representing requested neighbor. //! @note In case of a non-circular shift the neighbor might be //! null, check the target for further information. Target getNeighbor(int const dimension, int const displacement) const; //! @brief Get target by ID. //! @param ID ID. //! @return Target with requested ID. //! @note Returns target loop in case ID is own ID. //! @note Returns targel null in case of negative ID. Target getTarget(int const ID) const; MPI_Comm get() const; //! @brief Get the communicator's topology. //! @return Vector of length dimensions containing the number of //! processes in each dimension. std::vector<int> topology() const; //! @brief Get the communicator's topology periodicity. //! @return Vector of length dimensions containing 0 or 1 //! indicating wether dimensions is periodic or not. std::vector<int> periodic() const; private: MPI_Comm mCommunicator; int mID; int mSize; std::vector<int> mCoordinates; std::vector<int> mTopology; std::vector<int> mPeriodic; bool mCartesian = false; }; } #endif // pMR_BACKENDS_MPI_COMMUNICATOR_H <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propacc.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-10-12 14:25:24 $ * * 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_basic.hxx" #include "propacc.hxx" #include <tools/urlobj.hxx> #include <tools/errcode.hxx> #include <svtools/svarray.hxx> #include <sbstar.hxx> #include <sbunoobj.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace cppu; using namespace rtl; //======================================================================== // Deklaration Konvertierung von Sbx nach Uno mit bekannter Zielklasse Any sbxToUnoValue( SbxVariable* pVar, const Type& rType, Property* pUnoProperty = NULL ); //======================================================================== #ifdef WNT #define CDECL _cdecl #endif #if defined(UNX) #define CDECL #endif int CDECL SbCompare_PropertyValues_Impl( const void *arg1, const void *arg2 ) { return ((PropertyValue*)arg1)->Name.compareTo( ((PropertyValue*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_PropertyValue_Impl( const void *arg1, const void *arg2 ) { const OUString *pArg1 = (OUString*) arg1; const PropertyValue **pArg2 = (const PropertyValue**) arg2; return pArg1->compareTo( (*pArg2)->Name ); } int CDECL SbCompare_Properties_Impl( const void *arg1, const void *arg2 ) { return ((Property*)arg1)->Name.compareTo( ((Property*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 ) { const OUString *pArg1 = (OUString*) arg1; const Property *pArg2 = (Property*) arg2; return pArg1->compareTo( pArg2->Name ); } //---------------------------------------------------------------------------- SbPropertyValues::SbPropertyValues() { } //---------------------------------------------------------------------------- SbPropertyValues::~SbPropertyValues() { _xInfo = Reference< XPropertySetInfo >(); for ( USHORT n = 0; n < _aPropVals.Count(); ++n ) delete _aPropVals.GetObject( n ); } //---------------------------------------------------------------------------- Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException ) { // create on demand? if ( !_xInfo.is() ) { SbPropertySetInfo *pInfo = new SbPropertySetInfo( _aPropVals ); ((SbPropertyValues*)this)->_xInfo = (XPropertySetInfo*)pInfo; } return _xInfo; } //------------------------------------------------------------------------- INT32 SbPropertyValues::GetIndex_Impl( const OUString &rPropName ) const { PropertyValue **ppPV; ppPV = (PropertyValue **) bsearch( &rPropName, _aPropVals.GetData(), _aPropVals.Count(), sizeof( PropertyValue* ), SbCompare_UString_PropertyValue_Impl ); return ppPV ? ( (ppPV-_aPropVals.GetData()) / sizeof(ppPV) ) : USHRT_MAX; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValue( const OUString& aPropertyName, const 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) { INT32 nIndex = GetIndex_Impl( aPropertyName ); PropertyValue *pPropVal = _aPropVals.GetObject( sal::static_int_cast< USHORT >(nIndex)); pPropVal->Value = aValue; } //---------------------------------------------------------------------------- Any SbPropertyValues::getPropertyValue( const OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { INT32 nIndex = GetIndex_Impl( aPropertyName ); if ( nIndex != USHRT_MAX ) return _aPropVals.GetObject( sal::static_int_cast< USHORT >(nIndex))->Value; return Any(); } //---------------------------------------------------------------------------- void SbPropertyValues::addPropertyChangeListener( const OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removePropertyChangeListener( const OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::addVetoableChangeListener( const OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removeVetoableChangeListener( const OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException) { Sequence<PropertyValue> aRet( _aPropVals.Count()); for ( USHORT n = 0; n < _aPropVals.Count(); ++n ) aRet.getArray()[n] = *_aPropVals.GetObject(n); return aRet; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues ) 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) { if ( _aPropVals.Count() ) throw PropertyExistException(); const PropertyValue *pPropVals = rPropertyValues.getConstArray(); for ( sal_Int16 n = 0; n < rPropertyValues.getLength(); ++n ) { PropertyValue *pPropVal = new PropertyValue(pPropVals[n]); _aPropVals.Insert( pPropVal, n ); } } //============================================================================ //PropertySetInfoImpl PropertySetInfoImpl::PropertySetInfoImpl() { } INT32 PropertySetInfoImpl::GetIndex_Impl( const OUString &rPropName ) const { Property *pP; pP = (Property*) bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(), sizeof( Property ), SbCompare_UString_Property_Impl ); return pP ? sal::static_int_cast<INT32>( (pP-_aProps.getConstArray()) / sizeof(pP) ) : -1; } Sequence< Property > PropertySetInfoImpl::getProperties(void) throw() { return _aProps; } Property PropertySetInfoImpl::getPropertyByName(const OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); if( USHRT_MAX != nIndex ) return _aProps.getConstArray()[ nIndex ]; return Property(); } sal_Bool PropertySetInfoImpl::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); return USHRT_MAX != nIndex; } //============================================================================ SbPropertySetInfo::SbPropertySetInfo() { } //---------------------------------------------------------------------------- SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals ) { aImpl._aProps.realloc( rPropVals.Count() ); for ( USHORT n = 0; n < rPropVals.Count(); ++n ) { Property &rProp = aImpl._aProps.getArray()[n]; const PropertyValue &rPropVal = *rPropVals.GetObject(n); rProp.Name = rPropVal.Name; rProp.Handle = rPropVal.Handle; rProp.Type = getCppuVoidType(); rProp.Attributes = 0; } } //---------------------------------------------------------------------------- SbPropertySetInfo::~SbPropertySetInfo() { } //------------------------------------------------------------------------- Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException ) { return aImpl.getProperties(); } Property SbPropertySetInfo::getPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } BOOL SbPropertySetInfo::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- SbPropertyContainer::SbPropertyContainer() { } //---------------------------------------------------------------------------- SbPropertyContainer::~SbPropertyContainer() { } //---------------------------------------------------------------------------- void SbPropertyContainer::addProperty(const OUString& Name, INT16 Attributes, const Any& DefaultValue) throw( PropertyExistException, IllegalTypeException, IllegalArgumentException, RuntimeException ) { (void)Name; (void)Attributes; (void)DefaultValue; } //---------------------------------------------------------------------------- void SbPropertyContainer::removeProperty(const OUString& Name) throw( UnknownPropertyException, RuntimeException ) { (void)Name; } //---------------------------------------------------------------------------- // XPropertySetInfo Sequence< Property > SbPropertyContainer::getProperties(void) throw () { return aImpl.getProperties(); } Property SbPropertyContainer::getPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } BOOL SbPropertyContainer::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyContainer::getPropertyValues(void) { return Sequence<PropertyValue>(); } //---------------------------------------------------------------------------- void SbPropertyContainer::setPropertyValues(const Sequence< PropertyValue >& PropertyValues_) { (void)PropertyValues_; } //---------------------------------------------------------------------------- void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite ) { (void)pBasic; (void)bWrite; // Wir brauchen mindestens 1 Parameter if ( rPar.Count() < 2 ) { StarBASIC::Error( SbERR_BAD_ARGUMENT ); return; } // Klassen-Name der struct holen String aServiceName( RTL_CONSTASCII_USTRINGPARAM("stardiv.uno.beans.PropertySet") ); #if 0 // Service suchen und instanzieren Reference< XMultiServiceFactory > xServiceManager = getProcessServiceFactory(); Reference< XInterface > xInterface; if( xProv.is() ) xInterface = xProv->newInstance(); #else Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues(); #endif SbxVariableRef refVar = rPar.Get(0); if( xInterface.is() ) { // PropertyValues setzen Any aArgAsAny = sbxToUnoValue( rPar.Get(1), getCppuType( (Sequence<PropertyValue>*)0 ) ); Sequence<PropertyValue> *pArg = (Sequence<PropertyValue>*) aArgAsAny.getValue(); Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface ); xPropAcc->setPropertyValues( *pArg ); // SbUnoObject daraus basteln und zurueckliefern Any aAny; aAny <<= xInterface; SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny ); if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID ) { // Objekt zurueckliefern refVar->PutObject( (SbUnoObject*)xUnoObj ); return; } } // Objekt konnte nicht erzeugt werden refVar->PutObject( NULL ); } <commit_msg>INTEGRATION: CWS bgdlremove (1.11.68); FILE MERGED 2007/05/25 10:45:36 kso 1.11.68.1: #i76911# - ucbhelper no longer uses vos::ORef but rtl::Reference.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propacc.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: ihi $ $Date: 2007-06-05 15:10:29 $ * * 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_basic.hxx" #include "propacc.hxx" #include <tools/urlobj.hxx> #include <tools/errcode.hxx> #include <svtools/svarray.hxx> #include <sbstar.hxx> #include <sbunoobj.hxx> using com::sun::star::uno::Reference; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace cppu; using namespace rtl; //======================================================================== // Deklaration Konvertierung von Sbx nach Uno mit bekannter Zielklasse Any sbxToUnoValue( SbxVariable* pVar, const Type& rType, Property* pUnoProperty = NULL ); //======================================================================== #ifdef WNT #define CDECL _cdecl #endif #if defined(UNX) #define CDECL #endif int CDECL SbCompare_PropertyValues_Impl( const void *arg1, const void *arg2 ) { return ((PropertyValue*)arg1)->Name.compareTo( ((PropertyValue*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_PropertyValue_Impl( const void *arg1, const void *arg2 ) { const OUString *pArg1 = (OUString*) arg1; const PropertyValue **pArg2 = (const PropertyValue**) arg2; return pArg1->compareTo( (*pArg2)->Name ); } int CDECL SbCompare_Properties_Impl( const void *arg1, const void *arg2 ) { return ((Property*)arg1)->Name.compareTo( ((Property*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 ) { const OUString *pArg1 = (OUString*) arg1; const Property *pArg2 = (Property*) arg2; return pArg1->compareTo( pArg2->Name ); } //---------------------------------------------------------------------------- SbPropertyValues::SbPropertyValues() { } //---------------------------------------------------------------------------- SbPropertyValues::~SbPropertyValues() { _xInfo = Reference< XPropertySetInfo >(); for ( USHORT n = 0; n < _aPropVals.Count(); ++n ) delete _aPropVals.GetObject( n ); } //---------------------------------------------------------------------------- Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException ) { // create on demand? if ( !_xInfo.is() ) { SbPropertySetInfo *pInfo = new SbPropertySetInfo( _aPropVals ); ((SbPropertyValues*)this)->_xInfo = (XPropertySetInfo*)pInfo; } return _xInfo; } //------------------------------------------------------------------------- INT32 SbPropertyValues::GetIndex_Impl( const OUString &rPropName ) const { PropertyValue **ppPV; ppPV = (PropertyValue **) bsearch( &rPropName, _aPropVals.GetData(), _aPropVals.Count(), sizeof( PropertyValue* ), SbCompare_UString_PropertyValue_Impl ); return ppPV ? ( (ppPV-_aPropVals.GetData()) / sizeof(ppPV) ) : USHRT_MAX; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValue( const OUString& aPropertyName, const 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) { INT32 nIndex = GetIndex_Impl( aPropertyName ); PropertyValue *pPropVal = _aPropVals.GetObject( sal::static_int_cast< USHORT >(nIndex)); pPropVal->Value = aValue; } //---------------------------------------------------------------------------- Any SbPropertyValues::getPropertyValue( const OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { INT32 nIndex = GetIndex_Impl( aPropertyName ); if ( nIndex != USHRT_MAX ) return _aPropVals.GetObject( sal::static_int_cast< USHORT >(nIndex))->Value; return Any(); } //---------------------------------------------------------------------------- void SbPropertyValues::addPropertyChangeListener( const OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removePropertyChangeListener( const OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::addVetoableChangeListener( const OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removeVetoableChangeListener( const OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException) { Sequence<PropertyValue> aRet( _aPropVals.Count()); for ( USHORT n = 0; n < _aPropVals.Count(); ++n ) aRet.getArray()[n] = *_aPropVals.GetObject(n); return aRet; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues ) 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) { if ( _aPropVals.Count() ) throw PropertyExistException(); const PropertyValue *pPropVals = rPropertyValues.getConstArray(); for ( sal_Int16 n = 0; n < rPropertyValues.getLength(); ++n ) { PropertyValue *pPropVal = new PropertyValue(pPropVals[n]); _aPropVals.Insert( pPropVal, n ); } } //============================================================================ //PropertySetInfoImpl PropertySetInfoImpl::PropertySetInfoImpl() { } INT32 PropertySetInfoImpl::GetIndex_Impl( const OUString &rPropName ) const { Property *pP; pP = (Property*) bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(), sizeof( Property ), SbCompare_UString_Property_Impl ); return pP ? sal::static_int_cast<INT32>( (pP-_aProps.getConstArray()) / sizeof(pP) ) : -1; } Sequence< Property > PropertySetInfoImpl::getProperties(void) throw() { return _aProps; } Property PropertySetInfoImpl::getPropertyByName(const OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); if( USHRT_MAX != nIndex ) return _aProps.getConstArray()[ nIndex ]; return Property(); } sal_Bool PropertySetInfoImpl::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); return USHRT_MAX != nIndex; } //============================================================================ SbPropertySetInfo::SbPropertySetInfo() { } //---------------------------------------------------------------------------- SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals ) { aImpl._aProps.realloc( rPropVals.Count() ); for ( USHORT n = 0; n < rPropVals.Count(); ++n ) { Property &rProp = aImpl._aProps.getArray()[n]; const PropertyValue &rPropVal = *rPropVals.GetObject(n); rProp.Name = rPropVal.Name; rProp.Handle = rPropVal.Handle; rProp.Type = getCppuVoidType(); rProp.Attributes = 0; } } //---------------------------------------------------------------------------- SbPropertySetInfo::~SbPropertySetInfo() { } //------------------------------------------------------------------------- Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException ) { return aImpl.getProperties(); } Property SbPropertySetInfo::getPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } BOOL SbPropertySetInfo::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- SbPropertyContainer::SbPropertyContainer() { } //---------------------------------------------------------------------------- SbPropertyContainer::~SbPropertyContainer() { } //---------------------------------------------------------------------------- void SbPropertyContainer::addProperty(const OUString& Name, INT16 Attributes, const Any& DefaultValue) throw( PropertyExistException, IllegalTypeException, IllegalArgumentException, RuntimeException ) { (void)Name; (void)Attributes; (void)DefaultValue; } //---------------------------------------------------------------------------- void SbPropertyContainer::removeProperty(const OUString& Name) throw( UnknownPropertyException, RuntimeException ) { (void)Name; } //---------------------------------------------------------------------------- // XPropertySetInfo Sequence< Property > SbPropertyContainer::getProperties(void) throw () { return aImpl.getProperties(); } Property SbPropertyContainer::getPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } BOOL SbPropertyContainer::hasPropertyByName(const OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyContainer::getPropertyValues(void) { return Sequence<PropertyValue>(); } //---------------------------------------------------------------------------- void SbPropertyContainer::setPropertyValues(const Sequence< PropertyValue >& PropertyValues_) { (void)PropertyValues_; } //---------------------------------------------------------------------------- void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite ) { (void)pBasic; (void)bWrite; // Wir brauchen mindestens 1 Parameter if ( rPar.Count() < 2 ) { StarBASIC::Error( SbERR_BAD_ARGUMENT ); return; } // Klassen-Name der struct holen String aServiceName( RTL_CONSTASCII_USTRINGPARAM("stardiv.uno.beans.PropertySet") ); #if 0 // Service suchen und instanzieren Reference< XMultiServiceFactory > xServiceManager = getProcessServiceFactory(); Reference< XInterface > xInterface; if( xProv.is() ) xInterface = xProv->newInstance(); #else Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues(); #endif SbxVariableRef refVar = rPar.Get(0); if( xInterface.is() ) { // PropertyValues setzen Any aArgAsAny = sbxToUnoValue( rPar.Get(1), getCppuType( (Sequence<PropertyValue>*)0 ) ); Sequence<PropertyValue> *pArg = (Sequence<PropertyValue>*) aArgAsAny.getValue(); Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface ); xPropAcc->setPropertyValues( *pArg ); // SbUnoObject daraus basteln und zurueckliefern Any aAny; aAny <<= xInterface; SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny ); if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID ) { // Objekt zurueckliefern refVar->PutObject( (SbUnoObject*)xUnoObj ); return; } } // Objekt konnte nicht erzeugt werden refVar->PutObject( NULL ); } <|endoftext|>
<commit_before>/* * vvms.cpp * * Created on: Nov 20, 2012 * Author: partio */ #include "vvms.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #include "writer.h" #include "neons.h" #include "pcuda.h" #undef HIMAN_AUXILIARY_INCLUDE #ifdef DEBUG #include "timer_factory.h" #endif using namespace std; using namespace himan::plugin; #include "cuda_extern.h" vvms::vvms() : itsUseCuda(false), itsCudaDeviceCount(0) { itsClearTextFormula = "w = -(ver) * 287 * T * (9.81*p)"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("vvms")); } void vvms::Process(std::shared_ptr<const plugin_configuration> conf) { shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda")); if (c->HaveCuda()) { string msg = "I possess the powers of CUDA"; if (!conf->UseCuda()) { msg += ", but I won't use them"; } else { msg += ", and I'm not afraid to use them"; itsUseCuda = true; } itsLogger->Info(msg); itsCudaDeviceCount = c->DeviceCount(); } // Get number of threads to use unsigned short threadCount = ThreadCount(conf->ThreadCount()); if (conf->StatisticsEnabled()) { conf->Statistics()->UsedThreadCount(threadCount); conf->Statistics()->UsedGPUCount(itsCudaDeviceCount); } boost::thread_group g; shared_ptr<info> targetInfo = conf->Info(); /* * Set target parameter to potential temperature * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * (todo: we could check from conf but why bother?) * */ vector<param> theParams; param theRequestedParam ("VV-MS", 143); // GRIB 2 theRequestedParam.GribDiscipline(0); theRequestedParam.GribCategory(2); theRequestedParam.GribParameter(9); // GRIB 1 if (conf->OutputFileType() == kGRIB1) { shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons")); long parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), theRequestedParam.Name()); theRequestedParam.GribIndicatorOfParameter(parm_id); theRequestedParam.GribTableVersion(targetInfo->Producer().TableVersion()); } theParams.push_back(theRequestedParam); targetInfo->Params(theParams); /* * Create data structures. */ targetInfo->Create(); /* * Initialize parent class functions for dimension handling */ Dimension(conf->LeadingDimension()); FeederInfo(shared_ptr<info> (new info(*targetInfo))); FeederInfo()->Param(theRequestedParam); /* * Each thread will have a copy of the target info. */ vector<shared_ptr<info> > targetInfos; targetInfos.resize(threadCount); for (size_t i = 0; i < threadCount; i++) { itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting"); targetInfos[i] = shared_ptr<info> (new info(*targetInfo)); boost::thread* t = new boost::thread(&vvms::Run, this, targetInfos[i], conf, i + 1); g.add_thread(t); } g.join_all(); if (conf->FileWriteOption() == kSingleFile) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); string theOutputFile = conf->ConfigurationFile(); theWriter->ToFile(targetInfo, conf, theOutputFile); } } void vvms::Run(shared_ptr<info> myTargetInfo, shared_ptr<const plugin_configuration> conf, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, conf, threadIndex); } } /* * Calculate() * * This function does the actual calculation. */ void vvms::Calculate(shared_ptr<info> myTargetInfo, shared_ptr<const plugin_configuration> conf, unsigned short threadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); param PParam("P-PA"); param VVParam("VV-PAS"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("vvmsThread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Info("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H%M") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); double PScale = 1; double TBase = 0; /* * If vvms is calculated for pressure levels, the P value * equals to level value. Otherwise we have to fetch P * separately. */ shared_ptr<info> PInfo; shared_ptr<info> VVInfo; shared_ptr<info> TInfo; shared_ptr<NFmiGrid> PGrid; bool isPressureLevel = (myTargetInfo->Level().Type() == kPressure); try { VVInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), VVParam); TInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), TParam); if (!isPressureLevel) { // Source info for P PInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), PParam); if (PInfo->Param().Unit() == kHPa) { PScale = 100; } PGrid = shared_ptr<NFmiGrid> (PInfo->Grid()->ToNewbaseGrid()); } } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); // Fill data with missing value if (conf->StatisticsEnabled()) { conf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); conf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (conf->StatisticsEnabled()) { processTimer->Start(); } if (TInfo->Param().Unit() == kC) { TBase = 273.15; } shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> VVGrid(VVInfo->Grid()->ToNewbaseGrid()); int missingCount = 0; int count = 0; bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *VVInfo->Grid() && (isPressureLevel || *myTargetInfo->Grid() == *PInfo->Grid())); string deviceType; if (itsUseCuda && equalGrids && threadIndex <= itsCudaDeviceCount) { deviceType = "GPU"; size_t N = TGrid->Size(); float* VVout = new float[N]; double *infoData = new double[N]; if (!isPressureLevel) { vvms_cuda::DoCuda(TGrid->DataPool()->Data(), TBase, PGrid->DataPool()->Data(), PScale, VVGrid->DataPool()->Data(), VVout, N, 0, threadIndex-1); } else { vvms_cuda::DoCuda(TGrid->DataPool()->Data(), TBase, 0, 0, VVGrid->DataPool()->Data(), VVout, N, 100 * myTargetInfo->Level().Value(), threadIndex-1); } for (size_t i = 0; i < N; i++) { infoData[i] = static_cast<double> (VVout[i]); if (infoData[i] == kFloatMissing) { missingCount++; } count++; } myTargetInfo->Data()->Set(infoData, N); delete [] infoData; delete [] VVout; } else { deviceType = "CPU"; assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double P = kFloatMissing; double VV = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, VVGrid, equalGrids, VV); if (isPressureLevel) { P = 100 * myTargetInfo->Level().Value(); } else { InterpolateToPoint(targetGrid, PGrid, equalGrids, P); } if (T == kFloatMissing || P == kFloatMissing || VV == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double VVms = 287 * -VV * (T + TBase) / (9.81 * P * PScale); if (!myTargetInfo->Value(VVms)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } } if (conf->StatisticsEnabled()) { processTimer->Stop(); conf->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif conf->Statistics()->AddToMissingCount(missingCount); conf->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); theWriter->ToFile(shared_ptr<info> (new info(*myTargetInfo)), conf); } } } <commit_msg>changes<commit_after>/* * vvms.cpp * * Created on: Nov 20, 2012 * Author: partio */ #include "vvms.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #include "writer.h" #include "neons.h" #include "pcuda.h" #undef HIMAN_AUXILIARY_INCLUDE #ifdef DEBUG #include "timer_factory.h" #endif using namespace std; using namespace himan::plugin; #include "vvms_cuda.h" vvms::vvms() : itsUseCuda(false), itsCudaDeviceCount(0) { itsClearTextFormula = "w = -(ver) * 287 * T * (9.81*p)"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("vvms")); } void vvms::Process(std::shared_ptr<const plugin_configuration> conf) { shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda")); if (c->HaveCuda()) { string msg = "I possess the powers of CUDA"; if (!conf->UseCuda()) { msg += ", but I won't use them"; } else { msg += ", and I'm not afraid to use them"; itsUseCuda = true; } itsLogger->Info(msg); itsCudaDeviceCount = c->DeviceCount(); } // Get number of threads to use unsigned short threadCount = ThreadCount(conf->ThreadCount()); if (conf->StatisticsEnabled()) { conf->Statistics()->UsedThreadCount(threadCount); conf->Statistics()->UsedGPUCount(itsCudaDeviceCount); } boost::thread_group g; shared_ptr<info> targetInfo = conf->Info(); /* * Set target parameter to potential temperature * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * (todo: we could check from conf but why bother?) * */ vector<param> theParams; param theRequestedParam ("VV-MS", 143); // GRIB 2 theRequestedParam.GribDiscipline(0); theRequestedParam.GribCategory(2); theRequestedParam.GribParameter(9); // GRIB 1 if (conf->OutputFileType() == kGRIB1) { shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons")); long parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), theRequestedParam.Name()); theRequestedParam.GribIndicatorOfParameter(parm_id); theRequestedParam.GribTableVersion(targetInfo->Producer().TableVersion()); } theParams.push_back(theRequestedParam); targetInfo->Params(theParams); /* * Create data structures. */ targetInfo->Create(); /* * Initialize parent class functions for dimension handling */ Dimension(conf->LeadingDimension()); FeederInfo(shared_ptr<info> (new info(*targetInfo))); FeederInfo()->Param(theRequestedParam); /* * Each thread will have a copy of the target info. */ vector<shared_ptr<info> > targetInfos; targetInfos.resize(threadCount); for (size_t i = 0; i < threadCount; i++) { itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting"); targetInfos[i] = shared_ptr<info> (new info(*targetInfo)); boost::thread* t = new boost::thread(&vvms::Run, this, targetInfos[i], conf, i + 1); g.add_thread(t); } g.join_all(); if (conf->FileWriteOption() == kSingleFile) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); string theOutputFile = conf->ConfigurationFile(); theWriter->ToFile(targetInfo, conf, theOutputFile); } } void vvms::Run(shared_ptr<info> myTargetInfo, shared_ptr<const plugin_configuration> conf, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, conf, threadIndex); } } /* * Calculate() * * This function does the actual calculation. */ void vvms::Calculate(shared_ptr<info> myTargetInfo, shared_ptr<const plugin_configuration> conf, unsigned short threadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); param PParam("P-PA"); param VVParam("VV-PAS"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("vvmsThread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); bool useCudaInThisThread = itsUseCuda && threadIndex <= itsCudaDeviceCount; while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Info("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H%M") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); double PScale = 1; double TBase = 0; /* * If vvms is calculated for pressure levels, the P value * equals to level value. Otherwise we have to fetch P * separately. */ shared_ptr<info> PInfo; shared_ptr<info> VVInfo; shared_ptr<info> TInfo; shared_ptr<NFmiGrid> PGrid; bool isPressureLevel = (myTargetInfo->Level().Type() == kPressure); cout << threadIndex << " " << useCudaInThisThread << endl; try { VVInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), VVParam, useCudaInThisThread); TInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), TParam); if (!isPressureLevel) { // Source info for P PInfo = theFetcher->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), PParam); if (PInfo->Param().Unit() == kHPa) { PScale = 100; } PGrid = shared_ptr<NFmiGrid> (PInfo->Grid()->ToNewbaseGrid()); } } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); // Fill data with missing value if (conf->StatisticsEnabled()) { conf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); conf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (conf->StatisticsEnabled()) { processTimer->Start(); } if (TInfo->Param().Unit() == kC) { TBase = 273.15; } int missingCount = 0; int count = 0; bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *VVInfo->Grid() && (isPressureLevel || *myTargetInfo->Grid() == *PInfo->Grid())); string deviceType; if (useCudaInThisThread && equalGrids) { deviceType = "GPU"; vvms_cuda::vvms_cuda_options opts; opts.isConstantPressure = isPressureLevel; opts.TBase = TBase; opts.PScale = PScale; opts.cudaDeviceIndex = threadIndex-1; opts.N = TInfo->Grid()->Size(); if (TInfo->Grid()->DataIsPacked()) { assert(TInfo->Grid()->PackedData()->ClassName() == "simple_packed"); opts.NPacked = TInfo->Grid()->PackedData()->Size(); opts.TInPacked = dynamic_pointer_cast<simple_packed> (TInfo->Grid()->PackedData())->Values(); opts.VVInPacked = dynamic_pointer_cast<simple_packed> (VVInfo->Grid()->PackedData())->Values(); if (!opts.isConstantPressure) { opts.PInPacked = dynamic_pointer_cast<simple_packed> (PInfo->Grid()->PackedData())->Values(); } opts.isPackedData = true; } else { opts.TIn = TInfo->Grid()->Data()->Values(); opts.VVIn = VVInfo->Grid()->Data()->Values(); if (!opts.isConstantPressure) { opts.PIn = PInfo->Grid()->Data()->Values(); } opts.isPackedData = false; } if (opts.isConstantPressure) { opts.PConst = myTargetInfo->Level().Value() * 100; // Pa } cudaMallocHost(reinterpret_cast<void**> (&opts.VVOut), opts.N * sizeof(double)); vvms_cuda::DoCuda(opts); assert(TInfo->Grid()->ScanningMode() == VVInfo->Grid()->ScanningMode() && (isPressureLevel || VVInfo->Grid()->ScanningMode() == PInfo->Grid()->ScanningMode())); if (TInfo->Grid()->ScanningMode() != myTargetInfo->Grid()->ScanningMode()) { HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode(); myTargetInfo->Grid()->ScanningMode(TInfo->Grid()->ScanningMode()); myTargetInfo->Grid()->Swap(originalMode); } myTargetInfo->Data()->Set(opts.VVOut, opts.N); cudaFreeHost(opts.VVOut); } else { deviceType = "CPU"; shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> VVGrid(VVInfo->Grid()->ToNewbaseGrid()); assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double P = kFloatMissing; double VV = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, VVGrid, equalGrids, VV); if (isPressureLevel) { P = 100 * myTargetInfo->Level().Value(); } else { InterpolateToPoint(targetGrid, PGrid, equalGrids, P); } if (T == kFloatMissing || P == kFloatMissing || VV == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double VVms = 287 * -VV * (T + TBase) / (9.81 * P * PScale); if (!myTargetInfo->Value(VVms)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } /* * Newbase normalizes scanning mode to bottom left -- if that's not what * the target scanning mode is, we have to swap the data back. */ if (myTargetInfo->Grid()->ScanningMode() != kBottomLeft) { HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode(); myTargetInfo->Grid()->ScanningMode(kBottomLeft); myTargetInfo->Grid()->Swap(originalMode); } } if (conf->StatisticsEnabled()) { processTimer->Stop(); conf->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif conf->Statistics()->AddToMissingCount(missingCount); conf->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); theWriter->ToFile(shared_ptr<info> (new info(*myTargetInfo)), conf); } } } <|endoftext|>
<commit_before><commit_msg>fdo#54718 fix opcode detection in basic resulting in failed/unregcognized code<commit_after><|endoftext|>
<commit_before>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <sstream> #include "runtime/raw-value.h" #include "common/names.h" using namespace impala; namespace impala { class RawValueTest : public testing::Test { }; TEST_F(RawValueTest, Compare) { int64_t v1, v2; v1 = -2128609280; v2 = 9223372036854775807; EXPECT_LT(RawValue::Compare(&v1, &v2, TYPE_BIGINT), 0); EXPECT_GT(RawValue::Compare(&v2, &v1, TYPE_BIGINT), 0); int32_t i1, i2; i1 = 2147483647; i2 = -2147483640; EXPECT_GT(RawValue::Compare(&i1, &i2, TYPE_INT), 0); EXPECT_LT(RawValue::Compare(&i2, &i1, TYPE_INT), 0); int16_t s1, s2; s1 = 32767; s2 = -32767; EXPECT_GT(RawValue::Compare(&s1, &s2, TYPE_SMALLINT), 0); EXPECT_LT(RawValue::Compare(&s2, &s1, TYPE_SMALLINT), 0); } TEST_F(RawValueTest, TypeChar) { const int N = 5; const char* v1 = "aaaaa"; const char* v2 = "aaaaab"; const char* v3 = "aaaab"; EXPECT_EQ(RawValue::Compare(v1, v1, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v1, v2, ColumnType::CreateCharType(N)), 0); EXPECT_LT(RawValue::Compare(v1, v3, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v2, v1, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v2, v2, ColumnType::CreateCharType(N)), 0); EXPECT_LT(RawValue::Compare(v2, v3, ColumnType::CreateCharType(N)), 0); EXPECT_GT(RawValue::Compare(v3, v1, ColumnType::CreateCharType(N)), 0); EXPECT_GT(RawValue::Compare(v3, v2, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v3, v3, ColumnType::CreateCharType(N)), 0); // Try putting non-string data (multiple nulls, non-ascii) and make // sure we can output it. stringstream ss; int val = 123; RawValue::PrintValue(&val, ColumnType::CreateCharType(sizeof(int)), -1, &ss); string s = ss.str(); EXPECT_EQ(s.size(), sizeof(int)); EXPECT_EQ(memcmp(&val, s.data(), sizeof(int)), 0); } // IMPALA-2270: "", false, and NULL should hash to distinct values. TEST_F(RawValueTest, HashEmptyAndNull) { uint32_t seed = 12345; uint32_t null_hash = RawValue::GetHashValue(NULL, TYPE_STRING, seed); uint32_t null_hash_fnv = RawValue::GetHashValueFnv(NULL, TYPE_STRING, seed); StringValue empty(NULL, 0); uint32_t empty_hash = RawValue::GetHashValue(&empty, TYPE_STRING, seed); uint32_t empty_hash_fnv = RawValue::GetHashValueFnv(&empty, TYPE_STRING, seed); bool false_val = false; uint32_t false_hash = RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed); uint32_t false_hash_fnv = RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed); EXPECT_NE(seed, null_hash); EXPECT_NE(seed, empty_hash); EXPECT_NE(seed, false_hash); EXPECT_NE(seed, null_hash_fnv); EXPECT_NE(seed, empty_hash_fnv); EXPECT_NE(seed, false_hash_fnv); EXPECT_NE(null_hash, empty_hash); EXPECT_NE(null_hash_fnv, empty_hash_fnv); EXPECT_NE(null_hash, false_hash); EXPECT_NE(false_hash, null_hash_fnv); } /// IMPALA-2270: Test that FNV hash of (int, "") is not skewed. TEST(HashUtil, IntNullSkew) { int num_values = 100000; int num_buckets = 16; vector<int> buckets(num_buckets, 0); for (int32_t i = 0; i < num_values; ++i) { uint32_t hash = RawValue::GetHashValueFnv(&i, TYPE_INT, 9999); StringValue empty(NULL, 0); hash = RawValue::GetHashValueFnv(&empty, TYPE_STRING, hash); ++buckets[hash % num_buckets]; } for (int i = 0; i < num_buckets; ++i) { LOG(INFO) << "Bucket " << i << ": " << buckets[i]; double exp_count = num_values / (double) num_buckets; EXPECT_GT(buckets[i], 0.9 * exp_count) << "Bucket " << i << " has <= 90%% of expected"; EXPECT_LT(buckets[i], 1.1 * exp_count) << "Bucket " << i << " has >= 110%% of expected"; } } TEST_F(RawValueTest, TemplatizedHash) { uint32_t seed = 12345; int8_t tinyint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int8_t>(&tinyint_val, TYPE_TINYINT, seed), RawValue::GetHashValue(&tinyint_val, TYPE_TINYINT, seed)); int16_t smallint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int16_t>(&smallint_val, TYPE_SMALLINT, seed), RawValue::GetHashValue(&smallint_val, TYPE_SMALLINT, seed)); int32_t int_val = 8; EXPECT_EQ(RawValue::GetHashValue<int32_t>(&int_val, TYPE_INT, seed), RawValue::GetHashValue(&int_val, TYPE_INT, seed)); int64_t bigint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int64_t>(&bigint_val, TYPE_BIGINT, seed), RawValue::GetHashValue(&bigint_val, TYPE_BIGINT, seed)); float float_val = 8.0f; EXPECT_EQ(RawValue::GetHashValue<float>(&float_val, TYPE_FLOAT, seed), RawValue::GetHashValue(&float_val, TYPE_FLOAT, seed)); double double_val = 8.0d; EXPECT_EQ(RawValue::GetHashValue<double>(&double_val, TYPE_DOUBLE, seed), RawValue::GetHashValue(&double_val, TYPE_DOUBLE, seed)); bool false_val = false; EXPECT_EQ(RawValue::GetHashValue<bool>(&false_val, TYPE_BOOLEAN, seed), RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed)); bool true_val = true; EXPECT_EQ(RawValue::GetHashValue<bool>(&true_val, TYPE_BOOLEAN, seed), RawValue::GetHashValue(&true_val, TYPE_BOOLEAN, seed)); StringValue string_value("aaaaa"); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, ColumnType::CreateCharType(10), seed), RawValue::GetHashValue(&string_value, ColumnType::CreateCharType(10), seed)); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, TYPE_STRING, seed), RawValue::GetHashValue(&string_value, TYPE_STRING, seed)); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, ColumnType::CreateVarcharType( ColumnType::MAX_VARCHAR_LENGTH), seed), RawValue::GetHashValue(&string_value,ColumnType::CreateVarcharType( ColumnType::MAX_VARCHAR_LENGTH), seed)); TimestampValue timestamp_value(253433923200); EXPECT_EQ(RawValue::GetHashValue<impala::TimestampValue>( &timestamp_value, TYPE_TIMESTAMP, seed),RawValue::GetHashValue( &timestamp_value, TYPE_TIMESTAMP, seed)); ColumnType d4_type = ColumnType::CreateDecimalType(9, 1); Decimal4Value d4_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal4Value>(&d4_value, d4_type, seed), RawValue::GetHashValue(&d4_value, d4_type, seed)); ColumnType d8_type = ColumnType::CreateDecimalType(18, 6); Decimal8Value d8_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal8Value>(&d8_value, d8_type, seed), RawValue::GetHashValue(&d8_value, d8_type, seed)); ColumnType d16_type = ColumnType::CreateDecimalType(19, 4); Decimal16Value d16_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal16Value>(&d16_value, d16_type, seed), RawValue::GetHashValue(&d16_value, d16_type, seed)); } } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::CpuInfo::Init(); return RUN_ALL_TESTS(); } <commit_msg>IMPALA-2955 : ASAN compilation fix, remove suffix 'd' on floating constant<commit_after>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <sstream> #include "runtime/raw-value.h" #include "common/names.h" using namespace impala; namespace impala { class RawValueTest : public testing::Test { }; TEST_F(RawValueTest, Compare) { int64_t v1, v2; v1 = -2128609280; v2 = 9223372036854775807; EXPECT_LT(RawValue::Compare(&v1, &v2, TYPE_BIGINT), 0); EXPECT_GT(RawValue::Compare(&v2, &v1, TYPE_BIGINT), 0); int32_t i1, i2; i1 = 2147483647; i2 = -2147483640; EXPECT_GT(RawValue::Compare(&i1, &i2, TYPE_INT), 0); EXPECT_LT(RawValue::Compare(&i2, &i1, TYPE_INT), 0); int16_t s1, s2; s1 = 32767; s2 = -32767; EXPECT_GT(RawValue::Compare(&s1, &s2, TYPE_SMALLINT), 0); EXPECT_LT(RawValue::Compare(&s2, &s1, TYPE_SMALLINT), 0); } TEST_F(RawValueTest, TypeChar) { const int N = 5; const char* v1 = "aaaaa"; const char* v2 = "aaaaab"; const char* v3 = "aaaab"; EXPECT_EQ(RawValue::Compare(v1, v1, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v1, v2, ColumnType::CreateCharType(N)), 0); EXPECT_LT(RawValue::Compare(v1, v3, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v2, v1, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v2, v2, ColumnType::CreateCharType(N)), 0); EXPECT_LT(RawValue::Compare(v2, v3, ColumnType::CreateCharType(N)), 0); EXPECT_GT(RawValue::Compare(v3, v1, ColumnType::CreateCharType(N)), 0); EXPECT_GT(RawValue::Compare(v3, v2, ColumnType::CreateCharType(N)), 0); EXPECT_EQ(RawValue::Compare(v3, v3, ColumnType::CreateCharType(N)), 0); // Try putting non-string data (multiple nulls, non-ascii) and make // sure we can output it. stringstream ss; int val = 123; RawValue::PrintValue(&val, ColumnType::CreateCharType(sizeof(int)), -1, &ss); string s = ss.str(); EXPECT_EQ(s.size(), sizeof(int)); EXPECT_EQ(memcmp(&val, s.data(), sizeof(int)), 0); } // IMPALA-2270: "", false, and NULL should hash to distinct values. TEST_F(RawValueTest, HashEmptyAndNull) { uint32_t seed = 12345; uint32_t null_hash = RawValue::GetHashValue(NULL, TYPE_STRING, seed); uint32_t null_hash_fnv = RawValue::GetHashValueFnv(NULL, TYPE_STRING, seed); StringValue empty(NULL, 0); uint32_t empty_hash = RawValue::GetHashValue(&empty, TYPE_STRING, seed); uint32_t empty_hash_fnv = RawValue::GetHashValueFnv(&empty, TYPE_STRING, seed); bool false_val = false; uint32_t false_hash = RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed); uint32_t false_hash_fnv = RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed); EXPECT_NE(seed, null_hash); EXPECT_NE(seed, empty_hash); EXPECT_NE(seed, false_hash); EXPECT_NE(seed, null_hash_fnv); EXPECT_NE(seed, empty_hash_fnv); EXPECT_NE(seed, false_hash_fnv); EXPECT_NE(null_hash, empty_hash); EXPECT_NE(null_hash_fnv, empty_hash_fnv); EXPECT_NE(null_hash, false_hash); EXPECT_NE(false_hash, null_hash_fnv); } /// IMPALA-2270: Test that FNV hash of (int, "") is not skewed. TEST(HashUtil, IntNullSkew) { int num_values = 100000; int num_buckets = 16; vector<int> buckets(num_buckets, 0); for (int32_t i = 0; i < num_values; ++i) { uint32_t hash = RawValue::GetHashValueFnv(&i, TYPE_INT, 9999); StringValue empty(NULL, 0); hash = RawValue::GetHashValueFnv(&empty, TYPE_STRING, hash); ++buckets[hash % num_buckets]; } for (int i = 0; i < num_buckets; ++i) { LOG(INFO) << "Bucket " << i << ": " << buckets[i]; double exp_count = num_values / (double) num_buckets; EXPECT_GT(buckets[i], 0.9 * exp_count) << "Bucket " << i << " has <= 90%% of expected"; EXPECT_LT(buckets[i], 1.1 * exp_count) << "Bucket " << i << " has >= 110%% of expected"; } } TEST_F(RawValueTest, TemplatizedHash) { uint32_t seed = 12345; int8_t tinyint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int8_t>(&tinyint_val, TYPE_TINYINT, seed), RawValue::GetHashValue(&tinyint_val, TYPE_TINYINT, seed)); int16_t smallint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int16_t>(&smallint_val, TYPE_SMALLINT, seed), RawValue::GetHashValue(&smallint_val, TYPE_SMALLINT, seed)); int32_t int_val = 8; EXPECT_EQ(RawValue::GetHashValue<int32_t>(&int_val, TYPE_INT, seed), RawValue::GetHashValue(&int_val, TYPE_INT, seed)); int64_t bigint_val = 8; EXPECT_EQ(RawValue::GetHashValue<int64_t>(&bigint_val, TYPE_BIGINT, seed), RawValue::GetHashValue(&bigint_val, TYPE_BIGINT, seed)); float float_val = 8.0f; EXPECT_EQ(RawValue::GetHashValue<float>(&float_val, TYPE_FLOAT, seed), RawValue::GetHashValue(&float_val, TYPE_FLOAT, seed)); double double_val = 8.0; EXPECT_EQ(RawValue::GetHashValue<double>(&double_val, TYPE_DOUBLE, seed), RawValue::GetHashValue(&double_val, TYPE_DOUBLE, seed)); bool false_val = false; EXPECT_EQ(RawValue::GetHashValue<bool>(&false_val, TYPE_BOOLEAN, seed), RawValue::GetHashValue(&false_val, TYPE_BOOLEAN, seed)); bool true_val = true; EXPECT_EQ(RawValue::GetHashValue<bool>(&true_val, TYPE_BOOLEAN, seed), RawValue::GetHashValue(&true_val, TYPE_BOOLEAN, seed)); StringValue string_value("aaaaa"); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, ColumnType::CreateCharType(10), seed), RawValue::GetHashValue(&string_value, ColumnType::CreateCharType(10), seed)); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, TYPE_STRING, seed), RawValue::GetHashValue(&string_value, TYPE_STRING, seed)); EXPECT_EQ(RawValue::GetHashValue<impala::StringValue>( &string_value, ColumnType::CreateVarcharType( ColumnType::MAX_VARCHAR_LENGTH), seed), RawValue::GetHashValue(&string_value,ColumnType::CreateVarcharType( ColumnType::MAX_VARCHAR_LENGTH), seed)); TimestampValue timestamp_value(253433923200); EXPECT_EQ(RawValue::GetHashValue<impala::TimestampValue>( &timestamp_value, TYPE_TIMESTAMP, seed),RawValue::GetHashValue( &timestamp_value, TYPE_TIMESTAMP, seed)); ColumnType d4_type = ColumnType::CreateDecimalType(9, 1); Decimal4Value d4_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal4Value>(&d4_value, d4_type, seed), RawValue::GetHashValue(&d4_value, d4_type, seed)); ColumnType d8_type = ColumnType::CreateDecimalType(18, 6); Decimal8Value d8_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal8Value>(&d8_value, d8_type, seed), RawValue::GetHashValue(&d8_value, d8_type, seed)); ColumnType d16_type = ColumnType::CreateDecimalType(19, 4); Decimal16Value d16_value(123456789); EXPECT_EQ(RawValue::GetHashValue<impala::Decimal16Value>(&d16_value, d16_type, seed), RawValue::GetHashValue(&d16_value, d16_type, seed)); } } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::CpuInfo::Init(); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 Flowgrammable, LLC. // // 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. namespace freeflow { // -------------------------------------------------------------------------- // // Error /// Construct an error value that signifies success. inline Error::Error() : code_(), data_() { } /// Construt an error value with the given code. Additiional data /// may also be associated with the error. inline Error::Error(Code c, Data d) : code_(c), data_(d) { } /// Allows contextual conversion to bool, returning true if and only /// if there is no error (i.e., the underlying code has value 0). inline Error::operator bool() const { return (bool)code_; } /// Returns the error category. inline const Error_category& Error::category() const { return code_.category(); } /// Returns the error code. inline Error::Code Error::code() const { return code_; } /// Returns associated error data. inline Error::Data Error::data() const { return data_; } inline std::string Error::message() const { return code_.message(); } /// Returns true when two errors have the same error code. inline bool operator==(Error a, Error b) { return a.code() == b.code(); } inline bool operator!=(Error a, Error b) { return not(a == b); } // -------------------------------------------------------------------------- // // Error constructors /// Returns an error condition based on a predicate. /// /// If the condition b is true, the resulting error condition will evaluate /// to SUCCESS. Otherwise, the condition will evaluate to the code c. inline Error ok(bool b, Error err) { return b ? Error() : err; } /// Returns an error code that encapsulates the current system error. inline Error system_error() { return system_error(errno); } /// Returns an error value corresponding to the given system error. inline Error system_error(int n) { return make_error_code(static_cast<std::errc>(n)); } // -------------------------------------------------------------------------- // // Trap /// Initialzie the trap with an error. This allows implicit conversions /// to trap objects. inline Trap::Trap(Error e) : err_(e) { } /// Allows contextual conversion to bool, returning true if and only if /// the underlying error indicates failure. inline Trap::operator bool() const { return !err_; } /// Returns the underlying error. inline Error Trap::error() const { return err_; } /// Returns the error code. inline Error::Code Trap::code() const { return err_.code(); } /// Returns the error data. inline Error::Data Trap::data() const { return err_.data(); } } // namespace freeflow <commit_msg>Fixing error conversion bug.<commit_after>// Copyright (c) 2013-2014 Flowgrammable, LLC. // // 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. namespace freeflow { // -------------------------------------------------------------------------- // // Error /// Construct an error value that signifies success. inline Error::Error() : code_(), data_() { } /// Construt an error value with the given code. Additiional data /// may also be associated with the error. inline Error::Error(Code c, Data d) : code_(c), data_(d) { } /// Allows contextual conversion to bool, returning true if and only /// if there is no error (i.e., the underlying code has value 0). inline Error::operator bool() const { return !code_; } /// Returns the error category. inline const Error_category& Error::category() const { return code_.category(); } /// Returns the error code. inline Error::Code Error::code() const { return code_; } /// Returns associated error data. inline Error::Data Error::data() const { return data_; } inline std::string Error::message() const { return code_.message(); } /// Returns true when two errors have the same error code. inline bool operator==(Error a, Error b) { return a.code() == b.code(); } inline bool operator!=(Error a, Error b) { return not(a == b); } // -------------------------------------------------------------------------- // // Error constructors /// Returns an error condition based on a predicate. /// /// If the condition b is true, the resulting error condition will evaluate /// to SUCCESS. Otherwise, the condition will evaluate to the code c. inline Error ok(bool b, Error err) { return b ? Error() : err; } /// Returns an error code that encapsulates the current system error. inline Error system_error() { return system_error(errno); } /// Returns an error value corresponding to the given system error. inline Error system_error(int n) { return make_error_code(static_cast<std::errc>(n)); } // -------------------------------------------------------------------------- // // Trap /// Initialzie the trap with an error. This allows implicit conversions /// to trap objects. inline Trap::Trap(Error e) : err_(e) { } /// Allows contextual conversion to bool, returning true if and only if /// the underlying error does not indicate success. inline Trap::operator bool() const { return (bool)err_.code(); } /// Returns the underlying error. inline Error Trap::error() const { return err_; } /// Returns the error code. inline Error::Code Trap::code() const { return err_.code(); } /// Returns the error data. inline Error::Data Trap::data() const { return err_.data(); } } // namespace freeflow <|endoftext|>
<commit_before>#include <reactive/bridge.hpp> #include <reactive/ref.hpp> #include <reactive/transform.hpp> #include <reactive/while.hpp> #include <reactive/finite_state_machine.hpp> #include <reactive/filter.hpp> #include <reactive/generate.hpp> #include <reactive/ptr_observable.hpp> #include <reactive/cache.hpp> #include <reactive/get.hpp> #include <boost/scope_exit.hpp> #include <boost/variant.hpp> #include <vector> #ifdef _MSC_VER # include <SDL.h> #else # include <SDL2/SDL.h> #endif namespace { void throw_error() { throw std::runtime_error(std::string("SDL error :") + SDL_GetError()); } void check_sdl(int rc) { if (rc < 0) { throw_error(); } } struct window_destructor { void operator()(SDL_Window *w) const { SDL_DestroyWindow(w); } }; struct renderer_destructor { void operator()(SDL_Renderer *r) const { SDL_DestroyRenderer(r); } }; void set_render_draw_color(SDL_Renderer &renderer, SDL_Color color) { SDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a); } SDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { SDL_Color result; result.r = red; result.g = green; result.b = blue; result.a = alpha; return result; } SDL_Rect make_rect(int x, int y, int w, int h) { SDL_Rect result; result.x = x; result.y = y; result.w = w; result.h = h; return result; } struct draw_filled_rect { SDL_Color color; SDL_Rect where; }; typedef boost::variant< draw_filled_rect > draw_operation; struct frame { std::vector<draw_operation> operations; }; struct draw_operation_renderer : boost::static_visitor<> { explicit draw_operation_renderer(SDL_Renderer &sdl) : sdl(&sdl) { } void operator()(draw_filled_rect const &operation) const { set_render_draw_color(*sdl, operation.color); SDL_RenderDrawRect(sdl, &operation.where); } private: SDL_Renderer *sdl; }; void render_frame(SDL_Renderer &sdl, frame const &frame_) { set_render_draw_color(sdl, make_color(0, 0, 0, 0xff)); SDL_RenderClear(&sdl); for (auto const &operation : frame_.operations) { boost::apply_visitor(draw_operation_renderer{sdl}, operation); } SDL_RenderPresent(&sdl); } struct game_state { int x = 100; int y = 100; int count = 1; }; int const max_rect_count = 5; frame draw_game_state(game_state const &state) { std::vector<draw_operation> operations; for (int i = 0; i < state.count; ++i) { int const max_width = 80; int const single_offset = (max_width / 2) / max_rect_count; int const total_offset = single_offset * i; int const width = max_width - total_offset * 2; operations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)}); } return frame { std::move(operations) }; } boost::optional<game_state> step_game_state(game_state previous, SDL_Event event_) { switch (event_.type) { case SDL_QUIT: return boost::none; case SDL_KEYUP: { switch (event_.key.keysym.sym) { case SDLK_LEFT: previous.x -= 10; break; case SDLK_RIGHT: previous.x += 10; break; case SDLK_UP: previous.y -= 10; break; case SDLK_DOWN: previous.y += 10; break; case SDLK_PLUS: previous.count = std::min(max_rect_count, previous.count + 1); break; case SDLK_MINUS: previous.count = std::max(1, previous.count - 1); break; case SDLK_ESCAPE: return boost::none; } break; } } return previous; } template <class Events> auto make_frames(Events &&input) #ifdef _MSC_VER -> rx::unique_observable<frame> #endif { game_state initial_state; auto model = rx::make_finite_state_machine(std::forward<Events>(input), initial_state, step_game_state); return #ifdef _MSC_VER rx::box<frame> #endif (rx::transform(std::move(model), draw_game_state)); } } int main() { check_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)); BOOST_SCOPE_EXIT(void) { SDL_Quit(); } BOOST_SCOPE_EXIT_END; std::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow("Silicium react.cpp", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0)); if (!window) { throw_error(); return 1; } std::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0)); rx::bridge<SDL_Event> frame_events; auto frames = rx::cache(make_frames(rx::ref(frame_events)), frame{{}}); for (;;) { SDL_Event event{}; while (frame_events.is_waiting() && SDL_PollEvent(&event)) { frame_events.got_element(event); } auto f = rx::get(frames); if (!f) { break; } render_frame(*renderer, *f); SDL_Delay(16); } } <commit_msg>avoid VC++ 2013 compiler crash; fix linker problem<commit_after>#include <reactive/bridge.hpp> #include <reactive/ref.hpp> #include <reactive/transform.hpp> #include <reactive/while.hpp> #include <reactive/finite_state_machine.hpp> #include <reactive/filter.hpp> #include <reactive/generate.hpp> #include <reactive/ptr_observable.hpp> #include <reactive/cache.hpp> #include <reactive/get.hpp> #include <boost/scope_exit.hpp> #include <boost/variant.hpp> #include <vector> #ifdef _MSC_VER # include <SDL.h> #else # include <SDL2/SDL.h> #endif namespace { void throw_error() { throw std::runtime_error(std::string("SDL error :") + SDL_GetError()); } void check_sdl(int rc) { if (rc < 0) { throw_error(); } } struct window_destructor { void operator()(SDL_Window *w) const { SDL_DestroyWindow(w); } }; struct renderer_destructor { void operator()(SDL_Renderer *r) const { SDL_DestroyRenderer(r); } }; void set_render_draw_color(SDL_Renderer &renderer, SDL_Color color) { SDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a); } SDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { SDL_Color result; result.r = red; result.g = green; result.b = blue; result.a = alpha; return result; } SDL_Rect make_rect(int x, int y, int w, int h) { SDL_Rect result; result.x = x; result.y = y; result.w = w; result.h = h; return result; } struct draw_filled_rect { SDL_Color color; SDL_Rect where; }; typedef boost::variant< draw_filled_rect > draw_operation; struct frame { std::vector<draw_operation> operations; }; struct draw_operation_renderer : boost::static_visitor<> { explicit draw_operation_renderer(SDL_Renderer &sdl) : sdl(&sdl) { } void operator()(draw_filled_rect const &operation) const { set_render_draw_color(*sdl, operation.color); SDL_RenderDrawRect(sdl, &operation.where); } private: SDL_Renderer *sdl; }; void render_frame(SDL_Renderer &sdl, frame const &frame_) { set_render_draw_color(sdl, make_color(0, 0, 0, 0xff)); SDL_RenderClear(&sdl); for (auto const &operation : frame_.operations) { boost::apply_visitor(draw_operation_renderer{sdl}, operation); } SDL_RenderPresent(&sdl); } struct game_state { int x = 100; int y = 100; int count = 1; }; int const max_rect_count = 5; frame draw_game_state(game_state const &state) { std::vector<draw_operation> operations; for (int i = 0; i < state.count; ++i) { int const max_width = 80; int const single_offset = (max_width / 2) / max_rect_count; int const total_offset = single_offset * i; int const width = max_width - total_offset * 2; operations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)}); } return frame { std::move(operations) }; } boost::optional<game_state> step_game_state(game_state previous, SDL_Event event_) { switch (event_.type) { case SDL_QUIT: return boost::none; case SDL_KEYUP: { switch (event_.key.keysym.sym) { case SDLK_LEFT: previous.x -= 10; break; case SDLK_RIGHT: previous.x += 10; break; case SDLK_UP: previous.y -= 10; break; case SDLK_DOWN: previous.y += 10; break; case SDLK_PLUS: previous.count = std::min(max_rect_count, previous.count + 1); break; case SDLK_MINUS: previous.count = std::max(1, previous.count - 1); break; case SDLK_ESCAPE: return boost::none; } break; } } return previous; } template <class Events> auto make_frames(Events &&input) #ifdef _MSC_VER -> rx::unique_observable<frame> #endif { game_state initial_state; auto model = rx::make_finite_state_machine(std::forward<Events>(input), initial_state, step_game_state); return #ifdef _MSC_VER rx::box<frame> #endif (rx::transform(std::move(model), draw_game_state)); } } int main(int argc, char* argv[]) //SDL2 requires the parameters on Windows { check_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)); BOOST_SCOPE_EXIT(void) { SDL_Quit(); } BOOST_SCOPE_EXIT_END; std::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow("Silicium react.cpp", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0)); if (!window) { throw_error(); return 1; } std::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0)); rx::bridge<SDL_Event> frame_events; auto frames = rx::cache(make_frames(rx::ref(frame_events)), frame()); for (;;) { SDL_Event event{}; while (frame_events.is_waiting() && SDL_PollEvent(&event)) { frame_events.got_element(event); } auto f = rx::get(frames); if (!f) { break; } render_frame(*renderer, *f); SDL_Delay(16); } return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "stan/prob/distributions/multivariate/continuous/gaussian_dlm.hpp" using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using boost::math::policies::policy; using boost::math::policies::evaluation_error; using boost::math::policies::domain_error; using boost::math::policies::overflow_error; using boost::math::policies::domain_error; using boost::math::policies::pole_error; using boost::math::policies::errno_on_error; using stan::prob::gaussian_dlm_log; // NOTE: what does this do? typedef policy< domain_error<errno_on_error>, pole_error<errno_on_error>, overflow_error<errno_on_error>, evaluation_error<errno_on_error> > errno_policy; TEST(ProbDistributionsGaussianDLM,LoglikeUU) { Matrix<double, Dynamic, Dynamic> FF(1, 1); FF << 0.585528817843856; Matrix<double, Dynamic, Dynamic> GG(1, 1); GG << -0.109303314681054; Matrix<double, Dynamic, Dynamic> V(1, 1); V << 2.25500747900521; Matrix<double, Dynamic, Dynamic> W(1, 1); W << 0.461487989960454; Matrix<double, Dynamic, Dynamic> y(1, 10); y << 0.435794268894196, 1.22755796113506, 0.193264580222731, 1.76021889445093, 1.6470149263738, 0.059988547306031, -0.4980979884018, 1.77794742623532, -0.435458536090977, 1.1733293160216; double ll_expected = -21.0504107180498; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } TEST(ProbDistributionsGaussianDLM,LoglikeMM) { Matrix<double, Dynamic, Dynamic> FF(2, 3); FF << 0.585528817843856,0.709466017509524,-0.109303314681054,-0.453497173462763,0.605887455840394,-1.81795596770373; Matrix<double, Dynamic, Dynamic> GG(2, 2); GG << 0.520216457554957,0.816899839520583,-0.750531994502331,-0.886357521243213; Matrix<double, Dynamic, Dynamic> V(3, 3); V << 7.19105866377728,-0.311731853764732,4.87333111936296,-0.311731853764732,3.27048576782842,0.457616661474554,4.87333111936296,0.457616661474554,5.86564522448303; Matrix<double, Dynamic, Dynamic> W(2, 2); W << 2.24277594357501,-1.65863136283477,-1.65863136283477,6.69010664813895; Matrix<double, Dynamic, Dynamic> y(3, 10); y << 0.663454889128383, 1.84506567787219, -0.887054506009854, -2.41521382778332, 3.70875481434455, -4.55234499588754, -0.605128307725781, 1.37074056153151, -2.12107763131894, 2.24236743746261, 0.386569006173759, 3.91825641599579, 3.33368860016417, -0.469849046245645, -2.19806833413509, -1.45754611697235, 2.32377488296413, 4.8514565931381, -3.3192402890674, -4.86325482585216, -1.29504029175967, -1.15116681671907, -1.20273925104474, -2.53276712020605, -1.06306293348278, -2.38535359596865, 0.693389700056057, -3.25137196974247, 1.32287059182635, 0.745762191888096; double ll_expected = -90.0322237154493; // the error adds up in the multivariate version due to the inversion double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_NEAR(lp_ref, ll_expected, 1e-4); } TEST(ProbDistributionsGaussianDLM,LoglikeUUSeq) { Matrix<double, Dynamic, Dynamic> FF(1, 1); FF << 0.585528817843856; Matrix<double, Dynamic, Dynamic> GG(1, 1); GG << -0.109303314681054; Matrix<double, Dynamic, Dynamic> W(1, 1); W << 0.461487989960454; Matrix<double, Dynamic, 1> V(1); V << 2.25500747900521; Matrix<double, Dynamic, Dynamic> y(1, 10); y << -30.2383237005506, 4.58034073011305, -0.173205689832086, 1.80027530969998, 1.64263662741284, 0.0604671098951288, -0.49815029687907, 1.77795314372528, -0.435459161031581, 1.17332938432968; double ll_expected = -21.0616654161768; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } TEST(ProbDistributionsGaussianDLM,LoglikeMMSeq) { Matrix<double, Dynamic, Dynamic> FF(2, 3); FF << 0.585528817843856,0.709466017509524,-0.109303314681054,-0.453497173462763,0.605887455840394,-1.81795596770373; Matrix<double, Dynamic, Dynamic> GG(2, 2); GG << 0.520216457554957,0.816899839520583,-0.750531994502331,-0.886357521243213; Matrix<double, Dynamic, Dynamic> W(2, 2); W << 2.24277594357501,-1.65863136283477,-1.65863136283477,6.69010664813895; Matrix<double, Dynamic, 1> V(3); V << 7.19105866377728,3.27048576782842,5.86564522448303; Matrix<double, Dynamic, Dynamic> y(3, 10); y << -645.337793038888, -85.2449543825825, -1027.80947332792, 115.550478561317, 83.7383685001328, 79.50821971367, 52.2957712041988, -15.0415380740324, 124.483546197942, -34.6937213615964, -5.72301661410856, -55.3761417070498, 8.80290702350217, 4.44692709691049, -2.07768404916278, 1.57843833028236, 1.23783669851953, 15.5659876348306, -6.86188181853719, -5.50621793641665, -3.62888602818304, -0.145891471793544, -0.825028473757867, -2.52251372025581, -1.19867033251869, -2.47536209021952, 1.41122996270707, -5.95624742000524, 0.832231787736836, 2.38404919543544; double ll_expected = -82647.3683004951; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } <commit_msg>updated DLM test for sizes of matrices<commit_after>#include <gtest/gtest.h> #include "stan/prob/distributions/multivariate/continuous/gaussian_dlm.hpp" using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using boost::math::policies::policy; using boost::math::policies::evaluation_error; using boost::math::policies::domain_error; using boost::math::policies::overflow_error; using boost::math::policies::domain_error; using boost::math::policies::pole_error; using boost::math::policies::errno_on_error; using stan::prob::gaussian_dlm_log; // NOTE: what does this do? typedef policy< domain_error<errno_on_error>, pole_error<errno_on_error>, overflow_error<errno_on_error>, evaluation_error<errno_on_error> > errno_policy; TEST(ProbDistributionsGaussianDLM,LoglikeUU) { Matrix<double, Dynamic, Dynamic> FF(1, 1); FF << 0.585528817843856; Matrix<double, Dynamic, Dynamic> GG(1, 1); GG << -0.109303314681054; Matrix<double, Dynamic, Dynamic> V(1, 1); V << 2.25500747900521; Matrix<double, Dynamic, Dynamic> W(1, 1); W << 0.461487989960454; Matrix<double, Dynamic, Dynamic> y(1, 10); y << 0.435794268894196, 1.22755796113506, 0.193264580222731, 1.76021889445093, 1.6470149263738, 0.059988547306031, -0.4980979884018, 1.77794742623532, -0.435458536090977, 1.1733293160216; double ll_expected = -21.0504107180498; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } TEST(ProbDistributionsGaussianDLM,LoglikeMM) { Matrix<double, Dynamic, Dynamic> FF(2, 3); FF << 0.585528817843856,0.709466017509524,-0.109303314681054,-0.453497173462763,0.605887455840394,-1.81795596770373; Matrix<double, Dynamic, Dynamic> GG(2, 2); GG << 0.520216457554957,0.816899839520583,-0.750531994502331,-0.886357521243213; Matrix<double, Dynamic, Dynamic> V(3, 3); V << 7.19105866377728,-0.311731853764732,4.87333111936296,-0.311731853764732,3.27048576782842,0.457616661474554,4.87333111936296,0.457616661474554,5.86564522448303; Matrix<double, Dynamic, Dynamic> W(2, 2); W << 2.24277594357501,-1.65863136283477,-1.65863136283477,6.69010664813895; Matrix<double, Dynamic, Dynamic> y(3, 10); y << 0.663454889128383, 1.84506567787219, -0.887054506009854, -2.41521382778332, 3.70875481434455, -4.55234499588754, -0.605128307725781, 1.37074056153151, -2.12107763131894, 2.24236743746261, 0.386569006173759, 3.91825641599579, 3.33368860016417, -0.469849046245645, -2.19806833413509, -1.45754611697235, 2.32377488296413, 4.8514565931381, -3.3192402890674, -4.86325482585216, -1.29504029175967, -1.15116681671907, -1.20273925104474, -2.53276712020605, -1.06306293348278, -2.38535359596865, 0.693389700056057, -3.25137196974247, 1.32287059182635, 0.745762191888096; double ll_expected = -90.0322237154493; // the error adds up in the multivariate version due to the inversion double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_NEAR(lp_ref, ll_expected, 1e-4); } TEST(ProbDistributionsGaussianDLM,LoglikeUUSeq) { Matrix<double, Dynamic, Dynamic> FF(1, 1); FF << 0.585528817843856; Matrix<double, Dynamic, Dynamic> GG(1, 1); GG << -0.109303314681054; Matrix<double, Dynamic, Dynamic> W(1, 1); W << 0.461487989960454; Matrix<double, Dynamic, 1> V(1); V << 2.25500747900521; Matrix<double, Dynamic, Dynamic> y(1, 10); y << -30.2383237005506, 4.58034073011305, -0.173205689832086, 1.80027530969998, 1.64263662741284, 0.0604671098951288, -0.49815029687907, 1.77795314372528, -0.435459161031581, 1.17332938432968; double ll_expected = -21.0616654161768; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } TEST(ProbDistributionsGaussianDLM,LoglikeMMSeq) { Matrix<double, Dynamic, Dynamic> FF(2, 3); FF << 0.585528817843856,0.709466017509524,-0.109303314681054,-0.453497173462763,0.605887455840394,-1.81795596770373; Matrix<double, Dynamic, Dynamic> GG(2, 2); GG << 0.520216457554957,0.816899839520583,-0.750531994502331,-0.886357521243213; Matrix<double, Dynamic, Dynamic> W(2, 2); W << 2.24277594357501,-1.65863136283477,-1.65863136283477,6.69010664813895; Matrix<double, Dynamic, 1> V(3); V << 7.19105866377728,3.27048576782842,5.86564522448303; Matrix<double, Dynamic, Dynamic> y(3, 10); y << -645.337793038888, -85.2449543825825, -1027.80947332792, 115.550478561317, 83.7383685001328, 79.50821971367, 52.2957712041988, -15.0415380740324, 124.483546197942, -34.6937213615964, -5.72301661410856, -55.3761417070498, 8.80290702350217, 4.44692709691049, -2.07768404916278, 1.57843833028236, 1.23783669851953, 15.5659876348306, -6.86188181853719, -5.50621793641665, -3.62888602818304, -0.145891471793544, -0.825028473757867, -2.52251372025581, -1.19867033251869, -2.47536209021952, 1.41122996270707, -5.95624742000524, 0.832231787736836, 2.38404919543544; double ll_expected = -82647.3683004951; double lp_ref = gaussian_dlm_log(y, FF, GG, V, W); EXPECT_FLOAT_EQ(lp_ref, ll_expected); } TEST(ProbDistributionsGaussianDLM,Sizing) { // consistent matrices Matrix<double, Dynamic, Dynamic> FF = MatrixXd::Random(2, 3); Matrix<double, Dynamic, Dynamic> GG = MatrixXd::Random(2, 2); Matrix<double, Dynamic, Dynamic> V = MatrixXd::Identity(3, 3); Matrix<double, Dynamic, Dynamic> W = MatrixXd::Identity(2, 2); Matrix<double, Dynamic, Dynamic> y = MatrixXd::Identity(3, 5); Matrix<double, Dynamic, Dynamic> bad_FF_1 = MatrixXd::Random(4, 3); EXPECT_ANY_THROW(gaussian_dlm_log(y, bad_FF_1, GG, V, W)); Matrix<double, Dynamic, Dynamic> bad_FF_2 = MatrixXd::Random(2, 4); EXPECT_ANY_THROW(gaussian_dlm_log(y, bad_FF_2, GG, V, W)); Matrix<double, Dynamic, Dynamic> bad_GG_1 = MatrixXd::Random(3, 3); EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, bad_GG_1, V, W)); Matrix<double, Dynamic, Dynamic> bad_GG_2 = MatrixXd::Random(2, 3); EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, bad_GG_2, V, W)); //Not symmetric V(0, 2) = 1; EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W)); // negative V(0, 2) = -1; EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W)); // wrong size Matrix<double, Dynamic, Dynamic> V1 = MatrixXd::Identity(2, 2); EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V1, W)); // not square Matrix<double, Dynamic, Dynamic> V2 = MatrixXd::Identity(2, 3); EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V2, W)); //Not symmetric W(0, 1) = 1; EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W)); // negative W(0, 1) = -1; EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W)); // wrong size Matrix<double, Dynamic, Dynamic> W1 = MatrixXd::Identity(3, 3); EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W1)); // not square Matrix<double, Dynamic, Dynamic> W2 = MatrixXd::Identity(2, 3); // EXPECT_ANY_THROW(gaussian_dlm_log(y, FF, GG, V, W2)); } <|endoftext|>
<commit_before>#include "Base.h" #include "ScriptController.h" #include "ScriptTarget.h" namespace gameplay { extern void splitURL(const std::string& url, std::string* file, std::string* id); ScriptTarget::~ScriptTarget() { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.begin(); for (; iter != _callbacks.end(); iter++) { SAFE_DELETE(iter->second); } } template<> void ScriptTarget::fireEvent<void>(const char* eventName, ...) { va_list list; va_start(list, eventName); std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end() && iter->second != NULL) { ScriptController* sc = Game::getInstance()->getScriptController(); if (_events[eventName].size() > 0) { for (unsigned int i = 0; i < iter->second->size(); i++) { sc->executeFunction<void>((*iter->second)[i].function.c_str(), _events[eventName].c_str(), &list); } } else { for (unsigned int i = 0; i < iter->second->size(); i++) { sc->executeFunction<void>((*iter->second)[i].function.c_str(), _events[eventName].c_str()); } } } va_end(list); } template<> bool ScriptTarget::fireEvent<bool>(const char* eventName, ...) { va_list list; va_start(list, eventName); std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end()) { ScriptController* sc = Game::getInstance()->getScriptController(); if (_events[eventName].size() > 0) { for (unsigned int i = 0; i < iter->second->size(); i++) { if (sc->executeFunction<bool>((*iter->second)[i].function.c_str(), _events[eventName].c_str(), &list)) { va_end(list); return true; } } } else { for (unsigned int i = 0; i < iter->second->size(); i++) { if (sc->executeFunction<bool>((*iter->second)[i].function.c_str(), _events[eventName].c_str())) { va_end(list); return true; } } } } va_end(list); return false; } void ScriptTarget::addCallback(const std::string& eventName, const std::string& function) { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end()) { if (!iter->second) iter->second = new std::vector<Callback>(); // Add the function to the list of callbacks. std::string functionName = Game::getInstance()->getScriptController()->loadUrl(function.c_str()); iter->second->push_back(Callback(functionName)); } else { GP_ERROR("Attempting to add a script callback for unsupported event '%s'.", eventName.c_str()); } } void ScriptTarget::removeCallback(const std::string& eventName, const std::string& function) { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end()) { if (!iter->second) return; std::string file; std::string id; splitURL(function, &file, &id); // Make sure the function isn't empty. if (id.size() <= 0) return; // Remove the function from the list of callbacks. for (unsigned int i = 0; i < iter->second->size(); i++) { if ((*iter->second)[i].function == id) { iter->second->erase(iter->second->begin() + i); return; } } } else { GP_ERROR("Attempting to remove a script callback for unsupported event '%s'.", eventName.c_str()); } } void ScriptTarget::addEvent(const std::string& eventName, const char* argsString) { _events[eventName] = (argsString ? argsString : ""); _callbacks[eventName] = NULL; } ScriptTarget::Callback::Callback(const std::string& function) : function(function) { } } <commit_msg>Fixed null pointer in ScriptTarget.<commit_after>#include "Base.h" #include "ScriptController.h" #include "ScriptTarget.h" namespace gameplay { extern void splitURL(const std::string& url, std::string* file, std::string* id); ScriptTarget::~ScriptTarget() { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.begin(); for (; iter != _callbacks.end(); iter++) { SAFE_DELETE(iter->second); } } template<> void ScriptTarget::fireEvent<void>(const char* eventName, ...) { va_list list; va_start(list, eventName); std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end() && iter->second != NULL) { ScriptController* sc = Game::getInstance()->getScriptController(); if (_events[eventName].size() > 0) { for (unsigned int i = 0; i < iter->second->size(); i++) { sc->executeFunction<void>((*iter->second)[i].function.c_str(), _events[eventName].c_str(), &list); } } else { for (unsigned int i = 0; i < iter->second->size(); i++) { sc->executeFunction<void>((*iter->second)[i].function.c_str(), _events[eventName].c_str()); } } } va_end(list); } template<> bool ScriptTarget::fireEvent<bool>(const char* eventName, ...) { va_list list; va_start(list, eventName); std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end() && iter->second) { ScriptController* sc = Game::getInstance()->getScriptController(); if (_events[eventName].size() > 0) { for (unsigned int i = 0; i < iter->second->size(); i++) { if (sc->executeFunction<bool>((*iter->second)[i].function.c_str(), _events[eventName].c_str(), &list)) { va_end(list); return true; } } } else { for (unsigned int i = 0; i < iter->second->size(); i++) { if (sc->executeFunction<bool>((*iter->second)[i].function.c_str(), _events[eventName].c_str())) { va_end(list); return true; } } } } va_end(list); return false; } void ScriptTarget::addCallback(const std::string& eventName, const std::string& function) { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end()) { if (!iter->second) iter->second = new std::vector<Callback>(); // Add the function to the list of callbacks. std::string functionName = Game::getInstance()->getScriptController()->loadUrl(function.c_str()); iter->second->push_back(Callback(functionName)); } else { GP_ERROR("Attempting to add a script callback for unsupported event '%s'.", eventName.c_str()); } } void ScriptTarget::removeCallback(const std::string& eventName, const std::string& function) { std::map<std::string, std::vector<Callback>* >::iterator iter = _callbacks.find(eventName); if (iter != _callbacks.end()) { if (!iter->second) return; std::string file; std::string id; splitURL(function, &file, &id); // Make sure the function isn't empty. if (id.size() <= 0) return; // Remove the function from the list of callbacks. for (unsigned int i = 0; i < iter->second->size(); i++) { if ((*iter->second)[i].function == id) { iter->second->erase(iter->second->begin() + i); return; } } } else { GP_ERROR("Attempting to remove a script callback for unsupported event '%s'.", eventName.c_str()); } } void ScriptTarget::addEvent(const std::string& eventName, const char* argsString) { _events[eventName] = (argsString ? argsString : ""); _callbacks[eventName] = NULL; } ScriptTarget::Callback::Callback(const std::string& function) : function(function) { } } <|endoftext|>