text
stringlengths
54
60.6k
<commit_before>/**************************************************************************** ** Copyright (c) 2017 Adrian Schneider ** ** 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 <iostream> #include "mnist/mnist_reader.hpp" int main(int argc, char* argv[]) { // MNIST_DATA_LOCATION set by MNIST cmake config std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl; // Load MNIST data mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataSet = mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION); std::cout << "Nbr of training images = " << dataSet.training_images.size() << std::endl; std::cout << "Nbr of training labels = " << dataSet.training_labels.size() << std::endl; std::cout << "Nbr of test images = " << dataSet.test_images.size() << std::endl; std::cout << "Nbr of test labels = " << dataSet.test_labels.size() << std::endl; return 0; } <commit_msg>Apply clang-format of wichtounet<commit_after>/**************************************************************************** ** Copyright (c) 2017 Adrian Schneider ** ** 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 <iostream> #include "mnist/mnist_reader.hpp" int main(int argc, char* argv[]) { // MNIST_DATA_LOCATION set by MNIST cmake config std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl; // Load MNIST data mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataSet = mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION); std::cout << "Nbr of training images = " << dataSet.training_images.size() << std::endl; std::cout << "Nbr of training labels = " << dataSet.training_labels.size() << std::endl; std::cout << "Nbr of test images = " << dataSet.test_images.size() << std::endl; std::cout << "Nbr of test labels = " << dataSet.test_labels.size() << std::endl; return 0; } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "test_from_toml" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml/toml.hpp> #include <map> #include <unordered_map> #include <list> #include <deque> BOOST_AUTO_TEST_CASE(test_from_toml_exact) { toml::Boolean b(true); toml::Integer i(42); toml::Float f(3.14); toml::String s("hoge"); toml::Datetime d(std::chrono::system_clock::now()); toml::Array a; a.emplace_back(2); a.emplace_back(7); a.emplace_back(1); a.emplace_back(8); a.emplace_back(2); toml::Table t; t.emplace("val1", true); t.emplace("val2", 42); t.emplace("val3", 3.14); t.emplace("val4", "piyo"); toml::value v1(b); toml::value v2(i); toml::value v3(f); toml::value v4(s); toml::value v5(d); toml::value v6(a); toml::value v7(t); toml::Boolean u1; toml::Integer u2; toml::Float u3; toml::String u4; toml::Datetime u5; toml::Array u6; toml::Table u7; toml::from_toml(u1, v1); toml::from_toml(u2, v2); toml::from_toml(u3, v3); toml::from_toml(u4, v4); toml::from_toml(u5, v5); toml::from_toml(u6, v6); toml::from_toml(u7, v7); BOOST_CHECK_EQUAL(u1, b); BOOST_CHECK_EQUAL(u2, i); BOOST_CHECK_EQUAL(u3, f); BOOST_CHECK_EQUAL(u4, s); BOOST_CHECK_EQUAL(u6.at(0).cast<toml::value_t::Integer>(), a.at(0).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(1).cast<toml::value_t::Integer>(), a.at(1).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(2).cast<toml::value_t::Integer>(), a.at(2).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(3).cast<toml::value_t::Integer>(), a.at(3).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(4).cast<toml::value_t::Integer>(), a.at(4).cast<toml::value_t::Integer>()); } BOOST_AUTO_TEST_CASE(test_from_toml_cast) { toml::Integer i(42); toml::Float f(3.14); toml::Array a; a.emplace_back(2); a.emplace_back(7); a.emplace_back(1); a.emplace_back(8); a.emplace_back(2); toml::Table t; t.emplace("val1", true); t.emplace("val2", 42); t.emplace("val3", 3.14); t.emplace("val4", "piyo"); toml::value vi(i); toml::value vf(f); toml::value va(a); toml::value vt(t); int u1; std::size_t u2; float u3; std::list<int> u4; std::deque<std::size_t> u5; std::map<std::string, toml::value> u6; std::list<int> expect_list; expect_list.push_back(2); expect_list.push_back(7); expect_list.push_back(1); expect_list.push_back(8); expect_list.push_back(2); toml::from_toml(u1, vi); toml::from_toml(u2, vi); toml::from_toml(u3, vf); toml::from_toml(u4, va); toml::from_toml(u5, va); toml::from_toml(u6, vt); BOOST_CHECK_EQUAL(u1, 42); BOOST_CHECK_EQUAL(u2, 42ul); BOOST_CHECK_CLOSE_FRACTION(u3, 3.14, 1e-3); bool same_list = (u4 == expect_list); BOOST_CHECK(same_list); BOOST_CHECK_EQUAL(u5.at(0), 2); BOOST_CHECK_EQUAL(u5.at(1), 7); BOOST_CHECK_EQUAL(u5.at(2), 1); BOOST_CHECK_EQUAL(u5.at(3), 8); BOOST_CHECK_EQUAL(u5.at(4), 2); BOOST_CHECK_EQUAL(u6["val1"].cast<toml::value_t::Boolean>(), true); BOOST_CHECK_EQUAL(u6["val2"].cast<toml::value_t::Integer>(), 42); BOOST_CHECK_CLOSE_FRACTION(u6["val3"].cast<toml::value_t::Float>(), 3.14, 1e-3); BOOST_CHECK_EQUAL(u6["val4"].cast<toml::value_t::String >(), "piyo"); } <commit_msg>add test for from_toml: Table<commit_after>#define BOOST_TEST_MODULE "test_from_toml" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml/toml.hpp> #include <map> #include <unordered_map> #include <list> #include <deque> BOOST_AUTO_TEST_CASE(test_from_toml_exact) { toml::Boolean b(true); toml::Integer i(42); toml::Float f(3.14); toml::String s("hoge"); toml::Datetime d(std::chrono::system_clock::now()); toml::Array a; a.emplace_back(2); a.emplace_back(7); a.emplace_back(1); a.emplace_back(8); a.emplace_back(2); toml::Table t; t.emplace("val1", true); t.emplace("val2", 42); t.emplace("val3", 3.14); t.emplace("val4", "piyo"); toml::value v1(b); toml::value v2(i); toml::value v3(f); toml::value v4(s); toml::value v5(d); toml::value v6(a); toml::value v7(t); toml::Boolean u1; toml::Integer u2; toml::Float u3; toml::String u4; toml::Datetime u5; toml::Array u6; toml::Table u7; toml::from_toml(u1, v1); toml::from_toml(u2, v2); toml::from_toml(u3, v3); toml::from_toml(u4, v4); toml::from_toml(u5, v5); toml::from_toml(u6, v6); toml::from_toml(u7, v7); BOOST_CHECK_EQUAL(u1, b); BOOST_CHECK_EQUAL(u2, i); BOOST_CHECK_EQUAL(u3, f); BOOST_CHECK_EQUAL(u4, s); BOOST_CHECK_EQUAL(u6.at(0).cast<toml::value_t::Integer>(), a.at(0).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(1).cast<toml::value_t::Integer>(), a.at(1).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(2).cast<toml::value_t::Integer>(), a.at(2).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(3).cast<toml::value_t::Integer>(), a.at(3).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at(4).cast<toml::value_t::Integer>(), a.at(4).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u7.at("val1").cast<toml::value_t::Boolean>(), true); BOOST_CHECK_EQUAL(u7.at("val2").cast<toml::value_t::Integer>(), 42); BOOST_CHECK_CLOSE_FRACTION(u7.at("val3").cast<toml::value_t::Float>(),3.14, 1e-3); BOOST_CHECK_EQUAL(u7.at("val4").cast<toml::value_t::String>(), "piyo"); } BOOST_AUTO_TEST_CASE(test_from_toml_cast) { toml::Integer i(42); toml::Float f(3.14); toml::Array a; a.emplace_back(2); a.emplace_back(7); a.emplace_back(1); a.emplace_back(8); a.emplace_back(2); toml::Table t; t.emplace("val1", true); t.emplace("val2", 42); t.emplace("val3", 3.14); t.emplace("val4", "piyo"); toml::value vi(i); toml::value vf(f); toml::value va(a); toml::value vt(t); int u1; std::size_t u2; float u3; std::list<int> u4; std::deque<std::size_t> u5; std::map<std::string, toml::value> u6; std::list<int> expect_list; expect_list.push_back(2); expect_list.push_back(7); expect_list.push_back(1); expect_list.push_back(8); expect_list.push_back(2); toml::from_toml(u1, vi); toml::from_toml(u2, vi); toml::from_toml(u3, vf); toml::from_toml(u4, va); toml::from_toml(u5, va); toml::from_toml(u6, vt); BOOST_CHECK_EQUAL(u1, 42); BOOST_CHECK_EQUAL(u2, 42ul); BOOST_CHECK_CLOSE_FRACTION(u3, 3.14, 1e-3); bool same_list = (u4 == expect_list); BOOST_CHECK(same_list); BOOST_CHECK_EQUAL(u5.at(0), 2); BOOST_CHECK_EQUAL(u5.at(1), 7); BOOST_CHECK_EQUAL(u5.at(2), 1); BOOST_CHECK_EQUAL(u5.at(3), 8); BOOST_CHECK_EQUAL(u5.at(4), 2); BOOST_CHECK_EQUAL(u6["val1"].cast<toml::value_t::Boolean>(), true); BOOST_CHECK_EQUAL(u6["val2"].cast<toml::value_t::Integer>(), 42); BOOST_CHECK_CLOSE_FRACTION(u6["val3"].cast<toml::value_t::Float>(), 3.14, 1e-3); BOOST_CHECK_EQUAL(u6["val4"].cast<toml::value_t::String >(), "piyo"); } <|endoftext|>
<commit_before>// MFEM Example 1 // // Compile with: make ex1 // // Sample runs: ex1 -m ../data/square-disc.mesh // ex1 -m ../data/star.mesh // ex1 -m ../data/star-mixed.mesh // ex1 -m ../data/escher.mesh // ex1 -m ../data/fichera.mesh // ex1 -m ../data/fichera-mixed.mesh // ex1 -m ../data/toroid-wedge.mesh // ex1 -m ../data/square-disc-p2.vtk -o 2 // ex1 -m ../data/square-disc-p3.mesh -o 3 // ex1 -m ../data/square-disc-nurbs.mesh -o -1 // ex1 -m ../data/star-mixed-p2.mesh -o 2 // ex1 -m ../data/disc-nurbs.mesh -o -1 // ex1 -m ../data/pipe-nurbs.mesh -o -1 // ex1 -m ../data/fichera-mixed-p2.mesh -o 2 // ex1 -m ../data/star-surf.mesh // ex1 -m ../data/square-disc-surf.mesh // ex1 -m ../data/inline-segment.mesh // ex1 -m ../data/amr-quad.mesh // ex1 -m ../data/amr-hex.mesh // ex1 -m ../data/fichera-amr.mesh // ex1 -m ../data/mobius-strip.mesh // ex1 -m ../data/mobius-strip.mesh -o -1 -sc // // Description: This example code demonstrates the use of MFEM to define a // simple finite element discretization of the Laplace problem // -Delta u = 1 with homogeneous Dirichlet boundary conditions. // Specifically, we discretize using a FE space of the specified // order, or if order < 1 using an isoparametric/isogeometric // space (i.e. quadratic for quadratic curvilinear mesh, NURBS for // NURBS mesh, etc.) // // The example highlights the use of mesh refinement, finite // element grid functions, as well as linear and bilinear forms // corresponding to the left-hand side and right-hand side of the // discrete linear system. We also cover the explicit elimination // of essential boundary conditions, static condensation, and the // optional connection to the GLVis tool for visualization. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; //#include "/home/camier1/home/stk/stk.hpp" int main(int argc, char *argv[]) { dbg("main\n"); //stkIni(argv[0]); // 1. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; int level = -1; bool static_cond = false; bool pa = false; bool gpu = false; bool nvvp = false; bool sync = false; bool visualization = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree) or -1 for" " isoparametric space."); args.AddOption(&level, "-l", "--level", "Refinement level"); args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc", "--no-static-condensation", "Enable static condensation."); args.AddOption(&pa, "-p", "--pa", "-no-p", "--no-pa", "Enable Partial Assembly."); args.AddOption(&gpu, "-g", "--gpu", "-no-g", "--no-gpu", "Enable GPU."); args.AddOption(&nvvp, "-n", "--nvvp", "-no-n", "--no-nvvp", "Enable NVVP."); args.AddOption(&sync, "-s", "--sync", "-no-s", "--no-sync", "Enable SYNC."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); if (nvvp) { config::Get().Nvvp(true); } if (sync) { config::Get().Sync(true); } // 2. Read the mesh from the given mesh file. We can handle triangular, // quadrilateral, tetrahedral, hexahedral, surface and volume meshes with // the same code. Mesh *mesh = new Mesh(mesh_file, 1, 1); int dim = mesh->Dimension(); // 3. Refine the mesh to increase the resolution. In this example we do // 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the // largest number that gives a final mesh with no more than 50,000 // elements. { push(Refine,Indigo); int ref_levels = level>0 ? level : (int)floor(log(50000./mesh->GetNE())/log(2.)/dim); for (int l = 0; l < ref_levels; l++) { mesh->UniformRefinement(); } pop(); } // 4. Define a finite element space on the mesh. Here we use continuous // Lagrange finite elements of the specified order. If order < 1, we // instead use an isoparametric/isogeometric space. push(FEC,LightSalmon); FiniteElementCollection *fec; if (order > 0) { fec = new H1_FECollection(order, dim); } else if (mesh->GetNodes()) { fec = mesh->GetNodes()->OwnFEC(); cout << "Using isoparametric FEs: " << fec->Name() << endl; } else { fec = new H1_FECollection(order = 1, dim); } pop(); push(FES,Plum); FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec); cout << "Number of finite element unknowns: " << fespace->GetTrueVSize() << endl; pop(); // 5. Determine the list of true (i.e. conforming) essential boundary dofs. // In this example, the boundary conditions are defined by marking all // the boundary attributes from the mesh as essential (Dirichlet) and // converting them to a list of true dofs. push(BC,Tomato); Array<int> ess_tdof_list; if (mesh->bdr_attributes.Size()) { Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } pop(); // 6. Set up the linear form b(.) which corresponds to the right-hand side of // the FEM linear system, which in this case is (1,phi_i) where phi_i are // the basis functions in the finite element fespace. push(b,DarkMagenta); LinearForm *b = new LinearForm(fespace); ConstantCoefficient one(1.0); b->AddDomainIntegrator(new DomainLFIntegrator(one)); b->Assemble(); pop(); // ************************************************************************** push(SetCurvature,OliveDrab); mesh->SetCurvature(1, false, -1, Ordering::byVDIM); pop(); if (gpu) { config::Get().Cuda(true); } if (pa) { config::Get().PA(true); } dbg(" 7. Define the solution vector x");// as a finite element grid function // corresponding to fespace. Initialize x with initial guess of zero, // which satisfies the boundary conditions. push(GridFunction,Fuchsia); GridFunction x(fespace); x = 0.0; pop(); dbg(" 8. Set up the bilinear form a(.,.)");// on the finite element space // corresponding to the Laplacian operator -Delta, by adding the Diffusion // domain integrator. push(BilinearForm,Fuchsia); BilinearForm *a = new BilinearForm(fespace); // On piece here pop(); push(AddDomainIntegrator,Fuchsia); if (pa) { a->AddDomainIntegrator(new PADiffusionIntegrator(one)); } else { a->AddDomainIntegrator(new DiffusionIntegrator(one)); } pop(); dbg(" 9. Assemble the bilinear form");// and the corresponding linear system, // applying any necessary transformations such as: eliminating boundary // conditions, applying conforming constraints for non-conforming AMR, // static condensation, etc. if (static_cond) { a->EnableStaticCondensation(); } push(Assemble,Fuchsia); a->Assemble(); // On piece here pop(); Vector B, X; Operator *A; push(Operator,Fuchsia); if (pa) { A = new PABilinearForm(fespace); } else { A = new SparseMatrix(); } pop(); push(FormLinearSystem,Fuchsia); a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B); pop(); cout << "Size of linear system: " << A->Height() << endl; #ifndef MFEM_USE_SUITESPARSE push(); CG(*A, B, X, 3, 2000, 1e-12, 0.0); pop(); #else // 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system. UMFPackSolver umf_solver; umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS; umf_solver.SetOperator(A); umf_solver.Mult(B, X); #endif // 11. Recover the solution as a finite element grid function. a->RecoverFEMSolution(X, *b, x); // 12. Save the refined mesh and the solution. This output can be viewed later // using GLVis: "glvis -m refined.mesh -g sol.gf". ofstream mesh_ofs("refined.mesh"); mesh_ofs.precision(8); mesh->Print(mesh_ofs); ofstream sol_ofs("sol.gf"); sol_ofs.precision(8); x.Save(sol_ofs); // 13. Send the solution by socket to a GLVis server. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "solution\n" << *mesh << x << flush; } // 14. Free the used memory. delete a; delete b; delete fespace; if (order > 0) { delete fec; } delete mesh; delete A; return 0; } <commit_msg>In ex1.cpp, add CG timings to output; add 'mix_iter' option.<commit_after>// MFEM Example 1 // // Compile with: make ex1 // // Sample runs: ex1 -m ../data/square-disc.mesh // ex1 -m ../data/star.mesh // ex1 -m ../data/star-mixed.mesh // ex1 -m ../data/escher.mesh // ex1 -m ../data/fichera.mesh // ex1 -m ../data/fichera-mixed.mesh // ex1 -m ../data/toroid-wedge.mesh // ex1 -m ../data/square-disc-p2.vtk -o 2 // ex1 -m ../data/square-disc-p3.mesh -o 3 // ex1 -m ../data/square-disc-nurbs.mesh -o -1 // ex1 -m ../data/star-mixed-p2.mesh -o 2 // ex1 -m ../data/disc-nurbs.mesh -o -1 // ex1 -m ../data/pipe-nurbs.mesh -o -1 // ex1 -m ../data/fichera-mixed-p2.mesh -o 2 // ex1 -m ../data/star-surf.mesh // ex1 -m ../data/square-disc-surf.mesh // ex1 -m ../data/inline-segment.mesh // ex1 -m ../data/amr-quad.mesh // ex1 -m ../data/amr-hex.mesh // ex1 -m ../data/fichera-amr.mesh // ex1 -m ../data/mobius-strip.mesh // ex1 -m ../data/mobius-strip.mesh -o -1 -sc // // Description: This example code demonstrates the use of MFEM to define a // simple finite element discretization of the Laplace problem // -Delta u = 1 with homogeneous Dirichlet boundary conditions. // Specifically, we discretize using a FE space of the specified // order, or if order < 1 using an isoparametric/isogeometric // space (i.e. quadratic for quadratic curvilinear mesh, NURBS for // NURBS mesh, etc.) // // The example highlights the use of mesh refinement, finite // element grid functions, as well as linear and bilinear forms // corresponding to the left-hand side and right-hand side of the // discrete linear system. We also cover the explicit elimination // of essential boundary conditions, static condensation, and the // optional connection to the GLVis tool for visualization. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; //#include "/home/camier1/home/stk/stk.hpp" int main(int argc, char *argv[]) { dbg("main\n"); //stkIni(argv[0]); // 1. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; int level = -1; int max_iter = 2000; bool static_cond = false; bool pa = false; bool gpu = false; bool nvvp = false; bool sync = false; bool visualization = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree) or -1 for" " isoparametric space."); args.AddOption(&level, "-l", "--level", "Refinement level"); args.AddOption(&max_iter, "-mi", "--max-iter", "Maximum number of CG iterations"); args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc", "--no-static-condensation", "Enable static condensation."); args.AddOption(&pa, "-p", "--pa", "-no-p", "--no-pa", "Enable Partial Assembly."); args.AddOption(&gpu, "-g", "--gpu", "-no-g", "--no-gpu", "Enable GPU."); args.AddOption(&nvvp, "-n", "--nvvp", "-no-n", "--no-nvvp", "Enable NVVP."); args.AddOption(&sync, "-s", "--sync", "-no-s", "--no-sync", "Enable SYNC."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); if (nvvp) { config::Get().Nvvp(true); } if (sync) { config::Get().Sync(true); } // 2. Read the mesh from the given mesh file. We can handle triangular, // quadrilateral, tetrahedral, hexahedral, surface and volume meshes with // the same code. Mesh *mesh = new Mesh(mesh_file, 1, 1); int dim = mesh->Dimension(); // 3. Refine the mesh to increase the resolution. In this example we do // 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the // largest number that gives a final mesh with no more than 50,000 // elements. { push(Refine,Indigo); int ref_levels = level>=0 ? level : (int)floor(log(50000./mesh->GetNE())/log(2.)/dim); for (int l = 0; l < ref_levels; l++) { mesh->UniformRefinement(); } pop(); } // 4. Define a finite element space on the mesh. Here we use continuous // Lagrange finite elements of the specified order. If order < 1, we // instead use an isoparametric/isogeometric space. push(FEC,LightSalmon); FiniteElementCollection *fec; if (order > 0) { fec = new H1_FECollection(order, dim); } else if (mesh->GetNodes()) { fec = mesh->GetNodes()->OwnFEC(); cout << "Using isoparametric FEs: " << fec->Name() << endl; } else { fec = new H1_FECollection(order = 1, dim); } pop(); push(FES,Plum); FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec); cout << "Number of finite element unknowns: " << fespace->GetTrueVSize() << endl; pop(); // 5. Determine the list of true (i.e. conforming) essential boundary dofs. // In this example, the boundary conditions are defined by marking all // the boundary attributes from the mesh as essential (Dirichlet) and // converting them to a list of true dofs. push(BC,Tomato); Array<int> ess_tdof_list; if (mesh->bdr_attributes.Size()) { Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } pop(); // 6. Set up the linear form b(.) which corresponds to the right-hand side of // the FEM linear system, which in this case is (1,phi_i) where phi_i are // the basis functions in the finite element fespace. push(b,DarkMagenta); LinearForm *b = new LinearForm(fespace); ConstantCoefficient one(1.0); b->AddDomainIntegrator(new DomainLFIntegrator(one)); b->Assemble(); pop(); // ************************************************************************** push(SetCurvature,OliveDrab); mesh->SetCurvature(1, false, -1, Ordering::byVDIM); pop(); if (gpu) { config::Get().Cuda(true); } if (pa) { config::Get().PA(true); } dbg(" 7. Define the solution vector x");// as a finite element grid function // corresponding to fespace. Initialize x with initial guess of zero, // which satisfies the boundary conditions. push(GridFunction,Fuchsia); GridFunction x(fespace); x = 0.0; pop(); dbg(" 8. Set up the bilinear form a(.,.)");// on the finite element space // corresponding to the Laplacian operator -Delta, by adding the Diffusion // domain integrator. push(BilinearForm,Fuchsia); BilinearForm *a = new BilinearForm(fespace); // On piece here pop(); push(AddDomainIntegrator,Fuchsia); if (pa) { a->AddDomainIntegrator(new PADiffusionIntegrator(one)); } else { a->AddDomainIntegrator(new DiffusionIntegrator(one)); } pop(); dbg(" 9. Assemble the bilinear form");// and the corresponding linear system, // applying any necessary transformations such as: eliminating boundary // conditions, applying conforming constraints for non-conforming AMR, // static condensation, etc. if (static_cond) { a->EnableStaticCondensation(); } push(Assemble,Fuchsia); a->Assemble(); // On piece here pop(); Vector B, X; Operator *A; push(Operator,Fuchsia); if (pa) { A = new PABilinearForm(fespace); } else { A = new SparseMatrix(); } pop(); push(FormLinearSystem,Fuchsia); a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B); pop(); cout << "Size of linear system: " << A->Height() << endl; CGSolver *cg; cg = new CGSolver; cg->SetRelTol(1e-6); cg->SetMaxIter(max_iter); cg->SetPrintLevel(3); cg->SetOperator(*A); tic_toc.Clear(); tic_toc.Start(); #ifndef MFEM_USE_SUITESPARSE push(); cg->Mult(B, X); pop(); #else // 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system. UMFPackSolver umf_solver; umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS; umf_solver.SetOperator(A); umf_solver.Mult(B, X); #endif double my_rt = tic_toc.RealTime(); cout << "\nTotal CG time: " << my_rt << " sec." << endl; cout << "Time per CG step: " << my_rt / cg->GetNumIterations() << " sec." << endl; cout << "\n\"DOFs/sec\" in CG: " << 1e-6*A->Height()*cg->GetNumIterations()/my_rt << " million.\n" << endl; delete cg; // 11. Recover the solution as a finite element grid function. a->RecoverFEMSolution(X, *b, x); // 12. Save the refined mesh and the solution. This output can be viewed later // using GLVis: "glvis -m refined.mesh -g sol.gf". ofstream mesh_ofs("refined.mesh"); mesh_ofs.precision(8); mesh->Print(mesh_ofs); ofstream sol_ofs("sol.gf"); sol_ofs.precision(8); x.Save(sol_ofs); // 13. Send the solution by socket to a GLVis server. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "solution\n" << *mesh << x << flush; } // 14. Free the used memory. delete a; delete b; delete fespace; if (order > 0) { delete fec; } delete mesh; delete A; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000010ace86e884d6d7c8529b2050e2de9f987f7763f978109546b0d6659ba2")) ( 7380, uint256("0x00000000251fdf3d114a13430925b19a4dce4c40d230402933715182b6b0e33d")) ( 10000, uint256("0x0000000006c1a1573ca82ad24789c10a36535cf085f201122f1d112a88841271")) ( 15790, uint256("0x000000004151f93a4012545309d4bbcac5f2977dea643a178c4bec1310e6c086")) ( 21190, uint256("0x000000002a798fd88d0ce270cad1c217aceea236b573c68cfd02b086f5745921")) ( 26000, uint256("0x00000002bace42e673000616ed8dbf16a49e3a7aec6bf59774fed081f6deac5f")) ( 29999, uint256("0x00000000ede644fcbdf8f8ce8c53bb15de5dfd5c32384c751fa4ef409992aa07")) ; static const CCheckpointData data = { &mapCheckpoints, 1404869244, // * UNIX timestamp of last checkpoint block 25000, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 800.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x000008030a1e9a647ecc6119e0782166552e49dadfa8353afa26f3a6c2179845")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1402095180, 3000, 30 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>checkpoints added<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000010ace86e884d6d7c8529b2050e2de9f987f7763f978109546b0d6659ba2")) ( 7380, uint256("0x00000000251fdf3d114a13430925b19a4dce4c40d230402933715182b6b0e33d")) ( 10000, uint256("0x0000000006c1a1573ca82ad24789c10a36535cf085f201122f1d112a88841271")) ( 15790, uint256("0x000000004151f93a4012545309d4bbcac5f2977dea643a178c4bec1310e6c086")) ( 21190, uint256("0x000000002a798fd88d0ce270cad1c217aceea236b573c68cfd02b086f5745921")) ( 26000, uint256("0x00000002bace42e673000616ed8dbf16a49e3a7aec6bf59774fed081f6deac5f")) ( 29999, uint256("0x00000000ede644fcbdf8f8ce8c53bb15de5dfd5c32384c751fa4ef409992aa07")) ( 36200, uint256("0x00000004a711342c5c2286f47146faf246162be08b6078c8ff03076a4419551d")) ; static const CCheckpointData data = { &mapCheckpoints, 1404869244, // * UNIX timestamp of last checkpoint block 25000, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 800.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x000008030a1e9a647ecc6119e0782166552e49dadfa8353afa26f3a6c2179845")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1402095180, 3000, 30 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Fastly, Inc. * * 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. */ /* * This file implements a test harness for using h2o with LibFuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info. */ #define H2O_USE_EPOLL 1 #include <string.h> #include <errno.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/select.h> #include <wait.h> #include <malloc.h> #include <unistd.h> #include <fcntl.h> #include "h2o.h" #include "h2o/http1.h" #include "h2o/http2.h" #include "h2o/memcached.h" #if !defined(HTTP1) && !defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2" #endif #if defined(HTTP1) && defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2, but not both" #endif /* * Registers a request handler with h2o */ static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *)) { h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0); h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler)); handler->on_req = on_req; return pathconf; } /* * Request handler used for testing. Returns a basic "200 OK" response. */ static int chunked_test(h2o_handler_t *self, h2o_req_t *req) { static h2o_generator_t generator = {NULL, NULL}; if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX); req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, H2O_STRLIT("text/plain")); h2o_start_response(req, &generator); h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL); return 0; } /* * Request handler used for testing reproxy requests. Returns a basic "200 OK" * response. * See https://h2o.examp1e.net/configure/reproxy_directives.html for more info. */ static int reproxy_test(h2o_handler_t *self, h2o_req_t *req) { if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_X_REPROXY_URL, H2O_STRLIT("http://www.ietf.org/")); h2o_send_inline(req, H2O_STRLIT("you should never see this!\n")); return 0; } static h2o_globalconf_t config; static h2o_context_t ctx; static h2o_accept_ctx_t accept_ctx; /* copy from src to dst, return true if src has EOF */ static int drain(int fd) { char buf[4096]; ssize_t n; n = read(fd, buf, sizeof(buf)); if (n <= 0) { return 1; } return 0; } /* A request sent from client thread to h2o server */ struct writer_thread_arg { char *buf; size_t len; int fd; int ofd; pthread_barrier_t barrier; }; /* * Reads writer_thread_arg from fd and stores to buf */ static void read_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Writes the writer_thread_args at buf to fd */ static void write_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Thread: Loops writing fuzzed req to socket and then reading results back. * Acts as a client to h2o. *arg points to file descripter to read * writer_thread_args from. */ void *writer_thread(void *arg) { int rfd = (long)arg; while (1) { int pos, sockinp, sockoutp, cnt, len; char *buf; struct writer_thread_arg *wta; /* Get fuzzed request */ read_fully(rfd, (char *)&wta, sizeof(wta)); pos = 0; sockinp = wta->fd; sockoutp = wta->fd; cnt = 0; buf = wta->buf; len = wta->len; /* * Send fuzzed req and read results until the socket is closed (or * something spurious happens) */ while (cnt++ < 20 && (pos < len || sockinp >= 0)) { #define MARKER "\n--MARK--\n" /* send 1 packet */ if (pos < len) { char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1); if (p) { int l = p - (buf + pos); write(sockoutp, buf + pos, l); pos += l; pos += sizeof(MARKER) - 1; } } else { if (sockinp >= 0) { shutdown(sockinp, SHUT_WR); } } /* drain socket */ if (sockinp >= 0) { struct timeval timeo; fd_set rd; int n; FD_ZERO(&rd); FD_SET(sockinp, &rd); timeo.tv_sec = 0; timeo.tv_usec = 10 * 1000; n = select(sockinp + 1, &rd, NULL, NULL, &timeo); if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) { sockinp = -1; } } } close(wta->fd); close(wta->ofd); pthread_barrier_wait(&wta->barrier); free(wta); } } /* * Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client) * for writing to the target h2o server. Returns the server socket fd. */ static int feeder(int sfd, char *buf, size_t len, pthread_barrier_t **barrier) { int pair[2]; struct writer_thread_arg *wta; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) return -1; wta = (struct writer_thread_arg *)malloc(sizeof(*wta)); wta->fd = pair[0]; wta->ofd = pair[1]; wta->buf = buf; wta->len = len; pthread_barrier_init(&wta->barrier, NULL, 2); *barrier = &wta->barrier; write_fully(sfd, (char *)&wta, sizeof(wta)); return pair[1]; } /* * Creates/connects socket pair for client/server interaction and passes * fuzzed request to client for sending. * Returns server socket fd. */ static int create_accepted(int sfd, char *buf, size_t len, pthread_barrier_t **barrier) { int fd; h2o_socket_t *sock; struct timeval connected_at = *h2o_get_timestamp(&ctx, NULL, NULL); /* Create an HTTP[/2] client that will send the fuzzed request */ fd = feeder(sfd, buf, len, barrier); assert(fd >= 0); /* Pass the server socket to h2o and invoke request processing */ sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION); #if defined(HTTP1) h2o_http1_accept(&accept_ctx, sock, connected_at); #else h2o_http2_accept(&accept_ctx, sock, connected_at); #endif return fd; } /* * Returns true if fd if valid. Used to determine when connection is closed. */ static int is_valid_fd(int fd) { return fcntl(fd, F_GETFD) != -1 || errno != EBADF; } /* * Entry point for libfuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info */ static int init_done; static int job_queue[2]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int c; h2o_loop_t *loop; h2o_hostconf_t *hostconf; pthread_t t; /* * Perform one-time initialization */ if (!init_done) { signal(SIGPIPE, SIG_IGN); /* Create a single h2o host with multiple request handlers */ h2o_config_init(&config); config.http2.idle_timeout = 10 * 1000; config.http1.req_timeout = 10 * 1000; config.proxy.io_timeout = 10 * 1000; hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT("default")), 65535); register_handler(hostconf, "/chunked-test", chunked_test); h2o_reproxy_register(register_handler(hostconf, "/reproxy-test", reproxy_test)); h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0); loop = h2o_evloop_create(); h2o_context_init(&ctx, loop, &config); accept_ctx.ctx = &ctx; accept_ctx.hosts = config.hosts; /* Create a thread to act as the HTTP client */ assert(socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) == 0); assert(pthread_create(&t, NULL, writer_thread, (void *)(long)job_queue[1]) == 0); init_done = 1; } /* * Pass fuzzed request to client thread and get h2o server socket for * use below */ pthread_barrier_t *end; c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end); if (c < 0) { goto Error; } /* Loop until the connection is closed by the client or server */ while (is_valid_fd(c) && h2o_evloop_run(ctx.loop, 10)) ; pthread_barrier_wait(end); pthread_barrier_destroy(end); return 0; Error: return 1; } <commit_msg>Never exit the fuzzer until h2o ended up closing the fd internally.<commit_after>/* * Copyright (c) 2016 Fastly, Inc. * * 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. */ /* * This file implements a test harness for using h2o with LibFuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info. */ #define H2O_USE_EPOLL 1 #include <string.h> #include <errno.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/select.h> #include <wait.h> #include <malloc.h> #include <unistd.h> #include <fcntl.h> #include "h2o.h" #include "h2o/http1.h" #include "h2o/http2.h" #include "h2o/memcached.h" #if !defined(HTTP1) && !defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2" #endif #if defined(HTTP1) && defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2, but not both" #endif /* * Registers a request handler with h2o */ static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *)) { h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0); h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler)); handler->on_req = on_req; return pathconf; } /* * Request handler used for testing. Returns a basic "200 OK" response. */ static int chunked_test(h2o_handler_t *self, h2o_req_t *req) { static h2o_generator_t generator = {NULL, NULL}; if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX); req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, H2O_STRLIT("text/plain")); h2o_start_response(req, &generator); h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL); return 0; } /* * Request handler used for testing reproxy requests. Returns a basic "200 OK" * response. * See https://h2o.examp1e.net/configure/reproxy_directives.html for more info. */ static int reproxy_test(h2o_handler_t *self, h2o_req_t *req) { if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_X_REPROXY_URL, H2O_STRLIT("http://www.ietf.org/")); h2o_send_inline(req, H2O_STRLIT("you should never see this!\n")); return 0; } static h2o_globalconf_t config; static h2o_context_t ctx; static h2o_accept_ctx_t accept_ctx; /* copy from src to dst, return true if src has EOF */ static int drain(int fd) { char buf[4096]; ssize_t n; n = read(fd, buf, sizeof(buf)); if (n <= 0) { return 1; } return 0; } /* A request sent from client thread to h2o server */ struct writer_thread_arg { char *buf; size_t len; int fd; pthread_barrier_t barrier; }; /* * Reads writer_thread_arg from fd and stores to buf */ static void read_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Writes the writer_thread_args at buf to fd */ static void write_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Thread: Loops writing fuzzed req to socket and then reading results back. * Acts as a client to h2o. *arg points to file descripter to read * writer_thread_args from. */ void *writer_thread(void *arg) { int rfd = (long)arg; while (1) { int pos, sockinp, sockoutp, cnt, len; char *buf; struct writer_thread_arg *wta; /* Get fuzzed request */ read_fully(rfd, (char *)&wta, sizeof(wta)); pos = 0; sockinp = wta->fd; sockoutp = wta->fd; cnt = 0; buf = wta->buf; len = wta->len; /* * Send fuzzed req and read results until the socket is closed (or * something spurious happens) */ while (cnt++ < 20 && (pos < len || sockinp >= 0)) { #define MARKER "\n--MARK--\n" /* send 1 packet */ if (pos < len) { char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1); if (p) { int l = p - (buf + pos); write(sockoutp, buf + pos, l); pos += l; pos += sizeof(MARKER) - 1; } } else { if (sockinp >= 0) { shutdown(sockinp, SHUT_WR); } } /* drain socket */ if (sockinp >= 0) { struct timeval timeo; fd_set rd; int n; FD_ZERO(&rd); FD_SET(sockinp, &rd); timeo.tv_sec = 0; timeo.tv_usec = 10 * 1000; n = select(sockinp + 1, &rd, NULL, NULL, &timeo); if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) { sockinp = -1; } } } close(wta->fd); pthread_barrier_wait(&wta->barrier); free(wta); } } /* * Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client) * for writing to the target h2o server. Returns the server socket fd. */ static int feeder(int sfd, char *buf, size_t len, pthread_barrier_t **barrier) { int pair[2]; struct writer_thread_arg *wta; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) return -1; wta = (struct writer_thread_arg *)malloc(sizeof(*wta)); wta->fd = pair[0]; wta->buf = buf; wta->len = len; pthread_barrier_init(&wta->barrier, NULL, 2); *barrier = &wta->barrier; write_fully(sfd, (char *)&wta, sizeof(wta)); return pair[1]; } /* * Creates/connects socket pair for client/server interaction and passes * fuzzed request to client for sending. * Returns server socket fd. */ static int create_accepted(int sfd, char *buf, size_t len, pthread_barrier_t **barrier) { int fd; h2o_socket_t *sock; struct timeval connected_at = *h2o_get_timestamp(&ctx, NULL, NULL); /* Create an HTTP[/2] client that will send the fuzzed request */ fd = feeder(sfd, buf, len, barrier); assert(fd >= 0); /* Pass the server socket to h2o and invoke request processing */ sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION); #if defined(HTTP1) h2o_http1_accept(&accept_ctx, sock, connected_at); #else h2o_http2_accept(&accept_ctx, sock, connected_at); #endif return fd; } /* * Returns true if fd if valid. Used to determine when connection is closed. */ static int is_valid_fd(int fd) { return fcntl(fd, F_GETFD) != -1 || errno != EBADF; } /* * Entry point for libfuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info */ static int init_done; static int job_queue[2]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int c; h2o_loop_t *loop; h2o_hostconf_t *hostconf; pthread_t t; /* * Perform one-time initialization */ if (!init_done) { signal(SIGPIPE, SIG_IGN); /* Create a single h2o host with multiple request handlers */ h2o_config_init(&config); config.http2.idle_timeout = 10 * 1000; config.http1.req_timeout = 10 * 1000; config.proxy.io_timeout = 10 * 1000; hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT("default")), 65535); register_handler(hostconf, "/chunked-test", chunked_test); h2o_reproxy_register(register_handler(hostconf, "/reproxy-test", reproxy_test)); h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0); loop = h2o_evloop_create(); h2o_context_init(&ctx, loop, &config); accept_ctx.ctx = &ctx; accept_ctx.hosts = config.hosts; /* Create a thread to act as the HTTP client */ assert(socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) == 0); assert(pthread_create(&t, NULL, writer_thread, (void *)(long)job_queue[1]) == 0); init_done = 1; } /* * Pass fuzzed request to client thread and get h2o server socket for * use below */ pthread_barrier_t *end; c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end); if (c < 0) { goto Error; } /* Loop until the connection is closed by the client or server */ while (is_valid_fd(c)) { h2o_evloop_run(ctx.loop, 10); } pthread_barrier_wait(end); pthread_barrier_destroy(end); return 0; Error: return 1; } <|endoftext|>
<commit_before>// Copyright 2016-2020 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "message.h" #include <stddef.h> #include <algorithm> #include <memory> #include <set> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/stubs/strutil.h> #include "proto2-descriptor-extensions.pb.h" #include "enum.h" #include "field.h" #include "names.h" namespace google { namespace protobuf { namespace cl_protobufs { // Maximum value that an extension number can be. const int kMaxExtensionNumber = 0x1fffffff; // =================================================================== MessageGenerator::MessageGenerator(const Descriptor* descriptor) : descriptor_(descriptor), lisp_name_(MessageLispName(descriptor)), nested_(descriptor->nested_type_count()), enums_(descriptor->enum_type_count()) { for (int i = 0; i < descriptor->nested_type_count(); ++i) { nested_[i] = std::make_unique<MessageGenerator>(descriptor->nested_type(i)); } for (int i = 0; i < descriptor->enum_type_count(); ++i) { enums_[i] = std::make_unique<EnumGenerator>(descriptor->enum_type(i)); } } MessageGenerator::~MessageGenerator() {} namespace { // For the strange proto:define-group. const std::string FieldKeywordLabel(const FieldDescriptor::Label label) { switch (label) { case FieldDescriptor::LABEL_OPTIONAL: return ":optional"; case FieldDescriptor::LABEL_REQUIRED: return ":required"; case FieldDescriptor::LABEL_REPEATED: return ":repeated"; default: GOOGLE_LOG(FATAL) << "Unknown field label: " << label; return ":error"; } } } // namespace void MessageGenerator::GenerateSource(io::Printer* printer, const std::string& lisp_name, const int tag, const FieldDescriptor::Label label) { // Print group or message // Since we know the immediate next thing we emit is a newline we don't // need the extra space. const bool group = tag >= 0; printer->Print("\n"); printer->Print((group ? "(proto:define-group $name$" : "(proto:define-message $name$"), "name", lisp_name); printer->Annotate("name", descriptor_); printer->Indent(); // Message options. printer->Indent(); printer->Print("\n(:conc-name \"\""); if (group) { printer->Print("\n :index $tag$", "tag", StrCat(tag)); printer->Print("\n :label $label$", "label", FieldKeywordLabel(label)); } if (CamelIsSpitting(descriptor_->name())) { printer->Print("\n :name \"$name$\"", "name", descriptor_->name()); printer->Annotate("name", descriptor_->name()); } if (descriptor_->options().HasExtension(lisp_alias)) { // The symbol most likely doesn't exist yet. Use double-colon to create // the symbol if doesn't exist yet. const std::string& lasn = ToLispAliasSymbolName(descriptor_->options().GetExtension(lisp_alias)); printer->Print("\n :alias-for $for$", "for", lasn); printer->Annotate("for", lasn); } // END message options. printer->Print(")"); printer->Outdent(); if (descriptor_->enum_type_count() > 0) { printer->Print("\n;; Nested enums."); for (int i = 0; i < descriptor_->enum_type_count(); ++i) { enums_[i]->Generate(printer); } } if (descriptor_->nested_type_count() > 0) { printer->Print("\n;; Nested messages."); int printed = 0; for (int n = 0; n < descriptor_->nested_type_count(); ++n) { // Strange handling of group fields. // Remove all groups. Those should be generated with the fields. bool skip = false; for (int f = 0; f < descriptor_->field_count(); ++f) { if (descriptor_->field(f)->type() == FieldDescriptor::TYPE_GROUP && descriptor_->field(f)->message_type() == descriptor_->nested_type(n)) { skip = true; break; } } if (!skip) { nested_[n]->Generate(printer); ++printed; } } if (!printed) printer->Print(".. are all groups.\n"); } if (descriptor_->field_count() > 0) { printer->Print("\n;; Fields."); for (int i = 0; i < descriptor_->field_count(); ++i) { const FieldDescriptor* field = descriptor_->field(i); if (field->type() == FieldDescriptor::TYPE_GROUP) { // Strange way of handling group fields. MessageGenerator group(field->message_type()); group.GenerateSource(printer, ToLispName(field->message_type()->name()), field->number(), field->label()); } else { GenerateField(printer, field); } } } if (descriptor_->extension_count() > 0) { printer->Print("\n;; Extensions."); for (int i = 0; i < descriptor_->extension_count(); ++i) { GenerateExtension( printer, descriptor_->extension(i), descriptor_->file()); } } if (descriptor_->extension_range_count() > 0) { printer->Print("\n;; Extension ranges."); for (int i = 0; i < descriptor_->extension_range_count(); ++i) { const Descriptor::ExtensionRange* range = descriptor_->extension_range(i); printer->Print( "\n(proto:define-extension $start$ $end$)", "start", StrCat(range->start), // The end is inclusive in cl_protobufs. // For some reason, the extension number is generated as // 0x7ffffffe when specified as 'max', but the max must be // (2^29 - 1). "end", StrCat(std::min(kMaxExtensionNumber, range->end - 1))); } } printer->Print(")"); printer->Outdent(); } void MessageGenerator::Generate(io::Printer* printer) { GenerateSource(printer, lisp_name_, -1, FieldDescriptor::MAX_LABEL); } void MessageGenerator::AddExports(std::vector<std::string>* exports) { for (int n = 0; n < descriptor_->nested_type_count(); ++n) { // Strange handling of group fields. // Remove all groups. Those should be exported with the fields. // The field accessors of a group are not exported because // we're skipping the whole group. Fix it. bool skip = false; for (int f = 0; f < descriptor_->field_count(); ++f) { if (descriptor_->field(f)->type() == FieldDescriptor::TYPE_GROUP && descriptor_->field(f)->message_type() == descriptor_->nested_type(n)) { skip = true; break; } } if (!skip) { nested_[n]->AddExports(exports); } } for (int i = 0; i < descriptor_->enum_type_count(); ++i) { enums_[i]->AddExports(exports); } exports->push_back(lisp_name_); for (int i = 0; i < descriptor_->field_count(); ++i) { const FieldDescriptor* field = descriptor_->field(i); // For groups, the message type name must be used for the correct lisp name. // E.g. when a group is named `SomeGroup`, the field name is `somegroup`, // but we want `some-group`. std::string name = field->type() == FieldDescriptor::TYPE_GROUP ? ToLispName(field->message_type()->name()) : FieldLispName(field); exports->push_back(name); } for (int i = 0; i < descriptor_->extension_count(); ++i) { exports->push_back(FieldLispName(descriptor_->extension(i))); } } void MessageGenerator::AddPackages(std::set<std::string>* packages) { if (descriptor_->options().HasExtension(lisp_alias)) { const std::string alias = descriptor_->options().GetExtension(lisp_alias); const size_t colon = alias.find(':'); if (colon != std::string::npos && colon > 0) { packages->insert(ToUpper(alias.substr(0, colon))); } } for (int i = 0; i < descriptor_->nested_type_count(); ++i) { nested_[i]->AddPackages(packages); } } } // namespace cl_protobufs } // namespace protobuf } // namespace google <commit_msg>Add protoc modifications for oneof fields<commit_after>// Copyright 2016-2020 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "message.h" #include <stddef.h> #include <algorithm> #include <memory> #include <set> #include <unordered_set> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/stubs/strutil.h> #include "proto2-descriptor-extensions.pb.h" #include "enum.h" #include "field.h" #include "names.h" namespace google { namespace protobuf { namespace cl_protobufs { // Maximum value that an extension number can be. const int kMaxExtensionNumber = 0x1fffffff; // =================================================================== MessageGenerator::MessageGenerator(const Descriptor* descriptor) : descriptor_(descriptor), lisp_name_(MessageLispName(descriptor)), nested_(descriptor->nested_type_count()), enums_(descriptor->enum_type_count()) { for (int i = 0; i < descriptor->nested_type_count(); ++i) { nested_[i] = std::make_unique<MessageGenerator>(descriptor->nested_type(i)); } for (int i = 0; i < descriptor->enum_type_count(); ++i) { enums_[i] = std::make_unique<EnumGenerator>(descriptor->enum_type(i)); } } MessageGenerator::~MessageGenerator() {} namespace { // For the strange proto:define-group. const std::string FieldKeywordLabel(const FieldDescriptor::Label label) { switch (label) { case FieldDescriptor::LABEL_OPTIONAL: return ":optional"; case FieldDescriptor::LABEL_REQUIRED: return ":required"; case FieldDescriptor::LABEL_REPEATED: return ":repeated"; default: GOOGLE_LOG(FATAL) << "Unknown field label: " << label; return ":error"; } } } // namespace void MessageGenerator::GenerateSource(io::Printer* printer, const std::string& lisp_name, const int tag, const FieldDescriptor::Label label) { // Print group or message // Since we know the immediate next thing we emit is a newline we don't // need the extra space. const bool group = tag >= 0; printer->Print("\n"); printer->Print((group ? "(proto:define-group $name$" : "(proto:define-message $name$"), "name", lisp_name); printer->Annotate("name", descriptor_); printer->Indent(); // Message options. printer->Indent(); printer->Print("\n(:conc-name \"\""); if (group) { printer->Print("\n :index $tag$", "tag", StrCat(tag)); printer->Print("\n :label $label$", "label", FieldKeywordLabel(label)); } if (CamelIsSpitting(descriptor_->name())) { printer->Print("\n :name \"$name$\"", "name", descriptor_->name()); printer->Annotate("name", descriptor_->name()); } if (descriptor_->options().HasExtension(lisp_alias)) { // The symbol most likely doesn't exist yet. Use double-colon to create // the symbol if doesn't exist yet. const std::string& lasn = ToLispAliasSymbolName(descriptor_->options().GetExtension(lisp_alias)); printer->Print("\n :alias-for $for$", "for", lasn); printer->Annotate("for", lasn); } // END message options. printer->Print(")"); printer->Outdent(); if (descriptor_->enum_type_count() > 0) { printer->Print("\n;; Nested enums."); for (int i = 0; i < descriptor_->enum_type_count(); ++i) { enums_[i]->Generate(printer); } } if (descriptor_->nested_type_count() > 0) { printer->Print("\n;; Nested messages."); int printed = 0; for (int n = 0; n < descriptor_->nested_type_count(); ++n) { // Strange handling of group fields. // Remove all groups. Those should be generated with the fields. bool skip = false; for (int f = 0; f < descriptor_->field_count(); ++f) { if (descriptor_->field(f)->type() == FieldDescriptor::TYPE_GROUP && descriptor_->field(f)->message_type() == descriptor_->nested_type(n)) { skip = true; break; } } if (!skip) { nested_[n]->Generate(printer); ++printed; } } if (!printed) printer->Print(".. are all groups.\n"); } if (descriptor_->field_count() > 0) { printer->Print("\n;; Fields."); std::unordered_set<int> seen_fields; if (descriptor_->oneof_decl_count() > 0) { for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { const OneofDescriptor* oneof = descriptor_->oneof_decl(i); printer->Print("\n(proto:define-oneof $name$", "name", ToLispName(oneof->name())); printer->Indent(); for (int j = 0; j < oneof->field_count(); ++j) { const FieldDescriptor* field = oneof->field(j); seen_fields.insert(field->index()); if (field->type() == FieldDescriptor::TYPE_GROUP) { // Strange way of handling group fields. MessageGenerator group(field->message_type()); group.GenerateSource(printer, ToLispName(field->message_type()->name()), field->number(), field->label()); } else { GenerateField(printer, field); } } printer->Print(")"); printer->Outdent(); } } for (int i = 0; i < descriptor_->field_count(); ++i) { const FieldDescriptor* field = descriptor_->field(i); if (seen_fields.find(field->index()) == seen_fields.end()) { if (field->type() == FieldDescriptor::TYPE_GROUP) { // Strange way of handling group fields. MessageGenerator group(field->message_type()); group.GenerateSource(printer, ToLispName(field->message_type()->name()), field->number(), field->label()); } else { GenerateField(printer, field); } } } } if (descriptor_->extension_count() > 0) { printer->Print("\n;; Extensions."); for (int i = 0; i < descriptor_->extension_count(); ++i) { GenerateExtension( printer, descriptor_->extension(i), descriptor_->file()); } } if (descriptor_->extension_range_count() > 0) { printer->Print("\n;; Extension ranges."); for (int i = 0; i < descriptor_->extension_range_count(); ++i) { const Descriptor::ExtensionRange* range = descriptor_->extension_range(i); printer->Print( "\n(proto:define-extension $start$ $end$)", "start", StrCat(range->start), // The end is inclusive in cl_protobufs. // For some reason, the extension number is generated as // 0x7ffffffe when specified as 'max', but the max must be // (2^29 - 1). "end", StrCat(std::min(kMaxExtensionNumber, range->end - 1))); } } printer->Print(")"); printer->Outdent(); } void MessageGenerator::Generate(io::Printer* printer) { GenerateSource(printer, lisp_name_, -1, FieldDescriptor::MAX_LABEL); } void MessageGenerator::AddExports(std::vector<std::string>* exports) { for (int n = 0; n < descriptor_->nested_type_count(); ++n) { // Strange handling of group fields. // Remove all groups. Those should be exported with the fields. // The field accessors of a group are not exported because // we're skipping the whole group. Fix it. bool skip = false; for (int f = 0; f < descriptor_->field_count(); ++f) { if (descriptor_->field(f)->type() == FieldDescriptor::TYPE_GROUP && descriptor_->field(f)->message_type() == descriptor_->nested_type(n)) { skip = true; break; } } if (!skip) { nested_[n]->AddExports(exports); } } for (int i = 0; i < descriptor_->enum_type_count(); ++i) { enums_[i]->AddExports(exports); } exports->push_back(lisp_name_); for (int i = 0; i < descriptor_->field_count(); ++i) { const FieldDescriptor* field = descriptor_->field(i); // For groups, the message type name must be used for the correct lisp name. // E.g. when a group is named `SomeGroup`, the field name is `somegroup`, // but we want `some-group`. std::string name = field->type() == FieldDescriptor::TYPE_GROUP ? ToLispName(field->message_type()->name()) : FieldLispName(field); exports->push_back(name); } for (int i = 0; i < descriptor_->extension_count(); ++i) { exports->push_back(FieldLispName(descriptor_->extension(i))); } } void MessageGenerator::AddPackages(std::set<std::string>* packages) { if (descriptor_->options().HasExtension(lisp_alias)) { const std::string alias = descriptor_->options().GetExtension(lisp_alias); const size_t colon = alias.find(':'); if (colon != std::string::npos && colon > 0) { packages->insert(ToUpper(alias.substr(0, colon))); } } for (int i = 0; i < descriptor_->nested_type_count(); ++i) { nested_[i]->AddPackages(packages); } } } // namespace cl_protobufs } // namespace protobuf } // namespace google <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CLAWPACK_FORT_H #define CLAWPACK_FORT_H /* this header file must come first */ #include "fclaw2d_defs.H" #include "fclaw2d_convenience.h" #include "forestclaw2d.h" #include "amr_options.h" #include "fclaw2d_transform.h" #include <iostream> #include <cstdlib> #include <vector> #ifdef __cplusplus extern "C" { /* Beginning of extern "C" */ #if 0 } #endif #endif void set_common_levels_(const int& maxlevel,const int& a_level, const int& refratio); /* ---------------------------------------------------------------------------------- Initialization routines ---------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------ */ /* This is here for now; may be taken out once I figure out Carsten's 'mapping context' idea */ void set_maptype_cart_(); void set_maptype_pillowsphere_(); void set_maptype_hemisphere_(); void set_maptype_disk_(); void set_maptype_cubedsphere_(); void set_map_defaults_(); int isflat_(); int iscart_(); int isdisk_(); int ishemisphere_(); int issphere_(); int ispillowsphere_(); int iscubedsphere_(); /* ------------------------------------------------------------------------ */ void set_block_(const int * a_blockno); void set_context_(fclaw2d_map_context_t** a_context); void fclaw2d_mapc2m_(fclaw2d_map_context_t** cont, int *blockno, const double *xc, const double *yc, double *xp, double *yp, double *zp); void average_face_ghost_mapped_(const int& mx, const int& my, const int& mbc, const int& meqn, double qfine[],double qcoarse[], const double areacoarse[], const double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid); void mb_average_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qfine[],double qcoarse[], const double areacoarse[], const double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, fclaw2d_transform_data_t** transform_cptr); void fixcapaq2_(const int& mx, const int& my, const int& mbc, const int& meqn, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); /* ---------------------------------------------------------------------------------- Internal boundary conditions ---------------------------------------------------------------------------------- */ void exchange_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qneighbor[], const int& a_idir, fclaw2d_transform_data_t** transform_cptr); void average_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qcoarse[],double qfine[], double areacoarse[], double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, const int& manifold, fclaw2d_transform_data_t** transform_cptr); void interpolate_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qcoarse[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, fclaw2d_transform_data_t** transform_cptr); void exchange_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double this_q[],double neighbor_q[], const int& a_corner,fclaw2d_transform_data_t** transform_cptr); void average_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& a_refratio, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& manifold, const int& a_corner, fclaw2d_transform_data_t** transform_cptr); void interpolate_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& a_refratio, double this_q[], double neighbor_q[], const int& a_corner, fclaw2d_transform_data_t** transform_cptr); void mb_exchange_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& iface, const int& iblock); void mb_exchange_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& icorner, int bdry[], const int& iblock); void mb_exchange_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& icorner, const int& iblock); void mb_interpolate_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qcoarse[], const int& idir, const int& iside, const int& num_neighbors,const int& refratio, const int& igrid); void mb_average_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& refratio, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& icorner, int intersects_block[]); // Averaging at block boundaries between coarse and fine grids. void mb_average_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn,const int& refratio, double qcoarse[], double qfine[],double areacoarse[], double areafine[], const int& a_coarse_corner, const int& blockno); void mb_interpolate_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& refratio, double qcoarse[], double qfine[], const int& icorner, int intersects_block[]); // Averaging at block boundaries between coarse and fine grids. void mb_interpolate_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn,const int& refratio, double qcoarse[], double qfine[],const int& a_coarse_corner, const int& blockno); /* ---------------------------------------------------------------------------------- Physical boundary conditions ---------------------------------------------------------------------------------- */ void set_phys_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double q[],const int& icorner, const double &t, const double& dt, const int mthbc[]); void exchange_phys_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qneighbor[], const int& icorner, const int& iside); /* ---------------------------------------------------------------------------------- Tagging for refinement/coarsening ---------------------------------------------------------------------------------- */ void interpolate_to_fine_patch_(const int& mx,const int& my,const int& mbc, const int& meqn, double qcoarse[], double qfine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); void average_to_coarse_patch_(const int& mx,const int& my,const int& mbc, const int& meqn, double qcoarse[],double qfine[], double areacoarse[],double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid, const int& manifold); #if 0 void average_to_coarse_mapped_(const int& mx,const int& my, const int& mbc, const int& meqn, double qcoarse[], double qfine[], const double areacoarse[], const double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); #endif /* ---------------------------------------------------------------------------------- Mapped grids area : 1 float xp,yp,zp, xd,yd zp : 6 floats xnormals, ynormals : 6 floats ytangents, ytangent : 6 floats edgelengths : 2 floats surfnormals : 3 floats curvature : 1 float ----------------------------- total : 25 floats (in 2d!!) ---------------------------------------------------------------------------------- */ void setup_mesh_(const int& mx, const int& my, const int& mbc, const double& xlower, const double& ylower, const double& dx, const double& dy, double xp[], double yp[], double zp[], double xd[], double yd[], double zd[]); void compute_area_(const int& mx, const int& my, const int& mbc, const double& m_dx, const double& m_dy,const double& m_xlower, const double& m_ylower, double area[], const int& level, const int& maxlevel, const int& refratio); void compute_normals_(const int& mx, const int& my, const int& mbc, double xp[], double yp[], double zp[], double xd[], double yd[], double zd[], double xnormals[],double ynormals[]); void compute_tangents_(const int& mx, const int& my, const int& mbc, double xd[], double yd[], double zd[], double xtangents[],double ytangents[],double edge_lengths[]); void compute_surf_normals_(const int& mx, const int& my, const int& mbc, double xnormals[],double ynormals[],double edge_lengths[], double curvature[], double surfnormals[], double area[]); /* ---------------------------------------------------------------------------------- Output and diagnostics ---------------------------------------------------------------------------------- */ void write_tfile_(const int &iframe,const double &time,const int &meqn, const int &ngrids, const int& maux); void new_qfile_(const int &iframe); void write_qfile_(const int& maxmx, const int& maxmy, const int& meqn, const int& mbc, const int& mx, const int& my, const double& xlower, const double& ylower, const double& dx, const double& dy, double q[], const int& iframe, const int& patch_idx,const int& level,const int& blockno); void compute_sum_(const int& mx, const int& my, const int& mbc, const int& meqn, const double& dx, const double& dy, double q[], double& sum); void interpdata_(const int& m,double qlast[],double qcurr[], double qinterp[], const double& alpha); int get_debug_flag_(); void set_debug_flag_(const int& iflag); void set_debug_on_(); void set_debug_off_(); fclaw_bool debug_is_on_(); fclaw_bool debug_is_off_(); void set_debug_info_(const int& block_idx, const int& patch_idx, const int& level); void reset_debug_info_(); int get_block_idx_(); int get_patch_idx_(); int get_level_(); void debug_here_(const int& n, const char str[]); void dump_patch_(const int& mx, const int& my, const int& m_mbc, const int& meqn, const int& mq, double q[]); #ifdef __cplusplus #if 0 { #endif } /* end of extern "C" */ #endif class Box { public: Box(); Box(const int ll[], const int ur[]); Box(const Box& a_box); int smallEnd(int idir) const; int bigEnd(int idir) const; private: int m_ll[2]; int m_ur[2]; }; class FArrayBox { public: FArrayBox(); FArrayBox(const FArrayBox& A); ~FArrayBox(); void define(const Box& a_box, int a_fields); double* dataPtr(); Box box(); int fields(); int size(); void operator=(const FArrayBox& fbox); void copyToMemory(double *data); void copyFromMemory(double *data); private: double *m_data; int m_size; Box m_box; int m_fields; void set_dataPtr(int size); }; #endif <commit_msg>Got rid of headers for query functions; these are now in fclaw2d_map_qquery.h<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CLAWPACK_FORT_H #define CLAWPACK_FORT_H /* this header file must come first */ #include "fclaw2d_defs.H" #include "fclaw2d_convenience.h" #include "forestclaw2d.h" #include "amr_options.h" #include "fclaw2d_transform.h" #include <iostream> #include <cstdlib> #include <vector> #ifdef __cplusplus extern "C" { /* Beginning of extern "C" */ #if 0 } #endif #endif void set_common_levels_(const int& maxlevel,const int& a_level, const int& refratio); /* ---------------------------------------------------------------------------------- Initialization routines ---------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------ */ /* This is here for now; may be taken out once I figure out Carsten's 'mapping context' idea */ /* void set_maptype_cart_(); void set_maptype_pillowsphere_(); void set_maptype_hemisphere_(); void set_maptype_disk_(); void set_maptype_cubedsphere_(); void set_map_defaults_(); */ #define ISPILLOWSPHERE FCLAW_F77_FUNC_(ispillowsphere,ISPILLOWSPHERE) int ISPILLOWSPHERE(); #define IS_CUBEDSPHERE FCLAW_F77_FUNC_(iscubedsphere,ISCUBEDSPHERE) int ISCUBEDSPHERE(); #define ISPILLOWDISK FCLAW_F77_FUNC_(ispillowdisk,ISPILLOWDISK) int ISPILLOWDISK(); #define ISFLAT FCLAW_F77_FUNC_(isflat,ISFLAT) int ISFLAT(); #define ISSPHERE FCLAW_F77_FUNC_(issphere,ISSPHERE) int ISSPHERE(); /* ------------------------------------------------------------------------ */ void set_block_(const int * a_blockno); void set_context_(fclaw2d_map_context_t** a_context); void fclaw2d_mapc2m_(fclaw2d_map_context_t** cont, int *blockno, const double *xc, const double *yc, double *xp, double *yp, double *zp); void average_face_ghost_mapped_(const int& mx, const int& my, const int& mbc, const int& meqn, double qfine[],double qcoarse[], const double areacoarse[], const double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid); void mb_average_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qfine[],double qcoarse[], const double areacoarse[], const double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, fclaw2d_transform_data_t** transform_cptr); void fixcapaq2_(const int& mx, const int& my, const int& mbc, const int& meqn, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); /* ---------------------------------------------------------------------------------- Internal boundary conditions ---------------------------------------------------------------------------------- */ void exchange_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qneighbor[], const int& a_idir, fclaw2d_transform_data_t** transform_cptr); void average_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qcoarse[],double qfine[], double areacoarse[], double areafine[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, const int& manifold, fclaw2d_transform_data_t** transform_cptr); void interpolate_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qcoarse[], const int& idir, const int& iside, const int& num_neighbors, const int& refratio, const int& igrid, fclaw2d_transform_data_t** transform_cptr); void exchange_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double this_q[],double neighbor_q[], const int& a_corner,fclaw2d_transform_data_t** transform_cptr); void average_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& a_refratio, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& manifold, const int& a_corner, fclaw2d_transform_data_t** transform_cptr); void interpolate_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& a_refratio, double this_q[], double neighbor_q[], const int& a_corner, fclaw2d_transform_data_t** transform_cptr); void mb_exchange_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& iface, const int& iblock); void mb_exchange_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& icorner, int bdry[], const int& iblock); void mb_exchange_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[], double qneighbor[], const int& icorner, const int& iblock); void mb_interpolate_face_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qcoarse[], const int& idir, const int& iside, const int& num_neighbors,const int& refratio, const int& igrid); void mb_average_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& refratio, double qcoarse[], double qfine[], double areacoarse[], double areafine[], const int& icorner, int intersects_block[]); // Averaging at block boundaries between coarse and fine grids. void mb_average_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn,const int& refratio, double qcoarse[], double qfine[],double areacoarse[], double areafine[], const int& a_coarse_corner, const int& blockno); void mb_interpolate_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, const int& refratio, double qcoarse[], double qfine[], const int& icorner, int intersects_block[]); // Averaging at block boundaries between coarse and fine grids. void mb_interpolate_block_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn,const int& refratio, double qcoarse[], double qfine[],const int& a_coarse_corner, const int& blockno); /* ---------------------------------------------------------------------------------- Physical boundary conditions ---------------------------------------------------------------------------------- */ void set_phys_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double q[],const int& icorner, const double &t, const double& dt, const int mthbc[]); void exchange_phys_corner_ghost_(const int& mx, const int& my, const int& mbc, const int& meqn, double qthis[],double qneighbor[], const int& icorner, const int& iside); /* ---------------------------------------------------------------------------------- Tagging for refinement/coarsening ---------------------------------------------------------------------------------- */ void interpolate_to_fine_patch_(const int& mx,const int& my,const int& mbc, const int& meqn, double qcoarse[], double qfine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); void average_to_coarse_patch_(const int& mx,const int& my,const int& mbc, const int& meqn, double qcoarse[],double qfine[], double areacoarse[],double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid, const int& manifold); #if 0 void average_to_coarse_mapped_(const int& mx,const int& my, const int& mbc, const int& meqn, double qcoarse[], double qfine[], const double areacoarse[], const double areafine[], const int& p4est_refineFactor, const int& refratio, const int& igrid); #endif /* ---------------------------------------------------------------------------------- Mapped grids area : 1 float xp,yp,zp, xd,yd zp : 6 floats xnormals, ynormals : 6 floats ytangents, ytangent : 6 floats edgelengths : 2 floats surfnormals : 3 floats curvature : 1 float ----------------------------- total : 25 floats (in 2d!!) ---------------------------------------------------------------------------------- */ void setup_mesh_(const int& mx, const int& my, const int& mbc, const double& xlower, const double& ylower, const double& dx, const double& dy, double xp[], double yp[], double zp[], double xd[], double yd[], double zd[]); void compute_area_(const int& mx, const int& my, const int& mbc, const double& m_dx, const double& m_dy,const double& m_xlower, const double& m_ylower, double area[], const int& level, const int& maxlevel, const int& refratio); void compute_normals_(const int& mx, const int& my, const int& mbc, double xp[], double yp[], double zp[], double xd[], double yd[], double zd[], double xnormals[],double ynormals[]); void compute_tangents_(const int& mx, const int& my, const int& mbc, double xd[], double yd[], double zd[], double xtangents[],double ytangents[],double edge_lengths[]); void compute_surf_normals_(const int& mx, const int& my, const int& mbc, double xnormals[],double ynormals[],double edge_lengths[], double curvature[], double surfnormals[], double area[]); /* ---------------------------------------------------------------------------------- Output and diagnostics ---------------------------------------------------------------------------------- */ void write_tfile_(const int &iframe,const double &time,const int &meqn, const int &ngrids, const int& maux); void new_qfile_(const int &iframe); void write_qfile_(const int& maxmx, const int& maxmy, const int& meqn, const int& mbc, const int& mx, const int& my, const double& xlower, const double& ylower, const double& dx, const double& dy, double q[], const int& iframe, const int& patch_idx,const int& level,const int& blockno); void compute_sum_(const int& mx, const int& my, const int& mbc, const int& meqn, const double& dx, const double& dy, double q[], double& sum); void interpdata_(const int& m,double qlast[],double qcurr[], double qinterp[], const double& alpha); int get_debug_flag_(); void set_debug_flag_(const int& iflag); void set_debug_on_(); void set_debug_off_(); fclaw_bool debug_is_on_(); fclaw_bool debug_is_off_(); void set_debug_info_(const int& block_idx, const int& patch_idx, const int& level); void reset_debug_info_(); int get_block_idx_(); int get_patch_idx_(); int get_level_(); void debug_here_(const int& n, const char str[]); void dump_patch_(const int& mx, const int& my, const int& m_mbc, const int& meqn, const int& mq, double q[]); #ifdef __cplusplus #if 0 { #endif } /* end of extern "C" */ #endif class Box { public: Box(); Box(const int ll[], const int ur[]); Box(const Box& a_box); int smallEnd(int idir) const; int bigEnd(int idir) const; private: int m_ll[2]; int m_ur[2]; }; class FArrayBox { public: FArrayBox(); FArrayBox(const FArrayBox& A); ~FArrayBox(); void define(const Box& a_box, int a_fields); double* dataPtr(); Box box(); int fields(); int size(); void operator=(const FArrayBox& fbox); void copyToMemory(double *data); void copyFromMemory(double *data); private: double *m_data; int m_size; Box m_box; int m_fields; void set_dataPtr(int size); }; #endif <|endoftext|>
<commit_before>// Copyright 2019 The Marl Authors // // 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 // // https://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 "marl/blockingcall.h" #include "marl/defer.h" #include "marl_test.h" #include <mutex> TEST_P(WithBoundScheduler, BlockingCall) { auto mutex = std::make_shared<std::mutex>(); mutex->lock(); marl::WaitGroup wg(100); for (int i = 0; i < 100; i++) { marl::schedule([=] { defer(wg.done()); marl::blocking_call([=] { mutex->lock(); defer(mutex->unlock()); }); }); } marl::schedule([=] { mutex->unlock(); }); wg.wait(); } <commit_msg>Fix TSAN issue with BlockingCall test.<commit_after>// Copyright 2019 The Marl Authors // // 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 // // https://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 "marl/blockingcall.h" #include "marl/defer.h" #include "marl_test.h" #include <mutex> TEST_P(WithBoundScheduler, BlockingCall) { auto mutex = std::make_shared<std::mutex>(); mutex->lock(); marl::WaitGroup wg(100); for (int i = 0; i < 100; i++) { marl::schedule([=] { defer(wg.done()); marl::blocking_call([=] { mutex->lock(); defer(mutex->unlock()); }); }); } mutex->unlock(); wg.wait(); } <|endoftext|>
<commit_before>// Copyright 2018 Global Phasing Ltd. #include <complex> // for symmetrize_min and symmetrize_max bool operator<(const std::complex<float>& a, const std::complex<float>& b) { return std::norm(a) < std::norm(b); } bool operator>(const std::complex<float>& a, const std::complex<float>& b) { return std::norm(a) > std::norm(b); } #include "gemmi/grid.hpp" #include "gemmi/floodfill.hpp" // for flood_fill_above #include "gemmi/solmask.hpp" // for SolventMasker, mask_points_in_constant_radius #include "gemmi/blob.hpp" // for Blob, find_blobs_by_flood_fill #include "tostr.hpp" #include "common.h" #include <pybind11/complex.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> namespace py = pybind11; using namespace gemmi; template<typename T> py::class_<GridBase<T>, GridMeta> add_grid_base(py::module& m, const char* name) { using GrBase = GridBase<T>; using GrPoint = typename GridBase<T>::Point; py::class_<GrBase, GridMeta> grid_base(m, name, py::buffer_protocol()); py::class_<GrPoint>(grid_base, "Point") .def_readonly("u", &GrPoint::u) .def_readonly("v", &GrPoint::v) .def_readonly("w", &GrPoint::w) .def_property("value", [](const GrPoint& self) { return *self.value; }, [](GrPoint& self, T x) { *self.value = x; }) .def("__repr__", [=](const GrPoint& self) { return tostr("<gemmi.", name, ".Point (", self.u, ", ", self.v, ", ", self.w, ") -> ", +*self.value, '>'); }); grid_base .def_buffer([](GrBase& g) { return py::buffer_info(g.data.data(), {g.nu, g.nv, g.nw}, // dimensions {sizeof(T), // strides sizeof(T) * g.nu, sizeof(T) * g.nu * g.nv}); }) .def_property_readonly("array", [](const GrBase& g) { return py::array_t<T>({g.nu, g.nv, g.nw}, {sizeof(T), sizeof(T) * g.nu, sizeof(T) * g.nu * g.nv}, g.data.data(), py::cast(g)); }, py::return_value_policy::reference_internal) .def("point_to_index", &GrBase::point_to_index) .def("index_to_point", &GrBase::index_to_point) .def("fill", &GrBase::fill, py::arg("value")) .def("sum", &GrBase::sum) .def("__iter__", [](GrBase& self) { return py::make_iterator(self); }, py::keep_alive<0, 1>()) ; return grid_base; } template<typename T> py::class_<Grid<T>, GridBase<T>> add_grid(py::module& m, const std::string& name) { using Gr = Grid<T>; using GrPoint = typename GridBase<T>::Point; using Masked = MaskedGrid<T>; py::class_<Gr, GridBase<T>> grid(m, name.c_str()); py::class_<Masked> masked_grid (m, ("Masked" + name).c_str()); grid .def(py::init<>()) .def(py::init([](int nx, int ny, int nz) { Gr* grid = new Gr(); grid->set_size(nx, ny, nz); return grid; }), py::arg("nx"), py::arg("ny"), py::arg("nz")) .def(py::init([](py::array_t<T> arr, const UnitCell *cell, const SpaceGroup* sg) { auto r = arr.template unchecked<3>(); Gr* grid = new Gr(); grid->set_size((int)r.shape(0), (int)r.shape(1), (int)r.shape(2)); for (int k = 0; k < r.shape(2); ++k) for (int j = 0; j < r.shape(1); ++j) for (int i = 0; i < r.shape(0); ++i) grid->data[grid->index_q(i, j, k)] = r(i, j, k); if (cell) grid->set_unit_cell(*cell); if (sg) grid->spacegroup = sg; return grid; }), py::arg().noconvert(), py::arg("cell")=nullptr, py::arg("spacegroup")=nullptr) .def_property_readonly("spacing", [](const Gr& self) { return py::make_tuple(self.spacing[0], self.spacing[1], self.spacing[2]); }) .def("set_size", &Gr::set_size) .def("get_value", &Gr::get_value) .def("set_value", &Gr::set_value) .def("get_point", &Gr::get_point) .def("get_nearest_point", (GrPoint (Gr::*)(const Position&)) &Gr::get_nearest_point) .def("point_to_fractional", &Gr::point_to_fractional) .def("point_to_position", &Gr::point_to_position) .def("change_values", &Gr::change_values, py::arg("old_value"), py::arg("new_value")) .def("interpolate_value", (T (Gr::*)(const Fractional&) const) &Gr::interpolate_value) .def("interpolate_value", (T (Gr::*)(const Position&) const) &Gr::interpolate_value) .def("interpolate_values", [](const Gr& self, py::array_t<T> arr, const Transform& tr, bool cubic) { auto r = arr.template mutable_unchecked<3>(); for (int i = 0; i < r.shape(0); ++i) for (int j = 0; j < r.shape(1); ++j) for (int k = 0; k < r.shape(2); ++k) { Position pos(tr.apply(Vec3(i, j, k))); Fractional fpos = self.unit_cell.fractionalize(pos); if (cubic) r(i, j, k) = (T) self.tricubic_interpolation(fpos); else r(i, j, k) = self.interpolate_value(fpos); } }, py::arg().noconvert(), py::arg(), py::arg("cubic")=false) .def("tricubic_interpolation", (double (Gr::*)(const Fractional&) const) &Gr::tricubic_interpolation) .def("tricubic_interpolation", (double (Gr::*)(const Position&) const) &Gr::tricubic_interpolation) .def("tricubic_interpolation_der", (std::array<double,4> (Gr::*)(const Fractional&) const) &Gr::tricubic_interpolation_der) .def("copy_metadata_from", &Gr::copy_metadata_from) .def("setup_from", &Gr::template setup_from<Structure>, py::arg("st"), py::arg("spacing")) .def("set_unit_cell", (void (Gr::*)(const UnitCell&)) &Gr::set_unit_cell) .def("set_points_around", &Gr::set_points_around, py::arg("position"), py::arg("radius"), py::arg("value"), py::arg("use_pbc")=true) .def("symmetrize_min", &Gr::symmetrize_min) .def("symmetrize_max", &Gr::symmetrize_max) .def("symmetrize_abs_max", &Gr::symmetrize_abs_max) .def("symmetrize_sum", &Gr::symmetrize_sum) .def("masked_asu", &Gr::masked_asu, py::keep_alive<0, 1>()) .def("mask_points_in_constant_radius", &mask_points_in_constant_radius<T>, py::arg("model"), py::arg("radius"), py::arg("value")) .def("get_subarray", [](const Gr& self, std::array<int,3> start, std::array<int,3> shape) { py::array_t<T> arr({shape[0], shape[1], shape[2]}, {sizeof(T), sizeof(T)*shape[0], sizeof(T)*shape[0]*shape[1]}); self.get_subarray((T*) arr.request().ptr, start, shape); return arr; }, py::arg("start"), py::arg("shape")) .def("set_subarray", [](Gr& self, py::array_t<T, py::array::f_style | py::array::forcecast> arr, std::array<int,3> start) { self.set_subarray((T*) arr.request().ptr, start, {(int)arr.shape(0), (int)arr.shape(1), (int)arr.shape(2)}); }, py::arg("arr"), py::arg("start")) .def("clone", [](const Gr& self) { return new Gr(self); }) .def("__repr__", [=](const Gr& self) { return tostr("<gemmi.", name, '(', self.nu, ", ", self.nv, ", ", self.nw, ")>"); }); masked_grid .def_readonly("grid", &Masked::grid, py::return_value_policy::reference) .def_property_readonly("mask_array", [](const Masked& self) { const Gr& gr = *self.grid; py::array::ShapeContainer shape({gr.nu, gr.nv, gr.nw}); py::array::StridesContainer strides({gr.nv * gr.nw, gr.nw, 1}); return py::array_t<std::int8_t>(shape, strides, self.mask.data(), py::cast(self)); }, py::return_value_policy::reference_internal) .def("__iter__", [](Masked& self) { return py::make_iterator(self); }, py::keep_alive<0, 1>()) ; return grid; } void add_grid(py::module& m) { py::enum_<AxisOrder>(m, "AxisOrder") .value("Unknown", AxisOrder::Unknown) .value("XYZ", AxisOrder::XYZ) .value("ZYX", AxisOrder::ZYX); py::class_<GridMeta>(m, "GridMeta") .def_readwrite("spacegroup", &GridMeta::spacegroup) .def_readwrite("unit_cell", &GridMeta::unit_cell) .def_readonly("nu", &GridMeta::nu, "size in the first (fastest-changing) dim") .def_readonly("nv", &GridMeta::nv, "size in the second dimension") .def_readonly("nw", &GridMeta::nw, "size in the third (slowest-changing) dim") .def_readonly("axis_order", &GridMeta::axis_order) .def_property_readonly("point_count", &GridMeta::point_count) .def("get_position", &GridMeta::get_position) .def("get_fractional", &GridMeta::get_fractional) .def_property_readonly("shape", [](const GridMeta& self) { return py::make_tuple(self.nu, self.nv, self.nw); }); add_grid_base<int8_t>(m, "Int8GridBase"); add_grid<int8_t>(m, "Int8Grid"); add_grid_base<float>(m, "FloatGridBase") .def("calculate_correlation", &calculate_correlation<float>) ; add_grid<float>(m, "FloatGrid") .def("normalize", &normalize_grid<float>) ; add_grid_base<std::complex<float>>(m, "ComplexGridBase"); // from solmask.hpp py::enum_<AtomicRadiiSet>(m, "AtomicRadiiSet") .value("VanDerWaals", AtomicRadiiSet::VanDerWaals) .value("Cctbx", AtomicRadiiSet::Cctbx) .value("Refmac", AtomicRadiiSet::Refmac) .value("Constant", AtomicRadiiSet::Constant); py::class_<SolventMasker>(m, "SolventMasker") .def(py::init<AtomicRadiiSet, double>(), py::arg("choice"), py::arg("constant_r")=0.) .def_readwrite("atomic_radii_set", &SolventMasker::atomic_radii_set) .def_readwrite("rprobe", &SolventMasker::rprobe) .def_readwrite("rshrink", &SolventMasker::rshrink) .def_readwrite("island_min_volume", &SolventMasker::island_min_volume) .def_readwrite("constant_r", &SolventMasker::constant_r) .def("set_radii", &SolventMasker::set_radii, py::arg("choice"), py::arg("constant_r")=0.) .def("put_mask_on_int8_grid", &SolventMasker::put_mask_on_grid<int8_t>) .def("put_mask_on_float_grid", &SolventMasker::put_mask_on_grid<float>) .def("set_to_zero", &SolventMasker::set_to_zero) ; m.def("interpolate_grid_of_aligned_model2", &interpolate_grid_of_aligned_model2<float>, py::arg("dest"), py::arg("src"), py::arg("tr"), py::arg("dest_model"), py::arg("radius")); // from blob.hpp py::class_<Blob>(m, "Blob") .def_readonly("volume", &Blob::volume) .def_readonly("score", &Blob::score) .def_readonly("peak_value", &Blob::peak_value) .def_readonly("centroid", &Blob::centroid) .def_readonly("peak_pos", &Blob::peak_pos) ; m.def("find_blobs_by_flood_fill", [](const Grid<float>& grid, double cutoff, double min_volume, double min_score, double min_peak, bool negate) { BlobCriteria crit; crit.cutoff = cutoff; crit.min_volume = min_volume; crit.min_score = min_score; crit.min_peak = min_peak; return find_blobs_by_flood_fill(grid, crit, negate); }, py::arg("grid"), py::arg("cutoff"), py::arg("min_volume")=10., py::arg("min_score")=15., py::arg("min_peak")=0., py::arg("negate")=false); // from floodfill.hpp m.def("flood_fill_above", &flood_fill_above, py::arg("grid"), py::arg("seeds"), py::arg("threshold"), py::arg("negate")=false); } <commit_msg>python: remove interpolation functions from Int8Grid<commit_after>// Copyright 2018 Global Phasing Ltd. #include <complex> // for symmetrize_min and symmetrize_max bool operator<(const std::complex<float>& a, const std::complex<float>& b) { return std::norm(a) < std::norm(b); } bool operator>(const std::complex<float>& a, const std::complex<float>& b) { return std::norm(a) > std::norm(b); } #include "gemmi/grid.hpp" #include "gemmi/floodfill.hpp" // for flood_fill_above #include "gemmi/solmask.hpp" // for SolventMasker, mask_points_in_constant_radius #include "gemmi/blob.hpp" // for Blob, find_blobs_by_flood_fill #include "tostr.hpp" #include "common.h" #include <pybind11/complex.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> namespace py = pybind11; using namespace gemmi; template<typename T> py::class_<GridBase<T>, GridMeta> add_grid_base(py::module& m, const char* name) { using GrBase = GridBase<T>; using GrPoint = typename GridBase<T>::Point; py::class_<GrBase, GridMeta> grid_base(m, name, py::buffer_protocol()); py::class_<GrPoint>(grid_base, "Point") .def_readonly("u", &GrPoint::u) .def_readonly("v", &GrPoint::v) .def_readonly("w", &GrPoint::w) .def_property("value", [](const GrPoint& self) { return *self.value; }, [](GrPoint& self, T x) { *self.value = x; }) .def("__repr__", [=](const GrPoint& self) { return tostr("<gemmi.", name, ".Point (", self.u, ", ", self.v, ", ", self.w, ") -> ", +*self.value, '>'); }); grid_base .def_buffer([](GrBase& g) { return py::buffer_info(g.data.data(), {g.nu, g.nv, g.nw}, // dimensions {sizeof(T), // strides sizeof(T) * g.nu, sizeof(T) * g.nu * g.nv}); }) .def_property_readonly("array", [](const GrBase& g) { return py::array_t<T>({g.nu, g.nv, g.nw}, {sizeof(T), sizeof(T) * g.nu, sizeof(T) * g.nu * g.nv}, g.data.data(), py::cast(g)); }, py::return_value_policy::reference_internal) .def("point_to_index", &GrBase::point_to_index) .def("index_to_point", &GrBase::index_to_point) .def("fill", &GrBase::fill, py::arg("value")) .def("sum", &GrBase::sum) .def("__iter__", [](GrBase& self) { return py::make_iterator(self); }, py::keep_alive<0, 1>()) ; return grid_base; } template<typename T> py::class_<Grid<T>, GridBase<T>> add_grid_common(py::module& m, const std::string& name) { using Gr = Grid<T>; using GrPoint = typename GridBase<T>::Point; using Masked = MaskedGrid<T>; py::class_<Gr, GridBase<T>> grid(m, name.c_str()); py::class_<Masked> masked_grid (m, ("Masked" + name).c_str()); grid .def(py::init<>()) .def(py::init([](int nx, int ny, int nz) { Gr* grid = new Gr(); grid->set_size(nx, ny, nz); return grid; }), py::arg("nx"), py::arg("ny"), py::arg("nz")) .def(py::init([](py::array_t<T> arr, const UnitCell *cell, const SpaceGroup* sg) { auto r = arr.template unchecked<3>(); Gr* grid = new Gr(); grid->set_size((int)r.shape(0), (int)r.shape(1), (int)r.shape(2)); for (int k = 0; k < r.shape(2); ++k) for (int j = 0; j < r.shape(1); ++j) for (int i = 0; i < r.shape(0); ++i) grid->data[grid->index_q(i, j, k)] = r(i, j, k); if (cell) grid->set_unit_cell(*cell); if (sg) grid->spacegroup = sg; return grid; }), py::arg().noconvert(), py::arg("cell")=nullptr, py::arg("spacegroup")=nullptr) .def_property_readonly("spacing", [](const Gr& self) { return py::make_tuple(self.spacing[0], self.spacing[1], self.spacing[2]); }) .def("set_size", &Gr::set_size) .def("get_value", &Gr::get_value) .def("set_value", &Gr::set_value) .def("get_point", &Gr::get_point) .def("get_nearest_point", (GrPoint (Gr::*)(const Position&)) &Gr::get_nearest_point) .def("point_to_fractional", &Gr::point_to_fractional) .def("point_to_position", &Gr::point_to_position) .def("change_values", &Gr::change_values, py::arg("old_value"), py::arg("new_value")) .def("copy_metadata_from", &Gr::copy_metadata_from) .def("setup_from", &Gr::template setup_from<Structure>, py::arg("st"), py::arg("spacing")) .def("set_unit_cell", (void (Gr::*)(const UnitCell&)) &Gr::set_unit_cell) .def("set_points_around", &Gr::set_points_around, py::arg("position"), py::arg("radius"), py::arg("value"), py::arg("use_pbc")=true) .def("symmetrize_min", &Gr::symmetrize_min) .def("symmetrize_max", &Gr::symmetrize_max) .def("symmetrize_abs_max", &Gr::symmetrize_abs_max) .def("symmetrize_sum", &Gr::symmetrize_sum) .def("masked_asu", &Gr::masked_asu, py::keep_alive<0, 1>()) .def("mask_points_in_constant_radius", &mask_points_in_constant_radius<T>, py::arg("model"), py::arg("radius"), py::arg("value")) .def("get_subarray", [](const Gr& self, std::array<int,3> start, std::array<int,3> shape) { py::array_t<T> arr({shape[0], shape[1], shape[2]}, {sizeof(T), sizeof(T)*shape[0], sizeof(T)*shape[0]*shape[1]}); self.get_subarray((T*) arr.request().ptr, start, shape); return arr; }, py::arg("start"), py::arg("shape")) .def("set_subarray", [](Gr& self, py::array_t<T, py::array::f_style | py::array::forcecast> arr, std::array<int,3> start) { self.set_subarray((T*) arr.request().ptr, start, {(int)arr.shape(0), (int)arr.shape(1), (int)arr.shape(2)}); }, py::arg("arr"), py::arg("start")) .def("clone", [](const Gr& self) { return new Gr(self); }) .def("__repr__", [=](const Gr& self) { return tostr("<gemmi.", name, '(', self.nu, ", ", self.nv, ", ", self.nw, ")>"); }); masked_grid .def_readonly("grid", &Masked::grid, py::return_value_policy::reference) .def_property_readonly("mask_array", [](const Masked& self) { const Gr& gr = *self.grid; py::array::ShapeContainer shape({gr.nu, gr.nv, gr.nw}); py::array::StridesContainer strides({gr.nv * gr.nw, gr.nw, 1}); return py::array_t<std::int8_t>(shape, strides, self.mask.data(), py::cast(self)); }, py::return_value_policy::reference_internal) .def("__iter__", [](Masked& self) { return py::make_iterator(self); }, py::keep_alive<0, 1>()) ; return grid; } template<typename T> void add_grid_interpolation(py::class_<Grid<T>, GridBase<T>>& grid) { using Gr = Grid<T>; grid .def("interpolate_value", (T (Gr::*)(const Fractional&) const) &Gr::interpolate_value) .def("interpolate_value", (T (Gr::*)(const Position&) const) &Gr::interpolate_value) .def("interpolate_values", [](const Gr& self, py::array_t<T> arr, const Transform& tr, bool cubic) { auto r = arr.template mutable_unchecked<3>(); for (int i = 0; i < r.shape(0); ++i) for (int j = 0; j < r.shape(1); ++j) for (int k = 0; k < r.shape(2); ++k) { Position pos(tr.apply(Vec3(i, j, k))); Fractional fpos = self.unit_cell.fractionalize(pos); if (cubic) r(i, j, k) = (T) self.tricubic_interpolation(fpos); else r(i, j, k) = self.interpolate_value(fpos); } }, py::arg().noconvert(), py::arg(), py::arg("cubic")=false) .def("tricubic_interpolation", (double (Gr::*)(const Fractional&) const) &Gr::tricubic_interpolation) .def("tricubic_interpolation", (double (Gr::*)(const Position&) const) &Gr::tricubic_interpolation) .def("tricubic_interpolation_der", (std::array<double,4> (Gr::*)(const Fractional&) const) &Gr::tricubic_interpolation_der) ; } void add_grid(py::module& m) { py::enum_<AxisOrder>(m, "AxisOrder") .value("Unknown", AxisOrder::Unknown) .value("XYZ", AxisOrder::XYZ) .value("ZYX", AxisOrder::ZYX); py::class_<GridMeta>(m, "GridMeta") .def_readwrite("spacegroup", &GridMeta::spacegroup) .def_readwrite("unit_cell", &GridMeta::unit_cell) .def_readonly("nu", &GridMeta::nu, "size in the first (fastest-changing) dim") .def_readonly("nv", &GridMeta::nv, "size in the second dimension") .def_readonly("nw", &GridMeta::nw, "size in the third (slowest-changing) dim") .def_readonly("axis_order", &GridMeta::axis_order) .def_property_readonly("point_count", &GridMeta::point_count) .def("get_position", &GridMeta::get_position) .def("get_fractional", &GridMeta::get_fractional) .def_property_readonly("shape", [](const GridMeta& self) { return py::make_tuple(self.nu, self.nv, self.nw); }); add_grid_base<int8_t>(m, "Int8GridBase"); add_grid_common<int8_t>(m, "Int8Grid"); add_grid_base<float>(m, "FloatGridBase") .def("calculate_correlation", &calculate_correlation<float>) ; auto grid_float = add_grid_common<float>(m, "FloatGrid"); add_grid_interpolation<float>(grid_float); grid_float.def("normalize", &normalize_grid<float>); add_grid_base<std::complex<float>>(m, "ComplexGridBase"); // from solmask.hpp py::enum_<AtomicRadiiSet>(m, "AtomicRadiiSet") .value("VanDerWaals", AtomicRadiiSet::VanDerWaals) .value("Cctbx", AtomicRadiiSet::Cctbx) .value("Refmac", AtomicRadiiSet::Refmac) .value("Constant", AtomicRadiiSet::Constant); py::class_<SolventMasker>(m, "SolventMasker") .def(py::init<AtomicRadiiSet, double>(), py::arg("choice"), py::arg("constant_r")=0.) .def_readwrite("atomic_radii_set", &SolventMasker::atomic_radii_set) .def_readwrite("rprobe", &SolventMasker::rprobe) .def_readwrite("rshrink", &SolventMasker::rshrink) .def_readwrite("island_min_volume", &SolventMasker::island_min_volume) .def_readwrite("constant_r", &SolventMasker::constant_r) .def("set_radii", &SolventMasker::set_radii, py::arg("choice"), py::arg("constant_r")=0.) .def("put_mask_on_int8_grid", &SolventMasker::put_mask_on_grid<int8_t>) .def("put_mask_on_float_grid", &SolventMasker::put_mask_on_grid<float>) .def("set_to_zero", &SolventMasker::set_to_zero) ; m.def("interpolate_grid_of_aligned_model2", &interpolate_grid_of_aligned_model2<float>, py::arg("dest"), py::arg("src"), py::arg("tr"), py::arg("dest_model"), py::arg("radius")); // from blob.hpp py::class_<Blob>(m, "Blob") .def_readonly("volume", &Blob::volume) .def_readonly("score", &Blob::score) .def_readonly("peak_value", &Blob::peak_value) .def_readonly("centroid", &Blob::centroid) .def_readonly("peak_pos", &Blob::peak_pos) ; m.def("find_blobs_by_flood_fill", [](const Grid<float>& grid, double cutoff, double min_volume, double min_score, double min_peak, bool negate) { BlobCriteria crit; crit.cutoff = cutoff; crit.min_volume = min_volume; crit.min_score = min_score; crit.min_peak = min_peak; return find_blobs_by_flood_fill(grid, crit, negate); }, py::arg("grid"), py::arg("cutoff"), py::arg("min_volume")=10., py::arg("min_score")=15., py::arg("min_peak")=0., py::arg("negate")=false); // from floodfill.hpp m.def("flood_fill_above", &flood_fill_above, py::arg("grid"), py::arg("seeds"), py::arg("threshold"), py::arg("negate")=false); } <|endoftext|>
<commit_before>#include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" #include "../TimerManager.h" /* full name of the command */ CMDNAME("editcom"); /* description of the command */ CMDDESCR("modify a custom command"); /* command usage synopsis */ CMDUSAGE("$editcom [-A on|off] [-a] [-c CD] [-r] CMD [RESPONSE]"); /* rename flag usage */ static const std::string RUSAGE = "$editcom -r OLD NEW"; static bool edit(CustomCommandHandler *cch, const std::string &args, const std::string &set, time_t cooldown, TimerManager *tm, bool app, std::string &res); static bool rename(CustomCommandHandler *cch, const std::string &args, std::string &res); /* editcom: modify a custom command */ std::string CommandHandler::editcom(char *out, struct command *c) { if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return ""; } if (!m_customCmds->isActive()) return CMDNAME + ": custom commands are currently disabled"; std::string outp, res, set, cmd; time_t cooldown; bool ren, append; OptionParser op(c->fullCmd, "A:ac:r"); int opt; static struct OptionParser::option long_opts[] = { { "active", REQ_ARG, 'A'}, { "append", NO_ARG, 'a'}, { "cooldown", REQ_ARG, 'c'}, { "help", NO_ARG, 'h' }, { "rename", NO_ARG, 'r' }, { 0, 0, 0 } }; cooldown = -1; ren = append = false; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'A': if ((set = std::string(op.optarg())) != "on" && set != "off") return CMDNAME + ": -A setting must be on/off"; break; case 'a': append = true; break; case 'c': /* user provided a cooldown */ try { if ((cooldown = std::stoi(op.optarg())) < 0) return CMDNAME + ": cooldown cannot be " "negative"; } catch (std::invalid_argument) { return CMDNAME + ": invalid number -- '" + std::string(op.optarg()) + "'"; } catch (std::out_of_range) { return CMDNAME + ": number too large"; } break; case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case 'r': ren = true; break; case '?': return std::string(op.opterr()); default: return ""; } } if (op.optind() == c->fullCmd.length()) return USAGEMSG(CMDNAME, CMDUSAGE); outp = "@" + std::string(c->nick) + ", "; if (ren) { if (append || cooldown != -1 || !set.empty()) return CMDNAME + ": cannot use other flags with -r"; if (!rename(m_customCmds, c->fullCmd.substr(op.optind()), res)) { if (res.empty()) return USAGEMSG(CMDNAME, RUSAGE); else return CMDNAME + ": " + res; } return outp + res; } if (!edit(m_customCmds, c->fullCmd.substr(op.optind()), set, cooldown, &m_cooldowns, append, res)) return CMDNAME + ": " + res; return outp + res; } /* edit: edit a custom command */ static bool edit(CustomCommandHandler *cch, const std::string &args, const std::string &set, time_t cooldown, TimerManager *tm, bool app, std::string &res) { bool cd, resp, act; size_t sp; std::string cmd, response; Json::Value *com; /* determine which parts are being changed */ cd = cooldown != -1; resp = (sp = args.find(' ')) != std::string::npos; cmd = resp ? args.substr(0, sp) : args; act = !set.empty(); response = resp ? args.substr(sp + 1) : ""; if (app) { if ((com = cch->getcom(cmd))->empty()) { res = "not a command: $" + cmd; return false; } response = (*com)["response"].asString() + " " + response; } else if (response[0] == '/') { /* don't allow reponse to activate a twitch command */ response = " " + response; } if (!cch->editcom(cmd, response, cooldown)) { res = cch->error(); return false; } if (!cd && !resp && !act) { res = "command $" + cmd + " was unchanged"; return true; } /* build an output string detailing changes */ res += "command $" + cmd + " has been"; if (act) { if (set == "on") { if (!cch->activate(cmd)) { res = cch->error(); res += ". Command not activated."; return false; } res += " activated"; } else { cch->deactivate(cmd); res += " deactivated"; } } if (resp || cd) { res += (act) ? " and" : ""; res += " changed to "; if (resp) res += "\"" + response + "\"" + (cd ? ", with " : ""); if (cd) { /* reset cooldown in TimerManager */ tm->remove(cmd); tm->add(cmd, cooldown); res += "a " + std::to_string(cooldown) + "s cooldown"; } } res += "."; return true; } /* rename: rename a custom command */ static bool rename(CustomCommandHandler *cch, const std::string &args, std::string &res) { std::string cmd, newcmd; size_t t; if ((t = args.find(' ')) == std::string::npos) return false; cmd = args.substr(0, t); if ((newcmd = args.substr(t + 1)).find(' ') != std::string::npos) return false; if (!cch->rename(cmd, newcmd)) { res = cch->error(); return false; } res = "command $" + cmd + " has been renamed to $" + newcmd; return true; } <commit_msg>Changed editcom to use new command format<commit_after>#include <string.h> #include "command.h" #include "../CommandHandler.h" #include "../option.h" #include "../stringparse.h" #include "../TimerManager.h" #define ON 1 #define OFF 2 /* full name of the command */ _CMDNAME("editcom"); /* description of the command */ _CMDDESCR("modify a custom command"); /* command usage synopsis */ _CMDUSAGE("$editcom [-A on|off] [-a] [-c CD] [-r] CMD [RESPONSE]"); /* rename flag usage */ static const char *RUSAGE = "$editcom -r OLD NEW"; /* whether to append to existing response */ static int app; /* active setting */ static int set; static void edit(char *out, CustomCommandHandler *cch, struct command *c, time_t cooldown, TimerManager *tm); static void rename(char *out, CustomCommandHandler *cch, struct command *c); /* editcom: modify a custom command */ std::string CommandHandler::editcom(char *out, struct command *c) { time_t cooldown; int ren; int opt; static struct option long_opts[] = { { "active", REQ_ARG, 'A'}, { "append", NO_ARG, 'a'}, { "cooldown", REQ_ARG, 'c'}, { "help", NO_ARG, 'h' }, { "rename", NO_ARG, 'r' }, { 0, 0, 0 } }; if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return ""; } if (!m_customCmds->isActive()) { _sprintf(out, MAX_MSG, "%s: custom commands are currently " "disabled", c->argv[0]); return ""; } opt_init(); cooldown = -1; set = ren = app = 0; while ((opt = getopt_long(c->argc, c->argv, "A:ac:r", long_opts)) != EOF) { switch (opt) { case 'A': if (strcmp(optarg, "on") == 0) { set = ON; } else if (strcmp(optarg, "off") == 0) { set = OFF; } else { _sprintf(out, MAX_MSG, "%s: -A setting must " "be on/off", c->argv[0]); return ""; } break; case 'a': app = 1; break; case 'c': /* user provided a cooldown */ if (!parsenum(optarg, &cooldown)) { _sprintf(out, MAX_MSG, "%s: invalid number: %s", c->argv[0], optarg); return ""; } if (cooldown < 0) { _sprintf(out, MAX_MSG, "%s: cooldown cannot be " "negative", c->argv[0]); return ""; } break; case 'h': _HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR); return ""; case 'r': ren = 1; break; case '?': _sprintf(out, MAX_MSG, "%s", opterr()); return ""; default: return ""; } } if (optind == c->argc) { _USAGEMSG(out, _CMDNAME, _CMDUSAGE); return ""; } if (ren) { if (app || cooldown != -1 || set) _sprintf(out, MAX_MSG, "%s: cannot use other flags " "with -r", c->argv[0]); else rename(out, m_customCmds, c); } else { edit(out, m_customCmds, c, cooldown, &m_cooldowns); } return ""; } /* edit: edit a custom command */ static void edit(char *out, CustomCommandHandler *cch, struct command *c, time_t cooldown, TimerManager *tm) { int cd, resp; char response[MAX_MSG]; char buf[MAX_MSG]; Json::Value *com; /* determine which parts are being changed */ cd = cooldown != -1; resp = optind != c->argc - 1; argvcat(response, c->argc, c->argv, optind + 1, 1); if (app) { if ((com = cch->getcom(c->argv[optind]))->empty()) { _sprintf(out, MAX_MSG, "%s: not a command: $%s", c->argv[0], c->argv[optind]); return; } strcpy(buf, response); _sprintf(response, MAX_MSG, "%s %s", (*com)["response"].asCString(), buf); } if (!cch->editcom(c->argv[optind], response, cooldown)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return; } if (!cd && !resp && !set) { _sprintf(out, MAX_MSG, "@%s, command $%s was unchanged", c->nick, c->argv[optind]); return; } /* build an output string detailing changes */ _sprintf(out, MAX_MSG, "@%s, command $%s has been", c->nick, c->argv[optind]); if (set) { if (set == ON) { if (!cch->activate(c->argv[optind])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return; } strcat(out, " activated"); } else { cch->deactivate(c->argv[optind]); strcat(out, " deactivated"); } } if (resp || cd) { if (set) strcat(out, " and"); strcat(out, " changed to "); out = strchr(out, '\0'); if (resp) { _sprintf(out, MAX_MSG, "\"%s\"%s", response, cd ? ", with " : ""); out = strchr(out, '\0'); } if (cd) { /* reset cooldown in TimerManager */ tm->remove(c->argv[optind]); tm->add(c->argv[optind], cooldown); _sprintf(out, MAX_MSG, "a %lds cooldown", cooldown); } } strcat(out, "."); } /* rename: rename a custom command */ static void rename(char *out, CustomCommandHandler *cch, struct command *c) { if (optind != c->argc - 2) _USAGEMSG(out, _CMDNAME, RUSAGE); else if (!cch->rename(c->argv[optind], c->argv[optind + 1])) _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); else _sprintf(out, MAX_MSG, "@%s, command $%s has been renamed " "to $%s", c->nick, c->argv[optind], c->argv[optind + 1]); } <|endoftext|>
<commit_before>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Definition of UDP connection (server) for unmanned vehicles * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <QTimer> #include <QList> #include <QDebug> #include <QMutexLocker> #include <iostream> #include "UDPLink.h" #include "LinkManager.h" #include "MG.h" #include <netinet/in.h> UDPLink::UDPLink(QHostAddress host, quint16 port) { this->host = host; this->port = port; this->connectState = false; this->hosts = new QList<QHostAddress>(); //this->ports = new QMap<QHostAddress, quint16>(); this->ports = new QList<quint16>(); // Set unique ID and add link to the list of links this->id = getNextLinkId(); this->name = tr("UDP link ") + QString::number(getId()); LinkManager::instance()->add(this); } UDPLink::~UDPLink() { disconnect(); } /** * @brief Runs the thread * **/ void UDPLink::run() { } void UDPLink::setAddress(QString address) { Q_UNUSED(address); // FIXME TODO Implement address //socket->setLocalAddress(QHostAddress(address)); } void UDPLink::setPort(quint16 port) { this->port = port; } void UDPLink::writeBytes(const char* data, qint64 size) { // Broadcast to all connected systems //QList<QHostAddress>::iterator h; // for (h = hosts->begin(); h != hosts->end(); ++h) for (int h = 0; h < hosts->size(); h++) { QHostAddress currentHost = hosts->at(h); quint16 currentPort = ports->at(h); // QList<quint16> currentPorts = ports->values(currentHost); // for (int p = 0; p < currentPorts.size(); p++) // { // quint16 currentPort = currentPorts.at(p); //qDebug() << "Sent message to " << currentHost << ":" << currentPort << "at" << __FILE__ << ":" << __LINE__; socket->writeDatagram(data, size, currentHost, currentPort); // } } //if(socket->write(data, size) > 0) { // qDebug() << "Transmitted " << size << "bytes:"; // // /* Increase write counter */ // bitsSentTotal += size * 8; // // int i; // for (i=0; i<size; i++){ // unsigned int v=data[i]; // // fprintf(stderr,"%02x ", v); // } //} } /** * @brief Read a number of bytes from the interface. * * @param data Pointer to the data byte array to write the bytes to * @param maxLength The maximum number of bytes to write **/ void UDPLink::readBytes() { const qint64 maxLength = 2048; char data[maxLength]; QHostAddress sender; quint16 senderPort; unsigned int s = socket->pendingDatagramSize(); if (s > maxLength) std::cerr << __FILE__ << __LINE__ << " UDP datagram overflow, allowed to read less bytes than datagram size" << std::endl; socket->readDatagram(data, maxLength, &sender, &senderPort); // FIXME TODO Check if this method is better than retrieving the data by individual processes QByteArray b(data, s); emit bytesReceived(this, b); // // Echo data for debugging purposes // std::cerr << __FILE__ << __LINE__ << "Received datagram:" << std::endl; // int i; // for (i=0; i<s; i++) // { // unsigned int v=data[i]; // fprintf(stderr,"%02x ", v); // } // std::cerr << std::endl; // Add host to broadcast list if not yet present if (!hosts->contains(sender)) { hosts->append(sender); ports->append(senderPort); // ports->insert(sender, senderPort); } else { int index = hosts->indexOf(sender); ports->replace(index, senderPort); } } /** * @brief Get the number of bytes to read. * * @return The number of bytes to read **/ qint64 UDPLink::bytesAvailable() { return socket->pendingDatagramSize(); } /** * @brief Disconnect the connection. * * @return True if connection has been disconnected, false if connection couldn't be disconnected. **/ bool UDPLink::disconnect() { delete socket; socket = NULL; connectState = false; emit disconnected(); emit connected(false); return !connectState; } /** * @brief Connect the connection. * * @return True if connection has been established, false if connection couldn't be established. **/ bool UDPLink::connect() { socket = new QUdpSocket(this); //Check if we are using a multicast-address // bool multicast = false; // if (host.isInSubnet(QHostAddress("224.0.0.0"),4)) // { // multicast = true; // connectState = socket->bind(port, QUdpSocket::ShareAddress); // } // else // { connectState = socket->bind(host, port); // } //Provides Multicast functionality to UdpSocket /* not working yet if (multicast) { int sendingFd = socket->socketDescriptor(); if (sendingFd != -1) { // set up destination address struct sockaddr_in sendAddr; memset(&sendAddr,0,sizeof(sendAddr)); sendAddr.sin_family=AF_INET; sendAddr.sin_addr.s_addr=inet_addr(HELLO_GROUP); sendAddr.sin_port=htons(port); // set TTL unsigned int ttl = 1; // restricted to the same subnet if (setsockopt(sendingFd, IPPROTO_IP, IP_MULTICAST_TTL, (unsigned int*)&ttl, sizeof(ttl) ) < 0) { std::cout << "TTL failed\n"; } } } */ //QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes())); emit connected(connectState); if (connectState) { emit connected(); connectionStartTime = MG::TIME::getGroundTimeNow(); } start(HighPriority); return connectState; } /** * @brief Check if connection is active. * * @return True if link is connected, false otherwise. **/ bool UDPLink::isConnected() { return connectState; } int UDPLink::getId() { return id; } QString UDPLink::getName() { return name; } void UDPLink::setName(QString name) { this->name = name; emit nameChanged(this->name); } qint64 UDPLink::getNominalDataRate() { return 54000000; // 54 Mbit } qint64 UDPLink::getTotalUpstream() { statisticsMutex.lock(); qint64 totalUpstream = bitsSentTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000); statisticsMutex.unlock(); return totalUpstream; } qint64 UDPLink::getCurrentUpstream() { return 0; // TODO } qint64 UDPLink::getMaxUpstream() { return 0; // TODO } qint64 UDPLink::getBitsSent() { return bitsSentTotal; } qint64 UDPLink::getBitsReceived() { return bitsReceivedTotal; } qint64 UDPLink::getTotalDownstream() { statisticsMutex.lock(); qint64 totalDownstream = bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000); statisticsMutex.unlock(); return totalDownstream; } qint64 UDPLink::getCurrentDownstream() { return 0; // TODO } qint64 UDPLink::getMaxDownstream() { return 0; // TODO } bool UDPLink::isFullDuplex() { return true; } int UDPLink::getLinkQuality() { /* This feature is not supported with this interface */ return -1; } <commit_msg>Fixed unneccesary header in UDPLink.cc<commit_after>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Definition of UDP connection (server) for unmanned vehicles * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <QTimer> #include <QList> #include <QDebug> #include <QMutexLocker> #include <iostream> #include "UDPLink.h" #include "LinkManager.h" #include "MG.h" //#include <netinet/in.h> UDPLink::UDPLink(QHostAddress host, quint16 port) { this->host = host; this->port = port; this->connectState = false; this->hosts = new QList<QHostAddress>(); //this->ports = new QMap<QHostAddress, quint16>(); this->ports = new QList<quint16>(); // Set unique ID and add link to the list of links this->id = getNextLinkId(); this->name = tr("UDP link ") + QString::number(getId()); LinkManager::instance()->add(this); } UDPLink::~UDPLink() { disconnect(); } /** * @brief Runs the thread * **/ void UDPLink::run() { } void UDPLink::setAddress(QString address) { Q_UNUSED(address); // FIXME TODO Implement address //socket->setLocalAddress(QHostAddress(address)); } void UDPLink::setPort(quint16 port) { this->port = port; } void UDPLink::writeBytes(const char* data, qint64 size) { // Broadcast to all connected systems //QList<QHostAddress>::iterator h; // for (h = hosts->begin(); h != hosts->end(); ++h) for (int h = 0; h < hosts->size(); h++) { QHostAddress currentHost = hosts->at(h); quint16 currentPort = ports->at(h); // QList<quint16> currentPorts = ports->values(currentHost); // for (int p = 0; p < currentPorts.size(); p++) // { // quint16 currentPort = currentPorts.at(p); //qDebug() << "Sent message to " << currentHost << ":" << currentPort << "at" << __FILE__ << ":" << __LINE__; socket->writeDatagram(data, size, currentHost, currentPort); // } } //if(socket->write(data, size) > 0) { // qDebug() << "Transmitted " << size << "bytes:"; // // /* Increase write counter */ // bitsSentTotal += size * 8; // // int i; // for (i=0; i<size; i++){ // unsigned int v=data[i]; // // fprintf(stderr,"%02x ", v); // } //} } /** * @brief Read a number of bytes from the interface. * * @param data Pointer to the data byte array to write the bytes to * @param maxLength The maximum number of bytes to write **/ void UDPLink::readBytes() { const qint64 maxLength = 2048; char data[maxLength]; QHostAddress sender; quint16 senderPort; unsigned int s = socket->pendingDatagramSize(); if (s > maxLength) std::cerr << __FILE__ << __LINE__ << " UDP datagram overflow, allowed to read less bytes than datagram size" << std::endl; socket->readDatagram(data, maxLength, &sender, &senderPort); // FIXME TODO Check if this method is better than retrieving the data by individual processes QByteArray b(data, s); emit bytesReceived(this, b); // // Echo data for debugging purposes // std::cerr << __FILE__ << __LINE__ << "Received datagram:" << std::endl; // int i; // for (i=0; i<s; i++) // { // unsigned int v=data[i]; // fprintf(stderr,"%02x ", v); // } // std::cerr << std::endl; // Add host to broadcast list if not yet present if (!hosts->contains(sender)) { hosts->append(sender); ports->append(senderPort); // ports->insert(sender, senderPort); } else { int index = hosts->indexOf(sender); ports->replace(index, senderPort); } } /** * @brief Get the number of bytes to read. * * @return The number of bytes to read **/ qint64 UDPLink::bytesAvailable() { return socket->pendingDatagramSize(); } /** * @brief Disconnect the connection. * * @return True if connection has been disconnected, false if connection couldn't be disconnected. **/ bool UDPLink::disconnect() { delete socket; socket = NULL; connectState = false; emit disconnected(); emit connected(false); return !connectState; } /** * @brief Connect the connection. * * @return True if connection has been established, false if connection couldn't be established. **/ bool UDPLink::connect() { socket = new QUdpSocket(this); //Check if we are using a multicast-address // bool multicast = false; // if (host.isInSubnet(QHostAddress("224.0.0.0"),4)) // { // multicast = true; // connectState = socket->bind(port, QUdpSocket::ShareAddress); // } // else // { connectState = socket->bind(host, port); // } //Provides Multicast functionality to UdpSocket /* not working yet if (multicast) { int sendingFd = socket->socketDescriptor(); if (sendingFd != -1) { // set up destination address struct sockaddr_in sendAddr; memset(&sendAddr,0,sizeof(sendAddr)); sendAddr.sin_family=AF_INET; sendAddr.sin_addr.s_addr=inet_addr(HELLO_GROUP); sendAddr.sin_port=htons(port); // set TTL unsigned int ttl = 1; // restricted to the same subnet if (setsockopt(sendingFd, IPPROTO_IP, IP_MULTICAST_TTL, (unsigned int*)&ttl, sizeof(ttl) ) < 0) { std::cout << "TTL failed\n"; } } } */ //QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes())); emit connected(connectState); if (connectState) { emit connected(); connectionStartTime = MG::TIME::getGroundTimeNow(); } start(HighPriority); return connectState; } /** * @brief Check if connection is active. * * @return True if link is connected, false otherwise. **/ bool UDPLink::isConnected() { return connectState; } int UDPLink::getId() { return id; } QString UDPLink::getName() { return name; } void UDPLink::setName(QString name) { this->name = name; emit nameChanged(this->name); } qint64 UDPLink::getNominalDataRate() { return 54000000; // 54 Mbit } qint64 UDPLink::getTotalUpstream() { statisticsMutex.lock(); qint64 totalUpstream = bitsSentTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000); statisticsMutex.unlock(); return totalUpstream; } qint64 UDPLink::getCurrentUpstream() { return 0; // TODO } qint64 UDPLink::getMaxUpstream() { return 0; // TODO } qint64 UDPLink::getBitsSent() { return bitsSentTotal; } qint64 UDPLink::getBitsReceived() { return bitsReceivedTotal; } qint64 UDPLink::getTotalDownstream() { statisticsMutex.lock(); qint64 totalDownstream = bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000); statisticsMutex.unlock(); return totalDownstream; } qint64 UDPLink::getCurrentDownstream() { return 0; // TODO } qint64 UDPLink::getMaxDownstream() { return 0; // TODO } bool UDPLink::isFullDuplex() { return true; } int UDPLink::getLinkQuality() { /* This feature is not supported with this interface */ return -1; } <|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: SlsCurrentSlideManager.cxx,v $ * * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_sd.hxx" #include "SlideSorter.hxx" #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "controller/SlsPageSelector.hxx" #include "controller/SlideSorterController.hxx" #include "controller/SlsCurrentSlideManager.hxx" #include "view/SlideSorterView.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "view/SlsHighlightObject.hxx" #include "ViewShellBase.hxx" #include "ViewShell.hxx" #include "DrawViewShell.hxx" #include "sdpage.hxx" #include "FrameView.hxx" #include <com/sun/star/beans/XPropertySet.hpp> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::sd::slidesorter::model; namespace sd { namespace slidesorter { namespace controller { CurrentSlideManager::CurrentSlideManager (SlideSorter& rSlideSorter) : mrSlideSorter(rSlideSorter), mnCurrentSlideIndex(-1), mpCurrentSlide() { } CurrentSlideManager::~CurrentSlideManager (void) { } void CurrentSlideManager::CurrentSlideHasChanged (const sal_Int32 nSlideIndex) { if (mnCurrentSlideIndex != nSlideIndex) { ReleaseCurrentSlide(); AcquireCurrentSlide(nSlideIndex); // Update the selection. mrSlideSorter.GetController().GetPageSelector().DeselectAllPages(); if (mpCurrentSlide.get() != NULL) mrSlideSorter.GetController().GetPageSelector().SelectPage(mpCurrentSlide); } } void CurrentSlideManager::ReleaseCurrentSlide (void) { if (mpCurrentSlide.get() != NULL) { mpCurrentSlide->SetIsCurrentPage(false); mrSlideSorter.GetView().RequestRepaint(mpCurrentSlide); } mpCurrentSlide.reset(); } bool CurrentSlideManager::IsCurrentSlideIsValid (void) { return mnCurrentSlideIndex >= 0 && mnCurrentSlideIndex<mrSlideSorter.GetModel().GetPageCount(); } void CurrentSlideManager::AcquireCurrentSlide (const sal_Int32 nSlideIndex) { mnCurrentSlideIndex = nSlideIndex; if (IsCurrentSlideIsValid()) { // Get a descriptor for the XDrawPage reference. Note that the // given XDrawPage may or may not be member of the slide sorter // document. mpCurrentSlide = mrSlideSorter.GetModel().GetPageDescriptor(mnCurrentSlideIndex); if (mpCurrentSlide.get() != NULL) { mpCurrentSlide->SetIsCurrentPage(true); view::HighlightObject* pObject = mrSlideSorter.GetController().GetHighlightObject(); if (pObject != NULL) pObject->SetSlide(mpCurrentSlide); mrSlideSorter.GetView().RequestRepaint(mpCurrentSlide); } } } void CurrentSlideManager::SwitchCurrentSlide (const sal_Int32 nSlideIndex) { SwitchCurrentSlide(mrSlideSorter.GetModel().GetPageDescriptor(nSlideIndex)); } void CurrentSlideManager::SwitchCurrentSlide (const SharedPageDescriptor& rpDescriptor) { if (rpDescriptor.get() != NULL) { mpCurrentSlide = rpDescriptor; mnCurrentSlideIndex = (rpDescriptor->GetPage()->GetPageNum()-1)/2; ViewShell* pViewShell = mrSlideSorter.GetViewShell(); if (pViewShell != NULL && pViewShell->IsMainViewShell()) { FrameView* pFrameView = pViewShell->GetFrameView(); if (pFrameView != NULL) pFrameView->SetSelectedPage(sal::static_int_cast<USHORT>(mnCurrentSlideIndex)); } else { // Set current page. At the moment we have to do this in two // different ways. The UNO way is the preferable one but, alas, // it does not work always correctly (after some kinds of model // changes). Therefore, we call DrawViewShell::SwitchPage(), // too. SetCurrentSlideAtViewShellBase(rpDescriptor); SetCurrentSlideAtXController(rpDescriptor); } } } void CurrentSlideManager::SetCurrentSlideAtViewShellBase (const SharedPageDescriptor& rpDescriptor) { OSL_ASSERT(rpDescriptor.get() != NULL); ViewShellBase* pBase = mrSlideSorter.GetViewShellBase(); if (pBase != NULL) { DrawViewShell* pDrawViewShell = dynamic_cast<DrawViewShell*>( pBase->GetMainViewShell().get()); if (pDrawViewShell != NULL) { USHORT nPageNumber = (rpDescriptor->GetPage()->GetPageNum()-1)/2; pDrawViewShell->SwitchPage(nPageNumber); pDrawViewShell->GetPageTabControl()->SetCurPageId(nPageNumber+1); } /* else { presenter::PresenterViewShell* pPresenterViewShell = dynamic_cast<presenter::PresenterViewShell*>(pBase->GetMainViewShell()); if (pPresenterViewShell != NULL) { pPresenterViewShell->SetCurrentSlide( Reference<drawing::XDrawPage>( rpDescriptor->GetPage()->getUnoPage(), UNO_QUERY)); } } */ } } void CurrentSlideManager::SetCurrentSlideAtXController (const SharedPageDescriptor& rpDescriptor) { OSL_ASSERT(rpDescriptor.get() != NULL); try { Reference<beans::XPropertySet> xSet (mrSlideSorter.GetXController(), UNO_QUERY); if (xSet.is()) { Any aPage; aPage <<= rpDescriptor->GetPage()->getUnoPage(); xSet->setPropertyValue ( String::CreateFromAscii("CurrentPage"), aPage); } } catch (beans::UnknownPropertyException aException) { // We have not been able to set the current page at the main view. // This is sad but still leaves us in a valid state. Therefore, // this exception is silently ignored. } } SharedPageDescriptor CurrentSlideManager::GetCurrentSlide (void) { return mpCurrentSlide; } void CurrentSlideManager::PrepareModelChange (void) { mpCurrentSlide.reset(); } void CurrentSlideManager::HandleModelChange (void) { if (mpCurrentSlide.get() != NULL) { mpCurrentSlide = mrSlideSorter.GetModel().GetPageDescriptor( mpCurrentSlide->GetPageIndex()); mpCurrentSlide->SetIsCurrentPage(true); } } SdPage* GetCurrentSdPage (SlideSorter& rSlideSorter) { SharedPageDescriptor pDescriptor ( rSlideSorter.GetController().GetCurrentSlideManager()->GetCurrentSlide()); if (pDescriptor.get() == NULL) return NULL; else return pDescriptor->GetPage(); } } } } // end of namespace ::sd::slidesorter::controller <commit_msg>INTEGRATION: CWS impress142 (1.3.18); FILE MERGED 2008/05/09 12:27:41 af 1.3.18.2: #i89229# Added check for missing current slide. 2008/05/07 11:55:49 af 1.3.18.1: #i89030# Use index of current page, not pointer, in HandleModelChange().<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: SlsCurrentSlideManager.cxx,v $ * * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_sd.hxx" #include "SlideSorter.hxx" #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "controller/SlsPageSelector.hxx" #include "controller/SlideSorterController.hxx" #include "controller/SlsCurrentSlideManager.hxx" #include "view/SlideSorterView.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "view/SlsHighlightObject.hxx" #include "ViewShellBase.hxx" #include "ViewShell.hxx" #include "DrawViewShell.hxx" #include "sdpage.hxx" #include "FrameView.hxx" #include <com/sun/star/beans/XPropertySet.hpp> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::sd::slidesorter::model; namespace sd { namespace slidesorter { namespace controller { CurrentSlideManager::CurrentSlideManager (SlideSorter& rSlideSorter) : mrSlideSorter(rSlideSorter), mnCurrentSlideIndex(-1), mpCurrentSlide() { } CurrentSlideManager::~CurrentSlideManager (void) { } void CurrentSlideManager::CurrentSlideHasChanged (const sal_Int32 nSlideIndex) { if (mnCurrentSlideIndex != nSlideIndex) { ReleaseCurrentSlide(); AcquireCurrentSlide(nSlideIndex); // Update the selection. mrSlideSorter.GetController().GetPageSelector().DeselectAllPages(); if (mpCurrentSlide.get() != NULL) mrSlideSorter.GetController().GetPageSelector().SelectPage(mpCurrentSlide); } } void CurrentSlideManager::ReleaseCurrentSlide (void) { if (mpCurrentSlide.get() != NULL) { mpCurrentSlide->SetIsCurrentPage(false); mrSlideSorter.GetView().RequestRepaint(mpCurrentSlide); } mpCurrentSlide.reset(); mnCurrentSlideIndex = -1; } bool CurrentSlideManager::IsCurrentSlideIsValid (void) { return mnCurrentSlideIndex >= 0 && mnCurrentSlideIndex<mrSlideSorter.GetModel().GetPageCount(); } void CurrentSlideManager::AcquireCurrentSlide (const sal_Int32 nSlideIndex) { mnCurrentSlideIndex = nSlideIndex; if (IsCurrentSlideIsValid()) { // Get a descriptor for the XDrawPage reference. Note that the // given XDrawPage may or may not be member of the slide sorter // document. mpCurrentSlide = mrSlideSorter.GetModel().GetPageDescriptor(mnCurrentSlideIndex); if (mpCurrentSlide.get() != NULL) { mpCurrentSlide->SetIsCurrentPage(true); view::HighlightObject* pObject = mrSlideSorter.GetController().GetHighlightObject(); if (pObject != NULL) pObject->SetSlide(mpCurrentSlide); mrSlideSorter.GetView().RequestRepaint(mpCurrentSlide); } } } void CurrentSlideManager::SwitchCurrentSlide (const sal_Int32 nSlideIndex) { SwitchCurrentSlide(mrSlideSorter.GetModel().GetPageDescriptor(nSlideIndex)); } void CurrentSlideManager::SwitchCurrentSlide (const SharedPageDescriptor& rpDescriptor) { if (rpDescriptor.get() != NULL) { mpCurrentSlide = rpDescriptor; mnCurrentSlideIndex = (rpDescriptor->GetPage()->GetPageNum()-1)/2; ViewShell* pViewShell = mrSlideSorter.GetViewShell(); if (pViewShell != NULL && pViewShell->IsMainViewShell()) { FrameView* pFrameView = pViewShell->GetFrameView(); if (pFrameView != NULL) pFrameView->SetSelectedPage(sal::static_int_cast<USHORT>(mnCurrentSlideIndex)); } else { // Set current page. At the moment we have to do this in two // different ways. The UNO way is the preferable one but, alas, // it does not work always correctly (after some kinds of model // changes). Therefore, we call DrawViewShell::SwitchPage(), // too. SetCurrentSlideAtViewShellBase(rpDescriptor); SetCurrentSlideAtXController(rpDescriptor); } } } void CurrentSlideManager::SetCurrentSlideAtViewShellBase (const SharedPageDescriptor& rpDescriptor) { OSL_ASSERT(rpDescriptor.get() != NULL); ViewShellBase* pBase = mrSlideSorter.GetViewShellBase(); if (pBase != NULL) { DrawViewShell* pDrawViewShell = dynamic_cast<DrawViewShell*>( pBase->GetMainViewShell().get()); if (pDrawViewShell != NULL) { USHORT nPageNumber = (rpDescriptor->GetPage()->GetPageNum()-1)/2; pDrawViewShell->SwitchPage(nPageNumber); pDrawViewShell->GetPageTabControl()->SetCurPageId(nPageNumber+1); } /* else { presenter::PresenterViewShell* pPresenterViewShell = dynamic_cast<presenter::PresenterViewShell*>(pBase->GetMainViewShell()); if (pPresenterViewShell != NULL) { pPresenterViewShell->SetCurrentSlide( Reference<drawing::XDrawPage>( rpDescriptor->GetPage()->getUnoPage(), UNO_QUERY)); } } */ } } void CurrentSlideManager::SetCurrentSlideAtXController (const SharedPageDescriptor& rpDescriptor) { OSL_ASSERT(rpDescriptor.get() != NULL); try { Reference<beans::XPropertySet> xSet (mrSlideSorter.GetXController(), UNO_QUERY); if (xSet.is()) { Any aPage; aPage <<= rpDescriptor->GetPage()->getUnoPage(); xSet->setPropertyValue ( String::CreateFromAscii("CurrentPage"), aPage); } } catch (beans::UnknownPropertyException aException) { // We have not been able to set the current page at the main view. // This is sad but still leaves us in a valid state. Therefore, // this exception is silently ignored. } } SharedPageDescriptor CurrentSlideManager::GetCurrentSlide (void) { return mpCurrentSlide; } void CurrentSlideManager::PrepareModelChange (void) { mpCurrentSlide.reset(); } void CurrentSlideManager::HandleModelChange (void) { if (mnCurrentSlideIndex >= 0) { mpCurrentSlide = mrSlideSorter.GetModel().GetPageDescriptor( mnCurrentSlideIndex); if (mpCurrentSlide.get() != NULL) mpCurrentSlide->SetIsCurrentPage(true); } } SdPage* GetCurrentSdPage (SlideSorter& rSlideSorter) { SharedPageDescriptor pDescriptor ( rSlideSorter.GetController().GetCurrentSlideManager()->GetCurrentSlide()); if (pDescriptor.get() == NULL) return NULL; else return pDescriptor->GetPage(); } } } } // end of namespace ::sd::slidesorter::controller <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "gk_utils.h" using namespace std; using namespace cv; static void help() { cout << endl << "Usage: ./gekon lena.jpg" << endl; } const char* keys = { "{help h||}{@image |../lena.jpg|input image name}" }; int main(int argc, char **argv) { cout << "GeKon" << endl; cout << "Vojtech Vladyka & Martin Sehnoutka" << endl; cout << "FEEC BUT 2016" << endl; cout << "******************" << endl; // do something here Mat image; CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } string filename = parser.get<string>(0); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } // Show the image imshow("Original Image", image); // Wait for a key stroke; the same function arranges events processing waitKey(0); cout << "Bye!" << endl; return 0; } <commit_msg>Reworked helper and loader<commit_after>#include <iostream> #include <unistd.h> #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "gk_utils.h" using namespace std; using namespace cv; static void help() { cout << "Usage: gekon [PARAMETER] [ORIGNAL IMAGE] [MODIFIED IMAGE]" << endl << endl; cout << "All parameters are mandatory." << endl; cout << "PARAMETER is size of convolution matrix" << endl; cout << "ORIGINAL IMAGE is image before modification" << endl; cout << "MODIFIED IMAGE is image after modification" << endl << endl; cout << "Example of usage: ./gekon 3 lena.jpg lena-mod.jpg" << endl << endl; cout << "Authors: Vojtech Vladyka <vojtech.vladyka@gmail.com> and Martin Sehnoutka <>" << endl; cout << "Department of Automation and Measurement, FEEC BUT, 2016" << endl; } const char* keys = { "{help h||}{@convSize|3|convolution size}{@original|lena.jpg|original image name}{@modified|lena.mod.jpg|modiifed image name}" }; int main(int argc, char **argv) { cout << "GeKon" << endl; CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } string original = parser.get<string>(1); string modified = parser.get<string>(2); int convSize = parser.get<int>(0); cout << "Convolution matrix size: " << convSize << endl; cout << "Original image: " << original << endl; cout << "Modified image: " << modified << endl; // init gekon here // test inputs // run! cout << "Bye!" << endl; return 0; } <|endoftext|>
<commit_before>// Copyright 2021 Global Phasing Ltd. #include "gemmi/topo.hpp" #include "gemmi/placeh.hpp" // for adjust_hydrogen_distances #include "common.h" #include <pybind11/stl.h> #include <pybind11/stl_bind.h> namespace py = pybind11; using namespace gemmi; PYBIND11_MAKE_OPAQUE(std::vector<Topo::Bond>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Angle>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Torsion>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Chirality>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Plane>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::ExtraLink>) void add_topo(py::module& m) { py::class_<Topo> topo(m, "Topo"); py::enum_<HydrogenChange>(m, "HydrogenChange") .value("None", HydrogenChange::None) .value("Shift", HydrogenChange::Shift) .value("Remove", HydrogenChange::Remove) .value("ReAdd", HydrogenChange::ReAdd) .value("ReAddButWater", HydrogenChange::ReAddButWater); py::class_<Topo::Bond>(topo, "Bond") .def_readonly("restr", &Topo::Bond::restr) .def_readonly("atoms", &Topo::Bond::atoms) .def("calculate", &Topo::Bond::calculate) .def("calculate_z", &Topo::Bond::calculate_z) ; py::class_<Topo::Angle>(topo, "Angle") .def_readonly("restr", &Topo::Angle::restr) .def_readonly("atoms", &Topo::Angle::atoms) .def("calculate", &Topo::Angle::calculate) .def("calculate_z", &Topo::Angle::calculate_z) ; py::class_<Topo::Torsion>(topo, "Torsion") .def_readonly("restr", &Topo::Torsion::restr) .def_readonly("atoms", &Topo::Torsion::atoms) .def("calculate", &Topo::Torsion::calculate) .def("calculate_z", &Topo::Torsion::calculate_z) ; py::class_<Topo::Chirality>(topo, "Chirality") .def_readonly("restr", &Topo::Chirality::restr) .def_readonly("atoms", &Topo::Chirality::atoms) .def("calculate", &Topo::Chirality::calculate) .def("check", &Topo::Chirality::check) ; py::class_<Topo::Plane>(topo, "Plane") .def_readonly("restr", &Topo::Plane::restr) .def_readonly("atoms", &Topo::Plane::atoms) .def("has", &Topo::Plane::has) ; py::class_<Topo::ExtraLink>(topo, "ExtraLink") .def_readonly("res1", &Topo::ExtraLink::res1) .def_readonly("res2", &Topo::ExtraLink::res2) .def_readonly("alt1", &Topo::ExtraLink::alt1) .def_readonly("alt2", &Topo::ExtraLink::alt2) .def_readonly("link_id", &Topo::ExtraLink::link_id) ; py::bind_vector<std::vector<Topo::Bond>>(m, "TopoBonds"); py::bind_vector<std::vector<Topo::Angle>>(m, "TopoAngles"); py::bind_vector<std::vector<Topo::Torsion>>(m, "TopoTorsions"); py::bind_vector<std::vector<Topo::Chirality>>(m, "TopoChirs"); py::bind_vector<std::vector<Topo::Plane>>(m, "TopoPlanes"); py::bind_vector<std::vector<Topo::ExtraLink>>(m, "TopoExtraLinks"); topo .def(py::init<>()) .def("adjust_hydrogen_distances", &adjust_hydrogen_distances, py::arg("of"), py::arg("default_scale")=1.) .def_readonly("bonds", &Topo::bonds) .def_readonly("angles", &Topo::angles) .def_readonly("torsions", &Topo::torsions) .def_readonly("chirs", &Topo::chirs) .def_readonly("planes", &Topo::planes) .def_readonly("extras", &Topo::extras) ; m.def("prepare_topology", &prepare_topology, py::arg("st"), py::arg("monlib"), py::arg("model_index")=0, py::arg("h_change")=HydrogenChange::None, py::arg("reorder")=false, py::arg("raise_errors")=false); } <commit_msg>added missing Topo python bindings<commit_after>// Copyright 2021 Global Phasing Ltd. #include "gemmi/topo.hpp" #include "gemmi/placeh.hpp" // for adjust_hydrogen_distances #include "common.h" #include <pybind11/stl.h> #include <pybind11/stl_bind.h> namespace py = pybind11; using namespace gemmi; PYBIND11_MAKE_OPAQUE(std::vector<Topo::Bond>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Angle>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Torsion>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Chirality>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Plane>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::ExtraLink>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::ChainInfo>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::ResInfo::Prev>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::ResInfo>) PYBIND11_MAKE_OPAQUE(std::vector<Topo::Force>) void add_topo(py::module& m) { py::class_<Topo> topo(m, "Topo"); py::enum_<HydrogenChange>(m, "HydrogenChange") .value("None", HydrogenChange::None) .value("Shift", HydrogenChange::Shift) .value("Remove", HydrogenChange::Remove) .value("ReAdd", HydrogenChange::ReAdd) .value("ReAddButWater", HydrogenChange::ReAddButWater); py::class_<Topo::Bond>(topo, "Bond") .def_readonly("restr", &Topo::Bond::restr) .def_readonly("atoms", &Topo::Bond::atoms) .def("calculate", &Topo::Bond::calculate) .def("calculate_z", &Topo::Bond::calculate_z) ; py::class_<Topo::Angle>(topo, "Angle") .def_readonly("restr", &Topo::Angle::restr) .def_readonly("atoms", &Topo::Angle::atoms) .def("calculate", &Topo::Angle::calculate) .def("calculate_z", &Topo::Angle::calculate_z) ; py::class_<Topo::Torsion>(topo, "Torsion") .def_readonly("restr", &Topo::Torsion::restr) .def_readonly("atoms", &Topo::Torsion::atoms) .def("calculate", &Topo::Torsion::calculate) .def("calculate_z", &Topo::Torsion::calculate_z) ; py::class_<Topo::Chirality>(topo, "Chirality") .def_readonly("restr", &Topo::Chirality::restr) .def_readonly("atoms", &Topo::Chirality::atoms) .def("calculate", &Topo::Chirality::calculate) .def("check", &Topo::Chirality::check) ; py::class_<Topo::Plane>(topo, "Plane") .def_readonly("restr", &Topo::Plane::restr) .def_readonly("atoms", &Topo::Plane::atoms) .def("has", &Topo::Plane::has) ; py::enum_<Topo::Provenance>(m, "Provenance") .value("None", Topo::Provenance::None) .value("PrevLink", Topo::Provenance::PrevLink) .value("Monomer", Topo::Provenance::Monomer) .value("NextLink", Topo::Provenance::NextLink) .value("ExtraLink", Topo::Provenance::ExtraLink) ; py::enum_<Topo::RKind>(m, "RKind") .value("Bond", Topo::RKind::Bond) .value("Angle", Topo::RKind::Angle) .value("Torsion", Topo::RKind::Torsion) .value("Chirality", Topo::RKind::Chirality) .value("Plane", Topo::RKind::Plane) ; py::class_<Topo::Force>(topo, "Force") .def_readonly("provenance", &Topo::Force::provenance) .def_readonly("rkind", &Topo::Force::rkind) .def_readonly("index", &Topo::Force::index) ; py::class_<Topo::ResInfo> resinfo(topo, "ResInfo"); py::class_<Topo::ResInfo::Prev>(resinfo, "Prev") .def_readonly("link", &Topo::ResInfo::Prev::link) .def_readonly("idx", &Topo::ResInfo::Prev::idx) .def("get", (Topo::ResInfo* (Topo::ResInfo::Prev::*)(Topo::ResInfo*)const) &Topo::ResInfo::Prev::get, py::keep_alive<0, 1>()) ; resinfo .def_readonly("res", &Topo::ResInfo::res) .def_readonly("prev", &Topo::ResInfo::prev) .def_readonly("mods", &Topo::ResInfo::mods) .def_readonly("chemcomp", &Topo::ResInfo::chemcomp) .def_readonly("forces", &Topo::ResInfo::forces) ; py::class_<Topo::ChainInfo>(topo, "ChainInfo") .def_readonly("name", &Topo::ChainInfo::name) .def_readonly("entity_id", &Topo::ChainInfo::entity_id) .def_readonly("polymer", &Topo::ChainInfo::polymer) .def_readonly("polymer_type", &Topo::ChainInfo::polymer_type) .def_readonly("res_infos", &Topo::ChainInfo::res_infos) ; py::class_<Topo::ExtraLink>(topo, "ExtraLink") .def_readonly("res1", &Topo::ExtraLink::res1) .def_readonly("res2", &Topo::ExtraLink::res2) .def_readonly("alt1", &Topo::ExtraLink::alt1) .def_readonly("alt2", &Topo::ExtraLink::alt2) .def_readonly("link_id", &Topo::ExtraLink::link_id) ; py::bind_vector<std::vector<Topo::Bond>>(m, "TopoBonds"); py::bind_vector<std::vector<Topo::Angle>>(m, "TopoAngles"); py::bind_vector<std::vector<Topo::Torsion>>(m, "TopoTorsions"); py::bind_vector<std::vector<Topo::Chirality>>(m, "TopoChirs"); py::bind_vector<std::vector<Topo::Plane>>(m, "TopoPlanes"); py::bind_vector<std::vector<Topo::ChainInfo>>(m, "TopoChainInfos"); py::bind_vector<std::vector<Topo::Force>>(m, "TopoForces"); py::bind_vector<std::vector<Topo::ResInfo::Prev>>(m, "TopoResInfoPrevs"); py::bind_vector<std::vector<Topo::ResInfo>>(m, "TopoResInfos"); py::bind_vector<std::vector<Topo::ExtraLink>>(m, "TopoExtraLinks"); topo .def(py::init<>()) .def("adjust_hydrogen_distances", &adjust_hydrogen_distances, py::arg("of"), py::arg("default_scale")=1.) .def_readonly("bonds", &Topo::bonds) .def_readonly("angles", &Topo::angles) .def_readonly("torsions", &Topo::torsions) .def_readonly("chirs", &Topo::chirs) .def_readonly("planes", &Topo::planes) .def_readonly("extras", &Topo::extras) .def_readonly("chain_infos", &Topo::chain_infos) ; m.def("prepare_topology", &prepare_topology, py::arg("st"), py::arg("monlib"), py::arg("model_index")=0, py::arg("h_change")=HydrogenChange::None, py::arg("reorder")=false, py::arg("raise_errors")=false); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include <iostream> #include "tangram.h" #define GLFONTSTASH_IMPLEMENTATION #include "fontstash/glfontstash.h" #define ATLAS_WIDTH 512 #define ATLAS_HEIGHT 512 #define TEXT_BUFFER_SIZE 32 #define ID_OVERFLOW_SIZE TEXT_BUFFER_SIZE * TEXT_BUFFER_SIZE struct userPtr { fsuint bufferId; }; void createTexTransforms(void* _userPtr, unsigned int _width, unsigned int _height) { REQUIRE(_width == TEXT_BUFFER_SIZE); REQUIRE(_height == TEXT_BUFFER_SIZE * 2); } void updateTransforms(void* _userPtr, unsigned int _xoff, unsigned int _yoff, unsigned int _width, unsigned int _height, const unsigned int* _pixels, void* _ownerPtr) { } void updateAtlas(void* _userPtr, unsigned int _xoff, unsigned int _yoff, unsigned int _width, unsigned int _height, const unsigned int* _pixels) { } void createAtlas(void* _userPtr, unsigned int _width, unsigned int _height) { REQUIRE(_width == ATLAS_WIDTH); REQUIRE(_height == ATLAS_HEIGHT); } void errorCallback(void* _userPtr, fsuint buffer, GLFONSError error) { userPtr* ptr = static_cast<userPtr*>(_userPtr); REQUIRE(error == GLFONSError::ID_OVERFLOW); REQUIRE(ptr->bufferId == buffer); } FONScontext* initContext(void* _usrPtr) { GLFONSparams params; params.errorCallback = errorCallback; params.createAtlas = createAtlas; params.createTexTransforms = createTexTransforms; params.updateAtlas = updateAtlas; params.updateTransforms = updateTransforms; return glfonsCreate(ATLAS_WIDTH, ATLAS_HEIGHT, FONS_ZERO_TOPLEFT, params, _usrPtr); } int initFont(FONScontext* _context) { unsigned int dataSize; unsigned char* data = bytesFromResource("Roboto-Regular.ttf", &dataSize); return fonsAddFont(_context, "droid-serif", data, dataSize); } TEST_CASE( "Test context initialization", "[Core][Fontstash][glfonsCreate]" ) { FONScontext* context = initContext(nullptr); REQUIRE(context != NULL); glfonsDelete(context); } TEST_CASE( "Test .ttf file initialization", "[Core][Fontstash][fonsAddFont]" ) { FONScontext* context = initContext(nullptr); int font = initFont(context); REQUIRE(font != FONS_INVALID); glfonsDelete(context); } TEST_CASE( "Test the buffer creation and the size of the required texture transform", "[Core][Fontstash][glfonsBufferCreate]" ) { FONScontext* context = initContext(nullptr); fsuint buffer; glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &buffer); glfonsDelete(context); } TEST_CASE( "Test that the overflow callback gets called for the right overflow size", "[Core][Fontstash][errorCallback]" ) { userPtr p; FONScontext* context = initContext(&p); int font = initFont(context); glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId); glfonsBindBuffer(context, p.bufferId); fonsSetSize(context, 15.0); fonsSetFont(context, font); fsuint id[ID_OVERFLOW_SIZE + 1]; // create an overflow glfonsGenText(context, ID_OVERFLOW_SIZE + 1, id); glfonsDelete(context); } <commit_msg>unit tests<commit_after>#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include <iostream> #include <vector> #include "tangram.h" #define GLFONTSTASH_IMPLEMENTATION #include "fontstash/glfontstash.h" #define ATLAS_WIDTH 512 #define ATLAS_HEIGHT 512 #define TEXT_BUFFER_SIZE 32 #define ID_OVERFLOW_SIZE TEXT_BUFFER_SIZE * TEXT_BUFFER_SIZE struct userPtr { fsuint bufferId; }; void createTexTransforms(void* _userPtr, unsigned int _width, unsigned int _height) { REQUIRE(_width == TEXT_BUFFER_SIZE); REQUIRE(_height == TEXT_BUFFER_SIZE * 2); } void updateTransforms(void* _userPtr, unsigned int _xoff, unsigned int _yoff, unsigned int _width, unsigned int _height, const unsigned int* _pixels, void* _ownerPtr) { } void updateAtlas(void* _userPtr, unsigned int _xoff, unsigned int _yoff, unsigned int _width, unsigned int _height, const unsigned int* _pixels) { } void createAtlas(void* _userPtr, unsigned int _width, unsigned int _height) { REQUIRE(_width == ATLAS_WIDTH); REQUIRE(_height == ATLAS_HEIGHT); } void errorCallback(void* _userPtr, fsuint buffer, GLFONSError error) { userPtr* ptr = static_cast<userPtr*>(_userPtr); REQUIRE(error == GLFONSError::ID_OVERFLOW); REQUIRE(ptr->bufferId == buffer); } FONScontext* initContext(void* _usrPtr) { GLFONSparams params; params.errorCallback = errorCallback; params.createAtlas = createAtlas; params.createTexTransforms = createTexTransforms; params.updateAtlas = updateAtlas; params.updateTransforms = updateTransforms; return glfonsCreate(ATLAS_WIDTH, ATLAS_HEIGHT, FONS_ZERO_TOPLEFT, params, _usrPtr); } int initFont(FONScontext* _context) { unsigned int dataSize; unsigned char* data = bytesFromResource("Roboto-Regular.ttf", &dataSize); return fonsAddFont(_context, "droid-serif", data, dataSize); } TEST_CASE( "Test context initialization", "[Core][Fontstash][glfonsCreate]" ) { FONScontext* context = initContext(nullptr); REQUIRE(context != NULL); glfonsDelete(context); } TEST_CASE( "Test .ttf file initialization", "[Core][Fontstash][fonsAddFont]" ) { FONScontext* context = initContext(nullptr); int font = initFont(context); REQUIRE(font != FONS_INVALID); glfonsDelete(context); } TEST_CASE( "Test the buffer creation and the size of the required texture transform", "[Core][Fontstash][glfonsBufferCreate]" ) { FONScontext* context = initContext(nullptr); fsuint buffer; glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &buffer); glfonsDelete(context); } TEST_CASE( "Test that the overflow callback gets called for the right overflow size", "[Core][Fontstash][errorCallback]" ) { userPtr p; FONScontext* context = initContext(&p); int font = initFont(context); glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId); glfonsBindBuffer(context, p.bufferId); fsuint id[ID_OVERFLOW_SIZE + 1]; // create an overflow glfonsGenText(context, ID_OVERFLOW_SIZE + 1, id); glfonsDelete(context); } TEST_CASE( "Test that the number of vertices correspond to the logic", "[Core][Fontstash][glfonsVertices]" ) { userPtr p; FONScontext* context = initContext(&p); int font = initFont(context); glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId); glfonsBindBuffer(context, p.bufferId); fonsSetSize(context, 15.0); fonsSetFont(context, font); fsuint id; glfonsGenText(context, 1, &id); std::string text("tangram"); glfonsRasterize(context, id, text.c_str(), FONS_EFFECT_NONE); std::vector<float> vertices; int nverts = 0; glfonsVertices(context, &vertices, &nverts); REQUIRE(nverts == text.size() * 6); // shoud have 6 vertices per glyph glfonsDelete(context); } <|endoftext|>
<commit_before>/* Hume Library Copyright (C) 2015 Marshall Clyburn This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Window.h" namespace hume { Window::Window() : window(nullptr), renderer(nullptr) { } Window::~Window() { if(window) destroy(); } void Window::create() { window = SDL_CreateWindow(settings.title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, settings.width, settings.height, 0); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!window) throw SDLException(); if(!renderer) throw SDLException(); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); return; } void Window::destroy() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); window = nullptr; renderer = nullptr; return; } void Window::apply(WindowSettings& w) { // update the window based on what's changed if(settings.fullscreen != w.fullscreen) { settings.fullscreen = w.fullscreen; if(window) { if(settings.fullscreen) SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); else SDL_SetWindowFullscreen(window, 0); } } if(settings.title.compare(w.title) != 0) { settings.title = w.title; if(window) SDL_SetWindowTitle(window, settings.title.c_str()); } if(settings.width != w.width || settings.height != w.height) { // go ahead and assign the resolution, followed by a resize settings.width = w.width; settings.height = w.height; if(window) SDL_SetWindowSize(window, settings.width, settings.height); } return; } WindowSettings Window::get_settings() const { return settings; } SDL_Window* Window::get_window() { return window; } SDL_Renderer* Window::get_renderer() { return renderer; } void Window::draw(const Blittable* const b, const Properties& p) { SDL_Rect r; r.x = p.x; r.y = p.y; // use the default width and height if not specified if(p.w == 0 || p.h == 0) { r.w = b->get_width(); r.h = b->get_height(); } else // provided width and height { r.w = p.w; r.h = p.h; } if(p.sw == 0 || p.sh == 0) // use entire blittable SDL_RenderCopy(renderer, b->get_texture(), nullptr, &r); else // use specified portion { SDL_Rect s; s.x = p.sx; s.y = p.sy; s.w = p.sw; s.h = p.sh; SDL_RenderCopy(renderer, b->get_texture(), &s, &r); } return; } void Window::present() { SDL_RenderPresent(renderer); } void Window::clear() { SDL_RenderClear(renderer); return; } } <commit_msg>Add Exception-throwing to Window.<commit_after>/* Hume Library Copyright (C) 2015 Marshall Clyburn This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Window.h" namespace hume { Window::Window() : window(nullptr), renderer(nullptr) { } Window::~Window() { if(window) destroy(); } void Window::create() { window = SDL_CreateWindow(settings.title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, settings.width, settings.height, 0); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!window) throw SDLException(); if(!renderer) throw SDLException(); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); return; } void Window::destroy() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); window = nullptr; renderer = nullptr; return; } void Window::apply(WindowSettings& w) { // update the window based on what's changed if(settings.fullscreen != w.fullscreen) { settings.fullscreen = w.fullscreen; if(window) { int sdl_result; if(settings.fullscreen) sdl_result = SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); else sdl_result = SDL_SetWindowFullscreen(window, 0); if(sdl_result != 0) throw SDLException(); } } if(settings.title.compare(w.title) != 0) { settings.title = w.title; if(window) SDL_SetWindowTitle(window, settings.title.c_str()); } if(settings.width != w.width || settings.height != w.height) { // go ahead and assign the resolution, followed by a resize settings.width = w.width; settings.height = w.height; if(window) SDL_SetWindowSize(window, settings.width, settings.height); } return; } WindowSettings Window::get_settings() const { return settings; } SDL_Window* Window::get_window() { return window; } SDL_Renderer* Window::get_renderer() { return renderer; } void Window::draw(const Blittable* const b, const Properties& p) { SDL_Rect r; r.x = p.x; r.y = p.y; // use the default width and height if not specified if(p.w == 0 || p.h == 0) { r.w = b->get_width(); r.h = b->get_height(); } else // provided width and height { r.w = p.w; r.h = p.h; } int sdl_result; if(p.sw == 0 || p.sh == 0) // use entire blittable sdl_result = SDL_RenderCopy(renderer, b->get_texture(), nullptr, &r); else // use specified portion { SDL_Rect s; s.x = p.sx; s.y = p.sy; s.w = p.sw; s.h = p.sh; sdl_result = SDL_RenderCopy(renderer, b->get_texture(), &s, &r); } if(sdl_result != 0) throw SDLException(); return; } void Window::present() { SDL_RenderPresent(renderer); } void Window::clear() { if(SDL_RenderClear(renderer) != 0) throw SDLException(); return; } } <|endoftext|>
<commit_before>#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <QTextStream> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bbsupport/Keyboard> #include <bbsupport/Notification> #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); // Setup the initial font font = new QFont(); font->setStyleHint(QFont::Courier);//QFont::TypeWriter); font->setPointSize(12); font->setStyleStrategy(QFont::NoAntialias); font->setFamily("Monospace"); font->setFixedPitch(true); font->setKerning(false); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value QFontMetrics metrics(*font); char_width = metrics.maxWidth(); if(char_width==0) { fontWorkAround = true; char_width = metrics.width(QChar('X')); } char_height = metrics.lineSpacing(); #ifdef __QNX__ BlackBerry::Keyboard::instance().show(); #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { int coord_x; cursor_on ^= 1; if (fontWorkAround) { // The update region may not be quite monospaced. int i; char str[WIDTH]; const uint32_t **grid; QFontMetrics metrics(*font); grid = term_get_grid( terminal ); for (i=0;i < WIDTH; i++) { str[i] = grid[cursor_y][i]; } coord_x = metrics.width( QString(str),cursor_x ); } else { coord_x = cursor_x * char_width; } update( coord_x, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); char str[WIDTH+1]; int cursor_x_coord; QColor fgColor(255,255,255); QColor bgColor(0,0,0); int maxX=0; painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont( *font ); // First erase the grid with its current dimensions painter.drawRect(event->rect()); int x,y,w,h; event->rect().getRect(&x, &y, &w, &h); //fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); if (cursor_x < 0 || cursor_y < 0) { return; } #if 1 // Brute force convesion for(j=0;j<WIDTH;j++) { str[j]=grid[cursor_y][j]; } // Workaround to get the cursor in the right spot. For some // reason, on OSX (again), the monospace font does is not really // monospace for skinny characters! if (fontWorkAround) { cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x); } else { cursor_x_coord = cursor_x * char_width; } if ( cursor_on ) { painter.setPen(fgColor); painter.setBrush(fgColor); painter.drawRect( cursor_x_coord +1, cursor_y * char_height + 1, char_width-2, char_height-2); } else { painter.setPen(bgColor); painter.setBrush(bgColor); painter.drawRect( cursor_x_coord +1, cursor_y * char_height + 1, char_width-2, char_height-2); } painter.setPen(fgColor); painter.setBrush(fgColor); for (i=0; i<term_get_height( terminal );i++) { // Brute force convesion to 8-bit UTF for( j=0; j< term_get_width( terminal ); j++) { str[j]=grid[i][j]; } str[WIDTH]=0; painter.drawText(0, (i) * char_height, w, char_height, Qt::TextExpandTabs, str, NULL ); } #else painter.setBrush(fgColor); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } #endif } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } } <commit_msg>Fix a couple uses of uninitialized variables. This fixes the crash I was seeing, and the descent problem<commit_after>#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <QTextStream> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bbsupport/Keyboard> #include <bbsupport/Notification> #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); // Setup the initial font font = new QFont(); font->setStyleHint(QFont::Courier);//QFont::TypeWriter); font->setPointSize(12); font->setStyleStrategy(QFont::NoAntialias); font->setFamily("Monospace"); font->setFixedPitch(true); font->setKerning(false); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value QFontMetrics metrics(*font); char_width = metrics.maxWidth(); if(char_width==0) { fontWorkAround = true; char_width = metrics.width(QChar('X')); } else { fontWorkAround = false; } char_height = metrics.lineSpacing(); char_descent = metrics.descent(); #ifdef __QNX__ BlackBerry::Keyboard::instance().show(); #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { int coord_x; cursor_on ^= 1; if (fontWorkAround) { // The update region may not be quite monospaced. int i; char str[WIDTH]; const uint32_t **grid; QFontMetrics metrics(*font); grid = term_get_grid( terminal ); for (i=0;i < WIDTH; i++) { str[i] = grid[cursor_y][i]; } coord_x = metrics.width( QString(str),cursor_x ); } else { coord_x = cursor_x * char_width; } update( coord_x, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); char str[WIDTH+1]; int cursor_x_coord; QColor fgColor(255,255,255); QColor bgColor(0,0,0); int maxX=0; painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont( *font ); // First erase the grid with its current dimensions painter.drawRect(event->rect()); int x,y,w,h; event->rect().getRect(&x, &y, &w, &h); //fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); if (cursor_x < 0 || cursor_y < 0) { return; } #if 1 // Brute force convesion for(j=0;j<WIDTH;j++) { str[j]=grid[cursor_y][j]; } // Workaround to get the cursor in the right spot. For some // reason, on OSX (again), the monospace font does is not really // monospace for skinny characters! if (fontWorkAround) { cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x); } else { cursor_x_coord = cursor_x * char_width; } if ( cursor_on ) { painter.setPen(fgColor); painter.setBrush(fgColor); painter.drawRect( cursor_x_coord +1, cursor_y * char_height + 1, char_width-2, char_height-2); } else { painter.setPen(bgColor); painter.setBrush(bgColor); painter.drawRect( cursor_x_coord +1, cursor_y * char_height + 1, char_width-2, char_height-2); } painter.setPen(fgColor); painter.setBrush(fgColor); for (i=0; i<term_get_height( terminal );i++) { // Brute force convesion to 8-bit UTF for( j=0; j< term_get_width( terminal ); j++) { str[j]=grid[i][j]; } str[WIDTH]=0; painter.drawText(0, (i) * char_height, w, char_height, Qt::TextExpandTabs, str, NULL ); } #else painter.setBrush(fgColor); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } #endif } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #include <seastar/core/metrics.hh> #include <seastar/core/metrics_api.hh> #include <seastar/core/reactor.hh> #include <boost/range/algorithm.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm_ext/erase.hpp> namespace seastar { namespace metrics { double_registration::double_registration(std::string what): std::runtime_error(what) {} metric_groups::metric_groups() noexcept : _impl(impl::create_metric_groups()) { } void metric_groups::clear() { _impl = impl::create_metric_groups(); } metric_groups::metric_groups(std::initializer_list<metric_group_definition> mg) : _impl(impl::create_metric_groups()) { for (auto&& i : mg) { add_group(i.name, i.metrics); } } metric_groups& metric_groups::add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_groups& metric_groups::add_group(const group_name_type& name, const std::vector<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_group::metric_group() noexcept = default; metric_group::~metric_group() = default; metric_group::metric_group(const group_name_type& name, std::initializer_list<metric_definition> l) { add_group(name, l); } metric_group_definition::metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l) : name(name), metrics(l) { } metric_group_definition::~metric_group_definition() = default; metric_groups::~metric_groups() = default; metric_definition::metric_definition(metric_definition&& m) noexcept : _impl(std::move(m._impl)) { } metric_definition::~metric_definition() = default; metric_definition::metric_definition(impl::metric_definition_impl const& m) noexcept : _impl(std::make_unique<impl::metric_definition_impl>(m)) { } bool label_instance::operator<(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) < std::tie(id2.key(), id2.value()); } bool label_instance::operator==(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) == std::tie(id2.key(), id2.value()); } static std::string get_hostname() { char hostname[PATH_MAX]; gethostname(hostname, sizeof(hostname)); hostname[PATH_MAX-1] = '\0'; return hostname; } options::options(program_options::option_group* parent_group) : program_options::option_group(parent_group, "Metrics options") , metrics_hostname(*this, "metrics-hostname", get_hostname(), "set the hostname used by the metrics, if not set, the local hostname will be used") { } future<> configure(const options& opts) { impl::config c; c.hostname = opts.metrics_hostname.get_value(); return smp::invoke_on_all([c] { impl::get_local_impl()->set_config(c); }); } bool label_instance::operator!=(const label_instance& id2) const { auto& id1 = *this; return !(id1 == id2); } label shard_label("shard"); namespace impl { registered_metric::registered_metric(metric_id id, metric_function f, bool enabled) : _f(f), _impl(get_local_impl()) { _info.enabled = enabled; _info.id = id; } metric_value metric_value::operator+(const metric_value& c) { metric_value res(*this); switch (_type) { case data_type::HISTOGRAM: std::get<histogram>(res.u) += std::get<histogram>(c.u); break; default: std::get<double>(res.u) += std::get<double>(c.u); break; } return res; } void metric_value::ulong_conversion_error(double d) { throw std::range_error(format("cannot convert double value {} to unsigned long", d)); } metric_definition_impl::metric_definition_impl( metric_name_type name, metric_type type, metric_function f, description d, std::vector<label_instance> _labels) : name(name), type(type), f(f) , d(d), enabled(true) { for (auto i: _labels) { labels[i.key()] = i.value(); } if (labels.find(shard_label.name()) == labels.end()) { labels[shard_label.name()] = shard(); } } metric_definition_impl& metric_definition_impl::operator ()(bool _enabled) { enabled = _enabled; return *this; } metric_definition_impl& metric_definition_impl::operator ()(const label_instance& label) { labels[label.key()] = label.value(); return *this; } metric_definition_impl& metric_definition_impl::set_type(const sstring& type_name) { type.type_name = type_name; return *this; } std::unique_ptr<metric_groups_def> create_metric_groups() { return std::make_unique<metric_groups_impl>(); } metric_groups_impl::~metric_groups_impl() { for (const auto& i : _registration) { unregister_metric(i); } } metric_groups_impl& metric_groups_impl::add_metric(group_name_type name, const metric_definition& md) { metric_id id(name, md._impl->name, md._impl->labels); get_local_impl()->add_registration(id, md._impl->type, md._impl->f, md._impl->d, md._impl->enabled); _registration.push_back(id); return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::vector<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *(i->_impl.get())); } return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::initializer_list<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *i); } return *this; } bool metric_id::operator<( const metric_id& id2) const { return as_tuple() < id2.as_tuple(); } static std::string safe_name(const sstring& name) { auto rep = boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_"); boost::remove_erase_if(rep, boost::is_any_of("+()")); return rep; } sstring metric_id::full_name() const { return safe_name(_group + "_" + _name); } bool metric_id::operator==( const metric_id & id2) const { return as_tuple() == id2.as_tuple(); } // Unfortunately, metrics_impl can not be shared because it // need to be available before the first users (reactor) will call it shared_ptr<impl> get_local_impl() { static thread_local auto the_impl = ::seastar::make_shared<impl>(); return the_impl; } void impl::remove_registration(const metric_id& id) { auto i = get_value_map().find(id.full_name()); if (i != get_value_map().end()) { auto j = i->second.find(id.labels()); if (j != i->second.end()) { j->second = nullptr; i->second.erase(j); } if (i->second.empty()) { get_value_map().erase(i); } dirty(); } } void unregister_metric(const metric_id & id) { get_local_impl()->remove_registration(id); } const value_map& get_value_map() { return get_local_impl()->get_value_map(); } foreign_ptr<values_reference> get_values() { shared_ptr<values_copy> res_ref = ::seastar::make_shared<values_copy>(); auto& res = *(res_ref.get()); auto& mv = res.values; res.metadata = get_local_impl()->metadata(); auto & functions = get_local_impl()->functions(); mv.reserve(functions.size()); for (auto&& i : functions) { value_vector values; values.reserve(i.size()); for (auto&& v : i) { values.emplace_back(v()); } mv.emplace_back(std::move(values)); } return res_ref; } instance_id_type shard() { if (engine_is_ready()) { return to_sstring(this_shard_id()); } return sstring("0"); } void impl::update_metrics_if_needed() { if (_dirty) { // Forcing the metadata to an empty initialization // Will prevent using corrupted data if an exception is thrown _metadata = ::seastar::make_shared<metric_metadata>(); auto mt_ref = ::seastar::make_shared<metric_metadata>(); auto &mt = *(mt_ref.get()); mt.reserve(_value_map.size()); _current_metrics.resize(_value_map.size()); size_t i = 0; for (auto&& mf : _value_map) { metric_metadata_vector metrics; _current_metrics[i].clear(); for (auto&& m : mf.second) { if (m.second && m.second->is_enabled()) { metrics.emplace_back(m.second->info()); _current_metrics[i].emplace_back(m.second->get_function()); } } if (!metrics.empty()) { // If nothing was added, no need to add the metric_family // and no need to progress mt.emplace_back(metric_family_metadata{mf.second.info(), std::move(metrics)}); i++; } } // Maybe we didn't use all the original size _current_metrics.resize(i); _metadata = mt_ref; _dirty = false; } } shared_ptr<metric_metadata> impl::metadata() { update_metrics_if_needed(); return _metadata; } std::vector<std::vector<metric_function>>& impl::functions() { update_metrics_if_needed(); return _current_metrics; } void impl::add_registration(const metric_id& id, const metric_type& type, metric_function f, const description& d, bool enabled) { auto rm = ::seastar::make_shared<registered_metric>(id, f, enabled); sstring name = id.full_name(); if (_value_map.find(name) != _value_map.end()) { auto& metric = _value_map[name]; if (metric.find(id.labels()) != metric.end()) { throw double_registration("registering metrics twice for metrics: " + name); } if (metric.info().type != type.base_type) { throw std::runtime_error("registering metrics " + name + " registered with different type."); } metric[id.labels()] = rm; } else { _value_map[name].info().type = type.base_type; _value_map[name].info().d = d; _value_map[name].info().inherit_type = type.type_name; _value_map[name].info().name = id.full_name(); _value_map[name][id.labels()] = rm; } dirty(); } } const bool metric_disabled = false; histogram& histogram::operator+=(const histogram& c) { for (size_t i = 0; i < c.buckets.size(); i++) { if (buckets.size() <= i) { buckets.push_back(c.buckets[i]); } else { if (buckets[i].upper_bound != c.buckets[i].upper_bound) { throw std::out_of_range("Trying to add histogram with different bucket limits"); } buckets[i].count += c.buckets[i].count; } } return *this; } histogram histogram::operator+(const histogram& c) const { histogram res = *this; res += c; return res; } histogram histogram::operator+(histogram&& c) const { c += *this; return std::move(c); } } } <commit_msg>metrics.cc: missing count and sum when aggregating histograms<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #include <seastar/core/metrics.hh> #include <seastar/core/metrics_api.hh> #include <seastar/core/reactor.hh> #include <boost/range/algorithm.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm_ext/erase.hpp> namespace seastar { namespace metrics { double_registration::double_registration(std::string what): std::runtime_error(what) {} metric_groups::metric_groups() noexcept : _impl(impl::create_metric_groups()) { } void metric_groups::clear() { _impl = impl::create_metric_groups(); } metric_groups::metric_groups(std::initializer_list<metric_group_definition> mg) : _impl(impl::create_metric_groups()) { for (auto&& i : mg) { add_group(i.name, i.metrics); } } metric_groups& metric_groups::add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_groups& metric_groups::add_group(const group_name_type& name, const std::vector<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_group::metric_group() noexcept = default; metric_group::~metric_group() = default; metric_group::metric_group(const group_name_type& name, std::initializer_list<metric_definition> l) { add_group(name, l); } metric_group_definition::metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l) : name(name), metrics(l) { } metric_group_definition::~metric_group_definition() = default; metric_groups::~metric_groups() = default; metric_definition::metric_definition(metric_definition&& m) noexcept : _impl(std::move(m._impl)) { } metric_definition::~metric_definition() = default; metric_definition::metric_definition(impl::metric_definition_impl const& m) noexcept : _impl(std::make_unique<impl::metric_definition_impl>(m)) { } bool label_instance::operator<(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) < std::tie(id2.key(), id2.value()); } bool label_instance::operator==(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) == std::tie(id2.key(), id2.value()); } static std::string get_hostname() { char hostname[PATH_MAX]; gethostname(hostname, sizeof(hostname)); hostname[PATH_MAX-1] = '\0'; return hostname; } options::options(program_options::option_group* parent_group) : program_options::option_group(parent_group, "Metrics options") , metrics_hostname(*this, "metrics-hostname", get_hostname(), "set the hostname used by the metrics, if not set, the local hostname will be used") { } future<> configure(const options& opts) { impl::config c; c.hostname = opts.metrics_hostname.get_value(); return smp::invoke_on_all([c] { impl::get_local_impl()->set_config(c); }); } bool label_instance::operator!=(const label_instance& id2) const { auto& id1 = *this; return !(id1 == id2); } label shard_label("shard"); namespace impl { registered_metric::registered_metric(metric_id id, metric_function f, bool enabled) : _f(f), _impl(get_local_impl()) { _info.enabled = enabled; _info.id = id; } metric_value metric_value::operator+(const metric_value& c) { metric_value res(*this); switch (_type) { case data_type::HISTOGRAM: std::get<histogram>(res.u) += std::get<histogram>(c.u); break; default: std::get<double>(res.u) += std::get<double>(c.u); break; } return res; } void metric_value::ulong_conversion_error(double d) { throw std::range_error(format("cannot convert double value {} to unsigned long", d)); } metric_definition_impl::metric_definition_impl( metric_name_type name, metric_type type, metric_function f, description d, std::vector<label_instance> _labels) : name(name), type(type), f(f) , d(d), enabled(true) { for (auto i: _labels) { labels[i.key()] = i.value(); } if (labels.find(shard_label.name()) == labels.end()) { labels[shard_label.name()] = shard(); } } metric_definition_impl& metric_definition_impl::operator ()(bool _enabled) { enabled = _enabled; return *this; } metric_definition_impl& metric_definition_impl::operator ()(const label_instance& label) { labels[label.key()] = label.value(); return *this; } metric_definition_impl& metric_definition_impl::set_type(const sstring& type_name) { type.type_name = type_name; return *this; } std::unique_ptr<metric_groups_def> create_metric_groups() { return std::make_unique<metric_groups_impl>(); } metric_groups_impl::~metric_groups_impl() { for (const auto& i : _registration) { unregister_metric(i); } } metric_groups_impl& metric_groups_impl::add_metric(group_name_type name, const metric_definition& md) { metric_id id(name, md._impl->name, md._impl->labels); get_local_impl()->add_registration(id, md._impl->type, md._impl->f, md._impl->d, md._impl->enabled); _registration.push_back(id); return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::vector<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *(i->_impl.get())); } return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::initializer_list<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *i); } return *this; } bool metric_id::operator<( const metric_id& id2) const { return as_tuple() < id2.as_tuple(); } static std::string safe_name(const sstring& name) { auto rep = boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_"); boost::remove_erase_if(rep, boost::is_any_of("+()")); return rep; } sstring metric_id::full_name() const { return safe_name(_group + "_" + _name); } bool metric_id::operator==( const metric_id & id2) const { return as_tuple() == id2.as_tuple(); } // Unfortunately, metrics_impl can not be shared because it // need to be available before the first users (reactor) will call it shared_ptr<impl> get_local_impl() { static thread_local auto the_impl = ::seastar::make_shared<impl>(); return the_impl; } void impl::remove_registration(const metric_id& id) { auto i = get_value_map().find(id.full_name()); if (i != get_value_map().end()) { auto j = i->second.find(id.labels()); if (j != i->second.end()) { j->second = nullptr; i->second.erase(j); } if (i->second.empty()) { get_value_map().erase(i); } dirty(); } } void unregister_metric(const metric_id & id) { get_local_impl()->remove_registration(id); } const value_map& get_value_map() { return get_local_impl()->get_value_map(); } foreign_ptr<values_reference> get_values() { shared_ptr<values_copy> res_ref = ::seastar::make_shared<values_copy>(); auto& res = *(res_ref.get()); auto& mv = res.values; res.metadata = get_local_impl()->metadata(); auto & functions = get_local_impl()->functions(); mv.reserve(functions.size()); for (auto&& i : functions) { value_vector values; values.reserve(i.size()); for (auto&& v : i) { values.emplace_back(v()); } mv.emplace_back(std::move(values)); } return res_ref; } instance_id_type shard() { if (engine_is_ready()) { return to_sstring(this_shard_id()); } return sstring("0"); } void impl::update_metrics_if_needed() { if (_dirty) { // Forcing the metadata to an empty initialization // Will prevent using corrupted data if an exception is thrown _metadata = ::seastar::make_shared<metric_metadata>(); auto mt_ref = ::seastar::make_shared<metric_metadata>(); auto &mt = *(mt_ref.get()); mt.reserve(_value_map.size()); _current_metrics.resize(_value_map.size()); size_t i = 0; for (auto&& mf : _value_map) { metric_metadata_vector metrics; _current_metrics[i].clear(); for (auto&& m : mf.second) { if (m.second && m.second->is_enabled()) { metrics.emplace_back(m.second->info()); _current_metrics[i].emplace_back(m.second->get_function()); } } if (!metrics.empty()) { // If nothing was added, no need to add the metric_family // and no need to progress mt.emplace_back(metric_family_metadata{mf.second.info(), std::move(metrics)}); i++; } } // Maybe we didn't use all the original size _current_metrics.resize(i); _metadata = mt_ref; _dirty = false; } } shared_ptr<metric_metadata> impl::metadata() { update_metrics_if_needed(); return _metadata; } std::vector<std::vector<metric_function>>& impl::functions() { update_metrics_if_needed(); return _current_metrics; } void impl::add_registration(const metric_id& id, const metric_type& type, metric_function f, const description& d, bool enabled) { auto rm = ::seastar::make_shared<registered_metric>(id, f, enabled); sstring name = id.full_name(); if (_value_map.find(name) != _value_map.end()) { auto& metric = _value_map[name]; if (metric.find(id.labels()) != metric.end()) { throw double_registration("registering metrics twice for metrics: " + name); } if (metric.info().type != type.base_type) { throw std::runtime_error("registering metrics " + name + " registered with different type."); } metric[id.labels()] = rm; } else { _value_map[name].info().type = type.base_type; _value_map[name].info().d = d; _value_map[name].info().inherit_type = type.type_name; _value_map[name].info().name = id.full_name(); _value_map[name][id.labels()] = rm; } dirty(); } } const bool metric_disabled = false; histogram& histogram::operator+=(const histogram& c) { for (size_t i = 0; i < c.buckets.size(); i++) { if (buckets.size() <= i) { buckets.push_back(c.buckets[i]); } else { if (buckets[i].upper_bound != c.buckets[i].upper_bound) { throw std::out_of_range("Trying to add histogram with different bucket limits"); } buckets[i].count += c.buckets[i].count; } } sample_count += c.sample_count; sample_sum += c.sample_sum; return *this; } histogram histogram::operator+(const histogram& c) const { histogram res = *this; res += c; return res; } histogram histogram::operator+(histogram&& c) const { c += *this; return std::move(c); } } } <|endoftext|>
<commit_before>/* CUBE demo toolkit by MasterM/Asenses */ #include <stdafx.h> #include <core/system.h> #include <core/config.h> #include <core/ui.h> #include <utils/notify.h> #ifdef _DEBUG #include <assimp/DefaultLogger.hpp> #endif using namespace CUBE; class Core::System* CUBE::System = nullptr; class Core::Config* CUBE::Config = nullptr; class Core::UI* CUBE::UI = nullptr; using namespace CUBE::Core; System::System() : UI(nullptr), NotifyService(nullptr), paused(false), window(NULL), stream(NULL) { strcpy_s<100>(name, "CUBE"); } Core::System* System::Instance() { static System _this; return &_this; } void System::KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { #ifdef _DEBUG if(mods & GLFW_MOD_SHIFT) #endif glfwSetWindowShouldClose(window, GL_TRUE); return; } #ifdef _DEBUG switch(key) { case GLFW_KEY_F1: if(action == GLFW_PRESS) System::Instance()->ToggleUI(); return; case GLFW_KEY_F2: if(action == GLFW_PRESS) System::Instance()->ArrangeUI(PlacementMode::Horizontal); return; case GLFW_KEY_F3: if(action == GLFW_PRESS) System::Instance()->ArrangeUI(PlacementMode::Vertical); return; case GLFW_KEY_SPACE: if(action == GLFW_PRESS) System::Instance()->TogglePlayback(); return; case GLFW_KEY_S: if(mods & GLFW_MOD_CONTROL && action == GLFW_PRESS) { CUBE::Config->Write(); return; } break; case GLFW_KEY_LEFT: if(mods & GLFW_MOD_CONTROL) { if(action == GLFW_PRESS || action == GLFW_REPEAT) System::Instance()->Seek(-0.5f); return; } break; case GLFW_KEY_RIGHT: if(mods & GLFW_MOD_CONTROL) { if(action == GLFW_PRESS || action == GLFW_REPEAT) System::Instance()->Seek(0.5f); return; } break; } ((TweakBarUI*)System::Instance()->UI)->TranslateKeyEvent(key, action); #endif } void System::UpdateDebugInfo() { static double lastTime = 0.0; double time = glfwGetTime(); if((time - lastTime) >= 0.1) { char debugInfo[256]; std::string sceneName; if(!DebugInfo.SceneName.empty()) sceneName = DebugInfo.SceneName + ": "; lastTime = time; sprintf_s(debugInfo, "%s [ %s%05.1fs ] %s", name, sceneName.c_str(), System::GetTime(), paused?"(paused)":""); glfwSetWindowTitle(window, debugInfo); } } void System::Init() { std::setlocale(LC_ALL, "en_US.UTF-8"); strcpy_s<100>(System::name, "CUBE"); #ifdef _DEBUG AllocConsole(); SetConsoleTitleA("Debug Console"); CUBE::Config = new ConfigRW(); Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE); #else CUBE::Config = new Config(); #endif if(!glfwInit()) { System::Error("Failed to initialize GLFW library."); ExitProcess(1); } if(!BASS_Init(-1, 44100, 0, 0, NULL)) { System::Error("Failed to initialize BASS library."); glfwTerminate(); ExitProcess(1); } ilInit(); CUBE::System = this; System::Log("CUBE demo toolkit initialized.\n"); } void System::Terminate() { BASS_Stop(); BASS_Free(); delete NotifyService; delete CUBE::UI; delete CUBE::Config; glfwTerminate(); System::Log("CUBE demo toolkit terminated.\n"); #ifdef _DEBUG Assimp::DefaultLogger::kill(); FreeConsole(); #endif } void System::UseOpenGL(const int major, const int minor) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } void System::OpenStream(const char* path) { if(path) stream = BASS_StreamCreateFile(FALSE, path, 0, 0, BASS_STREAM_PRESCAN); else stream = BASS_StreamCreate(44100, 2, 0, STREAMPROC_DUMMY, NULL); if(!stream) { System::Error("Failed to open stream."); System::Terminate(); ExitProcess(1); } System::Log("Opened stream: %s\n", path?path:"(dummy)"); } void System::OpenDisplay(const int width, const int height, bool fullscreen) { glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(width, height, name, NULL, NULL); if(!window) { System::Error("Failed to initialize OpenGL context."); System::Terminate(); ExitProcess(1); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, System::KeyCallback); glewExperimental = GL_TRUE; glewInit(); System::Log("Opened display: OpenGL %s (%dx%d)\n", glGetString(GL_VERSION), width, height); System::Log("Renderer: %s %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER)); #ifdef _DEBUG System::UI = new Core::TweakBarUI(window, width, height); System::Log("Debug GUI initialized.\n"); #else System::UI = new Core::NullUI(); #endif CUBE::UI = System::UI; ClearErrorGL(); SetDefaults(); } void System::SetName(const char* name) { strcpy_s<100>(System::name, name); } float System::GetTime() { return (float)BASS_ChannelBytes2Seconds(stream, BASS_ChannelGetPosition(stream, BASS_POS_BYTE)); } void System::Run(RenderBlock renderFunction) { BASS_ChannelPlay(stream, TRUE); while(!glfwWindowShouldClose(window)) { if(!renderFunction(GetTime())) break; UI->Draw(); #ifdef _DEBUG System::UpdateDebugInfo(); if(NotifyService) NotifyService->ProcessEvents(); #endif glfwSwapBuffers(window); glfwPollEvents(); } } void System::Error(const char* error) { MessageBoxA(NULL, error, "CUBE", MB_ICONSTOP | MB_OK); } void System::Log(const char* fmt, ...) { const size_t BUFSIZE = 8192; char buffer[BUFSIZE]; va_list args; va_start(args, fmt); vsnprintf_s(buffer, BUFSIZE, fmt, args); va_end(args); DWORD written; WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), buffer, strlen(buffer), &written, NULL); } void System::GetDisplaySize(int& w, int& h) { glfwGetFramebufferSize(window, &w, &h); } float System::GetDisplayAspect() { int w, h; glfwGetFramebufferSize(window, &w, &h); return float(w)/float(h); } void System::TogglePlayback() { if(paused) { BASS_ChannelPlay(stream, FALSE); paused = false; } else { BASS_ChannelPause(stream); paused = true; } } void System::ToggleUI() { UI->Toggle(); } void System::ArrangeUI(PlacementMode placement) { if(UI->IsActive()) { UI->Placement = placement; UI->Arrange(); } } void System::Seek(const float delta) { double position = BASS_ChannelBytes2Seconds(stream, BASS_ChannelGetPosition(stream, BASS_POS_BYTE)); position += double(delta); BASS_ChannelSetPosition(stream, BASS_ChannelSeconds2Bytes(stream, position), BASS_POS_BYTE); } bool System::SetContentDirectory(const std::string& path) { #ifdef _DEBUG if(NotifyService) return false; NotifyService = new FileNotify(path); #endif contentDirectory = path; return true; } const std::string& System::GetContentDirectory() const { return contentDirectory; } void System::Debug_SetSceneName(const char* name) const { #ifdef _DEBUG DebugInfo.SceneName = std::string(name); #endif } void System::HandleException(const std::exception& e) { std::string message(e.what()); try { BASS_Stop(); } catch(const std::exception&) {}; #ifdef _DEBUG message.append("\nDo you want to debug?"); if(MessageBoxA(NULL, message.c_str(), "CUBE [Exception]", MB_ICONSTOP | MB_YESNO) == IDYES) throw; #else MessageBoxA(NULL, message.c_str(), "CUBE [Exception]", MB_ICONSTOP | MB_OK); #endif } void System::ClearErrorGL() { while(glGetError() != GL_NO_ERROR); } void System::CheckErrorGL(const char* call, const char* file, const int line) { static const std::map<GLenum, std::string> errorString = { { GL_INVALID_ENUM, "INVALID_ENUM" }, { GL_INVALID_VALUE, "INVALID_VALUE" }, { GL_INVALID_OPERATION, "INVALID_OPERATION" }, { GL_STACK_OVERFLOW, "STACK_OVERFLOW" }, { GL_STACK_UNDERFLOW, "STACK_UNDERFLOW" }, { GL_OUT_OF_MEMORY, "OUT_OF_MEMORY" }, { GL_INVALID_FRAMEBUFFER_OPERATION, "INVALID_FRAMEBUFFER_OPERATION" }, { GL_TABLE_TOO_LARGE, "TABLE_TOO_LARGE" } }; GLenum error; while((error = glGetError()) != GL_NO_ERROR) { System::Instance()->Log("Error: %s = %02x (%s)\n at %s:%d\n", call, error, errorString.at(error).c_str(), file, line); } } void System::SetDefaults() { /* Depth testing */ glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); /* Backface culling */ glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); /* Blending */ glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* Multisampling */ glEnable(GL_MULTISAMPLE); /* OpenIL setup */ ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_LOWER_LEFT); } <commit_msg>Implemented debug Assimp log stream.<commit_after>/* CUBE demo toolkit by MasterM/Asenses */ #include <stdafx.h> #include <core/system.h> #include <core/config.h> #include <core/ui.h> #include <utils/notify.h> #ifdef _DEBUG #include <assimp/DefaultLogger.hpp> #include <assimp/LogStream.hpp> #endif using namespace CUBE; class Core::System* CUBE::System = nullptr; class Core::Config* CUBE::Config = nullptr; class Core::UI* CUBE::UI = nullptr; using namespace CUBE::Core; #ifdef _DEBUG struct AssimpLogStream : public Assimp::LogStream { void write(const char* message) { System::Instance()->Log("Assimp: %s", message); } }; #endif System::System() : UI(nullptr), NotifyService(nullptr), paused(false), window(NULL), stream(NULL) { strcpy_s<100>(name, "CUBE"); } Core::System* System::Instance() { static System _this; return &_this; } void System::KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { #ifdef _DEBUG if(mods & GLFW_MOD_SHIFT) #endif glfwSetWindowShouldClose(window, GL_TRUE); return; } #ifdef _DEBUG switch(key) { case GLFW_KEY_F1: if(action == GLFW_PRESS) System::Instance()->ToggleUI(); return; case GLFW_KEY_F2: if(action == GLFW_PRESS) System::Instance()->ArrangeUI(PlacementMode::Horizontal); return; case GLFW_KEY_F3: if(action == GLFW_PRESS) System::Instance()->ArrangeUI(PlacementMode::Vertical); return; case GLFW_KEY_SPACE: if(action == GLFW_PRESS) System::Instance()->TogglePlayback(); return; case GLFW_KEY_S: if(mods & GLFW_MOD_CONTROL && action == GLFW_PRESS) { CUBE::Config->Write(); return; } break; case GLFW_KEY_LEFT: if(mods & GLFW_MOD_CONTROL) { if(action == GLFW_PRESS || action == GLFW_REPEAT) System::Instance()->Seek(-0.5f); return; } break; case GLFW_KEY_RIGHT: if(mods & GLFW_MOD_CONTROL) { if(action == GLFW_PRESS || action == GLFW_REPEAT) System::Instance()->Seek(0.5f); return; } break; } ((TweakBarUI*)System::Instance()->UI)->TranslateKeyEvent(key, action); #endif } void System::UpdateDebugInfo() { static double lastTime = 0.0; double time = glfwGetTime(); if((time - lastTime) >= 0.1) { char debugInfo[256]; std::string sceneName; if(!DebugInfo.SceneName.empty()) sceneName = DebugInfo.SceneName + ": "; lastTime = time; sprintf_s(debugInfo, "%s [ %s%05.1fs ] %s", name, sceneName.c_str(), System::GetTime(), paused?"(paused)":""); glfwSetWindowTitle(window, debugInfo); } } void System::Init() { std::setlocale(LC_ALL, "en_US.UTF-8"); strcpy_s<100>(System::name, "CUBE"); #ifdef _DEBUG AllocConsole(); SetConsoleTitleA("Debug Console"); CUBE::Config = new ConfigRW(); Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE); Assimp::DefaultLogger::get()->attachStream(new AssimpLogStream, Assimp::Logger::Warn | Assimp::Logger::Err); #else CUBE::Config = new Config(); #endif if(!glfwInit()) { System::Error("Failed to initialize GLFW library."); ExitProcess(1); } if(!BASS_Init(-1, 44100, 0, 0, NULL)) { System::Error("Failed to initialize BASS library."); glfwTerminate(); ExitProcess(1); } ilInit(); CUBE::System = this; System::Log("CUBE demo toolkit initialized.\n"); } void System::Terminate() { BASS_Stop(); BASS_Free(); delete NotifyService; delete CUBE::UI; delete CUBE::Config; glfwTerminate(); System::Log("CUBE demo toolkit terminated.\n"); #ifdef _DEBUG Assimp::DefaultLogger::kill(); FreeConsole(); #endif } void System::UseOpenGL(const int major, const int minor) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } void System::OpenStream(const char* path) { if(path) stream = BASS_StreamCreateFile(FALSE, path, 0, 0, BASS_STREAM_PRESCAN); else stream = BASS_StreamCreate(44100, 2, 0, STREAMPROC_DUMMY, NULL); if(!stream) { System::Error("Failed to open stream."); System::Terminate(); ExitProcess(1); } System::Log("Opened stream: %s\n", path?path:"(dummy)"); } void System::OpenDisplay(const int width, const int height, bool fullscreen) { glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(width, height, name, NULL, NULL); if(!window) { System::Error("Failed to initialize OpenGL context."); System::Terminate(); ExitProcess(1); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, System::KeyCallback); glewExperimental = GL_TRUE; glewInit(); System::Log("Opened display: OpenGL %s (%dx%d)\n", glGetString(GL_VERSION), width, height); System::Log("Renderer: %s %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER)); #ifdef _DEBUG System::UI = new Core::TweakBarUI(window, width, height); System::Log("Debug GUI initialized.\n"); #else System::UI = new Core::NullUI(); #endif CUBE::UI = System::UI; ClearErrorGL(); SetDefaults(); } void System::SetName(const char* name) { strcpy_s<100>(System::name, name); } float System::GetTime() { return (float)BASS_ChannelBytes2Seconds(stream, BASS_ChannelGetPosition(stream, BASS_POS_BYTE)); } void System::Run(RenderBlock renderFunction) { BASS_ChannelPlay(stream, TRUE); while(!glfwWindowShouldClose(window)) { if(!renderFunction(GetTime())) break; UI->Draw(); #ifdef _DEBUG System::UpdateDebugInfo(); if(NotifyService) NotifyService->ProcessEvents(); #endif glfwSwapBuffers(window); glfwPollEvents(); } } void System::Error(const char* error) { MessageBoxA(NULL, error, "CUBE", MB_ICONSTOP | MB_OK); } void System::Log(const char* fmt, ...) { const size_t BUFSIZE = 8192; char buffer[BUFSIZE]; va_list args; va_start(args, fmt); vsnprintf_s(buffer, BUFSIZE, fmt, args); va_end(args); DWORD written; WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), buffer, strlen(buffer), &written, NULL); } void System::GetDisplaySize(int& w, int& h) { glfwGetFramebufferSize(window, &w, &h); } float System::GetDisplayAspect() { int w, h; glfwGetFramebufferSize(window, &w, &h); return float(w)/float(h); } void System::TogglePlayback() { if(paused) { BASS_ChannelPlay(stream, FALSE); paused = false; } else { BASS_ChannelPause(stream); paused = true; } } void System::ToggleUI() { UI->Toggle(); } void System::ArrangeUI(PlacementMode placement) { if(UI->IsActive()) { UI->Placement = placement; UI->Arrange(); } } void System::Seek(const float delta) { double position = BASS_ChannelBytes2Seconds(stream, BASS_ChannelGetPosition(stream, BASS_POS_BYTE)); position += double(delta); BASS_ChannelSetPosition(stream, BASS_ChannelSeconds2Bytes(stream, position), BASS_POS_BYTE); } bool System::SetContentDirectory(const std::string& path) { #ifdef _DEBUG if(NotifyService) return false; NotifyService = new FileNotify(path); #endif contentDirectory = path; return true; } const std::string& System::GetContentDirectory() const { return contentDirectory; } void System::Debug_SetSceneName(const char* name) const { #ifdef _DEBUG DebugInfo.SceneName = std::string(name); #endif } void System::HandleException(const std::exception& e) { std::string message(e.what()); try { BASS_Stop(); } catch(const std::exception&) {}; #ifdef _DEBUG message.append("\nDo you want to debug?"); if(MessageBoxA(NULL, message.c_str(), "CUBE [Exception]", MB_ICONSTOP | MB_YESNO) == IDYES) throw; #else MessageBoxA(NULL, message.c_str(), "CUBE [Exception]", MB_ICONSTOP | MB_OK); #endif } void System::ClearErrorGL() { while(glGetError() != GL_NO_ERROR); } void System::CheckErrorGL(const char* call, const char* file, const int line) { static const std::map<GLenum, std::string> errorString = { { GL_INVALID_ENUM, "INVALID_ENUM" }, { GL_INVALID_VALUE, "INVALID_VALUE" }, { GL_INVALID_OPERATION, "INVALID_OPERATION" }, { GL_STACK_OVERFLOW, "STACK_OVERFLOW" }, { GL_STACK_UNDERFLOW, "STACK_UNDERFLOW" }, { GL_OUT_OF_MEMORY, "OUT_OF_MEMORY" }, { GL_INVALID_FRAMEBUFFER_OPERATION, "INVALID_FRAMEBUFFER_OPERATION" }, { GL_TABLE_TOO_LARGE, "TABLE_TOO_LARGE" } }; GLenum error; while((error = glGetError()) != GL_NO_ERROR) { System::Instance()->Log("Error: %s = %02x (%s)\n at %s:%d\n", call, error, errorString.at(error).c_str(), file, line); } } void System::SetDefaults() { /* Depth testing */ glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); /* Backface culling */ glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); /* Blending */ glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* Multisampling */ glEnable(GL_MULTISAMPLE); /* OpenIL setup */ ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_LOWER_LEFT); } <|endoftext|>
<commit_before>#pragma once #include "config.hpp" #include <string> #include <SDL.h> #undef main #include "context.hpp" namespace ORCore { class Context; const Uint32 defaultWindowFlag = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; void init_video(); class Window { public: Window(int width=800, int height=600, bool fullscreen=false, std::string title="Game"); ~Window(); SDL_Window* get_platform_window(); void make_current(Context* context); void flip(); bool disable_sync(); private: std::string m_title; bool m_fullscreen; int m_width; int m_height; int m_x; int m_y; Uint32 m_sdlFlags; SDL_Window* m_sdlWindow; Context* m_context; }; } // namespace ORCore <commit_msg>Make window not resizable<commit_after>#pragma once #include "config.hpp" #include <string> #include <SDL.h> #undef main #include "context.hpp" namespace ORCore { class Context; const Uint32 defaultWindowFlag = SDL_WINDOW_OPENGL; void init_video(); class Window { public: Window(int width=800, int height=600, bool fullscreen=false, std::string title="Game"); ~Window(); SDL_Window* get_platform_window(); void make_current(Context* context); void flip(); bool disable_sync(); private: std::string m_title; bool m_fullscreen; int m_width; int m_height; int m_x; int m_y; Uint32 m_sdlFlags; SDL_Window* m_sdlWindow; Context* m_context; }; } // namespace ORCore <|endoftext|>
<commit_before>#include "sdk/amxxmodule.h" #include "curl_class.h" #include "amx_curl_controller_class.h" int g_len; // params[1] CURL handle cell // params[2] char* url str // params[3] str ref | escaped url // params[4] int len cell | static cell AMX_NATIVE_CALL amx_curl_easy_escape(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { std::string escaped_str; char* str_to_escape = MF_GetAmxString(amx, params[2], 0, &g_len); manager.CurlEscapeUrl(curl_handle, str_to_escape, escaped_str); MF_SetAmxString(amx, params[3], escaped_str.c_str(), params[4]); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell // params[2] char* url str // params[3] str ref | escaped url // params[4] int len cell | // ret int new_len cell | static cell AMX_NATIVE_CALL amx_curl_easy_unescape(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { std::string unescaped_str; char* str_to_unescape = MF_GetAmxString(amx, params[2], 0, &g_len); manager.CurlEscapeUrl(curl_handle, str_to_unescape, unescaped_str); MF_SetAmxString(amx, params[3], unescaped_str.c_str(), params[4]); return unescaped_str.size(); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // ret CURL cell static cell AMX_NATIVE_CALL amx_curl_easy_init(AMX* amx, cell* params) { try { return static_cast<cell>(AmxCurlController::Instance().get_curl_tasks_manager().CreateTaskForAmx(amx)); } catch(const CurlInitFailtureException&) { return 0; } } // params[1] CURL handle cell // params[2] CURLoption option cell // params[3] ... str,cell // ret CURLcode cell static cell AMX_NATIVE_CALL amx_curl_easy_setopt(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; CURLoption option = static_cast<CURLoption>(params[2]); try { // CURLOPTTYPE_LONG if (option < CURLOPTTYPE_OBJECTPOINT) return manager.CurlSetOption(curl_handle, option, static_cast<long>(*MF_GetAmxAddr(amx, params[3]))); // CURLOPTTYPE_OBJECTPOINT if (option < CURLOPT_WRITEFUNCTION) { if (CurlCallback::IsDataOption(option)) { return manager.CurlSetOption(curl_handle, option, reinterpret_cast<void*>(*MF_GetAmxAddr(amx, params[3]))); } switch (option) { case CURLOPT_HTTPPOST: return manager.CurlSetOption(curl_handle, option, reinterpret_cast<curl_httppost*>(*MF_GetAmxAddr(amx, params[3]))); case CURLOPT_HTTPHEADER: case CURLOPT_PROXYHEADER: case CURLOPT_HTTP200ALIASES: case CURLOPT_MAIL_RCPT: case CURLOPT_QUOTE: case CURLOPT_POSTQUOTE: case CURLOPT_RESOLVE: case CURLOPT_TELNETOPTIONS: return manager.CurlSetOption(curl_handle, option, reinterpret_cast<curl_slist*>(*MF_GetAmxAddr(amx, params[3]))); default: return manager.CurlSetOption(curl_handle, option, MF_GetAmxString(amx, params[3], 0, &g_len)); } } // CURLOPT_WRITEFUNCTION if (option < CURLOPTTYPE_OFF_T) { manager.CurlSetupAmxCallback(curl_handle, option, MF_GetAmxString(amx, params[3], 0, &g_len)); return CURLE_OK; } // CURLOPTTYPE_OFF_T curl_off_t val = 0; cell* p = MF_GetAmxAddr(amx, params[3]); val = p[0]; val <<= 32; val |= p[1]; return manager.CurlSetOption(curl_handle, option, val); } catch (const CurlInvalidOptionException& ex) { MF_LogError(amx, AMX_ERR_NATIVE, "%s. Option: %d", ex.what(), ex.get_option()); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return -1; } // params[1] CURL handle cell // params[2] CURLINFO info cell // params[3] ... cell,str,float ref // params[4] int len | for string in third param // ret CURLcode cell static cell AMX_NATIVE_CALL amx_curl_easy_getinfo(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; CURLINFO curl_info = static_cast<CURLINFO>(params[2]); CURLcode ret_code; int curlinfo_mask = curl_info & CURLINFO_TYPEMASK; try { if (curlinfo_mask == CURLINFO_STRING) { char* str; ret_code = manager.CurlGetInfo(curl_handle, curl_info, str); if (ret_code == CURLE_OK) MF_SetAmxString(amx, params[3], str, params[4]); } else if (curlinfo_mask == CURLINFO_LONG || curlinfo_mask == CURLINFO_SOCKET) { long num; ret_code = manager.CurlGetInfo(curl_handle, curl_info, num); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = num; } else if (curlinfo_mask == CURLINFO_DOUBLE) { double num; ret_code = manager.CurlGetInfo(curl_handle, curl_info, num); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = amx_ftoc(num); } else if (curlinfo_mask == CURLINFO_SLIST) { curl_slist* csl; ret_code = manager.CurlGetInfo(curl_handle, curl_info, csl); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = reinterpret_cast<cell>(csl); } else { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid CURLINFO"); return 0; } return static_cast<cell>(ret_code); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell // params[2] str | complite callback public callback(CURL:curl, CURLcode:code, data); // params[3] data[] cells arr // params[3] data len cell static cell AMX_NATIVE_CALL amx_curl_easy_perform(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; const char* cb_function = MF_GetAmxString(amx, params[2], 0, &g_len); cell* data = nullptr; int data_len = static_cast<int>(params[4]); if (data_len > 0) { data = new cell[data_len]; MF_CopyAmxMemory(data, MF_GetAmxAddr(amx, params[3]), data_len); } try { manager.CurlPerformTask(curl_handle, cb_function, data, data_len); } catch (const CurlAmxManagerInvalidHandleException&) { if(data != nullptr) delete[] data; MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } catch (const CurlTaskCallbackNotFoundException&) { if (data != nullptr) delete[] data; MF_LogError(amx, AMX_ERR_NATIVE, "Not found callback function %s", cb_function); } return 0; } // params[1] CURL handle cell static cell AMX_NATIVE_CALL amx_curl_easy_cleanup(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { manager.RemoveTask(curl_handle); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell static cell AMX_NATIVE_CALL amx_curl_easy_reset(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { manager.CurlReset(curl_handle); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURLcode err cell // params[2] char* strerr str // params[3] int len cell // ret static cell AMX_NATIVE_CALL amx_curl_easy_strerror(AMX* amx, cell* params) { MF_SetAmxString(amx, params[2], curl_easy_strerror(static_cast<CURLcode>(params[1])), params[3]); return 0; } // params[1] curl_httppost*first cell // params[2] curl_httppost*last cell // ... // ret CURLFORMcode cell static cell AMX_NATIVE_CALL amx_curl_formadd(AMX* amx, cell* params) { curl_httppost* first = reinterpret_cast<curl_httppost*>(*MF_GetAmxAddr(amx, params[1])); curl_httppost* last = reinterpret_cast<curl_httppost*>(*MF_GetAmxAddr(amx, params[2])); int i = 3, pairs = 0; while (static_cast<CURLformoption>(*MF_GetAmxAddr(amx, params[i])) != CURLFORM_END) { i += 2; pairs++; } if (pairs == 0 || pairs > 14) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid params count, get %d, must be in range 0 - 14", pairs); return -1; } char strings[14][16384]; curl_forms* forms = new curl_forms[pairs + 1]; for (i = 0; i < pairs; i++) { strcpy(strings[i], MF_GetAmxString(amx, params[i * 2 + 4], 0, &g_len)); forms[i].option = static_cast<CURLformoption>(*MF_GetAmxAddr(amx, params[i * 2 + 3])); forms[i].value = strings[i]; } forms[pairs].option = CURLFORM_END; CURLFORMcode code = curl_formadd(&first, &last, CURLFORM_ARRAY, forms, CURLFORM_END); delete[] forms; // pairs + 1 return code; } // params[1] curl_httppost*first cell static cell AMX_NATIVE_CALL amx_curl_formfree(AMX* amx, cell* params) { curl_formfree(reinterpret_cast<curl_httppost*>(params[1])); return 0; } // params[1] curl_slist* list cell // params[2] char* string arr // ret curl_slist* list cell static cell AMX_NATIVE_CALL amx_curl_slist_append(AMX* amx, cell* params) { return reinterpret_cast<cell>(curl_slist_append(reinterpret_cast<curl_slist*>(params[1]), MF_GetAmxString(amx, params[2], 0, &g_len))); } // params[1] curl_slist* list cell static cell AMX_NATIVE_CALL amx_curl_slist_free_all(AMX* amx, cell* params) { curl_slist_free_all(reinterpret_cast<curl_slist*>(params[1])); return 0; } // params[1] char* buf str // params[2] int len cell // ret static cell AMX_NATIVE_CALL amx_curl_version(AMX* amx, cell* params) { MF_SetAmxString(amx, params[1], curl_version(), params[2]); return 0; } AMX_NATIVE_INFO g_amx_curl_natives[] = { { "curl_easy_escape", amx_curl_easy_escape }, { "curl_easy_unescape", amx_curl_easy_unescape }, { "curl_easy_init", amx_curl_easy_init }, { "curl_easy_perform", amx_curl_easy_perform }, { "curl_easy_setopt", amx_curl_easy_setopt }, { "curl_easy_cleanup", amx_curl_easy_cleanup }, { "curl_easy_reset", amx_curl_easy_reset }, { "curl_easy_getinfo", amx_curl_easy_getinfo }, { "curl_easy_strerror", amx_curl_easy_strerror }, { "curl_formadd", amx_curl_formadd }, { "curl_formfree", amx_curl_formfree }, { "curl_slist_append", amx_curl_slist_append }, { "curl_slist_free_all", amx_curl_slist_free_all }, { "curl_version", amx_curl_version }, { NULL, NULL }, };<commit_msg>fixed non-working curl_formadd and curl_formfree<commit_after>#include "sdk/amxxmodule.h" #include "curl_class.h" #include "amx_curl_controller_class.h" int g_len; // params[1] CURL handle cell // params[2] char* url str // params[3] str ref | escaped url // params[4] int len cell | static cell AMX_NATIVE_CALL amx_curl_easy_escape(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { std::string escaped_str; char* str_to_escape = MF_GetAmxString(amx, params[2], 0, &g_len); manager.CurlEscapeUrl(curl_handle, str_to_escape, escaped_str); MF_SetAmxString(amx, params[3], escaped_str.c_str(), params[4]); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell // params[2] char* url str // params[3] str ref | escaped url // params[4] int len cell | // ret int new_len cell | static cell AMX_NATIVE_CALL amx_curl_easy_unescape(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { std::string unescaped_str; char* str_to_unescape = MF_GetAmxString(amx, params[2], 0, &g_len); manager.CurlEscapeUrl(curl_handle, str_to_unescape, unescaped_str); MF_SetAmxString(amx, params[3], unescaped_str.c_str(), params[4]); return unescaped_str.size(); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // ret CURL cell static cell AMX_NATIVE_CALL amx_curl_easy_init(AMX* amx, cell* params) { try { return static_cast<cell>(AmxCurlController::Instance().get_curl_tasks_manager().CreateTaskForAmx(amx)); } catch(const CurlInitFailtureException&) { return 0; } } // params[1] CURL handle cell // params[2] CURLoption option cell // params[3] ... str,cell // ret CURLcode cell static cell AMX_NATIVE_CALL amx_curl_easy_setopt(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; CURLoption option = static_cast<CURLoption>(params[2]); try { // CURLOPTTYPE_LONG if (option < CURLOPTTYPE_OBJECTPOINT) return manager.CurlSetOption(curl_handle, option, static_cast<long>(*MF_GetAmxAddr(amx, params[3]))); // CURLOPTTYPE_OBJECTPOINT if (option < CURLOPT_WRITEFUNCTION) { if (CurlCallback::IsDataOption(option)) { return manager.CurlSetOption(curl_handle, option, reinterpret_cast<void*>(*MF_GetAmxAddr(amx, params[3]))); } switch (option) { case CURLOPT_HTTPPOST: return manager.CurlSetOption(curl_handle, option, reinterpret_cast<curl_httppost*>(*MF_GetAmxAddr(amx, params[3]))); case CURLOPT_HTTPHEADER: case CURLOPT_PROXYHEADER: case CURLOPT_HTTP200ALIASES: case CURLOPT_MAIL_RCPT: case CURLOPT_QUOTE: case CURLOPT_POSTQUOTE: case CURLOPT_RESOLVE: case CURLOPT_TELNETOPTIONS: return manager.CurlSetOption(curl_handle, option, reinterpret_cast<curl_slist*>(*MF_GetAmxAddr(amx, params[3]))); default: return manager.CurlSetOption(curl_handle, option, MF_GetAmxString(amx, params[3], 0, &g_len)); } } // CURLOPT_WRITEFUNCTION if (option < CURLOPTTYPE_OFF_T) { manager.CurlSetupAmxCallback(curl_handle, option, MF_GetAmxString(amx, params[3], 0, &g_len)); return CURLE_OK; } // CURLOPTTYPE_OFF_T curl_off_t val = 0; cell* p = MF_GetAmxAddr(amx, params[3]); val = p[0]; val <<= 32; val |= p[1]; return manager.CurlSetOption(curl_handle, option, val); } catch (const CurlInvalidOptionException& ex) { MF_LogError(amx, AMX_ERR_NATIVE, "%s. Option: %d", ex.what(), ex.get_option()); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return -1; } // params[1] CURL handle cell // params[2] CURLINFO info cell // params[3] ... cell,str,float ref // params[4] int len | for string in third param // ret CURLcode cell static cell AMX_NATIVE_CALL amx_curl_easy_getinfo(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; CURLINFO curl_info = static_cast<CURLINFO>(params[2]); CURLcode ret_code; int curlinfo_mask = curl_info & CURLINFO_TYPEMASK; try { if (curlinfo_mask == CURLINFO_STRING) { char* str; ret_code = manager.CurlGetInfo(curl_handle, curl_info, str); if (ret_code == CURLE_OK) MF_SetAmxString(amx, params[3], str, params[4]); } else if (curlinfo_mask == CURLINFO_LONG || curlinfo_mask == CURLINFO_SOCKET) { long num; ret_code = manager.CurlGetInfo(curl_handle, curl_info, num); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = num; } else if (curlinfo_mask == CURLINFO_DOUBLE) { double num; ret_code = manager.CurlGetInfo(curl_handle, curl_info, num); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = amx_ftoc(num); } else if (curlinfo_mask == CURLINFO_SLIST) { curl_slist* csl; ret_code = manager.CurlGetInfo(curl_handle, curl_info, csl); cell* ret = MF_GetAmxAddr(amx, params[3]); *ret = reinterpret_cast<cell>(csl); } else { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid CURLINFO"); return 0; } return static_cast<cell>(ret_code); } catch(const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell // params[2] str | complite callback public callback(CURL:curl, CURLcode:code, data); // params[3] data[] cells arr // params[3] data len cell static cell AMX_NATIVE_CALL amx_curl_easy_perform(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; const char* cb_function = MF_GetAmxString(amx, params[2], 0, &g_len); cell* data = nullptr; int data_len = static_cast<int>(params[4]); if (data_len > 0) { data = new cell[data_len]; MF_CopyAmxMemory(data, MF_GetAmxAddr(amx, params[3]), data_len); } try { manager.CurlPerformTask(curl_handle, cb_function, data, data_len); } catch (const CurlAmxManagerInvalidHandleException&) { if(data != nullptr) delete[] data; MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } catch (const CurlTaskCallbackNotFoundException&) { if (data != nullptr) delete[] data; MF_LogError(amx, AMX_ERR_NATIVE, "Not found callback function %s", cb_function); } return 0; } // params[1] CURL handle cell static cell AMX_NATIVE_CALL amx_curl_easy_cleanup(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { manager.RemoveTask(curl_handle); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURL handle cell static cell AMX_NATIVE_CALL amx_curl_easy_reset(AMX* amx, cell* params) { AmxCurlTaskManager& manager = AmxCurlController::Instance().get_curl_tasks_manager(); AmxCurlTaskManager::CurlTaskHandle curl_handle = params[1]; try { manager.CurlReset(curl_handle); } catch (const CurlAmxManagerInvalidHandleException&) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid curl handle"); } return 0; } // params[1] CURLcode err cell // params[2] char* strerr str // params[3] int len cell // ret static cell AMX_NATIVE_CALL amx_curl_easy_strerror(AMX* amx, cell* params) { MF_SetAmxString(amx, params[2], curl_easy_strerror(static_cast<CURLcode>(params[1])), params[3]); return 0; } // params[1] curl_httppost*first cell // params[2] curl_httppost*last cell // ... // ret CURLFORMcode cell static cell AMX_NATIVE_CALL amx_curl_formadd(AMX* amx, cell* params) { curl_httppost** first = reinterpret_cast<curl_httppost**>(MF_GetAmxAddr(amx, params[1])); curl_httppost** last = reinterpret_cast<curl_httppost**>(MF_GetAmxAddr(amx, params[2])); int i = 3, pairs = 0; while (static_cast<CURLformoption>(*MF_GetAmxAddr(amx, params[i])) != CURLFORM_END) { i += 2; pairs++; } if (pairs == 0 || pairs > 14) { MF_LogError(amx, AMX_ERR_NATIVE, "Invalid params count, get %d, must be in range 0 - 14", pairs); return -1; } char strings[14][16384]; curl_forms* forms = new curl_forms[pairs + 1]; for (i = 0; i < pairs; i++) { strcpy(strings[i], MF_GetAmxString(amx, params[i * 2 + 4], 0, &g_len)); forms[i].option = static_cast<CURLformoption>(*MF_GetAmxAddr(amx, params[i * 2 + 3])); forms[i].value = strings[i]; } forms[pairs].option = CURLFORM_END; CURLFORMcode code = curl_formadd(first, last, CURLFORM_ARRAY, forms, CURLFORM_END); delete[] forms; // pairs + 1 return code; } // params[1] curl_httppost*first cell static cell AMX_NATIVE_CALL amx_curl_formfree(AMX* amx, cell* params) { curl_formfree(reinterpret_cast<curl_httppost*>(*MF_GetAmxAddr(amx, params[1]))); return 0; } // params[1] curl_slist* list cell // params[2] char* string arr // ret curl_slist* list cell static cell AMX_NATIVE_CALL amx_curl_slist_append(AMX* amx, cell* params) { return reinterpret_cast<cell>(curl_slist_append(reinterpret_cast<curl_slist*>(params[1]), MF_GetAmxString(amx, params[2], 0, &g_len))); } // params[1] curl_slist* list cell static cell AMX_NATIVE_CALL amx_curl_slist_free_all(AMX* amx, cell* params) { curl_slist_free_all(reinterpret_cast<curl_slist*>(params[1])); return 0; } // params[1] char* buf str // params[2] int len cell // ret static cell AMX_NATIVE_CALL amx_curl_version(AMX* amx, cell* params) { MF_SetAmxString(amx, params[1], curl_version(), params[2]); return 0; } AMX_NATIVE_INFO g_amx_curl_natives[] = { { "curl_easy_escape", amx_curl_easy_escape }, { "curl_easy_unescape", amx_curl_easy_unescape }, { "curl_easy_init", amx_curl_easy_init }, { "curl_easy_perform", amx_curl_easy_perform }, { "curl_easy_setopt", amx_curl_easy_setopt }, { "curl_easy_cleanup", amx_curl_easy_cleanup }, { "curl_easy_reset", amx_curl_easy_reset }, { "curl_easy_getinfo", amx_curl_easy_getinfo }, { "curl_easy_strerror", amx_curl_easy_strerror }, { "curl_formadd", amx_curl_formadd }, { "curl_formfree", amx_curl_formfree }, { "curl_slist_append", amx_curl_slist_append }, { "curl_slist_free_all", amx_curl_slist_free_all }, { "curl_version", amx_curl_version }, { NULL, NULL }, };<|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Tests text rendering with LCD and subpixel rendering turned on and off. */ #include "gm.h" #include "SkCanvas.h" class LcdTextGM : public skiagm::GM { public: LcdTextGM() { const int pointSize = 36; textHeight = SkIntToScalar(pointSize); } protected: SkString onShortName() { return SkString("lcdtext"); } SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { y = textHeight; drawText(canvas, SkString("TEXT: SubpixelTrue LCDRenderTrue"), true, true); drawText(canvas, SkString("TEXT: SubpixelTrue LCDRenderFalse"), true, false); drawText(canvas, SkString("TEXT: SubpixelFalse LCDRenderTrue"), false, true); drawText(canvas, SkString("TEXT: SubpixelFalse LCDRenderFalse"), false, false); } void drawText(SkCanvas* canvas, const SkString& string, bool subpixelTextEnabled, bool lcdRenderTextEnabled) { SkPaint paint; paint.setColor(SK_ColorBLACK); paint.setDither(true); paint.setAntiAlias(true); sk_tool_utils::set_portable_typeface(&paint); paint.setSubpixelText(subpixelTextEnabled); paint.setLCDRenderText(lcdRenderTextEnabled); paint.setTextSize(textHeight); canvas->drawText(string.c_str(), string.size(), 0, y, paint); y += textHeight; } private: typedef skiagm::GM INHERITED; SkScalar y, textHeight; }; /* * Skia will automatically disable LCD requests if the total size exceeds some limit * (hard coded in this test for now, as it is now avaiable as an API) * * Test this both by changing "textsize" and by changing the computed size (textsize * CTM) */ class LcdTextSizeGM : public skiagm::GM { enum { kLCDTextSizeLimit = 48 }; static void ScaleAbout(SkCanvas* canvas, SkScalar sx, SkScalar sy, SkScalar px, SkScalar py) { SkMatrix m; m.setScale(sx, sy, px, py); canvas->concat(m); } public: LcdTextSizeGM() {} protected: SkString onShortName() { return SkString("lcdtextsize"); } SkISize onISize() { return SkISize::Make(320, 120); } virtual void onDraw(SkCanvas* canvas) { const char* lcd_text = "LCD"; const char* gray_text = "GRAY"; SkPaint paint; paint.setAntiAlias(true); paint.setLCDRenderText(true); const struct { SkPoint fLoc; SkScalar fTextSize; SkScalar fScale; const char* fText; } rec[] = { { { 10, 50 }, kLCDTextSizeLimit - 1, 1, lcd_text }, { { 160, 50 }, kLCDTextSizeLimit + 1, 1, gray_text }, { { 10, 100 }, kLCDTextSizeLimit / 2, 1.99f, lcd_text }, { { 160, 100 }, kLCDTextSizeLimit / 2, 2.01f, gray_text }, }; for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) { const SkPoint loc = rec[i].fLoc; SkAutoCanvasRestore acr(canvas, true); paint.setTextSize(rec[i].fTextSize); ScaleAbout(canvas, rec[i].fScale, rec[i].fScale, loc.x(), loc.y()); canvas->drawText(rec[i].fText, strlen(rec[i].fText), loc.x(), loc.y(), paint); } } private: typedef skiagm::GM INHERITED; }; #include "SkSurface.h" // ensure that we respect the SkPixelGeometry in SurfaceProps class LcdTextProps : public skiagm::GM { static void DrawText(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setLCDRenderText(true); paint.setTextSize(30); canvas->drawText("Base", 4, 4, 30, paint); canvas->saveLayer(NULL, NULL); canvas->drawText("Layer", 5, 4, 70, paint); canvas->restore(); } public: SkString onShortName() SK_OVERRIDE { return SkString("lcdtextprops"); } SkISize onISize() SK_OVERRIDE { return SkISize::Make(230, 120); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { const SkPixelGeometry geos[] = { kRGB_H_SkPixelGeometry, kUnknown_SkPixelGeometry, }; const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100); for (size_t i = 0; i < SK_ARRAY_COUNT(geos); ++i) { SkSurfaceProps props = SkSurfaceProps(0, geos[i]); SkAutoTUnref<SkSurface> surf(canvas->newSurface(info, &props)); if (!surf) { surf.reset(SkSurface::NewRaster(info, &props)); } DrawText(surf->getCanvas()); surf->draw(canvas, SkIntToScalar(i * (info.width() + 10)), 0, NULL); } } }; /////////////////////////////////////////////////////////////////////////////// DEF_GM( return new LcdTextGM; ) DEF_GM( return new LcdTextSizeGM; ) DEF_GM( return new LcdTextProps; ) <commit_msg>Disable GM:lcdtextprops on 565<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Tests text rendering with LCD and subpixel rendering turned on and off. */ #include "gm.h" #include "SkCanvas.h" class LcdTextGM : public skiagm::GM { public: LcdTextGM() { const int pointSize = 36; textHeight = SkIntToScalar(pointSize); } protected: SkString onShortName() { return SkString("lcdtext"); } SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { y = textHeight; drawText(canvas, SkString("TEXT: SubpixelTrue LCDRenderTrue"), true, true); drawText(canvas, SkString("TEXT: SubpixelTrue LCDRenderFalse"), true, false); drawText(canvas, SkString("TEXT: SubpixelFalse LCDRenderTrue"), false, true); drawText(canvas, SkString("TEXT: SubpixelFalse LCDRenderFalse"), false, false); } void drawText(SkCanvas* canvas, const SkString& string, bool subpixelTextEnabled, bool lcdRenderTextEnabled) { SkPaint paint; paint.setColor(SK_ColorBLACK); paint.setDither(true); paint.setAntiAlias(true); sk_tool_utils::set_portable_typeface(&paint); paint.setSubpixelText(subpixelTextEnabled); paint.setLCDRenderText(lcdRenderTextEnabled); paint.setTextSize(textHeight); canvas->drawText(string.c_str(), string.size(), 0, y, paint); y += textHeight; } private: typedef skiagm::GM INHERITED; SkScalar y, textHeight; }; /* * Skia will automatically disable LCD requests if the total size exceeds some limit * (hard coded in this test for now, as it is now avaiable as an API) * * Test this both by changing "textsize" and by changing the computed size (textsize * CTM) */ class LcdTextSizeGM : public skiagm::GM { enum { kLCDTextSizeLimit = 48 }; static void ScaleAbout(SkCanvas* canvas, SkScalar sx, SkScalar sy, SkScalar px, SkScalar py) { SkMatrix m; m.setScale(sx, sy, px, py); canvas->concat(m); } public: LcdTextSizeGM() {} protected: SkString onShortName() { return SkString("lcdtextsize"); } SkISize onISize() { return SkISize::Make(320, 120); } virtual void onDraw(SkCanvas* canvas) { const char* lcd_text = "LCD"; const char* gray_text = "GRAY"; SkPaint paint; paint.setAntiAlias(true); paint.setLCDRenderText(true); const struct { SkPoint fLoc; SkScalar fTextSize; SkScalar fScale; const char* fText; } rec[] = { { { 10, 50 }, kLCDTextSizeLimit - 1, 1, lcd_text }, { { 160, 50 }, kLCDTextSizeLimit + 1, 1, gray_text }, { { 10, 100 }, kLCDTextSizeLimit / 2, 1.99f, lcd_text }, { { 160, 100 }, kLCDTextSizeLimit / 2, 2.01f, gray_text }, }; for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) { const SkPoint loc = rec[i].fLoc; SkAutoCanvasRestore acr(canvas, true); paint.setTextSize(rec[i].fTextSize); ScaleAbout(canvas, rec[i].fScale, rec[i].fScale, loc.x(), loc.y()); canvas->drawText(rec[i].fText, strlen(rec[i].fText), loc.x(), loc.y(), paint); } } private: typedef skiagm::GM INHERITED; }; #include "SkSurface.h" // ensure that we respect the SkPixelGeometry in SurfaceProps class LcdTextProps : public skiagm::GM { static void DrawText(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setLCDRenderText(true); paint.setTextSize(30); canvas->drawText("Base", 4, 4, 30, paint); canvas->saveLayer(NULL, NULL); canvas->drawText("Layer", 5, 4, 70, paint); canvas->restore(); } protected: SkString onShortName() SK_OVERRIDE { return SkString("lcdtextprops"); } SkISize onISize() SK_OVERRIDE { return SkISize::Make(230, 120); } uint32_t onGetFlags() const SK_OVERRIDE { return kSkip565_Flag; } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { const SkPixelGeometry geos[] = { kRGB_H_SkPixelGeometry, kUnknown_SkPixelGeometry, }; const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100); for (size_t i = 0; i < SK_ARRAY_COUNT(geos); ++i) { SkSurfaceProps props = SkSurfaceProps(0, geos[i]); SkAutoTUnref<SkSurface> surf(canvas->newSurface(info, &props)); if (!surf) { surf.reset(SkSurface::NewRaster(info, &props)); } DrawText(surf->getCanvas()); surf->draw(canvas, SkIntToScalar(i * (info.width() + 10)), 0, NULL); } } }; /////////////////////////////////////////////////////////////////////////////// DEF_GM( return new LcdTextGM; ) DEF_GM( return new LcdTextSizeGM; ) DEF_GM( return new LcdTextProps; ) <|endoftext|>
<commit_before>#include "commands/commands.h" #include "config.h" #include "util/log.h" #include "interface/interface.h" #include "config.h" #include "pb_decode.h" #include "commands/passthrough_command.h" #include "commands/diagnostic_request_command.h" #include "commands/version_command.h" #include "commands/device_id_command.h" #include "commands/device_platform_command.h" #include "commands/can_message_write_command.h" #include "commands/simple_write_command.h" #include "commands/af_bypass_command.h" #include "commands/payload_format_command.h" #include "commands/predefined_obd2_command.h" #include "commands/modem_config_command.h" #include "commands/rtc_config_command.h" #include "commands/sd_mount_status_command.h" #include "commands/get_vin_command.h" using openxc::util::log::debug; using openxc::config::getConfiguration; using openxc::payload::PayloadFormat; using openxc::interface::InterfaceType; static bool handleComplexCommand(openxc_VehicleMessage* message) { bool status = true; if(message != NULL && message->type == openxc_VehicleMessage_Type_CONTROL_COMMAND) { openxc_ControlCommand* command = &message->control_command; switch(command->type) { case openxc_ControlCommand_Type_DIAGNOSTIC: status = openxc::commands::handleDiagnosticRequestCommand(command); break; case openxc_ControlCommand_Type_VERSION: status = openxc::commands::handleVersionCommand(); break; case openxc_ControlCommand_Type_DEVICE_ID: status = openxc::commands::handleDeviceIdCommmand(); break; case openxc_ControlCommand_Type_PLATFORM: status = openxc::commands::handleDevicePlatformCommmand(); break; case openxc_ControlCommand_Type_PASSTHROUGH: status = openxc::commands::handlePassthroughModeCommand(command); break; case openxc_ControlCommand_Type_PREDEFINED_OBD2_REQUESTS: status = openxc::commands::handlePredefinedObd2RequestsCommand(command); break; case openxc_ControlCommand_Type_ACCEPTANCE_FILTER_BYPASS: status = openxc::commands::handleFilterBypassCommand(command); break; case openxc_ControlCommand_Type_PAYLOAD_FORMAT: status = openxc::commands::handlePayloadFormatCommand(command); break; case openxc_ControlCommand_Type_MODEM_CONFIGURATION: status = openxc::commands::handleModemConfigurationCommand(command); break; case openxc_ControlCommand_Type_RTC_CONFIGURATION: status = openxc::commands::handleRTCConfigurationCommand(command); break; case openxc_ControlCommand_Type_SD_MOUNT_STATUS: status = openxc::commands::handleSDMountStatusCommand(); case openxc_ControlCommand_Type_GET_VIN: status = openxc::commands::handleGetVinCommand(); default: status = false; break; } } return status; } size_t openxc::commands::handleIncomingMessage(uint8_t payload[], size_t length, openxc::interface::InterfaceDescriptor* sourceInterfaceDescriptor) { openxc_VehicleMessage message = openxc_VehicleMessage(); // Zero fill size_t bytesRead = 0; #if (DO_NOT_PROCESS_BINARY_UART_PROTOBUFF == 1) // TODO Not attempting to deserialize binary messages via UART, // see https://github.com/openxc/vi-firmware/issues/313 if(sourceInterfaceDescriptor->type == InterfaceType::UART && getConfiguration()->payloadFormat == PayloadFormat::PROTOBUF) { return 0; } #endif // Ignore anything less than 2 bytes, we know it's an incomplete payload - // wait for more to come in before trying to parse it if(length > 2) { if((bytesRead = openxc::payload::deserialize(payload, length, getConfiguration()->payloadFormat, &message)) > 0) { if(validate(&message)) { switch(message.type) { case openxc_VehicleMessage_Type_CAN: handleCan(&message, sourceInterfaceDescriptor); break; case openxc_VehicleMessage_Type_SIMPLE: handleSimple(&message); break; case openxc_VehicleMessage_Type_CONTROL_COMMAND: handleComplexCommand(&message); break; default: debug("Incoming message had unrecognized type: %d", message.type); break; } } else { debug("Incoming message is complete but invalid"); } } else { // This is very noisy when using UART as the packet tends to arrive // in a couple or bursts and is passed to this function when // incomplete. // debug("Unable to deserialize a %s message from the payload", // getConfiguration()->payloadFormat == PayloadFormat::JSON ? // "JSON" : "Protobuf"); } } return bytesRead; } static bool validateControlCommand(openxc_VehicleMessage* message) { bool valid = (message->type == openxc_VehicleMessage_Type_CONTROL_COMMAND) && (message->control_command.type != openxc_ControlCommand_Type_UNUSED); if(valid) { switch(message->control_command.type) { case openxc_ControlCommand_Type_DIAGNOSTIC: valid = openxc::commands::validateDiagnosticRequest(message); break; case openxc_ControlCommand_Type_PASSTHROUGH: valid = openxc::commands::validatePassthroughRequest(message); break; case openxc_ControlCommand_Type_PREDEFINED_OBD2_REQUESTS: valid = openxc::commands::validatePredefinedObd2RequestsCommand(message); break; case openxc_ControlCommand_Type_ACCEPTANCE_FILTER_BYPASS: valid = openxc::commands::validateFilterBypassCommand(message); break; case openxc_ControlCommand_Type_PAYLOAD_FORMAT: valid = openxc::commands::validatePayloadFormatCommand(message); break; case openxc_ControlCommand_Type_VERSION: case openxc_ControlCommand_Type_DEVICE_ID: case openxc_ControlCommand_Type_PLATFORM: case openxc_ControlCommand_Type_SD_MOUNT_STATUS: case openxc_ControlCommand_Type_GET_VIN: valid = true; break; case openxc_ControlCommand_Type_MODEM_CONFIGURATION: valid = openxc::commands::validateModemConfigurationCommand(message); break; case openxc_ControlCommand_Type_RTC_CONFIGURATION: valid = openxc::commands::validateRTCConfigurationCommand(message); break; default: valid = false; break; } } return valid; } bool openxc::commands::validate(openxc_VehicleMessage* message) { bool valid = false; if(message != NULL) { switch(message->type) { case openxc_VehicleMessage_Type_CAN: valid = validateCan(message); break; case openxc_VehicleMessage_Type_SIMPLE: valid = validateSimple(message); break; case openxc_VehicleMessage_Type_CONTROL_COMMAND: valid = validateControlCommand(message); break; default: debug("Incoming message had unrecognized type: %d", message->type); break; } } return valid; } void openxc::commands::sendCommandResponse(openxc_ControlCommand_Type commandType, bool status, char* responseMessage, size_t responseMessageLength) { debug("Command response value %d", responseMessage); debug("Command response value %s", responseMessage); openxc_VehicleMessage message = openxc_VehicleMessage(); // Zero Fill message.type = openxc_VehicleMessage_Type_COMMAND_RESPONSE; message.command_response.type = commandType; message.command_response.status = status; if(responseMessage != NULL && responseMessageLength > 0) { strncpy(message.command_response.message, responseMessage, MIN(sizeof(message.command_response.message), responseMessageLength)); } pipeline::publish(&message, &getConfiguration()->pipeline); } void openxc::commands::sendCommandResponse(openxc_ControlCommand_Type commandType, bool status) { sendCommandResponse(commandType, status, NULL, 0); } <commit_msg>remove debug statement from the code.<commit_after>#include "commands/commands.h" #include "config.h" #include "util/log.h" #include "interface/interface.h" #include "config.h" #include "pb_decode.h" #include "commands/passthrough_command.h" #include "commands/diagnostic_request_command.h" #include "commands/version_command.h" #include "commands/device_id_command.h" #include "commands/device_platform_command.h" #include "commands/can_message_write_command.h" #include "commands/simple_write_command.h" #include "commands/af_bypass_command.h" #include "commands/payload_format_command.h" #include "commands/predefined_obd2_command.h" #include "commands/modem_config_command.h" #include "commands/rtc_config_command.h" #include "commands/sd_mount_status_command.h" #include "commands/get_vin_command.h" using openxc::util::log::debug; using openxc::config::getConfiguration; using openxc::payload::PayloadFormat; using openxc::interface::InterfaceType; static bool handleComplexCommand(openxc_VehicleMessage* message) { bool status = true; if(message != NULL && message->type == openxc_VehicleMessage_Type_CONTROL_COMMAND) { openxc_ControlCommand* command = &message->control_command; switch(command->type) { case openxc_ControlCommand_Type_DIAGNOSTIC: status = openxc::commands::handleDiagnosticRequestCommand(command); break; case openxc_ControlCommand_Type_VERSION: status = openxc::commands::handleVersionCommand(); break; case openxc_ControlCommand_Type_DEVICE_ID: status = openxc::commands::handleDeviceIdCommmand(); break; case openxc_ControlCommand_Type_PLATFORM: status = openxc::commands::handleDevicePlatformCommmand(); break; case openxc_ControlCommand_Type_PASSTHROUGH: status = openxc::commands::handlePassthroughModeCommand(command); break; case openxc_ControlCommand_Type_PREDEFINED_OBD2_REQUESTS: status = openxc::commands::handlePredefinedObd2RequestsCommand(command); break; case openxc_ControlCommand_Type_ACCEPTANCE_FILTER_BYPASS: status = openxc::commands::handleFilterBypassCommand(command); break; case openxc_ControlCommand_Type_PAYLOAD_FORMAT: status = openxc::commands::handlePayloadFormatCommand(command); break; case openxc_ControlCommand_Type_MODEM_CONFIGURATION: status = openxc::commands::handleModemConfigurationCommand(command); break; case openxc_ControlCommand_Type_RTC_CONFIGURATION: status = openxc::commands::handleRTCConfigurationCommand(command); break; case openxc_ControlCommand_Type_SD_MOUNT_STATUS: status = openxc::commands::handleSDMountStatusCommand(); case openxc_ControlCommand_Type_GET_VIN: status = openxc::commands::handleGetVinCommand(); default: status = false; break; } } return status; } size_t openxc::commands::handleIncomingMessage(uint8_t payload[], size_t length, openxc::interface::InterfaceDescriptor* sourceInterfaceDescriptor) { openxc_VehicleMessage message = openxc_VehicleMessage(); // Zero fill size_t bytesRead = 0; #if (DO_NOT_PROCESS_BINARY_UART_PROTOBUFF == 1) // TODO Not attempting to deserialize binary messages via UART, // see https://github.com/openxc/vi-firmware/issues/313 if(sourceInterfaceDescriptor->type == InterfaceType::UART && getConfiguration()->payloadFormat == PayloadFormat::PROTOBUF) { return 0; } #endif // Ignore anything less than 2 bytes, we know it's an incomplete payload - // wait for more to come in before trying to parse it if(length > 2) { if((bytesRead = openxc::payload::deserialize(payload, length, getConfiguration()->payloadFormat, &message)) > 0) { if(validate(&message)) { switch(message.type) { case openxc_VehicleMessage_Type_CAN: handleCan(&message, sourceInterfaceDescriptor); break; case openxc_VehicleMessage_Type_SIMPLE: handleSimple(&message); break; case openxc_VehicleMessage_Type_CONTROL_COMMAND: handleComplexCommand(&message); break; default: debug("Incoming message had unrecognized type: %d", message.type); break; } } else { debug("Incoming message is complete but invalid"); } } else { // This is very noisy when using UART as the packet tends to arrive // in a couple or bursts and is passed to this function when // incomplete. // debug("Unable to deserialize a %s message from the payload", // getConfiguration()->payloadFormat == PayloadFormat::JSON ? // "JSON" : "Protobuf"); } } return bytesRead; } static bool validateControlCommand(openxc_VehicleMessage* message) { bool valid = (message->type == openxc_VehicleMessage_Type_CONTROL_COMMAND) && (message->control_command.type != openxc_ControlCommand_Type_UNUSED); if(valid) { switch(message->control_command.type) { case openxc_ControlCommand_Type_DIAGNOSTIC: valid = openxc::commands::validateDiagnosticRequest(message); break; case openxc_ControlCommand_Type_PASSTHROUGH: valid = openxc::commands::validatePassthroughRequest(message); break; case openxc_ControlCommand_Type_PREDEFINED_OBD2_REQUESTS: valid = openxc::commands::validatePredefinedObd2RequestsCommand(message); break; case openxc_ControlCommand_Type_ACCEPTANCE_FILTER_BYPASS: valid = openxc::commands::validateFilterBypassCommand(message); break; case openxc_ControlCommand_Type_PAYLOAD_FORMAT: valid = openxc::commands::validatePayloadFormatCommand(message); break; case openxc_ControlCommand_Type_VERSION: case openxc_ControlCommand_Type_DEVICE_ID: case openxc_ControlCommand_Type_PLATFORM: case openxc_ControlCommand_Type_SD_MOUNT_STATUS: case openxc_ControlCommand_Type_GET_VIN: valid = true; break; case openxc_ControlCommand_Type_MODEM_CONFIGURATION: valid = openxc::commands::validateModemConfigurationCommand(message); break; case openxc_ControlCommand_Type_RTC_CONFIGURATION: valid = openxc::commands::validateRTCConfigurationCommand(message); break; default: valid = false; break; } } return valid; } bool openxc::commands::validate(openxc_VehicleMessage* message) { bool valid = false; if(message != NULL) { switch(message->type) { case openxc_VehicleMessage_Type_CAN: valid = validateCan(message); break; case openxc_VehicleMessage_Type_SIMPLE: valid = validateSimple(message); break; case openxc_VehicleMessage_Type_CONTROL_COMMAND: valid = validateControlCommand(message); break; default: debug("Incoming message had unrecognized type: %d", message->type); break; } } return valid; } void openxc::commands::sendCommandResponse(openxc_ControlCommand_Type commandType, bool status, char* responseMessage, size_t responseMessageLength) { openxc_VehicleMessage message = openxc_VehicleMessage(); // Zero Fill message.type = openxc_VehicleMessage_Type_COMMAND_RESPONSE; message.command_response.type = commandType; message.command_response.status = status; if(responseMessage != NULL && responseMessageLength > 0) { strncpy(message.command_response.message, responseMessage, MIN(sizeof(message.command_response.message), responseMessageLength)); } pipeline::publish(&message, &getConfiguration()->pipeline); } void openxc::commands::sendCommandResponse(openxc_ControlCommand_Type commandType, bool status) { sendCommandResponse(commandType, status, NULL, 0); } <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <algorithm> #include <cstddef> #include "SkArenaAlloc.h" static char* end_chain(char*) { return nullptr; } char* SkArenaAlloc::SkipPod(char* footerEnd) { char* objEnd = footerEnd - (sizeof(Footer) + sizeof(int32_t)); int32_t skip; memmove(&skip, objEnd, sizeof(int32_t)); return objEnd - skip; } void SkArenaAlloc::RunDtorsOnBlock(char* footerEnd) { while (footerEnd != nullptr) { Footer footer; memcpy(&footer, footerEnd - sizeof(Footer), sizeof(Footer)); FooterAction* action = (FooterAction*)(footer >> 6); ptrdiff_t padding = footer & 63; footerEnd = action(footerEnd) - padding; } } char* SkArenaAlloc::NextBlock(char* footerEnd) { char* objEnd = footerEnd - (sizeof(Footer) + sizeof(char*)); char* next; memmove(&next, objEnd, sizeof(char*)); RunDtorsOnBlock(next); delete [] objEnd; return nullptr; } SkArenaAlloc::SkArenaAlloc(char* block, size_t size, size_t extraSize) : fDtorCursor {block} , fCursor {block} , fEnd {block + size} , fFirstBlock {block} , fFirstSize {size} , fExtraSize {extraSize} { if (size < sizeof(Footer)) { fEnd = fCursor = fDtorCursor = nullptr; } if (fCursor != nullptr) { this->installFooter(end_chain, 0); } } SkArenaAlloc::~SkArenaAlloc() { RunDtorsOnBlock(fDtorCursor); } void SkArenaAlloc::reset() { this->~SkArenaAlloc(); new (this) SkArenaAlloc{fFirstBlock, fFirstSize, fExtraSize}; } void SkArenaAlloc::installFooter(FooterAction* action, uint32_t padding) { SkASSERT(padding < 64); int64_t actionInt = (int64_t)(intptr_t)action; Footer encodedFooter = (actionInt << 6) | padding; memmove(fCursor, &encodedFooter, sizeof(Footer)); fCursor += sizeof(Footer); fDtorCursor = fCursor; } void SkArenaAlloc::installPtrFooter(FooterAction* action, char* ptr, uint32_t padding) { memmove(fCursor, &ptr, sizeof(char*)); fCursor += sizeof(char*); this->installFooter(action, padding); } void SkArenaAlloc::installUint32Footer(FooterAction* action, uint32_t value, uint32_t padding) { memmove(fCursor, &value, sizeof(uint32_t)); fCursor += sizeof(uint32_t); this->installFooter(action, padding); } void SkArenaAlloc::ensureSpace(size_t size, size_t alignment) { constexpr size_t headerSize = sizeof(Footer) + sizeof(ptrdiff_t); // The chrome c++ library we use does not define std::max_align_t. // This must be conservative to add the right amount of extra memory to handle the alignment // padding. constexpr size_t alignof_max_align_t = 8; auto objSizeAndOverhead = size + headerSize + sizeof(Footer); if (alignment > alignof_max_align_t) { objSizeAndOverhead += alignment - 1; } auto allocationSize = std::max(objSizeAndOverhead, fExtraSize); // Round up to a nice size. If > 32K align to 4K boundary else up to max_align_t. The > 32K // heuristic is from the JEMalloc behavior. { size_t mask = allocationSize > (1 << 15) ? (1 << 12) - 1 : 16 - 1; allocationSize = (allocationSize + mask) & ~mask; } char* newBlock = new char[allocationSize]; auto previousDtor = fDtorCursor; fCursor = newBlock; fDtorCursor = newBlock; fEnd = fCursor + allocationSize; this->installPtrFooter(NextBlock, previousDtor, 0); } char* SkArenaAlloc::allocObject(size_t size, size_t alignment) { size_t mask = alignment - 1; char* objStart = (char*)((uintptr_t)(fCursor + mask) & ~mask); if ((ptrdiff_t)size > fEnd - objStart) { this->ensureSpace(size, alignment); objStart = (char*)((uintptr_t)(fCursor + mask) & ~mask); } return objStart; } char* SkArenaAlloc::allocObjectWithFooter(size_t sizeIncludingFooter, size_t alignment) { size_t mask = alignment - 1; restart: size_t skipOverhead = 0; bool needsSkipFooter = fCursor != fDtorCursor; if (needsSkipFooter) { skipOverhead = sizeof(Footer) + sizeof(uint32_t); } char* objStart = (char*)((uintptr_t)(fCursor + skipOverhead + mask) & ~mask); size_t totalSize = sizeIncludingFooter + skipOverhead; if ((ptrdiff_t)totalSize > fEnd - objStart) { this->ensureSpace(totalSize, alignment); goto restart; } SkASSERT((ptrdiff_t)totalSize <= fEnd - objStart); // Install a skip footer if needed, thus terminating a run of POD data. The calling code is // responsible for installing the footer after the object. if (needsSkipFooter) { this->installUint32Footer(SkipPod, SkTo<uint32_t>(fCursor - fDtorCursor), 0); } return objStart; } <commit_msg>Check that the upper bits are correct in the SkArenaAlloc footer.<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <algorithm> #include <cstddef> #include "SkArenaAlloc.h" static char* end_chain(char*) { return nullptr; } char* SkArenaAlloc::SkipPod(char* footerEnd) { char* objEnd = footerEnd - (sizeof(Footer) + sizeof(int32_t)); int32_t skip; memmove(&skip, objEnd, sizeof(int32_t)); return objEnd - skip; } void SkArenaAlloc::RunDtorsOnBlock(char* footerEnd) { while (footerEnd != nullptr) { Footer footer; memcpy(&footer, footerEnd - sizeof(Footer), sizeof(Footer)); FooterAction* action = (FooterAction*)(footer >> 6); ptrdiff_t padding = footer & 63; footerEnd = action(footerEnd) - padding; } } char* SkArenaAlloc::NextBlock(char* footerEnd) { char* objEnd = footerEnd - (sizeof(Footer) + sizeof(char*)); char* next; memmove(&next, objEnd, sizeof(char*)); RunDtorsOnBlock(next); delete [] objEnd; return nullptr; } SkArenaAlloc::SkArenaAlloc(char* block, size_t size, size_t extraSize) : fDtorCursor {block} , fCursor {block} , fEnd {block + size} , fFirstBlock {block} , fFirstSize {size} , fExtraSize {extraSize} { if (size < sizeof(Footer)) { fEnd = fCursor = fDtorCursor = nullptr; } if (fCursor != nullptr) { this->installFooter(end_chain, 0); } } SkArenaAlloc::~SkArenaAlloc() { RunDtorsOnBlock(fDtorCursor); } void SkArenaAlloc::reset() { this->~SkArenaAlloc(); new (this) SkArenaAlloc{fFirstBlock, fFirstSize, fExtraSize}; } void SkArenaAlloc::installFooter(FooterAction* action, uint32_t padding) { SkASSERT(padding < 64); int64_t actionInt = (int64_t)(intptr_t)action; // The top 14 bits should be either all 0s or all 1s. Check this. SkASSERT((actionInt << 6) >> 6 == actionInt); Footer encodedFooter = (actionInt << 6) | padding; memmove(fCursor, &encodedFooter, sizeof(Footer)); fCursor += sizeof(Footer); fDtorCursor = fCursor; } void SkArenaAlloc::installPtrFooter(FooterAction* action, char* ptr, uint32_t padding) { memmove(fCursor, &ptr, sizeof(char*)); fCursor += sizeof(char*); this->installFooter(action, padding); } void SkArenaAlloc::installUint32Footer(FooterAction* action, uint32_t value, uint32_t padding) { memmove(fCursor, &value, sizeof(uint32_t)); fCursor += sizeof(uint32_t); this->installFooter(action, padding); } void SkArenaAlloc::ensureSpace(size_t size, size_t alignment) { constexpr size_t headerSize = sizeof(Footer) + sizeof(ptrdiff_t); // The chrome c++ library we use does not define std::max_align_t. // This must be conservative to add the right amount of extra memory to handle the alignment // padding. constexpr size_t alignof_max_align_t = 8; auto objSizeAndOverhead = size + headerSize + sizeof(Footer); if (alignment > alignof_max_align_t) { objSizeAndOverhead += alignment - 1; } auto allocationSize = std::max(objSizeAndOverhead, fExtraSize); // Round up to a nice size. If > 32K align to 4K boundary else up to max_align_t. The > 32K // heuristic is from the JEMalloc behavior. { size_t mask = allocationSize > (1 << 15) ? (1 << 12) - 1 : 16 - 1; allocationSize = (allocationSize + mask) & ~mask; } char* newBlock = new char[allocationSize]; auto previousDtor = fDtorCursor; fCursor = newBlock; fDtorCursor = newBlock; fEnd = fCursor + allocationSize; this->installPtrFooter(NextBlock, previousDtor, 0); } char* SkArenaAlloc::allocObject(size_t size, size_t alignment) { size_t mask = alignment - 1; char* objStart = (char*)((uintptr_t)(fCursor + mask) & ~mask); if ((ptrdiff_t)size > fEnd - objStart) { this->ensureSpace(size, alignment); objStart = (char*)((uintptr_t)(fCursor + mask) & ~mask); } return objStart; } char* SkArenaAlloc::allocObjectWithFooter(size_t sizeIncludingFooter, size_t alignment) { size_t mask = alignment - 1; restart: size_t skipOverhead = 0; bool needsSkipFooter = fCursor != fDtorCursor; if (needsSkipFooter) { skipOverhead = sizeof(Footer) + sizeof(uint32_t); } char* objStart = (char*)((uintptr_t)(fCursor + skipOverhead + mask) & ~mask); size_t totalSize = sizeIncludingFooter + skipOverhead; if ((ptrdiff_t)totalSize > fEnd - objStart) { this->ensureSpace(totalSize, alignment); goto restart; } SkASSERT((ptrdiff_t)totalSize <= fEnd - objStart); // Install a skip footer if needed, thus terminating a run of POD data. The calling code is // responsible for installing the footer after the object. if (needsSkipFooter) { this->installUint32Footer(SkipPod, SkTo<uint32_t>(fCursor - fDtorCursor), 0); } return objStart; } <|endoftext|>
<commit_before>#ifndef KEYCODE_HPP #define KEYCODE_HPP namespace org_pqrs_KeyRemap4MacBook { class KeyCode; class Flags; class Buttons; // ====================================================================== class EventType { public: EventType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const EventType& other) const { return value_ == other.get(); } bool operator!=(const EventType& other) const { return ! (*this == other); } bool isKeyDownOrModifierDown(const KeyCode& key, const Flags& flags) const; #include "keycode/output/include.EventType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyboardType { public: KeyboardType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyboardType& other) const { return value_ == other.get(); } bool operator!=(const KeyboardType& other) const { return ! (*this == other); } bool isInternalKeyboard(void) const; #include "keycode/output/include.KeyboardType.hpp" private: unsigned int value_; }; // ====================================================================== class ModifierFlag { public: unsigned int get(void) const { return value_; } bool operator==(const ModifierFlag& other) const { return value_ == other.get(); } bool operator!=(const ModifierFlag& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } const KeyCode& getKeyCode(void) const; #include "keycode/output/include.ModifierFlag.hpp" private: ModifierFlag(unsigned int v) : value_(v) {} unsigned int value_; }; class Flags { public: Flags(unsigned int v = 0) : value_(v) {} Flags(const ModifierFlag& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Flags& other) const { return value_ == other.get(); } bool operator!=(const Flags& other) const { return ! (*this == other); } Flags operator|(const Flags& other) const { return value_ | other.get(); } Flags operator&(const Flags& other) const { return value_ & other.get(); } Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; } Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; } Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; } Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; } Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; } bool isOn(const ModifierFlag& flag) const { return (value_ & flag.get()) == flag.get(); } bool isOn(const Flags& flags) const { if (flags.isOn(ModifierFlag::NONE)) { return (value_ | ModifierFlag::NONE.get()) == flags.get(); } else { return (value_ & flags.get()) == flags.get(); } } private: unsigned int value_; }; inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); } // ====================================================================== class KeyCode { public: KeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyCode& other) const { return value_ == other.get(); } bool operator!=(const KeyCode& other) const { return ! (*this == other); } bool operator> (const KeyCode& other) const { return value_ > other.get(); } bool operator>=(const KeyCode& other) const { return value_ >= other.get(); } void normalizeKey(Flags& flags, const KeyboardType& keyboardType); void reverseNormalizeKey(Flags& flags, const KeyboardType& keyboardType); ModifierFlag getModifierFlag(void) const; bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; } #include "keycode/output/include.KeyCode.hpp" private: unsigned int value_; }; class CharCode { public: CharCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const CharCode& other) const { return value_ == other.get(); } bool operator!=(const CharCode& other) const { return ! (*this == other); } private: unsigned int value_; }; class CharSet { public: CharSet(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const CharSet& other) const { return value_ == other.get(); } bool operator!=(const CharSet& other) const { return ! (*this == other); } private: unsigned int value_; }; class OrigCharCode { public: OrigCharCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const OrigCharCode& other) const { return value_ == other.get(); } bool operator!=(const OrigCharCode& other) const { return ! (*this == other); } private: unsigned int value_; }; class OrigCharSet { public: OrigCharSet(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const OrigCharSet& other) const { return value_ == other.get(); } bool operator!=(const OrigCharSet& other) const { return ! (*this == other); } private: unsigned int value_; }; // ====================================================================== class ConsumerKeyCode { public: ConsumerKeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); } bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); } bool operator> (const ConsumerKeyCode& other) const { return value_ > other.get(); } bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); } #include "keycode/output/include.ConsumerKeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class PointingButton { public: unsigned int get(void) const { return value_; } bool operator==(const PointingButton& other) const { return value_ == other.get(); } bool operator!=(const PointingButton& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } #include "keycode/output/include.PointingButton.hpp" private: PointingButton(unsigned int v) : value_(v) {} unsigned int value_; }; class Buttons { public: Buttons(unsigned int v = 0) : value_(v) {} Buttons(const PointingButton& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Buttons& other) const { return value_ == other.get(); } bool operator!=(const Buttons& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } Buttons operator|(const Buttons& other) const { return value_ | other.get(); } Buttons& add(const Buttons& button) { value_ |= button.get(); return *this; } Buttons& remove(const Buttons& button) { value_ &= ~button; return *this; } bool isNONE(void) const { return value_ == 0; } bool isOn(const Buttons& buttons) const { return (value_ & buttons.get()) == buttons.get(); } private: unsigned int value_; }; inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); } } #endif <commit_msg>apply uncrustify<commit_after>#ifndef KEYCODE_HPP #define KEYCODE_HPP namespace org_pqrs_KeyRemap4MacBook { class KeyCode; class Flags; class Buttons; // ====================================================================== class EventType { public: EventType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const EventType& other) const { return value_ == other.get(); } bool operator!=(const EventType& other) const { return ! (*this == other); } bool isKeyDownOrModifierDown(const KeyCode& key, const Flags& flags) const; #include "keycode/output/include.EventType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyboardType { public: KeyboardType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyboardType& other) const { return value_ == other.get(); } bool operator!=(const KeyboardType& other) const { return ! (*this == other); } bool isInternalKeyboard(void) const; #include "keycode/output/include.KeyboardType.hpp" private: unsigned int value_; }; // ====================================================================== class ModifierFlag { public: unsigned int get(void) const { return value_; } bool operator==(const ModifierFlag& other) const { return value_ == other.get(); } bool operator!=(const ModifierFlag& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } const KeyCode& getKeyCode(void) const; #include "keycode/output/include.ModifierFlag.hpp" private: ModifierFlag(unsigned int v) : value_(v) {} unsigned int value_; }; class Flags { public: Flags(unsigned int v = 0) : value_(v) {} Flags(const ModifierFlag& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Flags& other) const { return value_ == other.get(); } bool operator!=(const Flags& other) const { return ! (*this == other); } Flags operator|(const Flags& other) const { return value_ | other.get(); } Flags operator&(const Flags& other) const { return value_ & other.get(); } Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; } Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; } Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; } Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; } Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; } bool isOn(const ModifierFlag& flag) const { return (value_ & flag.get()) == flag.get(); } bool isOn(const Flags& flags) const { if (flags.isOn(ModifierFlag::NONE)) { return (value_ | ModifierFlag::NONE.get()) == flags.get(); } else { return (value_ & flags.get()) == flags.get(); } } private: unsigned int value_; }; inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); } // ====================================================================== class KeyCode { public: KeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyCode& other) const { return value_ == other.get(); } bool operator!=(const KeyCode& other) const { return ! (*this == other); } bool operator>(const KeyCode& other) const { return value_ > other.get(); } bool operator>=(const KeyCode& other) const { return value_ >= other.get(); } void normalizeKey(Flags& flags, const KeyboardType& keyboardType); void reverseNormalizeKey(Flags& flags, const KeyboardType& keyboardType); ModifierFlag getModifierFlag(void) const; bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; } #include "keycode/output/include.KeyCode.hpp" private: unsigned int value_; }; class CharCode { public: CharCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const CharCode& other) const { return value_ == other.get(); } bool operator!=(const CharCode& other) const { return ! (*this == other); } private: unsigned int value_; }; class CharSet { public: CharSet(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const CharSet& other) const { return value_ == other.get(); } bool operator!=(const CharSet& other) const { return ! (*this == other); } private: unsigned int value_; }; class OrigCharCode { public: OrigCharCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const OrigCharCode& other) const { return value_ == other.get(); } bool operator!=(const OrigCharCode& other) const { return ! (*this == other); } private: unsigned int value_; }; class OrigCharSet { public: OrigCharSet(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const OrigCharSet& other) const { return value_ == other.get(); } bool operator!=(const OrigCharSet& other) const { return ! (*this == other); } private: unsigned int value_; }; // ====================================================================== class ConsumerKeyCode { public: ConsumerKeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); } bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); } bool operator>(const ConsumerKeyCode& other) const { return value_ > other.get(); } bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); } #include "keycode/output/include.ConsumerKeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class PointingButton { public: unsigned int get(void) const { return value_; } bool operator==(const PointingButton& other) const { return value_ == other.get(); } bool operator!=(const PointingButton& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } #include "keycode/output/include.PointingButton.hpp" private: PointingButton(unsigned int v) : value_(v) {} unsigned int value_; }; class Buttons { public: Buttons(unsigned int v = 0) : value_(v) {} Buttons(const PointingButton& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Buttons& other) const { return value_ == other.get(); } bool operator!=(const Buttons& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } Buttons operator|(const Buttons& other) const { return value_ | other.get(); } Buttons& add(const Buttons& button) { value_ |= button.get(); return *this; } Buttons& remove(const Buttons& button) { value_ &= ~button; return *this; } bool isNONE(void) const { return value_ == 0; } bool isOn(const Buttons& buttons) const { return (value_ & buttons.get()) == buttons.get(); } private: unsigned int value_; }; inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); } } #endif <|endoftext|>
<commit_before>#ifndef KEYCODE_HPP #define KEYCODE_HPP namespace org_pqrs_KeyRemap4MacBook { // ====================================================================== class EventType { public: EventType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const EventType& other) const { return value_ == other.get(); } bool operator!=(const EventType& other) const { return ! (*this == other); } #include "keycode/output/include.EventType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyboardType { public: KeyboardType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyboardType& other) const { return value_ == other.get(); } bool operator!=(const KeyboardType& other) const { return ! (*this == other); } bool isInternalKeyboard(void) const; #include "keycode/output/include.KeyboardType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyCode; class Flags; class ModifierFlag { public: unsigned int get(void) const { return value_; } bool operator==(const ModifierFlag& other) const { return value_ == other.get(); } bool operator!=(const ModifierFlag& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } const KeyCode& getKeyCode(void) const; #include "keycode/output/include.ModifierFlag.hpp" private: ModifierFlag(unsigned int v) : value_(v) {} unsigned int value_; }; namespace ModifierFlagList { const ModifierFlag list[] = { ModifierFlag::CAPSLOCK, ModifierFlag::SHIFT_L, ModifierFlag::SHIFT_R, ModifierFlag::CONTROL_L, ModifierFlag::CONTROL_R, ModifierFlag::OPTION_L, ModifierFlag::OPTION_R, ModifierFlag::COMMAND_L, ModifierFlag::COMMAND_R, ModifierFlag::FN, }; const int listsize = sizeof(list) / sizeof(list[0]); }; class Flags { public: Flags(unsigned int v = 0) : value_(v) {} Flags(const ModifierFlag& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Flags& other) const { return value_ == other.get(); } bool operator!=(const Flags& other) const { return ! (*this == other); } Flags operator|(const Flags& other) const { return value_ | other.get(); } Flags operator|(const ModifierFlag& other) const { return value_ | other.get(); } Flags& add(const ModifierFlag& flag) { value_ |= flag.get(); return *this; } Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; } Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; } Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; } Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; } Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; } bool isOn(const ModifierFlag& flag) const { return (value_ & flag.get()) == flag.get(); } private: unsigned int value_; }; inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); } // ====================================================================== class KeyCode { public: KeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyCode& other) const { return value_ == other.get(); } bool operator!=(const KeyCode& other) const { return ! (*this == other); } bool operator> (const KeyCode& other) const { return value_ > other.get(); } bool operator>=(const KeyCode& other) const { return value_ >= other.get(); } void normalizeKey(Flags & flags, const KeyboardType &keyboardType); void reverseNormalizeKey(Flags & flags, const KeyboardType &keyboardType); ModifierFlag getModifierFlag(void) const; bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; } #include "keycode/output/include.KeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class ConsumerKeyCode { public: ConsumerKeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); } bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); } bool operator> (const ConsumerKeyCode& other) const { return value_ > other.get(); } bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); } #include "keycode/output/include.ConsumerKeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class Buttons; class PointingButton { public: unsigned int get(void) const { return value_; } bool operator==(const PointingButton& other) const { return value_ == other.get(); } bool operator!=(const PointingButton& other) const { return ! (*this == other); } #include "keycode/output/include.PointingButton.hpp" private: PointingButton(unsigned int v) : value_(v) {} unsigned int value_; }; class Buttons { public: Buttons(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const Buttons& other) const { return value_ == other.get(); } bool operator!=(const Buttons& other) const { return ! (*this == other); } bool isNONE(void) const { return value_ == 0; } private: unsigned int value_; }; inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); } } #endif <commit_msg>update keycode @ kext<commit_after>#ifndef KEYCODE_HPP #define KEYCODE_HPP namespace org_pqrs_KeyRemap4MacBook { // ====================================================================== class EventType { public: EventType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const EventType& other) const { return value_ == other.get(); } bool operator!=(const EventType& other) const { return ! (*this == other); } #include "keycode/output/include.EventType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyboardType { public: KeyboardType(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyboardType& other) const { return value_ == other.get(); } bool operator!=(const KeyboardType& other) const { return ! (*this == other); } bool isInternalKeyboard(void) const; #include "keycode/output/include.KeyboardType.hpp" private: unsigned int value_; }; // ====================================================================== class KeyCode; class Flags; class ModifierFlag { public: unsigned int get(void) const { return value_; } bool operator==(const ModifierFlag& other) const { return value_ == other.get(); } bool operator!=(const ModifierFlag& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } const KeyCode& getKeyCode(void) const; #include "keycode/output/include.ModifierFlag.hpp" private: ModifierFlag(unsigned int v) : value_(v) {} unsigned int value_; }; namespace ModifierFlagList { const ModifierFlag list[] = { ModifierFlag::CAPSLOCK, ModifierFlag::SHIFT_L, ModifierFlag::SHIFT_R, ModifierFlag::CONTROL_L, ModifierFlag::CONTROL_R, ModifierFlag::OPTION_L, ModifierFlag::OPTION_R, ModifierFlag::COMMAND_L, ModifierFlag::COMMAND_R, ModifierFlag::FN, }; const int listsize = sizeof(list) / sizeof(list[0]); }; class Flags { public: Flags(unsigned int v = 0) : value_(v) {} Flags(const ModifierFlag& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Flags& other) const { return value_ == other.get(); } bool operator!=(const Flags& other) const { return ! (*this == other); } Flags operator|(const Flags& other) const { return value_ | other.get(); } Flags operator|(const ModifierFlag& other) const { return value_ | other.get(); } Flags& add(const ModifierFlag& flag) { value_ |= flag.get(); return *this; } Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; } Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; } Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; } Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; } Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; } bool isOn(const ModifierFlag& flag) const { return (value_ & flag.get()) == flag.get(); } private: unsigned int value_; }; inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); } // ====================================================================== class KeyCode { public: KeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const KeyCode& other) const { return value_ == other.get(); } bool operator!=(const KeyCode& other) const { return ! (*this == other); } bool operator> (const KeyCode& other) const { return value_ > other.get(); } bool operator>=(const KeyCode& other) const { return value_ >= other.get(); } void normalizeKey(Flags & flags, const KeyboardType &keyboardType); void reverseNormalizeKey(Flags & flags, const KeyboardType &keyboardType); ModifierFlag getModifierFlag(void) const; bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; } #include "keycode/output/include.KeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class ConsumerKeyCode { public: ConsumerKeyCode(unsigned int v = 0) : value_(v) {} unsigned int get(void) const { return value_; } bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); } bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); } bool operator> (const ConsumerKeyCode& other) const { return value_ > other.get(); } bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); } #include "keycode/output/include.ConsumerKeyCode.hpp" private: unsigned int value_; }; // ====================================================================== class Buttons; class PointingButton { public: unsigned int get(void) const { return value_; } bool operator==(const PointingButton& other) const { return value_ == other.get(); } bool operator!=(const PointingButton& other) const { return ! (*this == other); } unsigned int operator~(void) const { return ~value_; } #include "keycode/output/include.PointingButton.hpp" private: PointingButton(unsigned int v) : value_(v) {} unsigned int value_; }; class Buttons { public: Buttons(unsigned int v = 0) : value_(v) {} Buttons(const PointingButton& v) : value_(v.get()) {} unsigned int get(void) const { return value_; } bool operator==(const Buttons& other) const { return value_ == other.get(); } bool operator!=(const Buttons& other) const { return ! (*this == other); } Buttons& add(const PointingButton& button) { value_ |= button.get(); return *this; } Buttons& remove(const PointingButton& button) { value_ &= ~button; return *this; } bool isNONE(void) const { return value_ == 0; } private: unsigned int value_; }; inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); } } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtCore module of the Qt eXTension library ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of th Common Public License, version 1.0, as published by ** IBM. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL along with this file. ** See the LICENSE file and the cpl1.0.txt file included with the source ** distribution for more information. If you did not receive a copy of the ** license, contact the Qxt Foundation. ** ** <http://libqxt.sourceforge.net> <libqxt@gmail.com> ** ****************************************************************************/ #include "qxtsemaphore.h" /** \class QxtSemaphore QxtSemaphore \ingroup core \brief system wide semaphore (former QxtSingleInstance) \code QxtSemaphore instance("com.mycompany.foobla.uniquestring"); if(!instance.trylock()) { qDebug("already started") } \endcode Note that the semaphore is autoaticly unlocked on destruction, but not on segfault,sigkill,etc...! */ #ifdef Q_WS_WIN #include "Windows.h" class QxtSemaphorePrivate : public QxtPrivate<QxtSemaphore> { public: QString name; unsigned sem_m; void init() { sem_m=0; } bool trylock() { sem_m = (unsigned ) CreateSemaphoreA ( NULL , 1 , 2 , qPrintable("Global\\"+name) ); if (sem_m == 0 ) return false; return true; } bool unlock() { if(sem_m==0) return false; return CloseHandle((void *)sem_m); } }; #else #include <semaphore.h> #include <fcntl.h> #include <errno.h> class QxtSemaphorePrivate : public QxtPrivate<QxtSemaphore> { public: QString name; sem_t* m_sem; bool s_N; void init() { s_N=false; m_sem=NULL; } bool trylock() { m_sem=sem_open(qPrintable(name), O_CREAT, S_IRUSR | S_IWUSR, 1); if(m_sem==SEM_FAILED || sem_trywait(m_sem)) { m_sem=NULL; s_N=true; return false; } s_N=false; return true; } bool unlock() { if(m_sem==NULL) return false; if(!s_N) { sem_post(m_sem); } return (sem_close(m_sem)==0); } }; #endif QxtSemaphore::QxtSemaphore(QString uniqueID) { qxt_d().name=uniqueID; qxt_d().init(); } QxtSemaphore::~QxtSemaphore() { unlock(); } bool QxtSemaphore::trylock() { return qxt_d().trylock(); } bool QxtSemaphore::unlock() { return qxt_d().unlock(); } <commit_msg>this should make ISO C++ happy on both platforms<commit_after>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtCore module of the Qt eXTension library ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of th Common Public License, version 1.0, as published by ** IBM. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL along with this file. ** See the LICENSE file and the cpl1.0.txt file included with the source ** distribution for more information. If you did not receive a copy of the ** license, contact the Qxt Foundation. ** ** <http://libqxt.sourceforge.net> <libqxt@gmail.com> ** ****************************************************************************/ #include "qxtsemaphore.h" /** \class QxtSemaphore QxtSemaphore \ingroup core \brief system wide semaphore (former QxtSingleInstance) \code QxtSemaphore instance("com.mycompany.foobla.uniquestring"); if(!instance.trylock()) { qDebug("already started") } \endcode Note that the semaphore is autoaticly unlocked on destruction, but not on segfault,sigkill,etc...! */ #ifdef Q_WS_WIN #include "Windows.h" class QxtSemaphorePrivate : public QxtPrivate<QxtSemaphore> { public: QString name; unsigned sem_m; void init() { sem_m=0; } bool trylock() { sem_m = (unsigned ) CreateSemaphoreA ( NULL , 1 , 2 , qPrintable("Global\\"+name) ); if (sem_m == 0 ) return false; return true; } bool unlock() { if(sem_m==0) return false; return CloseHandle((void *)sem_m); } }; #else #include <semaphore.h> #include <fcntl.h> #include <errno.h> class QxtSemaphorePrivate : public QxtPrivate<QxtSemaphore> { public: QString name; sem_t* m_sem; bool s_N; void init() { s_N=false; m_sem=NULL; } bool trylock() { m_sem=sem_open(qPrintable(name), O_CREAT, S_IRUSR | S_IWUSR, 1); if(m_sem==(sem_t*)(SEM_FAILED) || sem_trywait(m_sem)) { m_sem=NULL; s_N=true; return false; } s_N=false; return true; } bool unlock() { if(m_sem==NULL) return false; if(!s_N) { sem_post(m_sem); } return (sem_close(m_sem)==0); } }; #endif QxtSemaphore::QxtSemaphore(QString uniqueID) { qxt_d().name=uniqueID; qxt_d().init(); } QxtSemaphore::~QxtSemaphore() { unlock(); } bool QxtSemaphore::trylock() { return qxt_d().trylock(); } bool QxtSemaphore::unlock() { return qxt_d().unlock(); } <|endoftext|>
<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal.h" #include "args.h" #include "trace.h" #include "deps_resolver.h" #include "utils.h" #include "coreclr.h" enum StatusCode { Failure = 0x87FF0000, InvalidArgFailure = Failure | 0x1, CoreClrResolveFailure = Failure | 0x2, CoreClrBindFailure = Failure | 0x3, CoreClrInitFailure = Failure | 0x4, CoreClrExeFailure = Failure | 0x5, ResolverInitFailure = Failure | 0x6, ResolverResolveFailure = Failure | 0x7, }; // ---------------------------------------------------------------------- // resolve_clr_path: Resolve CLR Path in priority order // // Description: // Check if CoreCLR library exists in runtime servicing dir or app // local or DOTNET_HOME directory in that order of priority. If these // fail to locate CoreCLR, then check platform-specific search. // // Returns: // "true" if path to the CoreCLR dir can be resolved in "clr_path" // parameter. Else, returns "false" with "clr_path" unmodified. // bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path) { const pal::string_t* dirs[] = { &args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING &args.app_dir, // APP LOCAL &args.dotnet_home // DOTNET_HOME }; for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i) { if (dirs[i]->empty()) { continue; } // App dir should contain coreclr, so skip appending path. pal::string_t cur_dir = *dirs[i]; if (dirs[i] != &args.app_dir) { append_path(&cur_dir, _X("runtime")); append_path(&cur_dir, _X("coreclr")); } // Found coreclr in priority order. if (coreclr_exists_in_dir(cur_dir)) { clr_path->assign(cur_dir); return true; } } // Use platform-specific search algorithm pal::string_t home_dir = args.dotnet_home; if (pal::find_coreclr(&home_dir)) { clr_path->assign(home_dir); return true; } return false; } int run(const arguments_t& args, const pal::string_t& clr_path) { // Load the deps resolver deps_resolver_t resolver(args); if (!resolver.valid()) { trace::error(_X("Invalid .deps file")); return StatusCode::ResolverInitFailure; } // Add packages directory pal::string_t packages_dir = args.dotnet_packages; if (!pal::directory_exists(packages_dir)) { (void)pal::get_default_packages_directory(&packages_dir); } trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str()); probe_paths_t probe_paths; if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths)) { return StatusCode::ResolverResolveFailure; } // Build CoreCLR properties const char* property_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "PLATFORM_RESOURCE_ROOTS", "AppDomainCompatSwitch", // TODO: pipe this from corehost.json "SERVER_GC" }; auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa); auto app_base_cstr = pal::to_stdstring(args.app_dir); auto native_dirs_cstr = pal::to_stdstring(probe_paths.native); auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture); const char* property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpa_paths_cstr.c_str(), // APP_PATHS app_base_cstr.c_str(), // APP_NI_PATHS app_base_cstr.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES native_dirs_cstr.c_str(), // PLATFORM_RESOURCE_ROOTS culture_dirs_cstr.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified", // SERVER_GC "1" }; size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]); // Bind CoreCLR if (!coreclr::bind(clr_path)) { trace::error(_X("Failed to bind to coreclr")); return StatusCode::CoreClrBindFailure; } // Verbose logging if (trace::is_enabled()) { for (size_t i = 0; i < property_size; ++i) { pal::string_t key, val; pal::to_palstring(property_keys[i], &key); pal::to_palstring(property_values[i], &val); trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str()); } } std::string own_path; pal::to_stdstring(args.own_path.c_str(), &own_path); // Initialize CoreCLR coreclr::host_handle_t host_handle; coreclr::domain_id_t domain_id; auto hr = coreclr::initialize( own_path.c_str(), "clrhost", property_keys, property_values, property_size, &host_handle, &domain_id); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr); return StatusCode::CoreClrInitFailure; } if (trace::is_enabled()) { pal::string_t arg_str; for (int i = 0; i < args.app_argc; i++) { arg_str.append(args.app_argv[i]); arg_str.append(_X(",")); } trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(), args.managed_application.c_str(), args.app_argc, arg_str.c_str()); } // Initialize with empty strings std::vector<std::string> argv_strs(args.app_argc); std::vector<const char*> argv(args.app_argc); for (int i = 0; i < args.app_argc; i++) { pal::to_stdstring(args.app_argv[i], &argv_strs[i]); argv[i] = argv_strs[i].c_str(); } // Execute the application unsigned int exit_code = 1; hr = coreclr::execute_assembly( host_handle, domain_id, argv.size(), argv.data(), pal::to_stdstring(args.managed_application).c_str(), &exit_code); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr); return StatusCode::CoreClrExeFailure; } // Shut down the CoreCLR hr = coreclr::shutdown(host_handle, domain_id); if (!SUCCEEDED(hr)) { trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr); } coreclr::unload(); return exit_code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { // Take care of arguments arguments_t args; if (!parse_arguments(argc, argv, args)) { return StatusCode::InvalidArgFailure; } // Resolve CLR path pal::string_t clr_path; if (!resolve_clr_path(args, &clr_path)) { trace::error(_X("Could not resolve coreclr path")); return StatusCode::CoreClrResolveFailure; } return run(args, clr_path); } <commit_msg>Use environment variable to disable Server GC<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal.h" #include "args.h" #include "trace.h" #include "deps_resolver.h" #include "utils.h" #include "coreclr.h" enum StatusCode { Failure = 0x87FF0000, InvalidArgFailure = Failure | 0x1, CoreClrResolveFailure = Failure | 0x2, CoreClrBindFailure = Failure | 0x3, CoreClrInitFailure = Failure | 0x4, CoreClrExeFailure = Failure | 0x5, ResolverInitFailure = Failure | 0x6, ResolverResolveFailure = Failure | 0x7, }; // ---------------------------------------------------------------------- // resolve_clr_path: Resolve CLR Path in priority order // // Description: // Check if CoreCLR library exists in runtime servicing dir or app // local or DOTNET_HOME directory in that order of priority. If these // fail to locate CoreCLR, then check platform-specific search. // // Returns: // "true" if path to the CoreCLR dir can be resolved in "clr_path" // parameter. Else, returns "false" with "clr_path" unmodified. // bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path) { const pal::string_t* dirs[] = { &args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING &args.app_dir, // APP LOCAL &args.dotnet_home // DOTNET_HOME }; for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i) { if (dirs[i]->empty()) { continue; } // App dir should contain coreclr, so skip appending path. pal::string_t cur_dir = *dirs[i]; if (dirs[i] != &args.app_dir) { append_path(&cur_dir, _X("runtime")); append_path(&cur_dir, _X("coreclr")); } // Found coreclr in priority order. if (coreclr_exists_in_dir(cur_dir)) { clr_path->assign(cur_dir); return true; } } // Use platform-specific search algorithm pal::string_t home_dir = args.dotnet_home; if (pal::find_coreclr(&home_dir)) { clr_path->assign(home_dir); return true; } return false; } int run(const arguments_t& args, const pal::string_t& clr_path) { // Load the deps resolver deps_resolver_t resolver(args); if (!resolver.valid()) { trace::error(_X("Invalid .deps file")); return StatusCode::ResolverInitFailure; } // Add packages directory pal::string_t packages_dir = args.dotnet_packages; if (!pal::directory_exists(packages_dir)) { (void)pal::get_default_packages_directory(&packages_dir); } trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str()); probe_paths_t probe_paths; if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths)) { return StatusCode::ResolverResolveFailure; } // Build CoreCLR properties const char* property_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "PLATFORM_RESOURCE_ROOTS", "AppDomainCompatSwitch", // TODO: pipe this from corehost.json "SERVER_GC", }; auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa); auto app_base_cstr = pal::to_stdstring(args.app_dir); auto native_dirs_cstr = pal::to_stdstring(probe_paths.native); auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture); // Workaround for dotnet/cli Issue #488 and #652 pal::string_t server_gc; std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc)) ? pal::to_stdstring(server_gc) : "1"; const char* property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpa_paths_cstr.c_str(), // APP_PATHS app_base_cstr.c_str(), // APP_NI_PATHS app_base_cstr.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES native_dirs_cstr.c_str(), // PLATFORM_RESOURCE_ROOTS culture_dirs_cstr.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified", // SERVER_GC server_gc_cstr.c_str(), }; size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]); // Bind CoreCLR if (!coreclr::bind(clr_path)) { trace::error(_X("Failed to bind to coreclr")); return StatusCode::CoreClrBindFailure; } // Verbose logging if (trace::is_enabled()) { for (size_t i = 0; i < property_size; ++i) { pal::string_t key, val; pal::to_palstring(property_keys[i], &key); pal::to_palstring(property_values[i], &val); trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str()); } } std::string own_path; pal::to_stdstring(args.own_path.c_str(), &own_path); // Initialize CoreCLR coreclr::host_handle_t host_handle; coreclr::domain_id_t domain_id; auto hr = coreclr::initialize( own_path.c_str(), "clrhost", property_keys, property_values, property_size, &host_handle, &domain_id); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr); return StatusCode::CoreClrInitFailure; } if (trace::is_enabled()) { pal::string_t arg_str; for (int i = 0; i < args.app_argc; i++) { arg_str.append(args.app_argv[i]); arg_str.append(_X(",")); } trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(), args.managed_application.c_str(), args.app_argc, arg_str.c_str()); } // Initialize with empty strings std::vector<std::string> argv_strs(args.app_argc); std::vector<const char*> argv(args.app_argc); for (int i = 0; i < args.app_argc; i++) { pal::to_stdstring(args.app_argv[i], &argv_strs[i]); argv[i] = argv_strs[i].c_str(); } // Execute the application unsigned int exit_code = 1; hr = coreclr::execute_assembly( host_handle, domain_id, argv.size(), argv.data(), pal::to_stdstring(args.managed_application).c_str(), &exit_code); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr); return StatusCode::CoreClrExeFailure; } // Shut down the CoreCLR hr = coreclr::shutdown(host_handle, domain_id); if (!SUCCEEDED(hr)) { trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr); } coreclr::unload(); return exit_code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { // Take care of arguments arguments_t args; if (!parse_arguments(argc, argv, args)) { return StatusCode::InvalidArgFailure; } // Resolve CLR path pal::string_t clr_path; if (!resolve_clr_path(args, &clr_path)) { trace::error(_X("Could not resolve coreclr path")); return StatusCode::CoreClrResolveFailure; } return run(args, clr_path); } <|endoftext|>
<commit_before>/* * Main.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <iostream> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/Log.hpp> #include <core/system/System.hpp> #include <core/spelling/SpellChecker.hpp> using namespace core ; int main(int argc, char * const argv[]) { try { // initialize log initializeSystemLog("coredev", core::system::kLogLevelWarning); #if defined(__APPLE__) std::string hunspellPath = "libhunspell-1.2.dylib"; #else std::string hunspellPath = "libhunspell-1.2.so.0"; #endif boost::shared_ptr<core::spelling::SpellChecker> pSpellChecker; Error error = core::spelling::createHunspell(hunspellPath, &pSpellChecker); if (error) LOG_ERROR(error); return EXIT_SUCCESS; } CATCH_UNEXPECTED_EXCEPTION // if we got this far we had an unexpected exception return EXIT_FAILURE ; } <commit_msg>eliminate hunspell code from coredev<commit_after>/* * Main.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <iostream> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/Log.hpp> #include <core/system/System.hpp> using namespace core ; int main(int argc, char * const argv[]) { try { // initialize log initializeSystemLog("coredev", core::system::kLogLevelWarning); return EXIT_SUCCESS; } CATCH_UNEXPECTED_EXCEPTION // if we got this far we had an unexpected exception return EXIT_FAILURE ; } <|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include <sstream> #include <libHierGA/HierGA.hpp> #include "1maxFitness.hpp" using namespace std; int main(void) { HierarchicalEA ea(100); vector<Locus*> baseLoci(8, new IntLocus(0, 1)); vector<PopulationNode*> bottomNodes; vector<Locus*> populationLoci; ea.addConstructiveTree<EANode>( new LocusMultiplierPopFormula(2), {{}, baseLoci}, {{new OneMaxFitness()}, {new OneMaxFitness()}}, {new OneMaxToString(), new OneMaxToString()}, {{new IterationCountEnd(100)}, {new IterationCountEnd(100)}}, TreeBuilder("P1").addSubNodes("P1", {"P2", "P3", "P4", "P5"}), {true, false}, {true, false}, new GA(2, false, new TournamentSelection(0.95, 4)), new NPointCrossover(2), new UniformMutation(0.2) ); ea.setEvolutionOrder({"P5", "P4", "P3", "P2", "P1"}); ea.run(true); ea.deleteAllNodes(); } <commit_msg>[Hier1max Example]: Streamlined code a bit<commit_after>#include <cstdio> #include <iostream> #include <sstream> #include <libHierGA/HierGA.hpp> #include "1maxFitness.hpp" using namespace std; int main(void) { HierarchicalEA ea(100); ea.addConstructiveTree<EANode>( new LocusMultiplierPopFormula(2), {{}, vector<Locus*>(8, new IntLocus(0, 1))}, {{new OneMaxFitness()}, {new OneMaxFitness()}}, {new OneMaxToString(), new OneMaxToString()}, {{new IterationCountEnd(100)}, {new IterationCountEnd(100)}}, TreeBuilder("P1").addSubNodes("P1", {"P2", "P3", "P4", "P5"}), {true, false}, {true, false}, new GA(2, false, new TournamentSelection(0.95, 4)), new NPointCrossover(2), new UniformMutation(0.2) ); ea.setEvolutionOrder({"P5", "P4", "P3", "P2", "P1"}); ea.run(true); ea.deleteAllNodes(); } <|endoftext|>
<commit_before>/** * \author Allann Jones */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QDir> #include <QFileDialog> #include <QMessageBox> #include <iostream> MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow) { currentWatchPath = ""; ui->setupUi(this); // Execution file path ui->labelExecutionPath->setText(qApp->applicationDirPath()); // Enable filesytem watcher watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &))); connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &))); // Path to monitor //watcher->addPath(ui->lineEditDevEventsFile->text()); } MainWindow::~MainWindow() { MainWindow::unwatchPath(); delete ui; delete watcher; } void MainWindow::directoryChanged(const QString& path) { logText("DIR CHANGE: " + path); } void MainWindow::fileChanged(const QString& path) { logText("FILE CHANGE: " + path); } void MainWindow::logText(const QString &str) { ui->textEdit->setText(ui->textEdit->toPlainText() + str + "\n"); } void MainWindow::on_actionWatcherControl_triggered() { // Unwatch if there is a watched path unwatchPath(); // Path to monitor bool rv = watcher->addPath(ui->lineEditDevEventsFile->text()); if (!rv) { logText("Error on trying to watch path: " + ui->lineEditDevEventsFile->text()); } else { currentWatchPath = ui->lineEditDevEventsFile->text(); logText("Watching path: " + ui->lineEditDevEventsFile->text()); } } void MainWindow::unwatchPath() { if (currentWatchPath.length() > 0) { logText("Unwatching path: " + currentWatchPath); watcher->removePath(currentWatchPath); } } void MainWindow::on_pushButton_clicked() { QFileDialog dialog; if (ui->lineEditDevEventsFile->text().length() > 0) { QFileInfo fileInfo(ui->lineEditDevEventsFile->text()); dialog.setDirectory(fileInfo.dir()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditDevEventsFile->setText(dirName); } } void MainWindow::on_pushButton_2_clicked() { QFileDialog dialog(this, tr("Choose directory where resides ADB")); dialog.setFileMode(QFileDialog::Directory); dialog.setOption(QFileDialog::ShowDirsOnly); if (ui->lineEditAdbDir->text().length() > 0) { dialog.setDirectory(ui->lineEditAdbDir->text()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditAdbDir->setText(dirName); } } void MainWindow::on_pushButtonApkPath_clicked() { QFileDialog dialog(this, tr("Choose Android APK to install when device is plugged")); dialog.setNameFilter(tr("Android APK files (*.apk)")); if (ui->lineEditApkPath->text().length() > 0) { QFileInfo fileInfo(ui->lineEditApkPath->text()); dialog.setDirectory(fileInfo.dir()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditApkPath->setText(dirName); } } <commit_msg>Read events file and get the last event occurred<commit_after>/** * \author Allann Jones */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QDir> #include <QFileDialog> #include <QMessageBox> #include <QProcess> #include <iostream> MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow) { currentWatchPath = ""; ui->setupUi(this); // Execution file path ui->labelExecutionPath->setText(qApp->applicationDirPath()); // Enable filesytem watcher watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &))); connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &))); // Path to monitor //watcher->addPath(ui->lineEditDevEventsFile->text()); } MainWindow::~MainWindow() { MainWindow::unwatchPath(); delete ui; delete watcher; } void MainWindow::directoryChanged(const QString& path) { logText("DIR CHANGE: " + path); } void MainWindow::fileChanged(const QString& path) { logText("FILE CHANGE: " + path); QProcess process; logText("Reading last entry from events file..."); process.start("tail -n 1 " + ui->lineEditDevEventsFile->text()); process.waitForFinished(-1); if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) { logText(QString("Exit code: %1").arg(process.exitCode())); } QString stdOutput = process.readAllStandardOutput().trimmed(); QString stdError = process.readAllStandardError().trimmed(); logText("Standard output: " + stdOutput); logText("Standard error: " + stdOutput); QRegExp regex("^DEV ADDED"); // Device was added if (regex.indexIn(stdOutput) >= 0) { logText("Device was added."); } // Device was removed else { logText("Device was removed."); } qDebug() << regex.captureCount(); //QThread::msleep(10); } void MainWindow::logText(const QString &str) { ui->textEdit->setText(ui->textEdit->toPlainText() + str + "\n"); } void MainWindow::on_actionWatcherControl_triggered() { // Unwatch if there is a watched path unwatchPath(); // Path to monitor bool rv = watcher->addPath(ui->lineEditDevEventsFile->text()); if (!rv) { logText("Error on trying to watch path: " + ui->lineEditDevEventsFile->text()); } else { currentWatchPath = ui->lineEditDevEventsFile->text(); logText("Watching path: " + ui->lineEditDevEventsFile->text()); } } void MainWindow::unwatchPath() { if (currentWatchPath.length() > 0) { logText("Unwatching path: " + currentWatchPath); watcher->removePath(currentWatchPath); } } void MainWindow::on_pushButton_clicked() { QFileDialog dialog; if (ui->lineEditDevEventsFile->text().length() > 0) { QFileInfo fileInfo(ui->lineEditDevEventsFile->text()); dialog.setDirectory(fileInfo.dir()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditDevEventsFile->setText(dirName); } } void MainWindow::on_pushButton_2_clicked() { QFileDialog dialog(this, tr("Choose directory where resides ADB")); dialog.setFileMode(QFileDialog::Directory); dialog.setOption(QFileDialog::ShowDirsOnly); if (ui->lineEditAdbDir->text().length() > 0) { dialog.setDirectory(ui->lineEditAdbDir->text()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditAdbDir->setText(dirName); } } void MainWindow::on_pushButtonApkPath_clicked() { QFileDialog dialog(this, tr("Choose Android APK to install when device is plugged")); dialog.setNameFilter(tr("Android APK files (*.apk)")); if (ui->lineEditApkPath->text().length() > 0) { QFileInfo fileInfo(ui->lineEditApkPath->text()); dialog.setDirectory(fileInfo.dir()); } int result = dialog.exec(); QString dirName = ""; if (result) { dirName = dialog.selectedFiles()[0]; qDebug() << dirName; } if (!dirName.isEmpty()) { ui->lineEditApkPath->setText(dirName); } } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedData.h" #include "MooseUtils.h" #include "MooseError.h" #include "libmesh/dense_vector.h" namespace StochasticTools { template <typename T> DistributedData<T>::DistributedData(const libMesh::Parallel::Communicator & comm_in) : libMesh::ParallelObject(comm_in), _closed(false), _n_local_entries(0) { } template <typename T> void DistributedData<T>::initializeContainer(unsigned int n_global_entries) { // This function can be used when a linear partitioning is required and the // number of global samples is known in advance. Need to do conversion because of // because of 64 bit dof indices. dof_id_type local_entry_begin; dof_id_type local_entry_end; dof_id_type n_local_entries; MooseUtils::linearPartitionItems(n_global_entries, n_processors(), processor_id(), n_local_entries, local_entry_begin, local_entry_end); _n_local_entries = n_local_entries; _local_entries.resize(_n_local_entries); _local_entry_ids.resize(_n_local_entries); // Filling the sample ID vector, leaving the elements of the sample vector // with the default constructor. for (dof_id_type entry_i = local_entry_begin; entry_i < local_entry_end; ++entry_i) { _local_entry_ids[entry_i] = entry_i; } } template <typename T> void DistributedData<T>::addNewEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") already exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot add new elements!"); _local_entries.push_back(entry); _local_entry_ids.push_back(glob_i); _n_local_entries += 1; } template <typename T> void DistributedData<T>::changeEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot change elements!"); _local_entries[std::distance(_local_entry_ids.begin(), it)] = entry; } template <typename T> const T & DistributedData<T>::getGlobalEntry(unsigned int glob_i) const { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return _local_entries[std::distance(_local_entry_ids.begin(), it)]; } template <typename T> const T & DistributedData<T>::getLocalEntry(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entries[loc_i]; } template <typename T> unsigned int DistributedData<T>::getNumberOfGlobalEntries() const { unsigned int val = _n_local_entries; _communicator.sum(val); return val; } template <typename T> bool DistributedData<T>::hasGlobalEntry(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) return true; return false; } template <typename T> unsigned int DistributedData<T>::getLocalIndex(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return std::distance(_local_entry_ids.begin(), it); } template <typename T> unsigned int DistributedData<T>::getGlobalIndex(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entry_ids[loc_i]; } // Explicit instantiation of types that are necessary. template class DistributedData<DenseVector<Real>>; template class DistributedData<std::shared_ptr<DenseVector<Real>>>; template class DistributedData<std::vector<Real>>; } // StochasticTools namespace <commit_msg>Apply modification to inline comment. (#15731)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedData.h" #include "MooseUtils.h" #include "MooseError.h" #include "libmesh/dense_vector.h" namespace StochasticTools { template <typename T> DistributedData<T>::DistributedData(const libMesh::Parallel::Communicator & comm_in) : libMesh::ParallelObject(comm_in), _closed(false), _n_local_entries(0) { } template <typename T> void DistributedData<T>::initializeContainer(unsigned int n_global_entries) { // This function can be used when a linear partitioning is required and the // number of global samples is known in advance. We must temporarily // use dof_id_type for the last three args (pass by reference), // but will cast back to unsigned int later dof_id_type local_entry_begin; dof_id_type local_entry_end; dof_id_type n_local_entries; MooseUtils::linearPartitionItems(n_global_entries, n_processors(), processor_id(), n_local_entries, local_entry_begin, local_entry_end); _n_local_entries = n_local_entries; _local_entries.resize(_n_local_entries); _local_entry_ids.resize(_n_local_entries); // Filling the sample ID vector, leaving the elements of the sample vector // with the default constructor. for (dof_id_type entry_i = local_entry_begin; entry_i < local_entry_end; ++entry_i) { _local_entry_ids[entry_i] = entry_i; } } template <typename T> void DistributedData<T>::addNewEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") already exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot add new elements!"); _local_entries.push_back(entry); _local_entry_ids.push_back(glob_i); _n_local_entries += 1; } template <typename T> void DistributedData<T>::changeEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot change elements!"); _local_entries[std::distance(_local_entry_ids.begin(), it)] = entry; } template <typename T> const T & DistributedData<T>::getGlobalEntry(unsigned int glob_i) const { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return _local_entries[std::distance(_local_entry_ids.begin(), it)]; } template <typename T> const T & DistributedData<T>::getLocalEntry(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entries[loc_i]; } template <typename T> unsigned int DistributedData<T>::getNumberOfGlobalEntries() const { unsigned int val = _n_local_entries; _communicator.sum(val); return val; } template <typename T> bool DistributedData<T>::hasGlobalEntry(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) return true; return false; } template <typename T> unsigned int DistributedData<T>::getLocalIndex(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return std::distance(_local_entry_ids.begin(), it); } template <typename T> unsigned int DistributedData<T>::getGlobalIndex(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entry_ids[loc_i]; } // Explicit instantiation of types that are necessary. template class DistributedData<DenseVector<Real>>; template class DistributedData<std::shared_ptr<DenseVector<Real>>>; template class DistributedData<std::vector<Real>>; } // StochasticTools namespace <|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 <sstream> #include "net/url_request/url_request_view_net_internal_job.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "net/base/escape.h" #include "net/base/host_cache.h" #include "net/base/load_log_util.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" namespace { //------------------------------------------------------------------------------ // Format helpers. //------------------------------------------------------------------------------ void OutputTextInPre(const std::string& text, std::string* out) { out->append("<pre>"); out->append(EscapeForHTML(text)); out->append("</pre>"); } //------------------------------------------------------------------------------ // Subsection definitions. //------------------------------------------------------------------------------ class SubSection { public: // |name| is the URL path component for this subsection. // |title| is the textual description. SubSection(SubSection* parent, const char* name, const char* title) : parent_(parent), name_(name), title_(title) { } virtual ~SubSection() { STLDeleteContainerPointers(children_.begin(), children_.end()); } // Outputs the subsection's contents to |out|. virtual void OutputBody(URLRequestContext* context, std::string* out) {} // Outputs this subsection, and all of its children. void OutputRecursive(URLRequestContext* context, std::string* out) { if (!is_root()) { std::string section_url = std::string("view-net-internal:") + GetFullyQualifiedName(); // Canonicalizing the URL escapes characters which cause problems in HTML. section_url = GURL(section_url).spec(); // Print the heading. out->append(StringPrintf("<div>" "<span class=subsection_title>%s</span> " "<span class=subsection_name>(<a href='%s'>%s</a>)<span>" "</div>", EscapeForHTML(title_).c_str(), section_url.c_str(), EscapeForHTML(section_url).c_str())); out->append("<div class=subsection_body>"); } OutputBody(context, out); for (size_t i = 0; i < children_.size(); ++i) children_[i]->OutputRecursive(context, out); if (!is_root()) out->append("</div>"); } // Returns the SubSection contained by |this| with fully qualified name // |dotted_name|, or NULL if none was found. SubSection* FindSubSectionByName(const std::string& dotted_name) { if (dotted_name == "") return this; std::string child_name; std::string child_sub_name; size_t split_pos = dotted_name.find('.'); if (split_pos == std::string::npos) { child_name = dotted_name; child_sub_name = std::string(); } else { child_name = dotted_name.substr(0, split_pos); child_sub_name = dotted_name.substr(split_pos + 1); } for (size_t i = 0; i < children_.size(); ++i) { if (children_[i]->name_ == child_name) return children_[i]->FindSubSectionByName(child_sub_name); } return NULL; // Not found. } std::string GetFullyQualifiedName() { if (!parent_) return name_; std::string parent_name = parent_->GetFullyQualifiedName(); if (parent_name.empty()) return name_; return parent_name + "." + name_; } bool is_root() const { return parent_ == NULL; } protected: typedef std::vector<SubSection*> SubSectionList; void AddSubSection(SubSection* subsection) { children_.push_back(subsection); } SubSection* parent_; std::string name_; std::string title_; SubSectionList children_; }; class ProxyServiceCurrentConfigSubSection : public SubSection { public: ProxyServiceCurrentConfigSubSection(SubSection* parent) : SubSection(parent, "config", "Current configuration") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { net::ProxyService* proxy_service = context->proxy_service(); if (proxy_service->config_has_been_initialized()) { // net::ProxyConfig defines an operator<<. std::ostringstream stream; stream << proxy_service->config(); OutputTextInPre(stream.str(), out); } else { out->append("<i>Not yet initialized</i>"); } } }; class ProxyServiceLastInitLogSubSection : public SubSection { public: ProxyServiceLastInitLogSubSection(SubSection* parent) : SubSection(parent, "init_log", "Last initialized load log") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { net::ProxyService* proxy_service = context->proxy_service(); net::LoadLog* log = proxy_service->init_proxy_resolver_log(); if (log) { OutputTextInPre(net::LoadLogUtil::PrettyPrintAsEventTree(log), out); } else { out->append("<i>None.</i>"); } } }; class ProxyServiceBadProxiesSubSection : public SubSection { public: ProxyServiceBadProxiesSubSection(SubSection* parent) : SubSection(parent, "bad_proxies", "Bad Proxies") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { out->append("TODO"); } }; class ProxyServiceSubSection : public SubSection { public: ProxyServiceSubSection(SubSection* parent) : SubSection(parent, "proxyservice", "ProxyService") { AddSubSection(new ProxyServiceCurrentConfigSubSection(this)); AddSubSection(new ProxyServiceLastInitLogSubSection(this)); AddSubSection(new ProxyServiceBadProxiesSubSection(this)); } }; class HostResolverCacheSubSection : public SubSection { public: HostResolverCacheSubSection(SubSection* parent) : SubSection(parent, "hostcache", "HostCache") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { const net::HostCache* host_cache = context->host_resolver()->GetHostCache(); if (!host_cache || host_cache->caching_is_disabled()) { out->append("<i>Caching is disabled.</i>"); return; } out->append(StringPrintf("<ul><li>Size: %u</li>" "<li>Capacity: %u</li>" "<li>Time to live (ms): %u</li></ul>", host_cache->size(), host_cache->max_entries(), host_cache->cache_duration_ms())); out->append("<table border=1>" "<tr>" "<th>Host</th>" "<th>First address</th>" "<th>Time to live (ms)</th>" "</tr>"); for (net::HostCache::EntryMap::const_iterator it = host_cache->entries().begin(); it != host_cache->entries().end(); ++it) { const std::string& host = it->first; const net::HostCache::Entry* entry = it->second.get(); if (entry->error == net::OK) { // Note that ttl_ms may be negative, for the cases where entries have // expired but not been garbage collected yet. int ttl_ms = static_cast<int>( (entry->expiration - base::TimeTicks::Now()).InMilliseconds()); // Color expired entries blue. if (ttl_ms > 0) { out->append("<tr>"); } else { out->append("<tr style='color:blue'>"); } std::string address_str = net::NetAddressToString(entry->addrlist.head()); out->append(StringPrintf("<td>%s</td><td>%s</td><td>%d</td></tr>", EscapeForHTML(host).c_str(), EscapeForHTML(address_str).c_str(), ttl_ms)); } else { // This was an entry that failed to be resolved. // Color negative entries red. out->append(StringPrintf( "<tr style='color:red'><td>%s</td>" "<td colspan=2>%s</td></tr>", EscapeForHTML(host).c_str(), EscapeForHTML(net::ErrorToString(entry->error)).c_str())); } } out->append("</table>"); } }; class HostResolverSubSection : public SubSection { public: HostResolverSubSection(SubSection* parent) : SubSection(parent, "hostresolver", "HostResolver") { AddSubSection(new HostResolverCacheSubSection(this)); } }; // Helper for the URLRequest "outstanding" and "live" sections. void OutputURLAndLoadLog(const GURL& url, const net::LoadLog* log, std::string* out) { out->append("<li>"); out->append("<nobr>"); out->append(EscapeForHTML(url.spec())); out->append("</nobr>"); if (log) OutputTextInPre(net::LoadLogUtil::PrettyPrintAsEventTree(log), out); out->append("</li>"); } class URLRequestLiveSubSection : public SubSection { public: URLRequestLiveSubSection(SubSection* parent) : SubSection(parent, "outstanding", "Outstanding requests") { } virtual void OutputBody(URLRequestContext* /*context*/, std::string* out) { URLRequest::InstanceTracker* tracker = URLRequest::InstanceTracker::Get(); // Note that these are the requests across ALL contexts. std::vector<URLRequest*> requests = tracker->GetLiveRequests(); out->append("<ol>"); for (size_t i = 0; i < requests.size(); ++i) { // Reverse the list order, so we dispay from most recent to oldest. size_t index = requests.size() - i - 1; OutputURLAndLoadLog(requests[index]->original_url(), requests[index]->load_log(), out); } out->append("</ol>"); } }; class URLRequestRecentSubSection : public SubSection { public: URLRequestRecentSubSection(SubSection* parent) : SubSection(parent, "recent", "Recently completed requests") { } virtual void OutputBody(URLRequestContext* /*context*/, std::string* out) { URLRequest::InstanceTracker* tracker = URLRequest::InstanceTracker::Get(); // Note that these are the recently completed requests across ALL contexts. URLRequest::InstanceTracker::RecentRequestInfoList recent = tracker->GetRecentlyDeceased(); out->append("<ol>"); for (size_t i = 0; i < recent.size(); ++i) { // Reverse the list order, so we dispay from most recent to oldest. size_t index = recent.size() - i - 1; OutputURLAndLoadLog(recent[index].original_url, recent[index].load_log, out); } out->append("</ol>"); } }; class URLRequestSubSection : public SubSection { public: URLRequestSubSection(SubSection* parent) : SubSection(parent, "urlrequest", "URLRequest") { AddSubSection(new URLRequestLiveSubSection(this)); AddSubSection(new URLRequestRecentSubSection(this)); } }; class AllSubSections : public SubSection { public: AllSubSections() : SubSection(NULL, "", "") { AddSubSection(new ProxyServiceSubSection(this)); AddSubSection(new HostResolverSubSection(this)); AddSubSection(new URLRequestSubSection(this)); } }; } // namespace // static URLRequestJob* URLRequestViewNetInternalJob::Factory( URLRequest* request, const std::string& scheme) { return new URLRequestViewNetInternalJob(request); } bool URLRequestViewNetInternalJob::GetData(std::string* mime_type, std::string* charset, std::string* data) const { DCHECK_EQ(std::string("view-net-internal"), request_->url().scheme()); mime_type->assign("text/html"); charset->assign("UTF-8"); URLRequestContext* context = request_->context(); std::string path = request_->url().path(); data->clear(); data->append("<html><head><title>Network internals</title>" "<style>" "body { font-family: sans-serif; }\n" ".subsection_body { margin: 10px 0 10px 2em; }\n" ".subsection_title { font-weight: bold; }\n" ".subsection_name { font-size: 80%; }\n" "</style>" "</head><body>"); SubSection* all = Singleton<AllSubSections>::get(); SubSection* section = all; // Display only the subsection tree asked for. if (!path.empty()) section = all->FindSubSectionByName(path); if (section) { section->OutputRecursive(context, data); } else { data->append("<i>Nothing found for \""); data->append(EscapeForHTML(path)); data->append("\"</i>"); } data->append("</body></html>"); return true; } <commit_msg>Add an href to help page for view-net-internal.<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 <sstream> #include "net/url_request/url_request_view_net_internal_job.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "net/base/escape.h" #include "net/base/host_cache.h" #include "net/base/load_log_util.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" namespace { //------------------------------------------------------------------------------ // Format helpers. //------------------------------------------------------------------------------ void OutputTextInPre(const std::string& text, std::string* out) { out->append("<pre>"); out->append(EscapeForHTML(text)); out->append("</pre>"); } //------------------------------------------------------------------------------ // Subsection definitions. //------------------------------------------------------------------------------ class SubSection { public: // |name| is the URL path component for this subsection. // |title| is the textual description. SubSection(SubSection* parent, const char* name, const char* title) : parent_(parent), name_(name), title_(title) { } virtual ~SubSection() { STLDeleteContainerPointers(children_.begin(), children_.end()); } // Outputs the subsection's contents to |out|. virtual void OutputBody(URLRequestContext* context, std::string* out) {} // Outputs this subsection, and all of its children. void OutputRecursive(URLRequestContext* context, std::string* out) { if (!is_root()) { std::string section_url = std::string("view-net-internal:") + GetFullyQualifiedName(); // Canonicalizing the URL escapes characters which cause problems in HTML. section_url = GURL(section_url).spec(); // Print the heading. out->append(StringPrintf("<div>" "<span class=subsection_title>%s</span> " "<span class=subsection_name>(<a href='%s'>%s</a>)<span>" "</div>", EscapeForHTML(title_).c_str(), section_url.c_str(), EscapeForHTML(section_url).c_str())); out->append("<div class=subsection_body>"); } OutputBody(context, out); for (size_t i = 0; i < children_.size(); ++i) children_[i]->OutputRecursive(context, out); if (!is_root()) out->append("</div>"); } // Returns the SubSection contained by |this| with fully qualified name // |dotted_name|, or NULL if none was found. SubSection* FindSubSectionByName(const std::string& dotted_name) { if (dotted_name == "") return this; std::string child_name; std::string child_sub_name; size_t split_pos = dotted_name.find('.'); if (split_pos == std::string::npos) { child_name = dotted_name; child_sub_name = std::string(); } else { child_name = dotted_name.substr(0, split_pos); child_sub_name = dotted_name.substr(split_pos + 1); } for (size_t i = 0; i < children_.size(); ++i) { if (children_[i]->name_ == child_name) return children_[i]->FindSubSectionByName(child_sub_name); } return NULL; // Not found. } std::string GetFullyQualifiedName() { if (!parent_) return name_; std::string parent_name = parent_->GetFullyQualifiedName(); if (parent_name.empty()) return name_; return parent_name + "." + name_; } bool is_root() const { return parent_ == NULL; } protected: typedef std::vector<SubSection*> SubSectionList; void AddSubSection(SubSection* subsection) { children_.push_back(subsection); } SubSection* parent_; std::string name_; std::string title_; SubSectionList children_; }; class ProxyServiceCurrentConfigSubSection : public SubSection { public: ProxyServiceCurrentConfigSubSection(SubSection* parent) : SubSection(parent, "config", "Current configuration") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { net::ProxyService* proxy_service = context->proxy_service(); if (proxy_service->config_has_been_initialized()) { // net::ProxyConfig defines an operator<<. std::ostringstream stream; stream << proxy_service->config(); OutputTextInPre(stream.str(), out); } else { out->append("<i>Not yet initialized</i>"); } } }; class ProxyServiceLastInitLogSubSection : public SubSection { public: ProxyServiceLastInitLogSubSection(SubSection* parent) : SubSection(parent, "init_log", "Last initialized load log") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { net::ProxyService* proxy_service = context->proxy_service(); net::LoadLog* log = proxy_service->init_proxy_resolver_log(); if (log) { OutputTextInPre(net::LoadLogUtil::PrettyPrintAsEventTree(log), out); } else { out->append("<i>None.</i>"); } } }; class ProxyServiceBadProxiesSubSection : public SubSection { public: ProxyServiceBadProxiesSubSection(SubSection* parent) : SubSection(parent, "bad_proxies", "Bad Proxies") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { out->append("TODO"); } }; class ProxyServiceSubSection : public SubSection { public: ProxyServiceSubSection(SubSection* parent) : SubSection(parent, "proxyservice", "ProxyService") { AddSubSection(new ProxyServiceCurrentConfigSubSection(this)); AddSubSection(new ProxyServiceLastInitLogSubSection(this)); AddSubSection(new ProxyServiceBadProxiesSubSection(this)); } }; class HostResolverCacheSubSection : public SubSection { public: HostResolverCacheSubSection(SubSection* parent) : SubSection(parent, "hostcache", "HostCache") { } virtual void OutputBody(URLRequestContext* context, std::string* out) { const net::HostCache* host_cache = context->host_resolver()->GetHostCache(); if (!host_cache || host_cache->caching_is_disabled()) { out->append("<i>Caching is disabled.</i>"); return; } out->append(StringPrintf("<ul><li>Size: %u</li>" "<li>Capacity: %u</li>" "<li>Time to live (ms): %u</li></ul>", host_cache->size(), host_cache->max_entries(), host_cache->cache_duration_ms())); out->append("<table border=1>" "<tr>" "<th>Host</th>" "<th>First address</th>" "<th>Time to live (ms)</th>" "</tr>"); for (net::HostCache::EntryMap::const_iterator it = host_cache->entries().begin(); it != host_cache->entries().end(); ++it) { const std::string& host = it->first; const net::HostCache::Entry* entry = it->second.get(); if (entry->error == net::OK) { // Note that ttl_ms may be negative, for the cases where entries have // expired but not been garbage collected yet. int ttl_ms = static_cast<int>( (entry->expiration - base::TimeTicks::Now()).InMilliseconds()); // Color expired entries blue. if (ttl_ms > 0) { out->append("<tr>"); } else { out->append("<tr style='color:blue'>"); } std::string address_str = net::NetAddressToString(entry->addrlist.head()); out->append(StringPrintf("<td>%s</td><td>%s</td><td>%d</td></tr>", EscapeForHTML(host).c_str(), EscapeForHTML(address_str).c_str(), ttl_ms)); } else { // This was an entry that failed to be resolved. // Color negative entries red. out->append(StringPrintf( "<tr style='color:red'><td>%s</td>" "<td colspan=2>%s</td></tr>", EscapeForHTML(host).c_str(), EscapeForHTML(net::ErrorToString(entry->error)).c_str())); } } out->append("</table>"); } }; class HostResolverSubSection : public SubSection { public: HostResolverSubSection(SubSection* parent) : SubSection(parent, "hostresolver", "HostResolver") { AddSubSection(new HostResolverCacheSubSection(this)); } }; // Helper for the URLRequest "outstanding" and "live" sections. void OutputURLAndLoadLog(const GURL& url, const net::LoadLog* log, std::string* out) { out->append("<li>"); out->append("<nobr>"); out->append(EscapeForHTML(url.spec())); out->append("</nobr>"); if (log) OutputTextInPre(net::LoadLogUtil::PrettyPrintAsEventTree(log), out); out->append("</li>"); } class URLRequestLiveSubSection : public SubSection { public: URLRequestLiveSubSection(SubSection* parent) : SubSection(parent, "outstanding", "Outstanding requests") { } virtual void OutputBody(URLRequestContext* /*context*/, std::string* out) { URLRequest::InstanceTracker* tracker = URLRequest::InstanceTracker::Get(); // Note that these are the requests across ALL contexts. std::vector<URLRequest*> requests = tracker->GetLiveRequests(); out->append("<ol>"); for (size_t i = 0; i < requests.size(); ++i) { // Reverse the list order, so we dispay from most recent to oldest. size_t index = requests.size() - i - 1; OutputURLAndLoadLog(requests[index]->original_url(), requests[index]->load_log(), out); } out->append("</ol>"); } }; class URLRequestRecentSubSection : public SubSection { public: URLRequestRecentSubSection(SubSection* parent) : SubSection(parent, "recent", "Recently completed requests") { } virtual void OutputBody(URLRequestContext* /*context*/, std::string* out) { URLRequest::InstanceTracker* tracker = URLRequest::InstanceTracker::Get(); // Note that these are the recently completed requests across ALL contexts. URLRequest::InstanceTracker::RecentRequestInfoList recent = tracker->GetRecentlyDeceased(); out->append("<ol>"); for (size_t i = 0; i < recent.size(); ++i) { // Reverse the list order, so we dispay from most recent to oldest. size_t index = recent.size() - i - 1; OutputURLAndLoadLog(recent[index].original_url, recent[index].load_log, out); } out->append("</ol>"); } }; class URLRequestSubSection : public SubSection { public: URLRequestSubSection(SubSection* parent) : SubSection(parent, "urlrequest", "URLRequest") { AddSubSection(new URLRequestLiveSubSection(this)); AddSubSection(new URLRequestRecentSubSection(this)); } }; class AllSubSections : public SubSection { public: AllSubSections() : SubSection(NULL, "", "") { AddSubSection(new ProxyServiceSubSection(this)); AddSubSection(new HostResolverSubSection(this)); AddSubSection(new URLRequestSubSection(this)); } }; } // namespace // static URLRequestJob* URLRequestViewNetInternalJob::Factory( URLRequest* request, const std::string& scheme) { return new URLRequestViewNetInternalJob(request); } bool URLRequestViewNetInternalJob::GetData(std::string* mime_type, std::string* charset, std::string* data) const { DCHECK_EQ(std::string("view-net-internal"), request_->url().scheme()); mime_type->assign("text/html"); charset->assign("UTF-8"); URLRequestContext* context = request_->context(); std::string path = request_->url().path(); data->clear(); data->append("<html><head><title>Network internals</title>" "<style>" "body { font-family: sans-serif; }\n" ".subsection_body { margin: 10px 0 10px 2em; }\n" ".subsection_title { font-weight: bold; }\n" ".subsection_name { font-size: 80%; }\n" "</style>" "</head><body>" "<p><a href='http://sites.google.com/a/chromium.org/dev/" "developers/design-documents/view-net-internal'>" "Help: how do I use this?</a></p>"); SubSection* all = Singleton<AllSubSections>::get(); SubSection* section = all; // Display only the subsection tree asked for. if (!path.empty()) section = all->FindSubSectionByName(path); if (section) { section->OutputRecursive(context, data); } else { data->append("<i>Nothing found for \""); data->append(EscapeForHTML(path)); data->append("\"</i>"); } data->append("</body></html>"); return true; } <|endoftext|>
<commit_before>/** Copyright (C) 2016 European Spallation Source ERIC */ #include <algorithm> #include <cassert> #include <common/EFUArgs.h> #include <common/Trace.h> #include <cstring> #include <efu/Parser.h> #include <efu/Server.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> //#undef TRC_LEVEL //#define TRC_LEVEL TRC_L_DEB #define UNUSED __attribute__((unused)) //============================================================================= static int stat_mask_set(std::vector<std::string> cmdargs, char UNUSED *output, unsigned int UNUSED *obytes) { XTRACE(CMD, INF, "STAT_MASK_SET\n"); if (cmdargs.size() != 2) { XTRACE(CMD, WAR, "STAT_MASK_SET: wrong number of arguments\n"); return -Parser::EBADARGS; } unsigned int mask = (unsigned int)std::stoul(cmdargs.at(1), nullptr, 0); XTRACE(CMD, INF, "STAT_MASK: 0x%08x\n", mask); efu_args->stat.set_mask(mask); //*obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); return Parser::OK; } //============================================================================= static int stat_input(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_INPUT\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_INPUT: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_INPUT %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.i.rx_packets, efu_args->stat.i.rx_bytes, efu_args->stat.i.fifo_push_errors, efu_args->stat.i.fifo_free); return Parser::OK; } //============================================================================= static int stat_processing(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_PROCESSING\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_PROCESSING: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_PROCESSING %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.p.rx_events, efu_args->stat.p.rx_error_bytes, efu_args->stat.p.rx_discards, efu_args->stat.p.rx_idle, efu_args->stat.p.fifo_push_errors, efu_args->stat.p.fifo_free); return Parser::OK; } //============================================================================= static int stat_output(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_OUTPUT\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_OUTPUT: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_OUTPUT %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.o.rx_events, efu_args->stat.o.rx_idle, efu_args->stat.o.tx_bytes); return Parser::OK; } //============================================================================= static int stat_reset(std::vector<std::string> cmdargs, char UNUSED *output, unsigned int UNUSED *obytes) { XTRACE(CMD, INF, "STAT_RESET\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_RESET: wrong number of arguments\n"); return -Parser::EBADARGS; } efu_args->stat.clear(); //*obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); return Parser::OK; } //============================================================================= static int load_file(std::string file, char *buffer) { struct stat buf; std::fill_n((char *)&buf, sizeof(struct stat), 0); int fd = open(file.c_str(), O_RDONLY); if (fd < 0) { XTRACE(CMD, WAR, "file open() failed for %s\n", file.c_str()); return -10; } if (fstat(fd, &buf) != 0) { XTRACE(CMD, ERR, "fstat() failed for %s\n", file.c_str()); close(fd); return -11; } if (buf.st_size != CSPECChanConv::adcsize * 2) { XTRACE(CMD, WAR, "file %s has wrong length: %d (should be %d)\n", file.c_str(), (int)buf.st_size, 16384 * 2); close(fd); return -12; } if (read(fd, buffer, CSPECChanConv::adcsize * 2) != CSPECChanConv::adcsize * 2) { XTRACE(CMD, ERR, "read() from %s incomplete\n", file.c_str()); close(fd); return -13; } XTRACE(CMD, INF, "Calibration file %s sucessfully read\n", file.c_str()); close(fd); return 0; } static int load_calib(std::string calibration) { XTRACE(CMD, ALW, "Attempt to load calibration %s\n", calibration.c_str()); auto file = calibration + std::string(".wcal"); if (load_file(file, (char *)efu_args->wirecal) < 0) { return -1; } file = calibration + std::string(".gcal"); if (load_file(file, (char *)efu_args->gridcal) < 0) { return -1; } return 0; } //============================================================================= static int cspec_load_calib(std::vector<std::string> cmdargs, UNUSED char *output, UNUSED unsigned int *obytes) { XTRACE(CMD, INF, "CSPEC_LOAD_CALIB\n"); if (cmdargs.size() != 2) { XTRACE(CMD, WAR, "CSPEC_LOAD_CALIB: wrong number of arguments\n"); return -Parser::EBADARGS; } auto ret = load_calib(cmdargs.at(1)); if (ret < 0) { return -Parser::EBADARGS; } /** @todo some other ipc between main and threads ? */ efu_args->proc_cmd = 1; // send load command to processing thread return Parser::OK; } //============================================================================= static int cspec_show_calib(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { auto nargs = cmdargs.size(); unsigned int offset = 0; XTRACE(CMD, INF, "CSPEC_SHOW_CALIB\n"); if (nargs == 1) { offset = 0; } else if (nargs == 2) { offset = atoi(cmdargs.at(1).c_str()); } else { XTRACE(CMD, WAR, "CSPEC_SHOW_CALIB: wrong number of arguments\n"); return -Parser::EBADARGS; } if (offset > CSPECChanConv::adcsize -1) { return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "wire %d 0x%04x, grid %d 0x%04x", offset, efu_args->wirecal[offset], offset, efu_args->gridcal[offset]); return Parser::OK; } /******************************************************************************/ /******************************************************************************/ Parser::Parser() { registercmd(std::string("STAT_MASK_SET"), stat_mask_set); registercmd(std::string("STAT_INPUT"), stat_input); registercmd(std::string("STAT_PROCESSING"), stat_processing); registercmd(std::string("STAT_OUTPUT"), stat_output); registercmd(std::string("STAT_RESET"), stat_reset); registercmd(std::string("CSPEC_LOAD_CALIB"), cspec_load_calib); registercmd(std::string("CSPEC_SHOW_CALIB"), cspec_show_calib); } int Parser::registercmd(std::string cmd_name, function_ptr cmd_fn) { XTRACE(CMD, INF, "Registering command: %s\n", cmd_name.c_str()); if (commands[cmd_name] != 0) { XTRACE(CMD, WAR, "Command already exist: %s\n", cmd_name.c_str()); return -1; } commands[cmd_name] = cmd_fn; return 0; } int Parser::parse(char *input, unsigned int ibytes, char *output, unsigned int *obytes) { XTRACE(CMD, DEB, "parse() received %u bytes\n", ibytes); *obytes = 0; memset(output, 0, SERVER_BUFFER_SIZE); if (ibytes == 0) { *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADSIZE>"); return -EUSIZE; } if (ibytes > SERVER_BUFFER_SIZE) { *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADSIZE>"); return -EOSIZE; } if (input[ibytes - 1] != '\0') { XTRACE(CMD, DEB, "adding null termination\n"); auto end = std::min(ibytes, SERVER_BUFFER_SIZE - 1); input[end] = '\0'; } std::vector<std::string> tokens; char *chars_array = strtok((char *)input, "\n "); while (chars_array) { std::string token(chars_array); tokens.push_back(token); chars_array = strtok(NULL, "\n "); } if ((int)tokens.size() < 1) { XTRACE(CMD, WAR, "No tokens\n"); *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADCMD>"); return -ENOTOKENS; } XTRACE(CMD, DEB, "Tokens in command: %d\n", (int)tokens.size()); for (auto token : tokens) { XTRACE(CMD, INF, "Token: %s\n", token.c_str()); } auto command = tokens.at(0); int res = -EBADCMD; if ((commands[command] != 0) && (command.size() < max_command_size)) { XTRACE(CMD, INF, "Calling registered command %s\n", command.c_str()); res = commands[command](tokens, output, obytes); } XTRACE(CMD, DEB, "parse1 res: %d, obytes: %d\n", res, *obytes); if (*obytes == 0) { // no reply specified, create one XTRACE(CMD, INF, "creating response\n"); switch (res) { case OK: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); break; case -ENOTOKENS: case -EBADCMD: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADCMD>"); break; case -EBADARGS: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADARGS>"); break; default: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <PARSER>"); break; } } XTRACE(CMD, DEB, "parse2 res: %d, obytes: %d\n", res, *obytes); return res; } /******************************************************************************/ <commit_msg>replaced default case with assert()<commit_after>/** Copyright (C) 2016 European Spallation Source ERIC */ #include <algorithm> #include <cassert> #include <common/EFUArgs.h> #include <common/Trace.h> #include <cstring> #include <efu/Parser.h> #include <efu/Server.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> //#undef TRC_LEVEL //#define TRC_LEVEL TRC_L_DEB #define UNUSED __attribute__((unused)) //============================================================================= static int stat_mask_set(std::vector<std::string> cmdargs, char UNUSED *output, unsigned int UNUSED *obytes) { XTRACE(CMD, INF, "STAT_MASK_SET\n"); if (cmdargs.size() != 2) { XTRACE(CMD, WAR, "STAT_MASK_SET: wrong number of arguments\n"); return -Parser::EBADARGS; } unsigned int mask = (unsigned int)std::stoul(cmdargs.at(1), nullptr, 0); XTRACE(CMD, INF, "STAT_MASK: 0x%08x\n", mask); efu_args->stat.set_mask(mask); //*obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); return Parser::OK; } //============================================================================= static int stat_input(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_INPUT\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_INPUT: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_INPUT %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.i.rx_packets, efu_args->stat.i.rx_bytes, efu_args->stat.i.fifo_push_errors, efu_args->stat.i.fifo_free); return Parser::OK; } //============================================================================= static int stat_processing(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_PROCESSING\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_PROCESSING: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_PROCESSING %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.p.rx_events, efu_args->stat.p.rx_error_bytes, efu_args->stat.p.rx_discards, efu_args->stat.p.rx_idle, efu_args->stat.p.fifo_push_errors, efu_args->stat.p.fifo_free); return Parser::OK; } //============================================================================= static int stat_output(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { XTRACE(CMD, INF, "STAT_OUTPUT\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_OUTPUT: wrong number of arguments\n"); return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "STAT_OUTPUT %" PRIu64 ", %" PRIu64 ", %" PRIu64, efu_args->stat.o.rx_events, efu_args->stat.o.rx_idle, efu_args->stat.o.tx_bytes); return Parser::OK; } //============================================================================= static int stat_reset(std::vector<std::string> cmdargs, char UNUSED *output, unsigned int UNUSED *obytes) { XTRACE(CMD, INF, "STAT_RESET\n"); if (cmdargs.size() != 1) { XTRACE(CMD, WAR, "STAT_RESET: wrong number of arguments\n"); return -Parser::EBADARGS; } efu_args->stat.clear(); //*obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); return Parser::OK; } //============================================================================= static int load_file(std::string file, char *buffer) { struct stat buf; std::fill_n((char *)&buf, sizeof(struct stat), 0); int fd = open(file.c_str(), O_RDONLY); if (fd < 0) { XTRACE(CMD, WAR, "file open() failed for %s\n", file.c_str()); return -10; } if (fstat(fd, &buf) != 0) { XTRACE(CMD, ERR, "fstat() failed for %s\n", file.c_str()); close(fd); return -11; } if (buf.st_size != CSPECChanConv::adcsize * 2) { XTRACE(CMD, WAR, "file %s has wrong length: %d (should be %d)\n", file.c_str(), (int)buf.st_size, 16384 * 2); close(fd); return -12; } if (read(fd, buffer, CSPECChanConv::adcsize * 2) != CSPECChanConv::adcsize * 2) { XTRACE(CMD, ERR, "read() from %s incomplete\n", file.c_str()); close(fd); return -13; } XTRACE(CMD, INF, "Calibration file %s sucessfully read\n", file.c_str()); close(fd); return 0; } static int load_calib(std::string calibration) { XTRACE(CMD, ALW, "Attempt to load calibration %s\n", calibration.c_str()); auto file = calibration + std::string(".wcal"); if (load_file(file, (char *)efu_args->wirecal) < 0) { return -1; } file = calibration + std::string(".gcal"); if (load_file(file, (char *)efu_args->gridcal) < 0) { return -1; } return 0; } //============================================================================= static int cspec_load_calib(std::vector<std::string> cmdargs, UNUSED char *output, UNUSED unsigned int *obytes) { XTRACE(CMD, INF, "CSPEC_LOAD_CALIB\n"); if (cmdargs.size() != 2) { XTRACE(CMD, WAR, "CSPEC_LOAD_CALIB: wrong number of arguments\n"); return -Parser::EBADARGS; } auto ret = load_calib(cmdargs.at(1)); if (ret < 0) { return -Parser::EBADARGS; } /** @todo some other ipc between main and threads ? */ efu_args->proc_cmd = 1; // send load command to processing thread return Parser::OK; } //============================================================================= static int cspec_show_calib(std::vector<std::string> cmdargs, char *output, unsigned int *obytes) { auto nargs = cmdargs.size(); unsigned int offset = 0; XTRACE(CMD, INF, "CSPEC_SHOW_CALIB\n"); if (nargs == 1) { offset = 0; } else if (nargs == 2) { offset = atoi(cmdargs.at(1).c_str()); } else { XTRACE(CMD, WAR, "CSPEC_SHOW_CALIB: wrong number of arguments\n"); return -Parser::EBADARGS; } if (offset > CSPECChanConv::adcsize -1) { return -Parser::EBADARGS; } *obytes = snprintf(output, SERVER_BUFFER_SIZE, "wire %d 0x%04x, grid %d 0x%04x", offset, efu_args->wirecal[offset], offset, efu_args->gridcal[offset]); return Parser::OK; } /******************************************************************************/ /******************************************************************************/ Parser::Parser() { registercmd(std::string("STAT_MASK_SET"), stat_mask_set); registercmd(std::string("STAT_INPUT"), stat_input); registercmd(std::string("STAT_PROCESSING"), stat_processing); registercmd(std::string("STAT_OUTPUT"), stat_output); registercmd(std::string("STAT_RESET"), stat_reset); registercmd(std::string("CSPEC_LOAD_CALIB"), cspec_load_calib); registercmd(std::string("CSPEC_SHOW_CALIB"), cspec_show_calib); } int Parser::registercmd(std::string cmd_name, function_ptr cmd_fn) { XTRACE(CMD, INF, "Registering command: %s\n", cmd_name.c_str()); if (commands[cmd_name] != 0) { XTRACE(CMD, WAR, "Command already exist: %s\n", cmd_name.c_str()); return -1; } commands[cmd_name] = cmd_fn; return 0; } int Parser::parse(char *input, unsigned int ibytes, char *output, unsigned int *obytes) { XTRACE(CMD, DEB, "parse() received %u bytes\n", ibytes); *obytes = 0; memset(output, 0, SERVER_BUFFER_SIZE); if (ibytes == 0) { *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADSIZE>"); return -EUSIZE; } if (ibytes > SERVER_BUFFER_SIZE) { *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADSIZE>"); return -EOSIZE; } if (input[ibytes - 1] != '\0') { XTRACE(CMD, DEB, "adding null termination\n"); auto end = std::min(ibytes, SERVER_BUFFER_SIZE - 1); input[end] = '\0'; } std::vector<std::string> tokens; char *chars_array = strtok((char *)input, "\n "); while (chars_array) { std::string token(chars_array); tokens.push_back(token); chars_array = strtok(NULL, "\n "); } if ((int)tokens.size() < 1) { XTRACE(CMD, WAR, "No tokens\n"); *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADCMD>"); return -ENOTOKENS; } XTRACE(CMD, DEB, "Tokens in command: %d\n", (int)tokens.size()); for (auto token : tokens) { XTRACE(CMD, INF, "Token: %s\n", token.c_str()); } auto command = tokens.at(0); int res = -EBADCMD; if ((commands[command] != 0) && (command.size() < max_command_size)) { XTRACE(CMD, INF, "Calling registered command %s\n", command.c_str()); res = commands[command](tokens, output, obytes); } XTRACE(CMD, DEB, "parse1 res: %d, obytes: %d\n", res, *obytes); if (*obytes == 0) { // no reply specified, create one assert((res == OK) || (res == -ENOTOKENS) || (res == -EBADCMD) || (res == -EBADARGS)); XTRACE(CMD, INF, "creating response\n"); switch (res) { case OK: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "<OK>"); break; case -ENOTOKENS: case -EBADCMD: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADCMD>"); break; case -EBADARGS: *obytes = snprintf(output, SERVER_BUFFER_SIZE, "Error: <BADARGS>"); break; } } XTRACE(CMD, DEB, "parse2 res: %d, obytes: %d\n", res, *obytes); return res; } /******************************************************************************/ <|endoftext|>
<commit_before>/** Copyright (C) 2016 European Spallation Source */ #include <cspec/CSPECData.h> #include <cspecgen/CspecArgs.h> #include <cstring> #include <inttypes.h> #include <iostream> #include <libs/include/Socket.h> #include <libs/include/Timer.h> #include <libs/include/gccintel.h> #include <unistd.h> using namespace std; const int TSC_MHZ = 2900; int main(int argc, char *argv[]) { DGArgs opts(argc, argv); // Parse command line opts char buffer[9000]; unsigned int seqno = 1; const int B1M = 1000000; Socket::Endpoint local("0.0.0.0", 0); Socket::Endpoint remote(opts.dest_ip.c_str(), opts.port); UDPClient DataSource(local, remote); DataSource.buflen(opts.buflen); DataSource.setbuffers(opts.sndbuf, 0); DataSource.printbuffers(); CSPECData cspec; int ndata = 100; int size = cspec.generate(buffer, 9000, ndata); assert(size == ndata * cspec.datasize); uint64_t tx_total = 0; uint64_t tx = 0; uint64_t txp = 0; uint64_t tsc0 = rdtsc(); uint64_t tsc1 = rdtsc(); uint64_t tsc; for (;;) { tsc = rdtsc(); if (unlikely((tx_total + tx) >= (long unsigned int)opts.txGB * 1000000000)) { cout << "Sent " << tx_total + tx << " bytes." << endl; cout << "done" << endl; exit(0); } // Generate Tx buffer // std::memcpy(buffer, &seqno, sizeof(seqno)); // For NMX // Sleep to throttle down speed if (unlikely((tsc - tsc1) >= TSC_MHZ * 10000)) { usleep(opts.speed_level * 1000); tsc1 = rdtsc(); } // Send data tx += DataSource.send(buffer, size); if (tx > 0) { txp++; seqno++; } else { cout << "unable to send" << endl; } #if 0 if ((txp % 10000) == 0) { usleep(15000); } #endif if (unlikely(((tsc - tsc0) / TSC_MHZ) >= opts.updint * 1000000)) { tx_total += tx; printf("Tx rate: %8.2f Mbps, tx %5" PRIu64 " MB (total: %7" PRIu64 " MB) %ld usecs\n", tx * 8.0 / (((tsc - tsc0) / TSC_MHZ) / 1000000.0) / B1M, tx / B1M, tx_total / B1M, ((tsc - tsc0) / TSC_MHZ)); tx = 0; tsc0 = rdtsc(); } } } <commit_msg>misc cleanup<commit_after>/** Copyright (C) 2016 European Spallation Source */ #include <cspec/CSPECData.h> #include <cspecgen/CspecArgs.h> #include <cstring> #include <inttypes.h> #include <iostream> #include <libs/include/Socket.h> #include <libs/include/Timer.h> #include <libs/include/gccintel.h> #include <unistd.h> using namespace std; const int TSC_MHZ = 2900; int main(int argc, char *argv[]) { DGArgs opts(argc, argv); // Parse command line opts char buffer[9000]; unsigned int seqno = 1; const int B1M = 1000000; Socket::Endpoint local("0.0.0.0", 0); Socket::Endpoint remote(opts.dest_ip.c_str(), opts.port); UDPClient DataSource(local, remote); DataSource.buflen(opts.buflen); DataSource.setbuffers(opts.sndbuf, 0); DataSource.printbuffers(); CSPECData cspec; int ndata = 100; int size = cspec.generate(buffer, 9000, ndata); assert(size == ndata * cspec.datasize); uint64_t tx_total = 0; uint64_t tx = 0; uint64_t txp = 0; uint64_t tsc0 = rdtsc(); uint64_t tsc1 = rdtsc(); uint64_t tsc; for (;;) { tsc = rdtsc(); if (unlikely((tx_total + tx) >= (long unsigned int)opts.txGB * 1000000000) { cout << "Sent " << tx_total + tx << " bytes." << endl; cout << "done" << endl; exit(0); } // Sleep to throttle down speed if (unlikely((tsc - tsc1) >= TSC_MHZ * 10000)) { usleep(opts.speed_level * 1000); tsc1 = rdtsc(); } // Send data int wrsize = DataSource.send(buffer, size); if (wrsize > 0) { tx += wrsize; txp++; seqno++; } else { cout << "unable to send" << endl; } if (unlikely(((tsc - tsc0) / TSC_MHZ) >= opts.updint * 1000000)) { tx_total += tx; printf("Tx rate: %8.2f Mbps, tx %5" PRIu64 " MB (total: %7" PRIu64 " MB) %ld usecs\n", tx * 8.0 / (((tsc - tsc0) / TSC_MHZ) / 1000000.0) / B1M, tx / B1M, tx_total / B1M, ((tsc - tsc0) / TSC_MHZ)); tx = 0; tsc0 = rdtsc(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperInputImageListParameter.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { InputImageListParameter::InputImageListParameter() { this->SetName("Input Image List"); this->SetKey("inList"); m_ImageList = FloatVectorImageListType::New(); m_ReaderList = ImageFileReaderListType::New(); } InputImageListParameter::~InputImageListParameter() { } bool InputImageListParameter::SetListFromFileName(const std::vector<std::string> & filenames) { // First clear previous file choosen this->ClearValue(); bool isOk = true; for(unsigned int i=0; i<filenames.size(); i++) { const std::string filename = filenames[i]; // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject & /*err*/) { this->ClearValue(); isOk = false; break; } // everything went fine, store the object references m_ReaderList->PushBack(reader); m_ImageList->PushBack(reader->GetOutput()); } } if( !isOk ) { return false; } SetActive(true); this->Modified(); return true; } void InputImageListParameter::AddNullElement() { m_ReaderList->PushBack(NULL); m_ImageList->PushBack(NULL); SetActive(false); this->Modified(); } bool InputImageListParameter::AddFromFileName(const std::string & filename) { // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject &) { this->ClearValue(); return false; } // everything went fine, store the object references m_ReaderList->PushBack(reader); m_ImageList->PushBack(reader->GetOutput()); SetActive(true); this->Modified(); return true; } return false; } bool InputImageListParameter::SetNthFileName( const unsigned int id, const std::string & filename ) { if( m_ReaderList->Size()<id ) { itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ReaderList->Size()<<" images available."); } // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject &) { this->ClearValue(); return false; } m_ReaderList->SetNthElement(id, reader); m_ImageList->SetNthElement(id, reader->GetOutput()); this->Modified(); return true; } return false; } std::vector<std::string> InputImageListParameter::GetFileNameList() const { if (m_ReaderList) { std::vector<std::string> filenames; for(unsigned int i=0; i<m_ReaderList->Size(); i++) { filenames.push_back( m_ReaderList->GetNthElement(i)->GetFileName() ); } return filenames; } itkExceptionMacro(<< "No filename value"); } std::string InputImageListParameter::GetNthFileName( unsigned int i ) const { if (m_ReaderList) { if(m_ReaderList->Size()<i) { itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ReaderList->Size()<<" images available."); } return m_ReaderList->GetNthElement(i)->GetFileName(); } itkExceptionMacro(<< "No filename value"); } FloatVectorImageListType* InputImageListParameter::GetImageList() const { return m_ImageList; } FloatVectorImageType* InputImageListParameter::GetNthImage(unsigned int i) const { if(m_ImageList->Size()<i) { itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available."); } return m_ImageList->GetNthElement(i); } void InputImageListParameter::SetImageList(FloatVectorImageListType* imList) { // Check input availability // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) try { for(unsigned int i=0; i<imList->Size(); i++) { imList->GetNthElement( i )->UpdateOutputInformation(); } } catch(itk::ExceptionObject &) { return; } m_ImageList = imList; m_ReaderList = ImageFileReaderListType::Pointer(); for(unsigned int i=0; i<m_ImageList->Size(); i++) { m_ReaderList->PushBack( ImageFileReaderType::Pointer() ); } SetActive(true); this->Modified(); } void InputImageListParameter::AddImage(FloatVectorImageType* image) { // Check input availability // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) try { image->UpdateOutputInformation(); } catch(itk::ExceptionObject &) { return; } m_ImageList->PushBack( image ); m_ReaderList->PushBack( ImageFileReaderType::Pointer() ); this->Modified(); } bool InputImageListParameter::HasValue() const { if(m_ImageList->Size() == 0) { return false; } bool res(true); unsigned int i(0); while(i<m_ImageList->Size() && res==true) { res = m_ImageList->GetNthElement(i).IsNotNull(); i++; } return res; } void InputImageListParameter::Erase( unsigned int id ) { if(m_ImageList->Size()<id) { itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ImageList->Size()<<" images available."); } m_ImageList->Erase( id ); m_ReaderList->Erase( id ); this->Modified(); } void InputImageListParameter::ClearValue() { m_ImageList->Clear(); m_ReaderList->Clear(); SetActive(false); this->Modified(); } } } <commit_msg>STYLE: Code formatting<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperInputImageListParameter.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { InputImageListParameter::InputImageListParameter() { this->SetName("Input Image List"); this->SetKey("inList"); m_ImageList = FloatVectorImageListType::New(); m_ReaderList = ImageFileReaderListType::New(); } InputImageListParameter::~InputImageListParameter() { } bool InputImageListParameter::SetListFromFileName(const std::vector<std::string> & filenames) { // First clear previous file choosen this->ClearValue(); bool isOk = true; for(unsigned int i=0; i<filenames.size(); i++) { const std::string filename = filenames[i]; // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject & /*err*/) { this->ClearValue(); isOk = false; break; } // everything went fine, store the object references m_ReaderList->PushBack(reader); m_ImageList->PushBack(reader->GetOutput()); } } if( !isOk ) { return false; } SetActive(true); this->Modified(); return true; } void InputImageListParameter::AddNullElement() { m_ReaderList->PushBack(NULL); m_ImageList->PushBack(NULL); SetActive(false); this->Modified(); } bool InputImageListParameter::AddFromFileName(const std::string & filename) { // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject & /*err*/) { this->ClearValue(); return false; } // everything went fine, store the object references m_ReaderList->PushBack(reader); m_ImageList->PushBack(reader->GetOutput()); SetActive(true); this->Modified(); return true; } return false; } bool InputImageListParameter::SetNthFileName( const unsigned int id, const std::string & filename ) { if( m_ReaderList->Size()<id ) { itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ReaderList->Size()<<" images available."); } // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) // File existance checked by the reader if (!filename.empty()) { ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(filename); try { reader->UpdateOutputInformation(); } catch(itk::ExceptionObject &) { this->ClearValue(); return false; } m_ReaderList->SetNthElement(id, reader); m_ImageList->SetNthElement(id, reader->GetOutput()); this->Modified(); return true; } return false; } std::vector<std::string> InputImageListParameter::GetFileNameList() const { if (m_ReaderList) { std::vector<std::string> filenames; for(unsigned int i=0; i<m_ReaderList->Size(); i++) { if( m_ReaderList->GetNthElement(i) ) filenames.push_back( m_ReaderList->GetNthElement(i)->GetFileName() ); } return filenames; } itkExceptionMacro(<< "No filename value"); } std::string InputImageListParameter::GetNthFileName( unsigned int i ) const { if (m_ReaderList) { if(m_ReaderList->Size()<i) { itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ReaderList->Size()<<" images available."); } return m_ReaderList->GetNthElement(i)->GetFileName(); } itkExceptionMacro(<< "No filename value"); } FloatVectorImageListType* InputImageListParameter::GetImageList() const { return m_ImageList; } FloatVectorImageType* InputImageListParameter::GetNthImage(unsigned int i) const { if(m_ImageList->Size()<i) { itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available."); } return m_ImageList->GetNthElement(i); } void InputImageListParameter::SetImageList(FloatVectorImageListType* imList) { // Check input availability // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) try { for(unsigned int i=0; i<imList->Size(); i++) { imList->GetNthElement( i )->UpdateOutputInformation(); } } catch(itk::ExceptionObject &) { return; } m_ImageList = imList; m_ReaderList = ImageFileReaderListType::Pointer(); for(unsigned int i=0; i<m_ImageList->Size(); i++) { m_ReaderList->PushBack( ImageFileReaderType::Pointer() ); } SetActive(true); this->Modified(); } void InputImageListParameter::AddImage(FloatVectorImageType* image) { // Check input availability // TODO : when the logger will be available, redirect the exception // in the logger (like what is done in MsgReporter) try { image->UpdateOutputInformation(); } catch(itk::ExceptionObject &) { return; } m_ImageList->PushBack( image ); m_ReaderList->PushBack( ImageFileReaderType::Pointer() ); this->Modified(); } bool InputImageListParameter::HasValue() const { if(m_ImageList->Size() == 0) { return false; } bool res(true); unsigned int i(0); while(i < m_ImageList->Size() && res == true) { res = m_ImageList->GetNthElement(i).IsNotNull(); i++; } return res; } void InputImageListParameter::Erase( unsigned int id ) { if(m_ImageList->Size()<id) { itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ImageList->Size()<<" images available."); } m_ImageList->Erase( id ); m_ReaderList->Erase( id ); this->Modified(); } void InputImageListParameter::ClearValue() { m_ImageList->Clear(); m_ReaderList->Clear(); SetActive(false); this->Modified(); } } } <|endoftext|>
<commit_before>#include <catch.hpp> #include <ophidian/parser/Lef.h> #include <iostream> using namespace ophidian; bool operator==(const parser::Lef::site & a, const parser::Lef::site & b) { return a.name == b.name && a.class_ == b.class_ && a.symmetry == b.symmetry && Approx(a.x) == b.x && Approx(a.y) == b.y; } bool operator==(const parser::Lef::layer & a, const parser::Lef::layer & b) { return a.name == b.name && a.type == b.type && a.direction == b.direction && Approx(a.pitch) == b.pitch && Approx(a.width) == b.width; } bool operator==(const parser::Lef::rect & a, const parser::Lef::rect & b) { return Approx(a.xl) == b.xl && Approx(a.yl) == b.yl && Approx(a.xh) == b.xh && Approx(a.yh) == b.yh; } bool operator==(const std::vector<parser::Lef::rect> & a, const std::vector<parser::Lef::rect> & b) { bool rectsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::rect & layer) -> bool { return i == layer; }; rectsAreEqual = rectsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return rectsAreEqual; } bool operator==(const std::vector<std::string> & a, const std::vector<std::string> & b) { bool layersAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const std::string & layer) -> bool { return i == layer; }; layersAreEqual = layersAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return layersAreEqual; } bool operator==(const parser::Lef::port & a, const parser::Lef::port & b) { return a.layers == b.layers && a.rects == b.rects; } bool operator==(const std::vector<parser::Lef::port> & a, const std::vector<parser::Lef::port> & b) { bool portsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::port & port) -> bool { return i == port; }; portsAreEqual = portsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return portsAreEqual; } bool operator==(const parser::Lef::pin & a, const parser::Lef::pin & b) { return a.name == b.name && a.direction == b.direction && a.ports == b.ports; } bool operator==(const parser::Lef::macro_size & a, const parser::Lef::macro_size & b) { return Approx(a.x) == b.x && Approx(a.y) == b.y; } bool operator==(const parser::Lef::macro_foreign & a, const parser::Lef::macro_foreign & b) { return a.name == b.name && Approx(a.x) == b.x && Approx(a.y) == b.y; } bool operator==(const std::vector<parser::Lef::pin> & a, const std::vector<parser::Lef::pin> & b) { bool pinsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::pin & pin) -> bool { return i == pin; }; pinsAreEqual = pinsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return pinsAreEqual; } bool operator==(const parser::Lef::macro & a, const parser::Lef::macro & b) { return a.name == b.name && a.class_ == b.class_ && a.pins == b.pins && a.foreign == b.foreign && a.size == b.size && a.site == b.site && a.origin == b.origin; } bool operator==(const parser::Lef::obs & a, const parser::Lef::obs & b) { auto pred = [] (auto lhs, auto rhs) { return lhs.first == rhs.first; }; auto aMap = a.layer2rects; auto bMap = b.layer2rects; return aMap.size() == bMap.size() && std::equal(aMap.begin(), aMap.end(), bMap.begin(), bMap.end(), pred); } TEST_CASE("lef: simple.lef parsing", "[parser][lef][simple]") { parser::LefParser parser; parser::Lef* simpleLef = parser.readFile("input_files/simple.lef"); SECTION("Sites are parsed correctly", "[parser][lef][simple]") { CHECK( simpleLef->sites().size() == 1 ); parser::Lef::site core; core.name = "core"; core.class_ = "CORE"; core.x = 0.19; core.y = 1.71; REQUIRE(simpleLef->sites().front() == core); } SECTION("Layers are parsed correctly", "[parser][lef][simple][layers]") { std::vector<parser::Lef::layer> layers { {"metal1", "ROUTING", parser::Lef::layer::HORIZONTAL, 0.2, 0.1}, {"metal2", "ROUTING", parser::Lef::layer::VERTICAL, 0.2, 0.1}, {"metal3", "ROUTING", parser::Lef::layer::HORIZONTAL, 0.2, 0.1} }; CHECK( simpleLef->layers().size() == layers.size() ); for(auto & simple_layer : layers) { auto comparePredicate = [simple_layer](const parser::Lef::layer & layer) -> bool { return simple_layer == layer; }; REQUIRE( std::find_if( simpleLef->layers().begin(), simpleLef->layers().end(), comparePredicate ) != simpleLef->layers().end()); } } SECTION("Macros are parsed correctly", "[parser][lef][simple][macros]") { CHECK( simpleLef->macros().size() == 212 ); std::vector<std::string> m1_pin_layers = {"metal1"}; std::vector<parser::Lef::rect> m1_o_rects = { {0.465, 0.150, 0.53, 1.255}, {0.415, 0.150, 0.61, 0.28} }; std::vector<parser::Lef::rect> m1_a_rects = { {0.210, 0.340, 0.34, 0.405} }; parser::Lef::port m1_o_port = {m1_pin_layers, m1_o_rects}; parser::Lef::port m1_a_port = {m1_pin_layers, m1_a_rects}; parser::Lef::pin o = {"o", parser::Lef::pin::OUTPUT, {m1_o_port}}; parser::Lef::pin a = {"a", parser::Lef::pin::INPUT, {m1_a_port}}; parser::Lef::macro_foreign m1_foreign = {"INV_X1", 0.000, 0.000}; parser::Lef::macro m1; m1.name = "INV_X1"; m1.class_ = "CORE"; m1.pins = {o, a}; m1.foreign = m1_foreign; m1.size = {0.760, 1.71}; m1.site = "core"; m1.origin = {0.000, 0.000}; REQUIRE( simpleLef->macros().front() == m1); } SECTION("Database units are correct", "[parser][lef][simple][dbunits]"){ CHECK(Approx(simpleLef->databaseUnits()) == 2000.0); } } TEST_CASE("lef: superblue18.lef parsing", "[parser][lef][superblue18]") { parser::LefParser parser; INFO("Have you put `superblue18.lef` in the tests binary directory?"); parser::Lef* superblue18 = parser.readFile("superblue18.lef"); SECTION("Obses are correct", "[parser][lef][superblue18][obses]"){ parser::Lef::rect r1 = {0, 0, 3.420, 1.71}; parser::Lef::obs obs1; obs1.layer2rects["metal1"] = {r1}; obs1.layer2rects["metal2"] = {r1}; obs1.layer2rects["metal3"] = {r1}; obs1.layer2rects["metal4"] = {r1}; obs1.layer2rects["via1"] = {r1}; obs1.layer2rects["via2"] = {r1}; obs1.layer2rects["via3"] = {r1}; REQUIRE(superblue18->macros()[212].obses == obs1); } } <commit_msg>lef_test: Change comparison to function<commit_after>#include <catch.hpp> #include <ophidian/parser/Lef.h> #include <iostream> using namespace ophidian; bool compare(const parser::Lef::site & a, const parser::Lef::site & b) { return a.name == b.name && a.class_ == b.class_ && a.symmetry == b.symmetry && Approx(a.x) == b.x && Approx(a.y) == b.y; } bool compare(const parser::Lef::layer & a, const parser::Lef::layer & b) { return a.name == b.name && a.type == b.type && a.direction == b.direction && Approx(a.pitch) == b.pitch && Approx(a.width) == b.width; } bool compare(const parser::Lef::rect & a, const parser::Lef::rect & b) { return Approx(a.xl) == b.xl && Approx(a.yl) == b.yl && Approx(a.xh) == b.xh && Approx(a.yh) == b.yh; } bool compare(const std::vector<parser::Lef::rect> & a, const std::vector<parser::Lef::rect> & b) { bool rectsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::rect & layer) -> bool { return compare(i, layer); }; rectsAreEqual = rectsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return rectsAreEqual; } bool compare(const std::vector<std::string> & a, const std::vector<std::string> & b) { bool layersAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const std::string & layer) -> bool { return i == layer; }; layersAreEqual = layersAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return layersAreEqual; } bool compare(const parser::Lef::port & a, const parser::Lef::port & b) { return compare(a.layers, b.layers) && compare(a.rects, b.rects); } bool compare(const std::vector<parser::Lef::port> & a, const std::vector<parser::Lef::port> & b) { bool portsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::port & port) -> bool { return compare(i, port); }; portsAreEqual = portsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return portsAreEqual; } bool compare(const parser::Lef::pin & a, const parser::Lef::pin & b) { return a.name == b.name && a.direction == b.direction && compare(a.ports, b.ports); } bool compare(const parser::Lef::macro_size & a, const parser::Lef::macro_size & b) { return Approx(a.x) == b.x && Approx(a.y) == b.y; } bool compare(const parser::Lef::macro_foreign & a, const parser::Lef::macro_foreign & b) { return a.name == b.name && Approx(a.x) == b.x && Approx(a.y) == b.y; } bool compare(const std::vector<parser::Lef::pin> & a, const std::vector<parser::Lef::pin> & b) { bool pinsAreEqual = true; for (auto& i : a) { auto comparePredicate = [i](const parser::Lef::pin & pin) -> bool { return compare(i, pin); }; pinsAreEqual = pinsAreEqual && std::find_if(a.begin(), a.end(), comparePredicate) != a.end(); } return pinsAreEqual; } bool compare(const parser::Lef::macro & a, const parser::Lef::macro & b) { return a.name == b.name && a.class_ == b.class_ && compare(a.pins, b.pins) && compare(a.foreign, b.foreign) && compare(a.size, b.size) && a.site == b.site && compare(a.origin, b.origin); } bool compare(const parser::Lef::obs & a, const parser::Lef::obs & b) { auto pred = [] (auto lhs, auto rhs) { return lhs.first == rhs.first; }; auto aMap = a.layer2rects; auto bMap = b.layer2rects; return aMap.size() == bMap.size() && std::equal(aMap.begin(), aMap.end(), bMap.begin(), bMap.end(), pred); } TEST_CASE("lef: simple.lef parsing", "[parser][lef][simple]") { parser::LefParser parser; parser::Lef* simpleLef = parser.readFile("input_files/simple.lef"); SECTION("Sites are parsed correctly", "[parser][lef][simple]") { CHECK( simpleLef->sites().size() == 1 ); parser::Lef::site core; core.name = "core"; core.class_ = "CORE"; core.x = 0.19; core.y = 1.71; REQUIRE(compare(simpleLef->sites().front(), core)); } SECTION("Layers are parsed correctly", "[parser][lef][simple][layers]") { std::vector<parser::Lef::layer> layers { {"metal1", "ROUTING", parser::Lef::layer::HORIZONTAL, 0.2, 0.1}, {"metal2", "ROUTING", parser::Lef::layer::VERTICAL, 0.2, 0.1}, {"metal3", "ROUTING", parser::Lef::layer::HORIZONTAL, 0.2, 0.1} }; CHECK( simpleLef->layers().size() == layers.size() ); for(auto & simple_layer : layers) { auto comparePredicate = [simple_layer](const parser::Lef::layer & layer) -> bool { return compare(simple_layer, layer); }; REQUIRE( std::find_if( simpleLef->layers().begin(), simpleLef->layers().end(), comparePredicate ) != simpleLef->layers().end()); } } SECTION("Macros are parsed correctly", "[parser][lef][simple][macros]") { CHECK( simpleLef->macros().size() == 212 ); std::vector<std::string> m1_pin_layers = {"metal1"}; std::vector<parser::Lef::rect> m1_o_rects = { {0.465, 0.150, 0.53, 1.255}, {0.415, 0.150, 0.61, 0.28} }; std::vector<parser::Lef::rect> m1_a_rects = { {0.210, 0.340, 0.34, 0.405} }; parser::Lef::port m1_o_port = {m1_pin_layers, m1_o_rects}; parser::Lef::port m1_a_port = {m1_pin_layers, m1_a_rects}; parser::Lef::pin o = {"o", parser::Lef::pin::OUTPUT, {m1_o_port}}; parser::Lef::pin a = {"a", parser::Lef::pin::INPUT, {m1_a_port}}; parser::Lef::macro_foreign m1_foreign = {"INV_X1", 0.000, 0.000}; parser::Lef::macro m1; m1.name = "INV_X1"; m1.class_ = "CORE"; m1.pins = {o, a}; m1.foreign = m1_foreign; m1.size = {0.760, 1.71}; m1.site = "core"; m1.origin = {0.000, 0.000}; REQUIRE(compare(simpleLef->macros().front(), m1)); } SECTION("Database units are correct", "[parser][lef][simple][dbunits]"){ CHECK(Approx(simpleLef->databaseUnits()) == 2000.0); } } TEST_CASE("lef: superblue18.lef parsing", "[parser][lef][superblue18]") { parser::LefParser parser; INFO("Have you put `superblue18.lef` in the tests binary directory?"); parser::Lef* superblue18 = parser.readFile("superblue18.lef"); SECTION("Obses are correct", "[parser][lef][superblue18][obses]"){ parser::Lef::rect r1 = {0, 0, 3.420, 1.71}; parser::Lef::obs obs1; obs1.layer2rects["metal1"] = {r1}; obs1.layer2rects["metal2"] = {r1}; obs1.layer2rects["metal3"] = {r1}; obs1.layer2rects["metal4"] = {r1}; obs1.layer2rects["via1"] = {r1}; obs1.layer2rects["via2"] = {r1}; obs1.layer2rects["via3"] = {r1}; REQUIRE(compare(superblue18->macros()[212].obses, obs1)); } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2006 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 <QApplication> # include <QPixmap> #endif #include <App/Part.h> #include <App/Origin.h> #include <App/Plane.h> #include <App/Line.h> #include <App/Document.h> /// Here the FreeCAD includes sorted by Base,App,Gui...... #include "ViewProviderPart.h" #include "ViewProviderPlane.h" #include "ViewProviderLine.h" #include "Application.h" #include "Command.h" #include "BitmapFactory.h" #include "Document.h" #include "Tree.h" #include "View3DInventor.h" #include "View3DInventorViewer.h" #include "Base/Console.h" #include <boost/bind.hpp> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/nodes/SoSeparator.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPart, Gui::ViewProviderGeometryObject) /** * Creates the view provider for an object group. */ ViewProviderPart::ViewProviderPart() { ADD_PROPERTY(Workbench,("PartDesignWorkbench")); } ViewProviderPart::~ViewProviderPart() { } /** * Whenever a property of the group gets changed then the same property of all * associated view providers of the objects of the object group get changed as well. */ void ViewProviderPart::onChanged(const App::Property* prop) { ViewProviderGeoFeatureGroup::onChanged(prop); } void ViewProviderPart::attach(App::DocumentObject *pcObj) { pcObj->getDocument()->signalChangedObject.connect(boost::bind(&ViewProviderPart::onObjectChanged, this, _1, _2)); ViewProviderGeoFeatureGroup::attach(pcObj); } void ViewProviderPart::updateData(const App::Property* prop) { ViewProviderGeoFeatureGroup::updateData(prop); } void ViewProviderPart::onObjectChanged(const App::DocumentObject& obj, const App::Property&) { App::Part* part = static_cast<App::Part*>(pcObject); if(static_cast<App::Part*>(pcObject)->hasObject(&obj) && obj.getTypeId() != App::Origin::getClassTypeId() && obj.getTypeId() != App::Plane::getClassTypeId() && obj.getTypeId() != App::Line::getClassTypeId()) { View3DInventorViewer* viewer = static_cast<View3DInventor*>(this->getActiveView())->getViewer(); SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); //calculate for everything but planes SbBox3f bbox(0.0001f,0.0001f,0.0001f,0.0001f,0.0001f,0.0001f); for(App::DocumentObject* obj : part->getObjects()) { if(obj->getTypeId() != App::Origin::getClassTypeId() && obj->getTypeId() != App::Plane::getClassTypeId() && obj->getTypeId() != App::Line::getClassTypeId() ) { //getting crash on deletion PartDesign::Body object. no viewprovider. ViewProvider *viewProvider = Gui::Application::Instance->getViewProvider(obj); if (!viewProvider) continue; bboxAction.apply(viewProvider->getRoot()); bbox.extendBy(bboxAction.getBoundingBox()); } }; //get the bounding box values SbVec3f size = bbox.getSize()*1.3; SbVec3f max = bbox.getMax()*1.3; SbVec3f min = bbox.getMin()*1.3; App::Origin* origin = static_cast<App::Origin*>(part->getObjectsOfType(App::Origin::getClassTypeId()).front()); if(!origin) return; //get the planes and set their values std::vector<App::DocumentObject*> planes = origin->getObjectsOfType(App::Plane::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = planes.begin(); p != planes.end(); p++) { Gui::ViewProviderPlane* vp = dynamic_cast<Gui::ViewProviderPlane*>(Gui::Application::Instance->getViewProvider(*p)); if (strcmp(App::Part::BaseplaneTypes[0], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., (max[1]+min[1])/2., 0), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[1])),std::max(max[0], max[1]))); } if (strcmp(App::Part::BaseplaneTypes[1], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., 0, (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[2])),std::max(max[0], max[2]))); } if (strcmp(App::Part::BaseplaneTypes[2], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d(0, (max[1]+min[1])/2., (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[1], min[2])),std::max(max[1], max[2]))); } } //get the lines and set their values std::vector<App::DocumentObject*> lines = origin->getObjectsOfType(App::Line::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = lines.begin(); p != lines.end(); p++) { Gui::ViewProviderLine* vp = dynamic_cast<Gui::ViewProviderLine*>(Gui::Application::Instance->getViewProvider(*p)); if (strcmp(App::Part::BaselineTypes[0], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., (max[1]+min[1])/2., 0), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[1])),std::max(max[0], max[1]))); } if (strcmp(App::Part::BaselineTypes[1], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., 0, (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[2])),std::max(max[0], max[2]))); } if (strcmp(App::Part::BaselineTypes[2], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d(0, (max[1]+min[1])/2., (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[1], min[2])),std::max(max[1], max[2]))); } } } } bool ViewProviderPart::doubleClicked(void) { if(Workbench.getValue() != "") // assure the PartDesign workbench Gui::Command::assureWorkbench( Workbench.getValue() ); return true; } bool ViewProviderPart::onDelete(const std::vector<std::string> &) { //Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()" // ,getObject()->getDocument()->getName(), getObject()->getNameInDocument()); return true; } void ViewProviderPart::Restore(Base::XMLReader &reader) { Visibility.StatusBits.set(9); // tmp. set ViewProviderDocumentObject::Restore(reader); Visibility.StatusBits.reset(9); // unset } /** * Returns the pixmap for the list item. */ QIcon ViewProviderPart::getIcon() const { QIcon groupIcon; groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon), QIcon::Normal, QIcon::Off); groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon), QIcon::Normal, QIcon::On); return groupIcon; } void ViewProviderPart::setUpPart(const App::Part *part) { // add the standard planes at the root of the Part // first check if they already exist // FIXME: If the user renames them, they won't be found... bool found = false; std::vector<App::DocumentObject*> planes = part->getObjectsOfType(App::Plane::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = planes.begin(); p != planes.end(); p++) { for (unsigned i = 0; i < 3; i++) { if (strcmp(App::Part::BaseplaneTypes[i], dynamic_cast<App::Plane*>(*p)->PlaneType.getValue()) == 0) { found = true; break; } } if (found) break; } if (!found) { // ... and put them in the 'Origin' group Gui::Command::doCommand(Gui::Command::Doc,"Origin = App.activeDocument().addObject('App::Origin','%s')", "Origin"); Gui::Command::doCommand(Gui::Command::Doc,"Origin.Label = '%s'", QObject::tr("Origin").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().%s.addObject(Origin)", part->getNameInDocument()); // Add the planes ... Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[0]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("XY-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[1]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(1,0,0),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("XZ-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[2]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(1,1,1),120))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("YZ-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); // Add the lines ... Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[0]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("X-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[1]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(0,0,1),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("Y-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[2]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(0,1,0),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("Z-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); } } // Python feature ----------------------------------------------------------------------- namespace Gui { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderPartPython, Gui::ViewProviderPart) /// @endcond // explicit template instantiation template class GuiExport ViewProviderPythonFeatureT<ViewProviderPart>; } <commit_msg>fix crash when deleting body<commit_after>/*************************************************************************** * Copyright (c) 2006 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 <QApplication> # include <QPixmap> #endif #include <App/Part.h> #include <App/Origin.h> #include <App/Plane.h> #include <App/Line.h> #include <App/Document.h> /// Here the FreeCAD includes sorted by Base,App,Gui...... #include "ViewProviderPart.h" #include "ViewProviderPlane.h" #include "ViewProviderLine.h" #include "Application.h" #include "Command.h" #include "BitmapFactory.h" #include "Document.h" #include "Tree.h" #include "View3DInventor.h" #include "View3DInventorViewer.h" #include "Base/Console.h" #include <boost/bind.hpp> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/nodes/SoSeparator.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPart, Gui::ViewProviderGeometryObject) /** * Creates the view provider for an object group. */ ViewProviderPart::ViewProviderPart() { ADD_PROPERTY(Workbench,("PartDesignWorkbench")); } ViewProviderPart::~ViewProviderPart() { } /** * Whenever a property of the group gets changed then the same property of all * associated view providers of the objects of the object group get changed as well. */ void ViewProviderPart::onChanged(const App::Property* prop) { ViewProviderGeoFeatureGroup::onChanged(prop); } void ViewProviderPart::attach(App::DocumentObject *pcObj) { pcObj->getDocument()->signalChangedObject.connect(boost::bind(&ViewProviderPart::onObjectChanged, this, _1, _2)); ViewProviderGeoFeatureGroup::attach(pcObj); } void ViewProviderPart::updateData(const App::Property* prop) { ViewProviderGeoFeatureGroup::updateData(prop); } void ViewProviderPart::onObjectChanged(const App::DocumentObject& obj, const App::Property&) { App::Part* part = static_cast<App::Part*>(pcObject); if(static_cast<App::Part*>(pcObject)->hasObject(&obj) && obj.getTypeId() != App::Origin::getClassTypeId() && obj.getTypeId() != App::Plane::getClassTypeId() && obj.getTypeId() != App::Line::getClassTypeId()) { View3DInventorViewer* viewer = static_cast<View3DInventor*>(this->getActiveView())->getViewer(); SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); //calculate for everything but planes SbBox3f bbox(1e-9, 1e-9, 1e-9, 1e-9, 1e-9, 1e-9); for(App::DocumentObject* obj : part->getObjects()) { if(obj->getTypeId() != App::Origin::getClassTypeId() && obj->getTypeId() != App::Plane::getClassTypeId() && obj->getTypeId() != App::Line::getClassTypeId() ) { //getting crash on deletion PartDesign::Body object. no viewprovider. ViewProvider *viewProvider = Gui::Application::Instance->getViewProvider(obj); if (!viewProvider) continue; bboxAction.apply(viewProvider->getRoot()); bbox.extendBy(bboxAction.getBoundingBox()); } }; if(bbox.getSize().length() < 1e-6); bbox = SbBox3f(1e2, 1e2, 1e2, 1e2, 1e2, 1e2); //get the bounding box values SbVec3f size = bbox.getSize()*1.3; SbVec3f max = bbox.getMax()*1.3; SbVec3f min = bbox.getMin()*1.3; App::Origin* origin = static_cast<App::Origin*>(part->getObjectsOfType(App::Origin::getClassTypeId()).front()); if(!origin) return; //get the planes and set their values std::vector<App::DocumentObject*> planes = origin->getObjectsOfType(App::Plane::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = planes.begin(); p != planes.end(); p++) { Gui::ViewProviderPlane* vp = dynamic_cast<Gui::ViewProviderPlane*>(Gui::Application::Instance->getViewProvider(*p)); if (strcmp(App::Part::BaseplaneTypes[0], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., (max[1]+min[1])/2., 0), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[1])),std::max(max[0], max[1]))); } if (strcmp(App::Part::BaseplaneTypes[1], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., 0, (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[2])),std::max(max[0], max[2]))); } if (strcmp(App::Part::BaseplaneTypes[2], dynamic_cast<App::Plane*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Plane*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d(0, (max[1]+min[1])/2., (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[1], min[2])),std::max(max[1], max[2]))); } } //get the lines and set their values std::vector<App::DocumentObject*> lines = origin->getObjectsOfType(App::Line::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = lines.begin(); p != lines.end(); p++) { Gui::ViewProviderLine* vp = dynamic_cast<Gui::ViewProviderLine*>(Gui::Application::Instance->getViewProvider(*p)); if (strcmp(App::Part::BaselineTypes[0], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., (max[1]+min[1])/2., 0), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[1])),std::max(max[0], max[1]))); } if (strcmp(App::Part::BaselineTypes[1], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d((max[0]+min[0])/2., 0, (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[0], min[2])),std::max(max[0], max[2]))); } if (strcmp(App::Part::BaselineTypes[2], dynamic_cast<App::Line*>(*p)->getNameInDocument()) == 0) { Base::Placement cpl = dynamic_cast<App::Line*>(*p)->Placement.getValue(); cpl = Base::Placement(-cpl.getPosition() + Base::Vector3d(0, (max[1]+min[1])/2., (max[2]+min[2])/2.), Base::Rotation()); //dynamic_cast<App::Plane*>(*p)->Placement.setValue(cpl); if(vp) vp->Size.setValue(std::max(std::abs(std::min(min[1], min[2])),std::max(max[1], max[2]))); } } } } bool ViewProviderPart::doubleClicked(void) { if(Workbench.getValue() != "") // assure the PartDesign workbench Gui::Command::assureWorkbench( Workbench.getValue() ); return true; } bool ViewProviderPart::onDelete(const std::vector<std::string> &) { //Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()" // ,getObject()->getDocument()->getName(), getObject()->getNameInDocument()); return true; } void ViewProviderPart::Restore(Base::XMLReader &reader) { Visibility.StatusBits.set(9); // tmp. set ViewProviderDocumentObject::Restore(reader); Visibility.StatusBits.reset(9); // unset } /** * Returns the pixmap for the list item. */ QIcon ViewProviderPart::getIcon() const { QIcon groupIcon; groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon), QIcon::Normal, QIcon::Off); groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon), QIcon::Normal, QIcon::On); return groupIcon; } void ViewProviderPart::setUpPart(const App::Part *part) { // add the standard planes at the root of the Part // first check if they already exist // FIXME: If the user renames them, they won't be found... bool found = false; std::vector<App::DocumentObject*> planes = part->getObjectsOfType(App::Plane::getClassTypeId()); for (std::vector<App::DocumentObject*>::const_iterator p = planes.begin(); p != planes.end(); p++) { for (unsigned i = 0; i < 3; i++) { if (strcmp(App::Part::BaseplaneTypes[i], dynamic_cast<App::Plane*>(*p)->PlaneType.getValue()) == 0) { found = true; break; } } if (found) break; } if (!found) { // ... and put them in the 'Origin' group Gui::Command::doCommand(Gui::Command::Doc,"Origin = App.activeDocument().addObject('App::Origin','%s')", "Origin"); Gui::Command::doCommand(Gui::Command::Doc,"Origin.Label = '%s'", QObject::tr("Origin").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().%s.addObject(Origin)", part->getNameInDocument()); // Add the planes ... Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[0]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("XY-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[1]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(1,0,0),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("XZ-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Plane','%s')", App::Part::BaseplaneTypes[2]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(1,1,1),120))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("YZ-Plane").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); // Add the lines ... Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[0]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("X-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[1]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(0,0,1),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("Y-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Line','%s')", App::Part::BaselineTypes[2]); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(0,1,0),90))"); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().ActiveObject.Label = '%s'", QObject::tr("Z-Axis").toStdString().c_str()); Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Origin.addObject(App.activeDocument().ActiveObject)"); } } // Python feature ----------------------------------------------------------------------- namespace Gui { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderPartPython, Gui::ViewProviderPart) /// @endcond // explicit template instantiation template class GuiExport ViewProviderPythonFeatureT<ViewProviderPart>; } <|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 testSoundfileLoader = NULL; TTSampleMatrixPtr 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 1: set the filepath TTBoolean result1 = { testSoundfileLoader->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: instantiate a TTSampleMatrix and set is as the target TTBoolean result2 = { TTObjectBaseInstantiate("samplematrix", (TTObjectBasePtr*)&testTargetMatrix, kTTValNONE) == kTTErrNone}; // set up the samplematrix testTargetMatrix->setAttributeValue("numChannels", 1); testTargetMatrix->setAttributeValue("lengthInSamples", 500); TTInt32 lengthReturn, channelsReturn; testTargetMatrix->getAttributeValue("numChannels", channelsReturn); testTargetMatrix->getAttributeValue("lengthInSamples", lengthReturn); TTTestLog("samplematrix now has %i samples and %i channels", lengthReturn, channelsReturn); TTBoolean result2b = { testSoundfileLoader->setTargetMatrix(testTargetMatrix) == kTTErrNone }; TTTestAssertion("setTargetMatrix operates successfully", result2b, testAssertionCount, errorCount); // pre-test TTSampleValue test13expect = TTRandom64(); testTargetMatrix->poke(0,0,test13expect); TTTestLog("poking from here worked"); // TEST 3: copy one second of samplevalues TTBoolean result3 = { testSoundfileLoader->copyUntilFull() == kTTErrNone };//false;// TTTestAssertion("copyUntilFull operates successfully", result3, testAssertionCount, errorCount); // TEST X prep TTValue loadInput, loadOuput; loadInput.append(TT(TESTFILE)); loadInput.append(testTargetMatrix); /* // TEST X: use the public method to perform loading action // the final test, not working yet TTBoolean resultX = { load(loadInput, loadOuput) == kTTErrNone }; TTTestAssertion("load operates successfully", resultX, testAssertionCount, errorCount); */ } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>one more change from Length to LengthInSeconds<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; TTSampleMatrixPtr 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 1: set the filepath TTBoolean result1 = { testSoundfileLoader->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: instantiate a TTSampleMatrix and set is as the target TTBoolean result2 = { TTObjectBaseInstantiate("samplematrix", (TTObjectBasePtr*)&testTargetMatrix, kTTValNONE) == kTTErrNone}; // set up the samplematrix testTargetMatrix->setAttributeValue("numChannels", 1); testTargetMatrix->setAttributeValue("lengthInSeconds", 1.0); TTInt32 lengthReturn, channelsReturn; testTargetMatrix->getAttributeValue("numChannels", channelsReturn); testTargetMatrix->getAttributeValue("lengthInSamples", lengthReturn); TTTestLog("samplematrix now has %i samples and %i channels", lengthReturn, channelsReturn); TTBoolean result2b = { testSoundfileLoader->setTargetMatrix(testTargetMatrix) == kTTErrNone }; TTTestAssertion("setTargetMatrix operates successfully", result2b, testAssertionCount, errorCount); // pre-test TTSampleValue test13expect = TTRandom64(); testTargetMatrix->poke(0,0,test13expect); TTTestLog("poking from here worked"); // TEST 3: copy one second of samplevalues TTBoolean result3 = { testSoundfileLoader->copyUntilFull() == kTTErrNone };//false;// TTTestAssertion("copyUntilFull operates successfully", result3, testAssertionCount, errorCount); // TEST X prep TTValue loadInput, loadOuput; loadInput.append(TT(TESTFILE)); loadInput.append(testTargetMatrix); /* // TEST X: use the public method to perform loading action // the final test, not working yet TTBoolean resultX = { load(loadInput, loadOuput) == kTTErrNone }; TTTestAssertion("load operates successfully", resultX, testAssertionCount, errorCount); */ } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|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, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class. * * @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" /* It is possible to change the target sound file for this test using the macros below. Both sound files are included in the Jamoma respository at the following path: {JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/ The test should look for the named TESTFILE at this path. */ /* */ #define TESTFILE "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 "ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // assemble the full path of the target sound file TTString testSoundPath = TTFoundationBinaryPath; int pos = testSoundPath.find_last_of('/'); testSoundPath = testSoundPath.substr(0,pos+1); testSoundPath += TESTFILE; std::cout << "We will be using the following path for testing: " << testSoundPath << "\n"; try { TTTestLog("\n"); TTTestLog("Testing TTSoundfileLoader Basics..."); // TEST 0: establish our objects & pointers TTObject* testTargetMatrix = new TTObject("samplematrix"); TTObject* testNonSampleMatrix = new TTObject("delay"); TTObjectBase* objectBasePtrToSampleMatrix; TTObjectBase* ptrToNonSampleMatrix; // TEST 1: set the filepath TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: set up the samplematrix first int channelsSend = 1; // compiler complained about TTInt32 being ambiguous here int lengthSend = 22050; // compiler complained about TTInt32 being ambiguous here testTargetMatrix->set("numChannels", channelsSend); testTargetMatrix->set("lengthInSamples", lengthSend); TTInt32 channelsReturn, lengthReturn; testTargetMatrix->get("numChannels", channelsReturn); testTargetMatrix->get("lengthInSamples", lengthReturn); // now for the actual test TTBoolean result2a = { channelsSend == channelsReturn }; TTTestAssertion("numChannels attribute set successfully", result2a, testAssertionCount, errorCount); TTBoolean result2b = { lengthSend == lengthReturn }; TTTestAssertion("lengthInSamples attribute set successfully", result2b, testAssertionCount, errorCount); // // TEST 3: set the target via an objectBasePtr objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this? TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone }; TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully", result3, testAssertionCount, errorCount); // TEST 4: set the target to a non-SampleMatrix, should FAIL ptrToNonSampleMatrix = testNonSampleMatrix->instance(); TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue }; TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix", result4, testAssertionCount, errorCount); // TEST 5: copy samplevalues until samplematrix is filled TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone }; TTTestAssertion("copyUntilFilled operates successfully", result5, testAssertionCount, errorCount); // TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence // create a new TTSampleMatrix TTObject newTargetMatrix("samplematrix"); // set the length and channel count newTargetMatrix.set("numChannels", TESTNUMCHANNELS); newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES); // prepare necessary TTValues TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue TTValue aReturnWeDontCareAbout6; // send message newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6); // now let's test some values! int randomIndex6; TTSampleValue randomValueSoundFile6; TTBoolean result6 = true; for (int i = 0; i<5; i++) { randomIndex6 = lengthReturn * TTRandom64(); std::cout << "let's look at index " << randomIndex6 << "\n"; TTValue peekInput6(randomIndex6); peekInput6.append(0); TTValue peekOutput6; this->peek(randomIndex6,0,randomValueSoundFile6); newTargetMatrix.send("peek",peekInput6,peekOutput6); std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n"; if (result6) // allows test to keep variable false once it is false result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001); } TTTestAssertion("comparing 5 random values for equivalence", result6, testAssertionCount, errorCount); // // TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence // create a new TTBuffer TTObject newTargetBuffer("buffer"); // set the length and channel count newTargetBuffer.set("numChannels", TESTNUMCHANNELS); newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES); //need to confirm these are set TTInt32 channelsReturn7, lengthReturn7; newTargetBuffer.get("numChannels", channelsReturn7); newTargetBuffer.get("lengthInSamples", lengthReturn7); std::cout << "The new buffer is " << lengthReturn7 << " samples & " << channelsReturn7 << " channels\n"; // prepare necessary TTValues TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue TTValue aReturnWeDontCareAbout7; // send message newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7); // now let's test some values! int randomIndex7; TTSampleValue randomValueSoundFile7; TTBoolean result7 = true; for (int i = 0; i<5; i++) { randomIndex7 = lengthReturn * TTRandom64(); std::cout << "let's look at index " << randomIndex7 << "\n"; TTValue peekInput7(randomIndex7); peekInput7.append(0); TTValue peekOutput7; this->peek(randomIndex7,0,randomValueSoundFile7); newTargetBuffer.send("peek",peekInput7,peekOutput7); std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n"; if (result7) // allows test to keep variable false once it is false result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001); } TTTestAssertion("comparing 5 random values for equivalence", result7, testAssertionCount, errorCount); // // releasing objects objectBasePtrToSampleMatrix = NULL; ptrToNonSampleMatrix = NULL; delete testTargetMatrix; delete testNonSampleMatrix; } catch (...) { TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate", 0, testAssertionCount, errorCount); } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>TTSoundfileLoader::test() - added pre-test for load messages<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, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class. * * @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" /* It is possible to change the target sound file for this test using the macros below. Both sound files are included in the Jamoma respository at the following path: {JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/ The test should look for the named TESTFILE at this path. */ /* */ #define TESTFILE "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 "ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // assemble the full path of the target sound file TTString testSoundPath = TTFoundationBinaryPath; int pos = testSoundPath.find_last_of('/'); testSoundPath = testSoundPath.substr(0,pos+1); testSoundPath += TESTFILE; std::cout << "We will be using the following path for testing: " << testSoundPath << "\n"; try { TTTestLog("\n"); TTTestLog("Testing TTSoundfileLoader Basics..."); // TEST 0: establish our objects & pointers TTObject* testTargetMatrix = new TTObject("samplematrix"); TTObject* testNonSampleMatrix = new TTObject("delay"); TTObjectBase* objectBasePtrToSampleMatrix; TTObjectBase* ptrToNonSampleMatrix; // TEST 1: set the filepath TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: set up the samplematrix first int channelsSend = 1; // compiler complained about TTInt32 being ambiguous here int lengthSend = 22050; // compiler complained about TTInt32 being ambiguous here testTargetMatrix->set("numChannels", channelsSend); testTargetMatrix->set("lengthInSamples", lengthSend); TTInt32 channelsReturn, lengthReturn; testTargetMatrix->get("numChannels", channelsReturn); testTargetMatrix->get("lengthInSamples", lengthReturn); // now for the actual test TTBoolean result2a = { channelsSend == channelsReturn }; TTTestAssertion("numChannels attribute set successfully", result2a, testAssertionCount, errorCount); TTBoolean result2b = { lengthSend == lengthReturn }; TTTestAssertion("lengthInSamples attribute set successfully", result2b, testAssertionCount, errorCount); // // TEST 3: set the target via an objectBasePtr objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this? TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone }; TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully", result3, testAssertionCount, errorCount); // TEST 4: set the target to a non-SampleMatrix, should FAIL ptrToNonSampleMatrix = testNonSampleMatrix->instance(); TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue }; TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix", result4, testAssertionCount, errorCount); // TEST 5: copy samplevalues until samplematrix is filled TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone }; TTTestAssertion("copyUntilFilled operates successfully", result5, testAssertionCount, errorCount); // TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence // create a new TTSampleMatrix TTObject newTargetMatrix("samplematrix"); // set the length and channel count newTargetMatrix.set("numChannels", TESTNUMCHANNELS); newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES); // prepare necessary TTValues TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue TTValue aReturnWeDontCareAbout6; // send message TTBoolean result6a = { newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone }; TTTestAssertion("TTSampleMatrix load operates successfully", result6a, testAssertionCount, errorCount); // now let's test some values! int randomIndex6; TTSampleValue randomValueSoundFile6; TTBoolean result6 = true; for (int i = 0; i<5; i++) { randomIndex6 = lengthReturn * TTRandom64(); std::cout << "let's look at index " << randomIndex6 << "\n"; TTValue peekInput6(randomIndex6); peekInput6.append(0); TTValue peekOutput6; this->peek(randomIndex6,0,randomValueSoundFile6); newTargetMatrix.send("peek",peekInput6,peekOutput6); std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n"; if (result6) // allows test to keep variable false once it is false result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001); } TTTestAssertion("comparing 5 random values for equivalence", result6, testAssertionCount, errorCount); // // TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence // create a new TTBuffer TTObject newTargetBuffer("buffer"); // set the length and channel count newTargetBuffer.set("numChannels", TESTNUMCHANNELS); newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES); // prepare necessary TTValues TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue TTValue aReturnWeDontCareAbout7; // send message TTBoolean result7a = { newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone }; TTTestAssertion("TTBuffer load operates successfully", result7a, testAssertionCount, errorCount); // now let's test some values! int randomIndex7; TTSampleValue randomValueSoundFile7; TTBoolean result7 = true; for (int i = 0; i<5; i++) { randomIndex7 = lengthReturn * TTRandom64(); std::cout << "let's look at index " << randomIndex7 << "\n"; TTValue peekInput7(randomIndex7); peekInput7.append(0); TTValue peekOutput7; this->peek(randomIndex7,0,randomValueSoundFile7); newTargetBuffer.send("peek",peekInput7,peekOutput7); std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n"; if (result7) // allows test to keep variable false once it is false result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001); } TTTestAssertion("comparing 5 random values for equivalence", result7, testAssertionCount, errorCount); // // releasing objects objectBasePtrToSampleMatrix = NULL; ptrToNonSampleMatrix = NULL; delete testTargetMatrix; delete testNonSampleMatrix; } catch (...) { TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate", 0, testAssertionCount, errorCount); } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <fstream> #include <vector> #include <math.h> #include <string> #include <boost/lexical_cast.hpp> #include "analysistool.h" #include <votca/tools/histogram.h> #include <votca/csg/version.h> #include "bondedstatistics.h" #include "tabulatedpotential.h" using namespace std; using namespace boost; TabulatedPotential::TabulatedPotential() { _tab_smooth1 = _tab_smooth2 = 0; _T = 300; } void TabulatedPotential::Register(map<string, AnalysisTool *> &lib) { lib["tab"] = this; lib["hist"] = this; } void TabulatedPotential::Command(BondedStatistics &bs, string cmd, vector<string> &args) { if(args[0] == "set") { if(cmd == "hist") SetOption(_hist_options, args); else if(cmd == "tab") { if(!SetOption(_tab_options, args)) { if(args.size() >2) { if(args[1] == "smooth_pdf") _tab_smooth1 = lexical_cast<int>(args[2]); else if(args[1] == "smooth_pot") _tab_smooth2 = lexical_cast<int>(args[2]); else if(args[1] == "T") _T = lexical_cast<double>(args[2]); else { cout << "unknown option " << args[2] << endl; return; } } } if(args.size() <=2) { cout << "smooth_pdf: " << _tab_smooth1 << endl; cout << "smooth_pot: " << _tab_smooth2 << endl; cout << "T: " << _T << endl; } } } else if(args.size() >= 2) { if(cmd == "hist") WriteHistogram(bs, args); else if(cmd == "tab") WritePotential(bs, args); } else cout << "wrong number of arguments" << endl; } void TabulatedPotential::Help(string cmd, vector<string> &args) { if(args.size() == 0) { if(cmd == "tab") { cout << "tab <file> <selection>\n" << "Calculate tabulated potential by inverting the distribution function. " "Statistics is calculated using all interactions in selection.\n" "see also: help tab set\n\n" "example:\ntab set scale bond\ntab U_bond.txt *:bond:*\n"; } if(cmd == "hist") { cout << "hist <file> <selection>\n" << "Calculate distribution function for selection. " "Statistics is calculated using all interactions in selection.\n" "see also: help hist set\n\n" "example:hist U_bond.txt *:bond:*\n"; } return; } if(args[0] == "set") { if(args.size() == 1) { cout << cmd << " set <option> <value>\n" << "set option for this command. Use \"" << cmd << " set\"" " for a list of availale options. To get telp on a specific option use e.g.\n" << cmd << " set periodic\n"; return; } if(args[1] == "n") { cout << cmd << "set n <integer>\n" << "set number of bins for table\n"; return; } if(args[1] == "min") { cout << cmd << "set min <value>\n" << "minimum value of interval for histogram (see also periodic, extend)\n"; return; } if(args[1] == "max") { cout << cmd << "set max <value>\n" << "maximum value of interval for histogram (see also periodic, extend)\n"; return; } if(args[1] == "periodic") { cout << cmd << "set periodic <value>\n" << "can be 1 for periodic interval (e.g. dihedral) or 0 for " "non-periodic (e.g. bond)\n"; return; } if(args[1] == "auto") { cout << cmd << "set auto <value>\n" "can be 1 for automatically determine the interval for the " "table (min, max, extend will be ignored) or 0 to use min/max as specified\n"; return; } if(args[1] == "extend") { cout << cmd << "set extend <value>\n" "should only be used with auto=0. Can be 1 for extend the interval " "if values are out of bounds (min/max) " "or 0 to ignore values which are out of the interal\n"; return; } if(args[1] == "scale") { cout << cmd << "set scale <value>\n" "volume normalization of pdf. Can be no (no scaling), bond " "(1/r^2) or angle ( 1/sin(phi) ). See VOTCA manual, section " "theoretical background for details\n"; return; } if(args[1] == "normalize") { cout << cmd << "set normalize <value>\n" "can be 1 for a normalized histogram or 0 to skip normalization\n"; return; } if(cmd == "tab") { if(args[1] == "smooth_pdf") { cout << "tab set smooth_pdf <value>\n" "Perform so many smoothing iterations on the distribution function before inverting the potential\n"; return; } if(args[1] == "smooth_pot") { cout << "tab set smooth_pot <value>\n" "Perform so many smoothing iterations on tabulated potential after inverting the potential\n"; return; } if(args[1] == "T") { cout << "tab set T <value>\n" "Temperature in Kelvin the simulation was performed\n"; return; } } } cout << "no help text available" << endl; } bool TabulatedPotential::SetOption(Histogram::options_t &op, const vector<string> &args) { if(args.size() >2) { if(args[1] == "n") op._n = lexical_cast<int>(args[2]); else if(args[1] == "min") { op._min = lexical_cast<double>(args[2]); } else if(args[1] == "max") op._max = lexical_cast<double>(args[2]); else if(args[1] == "periodic") op._periodic = lexical_cast<bool>(args[2]); else if(args[1] == "auto") op._auto_interval = lexical_cast<bool>(args[2]); else if(args[1] == "extend") op._extend_interval = lexical_cast<bool>(args[2]); else if(args[1] == "normalize") op._normalize = lexical_cast<bool>(args[2]); else if(args[1] == "scale") { if(args[2]=="no" || args[2]=="bond" || args[2]=="angle") op._scale = args[2]; else { cout << "scale can be: no, bond or angle\n"; } } else { return false; } } else { cout << "n: " << op._n << endl; cout << "min: " << op._min << endl; cout << "max: " << op._max << endl; cout << "periodic: " << op._periodic << endl; cout << "auto: " << op._auto_interval << endl; cout << "extend: " << op._extend_interval << endl; cout << "scale: " << op._scale << endl; cout << "normalize: " << op._normalize << endl; } return true; } void TabulatedPotential::WriteHistogram(BondedStatistics &bs, vector<string> &args) { ofstream out; DataCollection<double>::selection *sel = NULL; for(size_t i=1; i<args.size(); i++) sel = bs.BondedValues().select(args[i], sel); Histogram h(_hist_options); h.ProcessData(sel); out.open(args[0].c_str()); /* out << "# histogram, created csg version " << VERSION_STR << endl; out << "# n = " << _hist_options._n << endl; out << "# min = " << _hist_options._min << endl; out << "# max = " << _hist_options._max << endl; out << "# periodic = " << _hist_options._periodic << endl; out << "# auto = " << _hist_options._auto_interval << endl; out << "# extend = " << _hist_options._extend_interval << endl; out << "# scale = " << _hist_options._scale << endl;*/ out << h ; out.close(); cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl; delete sel; } void TabulatedPotential::CalcForce(vector<double> &U, vector<double> &F, double dx, bool bPeriodic) { size_t n=U.size(); double f = 0.5/dx; F.resize(n); if(bPeriodic) F[n-1] = F[0] = -(U[1] - U[n-2])*f; else { F[0] = -(U[1] - U[0])*2*f; F[n-1] = -(U[n-1] - U[n-2])*2*f; } for(size_t i=1; i<n-1; i++) F[i] = -(U[i+1] - U[i-1])*f; } void TabulatedPotential::WritePotential(BondedStatistics &bs, vector<string> &args) { ofstream out; DataCollection<double>::selection *sel = NULL; for(size_t i=1; i<args.size(); i++) sel = bs.BondedValues().select(args[i], sel); Histogram h(_tab_options); h.ProcessData(sel); for(int i=0; i<_tab_smooth1; ++i) Smooth(h.getPdf(), _tab_options._periodic); BoltzmannInvert(h.getPdf(), _T); for(int i=0; i<_tab_smooth2; ++i) Smooth(h.getPdf(), _tab_options._periodic); out.open(args[0].c_str()); /* out << "# tabulated potential, created csg version " VERSION_STR << endl; out << "# n = " << _tab_options._n << endl; out << "# min = " << _tab_options._min << endl; out << "# max = " << _tab_options._max << endl; out << "# periodic = " << _tab_options._periodic << endl; out << "# auto = " << _tab_options._auto_interval << endl; out << "# extend = " << _tab_options._extend_interval << endl; out << "# scale = " << _tab_options._scale << endl; out << "# smooth_pdf = " << _tab_smooth1 << endl; out << "# smooth_pot = " << _tab_smooth2 << endl; out << "# T = " << _T << endl;*/ vector<double> F; CalcForce(h.getPdf(), F, h.getInterval(), _tab_options._periodic); for(int i=0; i<h.getN(); i++) { out << h.getMin() + h.getInterval()*((double)i) << " " << h.getPdf()[i] << " " << F[i] << endl; } out.close(); cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl; delete sel; } void TabulatedPotential::Smooth(vector<double> &data, bool bPeriodic) { double old[3]; int n=data.size(); if(bPeriodic) { old[0] = data[n-3]; old[1] = data[n-2]; } else { old[0] = data[0]; old[1] = data[0]; } size_t i; for(i=0; i<data.size()-2; i++) { old[2] = data[i]; data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[i+2])/9.; old[0]=old[1]; old[1]=old[2];; } if(bPeriodic) { data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[0])/9.; old[0]=old[1];old[1]=data[i]; data[n-1] = data[0]; } else { data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 3.*data[i+1])/9.; old[0]=old[1];old[1]=data[i]; i++; data[i] = (old[0] + 2.*old[1] + 6.*data[i])/9.; } } void TabulatedPotential::BoltzmannInvert(vector<double> &data, double T) { double _min, _max; _min = numeric_limits<double>::max(); _max = numeric_limits<double>::min(); for(size_t i=0; i<data.size(); i++) { _max = max(data[i], _max); if(data[i] > 0) _min = min(data[i], _min); } _max = -8.3109*T*log(_max)*0.001; _min = -8.3109*T*log(_min)*0.001-_max; for(size_t i=0; i<data.size(); i++) { if(data[i] == 0) data[i] = _min; else data[i] = -8.3109*T*log(data[i])*0.001 - _max; } } <commit_msg>fixed a typo (thx to lintian)<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <fstream> #include <vector> #include <math.h> #include <string> #include <boost/lexical_cast.hpp> #include "analysistool.h" #include <votca/tools/histogram.h> #include <votca/csg/version.h> #include "bondedstatistics.h" #include "tabulatedpotential.h" using namespace std; using namespace boost; TabulatedPotential::TabulatedPotential() { _tab_smooth1 = _tab_smooth2 = 0; _T = 300; } void TabulatedPotential::Register(map<string, AnalysisTool *> &lib) { lib["tab"] = this; lib["hist"] = this; } void TabulatedPotential::Command(BondedStatistics &bs, string cmd, vector<string> &args) { if(args[0] == "set") { if(cmd == "hist") SetOption(_hist_options, args); else if(cmd == "tab") { if(!SetOption(_tab_options, args)) { if(args.size() >2) { if(args[1] == "smooth_pdf") _tab_smooth1 = lexical_cast<int>(args[2]); else if(args[1] == "smooth_pot") _tab_smooth2 = lexical_cast<int>(args[2]); else if(args[1] == "T") _T = lexical_cast<double>(args[2]); else { cout << "unknown option " << args[2] << endl; return; } } } if(args.size() <=2) { cout << "smooth_pdf: " << _tab_smooth1 << endl; cout << "smooth_pot: " << _tab_smooth2 << endl; cout << "T: " << _T << endl; } } } else if(args.size() >= 2) { if(cmd == "hist") WriteHistogram(bs, args); else if(cmd == "tab") WritePotential(bs, args); } else cout << "wrong number of arguments" << endl; } void TabulatedPotential::Help(string cmd, vector<string> &args) { if(args.size() == 0) { if(cmd == "tab") { cout << "tab <file> <selection>\n" << "Calculate tabulated potential by inverting the distribution function. " "Statistics is calculated using all interactions in selection.\n" "see also: help tab set\n\n" "example:\ntab set scale bond\ntab U_bond.txt *:bond:*\n"; } if(cmd == "hist") { cout << "hist <file> <selection>\n" << "Calculate distribution function for selection. " "Statistics is calculated using all interactions in selection.\n" "see also: help hist set\n\n" "example:hist U_bond.txt *:bond:*\n"; } return; } if(args[0] == "set") { if(args.size() == 1) { cout << cmd << " set <option> <value>\n" << "set option for this command. Use \"" << cmd << " set\"" " for a list of available options. To get telp on a specific option use e.g.\n" << cmd << " set periodic\n"; return; } if(args[1] == "n") { cout << cmd << "set n <integer>\n" << "set number of bins for table\n"; return; } if(args[1] == "min") { cout << cmd << "set min <value>\n" << "minimum value of interval for histogram (see also periodic, extend)\n"; return; } if(args[1] == "max") { cout << cmd << "set max <value>\n" << "maximum value of interval for histogram (see also periodic, extend)\n"; return; } if(args[1] == "periodic") { cout << cmd << "set periodic <value>\n" << "can be 1 for periodic interval (e.g. dihedral) or 0 for " "non-periodic (e.g. bond)\n"; return; } if(args[1] == "auto") { cout << cmd << "set auto <value>\n" "can be 1 for automatically determine the interval for the " "table (min, max, extend will be ignored) or 0 to use min/max as specified\n"; return; } if(args[1] == "extend") { cout << cmd << "set extend <value>\n" "should only be used with auto=0. Can be 1 for extend the interval " "if values are out of bounds (min/max) " "or 0 to ignore values which are out of the interal\n"; return; } if(args[1] == "scale") { cout << cmd << "set scale <value>\n" "volume normalization of pdf. Can be no (no scaling), bond " "(1/r^2) or angle ( 1/sin(phi) ). See VOTCA manual, section " "theoretical background for details\n"; return; } if(args[1] == "normalize") { cout << cmd << "set normalize <value>\n" "can be 1 for a normalized histogram or 0 to skip normalization\n"; return; } if(cmd == "tab") { if(args[1] == "smooth_pdf") { cout << "tab set smooth_pdf <value>\n" "Perform so many smoothing iterations on the distribution function before inverting the potential\n"; return; } if(args[1] == "smooth_pot") { cout << "tab set smooth_pot <value>\n" "Perform so many smoothing iterations on tabulated potential after inverting the potential\n"; return; } if(args[1] == "T") { cout << "tab set T <value>\n" "Temperature in Kelvin the simulation was performed\n"; return; } } } cout << "no help text available" << endl; } bool TabulatedPotential::SetOption(Histogram::options_t &op, const vector<string> &args) { if(args.size() >2) { if(args[1] == "n") op._n = lexical_cast<int>(args[2]); else if(args[1] == "min") { op._min = lexical_cast<double>(args[2]); } else if(args[1] == "max") op._max = lexical_cast<double>(args[2]); else if(args[1] == "periodic") op._periodic = lexical_cast<bool>(args[2]); else if(args[1] == "auto") op._auto_interval = lexical_cast<bool>(args[2]); else if(args[1] == "extend") op._extend_interval = lexical_cast<bool>(args[2]); else if(args[1] == "normalize") op._normalize = lexical_cast<bool>(args[2]); else if(args[1] == "scale") { if(args[2]=="no" || args[2]=="bond" || args[2]=="angle") op._scale = args[2]; else { cout << "scale can be: no, bond or angle\n"; } } else { return false; } } else { cout << "n: " << op._n << endl; cout << "min: " << op._min << endl; cout << "max: " << op._max << endl; cout << "periodic: " << op._periodic << endl; cout << "auto: " << op._auto_interval << endl; cout << "extend: " << op._extend_interval << endl; cout << "scale: " << op._scale << endl; cout << "normalize: " << op._normalize << endl; } return true; } void TabulatedPotential::WriteHistogram(BondedStatistics &bs, vector<string> &args) { ofstream out; DataCollection<double>::selection *sel = NULL; for(size_t i=1; i<args.size(); i++) sel = bs.BondedValues().select(args[i], sel); Histogram h(_hist_options); h.ProcessData(sel); out.open(args[0].c_str()); /* out << "# histogram, created csg version " << VERSION_STR << endl; out << "# n = " << _hist_options._n << endl; out << "# min = " << _hist_options._min << endl; out << "# max = " << _hist_options._max << endl; out << "# periodic = " << _hist_options._periodic << endl; out << "# auto = " << _hist_options._auto_interval << endl; out << "# extend = " << _hist_options._extend_interval << endl; out << "# scale = " << _hist_options._scale << endl;*/ out << h ; out.close(); cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl; delete sel; } void TabulatedPotential::CalcForce(vector<double> &U, vector<double> &F, double dx, bool bPeriodic) { size_t n=U.size(); double f = 0.5/dx; F.resize(n); if(bPeriodic) F[n-1] = F[0] = -(U[1] - U[n-2])*f; else { F[0] = -(U[1] - U[0])*2*f; F[n-1] = -(U[n-1] - U[n-2])*2*f; } for(size_t i=1; i<n-1; i++) F[i] = -(U[i+1] - U[i-1])*f; } void TabulatedPotential::WritePotential(BondedStatistics &bs, vector<string> &args) { ofstream out; DataCollection<double>::selection *sel = NULL; for(size_t i=1; i<args.size(); i++) sel = bs.BondedValues().select(args[i], sel); Histogram h(_tab_options); h.ProcessData(sel); for(int i=0; i<_tab_smooth1; ++i) Smooth(h.getPdf(), _tab_options._periodic); BoltzmannInvert(h.getPdf(), _T); for(int i=0; i<_tab_smooth2; ++i) Smooth(h.getPdf(), _tab_options._periodic); out.open(args[0].c_str()); /* out << "# tabulated potential, created csg version " VERSION_STR << endl; out << "# n = " << _tab_options._n << endl; out << "# min = " << _tab_options._min << endl; out << "# max = " << _tab_options._max << endl; out << "# periodic = " << _tab_options._periodic << endl; out << "# auto = " << _tab_options._auto_interval << endl; out << "# extend = " << _tab_options._extend_interval << endl; out << "# scale = " << _tab_options._scale << endl; out << "# smooth_pdf = " << _tab_smooth1 << endl; out << "# smooth_pot = " << _tab_smooth2 << endl; out << "# T = " << _T << endl;*/ vector<double> F; CalcForce(h.getPdf(), F, h.getInterval(), _tab_options._periodic); for(int i=0; i<h.getN(); i++) { out << h.getMin() + h.getInterval()*((double)i) << " " << h.getPdf()[i] << " " << F[i] << endl; } out.close(); cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl; delete sel; } void TabulatedPotential::Smooth(vector<double> &data, bool bPeriodic) { double old[3]; int n=data.size(); if(bPeriodic) { old[0] = data[n-3]; old[1] = data[n-2]; } else { old[0] = data[0]; old[1] = data[0]; } size_t i; for(i=0; i<data.size()-2; i++) { old[2] = data[i]; data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[i+2])/9.; old[0]=old[1]; old[1]=old[2];; } if(bPeriodic) { data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[0])/9.; old[0]=old[1];old[1]=data[i]; data[n-1] = data[0]; } else { data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 3.*data[i+1])/9.; old[0]=old[1];old[1]=data[i]; i++; data[i] = (old[0] + 2.*old[1] + 6.*data[i])/9.; } } void TabulatedPotential::BoltzmannInvert(vector<double> &data, double T) { double _min, _max; _min = numeric_limits<double>::max(); _max = numeric_limits<double>::min(); for(size_t i=0; i<data.size(); i++) { _max = max(data[i], _max); if(data[i] > 0) _min = min(data[i], _min); } _max = -8.3109*T*log(_max)*0.001; _min = -8.3109*T*log(_min)*0.001-_max; for(size_t i=0; i<data.size(); i++) { if(data[i] == 0) data[i] = _min; else data[i] = -8.3109*T*log(data[i])*0.001 - _max; } } <|endoftext|>
<commit_before> #include "qmlscriptparser_p.h" #include "parser/javascriptengine_p.h" #include "parser/javascriptparser_p.h" #include "parser/javascriptlexer_p.h" #include "parser/javascriptnodepool_p.h" #include "parser/javascriptastvisitor_p.h" #include "parser/javascriptast_p.h" #include "parser/javascriptprettypretty_p.h" #include <QStack> #include <QtDebug> QT_BEGIN_NAMESPACE using namespace JavaScript; using namespace QmlParser; namespace { class ProcessAST: protected AST::Visitor { struct State { State() : object(0), property(0) {} State(Object *o) : object(o), property(0) {} State(Object *o, Property *p) : object(o), property(p) {} Object *object; Property *property; }; struct StateStack : public QStack<State> { void pushObject(Object *obj) { push(State(obj)); } void pushProperty(const QString &name, int lineNumber) { const State &state = top(); if (state.property) { State s(state.property->getValue(), state.property->getValue()->getProperty(name.toLatin1())); s.property->line = lineNumber; push(s); } else { State s(state.object, state.object->getProperty(name.toLatin1())); s.property->line = lineNumber; push(s); } } }; public: ProcessAST(QmlScriptParser *parser); virtual ~ProcessAST(); void operator()(AST::Node *node); protected: Object *defineObjectBinding(int line, const QString &propertyName, const QString &objectType, AST::UiObjectInitializer *initializer = 0); QString getPrimitive(const QByteArray &propertyName, AST::ExpressionNode *expr); using AST::Visitor::visit; using AST::Visitor::endVisit; virtual bool visit(AST::UiObjectDefinition *node); virtual bool visit(AST::UiPublicMember *node); virtual bool visit(AST::UiObjectBinding *node); virtual bool visit(AST::UiScriptBinding *node); virtual bool visit(AST::UiArrayBinding *node); void accept(AST::Node *node); QString asString(AST::UiQualifiedId *node) const; const State state() const; Object *currentObject() const; Property *currentProperty() const; QString qualifiedNameId() const; private: QmlScriptParser *_parser; StateStack _stateStack; QStringList _scope; }; ProcessAST::ProcessAST(QmlScriptParser *parser) : _parser(parser) { } ProcessAST::~ProcessAST() { } void ProcessAST::operator()(AST::Node *node) { accept(node); } void ProcessAST::accept(AST::Node *node) { AST::Node::acceptChild(node, this); } const ProcessAST::State ProcessAST::state() const { if (_stateStack.isEmpty()) return State(); return _stateStack.back(); } Object *ProcessAST::currentObject() const { return state().object; } Property *ProcessAST::currentProperty() const { return state().property; } QString ProcessAST::qualifiedNameId() const { return _scope.join(QLatin1String("/")); } QString ProcessAST::asString(AST::UiQualifiedId *node) const { QString s; for (AST::UiQualifiedId *it = node; it; it = it->next) { s.append(it->name->asString()); if (it->next) s.append(QLatin1Char('.')); } return s; } Object *ProcessAST::defineObjectBinding(int line, const QString &propertyName, const QString &objectType, AST::UiObjectInitializer *initializer) { bool isType = !objectType.isEmpty() && objectType.at(0).isUpper() && !objectType.contains(QLatin1Char('.')); if (!isType) { qWarning() << "bad name for a class"; // ### FIXME return false; } const QStringList str = propertyName.split(QLatin1Char('.'), QString::SkipEmptyParts); for(int ii = 0; ii < str.count(); ++ii) { const QString s = str.at(ii); _stateStack.pushProperty(s, line); } // Class const int typeId = _parser->findOrCreateTypeId(objectType); Object *obj = new Object; obj->type = typeId; _scope.append(objectType); obj->typeName = qualifiedNameId().toLatin1(); _scope.removeLast(); obj->line = line; if (!str.isEmpty()) { Property *prop = currentProperty(); Value *v = new Value; v->object = obj; v->line = line; prop->addValue(v); } for(int ii = str.count() - 1; ii >= 0; --ii) _stateStack.pop(); if (! _parser->tree()) { _parser->setTree(obj); _stateStack.pushObject(obj); } else { const State state = _stateStack.top(); Value *v = new Value; v->object = obj; v->line = line; if(state.property) state.property->addValue(v); else state.object->getDefaultProperty()->addValue(v); _stateStack.pushObject(obj); } accept(initializer); _stateStack.pop(); return obj; } // UiObjectMember: T_PUBLIC T_IDENTIFIER T_IDENTIFIER T_COLON Expression UiObjectInitializer ; bool ProcessAST::visit(AST::UiPublicMember *node) { const QString type = node->type->asString(); const QString name = node->name->asString(); if (type == QLatin1String("property")) { _stateStack.pushProperty(QLatin1String("properties"), node->publicToken.startLine); Object *obj = defineObjectBinding(node->identifierToken.startLine, QString(), QLatin1String("Property")); _stateStack.pushObject(obj); _stateStack.pushProperty(QLatin1String("name"), node->identifierToken.startLine); Value *value = new Value; value->primitive = name; value->line = node->identifierToken.startLine; currentProperty()->addValue(value); _stateStack.pop(); // name property if (node->expression) { // default value _stateStack.pushProperty(QLatin1String("value"), node->identifierToken.startLine); Value *value = new Value; value->primitive = getPrimitive("value", node->expression); value->line = node->identifierToken.startLine; currentProperty()->addValue(value); _stateStack.pop(); // value property } _stateStack.pop(); // object _stateStack.pop(); // properties } else { qWarning() << "bad public identifier" << type; // ### FIXME } return false; } // UiObjectMember: T_IDENTIFIER UiObjectInitializer ; bool ProcessAST::visit(AST::UiObjectDefinition *node) { defineObjectBinding(node->identifierToken.startLine, QString(), node->name->asString(), node->initializer); return false; } // UiObjectMember: UiQualifiedId T_COLON T_IDENTIFIER UiObjectInitializer ; bool ProcessAST::visit(AST::UiObjectBinding *node) { defineObjectBinding(node->identifierToken.startLine, asString(node->qualifiedId), node->name->asString(), node->initializer); return false; } QString ProcessAST::getPrimitive(const QByteArray &propertyName, AST::ExpressionNode *expr) { QString primitive; QTextStream out(&primitive); PrettyPretty pp(out); if(propertyName.length() >= 3 && propertyName.startsWith("on") && ('A' <= propertyName.at(2) && 'Z' >= propertyName.at(2))) { pp(expr); // here comes a cruel hack until we support functions properly with arguments for signal properties if (primitive.startsWith(QLatin1String("function("))) { int brace = 0; for (;brace < primitive.size(); ++brace) if (primitive.at(brace) == QLatin1Char('{')) break; primitive = primitive.mid(brace + 1, primitive.size() - brace - 2); } //end of hack } else if (propertyName == "id" && expr && expr->kind == AST::Node::Kind_IdentifierExpression) { primitive = static_cast<AST::IdentifierExpression *>(expr)->name->asString(); } else if (expr->kind == AST::Node::Kind_StringLiteral) { // hack: emulate weird XML feature that string literals are not quoted. //This needs to be fixed in the qmlcompiler once xml goes away. primitive = static_cast<AST::StringLiteral *>(expr)->value->asString(); } else if (expr->kind == AST::Node::Kind_TrueLiteral || expr->kind == AST::Node::Kind_FalseLiteral || expr->kind == AST::Node::Kind_NumericLiteral ) { pp(expr); } else { // create a binding out << "{"; pp(expr); out << "}"; } return primitive; } // UiObjectMember: UiQualifiedId T_COLON Statement ; bool ProcessAST::visit(AST::UiScriptBinding *node) { const QString qualifiedId = asString(node->qualifiedId); const QStringList str = qualifiedId.split(QLatin1Char('.')); int line = node->colonToken.startLine; for(int ii = 0; ii < str.count(); ++ii) { const QString s = str.at(ii); _stateStack.pushProperty(s, line); } QString primitive; QTextStream out(&primitive); PrettyPretty pp(out); Property *prop = currentProperty(); if (node->statement->kind == AST::Node::Kind_ExpressionStatement) { AST::ExpressionStatement *stmt = static_cast<AST::ExpressionStatement *>(node->statement); primitive = getPrimitive(prop->name, stmt->expression); } else { pp(node->statement); } Value *v = new Value; v->primitive = primitive; v->line = line; prop->addValue(v); for(int ii = str.count() - 1; ii >= 0; --ii) _stateStack.pop(); return true; } // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiObjectMemberList T_RBRACKET ; bool ProcessAST::visit(AST::UiArrayBinding *node) { qWarning() << Q_FUNC_INFO << "not implemented"; return false; } } // end of anonymous namespace QmlScriptParser::QmlScriptParser() : root(0) { } QmlScriptParser::~QmlScriptParser() { } bool QmlScriptParser::parse(const QByteArray &data, const QUrl &url) { const QString fileName = url.toString(); const QString code = QString::fromUtf8(data); // ### FIXME JavaScriptParser parser; JavaScriptEnginePrivate driver; NodePool nodePool(fileName, &driver); driver.setNodePool(&nodePool); Lexer lexer(&driver); lexer.setCode(code, /*line = */ 1); driver.setLexer(&lexer); if (! parser.parse(&driver)) { _error = parser.errorMessage(); return false; } ProcessAST process(this); process(parser.ast()); return true; } QString QmlScriptParser::errorDescription() const { return _error; } QMap<QString,QString> QmlScriptParser::nameSpacePaths() const { qWarning() << Q_FUNC_INFO << "not implemented"; return _nameSpacePaths; } QStringList QmlScriptParser::types() const { return _typeNames; } Object *QmlScriptParser::tree() const { return root; } int QmlScriptParser::findOrCreateTypeId(const QString &name) { int index = _typeNames.indexOf(name); if (index == -1) { index = _typeNames.size(); _typeNames.append(name); } return index; } void QmlScriptParser::setTree(Object *tree) { Q_ASSERT(! root); root = tree; } QT_END_NAMESPACE <commit_msg>make arrays work, these visitors are ***** awesome<commit_after> #include "qmlscriptparser_p.h" #include "parser/javascriptengine_p.h" #include "parser/javascriptparser_p.h" #include "parser/javascriptlexer_p.h" #include "parser/javascriptnodepool_p.h" #include "parser/javascriptastvisitor_p.h" #include "parser/javascriptast_p.h" #include "parser/javascriptprettypretty_p.h" #include <QStack> #include <QtDebug> QT_BEGIN_NAMESPACE using namespace JavaScript; using namespace QmlParser; namespace { class ProcessAST: protected AST::Visitor { struct State { State() : object(0), property(0) {} State(Object *o) : object(o), property(0) {} State(Object *o, Property *p) : object(o), property(p) {} Object *object; Property *property; }; struct StateStack : public QStack<State> { void pushObject(Object *obj) { push(State(obj)); } void pushProperty(const QString &name, int lineNumber) { const State &state = top(); if (state.property) { State s(state.property->getValue(), state.property->getValue()->getProperty(name.toLatin1())); s.property->line = lineNumber; push(s); } else { State s(state.object, state.object->getProperty(name.toLatin1())); s.property->line = lineNumber; push(s); } } }; public: ProcessAST(QmlScriptParser *parser); virtual ~ProcessAST(); void operator()(AST::Node *node); protected: Object *defineObjectBinding(int line, const QString &propertyName, const QString &objectType, AST::UiObjectInitializer *initializer = 0); QString getPrimitive(const QByteArray &propertyName, AST::ExpressionNode *expr); using AST::Visitor::visit; using AST::Visitor::endVisit; virtual bool visit(AST::UiObjectDefinition *node); virtual bool visit(AST::UiPublicMember *node); virtual bool visit(AST::UiObjectBinding *node); virtual bool visit(AST::UiScriptBinding *node); virtual bool visit(AST::UiArrayBinding *node); void accept(AST::Node *node); QString asString(AST::UiQualifiedId *node) const; const State state() const; Object *currentObject() const; Property *currentProperty() const; QString qualifiedNameId() const; private: QmlScriptParser *_parser; StateStack _stateStack; QStringList _scope; }; ProcessAST::ProcessAST(QmlScriptParser *parser) : _parser(parser) { } ProcessAST::~ProcessAST() { } void ProcessAST::operator()(AST::Node *node) { accept(node); } void ProcessAST::accept(AST::Node *node) { AST::Node::acceptChild(node, this); } const ProcessAST::State ProcessAST::state() const { if (_stateStack.isEmpty()) return State(); return _stateStack.back(); } Object *ProcessAST::currentObject() const { return state().object; } Property *ProcessAST::currentProperty() const { return state().property; } QString ProcessAST::qualifiedNameId() const { return _scope.join(QLatin1String("/")); } QString ProcessAST::asString(AST::UiQualifiedId *node) const { QString s; for (AST::UiQualifiedId *it = node; it; it = it->next) { s.append(it->name->asString()); if (it->next) s.append(QLatin1Char('.')); } return s; } Object *ProcessAST::defineObjectBinding(int line, const QString &propertyName, const QString &objectType, AST::UiObjectInitializer *initializer) { bool isType = !objectType.isEmpty() && objectType.at(0).isUpper() && !objectType.contains(QLatin1Char('.')); if (!isType) { qWarning() << "bad name for a class"; // ### FIXME return false; } const QStringList str = propertyName.split(QLatin1Char('.'), QString::SkipEmptyParts); for(int ii = 0; ii < str.count(); ++ii) { const QString s = str.at(ii); _stateStack.pushProperty(s, line); } // Class const int typeId = _parser->findOrCreateTypeId(objectType); Object *obj = new Object; obj->type = typeId; _scope.append(objectType); obj->typeName = qualifiedNameId().toLatin1(); _scope.removeLast(); obj->line = line; if (!str.isEmpty()) { Property *prop = currentProperty(); Value *v = new Value; v->object = obj; v->line = line; prop->addValue(v); } for(int ii = str.count() - 1; ii >= 0; --ii) _stateStack.pop(); if (! _parser->tree()) { _parser->setTree(obj); _stateStack.pushObject(obj); } else { const State state = _stateStack.top(); Value *v = new Value; v->object = obj; v->line = line; if(state.property) state.property->addValue(v); else state.object->getDefaultProperty()->addValue(v); _stateStack.pushObject(obj); } accept(initializer); _stateStack.pop(); return obj; } // UiObjectMember: T_PUBLIC T_IDENTIFIER T_IDENTIFIER T_COLON Expression UiObjectInitializer ; bool ProcessAST::visit(AST::UiPublicMember *node) { const QString type = node->type->asString(); const QString name = node->name->asString(); if (type == QLatin1String("property")) { _stateStack.pushProperty(QLatin1String("properties"), node->publicToken.startLine); Object *obj = defineObjectBinding(node->identifierToken.startLine, QString(), QLatin1String("Property")); _stateStack.pushObject(obj); _stateStack.pushProperty(QLatin1String("name"), node->identifierToken.startLine); Value *value = new Value; value->primitive = name; value->line = node->identifierToken.startLine; currentProperty()->addValue(value); _stateStack.pop(); // name property if (node->expression) { // default value _stateStack.pushProperty(QLatin1String("value"), node->identifierToken.startLine); Value *value = new Value; value->primitive = getPrimitive("value", node->expression); value->line = node->identifierToken.startLine; currentProperty()->addValue(value); _stateStack.pop(); // value property } _stateStack.pop(); // object _stateStack.pop(); // properties } else { qWarning() << "bad public identifier" << type; // ### FIXME } // ### TODO drop initializer (unless some example needs differnet properties than name and type and value. return false; } // UiObjectMember: T_IDENTIFIER UiObjectInitializer ; bool ProcessAST::visit(AST::UiObjectDefinition *node) { defineObjectBinding(node->identifierToken.startLine, QString(), node->name->asString(), node->initializer); return false; } // UiObjectMember: UiQualifiedId T_COLON T_IDENTIFIER UiObjectInitializer ; bool ProcessAST::visit(AST::UiObjectBinding *node) { defineObjectBinding(node->identifierToken.startLine, asString(node->qualifiedId), node->name->asString(), node->initializer); return false; } QString ProcessAST::getPrimitive(const QByteArray &propertyName, AST::ExpressionNode *expr) { QString primitive; QTextStream out(&primitive); PrettyPretty pp(out); if(propertyName.length() >= 3 && propertyName.startsWith("on") && ('A' <= propertyName.at(2) && 'Z' >= propertyName.at(2))) { pp(expr); // here comes a cruel hack until we support functions properly with arguments for signal properties if (primitive.startsWith(QLatin1String("function("))) { int brace = 0; for (;brace < primitive.size(); ++brace) if (primitive.at(brace) == QLatin1Char('{')) break; primitive = primitive.mid(brace + 1, primitive.size() - brace - 2); } //end of hack } else if (propertyName == "id" && expr && expr->kind == AST::Node::Kind_IdentifierExpression) { primitive = static_cast<AST::IdentifierExpression *>(expr)->name->asString(); } else if (expr->kind == AST::Node::Kind_StringLiteral) { // hack: emulate weird XML feature that string literals are not quoted. //This needs to be fixed in the qmlcompiler once xml goes away. primitive = static_cast<AST::StringLiteral *>(expr)->value->asString(); } else if (expr->kind == AST::Node::Kind_TrueLiteral || expr->kind == AST::Node::Kind_FalseLiteral || expr->kind == AST::Node::Kind_NumericLiteral ) { pp(expr); } else { // create a binding out << "{"; pp(expr); out << "}"; } return primitive; } // UiObjectMember: UiQualifiedId T_COLON Statement ; bool ProcessAST::visit(AST::UiScriptBinding *node) { const QString qualifiedId = asString(node->qualifiedId); const QStringList str = qualifiedId.split(QLatin1Char('.')); int line = node->colonToken.startLine; for(int ii = 0; ii < str.count(); ++ii) { const QString s = str.at(ii); _stateStack.pushProperty(s, line); } QString primitive; QTextStream out(&primitive); PrettyPretty pp(out); Property *prop = currentProperty(); if (node->statement->kind == AST::Node::Kind_ExpressionStatement) { AST::ExpressionStatement *stmt = static_cast<AST::ExpressionStatement *>(node->statement); primitive = getPrimitive(prop->name, stmt->expression); } else { pp(node->statement); } Value *v = new Value; v->primitive = primitive; v->line = line; prop->addValue(v); for(int ii = str.count() - 1; ii >= 0; --ii) _stateStack.pop(); return true; } // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiObjectMemberList T_RBRACKET ; bool ProcessAST::visit(AST::UiArrayBinding *node) { QString propertyName = asString(node->qualifiedId); const QStringList str = propertyName.split(QLatin1Char('.'), QString::SkipEmptyParts); for(int ii = 0; ii < str.count(); ++ii) { const QString s = str.at(ii); _stateStack.pushProperty(s, node->colonToken.startLine); } accept(node->members); for(int ii = str.count() - 1; ii >= 0; --ii) _stateStack.pop(); return false; } } // end of anonymous namespace QmlScriptParser::QmlScriptParser() : root(0) { } QmlScriptParser::~QmlScriptParser() { } bool QmlScriptParser::parse(const QByteArray &data, const QUrl &url) { const QString fileName = url.toString(); const QString code = QString::fromUtf8(data); // ### FIXME JavaScriptParser parser; JavaScriptEnginePrivate driver; NodePool nodePool(fileName, &driver); driver.setNodePool(&nodePool); Lexer lexer(&driver); lexer.setCode(code, /*line = */ 1); driver.setLexer(&lexer); if (! parser.parse(&driver)) { _error = parser.errorMessage(); return false; } ProcessAST process(this); process(parser.ast()); return true; } QString QmlScriptParser::errorDescription() const { return _error; } QMap<QString,QString> QmlScriptParser::nameSpacePaths() const { qWarning() << Q_FUNC_INFO << "not implemented"; return _nameSpacePaths; } QStringList QmlScriptParser::types() const { return _typeNames; } Object *QmlScriptParser::tree() const { return root; } int QmlScriptParser::findOrCreateTypeId(const QString &name) { int index = _typeNames.indexOf(name); if (index == -1) { index = _typeNames.size(); _typeNames.append(name); } return index; } void QmlScriptParser::setTree(Object *tree) { Q_ASSERT(! root); root = tree; } QT_END_NAMESPACE <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, 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 "boost/format.hpp" #include <iostream> #include "maya/MArgList.h" #include "maya/MGlobal.h" #include "maya/MSyntax.h" #include "maya/MArgDatabase.h" #include "IECoreMaya/PythonCmd.h" static const char *kCommandFlag = "-cmd"; static const char *kCommandFlagLong = "-command"; static const char *kFileFlag = "-f"; static const char *kFileFlagLong = "-file"; static const char *kEvalFlag = "-e"; static const char *kEvalFlagLong = "-eval"; static const char *kContextFlag = "-ctx"; static const char *kContextFlagLong = "-context"; static const char *kCreateContextFlag = "-cc"; static const char *kCreateContextFlagLong = "-createContext"; static const char *kDeleteContextFlag = "-dc"; static const char *kDeleteContextFlagLong = "-deleteContext"; using namespace IECoreMaya; using namespace boost::python; using namespace boost; using namespace std; object PythonCmd::g_globalContext; bool PythonCmd::g_initialized; PythonCmd::ContextMap PythonCmd::g_contextMap; namespace { PyMethodDef initial_methods[] = { { 0, 0, 0, 0 } }; } void PythonCmd::import( const std::string &moduleName ) { try { string toExecute = boost::str( format( "import %1%\n" ) % moduleName ); handle<> ignored( PyRun_String( toExecute.c_str(), Py_file_input, g_globalContext.ptr(), g_globalContext.ptr() ) ); } catch ( error_already_set & ) { PyErr_Print(); } } void PythonCmd::initialize() { if (!g_initialized) { /// Maya (8.5 onwards) may have already initialized Maya for us if (!Py_IsInitialized()) { Py_Initialize(); } assert( Py_IsInitialized() ); /// We need a valid current state to be able to execute Python. It seems /// that Maya 8.5 can leave us without one set, in which case we have /// to go and find one. PyThreadState *currentState = PyThreadState_GET(); if (!currentState) { PyInterpreterState *interp = PyInterpreterState_Head(); currentState = PyInterpreterState_ThreadHead( interp ); } assert( currentState ); /// Bring the current state into effect PyThreadState_Swap(currentState); /// Initialize the __main__ module if not already present PyObject* sysModules = PyImport_GetModuleDict(); assert(sysModules); object mainModule(borrowed(PyDict_GetItemString(sysModules, "__main__"))); if (!mainModule) { mainModule = object(borrowed(Py_InitModule("__main__", initial_methods))); } assert( mainModule ); /// Retrieve the global context from the __main__ module g_globalContext = mainModule.attr("__dict__"); assert( g_globalContext ); // Suppress warnings about mismatched API versions. We build IE modules // against python2.5 for use elsewhere, but then use them in maya with python 2.4. // Testing suggests that there are no ill effects of the mismatch. To be on the safe side // we only suppress for IE prefixed modules and only for the specific API versions with // which we've tested. // \todo It would be a jolly good idea to stop doing this. try { handle<> ignored( PyRun_String( "import warnings\n" "warnings.filterwarnings( 'ignore', 'Python C API version mismatch for module _IE.*: This Python has API version 1012, module _IE.* has version 1013.', RuntimeWarning, '.*', 0 )", Py_file_input, g_globalContext.ptr(), g_globalContext.ptr() ) ); } catch( error_already_set & ) { PyErr_Print(); } import( "IECore" ); import( "IECoreMaya" ); import( "IECoreGL" ); g_initialized = true; } } void PythonCmd::uninitialize() { if (g_initialized) { #if MAYA_API_VERSION < 850 Py_Finalize(); #endif g_contextMap.clear(); } g_initialized = false; } boost::python::object &PythonCmd::globalContext() { return g_globalContext; } PythonCmd::PythonCmd() { assert( g_initialized ); } PythonCmd::~PythonCmd() { } void *PythonCmd::creator() { return new PythonCmd; } MSyntax PythonCmd::newSyntax() { MSyntax syn; MStatus s; s = syn.addFlag( kCommandFlag, kCommandFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kFileFlag, kFileFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kEvalFlag, kEvalFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kContextFlag, kContextFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kCreateContextFlag, kCreateContextFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kDeleteContextFlag, kDeleteContextFlagLong, MSyntax::kString ); assert(s); return syn; } MStatus PythonCmd::doIt( const MArgList &argList ) { MStatus s; MArgDatabase args( syntax(), argList ); if (args.isFlagSet( kCommandFlag ) && args.isFlagSet( kFileFlag ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong)); return MS::kFailure; } list argv; PySys_SetObject("argv", argv.ptr()); object *context = &g_globalContext; assert(context); if (args.isFlagSet( kContextFlagLong ) ) { if (args.isFlagSet( kCreateContextFlagLong ) || args.isFlagSet( kDeleteContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } if (!args.isFlagSet( kCommandFlagLong ) && !args.isFlagSet( kFileFlagLong ) ) { displayError("Must specify one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) ); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it == g_contextMap.end()) { displayError("Context does not exist"); return MS::kFailure; } context = &(it->second); assert( context != &g_globalContext ); } if (args.isFlagSet( kCreateContextFlag ) || args.isFlagSet( kCreateContextFlagLong )) { if (args.isFlagSet( kContextFlagLong ) || args.isFlagSet( kDeleteContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kCreateContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it != g_contextMap.end()) { displayWarning("Context already exists"); context = &(it->second); } else { g_contextMap[ contextName.asChar() ] = dict(); context = &(g_contextMap[ contextName.asChar() ]); } assert( context != &g_globalContext ); return MS::kSuccess; } if (args.isFlagSet( kDeleteContextFlagLong ) ) { if (args.isFlagSet( kContextFlagLong ) || args.isFlagSet( kCreateContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kFileFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kDeleteContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it == g_contextMap.end()) { displayWarning("Context does not exist"); } else { g_contextMap.erase( it ); } return MS::kSuccess; } assert(context); if (args.isFlagSet( kCommandFlagLong ) ) { if (args.isFlagSet( kFileFlagLong ) || args.isFlagSet( kEvalFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong)); return MS::kFailure; } MString cmd; s = args.getFlagArgument( kCommandFlagLong, 0, cmd ); argv.append( "<string>" ); try { handle<> ignored(( PyRun_String( cmd.asChar(), Py_file_input, context->ptr(), context->ptr() ) )); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError("Caught unexpected exception"); return MS::kFailure; } } else if (args.isFlagSet( kFileFlagLong ) ) { if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kEvalFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong) ); return MS::kFailure; } MString filename; s = args.getFlagArgument( kFileFlagLong, 0, filename ); assert(s); argv.append( filename.asChar() ); // causes python to print out the filename appropriately in a stack trace FILE *fp = fopen( filename.asChar(), "r" ); if (!fp) { displayError( MString("Cannot open file ") + filename ); return MS::kFailure; } try { handle<> ignored(( PyRun_FileEx( fp, filename.asChar(), Py_file_input, context->ptr(), context->ptr(), 1 ) )); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError("Caught unexpected exception"); return MS::kFailure; } } else if (args.isFlagSet( kEvalFlagLong ) ) { if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kFileFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong) ); return MS::kFailure; } MString cmd; s = args.getFlagArgument( kEvalFlagLong, 0, cmd ); assert(s); argv.append( cmd.asChar() ); try { handle<> resultHandle( ( PyRun_String( cmd.asChar(), Py_eval_input, context->ptr(), context->ptr() ) ) ); object result( resultHandle ); string strResult = extract<string>( boost::python::str( result ) )(); setResult( strResult.c_str() ); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError( "Caught unexpected exception" ); return MS::kFailure; } } return MS::kFailure; } <commit_msg>Improved GIL handling using new ScopedGILLock classes. Removed very iffy warning suppression which dates back to whichever maya version used python 2.4.<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 "boost/format.hpp" #include <iostream> #include "maya/MArgList.h" #include "maya/MGlobal.h" #include "maya/MSyntax.h" #include "maya/MArgDatabase.h" #include "IECorePython/ScopedGILLock.h" #include "IECoreMaya/PythonCmd.h" static const char *kCommandFlag = "-cmd"; static const char *kCommandFlagLong = "-command"; static const char *kFileFlag = "-f"; static const char *kFileFlagLong = "-file"; static const char *kEvalFlag = "-e"; static const char *kEvalFlagLong = "-eval"; static const char *kContextFlag = "-ctx"; static const char *kContextFlagLong = "-context"; static const char *kCreateContextFlag = "-cc"; static const char *kCreateContextFlagLong = "-createContext"; static const char *kDeleteContextFlag = "-dc"; static const char *kDeleteContextFlagLong = "-deleteContext"; using namespace IECoreMaya; using namespace boost::python; using namespace boost; using namespace std; object PythonCmd::g_globalContext; bool PythonCmd::g_initialized; PythonCmd::ContextMap PythonCmd::g_contextMap; namespace { PyMethodDef initial_methods[] = { { 0, 0, 0, 0 } }; } void PythonCmd::import( const std::string &moduleName ) { IECorePython::ScopedGILLock lock; try { string toExecute = boost::str( format( "import %1%\n" ) % moduleName ); handle<> ignored( PyRun_String( toExecute.c_str(), Py_file_input, g_globalContext.ptr(), g_globalContext.ptr() ) ); } catch ( error_already_set & ) { PyErr_Print(); } } void PythonCmd::initialize() { if (!g_initialized) { /// Maya (8.5 onwards) may have already initialized Maya for us if (!Py_IsInitialized()) { Py_Initialize(); } assert( Py_IsInitialized() ); IECorePython::ScopedGILLock lock; /// Initialize the __main__ module if not already present PyObject* sysModules = PyImport_GetModuleDict(); assert(sysModules); object mainModule(borrowed(PyDict_GetItemString(sysModules, "__main__"))); if (!mainModule) { mainModule = object(borrowed(Py_InitModule("__main__", initial_methods))); } assert( mainModule ); /// Retrieve the global context from the __main__ module g_globalContext = mainModule.attr("__dict__"); assert( g_globalContext ); import( "IECore" ); import( "IECoreMaya" ); import( "IECoreGL" ); g_initialized = true; } } void PythonCmd::uninitialize() { if (g_initialized) { #if MAYA_API_VERSION < 850 Py_Finalize(); #endif g_contextMap.clear(); } g_initialized = false; } boost::python::object &PythonCmd::globalContext() { return g_globalContext; } PythonCmd::PythonCmd() { assert( g_initialized ); } PythonCmd::~PythonCmd() { } void *PythonCmd::creator() { return new PythonCmd; } MSyntax PythonCmd::newSyntax() { MSyntax syn; MStatus s; s = syn.addFlag( kCommandFlag, kCommandFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kFileFlag, kFileFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kEvalFlag, kEvalFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kContextFlag, kContextFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kCreateContextFlag, kCreateContextFlagLong, MSyntax::kString ); assert(s); s = syn.addFlag( kDeleteContextFlag, kDeleteContextFlagLong, MSyntax::kString ); assert(s); return syn; } MStatus PythonCmd::doIt( const MArgList &argList ) { MStatus s; MArgDatabase args( syntax(), argList ); if (args.isFlagSet( kCommandFlag ) && args.isFlagSet( kFileFlag ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong)); return MS::kFailure; } IECorePython::ScopedGILLock gilLock; list argv; PySys_SetObject("argv", argv.ptr()); object *context = &g_globalContext; assert(context); if (args.isFlagSet( kContextFlagLong ) ) { if (args.isFlagSet( kCreateContextFlagLong ) || args.isFlagSet( kDeleteContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } if (!args.isFlagSet( kCommandFlagLong ) && !args.isFlagSet( kFileFlagLong ) ) { displayError("Must specify one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) ); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it == g_contextMap.end()) { displayError("Context does not exist"); return MS::kFailure; } context = &(it->second); assert( context != &g_globalContext ); } if (args.isFlagSet( kCreateContextFlag ) || args.isFlagSet( kCreateContextFlagLong )) { if (args.isFlagSet( kContextFlagLong ) || args.isFlagSet( kDeleteContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kCreateContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it != g_contextMap.end()) { displayWarning("Context already exists"); context = &(it->second); } else { g_contextMap[ contextName.asChar() ] = dict(); context = &(g_contextMap[ contextName.asChar() ]); } assert( context != &g_globalContext ); return MS::kSuccess; } if (args.isFlagSet( kDeleteContextFlagLong ) ) { if (args.isFlagSet( kContextFlagLong ) || args.isFlagSet( kCreateContextFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kFileFlagLong ) ) { displayError("Syntax error"); return MS::kFailure; } MString contextName; s = args.getFlagArgument( kDeleteContextFlagLong, 0, contextName ); assert(s); ContextMap::iterator it = g_contextMap.find( contextName.asChar() ); if (it == g_contextMap.end()) { displayWarning("Context does not exist"); } else { g_contextMap.erase( it ); } return MS::kSuccess; } assert(context); if (args.isFlagSet( kCommandFlagLong ) ) { if (args.isFlagSet( kFileFlagLong ) || args.isFlagSet( kEvalFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong)); return MS::kFailure; } MString cmd; s = args.getFlagArgument( kCommandFlagLong, 0, cmd ); argv.append( "<string>" ); try { handle<> ignored(( PyRun_String( cmd.asChar(), Py_file_input, context->ptr(), context->ptr() ) )); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError("Caught unexpected exception"); return MS::kFailure; } } else if (args.isFlagSet( kFileFlagLong ) ) { if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kEvalFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong) ); return MS::kFailure; } MString filename; s = args.getFlagArgument( kFileFlagLong, 0, filename ); assert(s); argv.append( filename.asChar() ); // causes python to print out the filename appropriately in a stack trace FILE *fp = fopen( filename.asChar(), "r" ); if (!fp) { displayError( MString("Cannot open file ") + filename ); return MS::kFailure; } try { handle<> ignored(( PyRun_FileEx( fp, filename.asChar(), Py_file_input, context->ptr(), context->ptr(), 1 ) )); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError("Caught unexpected exception"); return MS::kFailure; } } else if (args.isFlagSet( kEvalFlagLong ) ) { if (args.isFlagSet( kCommandFlagLong ) || args.isFlagSet( kFileFlagLong ) ) { displayError("Must specify only one of " + MString(kCommandFlagLong) + "/" + MString(kFileFlagLong) + "/" + MString(kEvalFlagLong) ); return MS::kFailure; } MString cmd; s = args.getFlagArgument( kEvalFlagLong, 0, cmd ); assert(s); argv.append( cmd.asChar() ); try { handle<> resultHandle( ( PyRun_String( cmd.asChar(), Py_eval_input, context->ptr(), context->ptr() ) ) ); object result( resultHandle ); string strResult = extract<string>( boost::python::str( result ) )(); setResult( strResult.c_str() ); return MS::kSuccess; } catch(error_already_set) { PyErr_Print(); return MS::kFailure; } catch(...) { displayError( "Caught unexpected exception" ); return MS::kFailure; } } return MS::kFailure; } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "flexisip-exception.hh" #include <execinfo.h> #include <unistd.h> static void uncaught_handler () { std::exception_ptr p= current_exception(); try { rethrow_exception(p); } catch (FlexisipException& e) { SLOGE << e ; } catch (std::exception& ee ) { SLOGE << "Unexpected exception ["<< ee.what() << " ] use FlexisipException for better debug"; } abort(); } FlexisipException e; FlexisipException::FlexisipException(const char* message): mOffset(1), mSize(0){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); if (message) mOs << message; #if __clang if (get_terminate() != uncaught_handler) #endif set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } FlexisipException::FlexisipException(const FlexisipException& other ) : mOffset(other.mOffset), mSize(other.mSize) { memcpy(mArray,other.mArray,sizeof(mArray)); mOs << other.str(); } #if __cplusplus > 199711L FlexisipException::FlexisipException(const string& msg): FlexisipException(msg.c_str()){ mOffset++; } #else FlexisipException::FlexisipException(const string& message): mOffset(1){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); *this << message; set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } #endif FlexisipException::~FlexisipException() throw (){ //nop } #if __cplusplus > 199711L FlexisipException::FlexisipException(): FlexisipException(""){ mOffset++; } #else FlexisipException::FlexisipException(): mOffset(1){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); *this << ""; set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } #endif void FlexisipException::printStackTrace() const { backtrace_symbols_fd(mArray+mOffset, mSize-mOffset, STDERR_FILENO); } void FlexisipException::printStackTrace(std::ostream & os) const { char** bt = backtrace_symbols(mArray,mSize); for (unsigned int i = mOffset; i < mSize; ++i) { os << bt[i] <<endl; } delete (bt); } const std::string &FlexisipException::str() const { mMessage = mOs.str(); //avoid returning a reference to temporary return mMessage; } const char* FlexisipException::what() const throw () { return str().c_str(); } //Class Flexisip std::ostream& operator<<(std::ostream& __os,const FlexisipException& e) { __os << e.str() << std::endl; e.printStackTrace(__os); return __os; } <commit_msg>Fix exception definition when c++ is too old<commit_after> /* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "flexisip-exception.hh" #include <execinfo.h> #include <unistd.h> static void uncaught_handler () { std::exception_ptr p= current_exception(); try { rethrow_exception(p); } catch (FlexisipException& e) { SLOGE << e ; } catch (std::exception& ee ) { SLOGE << "Unexpected exception ["<< ee.what() << " ] use FlexisipException for better debug"; } abort(); } FlexisipException e; FlexisipException::FlexisipException(const char* message): mOffset(1), mSize(0){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); if (message) mOs << message; #if __clang if (get_terminate() != uncaught_handler) #endif set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } FlexisipException::FlexisipException(const FlexisipException& other ) : mOffset(other.mOffset), mSize(other.mSize) { memcpy(mArray,other.mArray,sizeof(mArray)); mOs << other.str(); } #if __cplusplus > 199711L FlexisipException::FlexisipException(const string& msg): FlexisipException(msg.c_str()){ mOffset++; } #else FlexisipException::FlexisipException(const string& message): mOffset(1){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); *this << message; set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } #endif FlexisipException::~FlexisipException() throw (){ //nop } #if __cplusplus > 199711L FlexisipException::FlexisipException(): FlexisipException(""){ mOffset++; } #else FlexisipException::FlexisipException(): mOffset(1){ mSize = backtrace(mArray, sizeof(mArray)/sizeof(void*)); *this << ""; set_terminate(uncaught_handler); //invoke in case of uncautch exception for this thread } #endif void FlexisipException::printStackTrace() const { backtrace_symbols_fd(mArray+mOffset, mSize-mOffset, STDERR_FILENO); } void FlexisipException::printStackTrace(std::ostream & os) const { char** bt = backtrace_symbols(mArray,mSize); for (unsigned int i = mOffset; i < mSize; ++i) { os << bt[i] <<endl; } delete (bt); } const std::string &FlexisipException::str() const { mMessage = mOs.str(); //avoid returning a reference to temporary return mMessage; } const char* FlexisipException::what() const throw () { return str().c_str(); } //Class Flexisip std::ostream& operator<<(std::ostream& __os,const FlexisipException& e) { __os << e.str() << std::endl; e.printStackTrace(__os); return __os; } <|endoftext|>
<commit_before>/* KOrganizer Alarm Daemon Client. This file is part of KOrganizer. Copyright (c) 2002,2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ //krazy:excludeall=kdebug because we use the korgac(check) debug area in here #include "koalarmclient.h" #include "korgacadaptor.h" #include "alarmdockwindow.h" #include "alarmdialog.h" #include <kcal/calendarresources.h> #include <kstandarddirs.h> #include <kdebug.h> #include <klocale.h> #include <kdatetime.h> #include <kapplication.h> #include <kwindowsystem.h> #include <kconfiggroup.h> #include <kglobal.h> #include <QPushButton> #include <QtDBus/QtDBus> KOAlarmClient::KOAlarmClient( QObject *parent ) : QObject( parent ), mDialog( 0 ) { new KOrgacAdaptor( this ); QDBusConnection::sessionBus().registerObject( "/ac", this ); kDebug(); mDocker = new AlarmDockWindow; mDocker->show(); connect( this, SIGNAL( reminderCount( int ) ), mDocker, SLOT( slotUpdate( int ) ) ); connect( mDocker, SIGNAL( quitSignal() ), SLOT( slotQuit() ) ); KConfig c( KStandardDirs::locate( "config", "korganizerrc" ) ); KConfigGroup cg( &c, "Time & Date" ); QString tz = cg.readEntry( "TimeZoneId" ); kDebug() << "TimeZone:" << tz; mCalendar = new CalendarResources( tz ); mCalendar->readConfig(); mCalendar->load(); connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) ); KConfigGroup alarmGroup( KGlobal::config(), "Alarms" ); int interval = alarmGroup.readEntry( "Interval", 60 ); kDebug() << "KOAlarmClient check interval:" << interval << "seconds."; mLastChecked = alarmGroup.readEntry( "CalendarsLastChecked", QDateTime() ); // load reminders that were active when quitting KConfigGroup genGroup( KGlobal::config(), "General" ); int numReminders = genGroup.readEntry( "Reminders", 0 ); for ( int i=1; i<=numReminders; ++i ) { QString group( QString( "Incidence-%1" ).arg( i ) ); KConfigGroup *incGroup = new KConfigGroup( KGlobal::config(), group ); QString uid = incGroup->readEntry( "UID" ); QDateTime dt = incGroup->readEntry( "RemindAt", QDateTime() ); if ( !uid.isEmpty() ) { createReminder( mCalendar->incidence( uid ), dt ); } delete incGroup; } if ( numReminders ) { genGroup.writeEntry( "Reminders", 0 ); genGroup.sync(); } checkAlarms(); mCheckTimer.start( 1000 * interval ); // interval in seconds } KOAlarmClient::~KOAlarmClient() { delete mCalendar; delete mDocker; delete mDialog; } void KOAlarmClient::checkAlarms() { KConfigGroup cfg( KGlobal::config(), "General" ); if ( !cfg.readEntry( "Enabled", true ) ) { return; } QDateTime from = mLastChecked.addSecs( 1 ); mLastChecked = QDateTime::currentDateTime(); kDebug(5891) << "Check:" << from.toString() << " -" << mLastChecked.toString(); QList<Alarm *>alarms = mCalendar->alarms( KDateTime( from, KDateTime::LocalZone ), KDateTime( mLastChecked, KDateTime::LocalZone ) ); QList<Alarm *>::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { kDebug(5891) << "REMINDER:" << (*it)->parent()->summary(); Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() ); createReminder( incidence, QDateTime::currentDateTime() ); } } void KOAlarmClient::createReminder( KCal::Incidence *incidence, const QDateTime &dt ) { if ( !incidence ) { return; } if ( !mDialog ) { mDialog = new AlarmDialog(); connect( mDialog, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(suspendAllSignal()), mDialog, SLOT(suspendAll()) ); connect( mDocker, SIGNAL(dismissAllSignal()), mDialog, SLOT(dismissAll()) ); connect( this, SIGNAL( saveAllSignal() ), mDialog, SLOT( slotSave() ) ); } mDialog->addIncidence( incidence, dt ); mDialog->wakeUp(); saveLastCheckTime(); } void KOAlarmClient::slotQuit() { emit saveAllSignal(); saveLastCheckTime(); quit(); } void KOAlarmClient::saveLastCheckTime() { KConfigGroup cg( KGlobal::config(), "Alarms" ); cg.writeEntry( "CalendarsLastChecked", mLastChecked ); KGlobal::config()->sync(); } void KOAlarmClient::quit() { kDebug(); kapp->quit(); } bool KOAlarmClient::commitData( QSessionManager & ) { emit saveAllSignal(); saveLastCheckTime(); return true; } void KOAlarmClient::forceAlarmCheck() { checkAlarms(); saveLastCheckTime(); } void KOAlarmClient::dumpDebug() { KConfigGroup cfg( KGlobal::config(), "Alarms" ); QDateTime lastChecked = cfg.readEntry( "CalendarsLastChecked", QDateTime() ); kDebug() << "Last Check:" << lastChecked; } QStringList KOAlarmClient::dumpAlarms() { KDateTime start = KDateTime( QDateTime::currentDateTime().date(), QTime( 0, 0 ), KDateTime::LocalZone ); KDateTime end = start.addDays( 1 ).addSecs( -1 ); QStringList lst; // Don't translate, this is for debugging purposes. lst << QString( "AlarmDeamon::dumpAlarms() from " ) + start.toString() + " to " + end.toString(); QList<Alarm *> alarms = mCalendar->alarms( start, end ); QList<Alarm *>::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *a = *it; lst << QString( " " ) + a->parent()->summary() + " (" + a->time().toString() + ')'; } return lst; } void KOAlarmClient::debugShowDialog() { // showAlarmDialog(); } #include "koalarmclient.moc" <commit_msg>New option: if [General]->ShowReminderDaemon is false, then do not show the korgac icon in the systray.<commit_after>/* KOrganizer Alarm Daemon Client. This file is part of KOrganizer. Copyright (c) 2002,2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ //krazy:excludeall=kdebug because we use the korgac(check) debug area in here #include "koalarmclient.h" #include "korgacadaptor.h" #include "alarmdockwindow.h" #include "alarmdialog.h" #include <kcal/calendarresources.h> #include <kstandarddirs.h> #include <kdebug.h> #include <klocale.h> #include <kdatetime.h> #include <kapplication.h> #include <kwindowsystem.h> #include <kconfiggroup.h> #include <kglobal.h> #include <QPushButton> #include <QtDBus/QtDBus> KOAlarmClient::KOAlarmClient( QObject *parent ) : QObject( parent ), mDialog( 0 ) { new KOrgacAdaptor( this ); QDBusConnection::sessionBus().registerObject( "/ac", this ); kDebug(); KConfig korgConfig( KStandardDirs::locate( "config", "korganizerrc" ) ); KConfigGroup generalGroup( &korgConfig, "General" ); bool showDock = generalGroup.readEntry( "ShowReminderDaemon", true ); mDocker = new AlarmDockWindow; if ( showDock ) { mDocker->show(); } connect( this, SIGNAL( reminderCount( int ) ), mDocker, SLOT( slotUpdate( int ) ) ); connect( mDocker, SIGNAL( quitSignal() ), SLOT( slotQuit() ) ); KConfigGroup timedateGroup( &korgConfig, "Time & Date" ); QString tz = timedateGroup.readEntry( "TimeZoneId" ); kDebug() << "TimeZone:" << tz; mCalendar = new CalendarResources( tz ); mCalendar->readConfig(); mCalendar->load(); connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) ); KConfigGroup alarmGroup( KGlobal::config(), "Alarms" ); int interval = alarmGroup.readEntry( "Interval", 60 ); kDebug() << "KOAlarmClient check interval:" << interval << "seconds."; mLastChecked = alarmGroup.readEntry( "CalendarsLastChecked", QDateTime() ); // load reminders that were active when quitting KConfigGroup genGroup( KGlobal::config(), "General" ); int numReminders = genGroup.readEntry( "Reminders", 0 ); for ( int i=1; i<=numReminders; ++i ) { QString group( QString( "Incidence-%1" ).arg( i ) ); KConfigGroup *incGroup = new KConfigGroup( KGlobal::config(), group ); QString uid = incGroup->readEntry( "UID" ); QDateTime dt = incGroup->readEntry( "RemindAt", QDateTime() ); if ( !uid.isEmpty() ) { createReminder( mCalendar->incidence( uid ), dt ); } delete incGroup; } if ( numReminders ) { genGroup.writeEntry( "Reminders", 0 ); genGroup.sync(); } checkAlarms(); mCheckTimer.start( 1000 * interval ); // interval in seconds } KOAlarmClient::~KOAlarmClient() { delete mCalendar; delete mDocker; delete mDialog; } void KOAlarmClient::checkAlarms() { KConfigGroup cfg( KGlobal::config(), "General" ); if ( !cfg.readEntry( "Enabled", true ) ) { return; } QDateTime from = mLastChecked.addSecs( 1 ); mLastChecked = QDateTime::currentDateTime(); kDebug(5891) << "Check:" << from.toString() << " -" << mLastChecked.toString(); QList<Alarm *>alarms = mCalendar->alarms( KDateTime( from, KDateTime::LocalZone ), KDateTime( mLastChecked, KDateTime::LocalZone ) ); QList<Alarm *>::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { kDebug(5891) << "REMINDER:" << (*it)->parent()->summary(); Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() ); createReminder( incidence, QDateTime::currentDateTime() ); } } void KOAlarmClient::createReminder( KCal::Incidence *incidence, const QDateTime &dt ) { if ( !incidence ) { return; } if ( !mDialog ) { mDialog = new AlarmDialog(); connect( mDialog, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(suspendAllSignal()), mDialog, SLOT(suspendAll()) ); connect( mDocker, SIGNAL(dismissAllSignal()), mDialog, SLOT(dismissAll()) ); connect( this, SIGNAL( saveAllSignal() ), mDialog, SLOT( slotSave() ) ); } mDialog->addIncidence( incidence, dt ); mDialog->wakeUp(); saveLastCheckTime(); } void KOAlarmClient::slotQuit() { emit saveAllSignal(); saveLastCheckTime(); quit(); } void KOAlarmClient::saveLastCheckTime() { KConfigGroup cg( KGlobal::config(), "Alarms" ); cg.writeEntry( "CalendarsLastChecked", mLastChecked ); KGlobal::config()->sync(); } void KOAlarmClient::quit() { kDebug(); kapp->quit(); } bool KOAlarmClient::commitData( QSessionManager & ) { emit saveAllSignal(); saveLastCheckTime(); return true; } void KOAlarmClient::forceAlarmCheck() { checkAlarms(); saveLastCheckTime(); } void KOAlarmClient::dumpDebug() { KConfigGroup cfg( KGlobal::config(), "Alarms" ); QDateTime lastChecked = cfg.readEntry( "CalendarsLastChecked", QDateTime() ); kDebug() << "Last Check:" << lastChecked; } QStringList KOAlarmClient::dumpAlarms() { KDateTime start = KDateTime( QDateTime::currentDateTime().date(), QTime( 0, 0 ), KDateTime::LocalZone ); KDateTime end = start.addDays( 1 ).addSecs( -1 ); QStringList lst; // Don't translate, this is for debugging purposes. lst << QString( "AlarmDeamon::dumpAlarms() from " ) + start.toString() + " to " + end.toString(); QList<Alarm *> alarms = mCalendar->alarms( start, end ); QList<Alarm *>::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *a = *it; lst << QString( " " ) + a->parent()->summary() + " (" + a->time().toString() + ')'; } return lst; } void KOAlarmClient::debugShowDialog() { // showAlarmDialog(); } #include "koalarmclient.moc" <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005,2006,2007 by Siraj Razick <siraj@kdemail.net> * * Copyright (C) 2007 by Riccardo Iaconelli <ruphy@fsfe.org> * * Copyright (C) 2007 by Matthias Kretz <kretz@kde.org> * * Copyright (C) 2008 by Richard Dale <richard.j.dale@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ #include <ruby.h> #include <QString> #include <QDir> #include <QFileInfo> #include <QWidget> #include <KStandardDirs> #include <klibloader.h> #include <kdebug.h> #include <kio/slavebase.h> #include <qtruby.h> extern "C" { extern VALUE rb_load_path; extern VALUE qt_internal_module; } // // This function was borrowed from the kross code. It puts out // an error message and stacktrace on stderr for the current exception. // static void show_exception_message() { VALUE info = rb_gv_get("$!"); VALUE bt = rb_funcall(info, rb_intern("backtrace"), 0); VALUE message = RARRAY_PTR(bt)[0]; QString errormessage = QString("%1: %2 (%3)") .arg( STR2CSTR(message) ) .arg( STR2CSTR(rb_obj_as_string(info)) ) .arg( rb_class2name(CLASS_OF(info)) ); fprintf(stderr, "%s\n", errormessage.toLatin1().constData()); QString tracemessage; for(int i = 1; i < RARRAY_LEN(bt); ++i) { if( TYPE(RARRAY_PTR(bt)[i]) == T_STRING ) { QString s = QString("%1\n").arg( STR2CSTR(RARRAY_PTR(bt)[i]) ); Q_ASSERT( ! s.isNull() ); tracemessage += s; fprintf(stderr, "\t%s", s.toLatin1().constData()); } } } static VALUE plugin_class = Qnil; static VALUE create_plugin_instance3(VALUE av) { VALUE pv = rb_ary_pop(av); VALUE pw = rb_ary_pop(av); return rb_funcall(plugin_class, rb_intern("new"), 3, pv, pw, av); } static VALUE create_plugin_instance2(VALUE av) { VALUE pv = rb_ary_pop(av); return rb_funcall(plugin_class, rb_intern("new"), 2, pv, av); } class KRubyPluginFactory : public KPluginFactory { public: KRubyPluginFactory(); protected: virtual QObject *create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString &keyword); public: static QByteArray camelize(QByteArray name); }; K_EXPORT_PLUGIN(KRubyPluginFactory) KRubyPluginFactory::KRubyPluginFactory() : KPluginFactory() // no useful KComponentData object for now { } QByteArray KRubyPluginFactory::camelize(QByteArray name) { // Convert foo_bar_baz to FooBarBaz QByteArray camelCaseName = name.left(1).toUpper(); for (int i = 1; i < name.size(); i++) { if (name[i] == '_' || name[i] == '-') { i++; if (i < name.size()) { camelCaseName += name.mid(i, 1).toUpper(); } } else { camelCaseName += name[i]; } } return camelCaseName; } QObject *KRubyPluginFactory::create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString &keyword) { Q_UNUSED(iface); Q_UNUSED(parentWidget); if (keyword.isEmpty()) { kWarning() << "\"keyword\" is empty. It's either missing in the .desktop file or the app doesn't pass it to the pluginfactory."; return 0; } QString path = KStandardDirs::locate("data", keyword); if (path.isEmpty()) { kWarning() << "Ruby script" << keyword << "missing"; return 0; } QFileInfo program(path); #ifdef RUBY_INIT_STACK RUBY_INIT_STACK #endif #if RUBY_VERSION < 0x10900 bool firstTime = (rb_load_path == 0); #else bool firstTime = true; #endif ruby_init(); ruby_script(QFile::encodeName(program.fileName())); // If ruby_init_loadpath() is called more than once, it keeps // adding the same standard directories to it. if (firstTime) { ruby_init_loadpath(); } ruby_incpush(QFile::encodeName(program.path())); int state = 0; const QByteArray encodedFilePath = QFile::encodeName(program.filePath()); rb_load_protect(rb_str_new2(encodedFilePath), 0, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to load" << encodedFilePath << keyword << path; return 0; } // A path of my_app/foo_bar.rb is turned into module/class 'MyApp::FooBar' const QByteArray moduleName = KRubyPluginFactory::camelize(QFile::encodeName(program.dir().dirName())); const QByteArray className = KRubyPluginFactory::camelize(program.baseName().toLatin1()); VALUE plugin_module = rb_const_get(rb_cObject, rb_intern(moduleName)); if (plugin_module == Qnil) { kWarning() << "no " << moduleName << " module found"; return 0; } plugin_class = rb_const_get(plugin_module, rb_intern(className)); if (plugin_class == Qnil) { kWarning() << "no " << moduleName << "::" << className << " class found"; return 0; } VALUE pw, po; #define MKPARENT(cvar, rvar)\ if(cvar == 0) \ rvar = Qnil; \ else \ { \ Smoke::ModuleIndex mi = smokeList[0]->findClass("QObject"); \ smokeruby_object *o = alloc_smokeruby_object(false, mi.smoke, mi.smoke->idClass("QObject").index, cvar); \ const char *class_name = resolve_classname(o); \ rvar = set_obj_info(class_name, o); \ } MKPARENT(parentWidget, pw) MKPARENT(parent, po) #undef MKPARENT // Assume the args list only contains strings, ints and booleans VALUE av = rb_ary_new(); for (int i = 0; i < args.size(); ++i) { if (args.at(i).type() == QVariant::String) { rb_ary_push(av, rb_str_new2(args.at(i).toByteArray())); } else if (args.at(i).type() == QVariant::Int) { rb_ary_push(av, INT2NUM(args.at(i).toInt())); } else if (args.at(i).type() == QVariant::Bool) { rb_ary_push(av, args.at(i).toBool() ? Qtrue : Qfalse); } } rb_ary_push(av, pw); rb_ary_push(av, po); VALUE plugin_value = rb_protect(create_plugin_instance3, av, &state); if (state != 0 || plugin_value == Qnil) { show_exception_message(); rb_ary_push(av, po); plugin_value = rb_protect(create_plugin_instance2, av, &state); if(state != 0 || plugin_value == Qnil) { show_exception_message(); kWarning() << "failed to create instance of plugin class"; return 0; } } // Set an instance variable '@componentData' that contains the plugin specific // component data. Smoke::ModuleIndex mi = Smoke::findClass("KComponentData"); smokeruby_object *comp_o = alloc_smokeruby_object(true, mi.smoke, mi.index, new KComponentData(moduleName, moduleName)); const char *class_name = resolve_classname(comp_o); VALUE rb_componentData = set_obj_info(class_name, comp_o); rb_iv_set(plugin_value, "@componentData", rb_componentData); // Set a global variable '$my_app_foo_bar + <numeric id>' to the value of the new // instance of MyApp::FooBar to prevent it being GC'd. Note that it would be // better to be able to come up with a way to discover all the plugin instances, // and call rb_gc_mark() on them, in the mark phase of GC. QByteArray variableBaseName("$"); variableBaseName += QFile::encodeName(program.dir().dirName()); variableBaseName += "_"; variableBaseName += program.baseName().toLatin1(); // Handle multiple instances of the same class, and look for an unused global // variable QByteArray variableName; VALUE variable = Qnil; int id = 0; do { id++; variableName = variableBaseName + QByteArray::number(id); variable = rb_gv_get(variableName); } while (variable != Qnil); rb_gv_set(variableName, plugin_value); smokeruby_object *o = 0; Data_Get_Struct(plugin_value, smokeruby_object, o); QObject * createdInstance = reinterpret_cast<QObject *>(o->ptr); if(createdInstance->parent() == 0) createdInstance->setParent(parent); return createdInstance; } VALUE slave_class = Qnil; static VALUE create_slave_instance(VALUE av) { VALUE a = rb_ary_pop(av); VALUE b = rb_ary_pop(av); VALUE c = rb_ary_pop(av); return rb_funcall(slave_class, rb_intern("new"), 3, c, b, a); } extern "C" { Q_DECL_EXPORT int kdemain(int argc, char **argv) { if (argc != 4) { printf("USAGE: krubypluginfactory protocol pool_sock app_sock"); return -1; } KComponentData("krubypluginfactory"); KRubyPluginFactory factory; QByteArray protocol(argv[1]); QByteArray pool_sock(argv[2]); QByteArray app_sock(argv[3]); // find the script QString keyword("kio_"); keyword.append(protocol); keyword.append("/main.rb"); QString path = KStandardDirs::locate("data", keyword); if (path.isEmpty()) { kWarning() << "Couldn't find" << keyword; return -1; } QFileInfo program(path); #ifdef RUBY_INIT_STACK RUBY_INIT_STACK #endif #if RUBY_VERSION < 0x10900 bool firstTime = (rb_load_path == 0); #else bool firstTime = true; #endif ruby_init(); ruby_script(QFile::encodeName(program.fileName())); // If ruby_init_loadpath() is called more than once, it keeps // adding the same standard directories to it. if (firstTime) { ruby_init_loadpath(); } ruby_incpush(QFile::encodeName(program.path())); int state = 0; const QByteArray encodedFilePath = QFile::encodeName(program.filePath()); rb_load_protect(rb_str_new2(encodedFilePath), 0, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to load " << encodedFilePath << keyword << path; return -1; } QByteArray module_name = KRubyPluginFactory::camelize(protocol); VALUE slave_module = rb_const_get(rb_cObject, rb_intern(module_name)); if (slave_module == Qnil) { kWarning() << "Constant " << module_name << " not found."; return -1; } slave_class = rb_const_get(slave_module, rb_intern("Main")); if (slave_class == Qnil) { kWarning() << "Constant Main in module " << module_name << " not found."; return -1; } #define WRAP_BYTEARRAY(cvar, rvar) \ { \ smokeruby_object *o = alloc_smokeruby_object(true, byteArrayIndex.smoke, byteArrayIndex.index, cvar); \ const char *class_name = resolve_classname(o); \ rb_ary_push(rvar, set_obj_info(class_name, o)); \ } VALUE av = rb_ary_new(); Smoke::ModuleIndex byteArrayIndex = Smoke::findClass("QByteArray"); WRAP_BYTEARRAY(new QByteArray(protocol), av) WRAP_BYTEARRAY(new QByteArray(pool_sock), av) WRAP_BYTEARRAY(new QByteArray(app_sock), av) #undef WRAP_BYTEARRAY VALUE slave_value = rb_protect(create_slave_instance, av, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to create instance of slave instance."; return -1; } // Set a global variable '$my_app_foo_bar + <numeric id>' to the value of the new // instance of MyApp::FooBar to prevent it being GC'd. Note that it would be // better to be able to come up with a way to discover all the plugin instances, // and call rb_gc_mark() on them, in the mark phase of GC. QByteArray variableBaseName("$"); variableBaseName += protocol; // Handle multiple instances of the same class, and look for an unused global // variable QByteArray variableName; VALUE variable = Qnil; int id = 0; do { id++; variableName = variableBaseName + QByteArray::number(id); variable = rb_gv_get(variableName); } while (variable != Qnil); rb_gv_set(variableName, slave_value); smokeruby_object *o = 0; Data_Get_Struct(slave_value, smokeruby_object, o); KIO::SlaveBase *slave = reinterpret_cast<KIO::SlaveBase *>(o->ptr); slave->dispatchLoop(); delete slave; return 0; } } <commit_msg>* When loading a Ruby plugin and it has the wrong number of args, don't output an error message about it, just try with 2 args instead of 3 and see if that works.<commit_after>/*************************************************************************** * Copyright (C) 2005,2006,2007 by Siraj Razick <siraj@kdemail.net> * * Copyright (C) 2007 by Riccardo Iaconelli <ruphy@fsfe.org> * * Copyright (C) 2007 by Matthias Kretz <kretz@kde.org> * * Copyright (C) 2008 by Richard Dale <richard.j.dale@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ #include <ruby.h> #include <QString> #include <QDir> #include <QFileInfo> #include <QWidget> #include <KStandardDirs> #include <klibloader.h> #include <kdebug.h> #include <kio/slavebase.h> #include <qtruby.h> extern "C" { extern VALUE rb_load_path; extern VALUE qt_internal_module; } // // This function was borrowed from the kross code. It puts out // an error message and stacktrace on stderr for the current exception. // static void show_exception_message() { VALUE info = rb_gv_get("$!"); VALUE bt = rb_funcall(info, rb_intern("backtrace"), 0); VALUE message = RARRAY_PTR(bt)[0]; QString errormessage = QString("%1: %2 (%3)") .arg( STR2CSTR(message) ) .arg( STR2CSTR(rb_obj_as_string(info)) ) .arg( rb_class2name(CLASS_OF(info)) ); fprintf(stderr, "%s\n", errormessage.toLatin1().constData()); QString tracemessage; for(int i = 1; i < RARRAY_LEN(bt); ++i) { if( TYPE(RARRAY_PTR(bt)[i]) == T_STRING ) { QString s = QString("%1\n").arg( STR2CSTR(RARRAY_PTR(bt)[i]) ); Q_ASSERT( ! s.isNull() ); tracemessage += s; fprintf(stderr, "\t%s", s.toLatin1().constData()); } } } static VALUE plugin_class = Qnil; static VALUE create_plugin_instance3(VALUE av) { VALUE pv = rb_ary_pop(av); VALUE pw = rb_ary_pop(av); return rb_funcall(plugin_class, rb_intern("new"), 3, pv, pw, av); } static VALUE create_plugin_instance2(VALUE av) { VALUE pv = rb_ary_pop(av); return rb_funcall(plugin_class, rb_intern("new"), 2, pv, av); } class KRubyPluginFactory : public KPluginFactory { public: KRubyPluginFactory(); protected: virtual QObject *create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString &keyword); public: static QByteArray camelize(QByteArray name); }; K_EXPORT_PLUGIN(KRubyPluginFactory) KRubyPluginFactory::KRubyPluginFactory() : KPluginFactory() // no useful KComponentData object for now { } QByteArray KRubyPluginFactory::camelize(QByteArray name) { // Convert foo_bar_baz to FooBarBaz QByteArray camelCaseName = name.left(1).toUpper(); for (int i = 1; i < name.size(); i++) { if (name[i] == '_' || name[i] == '-') { i++; if (i < name.size()) { camelCaseName += name.mid(i, 1).toUpper(); } } else { camelCaseName += name[i]; } } return camelCaseName; } QObject *KRubyPluginFactory::create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString &keyword) { Q_UNUSED(iface); Q_UNUSED(parentWidget); if (keyword.isEmpty()) { kWarning() << "\"keyword\" is empty. It's either missing in the .desktop file or the app doesn't pass it to the pluginfactory."; return 0; } QString path = KStandardDirs::locate("data", keyword); if (path.isEmpty()) { kWarning() << "Ruby script" << keyword << "missing"; return 0; } QFileInfo program(path); #ifdef RUBY_INIT_STACK RUBY_INIT_STACK #endif #if RUBY_VERSION < 0x10900 bool firstTime = (rb_load_path == 0); #else bool firstTime = true; #endif ruby_init(); ruby_script(QFile::encodeName(program.fileName())); // If ruby_init_loadpath() is called more than once, it keeps // adding the same standard directories to it. if (firstTime) { ruby_init_loadpath(); } ruby_incpush(QFile::encodeName(program.path())); int state = 0; const QByteArray encodedFilePath = QFile::encodeName(program.filePath()); rb_load_protect(rb_str_new2(encodedFilePath), 0, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to load" << encodedFilePath << keyword << path; return 0; } // A path of my_app/foo_bar.rb is turned into module/class 'MyApp::FooBar' const QByteArray moduleName = KRubyPluginFactory::camelize(QFile::encodeName(program.dir().dirName())); const QByteArray className = KRubyPluginFactory::camelize(program.baseName().toLatin1()); VALUE plugin_module = rb_const_get(rb_cObject, rb_intern(moduleName)); if (plugin_module == Qnil) { kWarning() << "no " << moduleName << " module found"; return 0; } plugin_class = rb_const_get(plugin_module, rb_intern(className)); if (plugin_class == Qnil) { kWarning() << "no " << moduleName << "::" << className << " class found"; return 0; } VALUE pw, po; #define MKPARENT(cvar, rvar)\ if(cvar == 0) \ rvar = Qnil; \ else \ { \ Smoke::ModuleIndex mi = smokeList[0]->findClass("QObject"); \ smokeruby_object *o = alloc_smokeruby_object(false, mi.smoke, mi.smoke->idClass("QObject").index, cvar); \ const char *class_name = resolve_classname(o); \ rvar = set_obj_info(class_name, o); \ } MKPARENT(parentWidget, pw) MKPARENT(parent, po) #undef MKPARENT // Assume the args list only contains strings, ints and booleans VALUE av = rb_ary_new(); for (int i = 0; i < args.size(); ++i) { if (args.at(i).type() == QVariant::String) { rb_ary_push(av, rb_str_new2(args.at(i).toByteArray())); } else if (args.at(i).type() == QVariant::Int) { rb_ary_push(av, INT2NUM(args.at(i).toInt())); } else if (args.at(i).type() == QVariant::Bool) { rb_ary_push(av, args.at(i).toBool() ? Qtrue : Qfalse); } } rb_ary_push(av, pw); rb_ary_push(av, po); VALUE plugin_value = rb_protect(create_plugin_instance3, av, &state); if (state != 0 || plugin_value == Qnil) { VALUE lasterr = rb_gv_get("$!"); VALUE klass = rb_class_path(CLASS_OF(lasterr)); if (qstrcmp(RSTRING(klass)->ptr, "ArgumentError") != 0) { show_exception_message(); } rb_ary_push(av, po); plugin_value = rb_protect(create_plugin_instance2, av, &state); if (state != 0 || plugin_value == Qnil) { show_exception_message(); kWarning() << "failed to create instance of plugin class"; return 0; } } // Set an instance variable '@componentData' that contains the plugin specific // component data. Smoke::ModuleIndex mi = Smoke::findClass("KComponentData"); smokeruby_object *comp_o = alloc_smokeruby_object(true, mi.smoke, mi.index, new KComponentData(moduleName, moduleName)); const char *class_name = resolve_classname(comp_o); VALUE rb_componentData = set_obj_info(class_name, comp_o); rb_iv_set(plugin_value, "@componentData", rb_componentData); // Set a global variable '$my_app_foo_bar + <numeric id>' to the value of the new // instance of MyApp::FooBar to prevent it being GC'd. Note that it would be // better to be able to come up with a way to discover all the plugin instances, // and call rb_gc_mark() on them, in the mark phase of GC. QByteArray variableBaseName("$"); variableBaseName += QFile::encodeName(program.dir().dirName()); variableBaseName += "_"; variableBaseName += program.baseName().toLatin1(); // Handle multiple instances of the same class, and look for an unused global // variable QByteArray variableName; VALUE variable = Qnil; int id = 0; do { id++; variableName = variableBaseName + QByteArray::number(id); variable = rb_gv_get(variableName); } while (variable != Qnil); rb_gv_set(variableName, plugin_value); smokeruby_object *o = 0; Data_Get_Struct(plugin_value, smokeruby_object, o); QObject * createdInstance = reinterpret_cast<QObject *>(o->ptr); if(createdInstance->parent() == 0) createdInstance->setParent(parent); return createdInstance; } VALUE slave_class = Qnil; static VALUE create_slave_instance(VALUE av) { VALUE a = rb_ary_pop(av); VALUE b = rb_ary_pop(av); VALUE c = rb_ary_pop(av); return rb_funcall(slave_class, rb_intern("new"), 3, c, b, a); } extern "C" { Q_DECL_EXPORT int kdemain(int argc, char **argv) { if (argc != 4) { printf("USAGE: krubypluginfactory protocol pool_sock app_sock"); return -1; } KComponentData("krubypluginfactory"); KRubyPluginFactory factory; QByteArray protocol(argv[1]); QByteArray pool_sock(argv[2]); QByteArray app_sock(argv[3]); // find the script QString keyword("kio_"); keyword.append(protocol); keyword.append("/main.rb"); QString path = KStandardDirs::locate("data", keyword); if (path.isEmpty()) { kWarning() << "Couldn't find" << keyword; return -1; } QFileInfo program(path); #ifdef RUBY_INIT_STACK RUBY_INIT_STACK #endif #if RUBY_VERSION < 0x10900 bool firstTime = (rb_load_path == 0); #else bool firstTime = true; #endif ruby_init(); ruby_script(QFile::encodeName(program.fileName())); // If ruby_init_loadpath() is called more than once, it keeps // adding the same standard directories to it. if (firstTime) { ruby_init_loadpath(); } ruby_incpush(QFile::encodeName(program.path())); int state = 0; const QByteArray encodedFilePath = QFile::encodeName(program.filePath()); rb_load_protect(rb_str_new2(encodedFilePath), 0, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to load " << encodedFilePath << keyword << path; return -1; } QByteArray module_name = KRubyPluginFactory::camelize(protocol); VALUE slave_module = rb_const_get(rb_cObject, rb_intern(module_name)); if (slave_module == Qnil) { kWarning() << "Constant " << module_name << " not found."; return -1; } slave_class = rb_const_get(slave_module, rb_intern("Main")); if (slave_class == Qnil) { kWarning() << "Constant Main in module " << module_name << " not found."; return -1; } #define WRAP_BYTEARRAY(cvar, rvar) \ { \ smokeruby_object *o = alloc_smokeruby_object(true, byteArrayIndex.smoke, byteArrayIndex.index, cvar); \ const char *class_name = resolve_classname(o); \ rb_ary_push(rvar, set_obj_info(class_name, o)); \ } VALUE av = rb_ary_new(); Smoke::ModuleIndex byteArrayIndex = Smoke::findClass("QByteArray"); WRAP_BYTEARRAY(new QByteArray(protocol), av) WRAP_BYTEARRAY(new QByteArray(pool_sock), av) WRAP_BYTEARRAY(new QByteArray(app_sock), av) #undef WRAP_BYTEARRAY VALUE slave_value = rb_protect(create_slave_instance, av, &state); if (state != 0) { show_exception_message(); kWarning() << "Failed to create instance of slave instance."; return -1; } // Set a global variable '$my_app_foo_bar + <numeric id>' to the value of the new // instance of MyApp::FooBar to prevent it being GC'd. Note that it would be // better to be able to come up with a way to discover all the plugin instances, // and call rb_gc_mark() on them, in the mark phase of GC. QByteArray variableBaseName("$"); variableBaseName += protocol; // Handle multiple instances of the same class, and look for an unused global // variable QByteArray variableName; VALUE variable = Qnil; int id = 0; do { id++; variableName = variableBaseName + QByteArray::number(id); variable = rb_gv_get(variableName); } while (variable != Qnil); rb_gv_set(variableName, slave_value); smokeruby_object *o = 0; Data_Get_Struct(slave_value, smokeruby_object, o); KIO::SlaveBase *slave = reinterpret_cast<KIO::SlaveBase *>(o->ptr); slave->dispatchLoop(); delete slave; return 0; } } <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #include <functional> #include <unordered_map> #include <boost/functional/hash.hpp> #include <boost/graph/adjacency_matrix.hpp> #include "debug.hpp" namespace detail { boost::adjacency_matrix<boost::undirectedS> typedef graph; template <class Input, class Output> void copy_edges(const Input& in, Output& out) { auto es = edges(in); for(auto e = es.first; e != es.second; ++e) add_edge(source(*e, in), target(*e, in), out); } } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; boost::hash_combine(seed, v.first); boost::hash_combine(seed, v.second); return seed; } }; } template <class Graph> class leaf_info { public: leaf_info(Graph const & T_) : T(T_) { update(); } bool is_path() const { return L.size() == 2; } std::vector<unsigned> const & leaves() const { return L; } unsigned branching(unsigned l) const { return B.at(l); } unsigned parent(unsigned x, unsigned l) const { return P.at(uintpair(l, x)); } unsigned branching_neighbor(unsigned l, unsigned x) const { return BN.at(uintpair(l, x)); } bool on_branch(unsigned l, unsigned x) const { return BN.count(uintpair(l, x)) == 0; } void update() { L.clear(); B.clear(); P.clear(); BN.clear(); auto vs = vertices(T); for(auto vit = vs.first; vit != vs.second; ++vit) if(degree(*vit, T) == 1) { L.push_back(*vit); traverse(*vit, T); } } void traverse(unsigned l, Graph const & T) { traverse(l, l, l, T); } void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) { do { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; } while(degree(b, T) == 2); if(degree(b, T) > 2) { B[l] = b; auto vs = adjacent_vertices(b, T); for(auto v = vs.first; v != vs.second; ++v) if(*v != a) traverse(l, *v, b, *v, T); } } void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) { P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; while(degree(b, T) == 2) { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; } if(degree(b, T) > 2) { auto vs = adjacent_vertices(b, T); for(auto v = vs.first; v != vs.second; ++v) if(*v != a) traverse(l, blx, b, *v, T); } } std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) { auto it = adjacent_vertices(b, T).first; return make_pair(b, a == *it ? *(++it) : *it); } private: Graph const& T; std::vector<unsigned> L; std::pair<unsigned, unsigned> typedef uintpair; std::unordered_map<unsigned, unsigned> B; std::unordered_map<uintpair, unsigned> P, BN; }; template <class Graph> Graph prieto(Graph& G) { //detail::graph M(num_vertices(G)); //detail::copy_edges(G, M); auto T = dfs_tree(G); leaf_info<Graph> info(T); //int i = 0; do { //show("tree" + std::to_string(i++) + ".dot", M, T); } while(!info.is_path() && rule2(G, T, info)); return T; } template <class Graph, class Tree, class LeafInfo> bool rule2(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { add_edge(l1, l2, T); auto b = info.branching(l1); remove_edge(b, info.parent(b, l1), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule3(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor) { auto xl = info.parent(*x, l); if(degree(xl, T) > 2) { add_edge(l, *x, T); remove_edge(*x, xl, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule4(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor) { auto xl = info.parent(*x, l); if(degree(xl, T) == 2) { for(auto l2 : info.leaves()) if(l2 != l && edge(l2, xl, G).second) { add_edge(l, *x, T); remove_edge(*x, xl, T); add_edge(l2, xl, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule5(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor && !info.on_branch(l, *x)) { auto bl = info.branching(l); auto blx = info.branching_neighbor(l, *x); if(degree(blx, T) > 2) { add_edge(l, *x, T); remove_edge(bl, blx, T); info.update(); return true; } } } return false; } template <class Graph> Graph lost_light(Graph& G) { auto T = dfs_tree(G); leaf_info<Graph> info(T); std::function<bool(Graph&,Graph&,leaf_info<Graph>&)> typedef rule; std::vector<rule> rules { rule2<Graph,Graph,leaf_info<Graph>>, rule3<Graph,Graph,leaf_info<Graph>>, rule4<Graph,Graph,leaf_info<Graph>>, rule5<Graph,Graph,leaf_info<Graph>>, }; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { applied = true; break; } } } return T; } <commit_msg>fix possible bug<commit_after>// (C) 2014 Arek Olek #include <functional> #include <unordered_map> #include <boost/functional/hash.hpp> #include <boost/graph/adjacency_matrix.hpp> #include "debug.hpp" namespace detail { boost::adjacency_matrix<boost::undirectedS> typedef graph; template <class Input, class Output> void copy_edges(const Input& in, Output& out) { auto es = edges(in); for(auto e = es.first; e != es.second; ++e) add_edge(source(*e, in), target(*e, in), out); } } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; boost::hash_combine(seed, v.first); boost::hash_combine(seed, v.second); return seed; } }; } template <class Graph> class leaf_info { public: leaf_info(Graph const & T_) : T(T_) { update(); } bool is_path() const { return L.size() == 2; } std::vector<unsigned> const & leaves() const { return L; } unsigned branching(unsigned l) const { return B.at(l); } unsigned parent(unsigned x, unsigned l) const { return P.at(uintpair(l, x)); } unsigned branching_neighbor(unsigned l, unsigned x) const { return BN.at(uintpair(l, x)); } bool on_branch(unsigned l, unsigned x) const { return BN.count(uintpair(l, x)) == 0; } void update() { L.clear(); B.clear(); P.clear(); BN.clear(); auto vs = vertices(T); for(auto vit = vs.first; vit != vs.second; ++vit) if(degree(*vit, T) == 1) { L.push_back(*vit); traverse(*vit, T); } } void traverse(unsigned l, Graph const & T) { traverse(l, l, l, T); } void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) { do { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; } while(degree(b, T) == 2); if(degree(b, T) > 2) { B[l] = b; auto vs = adjacent_vertices(b, T); for(auto v = vs.first; v != vs.second; ++v) if(*v != a) traverse(l, *v, b, *v, T); } } void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) { P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; while(degree(b, T) == 2) { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; } if(degree(b, T) > 2) { auto vs = adjacent_vertices(b, T); for(auto v = vs.first; v != vs.second; ++v) if(*v != a) traverse(l, blx, b, *v, T); } } std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) { auto it = adjacent_vertices(b, T).first; return make_pair(b, a == *it ? *(++it) : *it); } private: Graph const& T; std::vector<unsigned> L; std::pair<unsigned, unsigned> typedef uintpair; std::unordered_map<unsigned, unsigned> B; std::unordered_map<uintpair, unsigned> P, BN; }; template <class Graph> Graph prieto(Graph& G) { //detail::graph M(num_vertices(G)); //detail::copy_edges(G, M); auto T = dfs_tree(G); leaf_info<Graph> info(T); //int i = 0; do { //show("tree" + std::to_string(i++) + ".dot", M, T); } while(!info.is_path() && rule2(G, T, info)); return T; } template <class Graph, class Tree, class LeafInfo> bool rule2(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { add_edge(l1, l2, T); auto b = info.branching(l1); remove_edge(b, info.parent(b, l1), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule3(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor) { auto xl = info.parent(*x, l); if(degree(xl, T) > 2) { add_edge(l, *x, T); remove_edge(*x, xl, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule4(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor) { auto xl = info.parent(*x, l); if(degree(xl, T) == 2) { for(auto l2 : info.leaves()) if(l2 != l && edge(l2, xl, G).second) { add_edge(l, *x, T); remove_edge(*x, xl, T); info.update(); add_edge(l2, xl, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule5(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; auto vs = adjacent_vertices(l, G); for(auto x = vs.first; x != vs.second; ++x) if(*x != treeNeighbor && !info.on_branch(l, *x)) { auto bl = info.branching(l); auto blx = info.branching_neighbor(l, *x); if(degree(blx, T) > 2) { add_edge(l, *x, T); remove_edge(bl, blx, T); info.update(); return true; } } } return false; } template <class Graph> Graph lost_light(Graph& G) { auto T = dfs_tree(G); leaf_info<Graph> info(T); std::function<bool(Graph&,Graph&,leaf_info<Graph>&)> typedef rule; std::vector<rule> rules { rule2<Graph,Graph,leaf_info<Graph>>, rule3<Graph,Graph,leaf_info<Graph>>, rule4<Graph,Graph,leaf_info<Graph>>, rule5<Graph,Graph,leaf_info<Graph>>, }; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { applied = true; break; } } } return T; } <|endoftext|>
<commit_before>#include "functional.h" #include "pw9xx.h" template<class num> static num energy(const densvars<num> &d) { const parameter param_AB[6] = { 0.19645, 7.7956, 0.2743, 0.1508, 100.0, 0.004}; using pw91_like_x_internal::prefactor; using pw91_like_x_internal::pw91xk_enhancement; return prefactor(d.a)*pw91xk_enhancement(param_AB,d.a,d.gaa) + prefactor(d.b)*pw91xk_enhancement(param_AB,d.b,d.gbb); } void setup_pw91x(functional &f) { f.describe(XC_PW91X, XC_GGA, "Perdew-Wang 1991 GGA Exchange Functional", "Perdew-Wang 1991 GGA Exchange Functional\n" "J. P. Perdew, J. A. Chevary, S. H. Vosko, " "K. A. Jackson, M. R. Pederson, and C. Fiolhais, " "Phys. Rev. B 46, 6671 (1992)\n" "Implemented by Andre Gomes.\n" "Test from http://www.cse.scitech.ac.uk/ccg/dft/" "data_pt_x_pw91.html\n"); SET_GGA_ENERGY_FUNCTION(f,energy); const double d[] = {0.82E+02, 0.81E+02, 0.49E+07, 0.49E+07, 0.49E+07}; const double out[] = { -0.739934270280E+03, -0.500194130392E+01, -0.497593413511E+01, -0.661655297347E-05, 0.000000000000E+00, -0.665149614704E-05, -0.259426653786E-01, 0.000000000000E+00, 0.352029178373E-07, 0.000000000000E+00, 0.000000000000E+00, -0.260706018375E-01, 0.000000000000E+00, 0.000000000000E+00, 0.346740334540E-07, 0.454242196579E-12, 0.000000000000E+00, 0.000000000000E+00, 0.000000000000E+00, 0.000000000000E+00, 0.463780470889E-12,}; f.add_test(XC_VARS_AB,2,d,out,1e-11); } <commit_msg>Add an extra decimal in a pw91x parameter. Does not affect the test.<commit_after>#include "functional.h" #include "pw9xx.h" template<class num> static num energy(const densvars<num> &d) { const parameter param_AB[6] = { 0.19645, 7.7956, 0.2743, 0.15084, 100.0, 0.004}; using pw91_like_x_internal::prefactor; using pw91_like_x_internal::pw91xk_enhancement; return prefactor(d.a)*pw91xk_enhancement(param_AB,d.a,d.gaa) + prefactor(d.b)*pw91xk_enhancement(param_AB,d.b,d.gbb); } void setup_pw91x(functional &f) { f.describe(XC_PW91X, XC_GGA, "Perdew-Wang 1991 GGA Exchange Functional", "Perdew-Wang 1991 GGA Exchange Functional\n" "J. P. Perdew, J. A. Chevary, S. H. Vosko, " "K. A. Jackson, M. R. Pederson, and C. Fiolhais, " "Phys. Rev. B 46, 6671 (1992)\n" "Implemented by Andre Gomes.\n" "Test from http://www.cse.scitech.ac.uk/ccg/dft/" "data_pt_x_pw91.html\n"); SET_GGA_ENERGY_FUNCTION(f,energy); const double d[] = {0.82E+02, 0.81E+02, 0.49E+07, 0.49E+07, 0.49E+07}; const double out[] = { -0.739934270280E+03, -0.500194130392E+01, -0.497593413511E+01, -0.661655297347E-05, 0.000000000000E+00, -0.665149614704E-05, -0.259426653786E-01, 0.000000000000E+00, 0.352029178373E-07, 0.000000000000E+00, 0.000000000000E+00, -0.260706018375E-01, 0.000000000000E+00, 0.000000000000E+00, 0.346740334540E-07, 0.454242196579E-12, 0.000000000000E+00, 0.000000000000E+00, 0.000000000000E+00, 0.000000000000E+00, 0.463780470889E-12,}; f.add_test(XC_VARS_AB,2,d,out,1e-11); } <|endoftext|>
<commit_before>#include "gamelib/core/Game.hpp" #include <SFML/Graphics.hpp> #include "gamelib/core/GameState.hpp" #include "gamelib/utils/log.hpp" #include "gamelib/utils/json.hpp" #include "gamelib/core/event/EventManager.hpp" #include "gamelib/events/SFMLEvent.hpp" #include "gamelib/core/input/InputSystem.hpp" constexpr const char* game_title = "Unnamed game"; constexpr int game_width = 640; constexpr int game_height = 480; constexpr int game_max_fps = 0; constexpr bool game_vsync = true; constexpr bool game_escclose = true; constexpr bool game_closebutton = true; constexpr bool game_repeatkeys = false; namespace gamelib { constexpr const char* Game::name; Game::Game() : _frametime(0), _handleclose(game_closebutton), _escclose(game_escclose) { } Game::~Game() { destroy(); } bool Game::init() { LOG("Initializing game..."); _window.create(sf::VideoMode(game_width, game_height), game_title, sf::Style::Close); _window.setFramerateLimit(game_max_fps); _window.setVerticalSyncEnabled(game_vsync); _window.setKeyRepeatEnabled(game_repeatkeys); return true; } void Game::run() { sf::Clock clock; sf::Event ev; while (_window.isOpen()) { clock.restart(); auto inputsys = getSubsystem<InputSystem>(); if (inputsys) inputsys->beginFrame(); while (_window.pollEvent(ev)) { if ((ev.type == sf::Event::KeyPressed && _escclose && ev.key.code == sf::Keyboard::Escape) || (ev.type == sf::Event::Closed && _handleclose)) { close(); return; } if (inputsys) inputsys->process(ev); auto evmgr = getSubsystem<EventManager>(); if (evmgr) evmgr->triggerEvent(SFMLEvent::create(ev)); } if (_window.hasFocus()) { bool frozen = false; for (auto it = _states.rbegin(), end = _states.rend(); it != end; ++it) { auto state = (*it).get(); if (state->flags & gamestate_paused) continue; if (!frozen || state->flags & gamestate_forceupdate) state->update(_frametime); if (state->flags & gamestate_freeze) frozen = true; } } _window.resetGLStates(); // without this things start randomly disappearing _window.clear(_bgcolor); for (auto& i : _states) i->render(_window); _window.display(); // Get elapsed time _frametime = clock.getElapsedTime().asMilliseconds() / 1000.0f; } } void Game::close() { if (_window.isOpen()) { _window.close(); LOG_DEBUG("Game window closed"); } } void Game::destroy() { close(); if (!_states.empty()) { LOG_DEBUG("Closing game states..."); for (auto& i : _states) i->quit(); _states.clear(); } } bool Game::loadFromJson(const Json::Value& node) { auto size = _window.getSize(); auto pos = _window.getPosition(); size.x = node.get("width", size.x).asUInt(); size.y = node.get("height", size.y).asUInt(); auto diff = size - _window.getSize(); pos.x -= diff.x / 2; pos.y -= diff.y / 2; _window.setSize(size); _window.setPosition(pos); _window.setView(sf::View(sf::FloatRect(0, 0, size.x, size.y))); // Don't create a new window, as it could lead to problems // if (size != _window.getSize()) // { // _window.close(); // _window.create(sf::VideoMode(size.x, size.y), game_title, sf::Style::Close); // } if (node.isMember("title")) _window.setTitle(node["title"].asString()); if (node.isMember("maxfps")) _window.setFramerateLimit(node["maxfps"].asUInt()); if (node.isMember("vsync")) _window.setVerticalSyncEnabled(node["vsync"].asBool()); if (node.isMember("repeatkeys")) _window.setKeyRepeatEnabled(node["repeatkeys"].asBool()); _handleclose = node.get("handleclose", _handleclose).asBool(); _escclose = node.get("escclose", _escclose).asBool(); if (node.isMember("bg")) { const auto& bg = node["bg"]; _bgcolor.r = bg.get("r", _bgcolor.r).asUInt(); _bgcolor.g = bg.get("g", _bgcolor.g).asUInt(); _bgcolor.b = bg.get("b", _bgcolor.b).asUInt(); } return true; } void Game::pushState(std::unique_ptr<GameState> state) { if (!state->init(this)) { LOG_ERROR("Failed to initialize game state"); return; } _states.push_back(std::move(state)); LOG_DEBUG("Game state added"); } void Game::popState() { _states.back()->quit(); _states.pop_back(); } GameState& Game::pullState() const { return *_states.back().get(); } float Game::getFrametime() const { return _frametime; } sf::RenderWindow& Game::getWindow() { return _window; } } <commit_msg>Use InputSystem to check for escape key press<commit_after>#include "gamelib/core/Game.hpp" #include <SFML/Graphics.hpp> #include "gamelib/core/GameState.hpp" #include "gamelib/utils/log.hpp" #include "gamelib/utils/json.hpp" #include "gamelib/core/event/EventManager.hpp" #include "gamelib/events/SFMLEvent.hpp" #include "gamelib/core/input/InputSystem.hpp" constexpr const char* game_title = "Unnamed game"; constexpr int game_width = 640; constexpr int game_height = 480; constexpr int game_max_fps = 0; constexpr bool game_vsync = true; constexpr bool game_escclose = true; constexpr bool game_closebutton = true; constexpr bool game_repeatkeys = false; namespace gamelib { constexpr const char* Game::name; Game::Game() : _frametime(0), _handleclose(game_closebutton), _escclose(game_escclose) { } Game::~Game() { destroy(); } bool Game::init() { LOG("Initializing game..."); _window.create(sf::VideoMode(game_width, game_height), game_title, sf::Style::Close); _window.setFramerateLimit(game_max_fps); _window.setVerticalSyncEnabled(game_vsync); _window.setKeyRepeatEnabled(game_repeatkeys); return true; } void Game::run() { sf::Clock clock; sf::Event ev; while (_window.isOpen()) { clock.restart(); auto inputsys = getSubsystem<InputSystem>(); if (inputsys) inputsys->beginFrame(); while (_window.pollEvent(ev)) { if (inputsys) inputsys->process(ev); auto evmgr = getSubsystem<EventManager>(); if (evmgr) evmgr->triggerEvent(SFMLEvent::create(ev)); } if (_window.hasFocus()) { bool frozen = false; for (auto it = _states.rbegin(), end = _states.rend(); it != end; ++it) { auto state = (*it).get(); if (state->flags & gamestate_paused) continue; if (!frozen || state->flags & gamestate_forceupdate) state->update(_frametime); if (state->flags & gamestate_freeze) frozen = true; } if (_escclose && inputsys && inputsys->isKeyPressed(sf::Keyboard::Escape)) { close(); return; } } _window.resetGLStates(); // without this things start randomly disappearing _window.clear(_bgcolor); for (auto& i : _states) i->render(_window); _window.display(); // Get elapsed time _frametime = clock.getElapsedTime().asMilliseconds() / 1000.0f; } } void Game::close() { if (_window.isOpen()) { _window.close(); LOG_DEBUG("Game window closed"); } } void Game::destroy() { close(); if (!_states.empty()) { LOG_DEBUG("Closing game states..."); for (auto& i : _states) i->quit(); _states.clear(); } } bool Game::loadFromJson(const Json::Value& node) { auto size = _window.getSize(); auto pos = _window.getPosition(); size.x = node.get("width", size.x).asUInt(); size.y = node.get("height", size.y).asUInt(); auto diff = size - _window.getSize(); pos.x -= diff.x / 2; pos.y -= diff.y / 2; _window.setSize(size); _window.setPosition(pos); _window.setView(sf::View(sf::FloatRect(0, 0, size.x, size.y))); // Don't create a new window, as it could lead to problems // if (size != _window.getSize()) // { // _window.close(); // _window.create(sf::VideoMode(size.x, size.y), game_title, sf::Style::Close); // } if (node.isMember("title")) _window.setTitle(node["title"].asString()); if (node.isMember("maxfps")) _window.setFramerateLimit(node["maxfps"].asUInt()); if (node.isMember("vsync")) _window.setVerticalSyncEnabled(node["vsync"].asBool()); if (node.isMember("repeatkeys")) _window.setKeyRepeatEnabled(node["repeatkeys"].asBool()); _handleclose = node.get("handleclose", _handleclose).asBool(); _escclose = node.get("escclose", _escclose).asBool(); if (node.isMember("bg")) { const auto& bg = node["bg"]; _bgcolor.r = bg.get("r", _bgcolor.r).asUInt(); _bgcolor.g = bg.get("g", _bgcolor.g).asUInt(); _bgcolor.b = bg.get("b", _bgcolor.b).asUInt(); } return true; } void Game::pushState(std::unique_ptr<GameState> state) { if (!state->init(this)) { LOG_ERROR("Failed to initialize game state"); return; } _states.push_back(std::move(state)); LOG_DEBUG("Game state added"); } void Game::popState() { _states.back()->quit(); _states.pop_back(); } GameState& Game::pullState() const { return *_states.back().get(); } float Game::getFrametime() const { return _frametime; } sf::RenderWindow& Game::getWindow() { return _window; } } <|endoftext|>
<commit_before>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include <map> #include <string> namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { FILE* outpipe = popen("???", "w"); // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); fwrite(&sizeLong, 1, 1, outpipe); long dictSize = contentDict.size(); fwrite(&dictSize, sizeof(long), 1, outpipe); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; fwrite(mimeType.c_str(), mimeType.size() + 1, 1, outpipe); const MIMEDataRef& mimeData = iContent.second; fwrite(&mimeData.m_Size, sizeof(long), 1, outpipe); fwrite(mimeData.m_Data, mimeData.m_Size, 1, outpipe); } pclose(outpipe); } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir) { auto interp = new cling::Interpreter(argc, argv, llvmdir); return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Evaluate a string of code. Returns 0 on success. int cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; //cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code /*, V*/); if (Res != cling::Interpreter::kSuccess) return 1; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); return 0; } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = *(int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <commit_msg>Stringify eval result; use pipe fd.<commit_after>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include <map> #include <string> // FIXME: should be moved into a Jupyter interp struct that then gets returned // from create. int pipeToJupyterFD = -1; namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); write(pipeToJupyterFD, &sizeLong, 1); long dictSize = contentDict.size(); write(pipeToJupyterFD, &dictSize, sizeof(long)); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1); const MIMEDataRef& mimeData = iContent.second; write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long)); write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size); } } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) { auto interp = new cling::Interpreter(argc, argv, llvmdir); pipeToJupyterFD = pipefd; return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Stringify a cling::Value static std::string ValueToString(const cling::Value& V) { std::string valueString; { llvm::raw_ostringstream os(valueString); V.print(os); } return valueString; } /// Evaluate a string of code. Returns nullptr on failure. /// Returns a string representation of the expression (can be "") on success. char* cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code, &V); if (Res != cling::Interpreter::kSuccess) return nullptr; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); if (!V.isValid()) return strdup(""); return strdup(valueString(V)); } void cling_eval_free(char* str) { free(str); } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = *(int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <|endoftext|>
<commit_before>5838dac2-5216-11e5-9493-6c40088e03e4<commit_msg>583fc1ca-5216-11e5-921f-6c40088e03e4<commit_after>583fc1ca-5216-11e5-921f-6c40088e03e4<|endoftext|>
<commit_before>6b383b61-2e4f-11e5-8a2b-28cfe91dbc4b<commit_msg>6b400d42-2e4f-11e5-a62c-28cfe91dbc4b<commit_after>6b400d42-2e4f-11e5-a62c-28cfe91dbc4b<|endoftext|>
<commit_before>8b332515-2d14-11e5-af21-0401358ea401<commit_msg>8b332516-2d14-11e5-af21-0401358ea401<commit_after>8b332516-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>2a5c837d-2d3d-11e5-ab6c-c82a142b6f9b<commit_msg>2ac11d8c-2d3d-11e5-a466-c82a142b6f9b<commit_after>2ac11d8c-2d3d-11e5-a466-c82a142b6f9b<|endoftext|>
<commit_before>965387de-2e4f-11e5-a18b-28cfe91dbc4b<commit_msg>965ab2de-2e4f-11e5-9549-28cfe91dbc4b<commit_after>965ab2de-2e4f-11e5-9549-28cfe91dbc4b<|endoftext|>
<commit_before>48dd4175-ad59-11e7-b5ea-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>4a34bdb8-ad59-11e7-b3dd-ac87a332f658<|endoftext|>
<commit_before>782ff668-2d53-11e5-baeb-247703a38240<commit_msg>7830750c-2d53-11e5-baeb-247703a38240<commit_after>7830750c-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>e8a58e08-585a-11e5-9239-6c40088e03e4<commit_msg>e8ac6b2e-585a-11e5-8243-6c40088e03e4<commit_after>e8ac6b2e-585a-11e5-8243-6c40088e03e4<|endoftext|>
<commit_before>99656ff8-327f-11e5-ae23-9cf387a8033e<commit_msg>996c6311-327f-11e5-b814-9cf387a8033e<commit_after>996c6311-327f-11e5-b814-9cf387a8033e<|endoftext|>
<commit_before>9f2645a4-35ca-11e5-b16f-6c40088e03e4<commit_msg>9f2d3a76-35ca-11e5-8252-6c40088e03e4<commit_after>9f2d3a76-35ca-11e5-8252-6c40088e03e4<|endoftext|>
<commit_before>fa3c13f3-2e4e-11e5-9d74-28cfe91dbc4b<commit_msg>fa48237d-2e4e-11e5-a7c7-28cfe91dbc4b<commit_after>fa48237d-2e4e-11e5-a7c7-28cfe91dbc4b<|endoftext|>
<commit_before>e2a81e8c-2747-11e6-a6c8-e0f84713e7b8<commit_msg>bug fix<commit_after>e2bdf3f5-2747-11e6-af2f-e0f84713e7b8<|endoftext|>
<commit_before>#include <QCoreApplication> #include <QDomDocument> #include <QStringList> #include <QFile> #include <QDir> #include <iostream> #include "protocolparser.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int Return = 1; bool nodoxygen = false; bool nomarkdown = false; bool nohelperfiles = false; QString inlinecss; QString docs; bool latexSupportOn = false; // The list of arguments QStringList arguments = a.arguments(); if(arguments.size() <= 1) { std::cout << "Protocol generator usage:" << std::endl; std::cout << "ProtoGen input.xml [outputpath] [-docs docspath] [-latex] [-verbose] [-no-doxygen] [-no-markdown] [-no-helper-files]" << std::endl; return 0; } // We expect the input file here QString filename = a.arguments().at(1); // The output path QString path; // Skip the first argument "ProtoGen.exe" for(int i = 1; i < arguments.size(); i++) { QString arg = arguments.at(i); if(arg.contains("-no-doxygen", Qt::CaseInsensitive)) nodoxygen = true; else if(arg.contains("-no-markdown", Qt::CaseInsensitive)) nomarkdown = true; else if(arg.contains("-no-helper-files", Qt::CaseInsensitive)) nohelperfiles = true; else if(arg.endsWith(".xml")) filename = arg; else if (arg.contains("-latex", Qt::CaseInsensitive)) latexSupportOn = true; else if(arg.endsWith(".css")) { QFile file(arg); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { inlinecss = file.readAll(); file.close(); } else std::cout << "Failed to open " << arg.toStdString() << "; using default css" << std::endl; } else if (arg.startsWith("-docs")) { //Is there an argument following this? if (arguments.size() > (i + 1)) { docs = arguments.at(i+1); QDir docDir(QDir::current()); if (docDir.exists() || docDir.mkdir(docs)) //Markdown directory is sane { //Skip the next argument; i++; } else { docs = ""; } } } else if((path.isEmpty()) && (arg != filename)) path = arg; } if(!filename.isEmpty()) { QDomDocument doc("protogen"); QFile file(filename); if (file.open(QIODevice::ReadOnly)) { if (doc.setContent(&file)) { ProtocolParser parser; parser.setLaTeXSupport(latexSupportOn); if (!docs.isEmpty()) parser.setDocsPath(docs); // Set our working directory if(!path.isEmpty()) { QDir dir(QDir::current()); // The path could be absolute or relative to // our current path, this works either way // Make sure the path exists dir.mkpath(path); // Now set it as the path to use QDir::setCurrent(path); } if(parser.parse(doc, nodoxygen, nomarkdown, nohelperfiles, inlinecss)) Return = 1; } else { std::cout << "failed to validate xml from file: " << filename.toStdString() << std::endl; Return = 0; } file.close(); } else { std::cout << "failed to open protocol file: " << filename.toStdString() << std::endl; Return = 0; } } else { std::cout << "must provide a protocol file." << std::endl; Return = 0; } if (Return == 1) std::cout << "Generated protocol files in " << path.toStdString() << std::endl; return Return; } <commit_msg>Removed -verbose commandline switch (shouldn't have been there, oops)<commit_after>#include <QCoreApplication> #include <QDomDocument> #include <QStringList> #include <QFile> #include <QDir> #include <iostream> #include "protocolparser.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int Return = 1; bool nodoxygen = false; bool nomarkdown = false; bool nohelperfiles = false; QString inlinecss; QString docs; bool latexSupportOn = false; // The list of arguments QStringList arguments = a.arguments(); if(arguments.size() <= 1) { std::cout << "Protocol generator usage:" << std::endl; std::cout << "ProtoGen input.xml [outputpath] [-docs docspath] [-latex] [-no-doxygen] [-no-markdown] [-no-helper-files]" << std::endl; return 0; } // We expect the input file here QString filename = a.arguments().at(1); // The output path QString path; // Skip the first argument "ProtoGen.exe" for(int i = 1; i < arguments.size(); i++) { QString arg = arguments.at(i); if(arg.contains("-no-doxygen", Qt::CaseInsensitive)) nodoxygen = true; else if(arg.contains("-no-markdown", Qt::CaseInsensitive)) nomarkdown = true; else if(arg.contains("-no-helper-files", Qt::CaseInsensitive)) nohelperfiles = true; else if(arg.endsWith(".xml")) filename = arg; else if (arg.contains("-latex", Qt::CaseInsensitive)) latexSupportOn = true; else if(arg.endsWith(".css")) { QFile file(arg); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { inlinecss = file.readAll(); file.close(); } else std::cout << "Failed to open " << arg.toStdString() << "; using default css" << std::endl; } else if (arg.startsWith("-docs")) { //Is there an argument following this? if (arguments.size() > (i + 1)) { docs = arguments.at(i+1); QDir docDir(QDir::current()); if (docDir.exists() || docDir.mkdir(docs)) //Markdown directory is sane { //Skip the next argument; i++; } else { docs = ""; } } } else if((path.isEmpty()) && (arg != filename)) path = arg; } if(!filename.isEmpty()) { QDomDocument doc("protogen"); QFile file(filename); if (file.open(QIODevice::ReadOnly)) { if (doc.setContent(&file)) { ProtocolParser parser; parser.setLaTeXSupport(latexSupportOn); if (!docs.isEmpty()) parser.setDocsPath(docs); // Set our working directory if(!path.isEmpty()) { QDir dir(QDir::current()); // The path could be absolute or relative to // our current path, this works either way // Make sure the path exists dir.mkpath(path); // Now set it as the path to use QDir::setCurrent(path); } if(parser.parse(doc, nodoxygen, nomarkdown, nohelperfiles, inlinecss)) Return = 1; } else { std::cout << "failed to validate xml from file: " << filename.toStdString() << std::endl; Return = 0; } file.close(); } else { std::cout << "failed to open protocol file: " << filename.toStdString() << std::endl; Return = 0; } } else { std::cout << "must provide a protocol file." << std::endl; Return = 0; } if (Return == 1) std::cout << "Generated protocol files in " << path.toStdString() << std::endl; return Return; } <|endoftext|>
<commit_before>27f8a705-2d3e-11e5-a1f0-c82a142b6f9b<commit_msg>286ee57d-2d3e-11e5-8367-c82a142b6f9b<commit_after>286ee57d-2d3e-11e5-8367-c82a142b6f9b<|endoftext|>
<commit_before>1355f973-2d3d-11e5-bbb6-c82a142b6f9b<commit_msg>13e6baca-2d3d-11e5-86db-c82a142b6f9b<commit_after>13e6baca-2d3d-11e5-86db-c82a142b6f9b<|endoftext|>
<commit_before>e4c34933-313a-11e5-a05f-3c15c2e10482<commit_msg>e4c96511-313a-11e5-82c2-3c15c2e10482<commit_after>e4c96511-313a-11e5-82c2-3c15c2e10482<|endoftext|>
<commit_before>a896dcc0-2e4f-11e5-b75c-28cfe91dbc4b<commit_msg>a89d2878-2e4f-11e5-ad54-28cfe91dbc4b<commit_after>a89d2878-2e4f-11e5-ad54-28cfe91dbc4b<|endoftext|>
<commit_before>98035919-327f-11e5-a757-9cf387a8033e<commit_msg>980b887d-327f-11e5-bdb7-9cf387a8033e<commit_after>980b887d-327f-11e5-bdb7-9cf387a8033e<|endoftext|>
<commit_before>#include <iostream> #include <boost/tokenizer.hpp> #include <string> #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <stdlib.h> #include <vector> using namespace std; using namespace boost; //function used to seperate commands void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command) { //different connectors string semicolon = ";"; string needfirst = "&&"; string needfirstfail = "||"; int i = 0; //finding connectors while (command.size() != 0) { int semi = 0;//command.find(semicolon); int needf = 0;//command.find(needfirst); int needff = 0;//command.find(needfirstfail); //test for cases where connectors are gone if (command.find(semicolon) != string::npos) { semi = command.find(semicolon); } else { semi = 10000; } if (command.find(needfirst) != string::npos) { needf = command.find(needfirst); } else { needf = 10000; } if (command.find(needfirstfail) != string::npos) { needff = command.find(needfirstfail); } else { needff = 10000; } //checks to see which index of the different connectors are first vector<string> temp; if (semi > needf) { if (needf > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } else { connect.push_back(needfirst); temp.push_back(command.substr(0, needf)); command = command.substr(needf + 2, command.size() - needf - 2); ++i; } } else if (needf > semi) { if (semi > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } else { connect.push_back(semicolon); temp.push_back(command.substr(0, semi)); command = command.substr(semi + 1, command.size() - semi - 1); ++i; } } else if ( (needf == semi) && (needff != 10000) ) { if (needf > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } } else { //used when out of connectors temp.push_back(command); cmd.push_back(temp); return; } cmd.push_back(temp); } } //tokenizer function void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2) { string f; for (int i = 0; i < cmdl.size(); ++i) { int j = 0; char_separator<char> sep(" "); tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep); cout << cmdl.at(i).at(0) << endl; cmdl2.push_back(vector<string>()); //must seperate vectors or the tokenizer will BREAK for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter) { cout << "deref iters: " << *iter << endl; f = *iter; cmdl2.at(i).push_back(f); ++j; } } } void startline() { char hostname[128]; //passes in an array named hostname & it basically makes a copy of the hostname stored int hostnameStatus = gethostname(hostname, sizeof(hostname)); //somewhere else and passes it back by reference (default b/c its an array). if (hostnameStatus == -1) { perror(hostname); } else { char* login = getlogin(); cout << login << "@" << hostname << " $ "; } } //main run function, will prepare the command line void run() { //sentinel for while loop while (true) { //take in a command into a variable string command; startline(); getline(cin, command); //exit command if (command == "exit") { exit(0); } else { //call to parse vector< vector<string> > cmdline; vector<string> connectors; parseconnect(cmdline, connectors, command); for (int i = 0; i < cmdline.size(); ++i) { cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl; } vector< vector<string> > cmdline2; token(cmdline, cmdline2); vector< vector<char*> > commands; //changes all strings to char pointers for (int i = 0; i < cmdline2.size(); ++i) { //cout << cmdline.size() << endl; commands.push_back( vector<char*>() ); for (int j = 0; j < cmdline2.at(i).size(); ++j) { cout << endl; cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl; cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl; commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str())); } char* temp = NULL; commands.at(i).push_back(temp); } /* for (int i = 0; i < cmdline.size(); ++i) { for (int j = 0; j < cmdline.at(i).size(); ++j) { cout << cmdline.at(i).at(j) << endl; cout << j << endl; } cout << "--------------------------------------------" << endl; } */ int i = 0; bool sentinel = true; while (sentinel == true) { //checks for connector logic if (i >= connectors.size()) { sentinel = false; } else if (connectors.at(i) == ";") { sentinel == true; } //forking process to child pid_t pid = fork(); if (pid == 0) { if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1) { if (connectors.at(i) == "&&") { sentinel = false; } else { sentinel == true; } perror("exec"); } else { if (connectors.at(i) == "||") { sentinel = false; } } } if (pid > 0) { if (wait(0) == -1) { ++i; perror("wait"); } } ++i; } } } } //main function, will contain test cases int main() { string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf"; vector<string> connectors; vector< vector<string> > cmdline; vector< vector<string> > cmdline2; parseconnect(cmdline, connectors, command); for (int i = 0; i < cmdline.size() - 1; ++i) { cout << cmdline.at(i).at(0); for (int j = i; j < i + 1; ++j) { cout << connectors.at(j); } } cout << cmdline.at(cmdline.size() - 1).at(0) << endl; token(cmdline, cmdline2); for (int i = 0; i < cmdline2.size(); ++i) { for (int j = 0; j < cmdline2.at(i).size(); ++j) { cout << "<" << cmdline2.at(i).at(j) << ">" << endl; } } run(); return 0; } <commit_msg>takes into account single cmds, comments, and exit command<commit_after>#include <iostream> #include <boost/tokenizer.hpp> #include <string> #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <stdlib.h> #include <vector> using namespace std; using namespace boost; //function used to seperate commands void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command) { //different connectors string semicolon = ";"; string needfirst = "&&"; string needfirstfail = "||"; int i = 0; string comment = "#"; //deleting all comments if (command.find(comment) != string::npos) { int com = command.find(comment); command = command.substr(0, com); } //finding connectors while (command.size() != 0) { int semi = 0;//command.find(semicolon); int needf = 0;//command.find(needfirst); int needff = 0;//command.find(needfirstfail); //test for cases where connectors are gone if (command.find(semicolon) != string::npos) { semi = command.find(semicolon); } else { semi = 10000; } if (command.find(needfirst) != string::npos) { needf = command.find(needfirst); } else { needf = 10000; } if (command.find(needfirstfail) != string::npos) { needff = command.find(needfirstfail); } else { needff = 10000; } //checks to see which index of the different connectors are first vector<string> temp; if (semi > needf) { if (needf > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } else { connect.push_back(needfirst); temp.push_back(command.substr(0, needf)); command = command.substr(needf + 2, command.size() - needf - 2); ++i; } } else if (needf > semi) { if (semi > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } else { connect.push_back(semicolon); temp.push_back(command.substr(0, semi)); command = command.substr(semi + 1, command.size() - semi - 1); ++i; } } else if ( (needf == semi) && (needff != 10000) ) { if (needf > needff) { connect.push_back(needfirstfail); temp.push_back(command.substr(0, needff)); command = command.substr(needff + 2, command.size() - needff - 2); ++i; } } else { //used when out of connectors temp.push_back(command); cmd.push_back(temp); return; } cmd.push_back(temp); } } //tokenizer function void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2) { string f; for (int i = 0; i < cmdl.size(); ++i) { int j = 0; char_separator<char> sep(" "); tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep); //cout << cmdl.at(i).at(0) << endl; cmdl2.push_back(vector<string>()); //must seperate vectors or the tokenizer will BREAK for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter) { //cout << "deref iters: " << *iter << endl; f = *iter; cmdl2.at(i).push_back(f); ++j; } } } void startline() { char hostname[128]; //passes in an array named hostname & it basically makes a copy of the hostname stored int hostnameStatus = gethostname(hostname, sizeof(hostname)); //somewhere else and passes it back by reference (default b/c its an array). if (hostnameStatus == -1) { perror(hostname); } else { char* login = getlogin(); cout << login << "@" << hostname << " $ "; } } //main run function, will prepare the command line void run() { //sentinel for while loop while (true) { //take in a command into a variable string command; startline(); getline(cin, command); //exit command if (command == "exit") { exit(0); } else { //call to parse vector< vector<string> > cmdline; vector<string> connectors; parseconnect(cmdline, connectors, command); //for (int i = 0; i < cmdline.size(); ++i) //{ // cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl; //} vector< vector<string> > cmdline2; token(cmdline, cmdline2); vector< vector<char*> > commands; //changes all strings to char pointers for (int i = 0; i < cmdline2.size(); ++i) { //cout << cmdline.size() << endl; commands.push_back( vector<char*>() ); for (int j = 0; j < cmdline2.at(i).size(); ++j) { //cout << endl; //cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl; //cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl; commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str())); } char* temp = NULL; commands.at(i).push_back(temp); } //calls process int i = 0; int j = 0; bool sentinel = true; while (sentinel == true) { if (commands.size() == 1) { pid_t pid = fork(); if (pid == 0) { if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1) { perror("exec"); } } if (pid > 0) { if (wait(0) == -1) { perror("wait"); } } sentinel = false; } else { if (j == connectors.size()) { --j; } //checks for connector logic string temp = commands.at(i).at(0); string tempconnectors = connectors.at(j); if (temp.compare("exit") == 0) { exit(0); } //forking process to child pid_t pid = fork(); if (pid == 0) { if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1) { if (tempconnectors.compare("&&") == 0) { sentinel = false; } else { sentinel = true; } perror("exec"); } else { if (tempconnectors.compare("||") == 0) { sentinel = false; } } } if (pid > 0) { if (wait(0) == -1) { perror("wait"); } } if (i >= connectors.size()) { sentinel = false; } ++i; ++j; } } } } } //main function, will contain test cases int main() { /* string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf"; vector<string> connectors; vector< vector<string> > cmdline; vector< vector<string> > cmdline2; parseconnect(cmdline, connectors, command); for (int i = 0; i < cmdline.size() - 1; ++i) { cout << cmdline.at(i).at(0); for (int j = i; j < i + 1; ++j) { cout << connectors.at(j); } } cout << cmdline.at(cmdline.size() - 1).at(0) << endl; token(cmdline, cmdline2); for (int i = 0; i < cmdline2.size(); ++i) { for (int j = 0; j < cmdline2.at(i).size(); ++j) { cout << "<" << cmdline2.at(i).at(j) << ">" << endl; } } */ run(); return 0; } <|endoftext|>
<commit_before>//-------------------------------------------------------------------------------------- // Copyright 2015 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #include <windows.h> #include <thread> #include <cstdio> #include "PresentMon.hpp" #include "Util.hpp" #include <mutex> bool g_Quit = false; static std::thread *g_PresentMonThread; static std::mutex *g_ExitMutex; BOOL WINAPI HandlerRoutine( _In_ DWORD dwCtrlType ) { std::lock_guard<std::mutex> lock(*g_ExitMutex); g_Quit = true; if (g_PresentMonThread) { g_PresentMonThread->join(); } return TRUE; } void printHelp() { printf( "command line options:\n" " -captureall: record ALL processes (default).\n" " -process_name [exe name]: record specific process.\n" " -process_id [integer]: record specific process ID.\n" " -output_file [path]: override the default output path.\n" " -etl_file [path]: consume events from an ETL file instead of real-time.\n" " -delay [seconds]: wait before starting to consume events (allowing time for alt+tab)\n" " -timed [seconds]: stop listening and exit after a set amount of time\n" " -no_csv: do not create any output file.\n" " -scroll_toggle: only record events while scroll lock is enabled.\n" ); } int main(int argc, char ** argv) { --argc; ++argv; if (argc == 0) { printHelp(); return 0; } int waitpid = -1; PresentMonArgs args; std::string title_string = "PresentMon"; args.mTargetProcessName = "*"; for (int i = 0; i < argc; ++i) { // 2-component arguments if (i + 1 < argc) { if (!strcmp(argv[i], "-waitpid")) { waitpid = atoi(argv[++i]); continue; } else if (!strcmp(argv[i], "-process_name")) { args.mTargetProcessName = argv[++i]; } else if (!strcmp(argv[i], "-process_id")) { args.mTargetPid = atoi(argv[++i]); } else if (!strcmp(argv[i], "-output_file")) { args.mOutputFileName = argv[++i]; } else if (!strcmp(argv[i], "-etl_file")) { args.mEtlFileName = argv[++i]; } else if (!strcmp(argv[i], "-delay")) { args.mDelay = atoi(argv[++i]); } else if (!strcmp(argv[i], "-timed")) { args.mTimer = atoi(argv[++i]); } } // 1-component args { if (!strcmp(argv[i], "-no_csv")) { args.mOutputFileName = "*"; } else if (!strcmp(argv[i], "-scroll_toggle")) { args.mScrollLockToggle = true; } else if (!strcmp(argv[i], "-?") || !strcmp(argv[i], "-help")) { printHelp(); return 0; } } title_string += ' '; title_string += argv[i]; } if (waitpid >= 0) { WaitForProcess(waitpid); if (!HaveAdministratorPrivileges()) { printf("Elevation process failed. Aborting.\n"); return 0; } } if (!HaveAdministratorPrivileges()) { printf("Process is not running as admin. Attempting to elevate.\n"); RestartAsAdministrator(argc, argv); return 0; } SetConsoleCtrlHandler(HandlerRoutine, TRUE); SetConsoleTitleA(title_string.c_str()); std::mutex exit_mutex; g_ExitMutex = &exit_mutex; // Run PM in a separate thread so we can join it in the CtrlHandler (can't join the main thread) std::thread pm(PresentMonEtw, args); g_PresentMonThread = &pm; while (!g_Quit) { Sleep(100); } // Wait for tracing to finish, to ensure the PM thread closes the session correctly // Prevent races on joining the PM thread between the control handler and the main thread std::lock_guard<std::mutex> lock(exit_mutex); if (g_PresentMonThread->joinable()) { g_PresentMonThread->join(); } return 0; }<commit_msg>add punctuation in new command line help items<commit_after>//-------------------------------------------------------------------------------------- // Copyright 2015 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #include <windows.h> #include <thread> #include <cstdio> #include "PresentMon.hpp" #include "Util.hpp" #include <mutex> bool g_Quit = false; static std::thread *g_PresentMonThread; static std::mutex *g_ExitMutex; BOOL WINAPI HandlerRoutine( _In_ DWORD dwCtrlType ) { std::lock_guard<std::mutex> lock(*g_ExitMutex); g_Quit = true; if (g_PresentMonThread) { g_PresentMonThread->join(); } return TRUE; } void printHelp() { printf( "command line options:\n" " -captureall: record ALL processes (default).\n" " -process_name [exe name]: record specific process.\n" " -process_id [integer]: record specific process ID.\n" " -output_file [path]: override the default output path.\n" " -etl_file [path]: consume events from an ETL file instead of real-time.\n" " -delay [seconds]: wait before starting to consume events (allowing time for alt+tab).\n" " -timed [seconds]: stop listening and exit after a set amount of time.\n" " -no_csv: do not create any output file.\n" " -scroll_toggle: only record events while scroll lock is enabled.\n" ); } int main(int argc, char ** argv) { --argc; ++argv; if (argc == 0) { printHelp(); return 0; } int waitpid = -1; PresentMonArgs args; std::string title_string = "PresentMon"; args.mTargetProcessName = "*"; for (int i = 0; i < argc; ++i) { // 2-component arguments if (i + 1 < argc) { if (!strcmp(argv[i], "-waitpid")) { waitpid = atoi(argv[++i]); continue; } else if (!strcmp(argv[i], "-process_name")) { args.mTargetProcessName = argv[++i]; } else if (!strcmp(argv[i], "-process_id")) { args.mTargetPid = atoi(argv[++i]); } else if (!strcmp(argv[i], "-output_file")) { args.mOutputFileName = argv[++i]; } else if (!strcmp(argv[i], "-etl_file")) { args.mEtlFileName = argv[++i]; } else if (!strcmp(argv[i], "-delay")) { args.mDelay = atoi(argv[++i]); } else if (!strcmp(argv[i], "-timed")) { args.mTimer = atoi(argv[++i]); } } // 1-component args { if (!strcmp(argv[i], "-no_csv")) { args.mOutputFileName = "*"; } else if (!strcmp(argv[i], "-scroll_toggle")) { args.mScrollLockToggle = true; } else if (!strcmp(argv[i], "-?") || !strcmp(argv[i], "-help")) { printHelp(); return 0; } } title_string += ' '; title_string += argv[i]; } if (waitpid >= 0) { WaitForProcess(waitpid); if (!HaveAdministratorPrivileges()) { printf("Elevation process failed. Aborting.\n"); return 0; } } if (!HaveAdministratorPrivileges()) { printf("Process is not running as admin. Attempting to elevate.\n"); RestartAsAdministrator(argc, argv); return 0; } SetConsoleCtrlHandler(HandlerRoutine, TRUE); SetConsoleTitleA(title_string.c_str()); std::mutex exit_mutex; g_ExitMutex = &exit_mutex; // Run PM in a separate thread so we can join it in the CtrlHandler (can't join the main thread) std::thread pm(PresentMonEtw, args); g_PresentMonThread = &pm; while (!g_Quit) { Sleep(100); } // Wait for tracing to finish, to ensure the PM thread closes the session correctly // Prevent races on joining the PM thread between the control handler and the main thread std::lock_guard<std::mutex> lock(exit_mutex); if (g_PresentMonThread->joinable()) { g_PresentMonThread->join(); } return 0; }<|endoftext|>
<commit_before>77a38e8a-2d53-11e5-baeb-247703a38240<commit_msg>77a40f9a-2d53-11e5-baeb-247703a38240<commit_after>77a40f9a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>ffc243f6-585a-11e5-9dfa-6c40088e03e4<commit_msg>ffc8a306-585a-11e5-85d3-6c40088e03e4<commit_after>ffc8a306-585a-11e5-85d3-6c40088e03e4<|endoftext|>
<commit_before>f18021c8-585a-11e5-ae03-6c40088e03e4<commit_msg>f1876a98-585a-11e5-8a0b-6c40088e03e4<commit_after>f1876a98-585a-11e5-8a0b-6c40088e03e4<|endoftext|>
<commit_before>#pragma once #include <vector> #include <set> #include <memory> #include <utility> #include <atomic> #include <mutex> #include <thread> #include <functional> namespace audio_io { /**A physical output.*/ class OutputDevice { }; class OutputDeviceFactory { public: DeviceFactory() = default; virtual ~DeviceFactory(); virtual std::vector<std::string> getOutputNames() = 0; virtual std::vector<int> getOutputMaxChannels() = 0; virtual std::shared_ptr<Device> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) = 0; virtual unsigned int getOutputCount(); virtual std::string getName(); }; }<commit_msg>The empty class OutputDevice must have a virtual destructor<commit_after>#pragma once #include <vector> #include <set> #include <memory> #include <utility> #include <atomic> #include <mutex> #include <thread> #include <functional> namespace audio_io { /**A physical output.*/ class OutputDevice { virtual ~OutputDevice() {} }; class OutputDeviceFactory { public: DeviceFactory() = default; virtual ~DeviceFactory(); virtual std::vector<std::string> getOutputNames() = 0; virtual std::vector<int> getOutputMaxChannels() = 0; virtual std::shared_ptr<Device> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) = 0; virtual unsigned int getOutputCount(); virtual std::string getName(); }; }<|endoftext|>
<commit_before>761c6730-2d53-11e5-baeb-247703a38240<commit_msg>761ce9bc-2d53-11e5-baeb-247703a38240<commit_after>761ce9bc-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>77067942-2d53-11e5-baeb-247703a38240<commit_msg>77070222-2d53-11e5-baeb-247703a38240<commit_after>77070222-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>#pragma once /* * Covariant Script Version Info * * 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. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: mikecovlee@163.com * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,0,0,6 #define COVSCRIPT_VERSION_STR "3.0.0 Pantholops hodgsonii(Unstable) Build 6" #define COVSCRIPT_STD_VERSION 190101 #define COVSCRIPT_ABI_VERSION 190101 #if defined(_WIN32) || defined(WIN32) #define COVSCRIPT_PLATFORM_WIN32 #endif <commit_msg>Release: 3.0.0<commit_after>#pragma once /* * Covariant Script Version Info * * 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. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: mikecovlee@163.com * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,0,0,6 #define COVSCRIPT_VERSION_STR "3.0.0 Pantholops hodgsonii(Stable) Build 6" #define COVSCRIPT_STD_VERSION 190101 #define COVSCRIPT_ABI_VERSION 190101 #if defined(_WIN32) || defined(WIN32) #define COVSCRIPT_PLATFORM_WIN32 #endif <|endoftext|>
<commit_before>8e9fac42-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac43-2d14-11e5-af21-0401358ea401<commit_after>8e9fac43-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>aeea4435-327f-11e5-8384-9cf387a8033e<commit_msg>aef1fd3d-327f-11e5-8456-9cf387a8033e<commit_after>aef1fd3d-327f-11e5-8456-9cf387a8033e<|endoftext|>
<commit_before>7c411321-2e4f-11e5-81ed-28cfe91dbc4b<commit_msg>7c48d2c2-2e4f-11e5-9a0d-28cfe91dbc4b<commit_after>7c48d2c2-2e4f-11e5-9a0d-28cfe91dbc4b<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { namespace impl { namespace vec { /*! * \brief Standard implementation of a 2D 'valid' convolution C = I * K * \param input The input matrix * \param kernel The kernel matrix * \param conv The output matrix */ template <typename I, typename K, typename C> void conv2_valid_flipped(const I& input, const K& kernel, C&& conv, size_t s1, size_t s2, size_t p1, size_t p2) { using T = value_t<I>; const auto n1 = etl::dim<0>(input); const auto n2 = etl::dim<1>(input); if(p1 || p2){ const auto o1 = n1 + 2 * p1; const auto o2 = n2 + 2 * p2; etl::dyn_matrix<T> padded_matrix(o1, o2); for (size_t i = 0; i < n1; ++i) { for(size_t j = 0; j < n2; ++j){ padded_matrix[(i + p1) * o2 + p2 + j] = input[i * n2 + j]; } } conv2_valid_flipped(padded_matrix, kernel, conv, s1, s2, 0, 0); return; } const auto k1 = etl::dim<0>(kernel); const auto k2 = etl::dim<1>(kernel); const auto c1 = etl::dim<0>(conv); const auto c2 = etl::dim<1>(conv); const auto R = std::min(k1, c1); // Max number of kernels per line of input conv = 0; // Primary steps for(size_t i = 0; i < k1 - 1; ++i){ const auto M = std::min(i + 1, R); for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto k_i = i - m; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i * s1, j * s1 + k) * kernel(k_i, k); } conv(m,j) += value; } } } // Main steps for(size_t i = k1 - 1; i < c1; ++i){ const auto M = R; for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto c_i = n1 - 1 - m - i; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i * s1, j * s1 + k) * kernel(m, k); } conv(c_i, j) += value; } } } // Secondary steps for(size_t i = c1; i < n1; ++i){ auto M = std::min(n1 - i, R); for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto c_i = m + i - k1 + 1; const auto k_i = M - m - c1 + i; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i * s1, j * s1 + k) * kernel(k_i, k); } conv(c_i, j) += value; } } } } } //end of namespace vec } //end of namespace impl } //end of namespace etl <commit_msg>Review stride<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { namespace impl { namespace vec { /*! * \brief Standard implementation of a 2D 'valid' convolution C = I * K * \param input The input matrix * \param kernel The kernel matrix * \param conv The output matrix */ template <typename I, typename K, typename C> void conv2_valid_flipped(const I& input, const K& kernel, C&& conv, size_t s1, size_t s2, size_t p1, size_t p2) { using T = value_t<I>; const auto n1 = etl::dim<0>(input); const auto n2 = etl::dim<1>(input); const auto k1 = etl::dim<0>(kernel); const auto k2 = etl::dim<1>(kernel); const auto c1 = etl::dim<0>(conv); const auto c2 = etl::dim<1>(conv); if(cpp_unlikely(p1 || p2)){ const auto o1 = n1 + 2 * p1; const auto o2 = n2 + 2 * p2; etl::dyn_matrix<T> padded_matrix(o1, o2); for (size_t i = 0; i < n1; ++i) { for(size_t j = 0; j < n2; ++j){ padded_matrix[(i + p1) * o2 + p2 + j] = input[i * n2 + j]; } } conv2_valid_flipped(padded_matrix, kernel, conv, s1, s2, 0, 0); return; } if(cpp_unlikely(s1 > 1 || s2 > 1)){ etl::dyn_matrix<T> tmp_result(n1 - k1 + 1, n2 - k2 + 1); conv2_valid_flipped(input, kernel, tmp_result, 1, 1, 0, 0); // Strided copy of the large result into the small result for (std::size_t i = 0; i < c1; ++i) { for (std::size_t j = 0; j < c2; ++j) { conv(i, j) = tmp_result(i * s1, j * s2); } } return; } const auto R = std::min(k1, c1); // Max number of kernels per line of input conv = T(0); // Primary steps for(size_t i = 0; i < k1 - 1; ++i){ const auto M = std::min(i + 1, R); for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto k_i = i - m; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i, j + k) * kernel(k_i, k); } conv(m,j) += value; } } } // Main steps for(size_t i = k1 - 1; i < c1; ++i){ const auto M = R; for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto c_i = n1 - 1 - m - i; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i, j + k) * kernel(m, k); } conv(c_i, j) += value; } } } // Secondary steps for(size_t i = c1; i < n1; ++i){ auto M = std::min(n1 - i, R); for(size_t j = 0; j < c2; ++j){ for(size_t m = 0; m < M; ++m){ const auto c_i = m + i - k1 + 1; const auto k_i = M - m - c1 + i; T value = 0; for(size_t k = 0; k < k2; ++k){ value += input(i, j + k) * kernel(k_i, k); } conv(c_i, j) += value; } } } } } //end of namespace vec } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>c650c3a8-2e4e-11e5-a1aa-28cfe91dbc4b<commit_msg>c658f9e1-2e4e-11e5-8cb3-28cfe91dbc4b<commit_after>c658f9e1-2e4e-11e5-8cb3-28cfe91dbc4b<|endoftext|>
<commit_before>ecb1e86b-327f-11e5-b461-9cf387a8033e<commit_msg>ecb83257-327f-11e5-bc76-9cf387a8033e<commit_after>ecb83257-327f-11e5-bc76-9cf387a8033e<|endoftext|>
<commit_before>fefce8ec-585a-11e5-9314-6c40088e03e4<commit_msg>ff03d81c-585a-11e5-ab9e-6c40088e03e4<commit_after>ff03d81c-585a-11e5-ab9e-6c40088e03e4<|endoftext|>
<commit_before>4c18c575-2e4f-11e5-a94d-28cfe91dbc4b<commit_msg>4c1fa4c2-2e4f-11e5-9573-28cfe91dbc4b<commit_after>4c1fa4c2-2e4f-11e5-9573-28cfe91dbc4b<|endoftext|>
<commit_before>8fd04917-2d14-11e5-af21-0401358ea401<commit_msg>8fd04918-2d14-11e5-af21-0401358ea401<commit_after>8fd04918-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>13c2af02-2e4f-11e5-bc30-28cfe91dbc4b<commit_msg>13ca5447-2e4f-11e5-9f85-28cfe91dbc4b<commit_after>13ca5447-2e4f-11e5-9f85-28cfe91dbc4b<|endoftext|>
<commit_before>/* checkver.cpp ஢ઠ ॣ樨 */ /* Revision: 1.03 30.03.2001 $ */ /* Modify: 30.03.2001 SVS ! ... 砫 ⮣, 㦭 뫮 ਫ ப 室... 稫 ⠪ ᧢ "xUSSR ॣ" :-) 21.02.2001 IS ! Opt.TabSize -> Opt.EdOpt.TabSize 11.07.2000 SVS ! 樨 BC & VC 25.06.2000 SVS ! ⮢ Master Copy ! 뤥 ⢥ ᠬ⥫쭮 */ #include "headers.hpp" #pragma hdrstop /* $ 30.06.2000 IS ⠭ */ #include "internalheaders.hpp" /* IS $ */ unsigned char MyName[]={ 'E'^0x50,'u'^0x51,'g'^0x52,'e'^0x53,'n'^0x54,'e'^0x55, ' '^0x56,'R'^0x57,'o'^0x58,'s'^0x59,'h'^0x5a,'a'^0x5b,'l'^0x5c}; static char *GetDaysName(int wDayOfWeek) { static unsigned char *Days[7]={ {"\x0C\xF7\xF8\xB6\xF2\xB9\xFF\xBA\xF9\xF0\xB2\xFA"}, // "ᥭ", {"\x0c\xFA\xF8\xFA\xFD\xFD\xFF\xF0\xB0\xF0\xF6\xF5"}, // "쭨", {"\x08\xF7\xB4\xF9\xB8\xF4\xF2\xF1"}, // "୨", {"\x06\xB4\xB6\xF2\xFC\xF9"}, // "।", {"\x08\xB2\xF3\xB5\xFA\xFC\xBA\xF8"}, // "⢥", {"\x08\xFA\xB9\xB5\xF5\xF1\xBC\xFB"}, // "⭨", {"\x08\xB4\xB5\xF6\xF9\xF7\xB8\xFB"}, // "㡡" }; if(Days[0][0]) { int I, J; for(J=0; J < 7; ++J) { unsigned char B=0x55; for(I=1; I < Days[J][0]; ++I, ++B) Days[J][I]^=B; } Days[0][0]=0x00; } return &Days[wDayOfWeek][1]; } static char *GetxUSSRRegName() { // "xUSSR ॣ" static unsigned char xUSSRRegName[]="\x12\x2D\x03\x04\x0B\x0B\x7A\xBB\xF9\xFE\xF6\xBE\x82\x81\xC2\x85\xCC\x8A"; if(xUSSRRegName[0]) { unsigned char B=0x55; for(int I=1; I < xUSSRRegName[0]; ++I, ++B) xUSSRRegName[I]^=B; xUSSRRegName[0]=0; } return xUSSRRegName+1; } #ifndef _MSC_VER #pragma warn -par #endif void _cdecl CheckVersion(void *Param) { Sleep(1000); if (!RegVer) { Opt.EdOpt.TabSize=8; Opt.ViewerEditorClock=0; } _endthread(); } #ifndef _MSC_VER #pragma warn +par #endif void Register() { static struct DialogData RegDlgData[]= { DI_DOUBLEBOX,3,1,72,8,0,0,0,0,(char *)MRegTitle, DI_TEXT,5,2,0,0,0,0,0,0,(char *)MRegUser, DI_EDIT,5,3,70,3,1,0,0,0,"", DI_TEXT,5,4,0,0,0,0,0,0,(char *)MRegCode, DI_EDIT,5,5,70,5,0,0,0,0,"", DI_TEXT,3,6,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"", DI_BUTTON,0,7,0,0,0,0,DIF_CENTERGROUP,1,(char *)MOk, DI_BUTTON,0,7,0,0,0,0,DIF_CENTERGROUP,0,(char *)MCancel }; MakeDialogItems(RegDlgData,RegDlg); Dialog Dlg(RegDlg,sizeof(RegDlg)/sizeof(RegDlg[0])); Dlg.SetPosition(-1,-1,76,10); Dlg.SetHelp("Register"); Dlg.Process(); if (Dlg.GetExitCode()!=6) return; char RegName[256],RegCode[256],RegData[256]; strcpy(RegName,RegDlg[2].Data); strcpy(RegCode,RegDlg[4].Data); int Length=strlen(RegName); if (*RegName==0 || *RegCode==0) return; unsigned char Xor=17; int I; for (I=0;RegName[I]!=0;I++) Xor^=RegName[I]; int xUSSR=FALSE; if (strcmp(RegName,GetxUSSRRegName())==0) { SYSTEMTIME st; GetLocalTime(&st); if (strcmp(RegCode,GetDaysName(st.wDayOfWeek))==0) xUSSR=TRUE; } if (!xUSSR && (Length<4 || (Xor & 0xf)!=ToHex(RegCode[0]) || ((~(Xor>>4))&0xf)!=ToHex(RegCode[3]))) { Message(MSG_WARNING,1,MSG(MError),MSG(MRegFailed),MSG(MOk)); return; } Dlg.Hide(); RegData[0]=clock(); RegData[1]=strlen(RegName); RegData[2]=strlen(RegCode); strcpy(RegData+3,RegName); strcpy(RegData+RegData[1]+3,RegCode); int Size=RegData[1]+RegData[2]+3; for (I=0;I<Size;I++) RegData[I]^=I+7; for (I=1;I<Size;I++) RegData[I]^=RegData[0]; SetRegRootKey(HKEY_LOCAL_MACHINE); char SaveKey[512]; strcpy(SaveKey,Opt.RegRoot); strcpy(Opt.RegRoot,"Software\\Far"); SetRegKey("Registration","Data",(BYTE *)RegData,Size); strcpy(Opt.RegRoot,SaveKey); SetRegRootKey(HKEY_CURRENT_USER); Message(0,1,MSG(MRegTitle),MSG(MRegThanks),MSG(MOk)); } void _cdecl CheckReg(void *Param) { struct RegInfo *Reg=(struct RegInfo *)Param; char RegName[256],RegCode[256],RegData[256]; DWORD Size=sizeof(RegData); SetRegRootKey(HKEY_LOCAL_MACHINE); char SaveKey[512]; strcpy(SaveKey,Opt.RegRoot); strcpy(Opt.RegRoot,"Software\\Far"); Size=GetRegKey("Registration","Data",(BYTE *)RegData,NULL,Size); strcpy(Opt.RegRoot,SaveKey); SetRegRootKey(HKEY_CURRENT_USER); memset(Reg,0,sizeof(*Reg)); if (Size==0) RegVer=0; else { int I; for (I=1;I<Size;I++) RegData[I]^=RegData[0]; for (I=0;I<Size;I++) RegData[I]^=I+7; strncpy(RegName,RegData+3,RegData[1]); RegName[RegData[1]]=0; strncpy(RegCode,RegData+RegData[1]+3,RegData[2]); RegCode[RegData[2]]=0; RegVer=1; unsigned char Xor=17; for (I=0;RegName[I]!=0;I++) Xor^=RegName[I]; if ((Xor & 0xf)!=ToHex(RegCode[0]) || ((~(Xor>>4))&0xf)!=ToHex(RegCode[3])) RegVer=0; if (strcmp(RegName,GetxUSSRRegName())==0) RegVer=3; strcpy(Reg->RegCode,RegCode); strcpy(Reg->RegName,RegName); strcpy(::RegName,RegName); } Reg->Done=TRUE; _endthread(); } char ToHex(char Ch) { if (Ch>='0' && Ch<='9') return(Ch-'0'); if (Ch>='a' && Ch<='z') return(Ch-'a'+10); if (Ch>='A' && Ch<='Z') return(Ch-'A'+10); return(0); } #ifndef _MSC_VER #pragma warn -par #endif void _cdecl ErrRegFn(void *Param) { if (RegVer!=3) { Message(0,1,MSG(MRegTitle),MSG(MRegFailed),MSG(MOk)); RegVer=0; } _endthread(); } #ifndef _MSC_VER #pragma warn +par #endif <commit_msg>FAR patch 00551.checkver.cpp Дата : 03.04.2001 Сделал : Valentin Skirdin Описание : Ах этот VC ;-) Измененные файлы : checkver.cpp Новые файлы : Состав : 00551.checkver.cpp.txt checkver.cpp.551.diff Основан на патче : 550 Дополнение :<commit_after>/* checkver.cpp ஢ઠ ॣ樨 */ /* Revision: 1.04 03.04.2001 $ */ /* Modify: 03.04.2001 SVS - ஡ 樥 VC 30.03.2001 SVS ! ... 砫 ⮣, 㦭 뫮 ਫ ப 室... 稫 ⠪ ᧢ "xUSSR ॣ" :-) 21.02.2001 IS ! Opt.TabSize -> Opt.EdOpt.TabSize 11.07.2000 SVS ! 樨 BC & VC 25.06.2000 SVS ! ⮢ Master Copy ! 뤥 ⢥ ᠬ⥫쭮 */ #include "headers.hpp" #pragma hdrstop /* $ 30.06.2000 IS ⠭ */ #include "internalheaders.hpp" /* IS $ */ unsigned char MyName[]={ 'E'^0x50,'u'^0x51,'g'^0x52,'e'^0x53,'n'^0x54,'e'^0x55, ' '^0x56,'R'^0x57,'o'^0x58,'s'^0x59,'h'^0x5a,'a'^0x5b,'l'^0x5c}; static const char *GetDaysName(int wDayOfWeek) { static unsigned char *Days[7]={ {(BYTE*)"\x0C\xF7\xF8\xB6\xF2\xB9\xFF\xBA\xF9\xF0\xB2\xFA"}, // "ᥭ", {(BYTE*)"\x0c\xFA\xF8\xFA\xFD\xFD\xFF\xF0\xB0\xF0\xF6\xF5"}, // "쭨", {(BYTE*)"\x08\xF7\xB4\xF9\xB8\xF4\xF2\xF1"}, // "୨", {(BYTE*)"\x06\xB4\xB6\xF2\xFC\xF9"}, // "।", {(BYTE*)"\x08\xB2\xF3\xB5\xFA\xFC\xBA\xF8"}, // "⢥", {(BYTE*)"\x08\xFA\xB9\xB5\xF5\xF1\xBC\xFB"}, // "⭨", {(BYTE*)"\x08\xB4\xB5\xF6\xF9\xF7\xB8\xFB"}, // "㡡" }; if(Days[0][0]) { int I, J; for(J=0; J < 7; ++J) { unsigned char B=0x55; for(I=1; I < Days[J][0]; ++I, ++B) Days[J][I]^=B; } Days[0][0]=0x00; } return (const char*)&Days[wDayOfWeek][1]; } static const char *GetxUSSRRegName() { // "xUSSR ॣ" static unsigned char *xUSSRRegName=(BYTE*)"\x12\x2D\x03\x04\x0B\x0B\x7A\xBB\xF9\xFE\xF6\xBE\x82\x81\xC2\x85\xCC\x8A"; if(xUSSRRegName[0]) { unsigned char B=0x55; for(int I=1; I < xUSSRRegName[0]; ++I, ++B) xUSSRRegName[I]^=B; xUSSRRegName[0]=0; } return (const char*)xUSSRRegName+1; } #ifndef _MSC_VER #pragma warn -par #endif void _cdecl CheckVersion(void *Param) { Sleep(1000); if (!RegVer) { Opt.EdOpt.TabSize=8; Opt.ViewerEditorClock=0; } _endthread(); } #ifndef _MSC_VER #pragma warn +par #endif void Register() { static struct DialogData RegDlgData[]= { DI_DOUBLEBOX,3,1,72,8,0,0,0,0,(char *)MRegTitle, DI_TEXT,5,2,0,0,0,0,0,0,(char *)MRegUser, DI_EDIT,5,3,70,3,1,0,0,0,"", DI_TEXT,5,4,0,0,0,0,0,0,(char *)MRegCode, DI_EDIT,5,5,70,5,0,0,0,0,"", DI_TEXT,3,6,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"", DI_BUTTON,0,7,0,0,0,0,DIF_CENTERGROUP,1,(char *)MOk, DI_BUTTON,0,7,0,0,0,0,DIF_CENTERGROUP,0,(char *)MCancel }; MakeDialogItems(RegDlgData,RegDlg); Dialog Dlg(RegDlg,sizeof(RegDlg)/sizeof(RegDlg[0])); Dlg.SetPosition(-1,-1,76,10); Dlg.SetHelp("Register"); Dlg.Process(); if (Dlg.GetExitCode()!=6) return; char RegName[256],RegCode[256],RegData[256]; strcpy(RegName,RegDlg[2].Data); strcpy(RegCode,RegDlg[4].Data); int Length=strlen(RegName); if (*RegName==0 || *RegCode==0) return; unsigned char Xor=17; int I; for (I=0;RegName[I]!=0;I++) Xor^=RegName[I]; int xUSSR=FALSE; if (strcmp(RegName,GetxUSSRRegName())==0) { SYSTEMTIME st; GetLocalTime(&st); if (strcmp(RegCode,GetDaysName(st.wDayOfWeek))==0) xUSSR=TRUE; } if (!xUSSR && (Length<4 || (Xor & 0xf)!=ToHex(RegCode[0]) || ((~(Xor>>4))&0xf)!=ToHex(RegCode[3]))) { Message(MSG_WARNING,1,MSG(MError),MSG(MRegFailed),MSG(MOk)); return; } Dlg.Hide(); RegData[0]=clock(); RegData[1]=strlen(RegName); RegData[2]=strlen(RegCode); strcpy(RegData+3,RegName); strcpy(RegData+RegData[1]+3,RegCode); int Size=RegData[1]+RegData[2]+3; for (I=0;I<Size;I++) RegData[I]^=I+7; for (I=1;I<Size;I++) RegData[I]^=RegData[0]; SetRegRootKey(HKEY_LOCAL_MACHINE); char SaveKey[512]; strcpy(SaveKey,Opt.RegRoot); strcpy(Opt.RegRoot,"Software\\Far"); SetRegKey("Registration","Data",(BYTE *)RegData,Size); strcpy(Opt.RegRoot,SaveKey); SetRegRootKey(HKEY_CURRENT_USER); Message(0,1,MSG(MRegTitle),MSG(MRegThanks),MSG(MOk)); } void _cdecl CheckReg(void *Param) { struct RegInfo *Reg=(struct RegInfo *)Param; char RegName[256],RegCode[256],RegData[256]; DWORD Size=sizeof(RegData); SetRegRootKey(HKEY_LOCAL_MACHINE); char SaveKey[512]; strcpy(SaveKey,Opt.RegRoot); strcpy(Opt.RegRoot,"Software\\Far"); Size=GetRegKey("Registration","Data",(BYTE *)RegData,NULL,Size); strcpy(Opt.RegRoot,SaveKey); SetRegRootKey(HKEY_CURRENT_USER); memset(Reg,0,sizeof(*Reg)); if (Size==0) RegVer=0; else { int I; for (I=1;I<Size;I++) RegData[I]^=RegData[0]; for (I=0;I<Size;I++) RegData[I]^=I+7; strncpy(RegName,RegData+3,RegData[1]); RegName[RegData[1]]=0; strncpy(RegCode,RegData+RegData[1]+3,RegData[2]); RegCode[RegData[2]]=0; RegVer=1; unsigned char Xor=17; for (I=0;RegName[I]!=0;I++) Xor^=RegName[I]; if ((Xor & 0xf)!=ToHex(RegCode[0]) || ((~(Xor>>4))&0xf)!=ToHex(RegCode[3])) RegVer=0; if (strcmp(RegName,GetxUSSRRegName())==0) RegVer=3; strcpy(Reg->RegCode,RegCode); strcpy(Reg->RegName,RegName); strcpy(::RegName,RegName); } Reg->Done=TRUE; _endthread(); } char ToHex(char Ch) { if (Ch>='0' && Ch<='9') return(Ch-'0'); if (Ch>='a' && Ch<='z') return(Ch-'a'+10); if (Ch>='A' && Ch<='Z') return(Ch-'A'+10); return(0); } #ifndef _MSC_VER #pragma warn -par #endif void _cdecl ErrRegFn(void *Param) { if (RegVer!=3) { Message(0,1,MSG(MRegTitle),MSG(MRegFailed),MSG(MOk)); RegVer=0; } _endthread(); } #ifndef _MSC_VER #pragma warn +par #endif <|endoftext|>
<commit_before>77d1ce26-2d53-11e5-baeb-247703a38240<commit_msg>77d25274-2d53-11e5-baeb-247703a38240<commit_after>77d25274-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>ca1a746e-2747-11e6-aeea-e0f84713e7b8<commit_msg>updated some files<commit_after>ca24c770-2747-11e6-be34-e0f84713e7b8<|endoftext|>
<commit_before>062b04e6-2748-11e6-8dcc-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>065b246e-2748-11e6-bc09-e0f84713e7b8<|endoftext|>
<commit_before>8fd04949-2d14-11e5-af21-0401358ea401<commit_msg>8fd0494a-2d14-11e5-af21-0401358ea401<commit_after>8fd0494a-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f2bb9a6e-327f-11e5-8cf0-9cf387a8033e<commit_msg>f2c19735-327f-11e5-89ca-9cf387a8033e<commit_after>f2c19735-327f-11e5-89ca-9cf387a8033e<|endoftext|>
<commit_before>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #define TORRENT_USE_ICONV 0 // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #define TORRENT_USE_ICONV 0 #endif // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_ICONV 0 #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>don't use posix_fallocate on BSD<commit_after>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #define TORRENT_USE_ICONV 0 // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #define TORRENT_USE_ICONV 0 #endif #define TORRENT_HAS_FALLOCATE 0 // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 #define TORRENT_HAS_FALLOCATE 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_ICONV 0 #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>e7ac2ab8-2e4e-11e5-b334-28cfe91dbc4b<commit_msg>e7b5bd00-2e4e-11e5-8f9e-28cfe91dbc4b<commit_after>e7b5bd00-2e4e-11e5-8f9e-28cfe91dbc4b<|endoftext|>
<commit_before>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # define TORRENT_DEPRECATED __attribute__ ((deprecated)) // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) // ======= GENERIC COMPILER ========= #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 #define TORRENT_USE_I2P 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 0 // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #ifdef TORRENT_WINDOWS // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>fix some error/warning strings typos<commit_after>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # define TORRENT_DEPRECATED __attribute__ ((deprecated)) // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) // ======= GENERIC COMPILER ========= #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 #define TORRENT_USE_I2P 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 0 // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #ifdef TORRENT_WINDOWS // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR #error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators #endif #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // SunPRO seems to have an overly-strict // definition of POD types and doesn't // seem to allow boost::array in unions #define TORRENT_BROKEN_UNIONS 1 // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) // 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup #pragma warning(disable: 4996) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #endif // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 0 #endif #endif #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_IFADDRS 1 #define TORRENT_USE_SYSCTL 1 #define TORRENT_USE_IFCONF 1 // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX #define TORRENT_USE_IFADDRS 1 #define TORRENT_USE_NETLINK 1 #define TORRENT_USE_IFCONF 1 #define TORRENT_HAS_SALEN 0 // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 1 #endif #define TORRENT_USE_RLIMIT 0 #define TORRENT_USE_NETLINK 0 #define TORRENT_USE_GETADAPTERSADDRESSES 1 #define TORRENT_HAS_SALEN 0 #define TORRENT_USE_GETIPFORWARDTABLE 1 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS #ifndef TORRENT_USE_GETIPFORWARDTABLE #define TORRENT_USE_GETIPFORWARDTABLE 1 #endif #define TORRENT_USE_GETADAPTERSADDRESSES 1 #define TORRENT_HAS_SALEN 0 // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 1 #endif #define TORRENT_USE_RLIMIT 0 #define TORRENT_HAS_FALLOCATE 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS #define TORRENT_COMPLETE_TYPES_REQUIRED 1 #define TORRENT_USE_IFCONF 1 // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #endif #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #ifndef TORRENT_HAS_SALEN #define TORRENT_HAS_SALEN 1 #endif #ifndef TORRENT_USE_GETADAPTERSADDRESSES #define TORRENT_USE_GETADAPTERSADDRESSES 0 #endif #ifndef TORRENT_USE_NETLINK #define TORRENT_USE_NETLINK 0 #endif #ifndef TORRENT_USE_SYSCTL #define TORRENT_USE_SYSCTL 0 #endif #ifndef TORRENT_USE_GETIPFORWARDTABLE #define TORRENT_USE_GETIPFORWARDTABLE 0 #endif #ifndef TORRENT_USE_LOCALE #define TORRENT_USE_LOCALE 0 #endif #ifndef TORRENT_BROKEN_UNIONS #define TORRENT_BROKEN_UNIONS 0 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_COMPLETE_TYPES_REQUIRED #define TORRENT_COMPLETE_TYPES_REQUIRED 0 #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IFADDRS #define TORRENT_USE_IFADDRS 0 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #ifndef TORRENT_HAS_STRDUP #define TORRENT_HAS_STRDUP 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif #if TORRENT_BROKEN_UNIONS #define TORRENT_UNION struct #else #define TORRENT_UNION union #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #if !TORRENT_HAS_STRDUP inline char* strdup(char const* str) { if (str == 0) return 0; char* tmp = (char*)malloc(strlen(str) + 1); if (tmp == 0) return 0; strcpy(tmp, str); return tmp; } #endif // for non-exception builds #ifdef BOOST_NO_EXCEPTIONS #define TORRENT_TRY if (true) #define TORRENT_CATCH(x) else if (false) #define TORRENT_DECLARE_DUMMY(x, y) x y #else #define TORRENT_TRY try #define TORRENT_CATCH(x) catch(x) #define TORRENT_DECLARE_DUMMY(x, y) #endif // BOOST_NO_EXCEPTIONS #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>fix minor mingw issue<commit_after>/* Copyright (c) 2005, 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_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR #error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators #endif #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _MSC_VER #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // SunPRO seems to have an overly-strict // definition of POD types and doesn't // seem to allow boost::array in unions #define TORRENT_BROKEN_UNIONS 1 // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) // 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup #pragma warning(disable: 4996) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #endif // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 0 #endif #endif #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_IFADDRS 1 #define TORRENT_USE_SYSCTL 1 #define TORRENT_USE_IFCONF 1 // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX #define TORRENT_USE_IFADDRS 1 #define TORRENT_USE_NETLINK 1 #define TORRENT_USE_IFCONF 1 #define TORRENT_HAS_SALEN 0 // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 1 #endif #define TORRENT_USE_RLIMIT 0 #define TORRENT_USE_NETLINK 0 #define TORRENT_USE_GETADAPTERSADDRESSES 1 #define TORRENT_HAS_SALEN 0 #define TORRENT_USE_GETIPFORWARDTABLE 1 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS #ifndef TORRENT_USE_GETIPFORWARDTABLE #define TORRENT_USE_GETIPFORWARDTABLE 1 #endif #define TORRENT_USE_GETADAPTERSADDRESSES 1 #define TORRENT_HAS_SALEN 0 // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #define TORRENT_USE_LOCALE 1 #endif #define TORRENT_USE_RLIMIT 0 #define TORRENT_HAS_FALLOCATE 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS #define TORRENT_COMPLETE_TYPES_REQUIRED 1 #define TORRENT_USE_IFCONF 1 // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 0 #endif #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #ifndef TORRENT_HAS_SALEN #define TORRENT_HAS_SALEN 1 #endif #ifndef TORRENT_USE_GETADAPTERSADDRESSES #define TORRENT_USE_GETADAPTERSADDRESSES 0 #endif #ifndef TORRENT_USE_NETLINK #define TORRENT_USE_NETLINK 0 #endif #ifndef TORRENT_USE_SYSCTL #define TORRENT_USE_SYSCTL 0 #endif #ifndef TORRENT_USE_GETIPFORWARDTABLE #define TORRENT_USE_GETIPFORWARDTABLE 0 #endif #ifndef TORRENT_USE_LOCALE #define TORRENT_USE_LOCALE 0 #endif #ifndef TORRENT_BROKEN_UNIONS #define TORRENT_BROKEN_UNIONS 0 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_COMPLETE_TYPES_REQUIRED #define TORRENT_COMPLETE_TYPES_REQUIRED 0 #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IFADDRS #define TORRENT_USE_IFADDRS 0 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #ifndef TORRENT_HAS_STRDUP #define TORRENT_HAS_STRDUP 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif #if TORRENT_BROKEN_UNIONS #define TORRENT_UNION struct #else #define TORRENT_UNION union #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #if !TORRENT_HAS_STRDUP inline char* strdup(char const* str) { if (str == 0) return 0; char* tmp = (char*)malloc(strlen(str) + 1); if (tmp == 0) return 0; strcpy(tmp, str); return tmp; } #endif // for non-exception builds #ifdef BOOST_NO_EXCEPTIONS #define TORRENT_TRY if (true) #define TORRENT_CATCH(x) else if (false) #define TORRENT_DECLARE_DUMMY(x, y) x y #else #define TORRENT_TRY try #define TORRENT_CATCH(x) catch(x) #define TORRENT_DECLARE_DUMMY(x, y) #endif // BOOST_NO_EXCEPTIONS #endif // TORRENT_CONFIG_HPP_INCLUDED <|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: urlparameter.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _URLPARAMETER_HXX_ #define _URLPARAMETER_HXX_ #include <rtl/ustring.hxx> #include <rtl/string.hxx> #include <com/sun/star/ucb/IllegalIdentifierException.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/io/XActiveDataSink.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/ucb/Command.hpp> namespace chelp { class Databases; class DbtToStringConverter { public: DbtToStringConverter( const sal_Char* ptr,sal_Int32 len ) : m_len( len ), m_ptr( ptr ) { } rtl::OUString getHash() { if( m_ptr ) { sal_Int32 sizeOfFile = ( sal_Int32 ) m_ptr[0]; rtl::OUString Hash( m_ptr+1,sizeOfFile,RTL_TEXTENCODING_UTF8 ); sal_Int32 idx; if( ( idx = Hash.indexOf( sal_Unicode( '#' ) ) ) != -1 ) return Hash.copy( 1+idx ); } return rtl::OUString(); } rtl::OUString getFile() { if( ! m_ptr ) return rtl::OUString(); sal_Int32 sizeOfFile = ( sal_Int32 ) m_ptr[0]; rtl::OUString File( m_ptr+1,sizeOfFile,RTL_TEXTENCODING_UTF8 ); sal_Int32 idx; if( ( idx = File.indexOf( sal_Unicode( '#' ) ) ) != -1 ) return File.copy( 0,idx ); else return File; } rtl::OUString getDatabase() { if( ! m_ptr ) return rtl::OUString(); sal_Int32 sizeOfDatabase = ( int ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ]; return rtl::OUString( m_ptr + 2 + ( sal_Int32 ) m_ptr[0],sizeOfDatabase,RTL_TEXTENCODING_UTF8 ); } rtl::OUString getTitle() { if( ! m_ptr ) // || getHash().getLength() ) return rtl::OUString(); sal_Int32 sizeOfTitle = ( sal_Int32 ) m_ptr[ 2 + m_ptr[0] + ( sal_Int32 ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ] ]; return rtl::OUString( m_ptr + 3 + m_ptr[0] + ( sal_Int32 ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ], sizeOfTitle, RTL_TEXTENCODING_UTF8 ); } private: sal_Int32 m_len; const sal_Char* m_ptr; }; class URLParameter { public: URLParameter( const rtl::OUString& aURL, Databases* pDatabases ) throw( com::sun::star::ucb::IllegalIdentifierException ); URLParameter( const rtl::OUString& aURL, const rtl::OUString& aDefaultLanguage, Databases* pDatabases ) throw( com::sun::star::ucb::IllegalIdentifierException ); bool isPicture() { return m_aModule.compareToAscii("picture") == 0; } bool isActive() { return m_aActive.getLength() > 0 && m_aActive.compareToAscii( "true" ) == 0; } bool isQuery() { return m_aId.compareToAscii("") == 0 && m_aQuery.compareToAscii("") != 0; } bool isEntryForModule() { return m_aId.compareToAscii("start") == 0 || m_bStart; } bool isFile() { return m_aId.compareToAscii( "" ) != 0; } bool isModule() { return m_aId.compareToAscii("") == 0 && m_aModule.compareToAscii("") != 0; } bool isRoot() { return m_aModule.compareToAscii("") == 0; } bool isErrorDocument(); rtl::OUString get_url() { return m_aURL; } rtl::OUString get_id(); rtl::OUString get_tag(); // Not called for an directory rtl::OUString get_path() { return get_the_path(); } rtl::OUString get_eid() { return m_aEid; } rtl::OUString get_title(); rtl::OUString get_jar() { return get_the_jar(); } // BerkeleyDb rtl::OUString get_module() { return m_aModule; } rtl::OUString get_dbpar() { if( m_aDbPar.getLength() ) return m_aDbPar; else return m_aModule; } rtl::OUString get_prefix() { return m_aPrefix; } rtl::OUString get_language(); rtl::OUString get_device() { return m_aDevice; } rtl::OUString get_program(); rtl::OUString get_query() { return m_aQuery; } rtl::OUString get_scope() { return m_aScope; } rtl::OUString get_system() { return m_aSystem; } sal_Int32 get_hitCount() { return m_nHitCount; } rtl::OString getByName( const char* par ); void open( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment, const com::sun::star::uno::Reference< com::sun::star::io::XActiveDataSink >& xDataSink ); void open( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment, const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xDataSink ); private: Databases* m_pDatabases; bool m_bBerkeleyRead; bool m_bStart; bool m_bUseDB; rtl::OUString m_aURL; rtl::OUString m_aTag; rtl::OUString m_aId; rtl::OUString m_aPath; rtl::OUString m_aModule; rtl::OUString m_aTitle; rtl::OUString m_aJar; rtl::OUString m_aEid; rtl::OUString m_aDbPar; rtl::OUString m_aDefaultLanguage; rtl::OUString m_aLanguage; rtl::OUString m_aPrefix; rtl::OUString m_aDevice; rtl::OUString m_aProgram; rtl::OUString m_aSystem; rtl::OUString m_aActive; rtl::OUString m_aQuery; rtl::OUString m_aScope; rtl::OUString m_aExpr; sal_Int32 m_nHitCount; // The default maximum hitcount // private methods void init( bool bDefaultLanguageIsInitialized ); rtl::OUString get_the_tag(); rtl::OUString get_the_path(); rtl::OUString get_the_title(); rtl::OUString get_the_jar(); void readBerkeley(); void parse() throw( com::sun::star::ucb::IllegalIdentifierException ); bool scheme(); bool module(); bool name( bool modulePresent ); bool query(); }; // end class URLParameter } // end namespace chelp #endif <commit_msg>INTEGRATION: CWS ab52 (1.3.6); FILE MERGED 2008/06/18 09:26:44 ab 1.3.6.1: #i90029# Removed unused code<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: urlparameter.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _URLPARAMETER_HXX_ #define _URLPARAMETER_HXX_ #include <rtl/ustring.hxx> #include <rtl/string.hxx> #include <com/sun/star/ucb/IllegalIdentifierException.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/io/XActiveDataSink.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/ucb/Command.hpp> namespace chelp { class Databases; class DbtToStringConverter { public: DbtToStringConverter( const sal_Char* ptr,sal_Int32 len ) : m_len( len ), m_ptr( ptr ) { } rtl::OUString getHash() { if( m_ptr ) { sal_Int32 sizeOfFile = ( sal_Int32 ) m_ptr[0]; rtl::OUString Hash( m_ptr+1,sizeOfFile,RTL_TEXTENCODING_UTF8 ); sal_Int32 idx; if( ( idx = Hash.indexOf( sal_Unicode( '#' ) ) ) != -1 ) return Hash.copy( 1+idx ); } return rtl::OUString(); } rtl::OUString getFile() { if( ! m_ptr ) return rtl::OUString(); sal_Int32 sizeOfFile = ( sal_Int32 ) m_ptr[0]; rtl::OUString File( m_ptr+1,sizeOfFile,RTL_TEXTENCODING_UTF8 ); sal_Int32 idx; if( ( idx = File.indexOf( sal_Unicode( '#' ) ) ) != -1 ) return File.copy( 0,idx ); else return File; } rtl::OUString getDatabase() { if( ! m_ptr ) return rtl::OUString(); sal_Int32 sizeOfDatabase = ( int ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ]; return rtl::OUString( m_ptr + 2 + ( sal_Int32 ) m_ptr[0],sizeOfDatabase,RTL_TEXTENCODING_UTF8 ); } rtl::OUString getTitle() { if( ! m_ptr ) // || getHash().getLength() ) return rtl::OUString(); sal_Int32 sizeOfTitle = ( sal_Int32 ) m_ptr[ 2 + m_ptr[0] + ( sal_Int32 ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ] ]; return rtl::OUString( m_ptr + 3 + m_ptr[0] + ( sal_Int32 ) m_ptr[ 1+ ( sal_Int32 ) m_ptr[0] ], sizeOfTitle, RTL_TEXTENCODING_UTF8 ); } private: sal_Int32 m_len; const sal_Char* m_ptr; }; class URLParameter { public: URLParameter( const rtl::OUString& aURL, Databases* pDatabases ) throw( com::sun::star::ucb::IllegalIdentifierException ); bool isPicture() { return m_aModule.compareToAscii("picture") == 0; } bool isActive() { return m_aActive.getLength() > 0 && m_aActive.compareToAscii( "true" ) == 0; } bool isQuery() { return m_aId.compareToAscii("") == 0 && m_aQuery.compareToAscii("") != 0; } bool isEntryForModule() { return m_aId.compareToAscii("start") == 0 || m_bStart; } bool isFile() { return m_aId.compareToAscii( "" ) != 0; } bool isModule() { return m_aId.compareToAscii("") == 0 && m_aModule.compareToAscii("") != 0; } bool isRoot() { return m_aModule.compareToAscii("") == 0; } bool isErrorDocument(); rtl::OUString get_url() { return m_aURL; } rtl::OUString get_id(); rtl::OUString get_tag(); // Not called for an directory rtl::OUString get_path() { return get_the_path(); } rtl::OUString get_eid() { return m_aEid; } rtl::OUString get_title(); rtl::OUString get_jar() { return get_the_jar(); } // BerkeleyDb rtl::OUString get_module() { return m_aModule; } rtl::OUString get_dbpar() { if( m_aDbPar.getLength() ) return m_aDbPar; else return m_aModule; } rtl::OUString get_prefix() { return m_aPrefix; } rtl::OUString get_language(); rtl::OUString get_device() { return m_aDevice; } rtl::OUString get_program(); rtl::OUString get_query() { return m_aQuery; } rtl::OUString get_scope() { return m_aScope; } rtl::OUString get_system() { return m_aSystem; } sal_Int32 get_hitCount() { return m_nHitCount; } rtl::OString getByName( const char* par ); void open( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment, const com::sun::star::uno::Reference< com::sun::star::io::XActiveDataSink >& xDataSink ); void open( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment, const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xDataSink ); private: Databases* m_pDatabases; bool m_bBerkeleyRead; bool m_bStart; bool m_bUseDB; rtl::OUString m_aURL; rtl::OUString m_aTag; rtl::OUString m_aId; rtl::OUString m_aPath; rtl::OUString m_aModule; rtl::OUString m_aTitle; rtl::OUString m_aJar; rtl::OUString m_aEid; rtl::OUString m_aDbPar; rtl::OUString m_aDefaultLanguage; rtl::OUString m_aLanguage; rtl::OUString m_aPrefix; rtl::OUString m_aDevice; rtl::OUString m_aProgram; rtl::OUString m_aSystem; rtl::OUString m_aActive; rtl::OUString m_aQuery; rtl::OUString m_aScope; rtl::OUString m_aExpr; sal_Int32 m_nHitCount; // The default maximum hitcount // private methods void init( bool bDefaultLanguageIsInitialized ); rtl::OUString get_the_tag(); rtl::OUString get_the_path(); rtl::OUString get_the_title(); rtl::OUString get_the_jar(); void readBerkeley(); void parse() throw( com::sun::star::ucb::IllegalIdentifierException ); bool scheme(); bool module(); bool name( bool modulePresent ); bool query(); }; // end class URLParameter } // end namespace chelp #endif <|endoftext|>
<commit_before>bbfda74c-327f-11e5-9ac2-9cf387a8033e<commit_msg>bc0353eb-327f-11e5-900c-9cf387a8033e<commit_after>bc0353eb-327f-11e5-900c-9cf387a8033e<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexSourceBaseContext.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:08:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_ #define _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_ #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif namespace com { namespace sun { namespace star { namespace xml { namespace sax { class XAttributeList; } } namespace beans { class XPropertySet; } } } } enum IndexSourceParamEnum { XML_TOK_INDEXSOURCE_OUTLINE_LEVEL, XML_TOK_INDEXSOURCE_USE_INDEX_MARKS, XML_TOK_INDEXSOURCE_INDEX_SCOPE, XML_TOK_INDEXSOURCE_RELATIVE_TABS, XML_TOK_INDEXSOURCE_USE_OTHER_OBJECTS, XML_TOK_INDEXSOURCE_USE_SHEET, XML_TOK_INDEXSOURCE_USE_CHART, XML_TOK_INDEXSOURCE_USE_DRAW, XML_TOK_INDEXSOURCE_USE_IMAGE, XML_TOK_INDEXSOURCE_USE_MATH, XML_TOK_INDEXSOURCE_MAIN_ENTRY_STYLE, XML_TOK_INDEXSOURCE_IGNORE_CASE, XML_TOK_INDEXSOURCE_SEPARATORS, XML_TOK_INDEXSOURCE_COMBINE_ENTRIES, XML_TOK_INDEXSOURCE_COMBINE_WITH_DASH, XML_TOK_INDEXSOURCE_KEYS_AS_ENTRIES, XML_TOK_INDEXSOURCE_COMBINE_WITH_PP, XML_TOK_INDEXSOURCE_CAPITALIZE, XML_TOK_INDEXSOURCE_USE_OBJECTS, XML_TOK_INDEXSOURCE_USE_GRAPHICS, XML_TOK_INDEXSOURCE_USE_TABLES, XML_TOK_INDEXSOURCE_USE_FRAMES, XML_TOK_INDEXSOURCE_COPY_OUTLINE_LEVELS, XML_TOK_INDEXSOURCE_USE_CAPTION, XML_TOK_INDEXSOURCE_SEQUENCE_NAME, XML_TOK_INDEXSOURCE_SEQUENCE_FORMAT, XML_TOK_INDEXSOURCE_COMMA_SEPARATED, XML_TOK_INDEXSOURCE_USE_INDEX_SOURCE_STYLES, XML_TOK_INDEXSOURCE_SORT_ALGORITHM, XML_TOK_INDEXSOURCE_LANGUAGE, XML_TOK_INDEXSOURCE_COUNTRY, XML_TOK_INDEXSOURCE_USER_INDEX_NAME, XML_TOK_INDEXSOURCE_USE_OUTLINE_LEVEL }; /** * Superclass for index source elements */ class XMLIndexSourceBaseContext : public SvXMLImportContext { const ::rtl::OUString sCreateFromChapter; const ::rtl::OUString sIsRelativeTabstops; sal_Bool bUseLevelFormats; sal_Bool bChapterIndex; /// chapter-wise or document index? sal_Bool bRelativeTabs; /// tab stops relative to margin or indent? protected: /// property set of index; must be accessible to subclasses ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & rIndexPropertySet; public: TYPEINFO(); XMLIndexSourceBaseContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLocalName, ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & rPropSet, sal_Bool bLevelFormats); ~XMLIndexSourceBaseContext(); protected: virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList); virtual void ProcessAttribute( enum IndexSourceParamEnum eParam, const ::rtl::OUString& rValue); virtual void EndElement(); virtual SvXMLImportContext* CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList ); }; #endif <commit_msg>INTEGRATION: CWS vgbugs07 (1.8.274); FILE MERGED 2007/06/04 13:23:37 vg 1.8.274.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexSourceBaseContext.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:59:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_ #define _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_ #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif namespace com { namespace sun { namespace star { namespace xml { namespace sax { class XAttributeList; } } namespace beans { class XPropertySet; } } } } enum IndexSourceParamEnum { XML_TOK_INDEXSOURCE_OUTLINE_LEVEL, XML_TOK_INDEXSOURCE_USE_INDEX_MARKS, XML_TOK_INDEXSOURCE_INDEX_SCOPE, XML_TOK_INDEXSOURCE_RELATIVE_TABS, XML_TOK_INDEXSOURCE_USE_OTHER_OBJECTS, XML_TOK_INDEXSOURCE_USE_SHEET, XML_TOK_INDEXSOURCE_USE_CHART, XML_TOK_INDEXSOURCE_USE_DRAW, XML_TOK_INDEXSOURCE_USE_IMAGE, XML_TOK_INDEXSOURCE_USE_MATH, XML_TOK_INDEXSOURCE_MAIN_ENTRY_STYLE, XML_TOK_INDEXSOURCE_IGNORE_CASE, XML_TOK_INDEXSOURCE_SEPARATORS, XML_TOK_INDEXSOURCE_COMBINE_ENTRIES, XML_TOK_INDEXSOURCE_COMBINE_WITH_DASH, XML_TOK_INDEXSOURCE_KEYS_AS_ENTRIES, XML_TOK_INDEXSOURCE_COMBINE_WITH_PP, XML_TOK_INDEXSOURCE_CAPITALIZE, XML_TOK_INDEXSOURCE_USE_OBJECTS, XML_TOK_INDEXSOURCE_USE_GRAPHICS, XML_TOK_INDEXSOURCE_USE_TABLES, XML_TOK_INDEXSOURCE_USE_FRAMES, XML_TOK_INDEXSOURCE_COPY_OUTLINE_LEVELS, XML_TOK_INDEXSOURCE_USE_CAPTION, XML_TOK_INDEXSOURCE_SEQUENCE_NAME, XML_TOK_INDEXSOURCE_SEQUENCE_FORMAT, XML_TOK_INDEXSOURCE_COMMA_SEPARATED, XML_TOK_INDEXSOURCE_USE_INDEX_SOURCE_STYLES, XML_TOK_INDEXSOURCE_SORT_ALGORITHM, XML_TOK_INDEXSOURCE_LANGUAGE, XML_TOK_INDEXSOURCE_COUNTRY, XML_TOK_INDEXSOURCE_USER_INDEX_NAME, XML_TOK_INDEXSOURCE_USE_OUTLINE_LEVEL }; /** * Superclass for index source elements */ class XMLIndexSourceBaseContext : public SvXMLImportContext { const ::rtl::OUString sCreateFromChapter; const ::rtl::OUString sIsRelativeTabstops; sal_Bool bUseLevelFormats; sal_Bool bChapterIndex; /// chapter-wise or document index? sal_Bool bRelativeTabs; /// tab stops relative to margin or indent? protected: /// property set of index; must be accessible to subclasses ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & rIndexPropertySet; public: TYPEINFO(); XMLIndexSourceBaseContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLocalName, ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & rPropSet, sal_Bool bLevelFormats); ~XMLIndexSourceBaseContext(); protected: virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList); virtual void ProcessAttribute( enum IndexSourceParamEnum eParam, const ::rtl::OUString& rValue); virtual void EndElement(); virtual SvXMLImportContext* CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList ); }; #endif <|endoftext|>